diff --git a/.github/workflows/buildtest.yaml b/.github/workflows/buildtest.yaml index f37e0e162..26d585ec7 100644 --- a/.github/workflows/buildtest.yaml +++ b/.github/workflows/buildtest.yaml @@ -8,32 +8,28 @@ jobs: os: [ubuntu-latest, windows-latest, macOS-latest] name: Dotnet build steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Setup dotnet - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: | - 6.0.x 8.0.x - # - name: Check Format - # # don't check formatting on Windows b/c of CRLF issues. - # if: matrix.os == 'ubuntu-latest' - # run: dotnet format --severity error --verify-no-changes --exclude ./src/KubernetesClient/generated/ + 9.0.x - name: Build - run: dotnet build --configuration Release -v detailed + run: dotnet build --configuration Release - name: Test run: dotnet test --configuration Release --collect:"Code Coverage;Format=Cobertura" --logger trx --results-directory TestResults --settings CodeCoverage.runsettings --no-build - name: Upload coverage to Codecov - uses: codecov/codecov-action@v4 + uses: codecov/codecov-action@v5 with: directory: ./TestResults files: '*.cobertura.xml' - name: Upload test results - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v5 with: - name: test-results + name: test-results-${{ matrix.os }} path: ./TestResults if: ${{ always() }} # Always run this step even on failure @@ -42,15 +38,15 @@ jobs: runs-on: windows-latest name: MSBuild build steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Add msbuild to PATH uses: microsoft/setup-msbuild@v2 - name: Setup dotnet SDK - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: - dotnet-version: '8.0.x' + dotnet-version: '9.0.x' - name: Restore nugets (msbuild) run: msbuild .\src\KubernetesClient\ -t:restore -p:RestorePackagesConfig=true - name: Build (msbuild) @@ -59,21 +55,21 @@ jobs: e2e: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Setup dotnet - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: | - 6.0.x 8.0.x + 9.0.x - name: Minikube run: minikube start - name: Test run: | true > skip.log - env K8S_E2E_MINIKUBE=1 dotnet test tests/E2E.Tests --logger "SkipTestLogger;file=$PWD/skip.log" + env K8S_E2E_MINIKUBE=1 dotnet test tests/E2E.Tests --logger "SkipTestLogger;file=$PWD/skip.log" -p:BuildInParallel=false if [ -s skip.log ]; then cat skip.log echo "CASES MUST NOT BE SKIPPED" @@ -82,7 +78,7 @@ jobs: - name: AOT Test run: | true > skip.log - env K8S_E2E_MINIKUBE=1 dotnet test tests/E2E.Aot.Tests --logger "SkipTestLogger;file=$PWD/skip.log" + env K8S_E2E_MINIKUBE=1 dotnet test tests/E2E.Aot.Tests --logger "SkipTestLogger;file=$PWD/skip.log" -p:BuildInParallel=false if [ -s skip.log ]; then cat skip.log echo "CASES MUST NOT BE SKIPPED" diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 82c9560ce..6355396eb 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -17,7 +17,7 @@ on: jobs: analyze: name: Analyze - runs-on: windows-2019 + runs-on: windows-2022 strategy: fail-fast: false @@ -26,20 +26,20 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 - name: Setup dotnet - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: | - 6.0.x 8.0.x + 9.0.x # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v3 + uses: github/codeql-action/init@v4 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. @@ -59,4 +59,4 @@ jobs: run: dotnet build --configuration Debug --no-restore - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 + uses: github/codeql-action/analyze@v4 diff --git a/.github/workflows/docfx.yaml b/.github/workflows/docfx.yaml index 00db8dc88..3eec06ec3 100644 --- a/.github/workflows/docfx.yaml +++ b/.github/workflows/docfx.yaml @@ -25,21 +25,21 @@ jobs: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Setup dotnet - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: | - 6.0.x 8.0.x + 9.0.x - name: Build run: dotnet build -c Release - - uses: nunit/docfx-action@v3.4.1 + - uses: nunit/docfx-action@v4.1.0 name: Build Documentation with: args: doc/docfx.json @@ -47,7 +47,7 @@ jobs: - name: Setup Pages uses: actions/configure-pages@v5 - name: Upload artifact - uses: actions/upload-pages-artifact@v3 + uses: actions/upload-pages-artifact@v4 with: # Upload entire repository path: doc/_site diff --git a/.github/workflows/draft.yaml b/.github/workflows/draft.yaml index 39f1ce94e..01b098518 100644 --- a/.github/workflows/draft.yaml +++ b/.github/workflows/draft.yaml @@ -13,16 +13,16 @@ jobs: runs-on: windows-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Setup dotnet - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: | - 6.0.x 8.0.x + 9.0.x - name: dotnet restore run: dotnet restore --verbosity minimal --configfile nuget.config diff --git a/.github/workflows/nuget.yaml b/.github/workflows/nuget.yaml index af5829007..fa654822f 100644 --- a/.github/workflows/nuget.yaml +++ b/.github/workflows/nuget.yaml @@ -10,16 +10,16 @@ jobs: runs-on: windows-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Setup dotnet - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: | - 6.0.x 8.0.x + 9.0.x - name: dotnet restore run: dotnet restore --verbosity minimal --configfile nuget.config diff --git a/Directory.Build.props b/Directory.Build.props index 10ec5bf39..3d3e1cfce 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -26,7 +26,7 @@ snupkg true $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb - 11.0 + 13.0 diff --git a/Directory.Packages.props b/Directory.Packages.props index 67df46d62..27783a77c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,54 +1,54 @@ - - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 6111f5c59..c8eb91626 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,11 @@ ${GEN_DIR}/openapi/csharp.sh ${REPO_DIR}/src/KubernetesClient ${REPO_DIR}/csharp | SDK Version | Kubernetes Version | .NET Targeting | |-------------|--------------------|-----------------------------------------------------| -| 14.0 | 1.30 | net6.0;net8.0;net48*;netstandard2.0* | +| 18.0 | 1.34 | net8.0;net9.0;net48*;netstandard2.0* | +| 17.0 | 1.33 | net8.0;net9.0;net48*;netstandard2.0* | +| 16.0 | 1.32 | net8.0;net9.0;net48*;netstandard2.0* | +| 15.0 | 1.31 | net6.0;net8.0;net48*;netstandard2.0* | +| 14.0 | 1.30 | net6.0;net8.0;net48*;netstandard2.0* | | 13.0 | 1.29 | net6.0;net7.0;net8.0;net48*;netstandard2.0* | | 12.0 | 1.28 | net6.0;net7.0;net48*;netstandard2.0* | | 11.0 | 1.27 | net6.0;net7.0;net48*;netstandard2.0* | diff --git a/SECURITY_CONTACTS b/SECURITY_CONTACTS index d22538052..df0df1c5f 100644 --- a/SECURITY_CONTACTS +++ b/SECURITY_CONTACTS @@ -11,3 +11,4 @@ # INSTRUCTIONS AT https://kubernetes.io/security/ brendandburns +tg123 diff --git a/csharp.settings b/csharp.settings index 979aadae8..0110958c8 100644 --- a/csharp.settings +++ b/csharp.settings @@ -1,3 +1,3 @@ -export KUBERNETES_BRANCH=v1.30.0 +export KUBERNETES_BRANCH=v1.34.0 export CLIENT_VERSION=0.0.1 export PACKAGE_NAME=k8s diff --git a/doc/CONTRIBUTING.md b/doc/CONTRIBUTING.md new file mode 120000 index 000000000..44fcc6343 --- /dev/null +++ b/doc/CONTRIBUTING.md @@ -0,0 +1 @@ +../CONTRIBUTING.md \ No newline at end of file diff --git a/doc/docfx.json b/doc/docfx.json index 9ba72e4c4..2917802e6 100644 --- a/doc/docfx.json +++ b/doc/docfx.json @@ -4,7 +4,7 @@ "src": [ { "files": [ - "KubernetesClient/KubernetesClient.csproj" + "KubernetesClient/bin/Release/net8.0/KubernetesClient.dll" ], "src": "../src" } @@ -20,6 +20,7 @@ "files": [ "api/**.yml", "index.md", + "CONTRIBUTING.md", "toc.yml" ] } diff --git a/examples/Directory.Build.props b/examples/Directory.Build.props index edc5738f1..b87fe6aaa 100644 --- a/examples/Directory.Build.props +++ b/examples/Directory.Build.props @@ -1,6 +1,7 @@ + - net8.0 + net9.0 diff --git a/examples/Directory.Build.targets b/examples/Directory.Build.targets index 65c630b6d..bf5f5ee49 100644 --- a/examples/Directory.Build.targets +++ b/examples/Directory.Build.targets @@ -1,4 +1,5 @@ + diff --git a/examples/attach/Attach.cs b/examples/attach/Attach.cs index a53b5da56..cfdce7d8e 100755 --- a/examples/attach/Attach.cs +++ b/examples/attach/Attach.cs @@ -3,38 +3,29 @@ using System; using System.Threading.Tasks; -namespace attach -{ - internal class Attach - { - private static async Task Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - IKubernetes client = new Kubernetes(config); - Console.WriteLine("Starting Request!"); +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +IKubernetes client = new Kubernetes(config); +Console.WriteLine("Starting Request!"); - var list = client.CoreV1.ListNamespacedPod("default"); - var pod = list.Items[0]; - await AttachToPod(client, pod).ConfigureAwait(false); - } +var list = client.CoreV1.ListNamespacedPod("default"); +var pod = list.Items[0]; +await AttachToPod(client, pod).ConfigureAwait(false); - private static async Task AttachToPod(IKubernetes client, V1Pod pod) - { - var webSocket = - await client.WebSocketNamespacedPodAttachAsync(pod.Metadata.Name, "default", - pod.Spec.Containers[0].Name).ConfigureAwait(false); +async Task AttachToPod(IKubernetes client, V1Pod pod) +{ + var webSocket = + await client.WebSocketNamespacedPodAttachAsync(pod.Metadata.Name, "default", + pod.Spec.Containers[0].Name).ConfigureAwait(false); - var demux = new StreamDemuxer(webSocket); - demux.Start(); + var demux = new StreamDemuxer(webSocket); + demux.Start(); - var buff = new byte[4096]; - var stream = demux.GetStream(1, 1); - while (true) - { - var read = stream.Read(buff, 0, 4096); - var str = System.Text.Encoding.Default.GetString(buff); - Console.WriteLine(str); - } - } + var buff = new byte[4096]; + var stream = demux.GetStream(1, 1); + while (true) + { + var read = stream.Read(buff, 0, 4096); + var str = System.Text.Encoding.Default.GetString(buff); + Console.WriteLine(str); } } diff --git a/examples/clientset/Program.cs b/examples/clientset/Program.cs new file mode 100644 index 000000000..a1b74e0f8 --- /dev/null +++ b/examples/clientset/Program.cs @@ -0,0 +1,32 @@ +using k8s; +using k8s.Models; +using k8s.ClientSets; +using System.Threading.Tasks; + +namespace clientset +{ + internal class Program + { + private static async Task Main(string[] args) + { + var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); + var client = new Kubernetes(config); + + var clientSet = new ClientSet(client); + var list = await clientSet.CoreV1.Pod.ListAsync("default").ConfigureAwait(false); + foreach (var item in list) + { + System.Console.WriteLine(item.Metadata.Name); + } + + var pod = await clientSet.CoreV1.Pod.GetAsync("test", "default").ConfigureAwait(false); + System.Console.WriteLine(pod?.Metadata?.Name); + + var watch = clientSet.CoreV1.Pod.WatchListAsync("default"); + await foreach (var (_, item) in watch.ConfigureAwait(false)) + { + System.Console.WriteLine(item.Metadata.Name); + } + } + } +} \ No newline at end of file diff --git a/examples/clientset/clientset.csproj b/examples/clientset/clientset.csproj new file mode 100644 index 000000000..4274ceb02 --- /dev/null +++ b/examples/clientset/clientset.csproj @@ -0,0 +1,6 @@ + + + Exe + + + diff --git a/examples/cp/Cp.cs b/examples/cp/Cp.cs index b7dd5b207..43e769490 100644 --- a/examples/cp/Cp.cs +++ b/examples/cp/Cp.cs @@ -1,4 +1,4 @@ -using ICSharpCode.SharpZipLib.Tar; +using ICSharpCode.SharpZipLib.Tar; using k8s; using System; using System.IO; @@ -7,110 +7,104 @@ using System.Threading; using System.Threading.Tasks; -namespace cp -{ - internal class Cp - { - private static IKubernetes client; +namespace cp; - private static async Task Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - client = new Kubernetes(config); +internal class Cp +{ + private static IKubernetes client; + private static async Task Main(string[] args) + { + var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); + client = new Kubernetes(config); - var pods = client.CoreV1.ListNamespacedPod("default", null, null, null, $"job-name=upload-demo"); - var pod = pods.Items.First(); - await CopyFileToPodAsync(pod.Metadata.Name, "default", "upload-demo", args[0], $"home/{args[1]}"); + var pods = client.CoreV1.ListNamespacedPod("default", null, null, null, $"job-name=upload-demo"); + var pod = pods.Items.First(); - } + await CopyFileToPodAsync(pod.Metadata.Name, "default", "upload-demo", args[0], $"home/{args[1]}").ConfigureAwait(false); + } - private static void ValidatePathParameters(string sourcePath, string destinationPath) + private static void ValidatePathParameters(string sourcePath, string destinationPath) + { + if (string.IsNullOrWhiteSpace(sourcePath)) { - if (string.IsNullOrWhiteSpace(sourcePath)) - { - throw new ArgumentException($"{nameof(sourcePath)} cannot be null or whitespace"); - } - - if (string.IsNullOrWhiteSpace(destinationPath)) - { - throw new ArgumentException($"{nameof(destinationPath)} cannot be null or whitespace"); - } - + throw new ArgumentException($"{nameof(sourcePath)} cannot be null or whitespace"); } - public static async Task CopyFileToPodAsync(string name, string @namespace, string container, string sourceFilePath, string destinationFilePath, CancellationToken cancellationToken = default(CancellationToken)) + if (string.IsNullOrWhiteSpace(destinationPath)) { - // All other parameters are being validated by MuxedStreamNamespacedPodExecAsync called by NamespacedPodExecAsync - ValidatePathParameters(sourceFilePath, destinationFilePath); + throw new ArgumentException($"{nameof(destinationPath)} cannot be null or whitespace"); + } + } + + public static async Task CopyFileToPodAsync(string name, string @namespace, string container, string sourceFilePath, string destinationFilePath, CancellationToken cancellationToken = default(CancellationToken)) + { + // All other parameters are being validated by MuxedStreamNamespacedPodExecAsync called by NamespacedPodExecAsync + ValidatePathParameters(sourceFilePath, destinationFilePath); - // The callback which processes the standard input, standard output and standard error of exec method - var handler = new ExecAsyncCallback(async (stdIn, stdOut, stdError) => + // The callback which processes the standard input, standard output and standard error of exec method + var handler = new ExecAsyncCallback(async (stdIn, stdOut, stdError) => + { + var fileInfo = new FileInfo(destinationFilePath); + try { - var fileInfo = new FileInfo(destinationFilePath); - try + using (var memoryStream = new MemoryStream()) { - using (var memoryStream = new MemoryStream()) + using (var inputFileStream = File.OpenRead(sourceFilePath)) + using (var tarOutputStream = new TarOutputStream(memoryStream, Encoding.Default)) { - using (var inputFileStream = File.OpenRead(sourceFilePath)) - using (var tarOutputStream = new TarOutputStream(memoryStream, Encoding.Default)) - { - tarOutputStream.IsStreamOwner = false; - - var fileSize = inputFileStream.Length; - var entry = TarEntry.CreateTarEntry(fileInfo.Name); - - entry.Size = fileSize; + tarOutputStream.IsStreamOwner = false; - tarOutputStream.PutNextEntry(entry); - await inputFileStream.CopyToAsync(tarOutputStream); - tarOutputStream.CloseEntry(); - } + var fileSize = inputFileStream.Length; + var entry = TarEntry.CreateTarEntry(fileInfo.Name); - memoryStream.Position = 0; + entry.Size = fileSize; - await memoryStream.CopyToAsync(stdIn); - await stdIn.FlushAsync(); + tarOutputStream.PutNextEntry(entry); + await inputFileStream.CopyToAsync(tarOutputStream).ConfigureAwait(false); + tarOutputStream.CloseEntry(); } - } - catch (Exception ex) - { - throw new IOException($"Copy command failed: {ex.Message}"); - } + memoryStream.Position = 0; - using StreamReader streamReader = new StreamReader(stdError); - while (streamReader.EndOfStream == false) - { - string error = await streamReader.ReadToEndAsync(); - throw new IOException($"Copy command failed: {error}"); + await memoryStream.CopyToAsync(stdIn).ConfigureAwait(false); + await stdIn.FlushAsync().ConfigureAwait(false); } - }); - - string destinationFolder = GetFolderName(destinationFilePath); - - return await client.NamespacedPodExecAsync( - name, - @namespace, - container, - new string[] { "sh", "-c", $"tar xmf - -C {destinationFolder}" }, - false, - handler, - cancellationToken); - } - + } + catch (Exception ex) + { + throw new IOException($"Copy command failed: {ex.Message}"); + } - private static string GetFolderName(string filePath) - { - var folderName = Path.GetDirectoryName(filePath); + using StreamReader streamReader = new StreamReader(stdError); + while (streamReader.EndOfStream == false) + { + string error = await streamReader.ReadToEndAsync().ConfigureAwait(false); + throw new IOException($"Copy command failed: {error}"); + } + }); + + string destinationFolder = GetFolderName(destinationFilePath); + + return await client.NamespacedPodExecAsync( + name, + @namespace, + container, + new string[] { "sh", "-c", $"tar xmf - -C {destinationFolder}" }, + false, + handler, + cancellationToken).ConfigureAwait(false); + } - return string.IsNullOrEmpty(folderName) ? "." : folderName; - } + private static string GetFolderName(string filePath) + { + var folderName = Path.GetDirectoryName(filePath); + return string.IsNullOrEmpty(folderName) ? "." : folderName; } } diff --git a/examples/csrApproval/Program.cs b/examples/csrApproval/Program.cs index b4f154864..6c374105b 100644 --- a/examples/csrApproval/Program.cs +++ b/examples/csrApproval/Program.cs @@ -1,4 +1,4 @@ -using Json.Patch; +using Json.Patch; using k8s; using k8s.Models; using System.Net; @@ -21,7 +21,7 @@ string GenerateCertificate(string name) var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false)); - request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.1") }, false)); + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new ("1.3.6.1.5.5.7.3.1")], false)); request.CertificateExtensions.Add(sanBuilder.Build()); var csr = request.CreateSigningRequest(); var pemKey = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + @@ -44,34 +44,42 @@ string GenerateCertificate(string name) Kind = "CertificateSigningRequest", Metadata = new V1ObjectMeta { - Name = name + Name = name, }, Spec = new V1CertificateSigningRequestSpec { Request = encodedCsr, SignerName = "kubernetes.io/kube-apiserver-client", Usages = new List { "client auth" }, - ExpirationSeconds = 600 // minimum should be 10 minutes - } + ExpirationSeconds = 600, // minimum should be 10 minutes + }, }; -await client.CertificatesV1.CreateCertificateSigningRequestAsync(request); +await client.CertificatesV1.CreateCertificateSigningRequestAsync(request).ConfigureAwait(false); var serializeOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - WriteIndented = true + WriteIndented = true, }; -var readCert = await client.CertificatesV1.ReadCertificateSigningRequestAsync(name); +var readCert = await client.CertificatesV1.ReadCertificateSigningRequestAsync(name).ConfigureAwait(false); var old = JsonSerializer.SerializeToDocument(readCert, serializeOptions); var replace = new List { - new("True", "Approved", DateTime.UtcNow, DateTime.UtcNow, "This certificate was approved by k8s client", "Approve") + new V1CertificateSigningRequestCondition + { + Type = "Approved", + Status = "True", + Reason = "Approve", + Message = "This certificate was approved by k8s client", + LastUpdateTime = DateTime.UtcNow, + LastTransitionTime = DateTime.UtcNow, + }, }; readCert.Status.Conditions = replace; var expected = JsonSerializer.SerializeToDocument(readCert, serializeOptions); var patch = old.CreatePatch(expected); -await client.CertificatesV1.PatchCertificateSigningRequestApprovalAsync(new V1Patch(patch, V1Patch.PatchType.JsonPatch), name); +await client.CertificatesV1.PatchCertificateSigningRequestApprovalAsync(new V1Patch(patch, V1Patch.PatchType.JsonPatch), name).ConfigureAwait(false); diff --git a/examples/customResource/cResource.cs b/examples/customResource/cResource.cs index f9df60b22..67440aee9 100644 --- a/examples/customResource/cResource.cs +++ b/examples/customResource/cResource.cs @@ -19,13 +19,13 @@ public override string ToString() } } - public class CResourceSpec + public record CResourceSpec { [JsonPropertyName("cityName")] public string CityName { get; set; } } - public class CResourceStatus : V1Status + public record CResourceStatus : V1Status { [JsonPropertyName("temperature")] public string Temperature { get; set; } diff --git a/examples/exec/Exec.cs b/examples/exec/Exec.cs index 9fdfc73b0..20bbd2125 100755 --- a/examples/exec/Exec.cs +++ b/examples/exec/Exec.cs @@ -3,35 +3,26 @@ using System; using System.Threading.Tasks; -namespace exec -{ - internal class Exec - { - private static async Task Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - IKubernetes client = new Kubernetes(config); - Console.WriteLine("Starting Request!"); +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +IKubernetes client = new Kubernetes(config); +Console.WriteLine("Starting Request!"); - var list = client.CoreV1.ListNamespacedPod("default"); - var pod = list.Items[0]; - await ExecInPod(client, pod).ConfigureAwait(false); - } +var list = client.CoreV1.ListNamespacedPod("default"); +var pod = list.Items[0]; +await ExecInPod(client, pod).ConfigureAwait(false); - private static async Task ExecInPod(IKubernetes client, V1Pod pod) - { - var webSocket = - await client.WebSocketNamespacedPodExecAsync(pod.Metadata.Name, "default", "ls", - pod.Spec.Containers[0].Name).ConfigureAwait(false); +async Task ExecInPod(IKubernetes client, V1Pod pod) +{ + var webSocket = + await client.WebSocketNamespacedPodExecAsync(pod.Metadata.Name, "default", "ls", + pod.Spec.Containers[0].Name).ConfigureAwait(false); - var demux = new StreamDemuxer(webSocket); - demux.Start(); + var demux = new StreamDemuxer(webSocket); + demux.Start(); - var buff = new byte[4096]; - var stream = demux.GetStream(1, 1); - var read = stream.Read(buff, 0, 4096); - var str = System.Text.Encoding.Default.GetString(buff); - Console.WriteLine(str); - } - } + var buff = new byte[4096]; + var stream = demux.GetStream(1, 1); + var read = stream.Read(buff, 0, 4096); + var str = System.Text.Encoding.Default.GetString(buff); + Console.WriteLine(str); } diff --git a/examples/generic/Generic.cs b/examples/generic/Generic.cs index 41f91b39f..f65fb944d 100644 --- a/examples/generic/Generic.cs +++ b/examples/generic/Generic.cs @@ -1,26 +1,16 @@ using k8s; using k8s.Models; using System; -using System.Threading.Tasks; -namespace exec -{ - internal class Generic - { - private static async Task Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - IKubernetes client = new Kubernetes(config); - var generic = new GenericClient(client, "", "v1", "nodes"); - var node = await generic.ReadAsync("kube0").ConfigureAwait(false); - Console.WriteLine(node.Metadata.Name); +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +IKubernetes client = new Kubernetes(config); +var generic = new GenericClient(client, "", "v1", "nodes"); +var node = await generic.ReadAsync("kube0").ConfigureAwait(false); +Console.WriteLine(node.Metadata.Name); - var genericPods = new GenericClient(client, "", "v1", "pods"); - var pods = await genericPods.ListNamespacedAsync("default").ConfigureAwait(false); - foreach (var pod in pods.Items) - { - Console.WriteLine(pod.Metadata.Name); - } - } - } +var genericPods = new GenericClient(client, "", "v1", "pods"); +var pods = await genericPods.ListNamespacedAsync("default").ConfigureAwait(false); +foreach (var pod in pods.Items) +{ + Console.WriteLine(pod.Metadata.Name); } diff --git a/examples/labels/PodList.cs b/examples/labels/PodList.cs index 2d59e9026..0c5df001d 100755 --- a/examples/labels/PodList.cs +++ b/examples/labels/PodList.cs @@ -2,47 +2,38 @@ using System; using System.Collections.Generic; -namespace simple +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +IKubernetes client = new Kubernetes(config); +Console.WriteLine("Starting Request!"); + +var list = client.CoreV1.ListNamespacedService("default"); +foreach (var item in list.Items) { - internal class PodList + Console.WriteLine("Pods for service: " + item.Metadata.Name); + Console.WriteLine("=-=-=-=-=-=-=-=-=-=-="); + if (item.Spec == null || item.Spec.Selector == null) { - private static void Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - IKubernetes client = new Kubernetes(config); - Console.WriteLine("Starting Request!"); - - var list = client.CoreV1.ListNamespacedService("default"); - foreach (var item in list.Items) - { - Console.WriteLine("Pods for service: " + item.Metadata.Name); - Console.WriteLine("=-=-=-=-=-=-=-=-=-=-="); - if (item.Spec == null || item.Spec.Selector == null) - { - continue; - } - - var labels = new List(); - foreach (var key in item.Spec.Selector) - { - labels.Add(key.Key + "=" + key.Value); - } + continue; + } - var labelStr = string.Join(",", labels.ToArray()); - Console.WriteLine(labelStr); - var podList = client.CoreV1.ListNamespacedPod("default", labelSelector: labelStr); - foreach (var pod in podList.Items) - { - Console.WriteLine(pod.Metadata.Name); - } + var labels = new List(); + foreach (var key in item.Spec.Selector) + { + labels.Add(key.Key + "=" + key.Value); + } - if (podList.Items.Count == 0) - { - Console.WriteLine("Empty!"); - } + var labelStr = string.Join(",", labels.ToArray()); + Console.WriteLine(labelStr); + var podList = client.CoreV1.ListNamespacedPod("default", labelSelector: labelStr); + foreach (var pod in podList.Items) + { + Console.WriteLine(pod.Metadata.Name); + } - Console.WriteLine(); - } - } + if (podList.Items.Count == 0) + { + Console.WriteLine("Empty!"); } + + Console.WriteLine(); } diff --git a/examples/logs/Logs.cs b/examples/logs/Logs.cs index ea23fa05f..5293de579 100755 --- a/examples/logs/Logs.cs +++ b/examples/logs/Logs.cs @@ -1,31 +1,21 @@ using k8s; using System; -using System.Threading.Tasks; -namespace logs -{ - internal class Logs - { - private static async Task Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - IKubernetes client = new Kubernetes(config); - Console.WriteLine("Starting Request!"); +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +IKubernetes client = new Kubernetes(config); +Console.WriteLine("Starting Request!"); - var list = client.CoreV1.ListNamespacedPod("default"); - if (list.Items.Count == 0) - { - Console.WriteLine("No pods!"); - return; - } +var list = client.CoreV1.ListNamespacedPod("default"); +if (list.Items.Count == 0) +{ + Console.WriteLine("No pods!"); + return; +} - var pod = list.Items[0]; +var pod = list.Items[0]; - var response = await client.CoreV1.ReadNamespacedPodLogWithHttpMessagesAsync( - pod.Metadata.Name, - pod.Metadata.NamespaceProperty, container: pod.Spec.Containers[0].Name, follow: true).ConfigureAwait(false); - var stream = response.Body; - stream.CopyTo(Console.OpenStandardOutput()); - } - } -} +var response = await client.CoreV1.ReadNamespacedPodLogWithHttpMessagesAsync( + pod.Metadata.Name, + pod.Metadata.NamespaceProperty, container: pod.Spec.Containers[0].Name, follow: true).ConfigureAwait(false); +var stream = response.Body; +stream.CopyTo(Console.OpenStandardOutput()); diff --git a/examples/metrics/Program.cs b/examples/metrics/Program.cs index 33a779f09..f823bf54d 100644 --- a/examples/metrics/Program.cs +++ b/examples/metrics/Program.cs @@ -3,58 +3,49 @@ using System.Linq; using System.Threading.Tasks; -namespace metrics +async Task NodesMetrics(IKubernetes client) { - internal class Program + var nodesMetrics = await client.GetKubernetesNodesMetricsAsync().ConfigureAwait(false); + + foreach (var item in nodesMetrics.Items) { - private static async Task NodesMetrics(IKubernetes client) + Console.WriteLine(item.Metadata.Name); + + foreach (var metric in item.Usage) { - var nodesMetrics = await client.GetKubernetesNodesMetricsAsync().ConfigureAwait(false); + Console.WriteLine($"{metric.Key}: {metric.Value}"); + } + } +} - foreach (var item in nodesMetrics.Items) - { - Console.WriteLine(item.Metadata.Name); +async Task PodsMetrics(IKubernetes client) +{ + var podsMetrics = await client.GetKubernetesPodsMetricsAsync().ConfigureAwait(false); - foreach (var metric in item.Usage) - { - Console.WriteLine($"{metric.Key}: {metric.Value}"); - } - } - } + if (!podsMetrics.Items.Any()) + { + Console.WriteLine("Empty"); + } - private static async Task PodsMetrics(IKubernetes client) + foreach (var item in podsMetrics.Items) + { + foreach (var container in item.Containers) { - var podsMetrics = await client.GetKubernetesPodsMetricsAsync().ConfigureAwait(false); - - if (!podsMetrics.Items.Any()) - { - Console.WriteLine("Empty"); - } + Console.WriteLine(container.Name); - foreach (var item in podsMetrics.Items) + foreach (var metric in container.Usage) { - foreach (var container in item.Containers) - { - Console.WriteLine(container.Name); - - foreach (var metric in container.Usage) - { - Console.WriteLine($"{metric.Key}: {metric.Value}"); - } - } - - Console.Write(Environment.NewLine); + Console.WriteLine($"{metric.Key}: {metric.Value}"); } } - private static async Task Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - var client = new Kubernetes(config); - - await NodesMetrics(client).ConfigureAwait(false); - Console.WriteLine(Environment.NewLine); - await PodsMetrics(client).ConfigureAwait(false); - } + Console.Write(Environment.NewLine); } } + +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +var client = new Kubernetes(config); + +await NodesMetrics(client).ConfigureAwait(false); +Console.WriteLine(Environment.NewLine); +await PodsMetrics(client).ConfigureAwait(false); diff --git a/examples/namespace/NamespaceExample.cs b/examples/namespace/NamespaceExample.cs index 22ad06cde..06e8757a4 100644 --- a/examples/namespace/NamespaceExample.cs +++ b/examples/namespace/NamespaceExample.cs @@ -4,52 +4,37 @@ using System.Net; using System.Threading.Tasks; -namespace @namespace +void ListNamespaces(IKubernetes client) { - internal class NamespaceExample + var list = client.CoreV1.ListNamespace(); + foreach (var item in list.Items) { - private static void ListNamespaces(IKubernetes client) - { - var list = client.CoreV1.ListNamespace(); - foreach (var item in list.Items) - { - Console.WriteLine(item.Metadata.Name); - } + Console.WriteLine(item.Metadata.Name); + } - if (list.Items.Count == 0) - { - Console.WriteLine("Empty!"); - } - } + if (list.Items.Count == 0) + { + Console.WriteLine("Empty!"); + } +} - private static async Task DeleteAsync(IKubernetes client, string name, int delayMillis) +async Task DeleteAsync(IKubernetes client, string name, int delayMillis) +{ + while (true) + { + await Task.Delay(delayMillis).ConfigureAwait(false); + try { - while (true) + await client.CoreV1.ReadNamespaceAsync(name).ConfigureAwait(false); + } + catch (AggregateException ex) + { + foreach (var innerEx in ex.InnerExceptions) { - await Task.Delay(delayMillis).ConfigureAwait(false); - try - { - await client.CoreV1.ReadNamespaceAsync(name).ConfigureAwait(false); - } - catch (AggregateException ex) - { - foreach (var innerEx in ex.InnerExceptions) - { - if (innerEx is k8s.Autorest.HttpOperationException exception) - { - var code = exception.Response.StatusCode; - if (code == HttpStatusCode.NotFound) - { - return; - } - - throw; - } - } - } - catch (k8s.Autorest.HttpOperationException ex) + if (innerEx is k8s.Autorest.HttpOperationException exception) { - if (ex.Response.StatusCode == HttpStatusCode.NotFound) + var code = exception.Response.StatusCode; + if (code == HttpStatusCode.NotFound) { return; } @@ -58,41 +43,47 @@ private static async Task DeleteAsync(IKubernetes client, string name, int delay } } } - - private static void Delete(IKubernetes client, string name, int delayMillis) + catch (k8s.Autorest.HttpOperationException ex) { - DeleteAsync(client, name, delayMillis).Wait(); + if (ex.Response.StatusCode == HttpStatusCode.NotFound) + { + return; + } + + throw; } + } +} - private static void Main(string[] args) - { - var k8SClientConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - IKubernetes client = new Kubernetes(k8SClientConfig); +void Delete(IKubernetes client, string name, int delayMillis) +{ + DeleteAsync(client, name, delayMillis).Wait(); +} - ListNamespaces(client); +var k8SClientConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +IKubernetes client = new Kubernetes(k8SClientConfig); - var ns = new V1Namespace { Metadata = new V1ObjectMeta { Name = "test" } }; +ListNamespaces(client); - var result = client.CoreV1.CreateNamespace(ns); - Console.WriteLine(result); +var ns = new V1Namespace { Metadata = new V1ObjectMeta { Name = "test" } }; - ListNamespaces(client); +var result = client.CoreV1.CreateNamespace(ns); +Console.WriteLine(result); - var status = client.CoreV1.DeleteNamespace(ns.Metadata.Name, new V1DeleteOptions()); +ListNamespaces(client); - if (status.HasObject) - { - var obj = status.ObjectView(); - Console.WriteLine(obj.Status.Phase); +var status = client.CoreV1.DeleteNamespace(ns.Metadata.Name, new V1DeleteOptions()); - Delete(client, ns.Metadata.Name, 3 * 1000); - } - else - { - Console.WriteLine(status.Message); - } +if (status.HasObject) +{ + var obj = status.ObjectView(); + Console.WriteLine(obj.Status.Phase); - ListNamespaces(client); - } - } + Delete(client, ns.Metadata.Name, 3 * 1000); } +else +{ + Console.WriteLine(status.Message); +} + +ListNamespaces(client); diff --git a/examples/openTelemetryConsole/Program.cs b/examples/openTelemetryConsole/Program.cs index 9a5460dcb..4b7406be3 100644 --- a/examples/openTelemetryConsole/Program.cs +++ b/examples/openTelemetryConsole/Program.cs @@ -24,11 +24,12 @@ // Read the list of pods contained in default namespace var list = client.CoreV1.ListNamespacedPod("default"); -// Print the name of pods +// Print the name of pods foreach (var item in list.Items) { Console.WriteLine(item.Metadata.Name); } + // Or empty if there are no pods if (list.Items.Count == 0) { diff --git a/examples/patch-aot/Program.cs b/examples/patch-aot/Program.cs new file mode 100644 index 000000000..e72f6a4d2 --- /dev/null +++ b/examples/patch-aot/Program.cs @@ -0,0 +1,33 @@ +using k8s; +using k8s.Models; + +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +IKubernetes client = new Kubernetes(config); +Console.WriteLine("Starting Request!"); + +var pod = client.CoreV1.ListNamespacedPod("default").Items.First(); +var name = pod.Metadata.Name; +PrintLabels(pod); + +var patchStr = @" +{ + ""metadata"": { + ""labels"": { + ""test"": ""test"" + } + } +}"; + +client.CoreV1.PatchNamespacedPod(new V1Patch(patchStr, V1Patch.PatchType.MergePatch), name, "default"); +PrintLabels(client.CoreV1.ReadNamespacedPod(name, "default")); + +static void PrintLabels(V1Pod pod) +{ + Console.WriteLine($"Labels: for {pod.Metadata.Name}"); + foreach (var (k, v) in pod.Metadata.Labels) + { + Console.WriteLine($"{k} : {v}"); + } + + Console.WriteLine("=-=-=-=-=-=-=-=-=-=-="); +} diff --git a/examples/patch-aot/patch-aot.csproj b/examples/patch-aot/patch-aot.csproj new file mode 100644 index 000000000..c2c806215 --- /dev/null +++ b/examples/patch-aot/patch-aot.csproj @@ -0,0 +1,11 @@ + + + Exe + enable + enable + true + + + + + diff --git a/examples/patch/Program.cs b/examples/patch/Program.cs index 7958fcc35..f8cefa67c 100644 --- a/examples/patch/Program.cs +++ b/examples/patch/Program.cs @@ -3,21 +3,15 @@ using System; using System.Linq; -namespace patch -{ - internal class Program - { - private static void Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - IKubernetes client = new Kubernetes(config); - Console.WriteLine("Starting Request!"); +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +IKubernetes client = new Kubernetes(config); +Console.WriteLine("Starting Request!"); - var pod = client.CoreV1.ListNamespacedPod("default").Items.First(); - var name = pod.Metadata.Name; - PrintLabels(pod); +var pod = client.CoreV1.ListNamespacedPod("default").Items.First(); +var name = pod.Metadata.Name; +PrintLabels(pod); - var patchStr = @" +var patchStr = @" { ""metadata"": { ""labels"": { @@ -26,19 +20,16 @@ private static void Main(string[] args) } }"; - client.CoreV1.PatchNamespacedPod(new V1Patch(patchStr, V1Patch.PatchType.MergePatch), name, "default"); - PrintLabels(client.CoreV1.ReadNamespacedPod(name, "default")); - } - - private static void PrintLabels(V1Pod pod) - { - Console.WriteLine($"Labels: for {pod.Metadata.Name}"); - foreach (var (k, v) in pod.Metadata.Labels) - { - Console.WriteLine($"{k} : {v}"); - } +client.CoreV1.PatchNamespacedPod(new V1Patch(patchStr, V1Patch.PatchType.MergePatch), name, "default"); +PrintLabels(client.CoreV1.ReadNamespacedPod(name, "default")); - Console.WriteLine("=-=-=-=-=-=-=-=-=-=-="); - } +void PrintLabels(V1Pod pod) +{ + Console.WriteLine($"Labels: for {pod.Metadata.Name}"); + foreach (var (k, v) in pod.Metadata.Labels) + { + Console.WriteLine($"{k} : {v}"); } + + Console.WriteLine("=-=-=-=-=-=-=-=-=-=-="); } diff --git a/examples/portforward/PortForward.cs b/examples/portforward/PortForward.cs index fe9485d86..ee095e073 100644 --- a/examples/portforward/PortForward.cs +++ b/examples/portforward/PortForward.cs @@ -6,74 +6,66 @@ using System.Text; using System.Threading.Tasks; -namespace portforward -{ - internal class Portforward - { - private static async Task Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - IKubernetes client = new Kubernetes(config); - Console.WriteLine("Starting port forward!"); +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +IKubernetes client = new Kubernetes(config); +Console.WriteLine("Starting port forward!"); - var list = client.CoreV1.ListNamespacedPod("default"); - var pod = list.Items[0]; - await Forward(client, pod); - } - - private static async Task Forward(IKubernetes client, V1Pod pod) - { - // Note this is single-threaded, it won't handle concurrent requests well... - var webSocket = await client.WebSocketNamespacedPodPortForwardAsync(pod.Metadata.Name, "default", new int[] { 80 }, "v4.channel.k8s.io"); - var demux = new StreamDemuxer(webSocket, StreamType.PortForward); - demux.Start(); +var list = client.CoreV1.ListNamespacedPod("default"); +var pod = list.Items[0]; +await Forward(client, pod).ConfigureAwait(false); - var stream = demux.GetStream((byte?)0, (byte?)0); +async Task Forward(IKubernetes client, V1Pod pod) +{ + // Note this is single-threaded, it won't handle concurrent requests well... + var webSocket = await client.WebSocketNamespacedPodPortForwardAsync(pod.Metadata.Name, "default", new int[] { 80 }, "v4.channel.k8s.io").ConfigureAwait(false); + var demux = new StreamDemuxer(webSocket, StreamType.PortForward); + demux.Start(); - IPAddress ipAddress = IPAddress.Loopback; - IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8080); - Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); - listener.Bind(localEndPoint); - listener.Listen(100); + var stream = demux.GetStream((byte?)0, (byte?)0); - Socket handler = null; + IPAddress ipAddress = IPAddress.Loopback; + IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8080); + Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + listener.Bind(localEndPoint); + listener.Listen(100); - // Note this will only accept a single connection - var accept = Task.Run(() => - { - while (true) - { - handler = listener.Accept(); - var bytes = new byte[4096]; - while (true) - { - int bytesRec = handler.Receive(bytes); - stream.Write(bytes, 0, bytesRec); - if (bytesRec == 0 || Encoding.ASCII.GetString(bytes, 0, bytesRec).IndexOf("") > -1) - { - break; - } - } - } - }); + Socket handler = null; - var copy = Task.Run(() => + // Note this will only accept a single connection + var accept = Task.Run(() => + { + while (true) + { + handler = listener.Accept(); + var bytes = new byte[4096]; + while (true) { - var buff = new byte[4096]; - while (true) + int bytesRec = handler.Receive(bytes); + stream.Write(bytes, 0, bytesRec); + if (bytesRec == 0 || Encoding.ASCII.GetString(bytes, 0, bytesRec).IndexOf("") > -1) { - var read = stream.Read(buff, 0, 4096); - handler.Send(buff, read, 0); + break; } - }); - - await accept; - await copy; - if (handler != null) - { - handler.Close(); } - listener.Close(); } + }); + + var copy = Task.Run(() => + { + var buff = new byte[4096]; + while (true) + { + var read = stream.Read(buff, 0, 4096); + handler.Send(buff, read, 0); + } + }); + + await accept.ConfigureAwait(false); + await copy.ConfigureAwait(false); + if (handler != null) + { + handler.Close(); } + + listener.Close(); } diff --git a/examples/resize/Program.cs b/examples/resize/Program.cs new file mode 100644 index 000000000..85fbeb9b2 --- /dev/null +++ b/examples/resize/Program.cs @@ -0,0 +1,63 @@ +using k8s; +using k8s.Models; +using System; +using System.Collections.Generic; + + +var config = KubernetesClientConfiguration.BuildDefaultConfig(); +var client = new Kubernetes(config); + + +var pod = new V1Pod +{ + Metadata = new V1ObjectMeta { Name = "nginx-pod" }, + Spec = new V1PodSpec + { + Containers = + [ + new V1Container + { + Name = "nginx", + Image = "nginx", + Resources = new V1ResourceRequirements + { + Requests = new Dictionary() + { + ["cpu"] = "100m", + }, + }, + }, + ], + }, +}; +{ + var created = await client.CoreV1.CreateNamespacedPodAsync(pod, "default").ConfigureAwait(false); + Console.WriteLine($"Created pod: {created.Metadata.Name}"); +} + +{ + var patchStr = @" + { + ""spec"": { + ""containers"": [ + { + ""name"": ""nginx"", + ""resources"": { + ""requests"": { + ""cpu"": ""200m"" + } + } + } + ] + } + }"; + + var patch = await client.CoreV1.PatchNamespacedPodResizeAsync(new V1Patch(patchStr, V1Patch.PatchType.MergePatch), "nginx-pod", "default").ConfigureAwait(false); + + if (patch?.Spec?.Containers?.Count > 0 && + patch.Spec.Containers[0].Resources?.Requests != null && + patch.Spec.Containers[0].Resources.Requests.TryGetValue("cpu", out var cpuQty)) + { + Console.WriteLine($"CPU request: {cpuQty}"); + } +} diff --git a/examples/resize/resize.csproj b/examples/resize/resize.csproj new file mode 100644 index 000000000..d1e5b4724 --- /dev/null +++ b/examples/resize/resize.csproj @@ -0,0 +1,5 @@ + + + Exe + + \ No newline at end of file diff --git a/examples/restart/Program.cs b/examples/restart/Program.cs index b6e7a6f22..894e305a6 100644 --- a/examples/restart/Program.cs +++ b/examples/restart/Program.cs @@ -1,17 +1,17 @@ -using Json.Patch; +using Json.Patch; using k8s; using k8s.Models; using System.Text.Json; async Task RestartDaemonSetAsync(string name, string @namespace, IKubernetes client) { - var daemonSet = await client.AppsV1.ReadNamespacedDaemonSetAsync(name, @namespace); + var daemonSet = await client.AppsV1.ReadNamespacedDaemonSetAsync(name, @namespace).ConfigureAwait(false); var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true }; var old = JsonSerializer.SerializeToDocument(daemonSet, options); var now = DateTimeOffset.Now.ToUnixTimeSeconds(); var restart = new Dictionary { - ["date"] = now.ToString() + ["date"] = now.ToString(), }; daemonSet.Spec.Template.Metadata.Annotations = restart; @@ -19,18 +19,18 @@ async Task RestartDaemonSetAsync(string name, string @namespace, IKubernetes cli var expected = JsonSerializer.SerializeToDocument(daemonSet); var patch = old.CreatePatch(expected); - await client.AppsV1.PatchNamespacedDaemonSetAsync(new V1Patch(patch, V1Patch.PatchType.JsonPatch), name, @namespace); + await client.AppsV1.PatchNamespacedDaemonSetAsync(new V1Patch(patch, V1Patch.PatchType.JsonPatch), name, @namespace).ConfigureAwait(false); } async Task RestartDeploymentAsync(string name, string @namespace, IKubernetes client) { - var deployment = await client.AppsV1.ReadNamespacedDeploymentAsync(name, @namespace); + var deployment = await client.AppsV1.ReadNamespacedDeploymentAsync(name, @namespace).ConfigureAwait(false); var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true }; var old = JsonSerializer.SerializeToDocument(deployment, options); var now = DateTimeOffset.Now.ToUnixTimeSeconds(); var restart = new Dictionary { - ["date"] = now.ToString() + ["date"] = now.ToString(), }; deployment.Spec.Template.Metadata.Annotations = restart; @@ -38,18 +38,18 @@ async Task RestartDeploymentAsync(string name, string @namespace, IKubernetes cl var expected = JsonSerializer.SerializeToDocument(deployment); var patch = old.CreatePatch(expected); - await client.AppsV1.PatchNamespacedDeploymentAsync(new V1Patch(patch, V1Patch.PatchType.JsonPatch), name, @namespace); + await client.AppsV1.PatchNamespacedDeploymentAsync(new V1Patch(patch, V1Patch.PatchType.JsonPatch), name, @namespace).ConfigureAwait(false); } async Task RestartStatefulSetAsync(string name, string @namespace, IKubernetes client) { - var deployment = await client.AppsV1.ReadNamespacedStatefulSetAsync(name, @namespace); + var deployment = await client.AppsV1.ReadNamespacedStatefulSetAsync(name, @namespace).ConfigureAwait(false); var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true }; var old = JsonSerializer.SerializeToDocument(deployment, options); var now = DateTimeOffset.Now.ToUnixTimeSeconds(); var restart = new Dictionary { - ["date"] = now.ToString() + ["date"] = now.ToString(), }; deployment.Spec.Template.Metadata.Annotations = restart; @@ -57,12 +57,12 @@ async Task RestartStatefulSetAsync(string name, string @namespace, IKubernetes c var expected = JsonSerializer.SerializeToDocument(deployment); var patch = old.CreatePatch(expected); - await client.AppsV1.PatchNamespacedStatefulSetAsync(new V1Patch(patch, V1Patch.PatchType.JsonPatch), name, @namespace); + await client.AppsV1.PatchNamespacedStatefulSetAsync(new V1Patch(patch, V1Patch.PatchType.JsonPatch), name, @namespace).ConfigureAwait(false); } var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); IKubernetes client = new Kubernetes(config); -await RestartDeploymentAsync("event-exporter", "monitoring", client); -await RestartDaemonSetAsync("prometheus-exporter", "monitoring", client); -await RestartStatefulSetAsync("argocd-application-controlle", "argocd", client); +await RestartDeploymentAsync("event-exporter", "monitoring", client).ConfigureAwait(false); +await RestartDaemonSetAsync("prometheus-exporter", "monitoring", client).ConfigureAwait(false); +await RestartStatefulSetAsync("argocd-application-controlle", "argocd", client).ConfigureAwait(false); diff --git a/examples/simple/PodList.cs b/examples/simple/PodList.cs index b9eb3cdcf..751622c16 100755 --- a/examples/simple/PodList.cs +++ b/examples/simple/PodList.cs @@ -1,26 +1,17 @@ using k8s; using System; -namespace simple -{ - internal class PodList - { - private static void Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildDefaultConfig(); - IKubernetes client = new Kubernetes(config); - Console.WriteLine("Starting Request!"); +var config = KubernetesClientConfiguration.BuildDefaultConfig(); +IKubernetes client = new Kubernetes(config); +Console.WriteLine("Starting Request!"); - var list = client.CoreV1.ListNamespacedPod("default"); - foreach (var item in list.Items) - { - Console.WriteLine(item.Metadata.Name); - } +var list = client.CoreV1.ListNamespacedPod("default"); +foreach (var item in list.Items) +{ + Console.WriteLine(item.Metadata.Name); +} - if (list.Items.Count == 0) - { - Console.WriteLine("Empty!"); - } - } - } +if (list.Items.Count == 0) +{ + Console.WriteLine("Empty!"); } diff --git a/examples/watch/Program.cs b/examples/watch/Program.cs index 525cbec5c..1aff65883 100644 --- a/examples/watch/Program.cs +++ b/examples/watch/Program.cs @@ -1,50 +1,39 @@ using k8s; -using k8s.Models; using System; using System.Threading; using System.Threading.Tasks; -namespace watch -{ - internal class Program - { - private static async Task Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - IKubernetes client = new Kubernetes(config); +IKubernetes client = new Kubernetes(config); - var podlistResp = client.CoreV1.ListNamespacedPodWithHttpMessagesAsync("default", watch: true); - // C# 8 required https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8 - await foreach (var (type, item) in podlistResp.WatchAsync()) - { - Console.WriteLine("==on watch event=="); - Console.WriteLine(type); - Console.WriteLine(item.Metadata.Name); - Console.WriteLine("==on watch event=="); - } +var podlistResp = client.CoreV1.WatchListNamespacedPodAsync("default"); - // uncomment if you prefer callback api - // WatchUsingCallback(client); - } +// C# 8 required https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8 +await foreach (var (type, item) in podlistResp.ConfigureAwait(false)) +{ + Console.WriteLine("==on watch event=="); + Console.WriteLine(type); + Console.WriteLine(item.Metadata.Name); + Console.WriteLine("==on watch event=="); +} - private static void WatchUsingCallback(IKubernetes client) - { - var podlistResp = client.CoreV1.ListNamespacedPodWithHttpMessagesAsync("default", watch: true); - using (podlistResp.Watch((type, item) => - { - Console.WriteLine("==on watch event=="); - Console.WriteLine(type); - Console.WriteLine(item.Metadata.Name); - Console.WriteLine("==on watch event=="); - })) - { - Console.WriteLine("press ctrl + c to stop watching"); +#pragma warning disable CS8321 // Remove unused private members +void WatchUsingCallback(IKubernetes client) +#pragma warning restore CS8321 // Remove unused private members +{ + using (var podlistResp = client.CoreV1.WatchListNamespacedPod("default", onEvent: (type, item) => + { + Console.WriteLine("==on watch event=="); + Console.WriteLine(type); + Console.WriteLine(item.Metadata.Name); + Console.WriteLine("==on watch event=="); + })) + { + Console.WriteLine("press ctrl + c to stop watching"); - var ctrlc = new ManualResetEventSlim(false); - Console.CancelKeyPress += (sender, eventArgs) => ctrlc.Set(); - ctrlc.Wait(); - } - } + var ctrlc = new ManualResetEventSlim(false); + Console.CancelKeyPress += (sender, eventArgs) => ctrlc.Set(); + ctrlc.Wait(); } -} +} \ No newline at end of file diff --git a/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnConstructorController.cs b/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnConstructorController.cs index 30fd2656c..6bff6df0d 100644 --- a/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnConstructorController.cs +++ b/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnConstructorController.cs @@ -10,22 +10,23 @@ public class ExampleDependencyInjectionOnConstructorController : ControllerBase private readonly IKubernetes kubernetesClient; /// - /// Inject the kubernets class in the constructor. + /// Initializes a new instance of the class. + /// Injects the Kubernetes client into the controller. /// - /// + /// The Kubernetes client to interact with the Kubernetes API. public ExampleDependencyInjectionOnConstructorController(IKubernetes kubernetesClient) { this.kubernetesClient = kubernetesClient; } /// - /// Example using the kubernetes client obtained from the constructor (this.kubernetesClient). + /// Retrieves the names of all pods in the default namespace using the injected Kubernetes client. /// - /// - [HttpGet()] + /// A collection of pod names in the default namespace. + [HttpGet] public IEnumerable GetPods() { - // Read the list of pods contained in default namespace + // Read the list of pods contained in the default namespace var podList = this.kubernetesClient.CoreV1.ListNamespacedPod("default"); // Return names of pods diff --git a/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnMethodController.cs b/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnMethodController.cs index 0a831befb..84427f5e2 100644 --- a/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnMethodController.cs +++ b/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnMethodController.cs @@ -10,11 +10,13 @@ public class ExampleDependencyInjectionOnMethodController : ControllerBase /// /// Example using the kubernetes client injected directly into the method ([FromServices] IKubernetes kubernetesClient). /// - /// - /// - [HttpGet()] + /// The Kubernetes client instance injected via dependency injection. + /// A collection of pod names in the default namespace. + [HttpGet] public IEnumerable GetPods([FromServices] IKubernetes kubernetesClient) { + ArgumentNullException.ThrowIfNull(kubernetesClient); + // Read the list of pods contained in default namespace var podList = kubernetesClient.CoreV1.ListNamespacedPod("default"); diff --git a/examples/workerServiceDependencyInjection/Program.cs b/examples/workerServiceDependencyInjection/Program.cs index 59bf3cf25..a894a33fe 100644 --- a/examples/workerServiceDependencyInjection/Program.cs +++ b/examples/workerServiceDependencyInjection/Program.cs @@ -14,4 +14,4 @@ }) .Build(); -await host.RunAsync(); +await host.RunAsync().ConfigureAwait(false); diff --git a/examples/workerServiceDependencyInjection/Worker.cs b/examples/workerServiceDependencyInjection/Worker.cs index 87d2ecfe2..cb2f82386 100644 --- a/examples/workerServiceDependencyInjection/Worker.cs +++ b/examples/workerServiceDependencyInjection/Worker.cs @@ -8,10 +8,11 @@ public class Worker : BackgroundService private readonly IKubernetes kubernetesClient; /// + /// Initializes a new instance of the class. /// Inject in the constructor the IKubernetes interface. /// - /// - /// + /// The logger instance used for logging information. + /// The Kubernetes client used to interact with the Kubernetes API. public Worker(ILogger logger, IKubernetes kubernetesClient) { this.logger = logger; @@ -33,7 +34,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) Console.WriteLine(pod.Metadata.Name); } - await Task.Delay(1000, stoppingToken); + await Task.Delay(1000, stoppingToken).ConfigureAwait(false); } } } diff --git a/examples/yaml/Program.cs b/examples/yaml/Program.cs index 04676b16f..47b70bdfe 100644 --- a/examples/yaml/Program.cs +++ b/examples/yaml/Program.cs @@ -2,27 +2,17 @@ using k8s.Models; using System; using System.Collections.Generic; -using System.Threading.Tasks; -namespace yaml +var typeMap = new Dictionary { - internal class Program - { - private static async Task Main(string[] args) - { - var typeMap = new Dictionary - { - { "v1/Pod", typeof(V1Pod) }, - { "v1/Service", typeof(V1Service) }, - { "apps/v1/Deployment", typeof(V1Deployment) } - }; + { "v1/Pod", typeof(V1Pod) }, + { "v1/Service", typeof(V1Service) }, + { "apps/v1/Deployment", typeof(V1Deployment) }, +}; - var objects = await KubernetesYaml.LoadAllFromFileAsync(args[0], typeMap); +var objects = await KubernetesYaml.LoadAllFromFileAsync(args[0], typeMap).ConfigureAwait(false); - foreach (var obj in objects) - { - Console.WriteLine(obj); - } - } - } +foreach (var obj in objects) +{ + Console.WriteLine(obj); } diff --git a/src/KubernetesClient.Aot/KubeConfigModels/ExecCredentialResponse.cs b/src/KubernetesClient.Aot/KubeConfigModels/ExecCredentialResponse.cs index 5bac4af5e..d593ff4f6 100644 --- a/src/KubernetesClient.Aot/KubeConfigModels/ExecCredentialResponse.cs +++ b/src/KubernetesClient.Aot/KubeConfigModels/ExecCredentialResponse.cs @@ -8,9 +8,13 @@ public class ExecCredentialResponse public class ExecStatus { #nullable enable + [JsonPropertyName("expirationTimestamp")] public DateTime? ExpirationTimestamp { get; set; } + [JsonPropertyName("token")] public string? Token { get; set; } + [JsonPropertyName("clientCertificateData")] public string? ClientCertificateData { get; set; } + [JsonPropertyName("clientKeyData")] public string? ClientKeyData { get; set; } #nullable disable diff --git a/src/KubernetesClient.Aot/KubeConfigModels/ExecCredentialResponseContext.cs b/src/KubernetesClient.Aot/KubeConfigModels/ExecCredentialResponseContext.cs new file mode 100644 index 000000000..c7ffd8294 --- /dev/null +++ b/src/KubernetesClient.Aot/KubeConfigModels/ExecCredentialResponseContext.cs @@ -0,0 +1,7 @@ +namespace k8s.KubeConfigModels +{ + [JsonSerializable(typeof(ExecCredentialResponse))] + internal partial class ExecCredentialResponseContext : JsonSerializerContext + { + } +} diff --git a/src/KubernetesClient.Aot/KubernetesClient.Aot.csproj b/src/KubernetesClient.Aot/KubernetesClient.Aot.csproj index 740ad73ff..5c7cf8fed 100644 --- a/src/KubernetesClient.Aot/KubernetesClient.Aot.csproj +++ b/src/KubernetesClient.Aot/KubernetesClient.Aot.csproj @@ -1,11 +1,12 @@ - + - net8.0 + net8.0;net9.0 k8s true true true + $(DefineConstants);K8S_AOT @@ -19,20 +20,18 @@ - + - + - - - - + + + - @@ -44,7 +43,15 @@ - + + + + + + + + + @@ -100,11 +107,7 @@ - - - - - \ No newline at end of file + diff --git a/src/KubernetesClient.Aot/KubernetesClientConfiguration.ConfigFile.cs b/src/KubernetesClient.Aot/KubernetesClientConfiguration.ConfigFile.cs index 597eea7c5..a2301b464 100644 --- a/src/KubernetesClient.Aot/KubernetesClientConfiguration.ConfigFile.cs +++ b/src/KubernetesClient.Aot/KubernetesClientConfiguration.ConfigFile.cs @@ -306,21 +306,32 @@ private void SetClusterDetails(K8SConfiguration k8SConfig, Context activeContext { if (!string.IsNullOrEmpty(clusterDetails.ClusterEndpoint.CertificateAuthorityData)) { + var data = clusterDetails.ClusterEndpoint.CertificateAuthorityData; +#if NET9_0_OR_GREATER + SslCaCerts = new X509Certificate2Collection(X509CertificateLoader.LoadCertificate(Convert.FromBase64String(data))); +#else + string nullPassword = null; // This null password is to change the constructor to fix this KB: // https://support.microsoft.com/en-us/topic/kb5025823-change-in-how-net-applications-import-x-509-certificates-bf81c936-af2b-446e-9f7a-016f4713b46b - string nullPassword = null; - var data = clusterDetails.ClusterEndpoint.CertificateAuthorityData; SslCaCerts = new X509Certificate2Collection(new X509Certificate2(Convert.FromBase64String(data), nullPassword)); +#endif } else if (!string.IsNullOrEmpty(clusterDetails.ClusterEndpoint.CertificateAuthority)) { +#if NET9_0_OR_GREATER + SslCaCerts = new X509Certificate2Collection(X509CertificateLoader.LoadCertificateFromFile(GetFullPath( + k8SConfig, + clusterDetails.ClusterEndpoint.CertificateAuthority))); +#else SslCaCerts = new X509Certificate2Collection(new X509Certificate2(GetFullPath( k8SConfig, clusterDetails.ClusterEndpoint.CertificateAuthority))); +#endif } } } + private void SetUserDetails(K8SConfiguration k8SConfig, Context activeContext) { if (string.IsNullOrWhiteSpace(activeContext.ContextDetails.User)) @@ -512,7 +523,10 @@ public static ExecCredentialResponse ExecuteExternalCommand(ExternalExecution co throw new KubeConfigException("external exec failed due to timeout"); } - var responseObject = KubernetesJson.Deserialize(process.StandardOutput.ReadToEnd()); + var responseObject = JsonSerializer.Deserialize( + process.StandardOutput.ReadToEnd(), + ExecCredentialResponseContext.Default.ExecCredentialResponse); + if (responseObject == null || responseObject.ApiVersion != config.ApiVersion) { throw new KubeConfigException( diff --git a/src/KubernetesClient.Aot/KubernetesJson.cs b/src/KubernetesClient.Aot/KubernetesJson.cs deleted file mode 100644 index cfa69ec01..000000000 --- a/src/KubernetesClient.Aot/KubernetesJson.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System.Globalization; -using System.Text.RegularExpressions; -using System.Xml; - -namespace k8s -{ - internal static class KubernetesJson - { - internal sealed class Iso8601TimeSpanConverter : JsonConverter - { - public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var str = reader.GetString(); - return XmlConvert.ToTimeSpan(str); - } - - public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options) - { - var iso8601TimeSpanString = XmlConvert.ToString(value); // XmlConvert for TimeSpan uses ISO8601, so delegate serialization to it - writer.WriteStringValue(iso8601TimeSpanString); - } - } - - internal sealed class KubernetesDateTimeOffsetConverter : JsonConverter - { - private const string RFC3339MicroFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.ffffffK"; - private const string RFC3339NanoFormat = "yyyy-MM-dd'T'HH':'mm':'ss.fffffffK"; - private const string RFC3339Format = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK"; - - public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var str = reader.GetString(); - - if (DateTimeOffset.TryParseExact(str, new[] { RFC3339Format, RFC3339MicroFormat }, CultureInfo.InvariantCulture, DateTimeStyles.None, out var result)) - { - return result; - } - - // try RFC3339NanoLenient by trimming 1-9 digits to 7 digits - var originalstr = str; - str = Regex.Replace(str, @"\.\d+", m => (m.Value + "000000000").Substring(0, 7 + 1)); // 7 digits + 1 for the dot - if (DateTimeOffset.TryParseExact(str, new[] { RFC3339NanoFormat }, CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) - { - return result; - } - - throw new FormatException($"Unable to parse {originalstr} as RFC3339 RFC3339Micro or RFC3339Nano"); - } - - public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString(RFC3339MicroFormat)); - } - } - - internal sealed class KubernetesDateTimeConverter : JsonConverter - { - private static readonly JsonConverter UtcConverter = new KubernetesDateTimeOffsetConverter(); - public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return UtcConverter.Read(ref reader, typeToConvert, options).UtcDateTime; - } - - public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) - { - UtcConverter.Write(writer, value, options); - } - } - - /// - /// Configures for the . - /// To override existing converters, add them to the top of the list - /// e.g. as follows: options.Converters.Insert(index: 0, new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); - /// - /// An to configure the . - public static void AddJsonOptions(Action configure) - { - } - - public static TValue Deserialize(string json, JsonSerializerOptions jsonSerializerOptions = null) - { - var info = SourceGenerationContext.Default.GetTypeInfo(typeof(TValue)); - return (TValue)JsonSerializer.Deserialize(json, info); - } - - public static TValue Deserialize(Stream json, JsonSerializerOptions jsonSerializerOptions = null) - { - var info = SourceGenerationContext.Default.GetTypeInfo(typeof(TValue)); - return (TValue)JsonSerializer.Deserialize(json, info); - } - - public static string Serialize(object value, JsonSerializerOptions jsonSerializerOptions = null) - { - var info = SourceGenerationContext.Default.GetTypeInfo(value.GetType()); - return JsonSerializer.Serialize(value, info); - } - } -} diff --git a/src/KubernetesClient.Aot/KubernetesYaml.cs b/src/KubernetesClient.Aot/KubernetesYaml.cs index 069b1c12e..5530a2e02 100644 --- a/src/KubernetesClient.Aot/KubernetesYaml.cs +++ b/src/KubernetesClient.Aot/KubernetesYaml.cs @@ -17,6 +17,8 @@ internal static class KubernetesYaml .WithTypeConverter(new IntOrStringYamlConverter()) .WithTypeConverter(new ByteArrayStringYamlConverter()) .WithTypeConverter(new ResourceQuantityYamlConverter()) + .WithTypeConverter(new KubernetesDateTimeYamlConverter()) + .WithTypeConverter(new KubernetesDateTimeOffsetYamlConverter()) .WithAttemptingUnquotedStringTypeDeserialization() ; @@ -33,6 +35,8 @@ internal static class KubernetesYaml .WithTypeConverter(new IntOrStringYamlConverter()) .WithTypeConverter(new ByteArrayStringYamlConverter()) .WithTypeConverter(new ResourceQuantityYamlConverter()) + .WithTypeConverter(new KubernetesDateTimeYamlConverter()) + .WithTypeConverter(new KubernetesDateTimeOffsetYamlConverter()) .WithEventEmitter(e => new StringQuotingEmitter(e)) .WithEventEmitter(e => new FloatEmitter(e)) .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull) @@ -56,7 +60,7 @@ public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeseria return null; } - return Encoding.UTF8.GetBytes(scalar.Value); + return Convert.FromBase64String(scalar.Value); } finally { @@ -69,8 +73,15 @@ public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeseria public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer) { + if (value == null) + { + emitter.Emit(new Scalar(string.Empty)); + return; + } + var obj = (byte[])value; - emitter?.Emit(new Scalar(Encoding.UTF8.GetString(obj))); + var encoded = Convert.ToBase64String(obj); + emitter.Emit(new Scalar(encoded)); } } diff --git a/src/KubernetesClient.Aot/SourceGenerationContext.cs b/src/KubernetesClient.Aot/SourceGenerationContext.cs deleted file mode 100644 index decb9b5a9..000000000 --- a/src/KubernetesClient.Aot/SourceGenerationContext.cs +++ /dev/null @@ -1,12 +0,0 @@ -using static k8s.KubernetesJson; - -namespace k8s; - -[JsonSourceGenerationOptions( - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, - PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, - Converters = new[] { typeof(Iso8601TimeSpanConverter), typeof(KubernetesDateTimeConverter), typeof(KubernetesDateTimeOffsetConverter) }) - ] -internal partial class SourceGenerationContext : JsonSerializerContext -{ -} diff --git a/src/KubernetesClient.Classic/IsExternalInit.cs b/src/KubernetesClient.Classic/IsExternalInit.cs new file mode 100644 index 000000000..749f30858 --- /dev/null +++ b/src/KubernetesClient.Classic/IsExternalInit.cs @@ -0,0 +1,5 @@ +// IntOrString.cs(7,36): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported +namespace System.Runtime.CompilerServices +{ + internal static class IsExternalInit { } +} \ No newline at end of file diff --git a/src/KubernetesClient.Classic/KubernetesClient.Classic.csproj b/src/KubernetesClient.Classic/KubernetesClient.Classic.csproj index 81093c91e..902dc41dd 100644 --- a/src/KubernetesClient.Classic/KubernetesClient.Classic.csproj +++ b/src/KubernetesClient.Classic/KubernetesClient.Classic.csproj @@ -7,8 +7,6 @@ - - @@ -24,22 +22,20 @@ - + - + - - - - + + + - @@ -53,6 +49,9 @@ + + + @@ -77,7 +76,10 @@ - + + + + diff --git a/src/KubernetesClient.Kubectl/KubernetesClient.Kubectl.csproj b/src/KubernetesClient.Kubectl/KubernetesClient.Kubectl.csproj index 09e37730b..25440a1f7 100644 --- a/src/KubernetesClient.Kubectl/KubernetesClient.Kubectl.csproj +++ b/src/KubernetesClient.Kubectl/KubernetesClient.Kubectl.csproj @@ -1,7 +1,7 @@ - net6.0;net8.0 + net8.0;net9.0 enable enable k8s.kubectl diff --git a/src/KubernetesClient.ModelConverter/AutoMapper/AutoMapperModelVersionConverter.cs b/src/KubernetesClient.ModelConverter/AutoMapper/AutoMapperModelVersionConverter.cs deleted file mode 100644 index c44190a46..000000000 --- a/src/KubernetesClient.ModelConverter/AutoMapper/AutoMapperModelVersionConverter.cs +++ /dev/null @@ -1,17 +0,0 @@ -using static k8s.Models.ModelVersionConverter; - -namespace k8s.ModelConverter.AutoMapper; - -public class AutoMapperModelVersionConverter : IModelVersionConverter -{ - public static IModelVersionConverter Instance { get; } = new AutoMapperModelVersionConverter(); - - private AutoMapperModelVersionConverter() - { - } - - public TTo Convert(TFrom from) - { - return VersionConverter.Mapper.Map(from); - } -} diff --git a/src/KubernetesClient.ModelConverter/AutoMapper/KubernetesVersionComparer.cs b/src/KubernetesClient.ModelConverter/AutoMapper/KubernetesVersionComparer.cs deleted file mode 100644 index de22d25e1..000000000 --- a/src/KubernetesClient.ModelConverter/AutoMapper/KubernetesVersionComparer.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; - -namespace k8s.ModelConverter.AutoMapper; - -internal class KubernetesVersionComparer : IComparer -{ - public static KubernetesVersionComparer Instance { get; } = new KubernetesVersionComparer(); - private static readonly Regex KubernetesVersionRegex = new Regex(@"^v(?[0-9]+)((?alpha|beta)(?[0-9]+))?$", RegexOptions.Compiled); - - internal KubernetesVersionComparer() - { - } - - public int Compare(string x, string y) - { - if (x == null || y == null) - { - return StringComparer.CurrentCulture.Compare(x, y); - } - - var matchX = KubernetesVersionRegex.Match(x); - if (!matchX.Success) - { - return StringComparer.CurrentCulture.Compare(x, y); - } - - var matchY = KubernetesVersionRegex.Match(y); - if (!matchY.Success) - { - return StringComparer.CurrentCulture.Compare(x, y); - } - - var versionX = ExtractVersion(matchX); - var versionY = ExtractVersion(matchY); - return versionX.CompareTo(versionY); - } - - private Version ExtractVersion(Match match) - { - var major = int.Parse(match.Groups["major"].Value); - if (!Enum.TryParse(match.Groups["stream"].Value, true, out var stream)) - { - stream = Stream.Final; - } - - _ = int.TryParse(match.Groups["minor"].Value, out var minor); - return new Version(major, (int)stream, minor); - } - - private enum Stream - { - Alpha = 1, - Beta = 2, - Final = 3, - } -} diff --git a/src/KubernetesClient.ModelConverter/AutoMapper/VersionConverter.cs b/src/KubernetesClient.ModelConverter/AutoMapper/VersionConverter.cs deleted file mode 100644 index 97e9080fe..000000000 --- a/src/KubernetesClient.ModelConverter/AutoMapper/VersionConverter.cs +++ /dev/null @@ -1,174 +0,0 @@ -// WARNING: DO NOT LEAVE COMMENTED CODE IN THIS FILE. IT GETS SCANNED BY GEN PROJECT SO IT CAN EXCLUDE ANY MANUALLY DEFINED MAPS - -using AutoMapper; -#if NET6_0_OR_GREATER -using AutoMapper.Internal; -#endif -using k8s.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -namespace k8s.ModelConverter.AutoMapper; - -/// -/// Provides mappers that converts Kubernetes models between different versions -/// -internal static partial class VersionConverter -{ - static VersionConverter() - { - UpdateMappingConfiguration(expression => { }); - } - - public static IMapper Mapper { get; private set; } - internal static MapperConfiguration MapperConfiguration { get; private set; } - - /// - /// Two level lookup of model types by Kind and then Version - /// - internal static Dictionary> KindVersionsMap { get; private set; } - - public static Type GetTypeForVersion(string version) - { - return GetTypeForVersion(typeof(T), version); - } - - public static Type GetTypeForVersion(Type type, string version) - { - return KindVersionsMap[type.GetKubernetesTypeMetadata().Kind][version]; - } - - public static void UpdateMappingConfiguration(Action configuration) - { - MapperConfiguration = new MapperConfiguration(cfg => - { - GetConfigurations(cfg); - configuration(cfg); - }); - Mapper = MapperConfiguration -#if NET6_0_OR_GREATER - .Internal() -#endif - .CreateMapper(); - KindVersionsMap = MapperConfiguration -#if NET6_0_OR_GREATER - .Internal() -#endif - .GetAllTypeMaps() - .SelectMany(x => new[] { x.Types.SourceType, x.Types.DestinationType }) - .Where(x => x.GetCustomAttribute() != null) - .Select(x => - { - var attr = GetKubernetesEntityAttribute(x); - return new { attr.Kind, attr.ApiVersion, Type = x }; - }) - .GroupBy(x => x.Kind) - .ToDictionary(x => x.Key, kindGroup => kindGroup - .GroupBy(x => x.ApiVersion) - .ToDictionary( - x => x.Key, - versionGroup => versionGroup.Select(x => x.Type).Distinct().Single())); // should only be one type for each Kind/Version combination - } - - public static object ConvertToVersion(object source, string apiVersion) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - var type = source.GetType(); - var attr = GetKubernetesEntityAttribute(type); - if (attr.ApiVersion == apiVersion) - { - return source; - } - - if (!KindVersionsMap.TryGetValue(attr.Kind, out var kindVersions)) - { - throw new InvalidOperationException($"Version converter does not have any registered types for Kind `{attr.Kind}`"); - } - - if (!kindVersions.TryGetValue(apiVersion, out var targetType) || !kindVersions.TryGetValue(attr.ApiVersion, out var sourceType) || - MapperConfiguration -#if NET6_0_OR_GREATER - .Internal() -#endif - .FindTypeMapFor(sourceType, targetType) == null) - { - throw new InvalidOperationException($"There is no conversion mapping registered for Kind `{attr.Kind}` from ApiVersion {attr.ApiVersion} to {apiVersion}"); - } - - return Mapper.Map(source, sourceType, targetType); - } - - private static KubernetesEntityAttribute GetKubernetesEntityAttribute(Type type) - { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - var attr = type.GetCustomAttribute(); - if (attr == null) - { - throw new InvalidOperationException($"Type {type} does not have {nameof(KubernetesEntityAttribute)}"); - } - - return attr; - } - - internal static void GetConfigurations(IMapperConfigurationExpression cfg) - { - AutoConfigurations(cfg); - ManualConfigurations(cfg); - } - - private static void ManualConfigurations(IMapperConfigurationExpression cfg) - { - cfg.AllowNullCollections = true; - cfg.DisableConstructorMapping(); - cfg -#if NET6_0_OR_GREATER - .Internal() -#endif - .ForAllMaps((typeMap, opt) => - { - if (!typeof(IKubernetesObject).IsAssignableFrom(typeMap.Types.DestinationType)) - { - return; - } - - var metadata = typeMap.Types.DestinationType.GetKubernetesTypeMetadata(); - opt.ForMember(nameof(IKubernetesObject.ApiVersion), x => x.Ignore()); - opt.ForMember(nameof(IKubernetesObject.Kind), x => x.Ignore()); - opt.AfterMap((from, to) => - { - var obj = (IKubernetesObject)to; - obj.ApiVersion = !string.IsNullOrEmpty(metadata.Group) ? $"{metadata.Group}/{metadata.ApiVersion}" : metadata.ApiVersion; - obj.Kind = metadata.Kind; - }); - }); - - cfg.CreateMap() - .ForMember(dest => dest.Metrics, opt => opt.Ignore()) - .ForMember(dest => dest.Behavior, opt => opt.Ignore()) - .ReverseMap(); - - - cfg.CreateMap() - .ForMember(dest => dest.Conditions, opt => opt.Ignore()) - .ForMember(dest => dest.CurrentMetrics, opt => opt.Ignore()) - .ReverseMap(); - - cfg.CreateMap() - .ForMember(dest => dest.Name, opt => opt.Ignore()) - .ReverseMap(); - - cfg.CreateMap() - .ForMember(dest => dest.Subjects, opt => opt.Ignore()) - .ReverseMap(); - } -} diff --git a/src/KubernetesClient.ModelConverter/KubernetesClient.ModelConverter.csproj b/src/KubernetesClient.ModelConverter/KubernetesClient.ModelConverter.csproj deleted file mode 100644 index 8d6a4f539..000000000 --- a/src/KubernetesClient.ModelConverter/KubernetesClient.ModelConverter.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - net6.0;net8.0 - k8s.ModelConverter - - - - - - - - - - - - - - - - diff --git a/src/KubernetesClient/Authentication/OidcTokenProvider.cs b/src/KubernetesClient/Authentication/OidcTokenProvider.cs index ef9c35403..912ea0fde 100644 --- a/src/KubernetesClient/Authentication/OidcTokenProvider.cs +++ b/src/KubernetesClient/Authentication/OidcTokenProvider.cs @@ -1,23 +1,28 @@ -using IdentityModel.OidcClient; using k8s.Exceptions; -using System.IdentityModel.Tokens.Jwt; +using System.Net.Http; using System.Net.Http.Headers; +using System.Text; namespace k8s.Authentication { public class OidcTokenProvider : ITokenProvider { - private readonly OidcClient _oidcClient; + private readonly string _clientId; + private readonly string _clientSecret; + private readonly string _idpIssuerUrl; + private string _idToken; private string _refreshToken; private DateTimeOffset _expiry; public OidcTokenProvider(string clientId, string clientSecret, string idpIssuerUrl, string idToken, string refreshToken) { + _clientId = clientId; + _clientSecret = clientSecret; + _idpIssuerUrl = idpIssuerUrl; _idToken = idToken; _refreshToken = refreshToken; - _oidcClient = getClient(clientId, clientSecret, idpIssuerUrl); - _expiry = getExpiryFromToken(); + _expiry = GetExpiryFromToken(); } public async Task GetAuthenticationHeaderAsync(CancellationToken cancellationToken) @@ -30,49 +35,77 @@ public async Task GetAuthenticationHeaderAsync(Cancel return new AuthenticationHeaderValue("Bearer", _idToken); } - private DateTime getExpiryFromToken() + private DateTimeOffset GetExpiryFromToken() { - long expiry; - var handler = new JwtSecurityTokenHandler(); try { - var token = handler.ReadJwtToken(_idToken); - expiry = token.Payload.Expiration ?? 0; + var parts = _idToken.Split('.'); + var payload = parts[1]; + var jsonBytes = Base64UrlDecode(payload); + var json = Encoding.UTF8.GetString(jsonBytes); + + using var document = JsonDocument.Parse(json); + if (document.RootElement.TryGetProperty("exp", out var expElement)) + { + var exp = expElement.GetInt64(); + return DateTimeOffset.FromUnixTimeSeconds(exp); + } } catch { - expiry = 0; + // ignore to default } - return DateTimeOffset.FromUnixTimeSeconds(expiry).UtcDateTime; + return default; } - private OidcClient getClient(string clientId, string clientSecret, string idpIssuerUrl) + private static byte[] Base64UrlDecode(string input) { - OidcClientOptions options = new OidcClientOptions + var output = input.Replace('-', '+').Replace('_', '/'); + switch (output.Length % 4) { - ClientId = clientId, - ClientSecret = clientSecret ?? "", - Authority = idpIssuerUrl, - }; + case 2: output += "=="; break; + case 3: output += "="; break; + } - return new OidcClient(options); + return Convert.FromBase64String(output); } private async Task RefreshToken() { try { - var result = await _oidcClient.RefreshTokenAsync(_refreshToken).ConfigureAwait(false); + using var httpClient = new HttpClient(); + var request = new HttpRequestMessage(HttpMethod.Post, _idpIssuerUrl); + request.Content = new FormUrlEncodedContent(new Dictionary + { + { "grant_type", "refresh_token" }, + { "client_id", _clientId }, + { "client_secret", _clientSecret }, + { "refresh_token", _refreshToken }, + }); + + var response = await httpClient.SendAsync(request).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); - if (result.IsError) + var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + var jsonDocument = JsonDocument.Parse(responseContent); + + if (jsonDocument.RootElement.TryGetProperty("id_token", out var idTokenElement)) + { + _idToken = idTokenElement.GetString(); + } + + if (jsonDocument.RootElement.TryGetProperty("refresh_token", out var refreshTokenElement)) { - throw new Exception(result.Error); + _refreshToken = refreshTokenElement.GetString(); } - _idToken = result.IdentityToken; - _refreshToken = result.RefreshToken; - _expiry = result.AccessTokenExpiration; + if (jsonDocument.RootElement.TryGetProperty("expires_in", out var expiresInElement)) + { + var expiresIn = expiresInElement.GetInt32(); + _expiry = DateTimeOffset.UtcNow.AddSeconds(expiresIn); + } } catch (Exception e) { diff --git a/src/KubernetesClient/CertUtils.cs b/src/KubernetesClient/CertUtils.cs index 53f6078f1..7a398d7e8 100644 --- a/src/KubernetesClient/CertUtils.cs +++ b/src/KubernetesClient/CertUtils.cs @@ -80,11 +80,20 @@ public static X509Certificate2 GeneratePfx(KubernetesClientConfiguration config) if (config.ClientCertificateKeyStoreFlags.HasValue) { +#if NET9_0_OR_GREATER + cert = X509CertificateLoader.LoadPkcs12(cert.Export(X509ContentType.Pkcs12), nullPassword, config.ClientCertificateKeyStoreFlags.Value); +#else cert = new X509Certificate2(cert.Export(X509ContentType.Pkcs12), nullPassword, config.ClientCertificateKeyStoreFlags.Value); +#endif + } else { +#if NET9_0_OR_GREATER + cert = X509CertificateLoader.LoadPkcs12(cert.Export(X509ContentType.Pkcs12), nullPassword); +#else cert = new X509Certificate2(cert.Export(X509ContentType.Pkcs12), nullPassword); +#endif } } diff --git a/src/KubernetesClient/ClientSets/ClientSet.cs b/src/KubernetesClient/ClientSets/ClientSet.cs new file mode 100644 index 000000000..53aa37df9 --- /dev/null +++ b/src/KubernetesClient/ClientSets/ClientSet.cs @@ -0,0 +1,16 @@ +namespace k8s.ClientSets +{ + /// + /// Represents a base class for clients that interact with Kubernetes resources. + /// Provides shared functionality for derived resource-specific clients. + /// + public partial class ClientSet + { + private readonly Kubernetes _kubernetes; + + public ClientSet(Kubernetes kubernetes) + { + _kubernetes = kubernetes; + } + } +} diff --git a/src/KubernetesClient/ClientSets/ResourceClient.cs b/src/KubernetesClient/ClientSets/ResourceClient.cs new file mode 100644 index 000000000..bbf1c43e8 --- /dev/null +++ b/src/KubernetesClient/ClientSets/ResourceClient.cs @@ -0,0 +1,16 @@ +namespace k8s.ClientSets +{ + /// + /// Represents a set of Kubernetes clients for interacting with the Kubernetes API. + /// This class provides access to various client implementations for managing Kubernetes resources. + /// + public abstract class ResourceClient + { + protected Kubernetes Client { get; } + + public ResourceClient(Kubernetes kubernetes) + { + Client = kubernetes; + } + } +} diff --git a/src/KubernetesClient/IItems.cs b/src/KubernetesClient/IItems.cs deleted file mode 100644 index 4f23d9388..000000000 --- a/src/KubernetesClient/IItems.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace k8s -{ - /// - /// Kubernetes object that exposes list of objects - /// - /// type of the objects - public interface IItems - { - /// - /// Gets or sets list of objects. More info: - /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md - /// - IList Items { get; set; } - } - - public static class ItemsExt - { - public static IEnumerator GetEnumerator(this IItems items) - { - if (items is null) - { - throw new ArgumentNullException(nameof(items)); - } - - return items.Items.GetEnumerator(); - } - } -} diff --git a/src/KubernetesClient/IKubernetes.cs b/src/KubernetesClient/IKubernetes.cs index c3f871d64..5fa42e955 100644 --- a/src/KubernetesClient/IKubernetes.cs +++ b/src/KubernetesClient/IKubernetes.cs @@ -1,6 +1,6 @@ namespace k8s; -public partial interface IKubernetes : IBasicKubernetes, IDisposable +public partial interface IKubernetes : IDisposable { /// /// The base URI of the service. diff --git a/src/KubernetesClient/IMetadata.cs b/src/KubernetesClient/IMetadata.cs deleted file mode 100644 index edf540184..000000000 --- a/src/KubernetesClient/IMetadata.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace k8s -{ - /// - /// Kubernetes object that exposes metadata - /// - /// Type of metadata exposed. Usually this will be either - /// for lists or for objects - public interface IMetadata - { - /// - /// Gets or sets standard object's metadata. More info: - /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata - /// - T Metadata { get; set; } - } -} diff --git a/src/KubernetesClient/ISpec.cs b/src/KubernetesClient/ISpec.cs deleted file mode 100644 index d286b7cca..000000000 --- a/src/KubernetesClient/ISpec.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace k8s -{ - /// - /// Represents a Kubernetes object that has a spec - /// - /// type of Kubernetes object - public interface ISpec - { - /// - /// Gets or sets specification of the desired behavior of the entity. More - /// info: - /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - /// - T Spec { get; set; } - } -} diff --git a/src/KubernetesClient/IStreamDemuxer.cs b/src/KubernetesClient/IStreamDemuxer.cs index 2097dcca7..ce46d40f8 100644 --- a/src/KubernetesClient/IStreamDemuxer.cs +++ b/src/KubernetesClient/IStreamDemuxer.cs @@ -3,13 +3,13 @@ namespace k8s /// /// /// The interface allows you to interact with processes running in a container in a Kubernetes pod. You can start an exec or attach command - /// by calling - /// or . These methods - /// will return you a connection. + /// by calling + /// or . These methods + /// will return you a connection. /// /// - /// Kubernetes 'multiplexes' multiple channels over this connection, such as standard input, standard output and standard error. The - /// allows you to extract individual s from this class. You can then use these streams to send/receive data from that process. + /// Kubernetes 'multiplexes' multiple channels over this connection, such as standard input, standard output and standard error. The + /// allows you to extract individual s from this . You can then use these streams to send/receive data from that process. /// /// public interface IStreamDemuxer : IDisposable diff --git a/src/KubernetesClient/IValidate.cs b/src/KubernetesClient/IValidate.cs deleted file mode 100644 index c81f553f2..000000000 --- a/src/KubernetesClient/IValidate.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace k8s -{ - /// - /// Object that allows self validation - /// - public interface IValidate - { - /// - /// Validate the object. - /// - void Validate(); - } -} diff --git a/src/KubernetesClient/Kubernetes.ConfigInit.cs b/src/KubernetesClient/Kubernetes.ConfigInit.cs index da36c9fcf..e87e4e96a 100644 --- a/src/KubernetesClient/Kubernetes.ConfigInit.cs +++ b/src/KubernetesClient/Kubernetes.ConfigInit.cs @@ -213,11 +213,13 @@ public static bool CertificateValidationCallBack( { chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; - // Added our trusted certificates to the chain - // - chain.ChainPolicy.ExtraStore.AddRange(caCerts); - - chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; +#if NET5_0_OR_GREATER + // Use custom trust store only, ignore system root CA + chain.ChainPolicy.CustomTrustStore.AddRange(caCerts); + chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; +#else + throw new NotSupportedException("Custom trust store requires .NET 5.0 or later. Current platform does not support this feature."); +#endif var isValid = chain.Build((X509Certificate2)certificate); var isTrusted = false; diff --git a/src/KubernetesClient/Kubernetes.WebSocket.cs b/src/KubernetesClient/Kubernetes.WebSocket.cs index a3a5bc908..aeca29708 100644 --- a/src/KubernetesClient/Kubernetes.WebSocket.cs +++ b/src/KubernetesClient/Kubernetes.WebSocket.cs @@ -18,11 +18,11 @@ public partial class Kubernetes /// public Task WebSocketNamespacedPodExecAsync(string name, string @namespace = "default", string command = null, string container = null, bool stderr = true, bool stdin = true, bool stdout = true, - bool tty = true, string webSocketSubProtol = null, Dictionary> customHeaders = null, + bool tty = true, string webSocketSubProtocol = null, Dictionary> customHeaders = null, CancellationToken cancellationToken = default) { return WebSocketNamespacedPodExecAsync(name, @namespace, new string[] { command }, container, stderr, stdin, - stdout, tty, webSocketSubProtol, customHeaders, cancellationToken); + stdout, tty, webSocketSubProtocol, customHeaders, cancellationToken); } /// @@ -30,7 +30,7 @@ public virtual async Task MuxedStreamNamespacedPodExecAsync( string name, string @namespace = "default", IEnumerable command = null, string container = null, bool stderr = true, bool stdin = true, bool stdout = true, bool tty = true, - string webSocketSubProtol = WebSocketProtocol.V4BinaryWebsocketProtocol, + string webSocketSubProtocol = WebSocketProtocol.V4BinaryWebsocketProtocol, Dictionary> customHeaders = null, CancellationToken cancellationToken = default) { @@ -45,7 +45,7 @@ public virtual async Task MuxedStreamNamespacedPodExecAsync( public virtual Task WebSocketNamespacedPodExecAsync(string name, string @namespace = "default", IEnumerable command = null, string container = null, bool stderr = true, bool stdin = true, bool stdout = true, bool tty = true, - string webSocketSubProtol = WebSocketProtocol.V4BinaryWebsocketProtocol, + string webSocketSubProtocol = WebSocketProtocol.V4BinaryWebsocketProtocol, Dictionary> customHeaders = null, CancellationToken cancellationToken = default) { @@ -114,7 +114,7 @@ public virtual Task WebSocketNamespacedPodExecAsync(string name, stri uriBuilder.Query = query.ToString(1, query.Length - 1); // UriBuilder.Query doesn't like leading '?' chars, so trim it - return StreamConnectAsync(uriBuilder.Uri, webSocketSubProtol, customHeaders, + return StreamConnectAsync(uriBuilder.Uri, webSocketSubProtocol, customHeaders, cancellationToken); } @@ -173,7 +173,7 @@ public Task WebSocketNamespacedPodPortForwardAsync(string name, strin /// public Task WebSocketNamespacedPodAttachAsync(string name, string @namespace, string container = default, bool stderr = true, bool stdin = false, bool stdout = true, - bool tty = false, string webSocketSubProtol = null, Dictionary> customHeaders = null, + bool tty = false, string webSocketSubProtocol = null, Dictionary> customHeaders = null, CancellationToken cancellationToken = default) { if (name == null) @@ -208,7 +208,7 @@ public Task WebSocketNamespacedPodAttachAsync(string name, string @na uriBuilder.Query = query.ToString(1, query.Length - 1); // UriBuilder.Query doesn't like leading '?' chars, so trim it - return StreamConnectAsync(uriBuilder.Uri, webSocketSubProtol, customHeaders, + return StreamConnectAsync(uriBuilder.Uri, webSocketSubProtocol, customHeaders, cancellationToken); } diff --git a/src/KubernetesClient/KubernetesClient.csproj b/src/KubernetesClient/KubernetesClient.csproj index 910492b2e..dba319136 100644 --- a/src/KubernetesClient/KubernetesClient.csproj +++ b/src/KubernetesClient/KubernetesClient.csproj @@ -1,15 +1,12 @@ - net6.0;net8.0 + net8.0;net9.0 k8s true - - - diff --git a/src/KubernetesClient/KubernetesClientConfiguration.ConfigFile.cs b/src/KubernetesClient/KubernetesClientConfiguration.ConfigFile.cs index ed5112296..f25c55bbb 100644 --- a/src/KubernetesClient/KubernetesClientConfiguration.ConfigFile.cs +++ b/src/KubernetesClient/KubernetesClientConfiguration.ConfigFile.cs @@ -307,17 +307,27 @@ private void SetClusterDetails(K8SConfiguration k8SConfig, Context activeContext { if (!string.IsNullOrEmpty(clusterDetails.ClusterEndpoint.CertificateAuthorityData)) { + var data = clusterDetails.ClusterEndpoint.CertificateAuthorityData; +#if NET9_0_OR_GREATER + SslCaCerts = new X509Certificate2Collection(X509CertificateLoader.LoadCertificate(Convert.FromBase64String(data))); +#else + string nullPassword = null; // This null password is to change the constructor to fix this KB: // https://support.microsoft.com/en-us/topic/kb5025823-change-in-how-net-applications-import-x-509-certificates-bf81c936-af2b-446e-9f7a-016f4713b46b - string nullPassword = null; - var data = clusterDetails.ClusterEndpoint.CertificateAuthorityData; SslCaCerts = new X509Certificate2Collection(new X509Certificate2(Convert.FromBase64String(data), nullPassword)); +#endif } else if (!string.IsNullOrEmpty(clusterDetails.ClusterEndpoint.CertificateAuthority)) { +#if NET9_0_OR_GREATER + SslCaCerts = new X509Certificate2Collection(X509CertificateLoader.LoadCertificateFromFile(GetFullPath( + k8SConfig, + clusterDetails.ClusterEndpoint.CertificateAuthority))); +#else SslCaCerts = new X509Certificate2Collection(new X509Certificate2(GetFullPath( k8SConfig, clusterDetails.ClusterEndpoint.CertificateAuthority))); +#endif } } } diff --git a/src/KubernetesClient/KubernetesJson.cs b/src/KubernetesClient/KubernetesJson.cs index d0d4e9d13..69ecdf43e 100644 --- a/src/KubernetesClient/KubernetesJson.cs +++ b/src/KubernetesClient/KubernetesJson.cs @@ -1,14 +1,19 @@ using System.Globalization; +using System.Text.Json.Nodes; using System.Text.RegularExpressions; using System.Xml; +#if NET8_0_OR_GREATER +using System.Text.Json.Serialization.Metadata; +#endif + namespace k8s { public static class KubernetesJson { - private static readonly JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions(); + internal static readonly JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions(); - private sealed class Iso8601TimeSpanConverter : JsonConverter + public sealed class Iso8601TimeSpanConverter : JsonConverter { public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { @@ -23,11 +28,11 @@ public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializer } } - private sealed class KubernetesDateTimeOffsetConverter : JsonConverter + public sealed class KubernetesDateTimeOffsetConverter : JsonConverter { - private const string RFC3339MicroFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.ffffffK"; - private const string RFC3339NanoFormat = "yyyy-MM-dd'T'HH':'mm':'ss.fffffffK"; - private const string RFC3339Format = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK"; + private const string RFC3339MicroFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.ffffffZ"; + private const string RFC3339NanoFormat = "yyyy-MM-dd'T'HH':'mm':'ss.fffffffZ"; + private const string RFC3339Format = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"; public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { @@ -49,13 +54,22 @@ public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConver throw new FormatException($"Unable to parse {originalstr} as RFC3339 RFC3339Micro or RFC3339Nano"); } + public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) { - writer.WriteStringValue(value.ToString(RFC3339MicroFormat)); + // Output as RFC3339Micro + var date = value.ToUniversalTime(); + + var basePart = date.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture); + var frac = date.ToString(".ffffff", CultureInfo.InvariantCulture) + .TrimEnd('0') + .TrimEnd('.'); + + writer.WriteStringValue(basePart + frac + "Z"); } } - private sealed class KubernetesDateTimeConverter : JsonConverter + public sealed class KubernetesDateTimeConverter : JsonConverter { private static readonly JsonConverter UtcConverter = new KubernetesDateTimeOffsetConverter(); public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) @@ -71,13 +85,22 @@ public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializer static KubernetesJson() { +#if K8S_AOT + // Uses Source Generated IJsonTypeInfoResolver + JsonSerializerOptions.TypeInfoResolver = SourceGenerationContext.Default; +#else +#if NET8_0_OR_GREATER + // Uses Source Generated IJsonTypeInfoResolver when available and falls back to reflection + JsonSerializerOptions.TypeInfoResolver = JsonTypeInfoResolver.Combine(SourceGenerationContext.Default, new DefaultJsonTypeInfoResolver()); +#endif + JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); +#endif JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; JsonSerializerOptions.Converters.Add(new Iso8601TimeSpanConverter()); JsonSerializerOptions.Converters.Add(new KubernetesDateTimeConverter()); JsonSerializerOptions.Converters.Add(new KubernetesDateTimeOffsetConverter()); JsonSerializerOptions.Converters.Add(new V1Status.V1StatusObjectViewConverter()); - JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); } /// @@ -98,17 +121,92 @@ public static void AddJsonOptions(Action configure) public static TValue Deserialize(string json, JsonSerializerOptions jsonSerializerOptions = null) { +#if NET8_0_OR_GREATER + var info = (JsonTypeInfo)(jsonSerializerOptions ?? JsonSerializerOptions).GetTypeInfo(typeof(TValue)); + return JsonSerializer.Deserialize(json, info); +#else return JsonSerializer.Deserialize(json, jsonSerializerOptions ?? JsonSerializerOptions); +#endif } public static TValue Deserialize(Stream json, JsonSerializerOptions jsonSerializerOptions = null) { +#if NET8_0_OR_GREATER + var info = (JsonTypeInfo)(jsonSerializerOptions ?? JsonSerializerOptions).GetTypeInfo(typeof(TValue)); + return JsonSerializer.Deserialize(json, info); +#else + return JsonSerializer.Deserialize(json, jsonSerializerOptions ?? JsonSerializerOptions); +#endif + } + + public static TValue Deserialize(JsonDocument json, JsonSerializerOptions jsonSerializerOptions = null) + { +#if NET8_0_OR_GREATER + var info = (JsonTypeInfo)(jsonSerializerOptions ?? JsonSerializerOptions).GetTypeInfo(typeof(TValue)); + return JsonSerializer.Deserialize(json, info); +#else + return JsonSerializer.Deserialize(json, jsonSerializerOptions ?? JsonSerializerOptions); +#endif + } + + public static TValue Deserialize(JsonElement json, JsonSerializerOptions jsonSerializerOptions = null) + { +#if NET8_0_OR_GREATER + var info = (JsonTypeInfo)(jsonSerializerOptions ?? JsonSerializerOptions).GetTypeInfo(typeof(TValue)); + return JsonSerializer.Deserialize(json, info); +#else + return JsonSerializer.Deserialize(json, jsonSerializerOptions ?? JsonSerializerOptions); +#endif + } + + public static TValue Deserialize(JsonNode json, JsonSerializerOptions jsonSerializerOptions = null) + { +#if NET8_0_OR_GREATER + var info = (JsonTypeInfo)(jsonSerializerOptions ?? JsonSerializerOptions).GetTypeInfo(typeof(TValue)); + return JsonSerializer.Deserialize(json, info); +#else return JsonSerializer.Deserialize(json, jsonSerializerOptions ?? JsonSerializerOptions); +#endif } public static string Serialize(object value, JsonSerializerOptions jsonSerializerOptions = null) { +#if NET8_0_OR_GREATER + var info = (jsonSerializerOptions ?? JsonSerializerOptions).GetTypeInfo(value.GetType()); + return JsonSerializer.Serialize(value, info); +#else + return JsonSerializer.Serialize(value, jsonSerializerOptions ?? JsonSerializerOptions); +#endif + } + + public static string Serialize(JsonDocument value, JsonSerializerOptions jsonSerializerOptions = null) + { +#if NET8_0_OR_GREATER + var info = (jsonSerializerOptions ?? JsonSerializerOptions).GetTypeInfo(value.GetType()); + return JsonSerializer.Serialize(value, info); +#else + return JsonSerializer.Serialize(value, jsonSerializerOptions ?? JsonSerializerOptions); +#endif + } + + public static string Serialize(JsonElement value, JsonSerializerOptions jsonSerializerOptions = null) + { +#if NET8_0_OR_GREATER + var info = (jsonSerializerOptions ?? JsonSerializerOptions).GetTypeInfo(value.GetType()); + return JsonSerializer.Serialize(value, info); +#else + return JsonSerializer.Serialize(value, jsonSerializerOptions ?? JsonSerializerOptions); +#endif + } + + public static string Serialize(JsonNode value, JsonSerializerOptions jsonSerializerOptions = null) + { +#if NET8_0_OR_GREATER + var info = (jsonSerializerOptions ?? JsonSerializerOptions).GetTypeInfo(value.GetType()); + return JsonSerializer.Serialize(value, info); +#else return JsonSerializer.Serialize(value, jsonSerializerOptions ?? JsonSerializerOptions); +#endif } } } diff --git a/src/KubernetesClient/KubernetesYaml.cs b/src/KubernetesClient/KubernetesYaml.cs index 7f677a3f2..ef5384c72 100644 --- a/src/KubernetesClient/KubernetesYaml.cs +++ b/src/KubernetesClient/KubernetesYaml.cs @@ -21,6 +21,8 @@ public static class KubernetesYaml .WithTypeConverter(new IntOrStringYamlConverter()) .WithTypeConverter(new ByteArrayStringYamlConverter()) .WithTypeConverter(new ResourceQuantityYamlConverter()) + .WithTypeConverter(new KubernetesDateTimeYamlConverter()) + .WithTypeConverter(new KubernetesDateTimeOffsetYamlConverter()) .WithAttemptingUnquotedStringTypeDeserialization() .WithOverridesFromJsonPropertyAttributes(); @@ -41,6 +43,8 @@ public static class KubernetesYaml .WithTypeConverter(new IntOrStringYamlConverter()) .WithTypeConverter(new ByteArrayStringYamlConverter()) .WithTypeConverter(new ResourceQuantityYamlConverter()) + .WithTypeConverter(new KubernetesDateTimeYamlConverter()) + .WithTypeConverter(new KubernetesDateTimeOffsetYamlConverter()) .WithEventEmitter(e => new StringQuotingEmitter(e)) .WithEventEmitter(e => new FloatEmitter(e)) .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull) @@ -78,7 +82,7 @@ public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeseria return null; } - return Encoding.UTF8.GetBytes(scalar.Value); + return Convert.FromBase64String(scalar.Value); } finally { @@ -91,8 +95,15 @@ public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeseria public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer) { + if (value == null) + { + emitter.Emit(new Scalar(string.Empty)); + return; + } + var obj = (byte[])value; - emitter?.Emit(new Scalar(Encoding.UTF8.GetString(obj))); + var encoded = Convert.ToBase64String(obj); + emitter.Emit(new Scalar(encoded)); } } diff --git a/src/KubernetesClient/LeaderElection/LeaderElector.cs b/src/KubernetesClient/LeaderElection/LeaderElector.cs index eb96b48a2..e7d86f9af 100644 --- a/src/KubernetesClient/LeaderElection/LeaderElector.cs +++ b/src/KubernetesClient/LeaderElection/LeaderElector.cs @@ -163,10 +163,9 @@ private async Task TryAcquireOrRenew(CancellationToken cancellationToken) { if (e.Response.StatusCode != HttpStatusCode.NotFound) { + OnError?.Invoke(e); return false; } - - OnError?.Invoke(e); } if (oldLeaderElectionRecord?.AcquireTime == null || diff --git a/src/KubernetesClient/LeaderElection/ResourceLock/MetaObjectLock.cs b/src/KubernetesClient/LeaderElection/ResourceLock/MetaObjectLock.cs index 4d97842d8..e2540482f 100644 --- a/src/KubernetesClient/LeaderElection/ResourceLock/MetaObjectLock.cs +++ b/src/KubernetesClient/LeaderElection/ResourceLock/MetaObjectLock.cs @@ -9,6 +9,11 @@ public abstract class MetaObjectLock : ILock private readonly string identity; private T metaObjCache; + /// + /// OnHttpError is called when there is a http operation error. + /// + public event Action OnHttpError; + protected MetaObjectLock(IKubernetes client, string @namespace, string name, string identity) { this.client = client ?? throw new ArgumentNullException(nameof(client)); @@ -47,8 +52,9 @@ public async Task CreateAsync(LeaderElectionRecord record, CancellationTok Interlocked.Exchange(ref metaObjCache, createdObj); return true; } - catch (HttpOperationException) + catch (HttpOperationException e) { + OnHttpError?.Invoke(e); // ignore } @@ -79,8 +85,9 @@ public async Task UpdateAsync(LeaderElectionRecord record, CancellationTok Interlocked.Exchange(ref metaObjCache, replacedObj); return true; } - catch (HttpOperationException) + catch (HttpOperationException e) { + OnHttpError?.Invoke(e); // ignore } diff --git a/src/KubernetesClient/Models/IItems.cs b/src/KubernetesClient/Models/IItems.cs new file mode 100644 index 000000000..b82c4c3de --- /dev/null +++ b/src/KubernetesClient/Models/IItems.cs @@ -0,0 +1,27 @@ +namespace k8s.Models; + +/// +/// Kubernetes object that exposes list of objects +/// +/// type of the objects +public interface IItems +{ + /// + /// Gets or sets list of objects. More info: + /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md + /// + IList Items { get; set; } +} + +public static class ItemsExt +{ + public static IEnumerator GetEnumerator(this IItems items) + { + if (items is null) + { + throw new ArgumentNullException(nameof(items)); + } + + return items.Items.GetEnumerator(); + } +} diff --git a/src/KubernetesClient/Models/IMetadata.cs b/src/KubernetesClient/Models/IMetadata.cs new file mode 100644 index 000000000..4fa7f3292 --- /dev/null +++ b/src/KubernetesClient/Models/IMetadata.cs @@ -0,0 +1,15 @@ +namespace k8s.Models; + +/// +/// Kubernetes object that exposes metadata +/// +/// Type of metadata exposed. Usually this will be either +/// for lists or for objects +public interface IMetadata +{ + /// + /// Gets or sets standard object's metadata. More info: + /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + /// + T Metadata { get; set; } +} diff --git a/src/KubernetesClient/Models/ISpec.cs b/src/KubernetesClient/Models/ISpec.cs new file mode 100644 index 000000000..d05d62fab --- /dev/null +++ b/src/KubernetesClient/Models/ISpec.cs @@ -0,0 +1,15 @@ +namespace k8s.Models; + +/// +/// Represents a Kubernetes object that has a spec +/// +/// type of Kubernetes object +public interface ISpec +{ + /// + /// Gets or sets specification of the desired behavior of the entity. More + /// info: + /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + /// + T Spec { get; set; } +} diff --git a/src/KubernetesClient/IStatus.cs b/src/KubernetesClient/Models/IStatus.cs similarity index 96% rename from src/KubernetesClient/IStatus.cs rename to src/KubernetesClient/Models/IStatus.cs index e60f59fec..75d796666 100644 --- a/src/KubernetesClient/IStatus.cs +++ b/src/KubernetesClient/Models/IStatus.cs @@ -1,4 +1,4 @@ -namespace k8s +namespace k8s.Models { /// /// Kubernetes object that exposes status diff --git a/src/KubernetesClient/Models/IntOrString.cs b/src/KubernetesClient/Models/IntOrString.cs new file mode 100644 index 000000000..65e9cd486 --- /dev/null +++ b/src/KubernetesClient/Models/IntOrString.cs @@ -0,0 +1,38 @@ +namespace k8s.Models +{ + [JsonConverter(typeof(IntOrStringJsonConverter))] + public class IntOrString + { + public string Value { get; private init; } + + public static implicit operator IntOrString(int v) + { + return Convert.ToString(v); + } + + public static implicit operator IntOrString(long v) + { + return Convert.ToString(v); + } + + public static implicit operator string(IntOrString v) + { + return v?.Value; + } + + public static implicit operator IntOrString(string v) + { + return new IntOrString { Value = v }; + } + + public override string ToString() + { + return Value; + } + + public int ToInt() + { + return int.Parse(Value); + } + } +} diff --git a/src/KubernetesClient/Models/IntOrStringJsonConverter.cs b/src/KubernetesClient/Models/IntOrStringJsonConverter.cs index 9b665a30c..c7cbe273a 100644 --- a/src/KubernetesClient/Models/IntOrStringJsonConverter.cs +++ b/src/KubernetesClient/Models/IntOrStringJsonConverter.cs @@ -1,8 +1,8 @@ namespace k8s.Models { - internal sealed class IntOrStringJsonConverter : JsonConverter + internal sealed class IntOrStringJsonConverter : JsonConverter { - public override IntstrIntOrString Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override IntOrString Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { switch (reader.TokenType) { @@ -17,14 +17,14 @@ public override IntstrIntOrString Read(ref Utf8JsonReader reader, Type typeToCon throw new NotSupportedException(); } - public override void Write(Utf8JsonWriter writer, IntstrIntOrString value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, IntOrString value, JsonSerializerOptions options) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } - var s = value?.Value; + var s = value.Value; if (long.TryParse(s, out var intv)) { diff --git a/src/KubernetesClient/Models/IntOrStringYamlConverter.cs b/src/KubernetesClient/Models/IntOrStringYamlConverter.cs index 49116bd6c..cfaa42205 100644 --- a/src/KubernetesClient/Models/IntOrStringYamlConverter.cs +++ b/src/KubernetesClient/Models/IntOrStringYamlConverter.cs @@ -7,7 +7,7 @@ public class IntOrStringYamlConverter : IYamlTypeConverter { public bool Accepts(Type type) { - return type == typeof(IntstrIntOrString); + return type == typeof(IntOrString); } public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) @@ -21,7 +21,7 @@ public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeseria return null; } - return new IntstrIntOrString(scalar?.Value); + return scalar?.Value; } finally { @@ -34,7 +34,7 @@ public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeseria public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer) { - var obj = (IntstrIntOrString)value; + var obj = (IntOrString)value; emitter?.Emit(new YamlDotNet.Core.Events.Scalar(obj?.Value)); } } diff --git a/src/KubernetesClient/Models/IntstrIntOrString.cs b/src/KubernetesClient/Models/IntstrIntOrString.cs deleted file mode 100644 index 6f378df9b..000000000 --- a/src/KubernetesClient/Models/IntstrIntOrString.cs +++ /dev/null @@ -1,56 +0,0 @@ -namespace k8s.Models -{ - [JsonConverter(typeof(IntOrStringJsonConverter))] - public partial class IntstrIntOrString - { - public static implicit operator IntstrIntOrString(int v) - { - return new IntstrIntOrString(Convert.ToString(v)); - } - - public static implicit operator IntstrIntOrString(long v) - { - return new IntstrIntOrString(Convert.ToString(v)); - } - - public static implicit operator string(IntstrIntOrString v) - { - return v?.Value; - } - - public static implicit operator IntstrIntOrString(string v) - { - return new IntstrIntOrString(v); - } - - protected bool Equals(IntstrIntOrString other) - { - return string.Equals(Value, other?.Value); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) - { - return false; - } - - if (ReferenceEquals(this, obj)) - { - return true; - } - - if (obj.GetType() != GetType()) - { - return false; - } - - return Equals((IntstrIntOrString)obj); - } - - public override int GetHashCode() - { - return Value != null ? Value.GetHashCode() : 0; - } - } -} diff --git a/src/KubernetesClient/Models/KubernetesDateTimeOffsetYamlConverter.cs b/src/KubernetesClient/Models/KubernetesDateTimeOffsetYamlConverter.cs new file mode 100644 index 000000000..5eb4153eb --- /dev/null +++ b/src/KubernetesClient/Models/KubernetesDateTimeOffsetYamlConverter.cs @@ -0,0 +1,64 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Serialization; + +namespace k8s.Models; + +public sealed class KubernetesDateTimeOffsetYamlConverter : IYamlTypeConverter +{ + private const string RFC3339MicroFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.ffffff'Z'"; + private const string RFC3339NanoFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffff'Z'"; + private const string RFC3339Format = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"; + + public bool Accepts(Type type) => type == typeof(DateTimeOffset); + + public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) + { + if (parser?.Current is Scalar scalar) + { + try + { + if (string.IsNullOrEmpty(scalar.Value)) + { + return null; + } + + var str = scalar.Value; + + if (DateTimeOffset.TryParseExact(str, new[] { RFC3339Format, RFC3339MicroFormat }, CultureInfo.InvariantCulture, DateTimeStyles.None, out var result)) + { + return result; + } + + // try RFC3339NanoLenient by trimming 1-9 digits to 7 digits + var originalstr = str; + str = Regex.Replace(str, @"\.\d+", m => (m.Value + "000000000").Substring(0, 7 + 1)); // 7 digits + 1 for the dot + if (DateTimeOffset.TryParseExact(str, new[] { RFC3339NanoFormat }, CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) + { + return result; + } + } + finally + { + parser.MoveNext(); + } + } + + throw new InvalidOperationException($"Unable to parse '{parser.Current?.ToString()}' as RFC3339, RFC3339Micro, or RFC3339Nano"); + } + + public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer) + { + // Output as RFC3339Micro + var date = ((DateTimeOffset)value).ToUniversalTime(); + + var basePart = date.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture); + var frac = date.ToString(".ffffff", CultureInfo.InvariantCulture) + .TrimEnd('0') + .TrimEnd('.'); + + emitter.Emit(new Scalar(AnchorName.Empty, TagName.Empty, basePart + frac + "Z", ScalarStyle.DoubleQuoted, true, false)); + } +} diff --git a/src/KubernetesClient/Models/KubernetesDateTimeYamlConverter.cs b/src/KubernetesClient/Models/KubernetesDateTimeYamlConverter.cs new file mode 100644 index 000000000..d6095983d --- /dev/null +++ b/src/KubernetesClient/Models/KubernetesDateTimeYamlConverter.cs @@ -0,0 +1,23 @@ +using YamlDotNet.Core; +using YamlDotNet.Serialization; + +namespace k8s.Models; + +public sealed class KubernetesDateTimeYamlConverter : IYamlTypeConverter +{ + private static readonly KubernetesDateTimeOffsetYamlConverter OffsetConverter = new(); + + public bool Accepts(Type type) => type == typeof(DateTime); + + public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) + { + var dto = (DateTimeOffset)OffsetConverter.ReadYaml(parser, typeof(DateTimeOffset), rootDeserializer); + return dto.DateTime; + } + + public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer) + { + var date = new DateTimeOffset((DateTime)value); + OffsetConverter.WriteYaml(emitter, date, typeof(DateTimeOffset), serializer); + } +} diff --git a/src/KubernetesClient/Models/KubernetesList.cs b/src/KubernetesClient/Models/KubernetesList.cs index e8167fd75..069c410b2 100644 --- a/src/KubernetesClient/Models/KubernetesList.cs +++ b/src/KubernetesClient/Models/KubernetesList.cs @@ -40,27 +40,5 @@ public KubernetesList(IList items, string apiVersion = default, string kind = /// [JsonPropertyName("metadata")] public V1ListMeta Metadata { get; set; } - - /// - /// Validate the object. - /// - /// - /// Thrown if validation fails - /// - public void Validate() - { - if (Items == null) - { - throw new ArgumentNullException("Items"); - } - - if (Items != null) - { - foreach (var element in Items.OfType()) - { - element.Validate(); - } - } - } } } diff --git a/src/KubernetesClient/Models/ModelExtensions.cs b/src/KubernetesClient/Models/ModelExtensions.cs index 0f4903b93..f2c6f6045 100644 --- a/src/KubernetesClient/Models/ModelExtensions.cs +++ b/src/KubernetesClient/Models/ModelExtensions.cs @@ -208,7 +208,7 @@ public static int FindOwnerReference(this IMetadata obj, IKubernet /// reference could be found. /// /// the object meta - /// a to test owner reference + /// a to test owner reference /// the index of the that matches the given object, or -1 if no such /// reference could be found. public static int FindOwnerReference(this IMetadata obj, Predicate predicate) @@ -300,7 +300,7 @@ public static V1OwnerReference GetOwnerReference( /// Gets the that matches the given predicate, or null if no matching reference exists. /// the object meta - /// a to test owner reference + /// a to test owner reference /// the that matches the given object, or null if no matching reference exists. public static V1OwnerReference GetOwnerReference( this IMetadata obj, @@ -400,7 +400,7 @@ public static V1OwnerReference RemoveOwnerReference( /// any were removed. /// /// the object meta - /// a to test owner reference + /// a to test owner reference /// true if any were removed public static bool RemoveOwnerReferences( this IMetadata obj, diff --git a/src/KubernetesClient/Models/ModelVersionConverter.cs b/src/KubernetesClient/Models/ModelVersionConverter.cs deleted file mode 100644 index e48f39787..000000000 --- a/src/KubernetesClient/Models/ModelVersionConverter.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace k8s.Models; - -public static class ModelVersionConverter -{ - public interface IModelVersionConverter - { - TTo Convert(TFrom from); - } - - public static IModelVersionConverter Converter { get; set; } - - internal static TTo Convert(TFrom from) - { - if (Converter == null) - { - throw new InvalidOperationException("Converter is not set"); - } - - return Converter.Convert(from); - } -} diff --git a/src/KubernetesClient/Models/ResourceQuantity.cs b/src/KubernetesClient/Models/ResourceQuantity.cs index 2d1a4898d..eee89c678 100644 --- a/src/KubernetesClient/Models/ResourceQuantity.cs +++ b/src/KubernetesClient/Models/ResourceQuantity.cs @@ -54,7 +54,7 @@ namespace k8s.Models /// cause implementors to also use a fixed point implementation. /// [JsonConverter(typeof(ResourceQuantityJsonConverter))] - public partial class ResourceQuantity + public class ResourceQuantity { public enum SuffixFormat { @@ -97,39 +97,6 @@ public override string ToString() return CanonicalizeString(); } - protected bool Equals(ResourceQuantity other) - { - return _unitlessValue.Equals(other?._unitlessValue); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) - { - return false; - } - - if (ReferenceEquals(this, obj)) - { - return true; - } - - if (obj.GetType() != GetType()) - { - return false; - } - - return Equals((ResourceQuantity)obj); - } - - public override int GetHashCode() - { - unchecked - { - return ((int)Format * 397) ^ _unitlessValue.GetHashCode(); - } - } - // // CanonicalizeString = go version CanonicalizeBytes // CanonicalizeBytes returns the canonical form of q and its suffix (see comment on Quantity). @@ -157,10 +124,9 @@ public string CanonicalizeString(SuffixFormat suffixFormat) return Suffixer.AppendMaxSuffix(_unitlessValue, suffixFormat); } - // ctor - partial void CustomInit() + public ResourceQuantity(string v) { - if (Value == null) + if (v == null) { // No value has been defined, initialize to 0. _unitlessValue = new Fraction(0); @@ -168,7 +134,7 @@ partial void CustomInit() return; } - var value = Value.Trim(); + var value = v.Trim(); var si = value.IndexOfAny(SuffixChars); if (si == -1) @@ -188,6 +154,11 @@ partial void CustomInit() } } + public static implicit operator ResourceQuantity(string v) + { + return new ResourceQuantity(v); + } + private static bool HasMantissa(Fraction value) { if (value.IsZero) @@ -200,7 +171,7 @@ private static bool HasMantissa(Fraction value) public static implicit operator decimal(ResourceQuantity v) { - return v?.ToDecimal() ?? 0; + return v.ToDecimal(); } public static implicit operator ResourceQuantity(decimal v) @@ -208,6 +179,46 @@ public static implicit operator ResourceQuantity(decimal v) return new ResourceQuantity(v, 0, SuffixFormat.DecimalExponent); } + public bool Equals(ResourceQuantity other) + { + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + + return _unitlessValue.Equals(other._unitlessValue); + } + + public override bool Equals(object obj) + { + return Equals(obj as ResourceQuantity); + } + + public override int GetHashCode() + { + return _unitlessValue.GetHashCode(); + } + + public static bool operator ==(ResourceQuantity left, ResourceQuantity right) + { + if (left is null) + { + return right is null; + } + + return left.Equals(right); + } + + public static bool operator !=(ResourceQuantity left, ResourceQuantity right) + { + return !(left == right); + } + private sealed class Suffixer { private static readonly IReadOnlyDictionary BinSuffixes = diff --git a/src/KubernetesClient/Models/ResourceQuantityJsonConverter.cs b/src/KubernetesClient/Models/ResourceQuantityJsonConverter.cs index 613208679..a99eb334b 100644 --- a/src/KubernetesClient/Models/ResourceQuantityJsonConverter.cs +++ b/src/KubernetesClient/Models/ResourceQuantityJsonConverter.cs @@ -8,16 +8,16 @@ public override ResourceQuantity Read(ref Utf8JsonReader reader, Type typeToConv switch (reader.TokenType) { case JsonTokenType.Null: - return new ResourceQuantity(null); + return null; case JsonTokenType.Number: if (reader.TryGetDouble(out var val)) { - return new ResourceQuantity(Convert.ToString(val)); + return Convert.ToString(val); } return reader.GetDecimal(); default: - return new ResourceQuantity(reader.GetString()); + return reader.GetString(); } } @@ -28,7 +28,7 @@ public override void Write(Utf8JsonWriter writer, ResourceQuantity value, JsonSe throw new ArgumentNullException(nameof(writer)); } - writer.WriteStringValue(value?.ToString()); + writer.WriteStringValue(value.ToString()); } } } diff --git a/src/KubernetesClient/Models/ResourceQuantityYamlConverter.cs b/src/KubernetesClient/Models/ResourceQuantityYamlConverter.cs index ce0ec8e54..1006a3cd7 100644 --- a/src/KubernetesClient/Models/ResourceQuantityYamlConverter.cs +++ b/src/KubernetesClient/Models/ResourceQuantityYamlConverter.cs @@ -21,7 +21,7 @@ public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeseria return null; } - return new ResourceQuantity(scalar?.Value); + return scalar?.Value; } finally { diff --git a/src/KubernetesClient/Models/V1Patch.cs b/src/KubernetesClient/Models/V1Patch.cs index 4f8f44c50..5838e4b05 100644 --- a/src/KubernetesClient/Models/V1Patch.cs +++ b/src/KubernetesClient/Models/V1Patch.cs @@ -1,7 +1,7 @@ namespace k8s.Models { [JsonConverter(typeof(V1PatchJsonConverter))] - public partial class V1Patch + public record V1Patch { public enum PatchType { @@ -31,26 +31,21 @@ public enum PatchType ApplyPatch, } + [JsonPropertyName("content")] + [JsonInclude] + public object Content { get; private set; } + public PatchType Type { get; private set; } public V1Patch(object body, PatchType type) { - Content = body; - Type = type; - CustomInit(); - } - - partial void CustomInit() - { - if (Content == null) + if (type == PatchType.Unknown) { - throw new ArgumentNullException(nameof(Content), "object must be set"); + throw new ArgumentException("patch type must be set", nameof(type)); } - if (Type == PatchType.Unknown) - { - throw new ArgumentException("patch type must be set", nameof(Type)); - } + Content = body ?? throw new ArgumentNullException(nameof(body), "object must be set"); + Type = type; } } } diff --git a/src/KubernetesClient/Models/V1PodTemplateSpec.cs b/src/KubernetesClient/Models/V1PodTemplateSpec.cs index 0462b5373..4efa3cdbb 100644 --- a/src/KubernetesClient/Models/V1PodTemplateSpec.cs +++ b/src/KubernetesClient/Models/V1PodTemplateSpec.cs @@ -4,7 +4,7 @@ namespace k8s.Models /// Partial implementation of the IMetadata interface /// to open this class up to ModelExtensions methods /// - public partial class V1PodTemplateSpec : IMetadata + public partial record V1PodTemplateSpec : IMetadata { } } diff --git a/src/KubernetesClient/Models/V1Status.ObjectView.cs b/src/KubernetesClient/Models/V1Status.ObjectView.cs index 6f5a1ae85..710657847 100644 --- a/src/KubernetesClient/Models/V1Status.ObjectView.cs +++ b/src/KubernetesClient/Models/V1Status.ObjectView.cs @@ -1,23 +1,28 @@ namespace k8s.Models { - public partial class V1Status + public partial record V1Status { - internal sealed class V1StatusObjectViewConverter : JsonConverter + public sealed class V1StatusObjectViewConverter : JsonConverter { public override V1Status Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var obj = JsonElement.ParseValue(ref reader); + using var doc = JsonDocument.ParseValue(ref reader); + var ele = doc.RootElement.Clone(); try { - return obj.Deserialize(); +#if NET8_0_OR_GREATER + return JsonSerializer.Deserialize(ele, StatusSourceGenerationContext.Default.V1Status); +#else + return ele.Deserialize(); +#endif } catch (JsonException) { // should be an object } - return new V1Status { _original = obj, HasObject = true }; + return new V1Status { _original = ele, HasObject = true }; } public override void Write(Utf8JsonWriter writer, V1Status value, JsonSerializerOptions options) @@ -32,7 +37,11 @@ public override void Write(Utf8JsonWriter writer, V1Status value, JsonSerializer public T ObjectView() { +#if NET8_0_OR_GREATER + return KubernetesJson.Deserialize(_original); +#else return _original.Deserialize(); +#endif } } } diff --git a/src/KubernetesClient/Models/V1Status.cs b/src/KubernetesClient/Models/V1Status.cs index 87e4be055..d69116d2e 100644 --- a/src/KubernetesClient/Models/V1Status.cs +++ b/src/KubernetesClient/Models/V1Status.cs @@ -2,7 +2,7 @@ namespace k8s.Models { - public partial class V1Status + public partial record V1Status { /// Converts a object into a short description of the status. /// string description of the status diff --git a/src/KubernetesClient/SourceGenerationContext.cs b/src/KubernetesClient/SourceGenerationContext.cs new file mode 100644 index 000000000..22cc9fa00 --- /dev/null +++ b/src/KubernetesClient/SourceGenerationContext.cs @@ -0,0 +1,28 @@ +using static k8s.KubernetesJson; +using static k8s.Models.V1Status; + +namespace k8s; + +[JsonSourceGenerationOptions( + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + UseStringEnumConverter = true, + Converters = new[] { typeof(Iso8601TimeSpanConverter), typeof(KubernetesDateTimeConverter), typeof(KubernetesDateTimeOffsetConverter), typeof(V1StatusObjectViewConverter) }) + ] +public partial class SourceGenerationContext : JsonSerializerContext +{ +} + +/// +/// Used by V1Status in order to avoid the recursive loop as SourceGenerationContext contains V1StatusObjectViewConverter +/// +[JsonSerializable(typeof(V1Status))] +[JsonSourceGenerationOptions( + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + UseStringEnumConverter = true, + Converters = new[] { typeof(Iso8601TimeSpanConverter), typeof(KubernetesDateTimeConverter), typeof(KubernetesDateTimeOffsetConverter) }) + ] +public partial class StatusSourceGenerationContext : JsonSerializerContext +{ +} diff --git a/src/KubernetesClient/StreamDemuxer.cs b/src/KubernetesClient/StreamDemuxer.cs index 3cebd172e..30263b9eb 100644 --- a/src/KubernetesClient/StreamDemuxer.cs +++ b/src/KubernetesClient/StreamDemuxer.cs @@ -7,13 +7,13 @@ namespace k8s /// /// /// The allows you to interact with processes running in a container in a Kubernetes pod. You can start an exec or attach command - /// by calling - /// or . These methods - /// will return you a connection. + /// by calling + /// or . These methods + /// will return you a connection. /// /// - /// Kubernetes 'multiplexes' multiple channels over this connection, such as standard input, standard output and standard error. The - /// allows you to extract individual s from this class. You can then use these streams to send/receive data from that process. + /// Kubernetes 'multiplexes' multiple channels over this connection, such as standard input, standard output and standard error. The + /// allows you to extract individual s from this . You can then use these streams to send/receive data from that process. /// /// public class StreamDemuxer : IStreamDemuxer diff --git a/src/KubernetesClient/WatcherExt.cs b/src/KubernetesClient/WatcherExt.cs index 7b2fe9308..28863341f 100644 --- a/src/KubernetesClient/WatcherExt.cs +++ b/src/KubernetesClient/WatcherExt.cs @@ -11,11 +11,12 @@ public static class WatcherExt /// type of the HttpOperationResponse object /// the api response /// a callback when any event raised from api server - /// a callbak when any exception was caught during watching + /// a callback when any exception was caught during watching /// /// The action to invoke when the server closes the connection. /// /// a watch object + [Obsolete("This method will be deprecated in future versions. Please use the Watch method instead.")] public static Watcher Watch( this Task> responseTask, Action onEvent, @@ -47,11 +48,12 @@ private static Func> MakeStreamReaderCreator(Tasktype of the HttpOperationResponse object /// the api response /// a callback when any event raised from api server - /// a callbak when any exception was caught during watching + /// a callback when any exception was caught during watching /// /// The action to invoke when the server closes the connection. /// /// a watch object + [Obsolete("This method will be deprecated in future versions. Please use the Watch method instead.")] public static Watcher Watch( this HttpOperationResponse response, Action onEvent, @@ -68,9 +70,10 @@ public static Watcher Watch( /// type of the event object /// type of the HttpOperationResponse object /// the api response - /// a callbak when any exception was caught during watching + /// a callback when any exception was caught during watching /// cancellation token /// IAsyncEnumerable of watch events + [Obsolete("This method will be deprecated in future versions. Please use the WatchAsync method instead.")] public static IAsyncEnumerable<(WatchEventType, T)> WatchAsync( this Task> responseTask, Action onError = null, diff --git a/src/LibKubernetesGenerator/ApiGenerator.cs b/src/LibKubernetesGenerator/ApiGenerator.cs index 63fd9667e..37f135db5 100644 --- a/src/LibKubernetesGenerator/ApiGenerator.cs +++ b/src/LibKubernetesGenerator/ApiGenerator.cs @@ -71,7 +71,7 @@ public void Generate(OpenApiDocument swagger, IncrementalGeneratorPostInitializa sc = scriptObjectFactory.CreateScriptObject(); sc.SetValue("groups", groups, true); - context.RenderToContext($"IBasicKubernetes.cs.template", sc, $"IBasicKubernetes.g.cs"); + context.RenderToContext($"IKubernetes.cs.template", sc, $"IKubernetes.g.cs"); context.RenderToContext($"AbstractKubernetes.cs.template", sc, $"AbstractKubernetes.g.cs"); } } diff --git a/src/LibKubernetesGenerator/ClassNameHelper.cs b/src/LibKubernetesGenerator/ClassNameHelper.cs index a307a160f..a3b012f29 100644 --- a/src/LibKubernetesGenerator/ClassNameHelper.cs +++ b/src/LibKubernetesGenerator/ClassNameHelper.cs @@ -78,6 +78,12 @@ public string GetClassNameForSchemaDefinition(JsonSchema definition) } + if (definition.Format == "int-or-string") + { + return "IntOrString"; + } + + return schemaToNameMapCooked[definition]; } } diff --git a/src/LibKubernetesGenerator/ClientSetGenerator.cs b/src/LibKubernetesGenerator/ClientSetGenerator.cs new file mode 100644 index 000000000..a0b392d8b --- /dev/null +++ b/src/LibKubernetesGenerator/ClientSetGenerator.cs @@ -0,0 +1,103 @@ +using CaseExtensions; +using Microsoft.CodeAnalysis; +using NSwag; +using System.Collections.Generic; +using System.Linq; + +namespace LibKubernetesGenerator +{ + internal class ClientSetGenerator + { + private readonly ScriptObjectFactory _scriptObjectFactory; + + public ClientSetGenerator(ScriptObjectFactory scriptObjectFactory) + { + _scriptObjectFactory = scriptObjectFactory; + } + + public void Generate(OpenApiDocument swagger, IncrementalGeneratorPostInitializationContext context) + { + var data = swagger.Operations + .Where(o => o.Method != OpenApiOperationMethod.Options) + .Select(o => + { + var ps = o.Operation.ActualParameters.OrderBy(p => !p.IsRequired).ToArray(); + + o.Operation.Parameters.Clear(); + + var name = new HashSet(); + + var i = 1; + foreach (var p in ps) + { + if (name.Contains(p.Name)) + { + p.Name += i++; + } + + o.Operation.Parameters.Add(p); + name.Add(p.Name); + } + + return o; + }) + .Select(o => + { + o.Path = o.Path.TrimStart('/'); + o.Method = char.ToUpper(o.Method[0]) + o.Method.Substring(1); + return o; + }) + .ToArray(); + + var sc = _scriptObjectFactory.CreateScriptObject(); + + var groups = new List(); + var apiGroups = new Dictionary(); + + foreach (var grouped in data.Where(d => HasKubernetesAction(d.Operation?.ExtensionData)) + .GroupBy(d => d.Operation.Tags.First())) + { + var clients = new List(); + var name = grouped.Key.ToPascalCase(); + groups.Add(name); + var apis = grouped.Select(x => + { + var groupVersionKindElements = x.Operation?.ExtensionData?["x-kubernetes-group-version-kind"]; + var groupVersionKind = (Dictionary)groupVersionKindElements; + + return new { Kind = groupVersionKind?["kind"] as string, Api = x }; + }); + + foreach (var item in apis.GroupBy(x => x.Kind)) + { + var kind = item.Key; + apiGroups[kind] = item.Select(x => x.Api).ToArray(); + clients.Add(kind); + } + + sc.SetValue("clients", clients, true); + sc.SetValue("name", name, true); + context.RenderToContext("GroupClient.cs.template", sc, $"{name}GroupClient.g.cs"); + } + + foreach (var apiGroup in apiGroups) + { + var name = apiGroup.Key; + var apis = apiGroup.Value.ToArray(); + var group = apis.Select(x => x.Operation.Tags[0]).First(); + sc.SetValue("apis", apis, true); + sc.SetValue("name", name, true); + sc.SetValue("group", group.ToPascalCase(), true); + context.RenderToContext("Client.cs.template", sc, $"{name}Client.g.cs"); + } + + sc = _scriptObjectFactory.CreateScriptObject(); + sc.SetValue("groups", groups, true); + + context.RenderToContext("ClientSet.cs.template", sc, $"ClientSet.g.cs"); + } + + private bool HasKubernetesAction(IDictionary extensionData) => + extensionData?.ContainsKey("x-kubernetes-action") ?? false; + } +} diff --git a/src/LibKubernetesGenerator/GeneralNameHelper.cs b/src/LibKubernetesGenerator/GeneralNameHelper.cs index c9b5cf5af..2d4f646f7 100644 --- a/src/LibKubernetesGenerator/GeneralNameHelper.cs +++ b/src/LibKubernetesGenerator/GeneralNameHelper.cs @@ -21,7 +21,8 @@ public GeneralNameHelper(ClassNameHelper classNameHelper) public void RegisterHelper(ScriptObject scriptObject) { scriptObject.Import(nameof(GetInterfaceName), new Func(GetInterfaceName)); - scriptObject.Import(nameof(GetMethodName), new Func(GetMethodName)); + scriptObject.Import(nameof(GetOperationId), new Func(GetOperationId)); + scriptObject.Import(nameof(GetActionName), new Func(GetActionName)); scriptObject.Import(nameof(GetDotNetName), new Func(GetDotNetName)); scriptObject.Import(nameof(GetDotNetNameOpenApiParameter), new Func(GetDotNetNameOpenApiParameter)); } @@ -56,8 +57,6 @@ private string GetInterfaceName(JsonSchema definition) } } - interfaces.Add("IValidate"); - return string.Join(", ", interfaces); } @@ -67,7 +66,7 @@ public string GetDotNetNameOpenApiParameter(OpenApiParameter parameter, string i if (init == "true" && !parameter.IsRequired) { - name += " = null"; + name += " = default"; } return name; @@ -138,7 +137,7 @@ public string GetDotNetName(string jsonName, string style = "parameter") return jsonName.ToCamelCase(); } - public static string GetMethodName(OpenApiOperation watchOperation, string suffix) + public static string GetOperationId(OpenApiOperation watchOperation, string suffix) { var tag = watchOperation.Tags[0]; tag = tag.Replace("_", string.Empty); @@ -162,5 +161,28 @@ public static string GetMethodName(OpenApiOperation watchOperation, string suffi return methodName; } + + public static string GetActionName(OpenApiOperation apiOperation, string resource, string suffix) + { + var operationId = apiOperation.OperationId.ToPascalCase(); + var replacements = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "Replace", "Update" }, + { "Read", "Get" }, + }; + + foreach (var replacement in replacements) + { + operationId = Regex.Replace(operationId, replacement.Key, replacement.Value, RegexOptions.IgnoreCase); + } + + var resources = new[] { resource, "ForAllNamespaces", "Namespaced" }; + var pattern = string.Join("|", Array.ConvertAll(resources, Regex.Escape)); + var actionName = pattern.Length > 0 + ? Regex.Replace(operationId, pattern, string.Empty, RegexOptions.IgnoreCase) + : operationId; + + return $"{actionName}{suffix}"; + } } } diff --git a/src/LibKubernetesGenerator/GeneratorExecutionContextExt.cs b/src/LibKubernetesGenerator/GeneratorExecutionContextExt.cs index de5975cc9..6c3653721 100644 --- a/src/LibKubernetesGenerator/GeneratorExecutionContextExt.cs +++ b/src/LibKubernetesGenerator/GeneratorExecutionContextExt.cs @@ -1,5 +1,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; +using Microsoft.CodeAnalysis.CSharp; using Scriban; using Scriban.Runtime; using System.Text; @@ -19,7 +20,10 @@ public static void RenderToContext(this IncrementalGeneratorPostInitializationCo { var template = Template.Parse(EmbedResource.GetResource(templatefile)); var generated = template.Render(tc); - context.AddSource(generatedfile, SourceText.From(generated, Encoding.UTF8)); + + var syntaxTree = CSharpSyntaxTree.ParseText(generated); + var normalized = syntaxTree.GetRoot().NormalizeWhitespace().ToFullString(); + context.AddSource(generatedfile, SourceText.From(normalized, Encoding.UTF8)); } } } diff --git a/src/LibKubernetesGenerator/KubernetesClientSourceGenerator.cs b/src/LibKubernetesGenerator/KubernetesClientSourceGenerator.cs index 8dd368e03..fd2713260 100644 --- a/src/LibKubernetesGenerator/KubernetesClientSourceGenerator.cs +++ b/src/LibKubernetesGenerator/KubernetesClientSourceGenerator.cs @@ -1,12 +1,6 @@ using Autofac; using Microsoft.CodeAnalysis; using NSwag; -#if GENERATE_AUTOMAPPER -using System.Collections.Generic; -using System; -using System.IO; -using System.Linq; -#endif namespace LibKubernetesGenerator { @@ -64,11 +58,10 @@ private static IContainer BuildContainer(OpenApiDocument swagger) builder.RegisterType() ; - builder.RegisterType(); + builder.RegisterType(); builder.RegisterType(); builder.RegisterType(); - builder.RegisterType(); - builder.RegisterType(); + builder.RegisterType(); builder.RegisterType(); return builder.Build(); @@ -84,39 +77,12 @@ public void Initialize(IncrementalGeneratorInitializationContext generatorContex container.Resolve().Generate(swagger, ctx); container.Resolve().Generate(swagger, ctx); - container.Resolve().Generate(swagger, ctx); - container.Resolve().Generate(swagger, ctx); + container.Resolve().Generate(swagger, ctx); container.Resolve().Generate(swagger, ctx); + container.Resolve().Generate(swagger, ctx); }); #endif -#if GENERATE_AUTOMAPPER - var automappersrc = generatorContext.CompilationProvider.Select((c, _) => c.SyntaxTrees.First(s => PathSuffixMath(s.FilePath, "AutoMapper/VersionConverter.cs"))); - generatorContext.RegisterSourceOutput(automappersrc, (ctx, srctree) => - { - var (swagger, container) = BuildContainer(); - container.Resolve().Generate(swagger, ctx, srctree); - }); -#endif - } - -#if GENERATE_AUTOMAPPER - private IEnumerable PathSplit(string path) - { - var p = path; - - while (!string.IsNullOrEmpty(p)) - { - yield return Path.GetFileName(p); - p = Path.GetDirectoryName(p); - } } - - private bool PathSuffixMath(string path, string suffix) - { - var s = PathSplit(suffix).ToList(); - return PathSplit(path).Take(s.Count).SequenceEqual(s); - } -#endif } } diff --git a/src/LibKubernetesGenerator/LibKubernetesGenerator.target b/src/LibKubernetesGenerator/LibKubernetesGenerator.target index ee9aeb083..80a9cd252 100644 --- a/src/LibKubernetesGenerator/LibKubernetesGenerator.target +++ b/src/LibKubernetesGenerator/LibKubernetesGenerator.target @@ -12,10 +12,12 @@ - + + + @@ -30,8 +32,10 @@ + + @@ -48,8 +52,10 @@ + + diff --git a/src/LibKubernetesGenerator/ModelExtGenerator.cs b/src/LibKubernetesGenerator/ModelExtGenerator.cs deleted file mode 100644 index bbadcb5c0..000000000 --- a/src/LibKubernetesGenerator/ModelExtGenerator.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Microsoft.CodeAnalysis; -using NSwag; -using System.Collections.Generic; -using System.Linq; - -namespace LibKubernetesGenerator -{ - internal class ModelExtGenerator - { - private readonly ClassNameHelper classNameHelper; - private readonly ScriptObjectFactory scriptObjectFactory; - - public ModelExtGenerator(ClassNameHelper classNameHelper, ScriptObjectFactory scriptObjectFactory) - { - this.classNameHelper = classNameHelper; - this.scriptObjectFactory = scriptObjectFactory; - } - - public void Generate(OpenApiDocument swagger, IncrementalGeneratorPostInitializationContext context) - { - // Generate the interface declarations - var skippedTypes = new HashSet { "V1WatchEvent" }; - - var definitions = swagger.Definitions.Values - .Where( - d => d.ExtensionData != null - && d.ExtensionData.ContainsKey("x-kubernetes-group-version-kind") - && !skippedTypes.Contains(classNameHelper.GetClassName(d))); - - var sc = scriptObjectFactory.CreateScriptObject(); - sc.SetValue("definitions", definitions, true); - - context.RenderToContext("ModelExtensions.cs.template", sc, "ModelExtensions.g.cs"); - } - } -} diff --git a/src/LibKubernetesGenerator/ModelGenerator.cs b/src/LibKubernetesGenerator/ModelGenerator.cs index 98b9576cd..df9f8d3ea 100644 --- a/src/LibKubernetesGenerator/ModelGenerator.cs +++ b/src/LibKubernetesGenerator/ModelGenerator.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using Microsoft.CodeAnalysis; using NSwag; @@ -18,15 +19,49 @@ public void Generate(OpenApiDocument swagger, IncrementalGeneratorPostInitializa { var sc = scriptObjectFactory.CreateScriptObject(); + var genSkippedTypes = new HashSet + { + "IntOrString", + "ResourceQuantity", + "V1Patch", + }; + + var extSkippedTypes = new HashSet + { + "V1WatchEvent", + }; + + var typeOverrides = new Dictionary + { + // not used at the moment + }; foreach (var kv in swagger.Definitions) { var def = kv.Value; var clz = classNameHelper.GetClassNameForSchemaDefinition(def); + if (genSkippedTypes.Contains(clz)) + { + continue; + } + + var hasExt = def.ExtensionData != null + && def.ExtensionData.ContainsKey("x-kubernetes-group-version-kind") + && !extSkippedTypes.Contains(clz); + + + var typ = "record"; + if (typeOverrides.TryGetValue(clz, out var to)) + { + typ = to; + } + sc.SetValue("clz", clz, true); sc.SetValue("def", def, true); sc.SetValue("properties", def.Properties.Values, true); + sc.SetValue("typ", typ, true); + sc.SetValue("hasExt", hasExt, true); context.RenderToContext("Model.cs.template", sc, $"Models_{clz}.g.cs"); } diff --git a/src/LibKubernetesGenerator/ParamHelper.cs b/src/LibKubernetesGenerator/ParamHelper.cs index 216c2f357..fcaf030d9 100644 --- a/src/LibKubernetesGenerator/ParamHelper.cs +++ b/src/LibKubernetesGenerator/ParamHelper.cs @@ -3,6 +3,7 @@ using Scriban.Runtime; using System; using System.Linq; +using System.Collections.Generic; namespace LibKubernetesGenerator { @@ -21,6 +22,8 @@ public void RegisterHelper(ScriptObject scriptObject) { scriptObject.Import(nameof(GetModelCtorParam), new Func(GetModelCtorParam)); scriptObject.Import(nameof(IfParamContains), IfParamContains); + scriptObject.Import(nameof(FilterParameters), FilterParameters); + scriptObject.Import(nameof(GetParameterValueForWatch), new Func(GetParameterValueForWatch)); } public static bool IfParamContains(OpenApiOperation operation, string name) @@ -39,6 +42,23 @@ public static bool IfParamContains(OpenApiOperation operation, string name) return found; } + public static IEnumerable FilterParameters(OpenApiOperation operation, string excludeParam) + { + return operation.Parameters.Where(p => p.Name != excludeParam); + } + + public string GetParameterValueForWatch(OpenApiParameter parameter, bool watch, string init = "false") + { + if (parameter.Name == "watch") + { + return watch ? "true" : "false"; + } + else + { + return generalNameHelper.GetDotNetNameOpenApiParameter(parameter, init); + } + } + public string GetModelCtorParam(JsonSchema schema) { return string.Join(", ", schema.Properties.Values @@ -57,4 +77,4 @@ public string GetModelCtorParam(JsonSchema schema) })); } } -} +} \ No newline at end of file diff --git a/src/LibKubernetesGenerator/PluralHelper.cs b/src/LibKubernetesGenerator/PluralHelper.cs index b2f697375..81091f88c 100644 --- a/src/LibKubernetesGenerator/PluralHelper.cs +++ b/src/LibKubernetesGenerator/PluralHelper.cs @@ -11,11 +11,12 @@ internal class PluralHelper : IScriptObjectHelper { private readonly Dictionary _classNameToPluralMap; private readonly ClassNameHelper classNameHelper; - private readonly HashSet opblackList = new HashSet() - { + private readonly HashSet opblackList = + [ "listClusterCustomObject", "listNamespacedCustomObject", - }; + "listCustomObjectForAllNamespaces", + ]; public PluralHelper(ClassNameHelper classNameHelper, OpenApiDocument swagger) { diff --git a/src/LibKubernetesGenerator/SourceGenerationContextGenerator.cs b/src/LibKubernetesGenerator/SourceGenerationContextGenerator.cs new file mode 100644 index 000000000..c73c020a1 --- /dev/null +++ b/src/LibKubernetesGenerator/SourceGenerationContextGenerator.cs @@ -0,0 +1,24 @@ +using Microsoft.CodeAnalysis; +using NSwag; + +namespace LibKubernetesGenerator +{ + internal class SourceGenerationContextGenerator + { + private readonly ScriptObjectFactory scriptObjectFactory; + + public SourceGenerationContextGenerator(ScriptObjectFactory scriptObjectFactory) + { + this.scriptObjectFactory = scriptObjectFactory; + } + + public void Generate(OpenApiDocument swagger, IncrementalGeneratorPostInitializationContext context) + { + var definitions = swagger.Definitions.Values; + var sc = scriptObjectFactory.CreateScriptObject(); + sc.SetValue("definitions", definitions, true); + + context.RenderToContext("SourceGenerationContext.cs.template", sc, "SourceGenerationContext.g.cs"); + } + } +} diff --git a/src/LibKubernetesGenerator/TypeHelper.cs b/src/LibKubernetesGenerator/TypeHelper.cs index 057a363a2..db27dab97 100644 --- a/src/LibKubernetesGenerator/TypeHelper.cs +++ b/src/LibKubernetesGenerator/TypeHelper.cs @@ -122,7 +122,6 @@ private string GetDotNetType(JsonSchema schema, JsonSchemaProperty parent) return $"IDictionary"; } - if (schema?.Reference != null) { return classNameHelper.GetClassNameForSchemaDefinition(schema.Reference); @@ -245,6 +244,16 @@ string toType() } break; + case "T": + var itemType = TryGetItemTypeFromSchema(response); + if (itemType != null) + { + return itemType; + } + + break; + case "TList": + return t; } return t; @@ -283,5 +292,26 @@ public static bool IfType(JsonSchemaProperty property, string type) return false; } + + private string TryGetItemTypeFromSchema(OpenApiResponse response) + { + var listSchema = response?.Schema?.Reference; + if (listSchema?.Properties?.TryGetValue("items", out var itemsProperty) != true) + { + return null; + } + + if (itemsProperty.Reference != null) + { + return classNameHelper.GetClassNameForSchemaDefinition(itemsProperty.Reference); + } + + if (itemsProperty.Item?.Reference != null) + { + return classNameHelper.GetClassNameForSchemaDefinition(itemsProperty.Item.Reference); + } + + return null; + } } -} +} \ No newline at end of file diff --git a/src/LibKubernetesGenerator/VersionConverterAutoMapperGenerator.cs b/src/LibKubernetesGenerator/VersionConverterAutoMapperGenerator.cs deleted file mode 100644 index 9a2c95cbc..000000000 --- a/src/LibKubernetesGenerator/VersionConverterAutoMapperGenerator.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; -using NSwag; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; - -namespace LibKubernetesGenerator -{ - internal class VersionConverterAutoMapperGenerator - { - private readonly ClassNameHelper classNameHelper; - - public VersionConverterAutoMapperGenerator(ClassNameHelper classNameHelper) - { - this.classNameHelper = classNameHelper; - } - - public void Generate(OpenApiDocument swagger, SourceProductionContext context, SyntaxTree manualconverter) - { - var allGeneratedModelClassNames = new List(); - - foreach (var kv in swagger.Definitions) - { - var def = kv.Value; - var clz = classNameHelper.GetClassNameForSchemaDefinition(def); - allGeneratedModelClassNames.Add(clz); - } - - var manualMaps = new List<(string, string)>(); - - manualMaps = Regex.Matches(manualconverter.GetText().ToString(), @"\.CreateMap<(?.+?),\s?(?.+?)>") - .OfType() - .Select(x => (x.Groups["T1"].Value, x.Groups["T2"].Value)) - .ToList(); - - var versionRegex = @"(^V|v)[0-9]+((alpha|beta)[0-9]+)?"; - var typePairs = allGeneratedModelClassNames - .OrderBy(x => x) - .Select(x => new - { - Version = Regex.Match(x, versionRegex).Value?.ToLower(), - Kinda = Regex.Replace(x, versionRegex, string.Empty), - Type = x, - }) - .Where(x => !string.IsNullOrEmpty(x.Version)) - .GroupBy(x => x.Kinda) - .Where(x => x.Count() > 1) - .SelectMany(x => - x.SelectMany((value, index) => x.Skip(index + 1), (first, second) => new { first, second })) - .OrderBy(x => x.first.Kinda) - .ThenBy(x => x.first.Version) - .Select(x => (x.first.Type, x.second.Type)) - .ToList(); - - var versionConverterPairs = typePairs.Except(manualMaps).ToList(); - - var sbversion = new StringBuilder(@"// -using AutoMapper; -using k8s.Models; - -namespace k8s.ModelConverter.AutoMapper; - -internal static partial class VersionConverter - { - private static void AutoConfigurations(IMapperConfigurationExpression cfg) - { - -"); - - foreach (var (t0, t1) in versionConverterPairs) - { - sbversion.AppendLine($@"cfg.CreateMap<{t0}, {t1}>().ReverseMap();"); - } - - sbversion.AppendLine("}}"); - - context.AddSource($"VersionConverter.g.cs", SourceText.From(sbversion.ToString(), Encoding.UTF8)); - } - } -} diff --git a/src/LibKubernetesGenerator/VersionConverterStubGenerator.cs b/src/LibKubernetesGenerator/VersionConverterStubGenerator.cs deleted file mode 100644 index 58550006d..000000000 --- a/src/LibKubernetesGenerator/VersionConverterStubGenerator.cs +++ /dev/null @@ -1,70 +0,0 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; -using NSwag; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; - -namespace LibKubernetesGenerator -{ - internal class VersionConverterStubGenerator - { - private readonly ClassNameHelper classNameHelper; - - public VersionConverterStubGenerator(ClassNameHelper classNameHelper) - { - this.classNameHelper = classNameHelper; - } - - public void Generate(OpenApiDocument swagger, IncrementalGeneratorPostInitializationContext context) - { - var allGeneratedModelClassNames = new List(); - - foreach (var kv in swagger.Definitions) - { - var def = kv.Value; - var clz = classNameHelper.GetClassNameForSchemaDefinition(def); - allGeneratedModelClassNames.Add(clz); - } - - var versionRegex = @"(^V|v)[0-9]+((alpha|beta)[0-9]+)?"; - var typePairs = allGeneratedModelClassNames - .OrderBy(x => x) - .Select(x => new - { - Version = Regex.Match(x, versionRegex).Value?.ToLower(), - Kinda = Regex.Replace(x, versionRegex, string.Empty), - Type = x, - }) - .Where(x => !string.IsNullOrEmpty(x.Version)) - .GroupBy(x => x.Kinda) - .Where(x => x.Count() > 1) - .SelectMany(x => - x.SelectMany((value, index) => x.Skip(index + 1), (first, second) => new { first, second })) - .OrderBy(x => x.first.Kinda) - .ThenBy(x => x.first.Version) - .Select(x => (x.first.Type, x.second.Type)) - .ToList(); - - var sbmodel = new StringBuilder(@"// -namespace k8s.Models; -"); - - foreach (var (t0, t1) in typePairs) - { - sbmodel.AppendLine($@" - public partial class {t0} - {{ - public static explicit operator {t0}({t1} s) => ModelVersionConverter.Convert<{t1}, {t0}>(s); - }} - public partial class {t1} - {{ - public static explicit operator {t1}({t0} s) => ModelVersionConverter.Convert<{t0}, {t1}>(s); - }}"); - } - - context.AddSource($"ModelOperators.g.cs", SourceText.From(sbmodel.ToString(), Encoding.UTF8)); - } - } -} diff --git a/src/LibKubernetesGenerator/generators/LibKubernetesGenerator.Automapper/LibKubernetesGenerator.Automapper.csproj b/src/LibKubernetesGenerator/generators/LibKubernetesGenerator.Automapper/LibKubernetesGenerator.Automapper.csproj deleted file mode 100644 index 1cf7ecd42..000000000 --- a/src/LibKubernetesGenerator/generators/LibKubernetesGenerator.Automapper/LibKubernetesGenerator.Automapper.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - $(DefineConstants);GENERATE_AUTOMAPPER; - - - - - diff --git a/src/LibKubernetesGenerator/templates/Client.cs.template b/src/LibKubernetesGenerator/templates/Client.cs.template new file mode 100644 index 000000000..f9ce845e5 --- /dev/null +++ b/src/LibKubernetesGenerator/templates/Client.cs.template @@ -0,0 +1,165 @@ +// +// Code generated by https://github.com/kubernetes-client/csharp/tree/master/src/LibKubernetesGenerator +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// +using System.Net.Http; +using System.Net.Http.Headers; + +namespace k8s.ClientSets; + +/// +/// +public partial class {{name}}Client : ResourceClient +{ + public {{name}}Client(Kubernetes kubernetes) : base(kubernetes) + { + } + + {{for api in apis }} + {{~ $filteredParams = FilterParameters api.operation "watch" ~}} + /// + /// {{ToXmlDoc api.operation.description}} + /// + {{ for parameter in $filteredParams}} + /// + /// {{ToXmlDoc parameter.description}} + /// + {{end}} + /// + /// A which can be used to cancel the asynchronous operation. + /// + public async Task{{GetReturnType api.operation "<>"}} {{GetActionName api.operation name "Async"}}( + {{ for parameter in $filteredParams}} + {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "true"}}, + {{ end }} + CancellationToken cancellationToken = default(CancellationToken)) + { + {{if IfReturnType api.operation "stream"}} + var _result = await Client.{{group}}.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( + {{ for parameter in api.operation.parameters}} + {{GetParameterValueForWatch parameter false}}, + {{end}} + null, + cancellationToken); + _result.Request.Dispose(); + {{GetReturnType api.operation "_result.Body"}}; + {{end}} + {{if IfReturnType api.operation "obj"}} + using (var _result = await Client.{{group}}.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( + {{ for parameter in api.operation.parameters}} + {{GetParameterValueForWatch parameter false}}, + {{end}} + null, + cancellationToken).ConfigureAwait(false)) + { + {{GetReturnType api.operation "_result.Body"}}; + } + {{end}} + {{if IfReturnType api.operation "void"}} + using (var _result = await Client.{{group}}.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( + {{ for parameter in api.operation.parameters}} + {{GetParameterValueForWatch parameter false}}, + {{end}} + null, + cancellationToken).ConfigureAwait(false)) + { + } + {{end}} + } + + {{if IfReturnType api.operation "object"}} + /// + /// {{ToXmlDoc api.operation.description}} + /// + {{ for parameter in $filteredParams}} + /// + /// {{ToXmlDoc parameter.description}} + /// + {{end}} + /// + /// A which can be used to cancel the asynchronous operation. + /// + public async Task {{GetActionName api.operation name "Async"}}( + {{ for parameter in $filteredParams}} + {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "false"}}, + {{ end }} + CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await Client.{{group}}.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( + {{ for parameter in api.operation.parameters}} + {{GetParameterValueForWatch parameter false}}, + {{end}} + null, + cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + {{end}} + +#if !K8S_AOT + {{if IfParamContains api.operation "watch"}} + /// + /// Watch {{ToXmlDoc api.operation.description}} + /// + {{ for parameter in $filteredParams}} + /// + /// {{ToXmlDoc parameter.description}} + /// + {{ end }} + /// Callback when any event raised from api server + /// Callback when any exception was caught during watching + /// Callback when the server closes the connection + public Watcher<{{GetReturnType api.operation "T"}}> Watch{{GetActionName api.operation name ""}}( + {{ for parameter in $filteredParams}} + {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "true"}}, + {{ end }} + Action onEvent = null, + Action onError = null, + Action onClosed = null) + { + if (onEvent == null) throw new ArgumentNullException(nameof(onEvent)); + + var responseTask = Client.{{group}}.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( + {{ for parameter in api.operation.parameters}} + {{GetParameterValueForWatch parameter true}}, + {{ end }} + null, + CancellationToken.None); + + return responseTask.Watch<{{GetReturnType api.operation "T"}}, {{GetReturnType api.operation "TList"}}>( + onEvent, onError, onClosed); + } + + /// + /// Watch {{ToXmlDoc api.operation.description}} as async enumerable + /// + {{ for parameter in $filteredParams}} + /// + /// {{ToXmlDoc parameter.description}} + /// + {{ end }} + /// Callback when any exception was caught during watching + /// Cancellation token + public IAsyncEnumerable<(WatchEventType, {{GetReturnType api.operation "T"}})> Watch{{GetActionName api.operation name "Async"}}( + {{ for parameter in $filteredParams}} + {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "true"}}, + {{ end }} + Action onError = null, + CancellationToken cancellationToken = default) + { + var responseTask = Client.{{group}}.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( + {{ for parameter in api.operation.parameters}} + {{GetParameterValueForWatch parameter true}}, + {{ end }} + null, + cancellationToken); + + return responseTask.WatchAsync<{{GetReturnType api.operation "T"}}, {{GetReturnType api.operation "TList"}}>( + onError, cancellationToken); + } + {{end}} +#endif + {{end}} +} \ No newline at end of file diff --git a/src/LibKubernetesGenerator/templates/ClientSet.cs.template b/src/LibKubernetesGenerator/templates/ClientSet.cs.template new file mode 100644 index 000000000..c358b2b3c --- /dev/null +++ b/src/LibKubernetesGenerator/templates/ClientSet.cs.template @@ -0,0 +1,16 @@ +// +// Code generated by https://github.com/kubernetes-client/csharp/tree/master/src/LibKubernetesGenerator +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace k8s.ClientSets; + +/// +/// +public partial class ClientSet +{ + {{for group in groups}} + public {{group}}GroupClient {{group}} => new {{group}}GroupClient(_kubernetes); + {{end}} +} diff --git a/src/LibKubernetesGenerator/templates/GroupClient.cs.template b/src/LibKubernetesGenerator/templates/GroupClient.cs.template new file mode 100644 index 000000000..45f219e55 --- /dev/null +++ b/src/LibKubernetesGenerator/templates/GroupClient.cs.template @@ -0,0 +1,24 @@ +// +// Code generated by https://github.com/kubernetes-client/csharp/tree/master/src/LibKubernetesGenerator +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace k8s.ClientSets; + + +/// +/// +public partial class {{name}}GroupClient +{ + private readonly Kubernetes _kubernetes; + + {{for client in clients}} + public {{client}}Client {{client}} => new {{client}}Client(_kubernetes); + {{end}} + + public {{name}}GroupClient(Kubernetes kubernetes) + { + _kubernetes = kubernetes; + } +} diff --git a/src/LibKubernetesGenerator/templates/IBasicKubernetes.cs.template b/src/LibKubernetesGenerator/templates/IKubernetes.cs.template similarity index 86% rename from src/LibKubernetesGenerator/templates/IBasicKubernetes.cs.template rename to src/LibKubernetesGenerator/templates/IKubernetes.cs.template index 99a284fcf..68e92500d 100644 --- a/src/LibKubernetesGenerator/templates/IBasicKubernetes.cs.template +++ b/src/LibKubernetesGenerator/templates/IKubernetes.cs.template @@ -8,7 +8,7 @@ namespace k8s; /// /// -public partial interface IBasicKubernetes +public partial interface IKubernetes { {{for group in groups}} I{{group}}Operations {{group}} { get; } diff --git a/src/LibKubernetesGenerator/templates/IOperations.cs.template b/src/LibKubernetesGenerator/templates/IOperations.cs.template index c310acf9f..6904b8b91 100644 --- a/src/LibKubernetesGenerator/templates/IOperations.cs.template +++ b/src/LibKubernetesGenerator/templates/IOperations.cs.template @@ -25,7 +25,7 @@ public partial interface I{{name}}Operations /// /// A which can be used to cancel the asynchronous operation. /// - Task"}}> {{GetMethodName api.operation "WithHttpMessagesAsync"}}( + Task"}}> {{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{ for parameter in api.operation.parameters}} {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "true"}}, {{ end }} @@ -47,7 +47,7 @@ public partial interface I{{name}}Operations /// /// A which can be used to cancel the asynchronous operation. /// - Task> {{GetMethodName api.operation "WithHttpMessagesAsync"}}( + Task> {{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{ for parameter in api.operation.parameters}} {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "true"}}, {{ end }} diff --git a/src/LibKubernetesGenerator/templates/Model.cs.template b/src/LibKubernetesGenerator/templates/Model.cs.template index f074ae72c..721709f1e 100644 --- a/src/LibKubernetesGenerator/templates/Model.cs.template +++ b/src/LibKubernetesGenerator/templates/Model.cs.template @@ -4,94 +4,29 @@ // regenerated. // -namespace k8s.Models +namespace k8s.Models; + +/// +/// {{ToXmlDoc def.description}} +/// +{{ if hasExt }} +[KubernetesEntity(Group=KubeGroup, Kind=KubeKind, ApiVersion=KubeApiVersion, PluralName=KubePluralName)] +{{ end }} +public partial {{typ}} {{clz}} {{ if hasExt }} : {{ GetInterfaceName def }} {{ end }} { + {{ if hasExt}} + public const string KubeApiVersion = "{{ GetApiVersion def }}"; + public const string KubeKind = "{{ GetKind def }}"; + public const string KubeGroup = "{{ GetGroup def }}"; + public const string KubePluralName = "{{ GetPlural def }}"; + {{ end }} + + {{ for property in properties }} /// - /// {{ToXmlDoc def.description}} + /// {{ToXmlDoc property.description}} /// - public partial class {{clz}} - { - /// - /// Initializes a new instance of the {{GetClassName def}} class. - /// - public {{clz}}() - { - CustomInit(); - } - - /// - /// Initializes a new instance of the {{GetClassName def}} class. - /// - {{ for property in properties }} - {{ if property.IsRequired }} - /// - /// {{ToXmlDoc property.description}} - /// - {{ end }} - {{ end }} - - {{ for property in properties }} - {{ if !property.IsRequired }} - /// - /// {{ToXmlDoc property.description}} - /// - {{ end }} - {{ end }} - public {{clz}}({{GetModelCtorParam def}}) - { - {{ for property in properties }} - {{GetDotNetName property.name "field"}} = {{GetDotNetName property.name "fieldctor"}}; - {{ end }} - CustomInit(); - } - - /// - /// An initialization method that performs custom operations like setting defaults - /// - partial void CustomInit(); - - {{ for property in properties }} - /// - /// {{ToXmlDoc property.description}} - /// - [JsonPropertyName("{{property.name}}")] - public {{GetDotNetType property}} {{GetDotNetName property.name "field"}} { get; set; } - {{ end }} - - /// - /// Validate the object. - /// - /// - /// Thrown if validation fails - /// - public virtual void Validate() - { - {{ for property in properties }} - {{if IfType property "object" }} - {{ if property.IsRequired }} - if ({{GetDotNetName property.name "field"}} == null) - { - throw new ArgumentNullException("{{GetDotNetName property.name "field"}}"); - } - {{ end }} - {{ end }} - - {{ end }} - - {{ for property in properties }} - {{if IfType property "object" }} - {{GetDotNetName property.name "field"}}?.Validate(); - {{ end }} - - {{if IfType property "objectarray" }} - if ({{GetDotNetName property.name "field"}} != null){ - foreach(var obj in {{GetDotNetName property.name "field"}}) - { - obj.Validate(); - } - } - {{ end }} - {{ end }} - } - } + [JsonPropertyName("{{property.name}}")] + public {{ if property.IsRequired }} required {{ end }} {{GetDotNetType property}} {{GetDotNetName property.name "field"}} { get; set; } + {{ end }} } + diff --git a/src/LibKubernetesGenerator/templates/ModelExtensions.cs.template b/src/LibKubernetesGenerator/templates/ModelExtensions.cs.template deleted file mode 100644 index bad5507bc..000000000 --- a/src/LibKubernetesGenerator/templates/ModelExtensions.cs.template +++ /dev/null @@ -1,29 +0,0 @@ -// -// Code generated by https://github.com/kubernetes-client/csharp/tree/master/src/LibKubernetesGenerator -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -// -namespace k8s.Models -{ -{{ for definition in definitions }} - [KubernetesEntity(Group=KubeGroup, Kind=KubeKind, ApiVersion=KubeApiVersion, PluralName=KubePluralName)] - public partial class {{ GetClassName definition }} : {{ GetInterfaceName definition }} - { - public const string KubeApiVersion = "{{ GetApiVersion definition }}"; - public const string KubeKind = "{{ GetKind definition }}"; - public const string KubeGroup = "{{ GetGroup definition }}"; - public const string KubePluralName = "{{ GetPlural definition }}"; - } -{{ end }} -} - -#if NET8_0_OR_GREATER -namespace k8s -{ - {{ for definition in definitions }} - [JsonSerializable(typeof({{ GetClassName definition }}))] - {{ end }} - internal partial class SourceGenerationContext : JsonSerializerContext - { - } -} -#endif \ No newline at end of file diff --git a/src/LibKubernetesGenerator/templates/Operations.cs.template b/src/LibKubernetesGenerator/templates/Operations.cs.template index 876ed8a16..d98337ada 100644 --- a/src/LibKubernetesGenerator/templates/Operations.cs.template +++ b/src/LibKubernetesGenerator/templates/Operations.cs.template @@ -10,13 +10,13 @@ public partial class AbstractKubernetes : I{{name}}Operations { {{for api in apis }} {{if IfReturnType api.operation "void"}} - private async Task I{{name}}Operations_{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + private async Task I{{name}}Operations_{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{end}} {{if IfReturnType api.operation "obj"}} - private async Task> I{{name}}Operations_{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + private async Task> I{{name}}Operations_{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{end}} {{if IfReturnType api.operation "stream"}} - private async Task> I{{name}}Operations_{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + private async Task> I{{name}}Operations_{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{end}} {{ for parameter in api.operation.parameters}} {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "false"}}, @@ -90,7 +90,7 @@ public partial class AbstractKubernetes : I{{name}}Operations } /// - async Task"}}> I{{name}}Operations.{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + async Task"}}> I{{name}}Operations.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{ for parameter in api.operation.parameters}} {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "false"}}, {{end}} @@ -98,7 +98,7 @@ public partial class AbstractKubernetes : I{{name}}Operations CancellationToken cancellationToken) { {{if IfReturnType api.operation "void"}} - return await I{{name}}Operations_{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + return await I{{name}}Operations_{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{ for parameter in api.operation.parameters}} {{GetDotNetNameOpenApiParameter parameter "false"}}, {{end}} @@ -106,7 +106,7 @@ public partial class AbstractKubernetes : I{{name}}Operations cancellationToken).ConfigureAwait(false); {{end}} {{if IfReturnType api.operation "obj"}} - return await I{{name}}Operations_{{GetMethodName api.operation "WithHttpMessagesAsync"}}{{GetReturnType api.operation "<>"}}( + return await I{{name}}Operations_{{GetOperationId api.operation "WithHttpMessagesAsync"}}{{GetReturnType api.operation "<>"}}( {{ for parameter in api.operation.parameters}} {{GetDotNetNameOpenApiParameter parameter "false"}}, {{end}} @@ -114,7 +114,7 @@ public partial class AbstractKubernetes : I{{name}}Operations cancellationToken).ConfigureAwait(false); {{end}} {{if IfReturnType api.operation "stream"}} - return await I{{name}}Operations_{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + return await I{{name}}Operations_{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{ for parameter in api.operation.parameters}} {{GetDotNetNameOpenApiParameter parameter "false"}}, {{end}} @@ -125,14 +125,14 @@ public partial class AbstractKubernetes : I{{name}}Operations {{if IfReturnType api.operation "object"}} /// - async Task> I{{name}}Operations.{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + async Task> I{{name}}Operations.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{ for parameter in api.operation.parameters}} {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "false"}}, {{end}} IReadOnlyDictionary> customHeaders, CancellationToken cancellationToken) { - return await I{{name}}Operations_{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + return await I{{name}}Operations_{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{ for parameter in api.operation.parameters}} {{GetDotNetNameOpenApiParameter parameter "false"}}, {{end}} diff --git a/src/LibKubernetesGenerator/templates/OperationsExtensions.cs.template b/src/LibKubernetesGenerator/templates/OperationsExtensions.cs.template index 98c304ede..7544d235d 100644 --- a/src/LibKubernetesGenerator/templates/OperationsExtensions.cs.template +++ b/src/LibKubernetesGenerator/templates/OperationsExtensions.cs.template @@ -12,26 +12,27 @@ namespace k8s; public static partial class {{name}}OperationsExtensions { {{for api in apis }} + {{~ $filteredParams = FilterParameters api.operation "watch" ~}} /// /// {{ToXmlDoc api.operation.description}} /// /// /// The operations group for this extension method. /// - {{ for parameter in api.operation.parameters}} + {{ for parameter in $filteredParams}} /// - /// {{ToXmlDoc api.description}} + /// {{ToXmlDoc parameter.description}} /// {{ end }} - public static {{GetReturnType api.operation "void"}} {{GetMethodName api.operation ""}}( + public static {{GetReturnType api.operation "void"}} {{GetOperationId api.operation ""}}( this I{{name}}Operations operations -{{ for parameter in api.operation.parameters}} +{{ for parameter in $filteredParams}} ,{{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "true"}} {{end}} ) { - {{GetReturnType api.operation "return"}} operations.{{GetMethodName api.operation "Async"}}( -{{ for parameter in api.operation.parameters}} + {{GetReturnType api.operation "return"}} operations.{{GetOperationId api.operation "Async"}}( +{{ for parameter in $filteredParams}} {{GetDotNetNameOpenApiParameter parameter "false"}}, {{end}} CancellationToken.None @@ -45,20 +46,20 @@ public static partial class {{name}}OperationsExtensions /// /// The operations group for this extension method. /// - {{ for parameter in api.operation.parameters}} + {{ for parameter in $filteredParams}} /// /// {{ToXmlDoc parameter.description}} /// {{end}} - public static T {{GetMethodName api.operation ""}}( + public static T {{GetOperationId api.operation ""}}( this I{{name}}Operations operations -{{ for parameter in api.operation.parameters}} +{{ for parameter in $filteredParams}} ,{{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "true"}} {{end}} ) { - return operations.{{GetMethodName api.operation "Async"}}( -{{ for parameter in api.operation.parameters}} + return operations.{{GetOperationId api.operation "Async"}}( +{{ for parameter in $filteredParams}} {{GetDotNetNameOpenApiParameter parameter "false"}}, {{end}} CancellationToken.None @@ -72,7 +73,7 @@ public static partial class {{name}}OperationsExtensions /// /// The operations group for this extension method. /// - {{ for parameter in api.operation.parameters}} + {{ for parameter in $filteredParams}} /// /// {{ToXmlDoc parameter.description}} /// @@ -80,17 +81,17 @@ public static partial class {{name}}OperationsExtensions /// /// A which can be used to cancel the asynchronous operation. /// - public static async Task{{GetReturnType api.operation "<>"}} {{GetMethodName api.operation "Async"}}( + public static async Task{{GetReturnType api.operation "<>"}} {{GetOperationId api.operation "Async"}}( this I{{name}}Operations operations, -{{ for parameter in api.operation.parameters}} +{{ for parameter in $filteredParams}} {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "true"}}, {{ end }} CancellationToken cancellationToken = default(CancellationToken)) { {{if IfReturnType api.operation "stream"}} - var _result = await operations.{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + var _result = await operations.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{ for parameter in api.operation.parameters}} - {{GetDotNetNameOpenApiParameter parameter "false"}}, + {{GetParameterValueForWatch parameter false}}, {{end}} null, cancellationToken); @@ -98,9 +99,9 @@ public static partial class {{name}}OperationsExtensions {{GetReturnType api.operation "_result.Body"}}; {{end}} {{if IfReturnType api.operation "obj"}} - using (var _result = await operations.{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + using (var _result = await operations.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{ for parameter in api.operation.parameters}} - {{GetDotNetNameOpenApiParameter parameter "false"}}, + {{GetParameterValueForWatch parameter false}}, {{end}} null, cancellationToken).ConfigureAwait(false)) @@ -109,9 +110,9 @@ public static partial class {{name}}OperationsExtensions } {{end}} {{if IfReturnType api.operation "void"}} - using (var _result = await operations.{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + using (var _result = await operations.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{ for parameter in api.operation.parameters}} - {{GetDotNetNameOpenApiParameter parameter "false"}}, + {{GetParameterValueForWatch parameter false}}, {{end}} null, cancellationToken).ConfigureAwait(false)) @@ -127,7 +128,7 @@ public static partial class {{name}}OperationsExtensions /// /// The operations group for this extension method. /// - {{ for parameter in api.operation.parameters}} + {{ for parameter in $filteredParams}} /// /// {{ToXmlDoc parameter.description}} /// @@ -135,16 +136,16 @@ public static partial class {{name}}OperationsExtensions /// /// A which can be used to cancel the asynchronous operation. /// - public static async Task {{GetMethodName api.operation "Async"}}( + public static async Task {{GetOperationId api.operation "Async"}}( this I{{name}}Operations operations, -{{ for parameter in api.operation.parameters}} +{{ for parameter in $filteredParams}} {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "true"}}, {{ end }} CancellationToken cancellationToken = default(CancellationToken)) { - using (var _result = await operations.{{GetMethodName api.operation "WithHttpMessagesAsync"}}( + using (var _result = await operations.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( {{ for parameter in api.operation.parameters}} - {{GetDotNetNameOpenApiParameter parameter "false"}}, + {{GetParameterValueForWatch parameter false}}, {{end}} null, cancellationToken).ConfigureAwait(false)) @@ -154,5 +155,77 @@ public static partial class {{name}}OperationsExtensions } {{end}} - {{end}} +#if !K8S_AOT +{{if IfParamContains api.operation "watch"}} +{{~ $filteredParams = FilterParameters api.operation "watch" ~}} +/// +/// Watch {{ToXmlDoc api.operation.description}} +/// +/// +/// The operations group for this extension method. +/// +{{ for parameter in $filteredParams}} +/// +/// {{ToXmlDoc parameter.description}} +/// +{{ end }} +/// Callback when any event raised from api server +/// Callback when any exception was caught during watching +/// Callback when the server closes the connection +public static Watcher<{{GetReturnType api.operation "T"}}> Watch{{GetOperationId api.operation ""}}( + this I{{name}}Operations operations, +{{ for parameter in $filteredParams}} + {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "true"}}, +{{end}} + Action onEvent = null, + Action onError = null, + Action onClosed = null) +{ + if (onEvent == null) throw new ArgumentNullException(nameof(onEvent)); + + var responseTask = operations.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( +{{ for parameter in api.operation.parameters}} + {{GetParameterValueForWatch parameter true}}, +{{end}} + null, + CancellationToken.None); + + return responseTask.Watch<{{GetReturnType api.operation "T"}}, {{GetReturnType api.operation "TList"}}>( + onEvent, onError, onClosed); +} + +/// +/// Watch {{ToXmlDoc api.operation.description}} as async enumerable +/// +/// +/// The operations group for this extension method. +/// +{{ for parameter in $filteredParams}} +/// +/// {{ToXmlDoc parameter.description}} +/// +{{ end }} +/// Callback when any exception was caught during watching +/// Cancellation token +public static IAsyncEnumerable<(WatchEventType, {{GetReturnType api.operation "T"}})> Watch{{GetOperationId api.operation "Async"}}( + this I{{name}}Operations operations, +{{ for parameter in $filteredParams}} + {{GetDotNetTypeOpenApiParameter parameter}} {{GetDotNetNameOpenApiParameter parameter "true"}}, +{{end}} + Action onError = null, + CancellationToken cancellationToken = default) +{ + var responseTask = operations.{{GetOperationId api.operation "WithHttpMessagesAsync"}}( +{{ for parameter in api.operation.parameters}} + {{GetParameterValueForWatch parameter true}}, +{{end}} + null, + cancellationToken); + + return responseTask.WatchAsync<{{GetReturnType api.operation "T"}}, {{GetReturnType api.operation "TList"}}>( + onError, cancellationToken); } +{{end}} +#endif + {{end}} +} \ No newline at end of file diff --git a/src/LibKubernetesGenerator/templates/SourceGenerationContext.cs.template b/src/LibKubernetesGenerator/templates/SourceGenerationContext.cs.template new file mode 100644 index 000000000..0a5113981 --- /dev/null +++ b/src/LibKubernetesGenerator/templates/SourceGenerationContext.cs.template @@ -0,0 +1,15 @@ +// +// Code generated by https://github.com/kubernetes-client/csharp/tree/master/src/LibKubernetesGenerator +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// +#if NET8_0_OR_GREATER +namespace k8s +{ + {{ for definition in definitions }} + [JsonSerializable(typeof({{ GetClassName definition }}))] + {{ end }} + public partial class SourceGenerationContext : JsonSerializerContext + { + } +} +#endif diff --git a/src/nuget.proj b/src/nuget.proj index feec6cda8..1f4213256 100644 --- a/src/nuget.proj +++ b/src/nuget.proj @@ -3,6 +3,5 @@ - diff --git a/swagger.json b/swagger.json index a96f9a6e0..2cc381669 100644 --- a/swagger.json +++ b/swagger.json @@ -497,6 +497,9 @@ "description": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds" } }, + "required": [ + "items" + ], "type": "object", "x-kubernetes-group-version-kind": [ { @@ -522,7 +525,7 @@ "type": "string" }, "validationActions": { - "description": "validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced. If a validation evaluates to false it is always enforced according to these actions.\n\nFailures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according to these actions only if the FailurePolicy is set to Fail, otherwise the failures are ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.\n\nvalidationActions is declared as a set of action values. Order does not matter. validationActions may not contain duplicates of the same action.\n\nThe supported actions values are:\n\n\"Deny\" specifies that a validation failure results in a denied request.\n\n\"Warn\" specifies that a validation failure is reported to the request client in HTTP Warning headers, with a warning code of 299. Warnings can be sent both for allowed or denied admission responses.\n\n\"Audit\" specifies that a validation failure is included in the published audit event for the request. The audit event will contain a `validation.policy.admission.k8s.io/validation_failure` audit annotation with a value containing the details of the validation failures, formatted as a JSON list of objects, each with the following fields: - message: The validation failure message string - policy: The resource name of the ValidatingAdmissionPolicy - binding: The resource name of the ValidatingAdmissionPolicyBinding - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy - validationActions: The enforcement actions enacted for the validation failure Example audit annotation: `\"validation.policy.admission.k8s.io/validation_failure\": \"[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]\"`\n\nClients should expect to handle additional values by ignoring any values not recognized.\n\n\"Deny\" and \"Warn\" may not be used together since this combination needlessly duplicates the validation failure both in the API response body and the HTTP warning headers.\n\nRequired.", + "description": "validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced. If a validation evaluates to false it is always enforced according to these actions.\n\nFailures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according to these actions only if the FailurePolicy is set to Fail, otherwise the failures are ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.\n\nvalidationActions is declared as a set of action values. Order does not matter. validationActions may not contain duplicates of the same action.\n\nThe supported actions values are:\n\n\"Deny\" specifies that a validation failure results in a denied request.\n\n\"Warn\" specifies that a validation failure is reported to the request client in HTTP Warning headers, with a warning code of 299. Warnings can be sent both for allowed or denied admission responses.\n\n\"Audit\" specifies that a validation failure is included in the published audit event for the request. The audit event will contain a `validation.policy.admission.k8s.io/validation_failure` audit annotation with a value containing the details of the validation failures, formatted as a JSON list of objects, each with the following fields: - message: The validation failure message string - policy: The resource name of the ValidatingAdmissionPolicy - binding: The resource name of the ValidatingAdmissionPolicyBinding - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy - validationActions: The enforcement actions enacted for the validation failure Example audit annotation: `\"validation.policy.admission.k8s.io/validation_failure\": \"[{\\\"message\\\": \\\"Invalid value\\\", {\\\"policy\\\": \\\"policy.example.com\\\", {\\\"binding\\\": \\\"policybinding.example.com\\\", {\\\"expressionIndex\\\": \\\"1\\\", {\\\"validationActions\\\": [\\\"Audit\\\"]}]\"`\n\nClients should expect to handle additional values by ignoring any values not recognized.\n\n\"Deny\" and \"Warn\" may not be used together since this combination needlessly duplicates the validation failure both in the API response body and the HTTP warning headers.\n\nRequired.", "items": { "type": "string" }, @@ -555,6 +558,9 @@ "description": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds" } }, + "required": [ + "items" + ], "type": "object", "x-kubernetes-group-version-kind": [ { @@ -860,40 +866,24 @@ }, "type": "object" }, - "v1alpha1.AuditAnnotation": { - "description": "AuditAnnotation describes how to produce an audit annotation for an API request.", + "v1alpha1.ApplyConfiguration": { + "description": "ApplyConfiguration defines the desired configuration values of an object.", "properties": { - "key": { - "description": "key specifies the audit annotation key. The audit annotation keys of a ValidatingAdmissionPolicy must be unique. The key must be a qualified name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.\n\nThe key is combined with the resource name of the ValidatingAdmissionPolicy to construct an audit annotation key: \"{ValidatingAdmissionPolicy name}/{key}\".\n\nIf an admission webhook uses the same resource name as this ValidatingAdmissionPolicy and the same audit annotation key, the annotation key will be identical. In this case, the first annotation written with the key will be included in the audit event and all subsequent annotations with the same key will be discarded.\n\nRequired.", - "type": "string" - }, - "valueExpression": { - "description": "valueExpression represents the expression which is evaluated by CEL to produce an audit annotation value. The expression must evaluate to either a string or null value. If the expression evaluates to a string, the audit annotation is included with the string value. If the expression evaluates to null or empty string the audit annotation will be omitted. The valueExpression may be no longer than 5kb in length. If the result of the valueExpression is more than 10kb in length, it will be truncated to 10kb.\n\nIf multiple ValidatingAdmissionPolicyBinding resources match an API request, then the valueExpression will be evaluated for each binding. All unique values produced by the valueExpressions will be joined together in a comma-separated list.\n\nRequired.", + "expression": { + "description": "expression will be evaluated by CEL to create an apply configuration. ref: https://github.com/google/cel-spec\n\nApply configurations are declared in CEL using object initialization. For example, this CEL expression returns an apply configuration to set a single field:\n\n\tObject{\n\t spec: Object.spec{\n\t serviceAccountName: \"example\"\n\t }\n\t}\n\nApply configurations may not modify atomic structs, maps or arrays due to the risk of accidental deletion of values not included in the apply configuration.\n\nCEL expressions have access to the object types needed to create apply configurations:\n\n- 'Object' - CEL type of the resource object. - 'Object.' - CEL type of object field (such as 'Object.spec') - 'Object.....` - CEL type of nested field (such as 'Object.spec.containers')\n\nCEL expressions have access to the contents of the API request, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources. - 'variables' - Map of composited variables, from its name to its lazily evaluated value.\n For example, a variable named 'foo' can be accessed as 'variables.foo'.\n- 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Required.", "type": "string" } }, - "required": [ - "key", - "valueExpression" - ], "type": "object" }, - "v1alpha1.ExpressionWarning": { - "description": "ExpressionWarning is a warning information that targets a specific expression.", + "v1alpha1.JSONPatch": { + "description": "JSONPatch defines a JSON Patch.", "properties": { - "fieldRef": { - "description": "The path to the field that refers the expression. For example, the reference to the expression of the first item of validations is \"spec.validations[0].expression\"", - "type": "string" - }, - "warning": { - "description": "The content of type checking information in a human-readable form. Each line of the warning contains the type that the expression is checked against, followed by the type check error from the compiler.", + "expression": { + "description": "expression will be evaluated by CEL to create a [JSON patch](https://jsonpatch.com/). ref: https://github.com/google/cel-spec\n\nexpression must return an array of JSONPatch values.\n\nFor example, this CEL expression returns a JSON patch to conditionally modify a value:\n\n\t [\n\t JSONPatch{op: \"test\", path: \"/spec/example\", value: \"Red\"},\n\t JSONPatch{op: \"replace\", path: \"/spec/example\", value: \"Green\"}\n\t ]\n\nTo define an object for the patch value, use Object types. For example:\n\n\t [\n\t JSONPatch{\n\t op: \"add\",\n\t path: \"/spec/selector\",\n\t value: Object.spec.selector{matchLabels: {\"environment\": \"test\"}}\n\t }\n\t ]\n\nTo use strings containing '/' and '~' as JSONPatch path keys, use \"jsonpatch.escapeKey\". For example:\n\n\t [\n\t JSONPatch{\n\t op: \"add\",\n\t path: \"/metadata/labels/\" + jsonpatch.escapeKey(\"example.com/environment\"),\n\t value: \"test\"\n\t },\n\t ]\n\nCEL expressions have access to the types needed to create JSON patches and objects:\n\n- 'JSONPatch' - CEL type of JSON Patch operations. JSONPatch has the fields 'op', 'from', 'path' and 'value'.\n See [JSON patch](https://jsonpatch.com/) for more details. The 'value' field may be set to any of: string,\n integer, array, map or object. If set, the 'path' and 'from' fields must be set to a\n [JSON pointer](https://datatracker.ietf.org/doc/html/rfc6901/) string, where the 'jsonpatch.escapeKey()' CEL\n function may be used to escape path keys containing '/' and '~'.\n- 'Object' - CEL type of the resource object. - 'Object.' - CEL type of object field (such as 'Object.spec') - 'Object.....` - CEL type of nested field (such as 'Object.spec.containers')\n\nCEL expressions have access to the contents of the API request, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources. - 'variables' - Map of composited variables, from its name to its lazily evaluated value.\n For example, a variable named 'foo' can be accessed as 'variables.foo'.\n- 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nCEL expressions have access to [Kubernetes CEL function libraries](https://kubernetes.io/docs/reference/using-api/cel/#cel-options-language-features-and-libraries) as well as:\n\n- 'jsonpatch.escapeKey' - Performs JSONPatch key escaping. '~' and '/' are escaped as '~0' and `~1' respectively).\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Required.", "type": "string" } }, - "required": [ - "fieldRef", - "warning" - ], "type": "object" }, "v1alpha1.MatchCondition": { @@ -917,7 +907,7 @@ "description": "MatchResources decides whether to run the admission control policy on an object based on whether it meets the match criteria. The exclude rules take precedence over include rules (if a resource matches both, it is excluded)", "properties": { "excludeResourceRules": { - "description": "ExcludeResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy should not care about. The exclude rules take precedence over include rules (if a resource matches both, it is excluded)", + "description": "ExcludeResourceRules describes what operations on what resources/subresources the policy should not care about. The exclude rules take precedence over include rules (if a resource matches both, it is excluded)", "items": { "$ref": "#/definitions/v1alpha1.NamedRuleWithOperations" }, @@ -925,7 +915,7 @@ "x-kubernetes-list-type": "atomic" }, "matchPolicy": { - "description": "matchPolicy defines how the \"MatchResources\" list is used to match incoming requests. Allowed values are \"Exact\" or \"Equivalent\".\n\n- Exact: match a request only if it exactly matches a specified rule. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, but \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the ValidatingAdmissionPolicy.\n\n- Equivalent: match a request if modifies a resource listed in rules, even via another API group or version. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, and \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the ValidatingAdmissionPolicy.\n\nDefaults to \"Equivalent\"", + "description": "matchPolicy defines how the \"MatchResources\" list is used to match incoming requests. Allowed values are \"Exact\" or \"Equivalent\".\n\n- Exact: match a request only if it exactly matches a specified rule. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, but \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, the admission policy does not consider requests to apps/v1beta1 or extensions/v1beta1 API groups.\n\n- Equivalent: match a request if modifies a resource listed in rules, even via another API group or version. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, and \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, the admission policy **does** consider requests made to apps/v1beta1 or extensions/v1beta1 API groups. The API server translates the request to a matched resource API if necessary.\n\nDefaults to \"Equivalent\"", "type": "string" }, "namespaceSelector": { @@ -934,10 +924,10 @@ }, "objectSelector": { "$ref": "#/definitions/v1.LabelSelector", - "description": "ObjectSelector decides whether to run the validation based on if the object has matching labels. objectSelector is evaluated against both the oldObject and newObject that would be sent to the cel validation, and is considered to match if either object matches the selector. A null object (oldObject in the case of create, or newObject in the case of delete) or an object that cannot have labels (like a DeploymentRollback or a PodProxyOptions object) is not considered to match. Use the object selector only if the webhook is opt-in, because end users may skip the admission webhook by setting the labels. Default to the empty LabelSelector, which matches everything." + "description": "ObjectSelector decides whether to run the policy based on if the object has matching labels. objectSelector is evaluated against both the oldObject and newObject that would be sent to the policy's expression (CEL), and is considered to match if either object matches the selector. A null object (oldObject in the case of create, or newObject in the case of delete) or an object that cannot have labels (like a DeploymentRollback or a PodProxyOptions object) is not considered to match. Use the object selector only if the webhook is opt-in, because end users may skip the admission webhook by setting the labels. Default to the empty LabelSelector, which matches everything." }, "resourceRules": { - "description": "ResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy matches. The policy cares about an operation if it matches _any_ Rule.", + "description": "ResourceRules describes what operations on what resources/subresources the admission policy matches. The policy cares about an operation if it matches _any_ Rule.", "items": { "$ref": "#/definitions/v1alpha1.NamedRuleWithOperations" }, @@ -948,111 +938,8 @@ "type": "object", "x-kubernetes-map-type": "atomic" }, - "v1alpha1.NamedRuleWithOperations": { - "description": "NamedRuleWithOperations is a tuple of Operations and Resources with ResourceNames.", - "properties": { - "apiGroups": { - "description": "APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "apiVersions": { - "description": "APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "operations": { - "description": "Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "resourceNames": { - "description": "ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "resources": { - "description": "Resources is a list of resources this rule applies to.\n\nFor example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources.\n\nIf wildcard is present, the validation rule will ensure resources do not overlap with each other.\n\nDepending on the enclosing object, subresources might not be allowed. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "scope": { - "description": "scope specifies the scope of this rule. Valid values are \"Cluster\", \"Namespaced\", and \"*\" \"Cluster\" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. \"Namespaced\" means that only namespaced resources will match this rule. \"*\" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is \"*\".", - "type": "string" - } - }, - "type": "object", - "x-kubernetes-map-type": "atomic" - }, - "v1alpha1.ParamKind": { - "description": "ParamKind is a tuple of Group Kind and Version.", - "properties": { - "apiVersion": { - "description": "APIVersion is the API group version the resources belong to. In format of \"group/version\". Required.", - "type": "string" - }, - "kind": { - "description": "Kind is the API kind the resources belong to. Required.", - "type": "string" - } - }, - "type": "object", - "x-kubernetes-map-type": "atomic" - }, - "v1alpha1.ParamRef": { - "description": "ParamRef describes how to locate the params to be used as input to expressions of rules applied by a policy binding.", - "properties": { - "name": { - "description": "`name` is the name of the resource being referenced.\n\n`name` and `selector` are mutually exclusive properties. If one is set, the other must be unset.", - "type": "string" - }, - "namespace": { - "description": "namespace is the namespace of the referenced resource. Allows limiting the search for params to a specific namespace. Applies to both `name` and `selector` fields.\n\nA per-namespace parameter may be used by specifying a namespace-scoped `paramKind` in the policy and leaving this field empty.\n\n- If `paramKind` is cluster-scoped, this field MUST be unset. Setting this field results in a configuration error.\n\n- If `paramKind` is namespace-scoped, the namespace of the object being evaluated for admission will be used when this field is left unset. Take care that if this is left empty the binding must not match any cluster-scoped resources, which will result in an error.", - "type": "string" - }, - "parameterNotFoundAction": { - "description": "`parameterNotFoundAction` controls the behavior of the binding when the resource exists, and name or selector is valid, but there are no parameters matched by the binding. If the value is set to `Allow`, then no matched parameters will be treated as successful validation by the binding. If set to `Deny`, then no matched parameters will be subject to the `failurePolicy` of the policy.\n\nAllowed values are `Allow` or `Deny` Default to `Deny`", - "type": "string" - }, - "selector": { - "$ref": "#/definitions/v1.LabelSelector", - "description": "selector can be used to match multiple param objects based on their labels. Supply selector: {} to match all resources of the ParamKind.\n\nIf multiple params are found, they are all evaluated with the policy expressions and the results are ANDed together.\n\nOne of `name` or `selector` must be set, but `name` and `selector` are mutually exclusive properties. If one is set, the other must be unset." - } - }, - "type": "object", - "x-kubernetes-map-type": "atomic" - }, - "v1alpha1.TypeChecking": { - "description": "TypeChecking contains results of type checking the expressions in the ValidatingAdmissionPolicy", - "properties": { - "expressionWarnings": { - "description": "The type checking warnings for each expression.", - "items": { - "$ref": "#/definitions/v1alpha1.ExpressionWarning" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - } - }, - "type": "object" - }, - "v1alpha1.ValidatingAdmissionPolicy": { - "description": "ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it.", + "v1alpha1.MutatingAdmissionPolicy": { + "description": "MutatingAdmissionPolicy describes the definition of an admission mutation policy that mutates the object coming into admission chain.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -1067,25 +954,21 @@ "description": "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata." }, "spec": { - "$ref": "#/definitions/v1alpha1.ValidatingAdmissionPolicySpec", - "description": "Specification of the desired behavior of the ValidatingAdmissionPolicy." - }, - "status": { - "$ref": "#/definitions/v1alpha1.ValidatingAdmissionPolicyStatus", - "description": "The status of the ValidatingAdmissionPolicy, including warnings that are useful to determine if the policy behaves in the expected way. Populated by the system. Read-only." + "$ref": "#/definitions/v1alpha1.MutatingAdmissionPolicySpec", + "description": "Specification of the desired behavior of the MutatingAdmissionPolicy." } }, "type": "object", "x-kubernetes-group-version-kind": [ { "group": "admissionregistration.k8s.io", - "kind": "ValidatingAdmissionPolicy", + "kind": "MutatingAdmissionPolicy", "version": "v1alpha1" } ] }, - "v1alpha1.ValidatingAdmissionPolicyBinding": { - "description": "ValidatingAdmissionPolicyBinding binds the ValidatingAdmissionPolicy with paramerized resources. ValidatingAdmissionPolicyBinding and parameter CRDs together define how cluster administrators configure policies for clusters.\n\nFor a given admission request, each binding will cause its policy to be evaluated N times, where N is 1 for policies/bindings that don't use params, otherwise N is the number of parameters selected by the binding.\n\nThe CEL expressions of a policy must have a computed CEL cost below the maximum CEL budget. Each evaluation of the policy is given an independent CEL cost budget. Adding/removing policies, bindings, or params can not affect whether a given (policy, binding, param) combination is within its own CEL budget.", + "v1alpha1.MutatingAdmissionPolicyBinding": { + "description": "MutatingAdmissionPolicyBinding binds the MutatingAdmissionPolicy with parametrized resources. MutatingAdmissionPolicyBinding and the optional parameter resource together define how cluster administrators configure policies for clusters.\n\nFor a given admission request, each binding will cause its policy to be evaluated N times, where N is 1 for policies/bindings that don't use params, otherwise N is the number of parameters selected by the binding. Each evaluation is constrained by a [runtime cost budget](https://kubernetes.io/docs/reference/using-api/cel/#runtime-cost-budget).\n\nAdding/removing policies, bindings, or params can not affect whether a given (policy, binding, param) combination is within its own CEL budget.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -1100,21 +983,21 @@ "description": "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata." }, "spec": { - "$ref": "#/definitions/v1alpha1.ValidatingAdmissionPolicyBindingSpec", - "description": "Specification of the desired behavior of the ValidatingAdmissionPolicyBinding." + "$ref": "#/definitions/v1alpha1.MutatingAdmissionPolicyBindingSpec", + "description": "Specification of the desired behavior of the MutatingAdmissionPolicyBinding." } }, "type": "object", "x-kubernetes-group-version-kind": [ { "group": "admissionregistration.k8s.io", - "kind": "ValidatingAdmissionPolicyBinding", + "kind": "MutatingAdmissionPolicyBinding", "version": "v1alpha1" } ] }, - "v1alpha1.ValidatingAdmissionPolicyBindingList": { - "description": "ValidatingAdmissionPolicyBindingList is a list of ValidatingAdmissionPolicyBinding.", + "v1alpha1.MutatingAdmissionPolicyBindingList": { + "description": "MutatingAdmissionPolicyBindingList is a list of MutatingAdmissionPolicyBinding.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -1123,7 +1006,7 @@ "items": { "description": "List of PolicyBinding.", "items": { - "$ref": "#/definitions/v1alpha1.ValidatingAdmissionPolicyBinding" + "$ref": "#/definitions/v1alpha1.MutatingAdmissionPolicyBinding" }, "type": "array" }, @@ -1136,43 +1019,38 @@ "description": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds" } }, + "required": [ + "items" + ], "type": "object", "x-kubernetes-group-version-kind": [ { "group": "admissionregistration.k8s.io", - "kind": "ValidatingAdmissionPolicyBindingList", + "kind": "MutatingAdmissionPolicyBindingList", "version": "v1alpha1" } ] }, - "v1alpha1.ValidatingAdmissionPolicyBindingSpec": { - "description": "ValidatingAdmissionPolicyBindingSpec is the specification of the ValidatingAdmissionPolicyBinding.", + "v1alpha1.MutatingAdmissionPolicyBindingSpec": { + "description": "MutatingAdmissionPolicyBindingSpec is the specification of the MutatingAdmissionPolicyBinding.", "properties": { "matchResources": { "$ref": "#/definitions/v1alpha1.MatchResources", - "description": "MatchResources declares what resources match this binding and will be validated by it. Note that this is intersected with the policy's matchConstraints, so only requests that are matched by the policy can be selected by this. If this is unset, all resources matched by the policy are validated by this binding When resourceRules is unset, it does not constrain resource matching. If a resource is matched by the other fields of this object, it will be validated. Note that this is differs from ValidatingAdmissionPolicy matchConstraints, where resourceRules are required." + "description": "matchResources limits what resources match this binding and may be mutated by it. Note that if matchResources matches a resource, the resource must also match a policy's matchConstraints and matchConditions before the resource may be mutated. When matchResources is unset, it does not constrain resource matching, and only the policy's matchConstraints and matchConditions must match for the resource to be mutated. Additionally, matchResources.resourceRules are optional and do not constraint matching when unset. Note that this is differs from MutatingAdmissionPolicy matchConstraints, where resourceRules are required. The CREATE, UPDATE and CONNECT operations are allowed. The DELETE operation may not be matched. '*' matches CREATE, UPDATE and CONNECT." }, "paramRef": { "$ref": "#/definitions/v1alpha1.ParamRef", - "description": "paramRef specifies the parameter resource used to configure the admission control policy. It should point to a resource of the type specified in ParamKind of the bound ValidatingAdmissionPolicy. If the policy specifies a ParamKind and the resource referred to by ParamRef does not exist, this binding is considered mis-configured and the FailurePolicy of the ValidatingAdmissionPolicy applied. If the policy does not specify a ParamKind then this field is ignored, and the rules are evaluated without a param." + "description": "paramRef specifies the parameter resource used to configure the admission control policy. It should point to a resource of the type specified in spec.ParamKind of the bound MutatingAdmissionPolicy. If the policy specifies a ParamKind and the resource referred to by ParamRef does not exist, this binding is considered mis-configured and the FailurePolicy of the MutatingAdmissionPolicy applied. If the policy does not specify a ParamKind then this field is ignored, and the rules are evaluated without a param." }, "policyName": { - "description": "PolicyName references a ValidatingAdmissionPolicy name which the ValidatingAdmissionPolicyBinding binds to. If the referenced resource does not exist, this binding is considered invalid and will be ignored Required.", + "description": "policyName references a MutatingAdmissionPolicy name which the MutatingAdmissionPolicyBinding binds to. If the referenced resource does not exist, this binding is considered invalid and will be ignored Required.", "type": "string" - }, - "validationActions": { - "description": "validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced. If a validation evaluates to false it is always enforced according to these actions.\n\nFailures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according to these actions only if the FailurePolicy is set to Fail, otherwise the failures are ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.\n\nvalidationActions is declared as a set of action values. Order does not matter. validationActions may not contain duplicates of the same action.\n\nThe supported actions values are:\n\n\"Deny\" specifies that a validation failure results in a denied request.\n\n\"Warn\" specifies that a validation failure is reported to the request client in HTTP Warning headers, with a warning code of 299. Warnings can be sent both for allowed or denied admission responses.\n\n\"Audit\" specifies that a validation failure is included in the published audit event for the request. The audit event will contain a `validation.policy.admission.k8s.io/validation_failure` audit annotation with a value containing the details of the validation failures, formatted as a JSON list of objects, each with the following fields: - message: The validation failure message string - policy: The resource name of the ValidatingAdmissionPolicy - binding: The resource name of the ValidatingAdmissionPolicyBinding - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy - validationActions: The enforcement actions enacted for the validation failure Example audit annotation: `\"validation.policy.admission.k8s.io/validation_failure\": \"[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]\"`\n\nClients should expect to handle additional values by ignoring any values not recognized.\n\n\"Deny\" and \"Warn\" may not be used together since this combination needlessly duplicates the validation failure both in the API response body and the HTTP warning headers.\n\nRequired.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "set" } }, "type": "object" }, - "v1alpha1.ValidatingAdmissionPolicyList": { - "description": "ValidatingAdmissionPolicyList is a list of ValidatingAdmissionPolicy.", + "v1alpha1.MutatingAdmissionPolicyList": { + "description": "MutatingAdmissionPolicyList is a list of MutatingAdmissionPolicy.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -1181,7 +1059,7 @@ "items": { "description": "List of ValidatingAdmissionPolicy.", "items": { - "$ref": "#/definitions/v1alpha1.ValidatingAdmissionPolicy" + "$ref": "#/definitions/v1alpha1.MutatingAdmissionPolicy" }, "type": "array" }, @@ -1194,32 +1072,27 @@ "description": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds" } }, + "required": [ + "items" + ], "type": "object", "x-kubernetes-group-version-kind": [ { "group": "admissionregistration.k8s.io", - "kind": "ValidatingAdmissionPolicyList", + "kind": "MutatingAdmissionPolicyList", "version": "v1alpha1" } ] }, - "v1alpha1.ValidatingAdmissionPolicySpec": { - "description": "ValidatingAdmissionPolicySpec is the specification of the desired behavior of the AdmissionPolicy.", + "v1alpha1.MutatingAdmissionPolicySpec": { + "description": "MutatingAdmissionPolicySpec is the specification of the desired behavior of the admission policy.", "properties": { - "auditAnnotations": { - "description": "auditAnnotations contains CEL expressions which are used to produce audit annotations for the audit event of the API request. validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is required.", - "items": { - "$ref": "#/definitions/v1alpha1.AuditAnnotation" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, "failurePolicy": { - "description": "failurePolicy defines how to handle failures for the admission policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions or bindings.\n\nA policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource.\n\nfailurePolicy does not define how validations that evaluate to false are handled.\n\nWhen failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions define how failures are enforced.\n\nAllowed values are Ignore or Fail. Defaults to Fail.", + "description": "failurePolicy defines how to handle failures for the admission policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions or bindings.\n\nA policy is invalid if paramKind refers to a non-existent Kind. A binding is invalid if paramRef.name refers to a non-existent resource.\n\nfailurePolicy does not define how validations that evaluate to false are handled.\n\nAllowed values are Ignore or Fail. Defaults to Fail.", "type": "string" }, "matchConditions": { - "description": "MatchConditions is a list of conditions that must be met for a request to be validated. Match conditions filter requests that have already been matched by the rules, namespaceSelector, and objectSelector. An empty list of matchConditions matches all requests. There are a maximum of 64 match conditions allowed.\n\nIf a parameter object is provided, it can be accessed via the `params` handle in the same manner as validation expressions.\n\nThe exact matching logic is (in order):\n 1. If ANY matchCondition evaluates to FALSE, the policy is skipped.\n 2. If ALL matchConditions evaluate to TRUE, the policy is evaluated.\n 3. If any matchCondition evaluates to an error (but none are FALSE):\n - If failurePolicy=Fail, reject the request\n - If failurePolicy=Ignore, the policy is skipped", + "description": "matchConditions is a list of conditions that must be met for a request to be validated. Match conditions filter requests that have already been matched by the matchConstraints. An empty list of matchConditions matches all requests. There are a maximum of 64 match conditions allowed.\n\nIf a parameter object is provided, it can be accessed via the `params` handle in the same manner as validation expressions.\n\nThe exact matching logic is (in order):\n 1. If ANY matchCondition evaluates to FALSE, the policy is skipped.\n 2. If ALL matchConditions evaluate to TRUE, the policy is evaluated.\n 3. If any matchCondition evaluates to an error (but none are FALSE):\n - If failurePolicy=Fail, reject the request\n - If failurePolicy=Ignore, the policy is skipped", "items": { "$ref": "#/definitions/v1alpha1.MatchCondition" }, @@ -1233,86 +1106,144 @@ }, "matchConstraints": { "$ref": "#/definitions/v1alpha1.MatchResources", - "description": "MatchConstraints specifies what resources this policy is designed to validate. The AdmissionPolicy cares about a request if it matches _all_ Constraints. However, in order to prevent clusters from being put into an unstable state that cannot be recovered from via the API ValidatingAdmissionPolicy cannot match ValidatingAdmissionPolicy and ValidatingAdmissionPolicyBinding. Required." - }, - "paramKind": { - "$ref": "#/definitions/v1alpha1.ParamKind", - "description": "ParamKind specifies the kind of resources used to parameterize this policy. If absent, there are no parameters for this policy and the param CEL variable will not be provided to validation expressions. If ParamKind refers to a non-existent kind, this policy definition is mis-configured and the FailurePolicy is applied. If paramKind is specified but paramRef is unset in ValidatingAdmissionPolicyBinding, the params variable will be null." + "description": "matchConstraints specifies what resources this policy is designed to validate. The MutatingAdmissionPolicy cares about a request if it matches _all_ Constraints. However, in order to prevent clusters from being put into an unstable state that cannot be recovered from via the API MutatingAdmissionPolicy cannot match MutatingAdmissionPolicy and MutatingAdmissionPolicyBinding. The CREATE, UPDATE and CONNECT operations are allowed. The DELETE operation may not be matched. '*' matches CREATE, UPDATE and CONNECT. Required." }, - "validations": { - "description": "Validations contain CEL expressions which is used to apply the validation. Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is required.", + "mutations": { + "description": "mutations contain operations to perform on matching objects. mutations may not be empty; a minimum of one mutation is required. mutations are evaluated in order, and are reinvoked according to the reinvocationPolicy. The mutations of a policy are invoked for each binding of this policy and reinvocation of mutations occurs on a per binding basis.", "items": { - "$ref": "#/definitions/v1alpha1.Validation" + "$ref": "#/definitions/v1alpha1.Mutation" }, "type": "array", "x-kubernetes-list-type": "atomic" }, + "paramKind": { + "$ref": "#/definitions/v1alpha1.ParamKind", + "description": "paramKind specifies the kind of resources used to parameterize this policy. If absent, there are no parameters for this policy and the param CEL variable will not be provided to validation expressions. If paramKind refers to a non-existent kind, this policy definition is mis-configured and the FailurePolicy is applied. If paramKind is specified but paramRef is unset in MutatingAdmissionPolicyBinding, the params variable will be null." + }, + "reinvocationPolicy": { + "description": "reinvocationPolicy indicates whether mutations may be called multiple times per MutatingAdmissionPolicyBinding as part of a single admission evaluation. Allowed values are \"Never\" and \"IfNeeded\".\n\nNever: These mutations will not be called more than once per binding in a single admission evaluation.\n\nIfNeeded: These mutations may be invoked more than once per binding for a single admission request and there is no guarantee of order with respect to other admission plugins, admission webhooks, bindings of this policy and admission policies. Mutations are only reinvoked when mutations change the object after this mutation is invoked. Required.", + "type": "string" + }, "variables": { - "description": "Variables contain definitions of variables that can be used in composition of other expressions. Each variable is defined as a named CEL expression. The variables defined here will be available under `variables` in other expressions of the policy except MatchConditions because MatchConditions are evaluated before the rest of the policy.\n\nThe expression of a variable can refer to other variables defined earlier in the list but not those after. Thus, Variables must be sorted by the order of first appearance and acyclic.", + "description": "variables contain definitions of variables that can be used in composition of other expressions. Each variable is defined as a named CEL expression. The variables defined here will be available under `variables` in other expressions of the policy except matchConditions because matchConditions are evaluated before the rest of the policy.\n\nThe expression of a variable can refer to other variables defined earlier in the list but not those after. Thus, variables must be sorted by the order of first appearance and acyclic.", "items": { "$ref": "#/definitions/v1alpha1.Variable" }, "type": "array", - "x-kubernetes-list-map-keys": [ - "name" - ], - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge" + "x-kubernetes-list-type": "atomic" } }, "type": "object" }, - "v1alpha1.ValidatingAdmissionPolicyStatus": { - "description": "ValidatingAdmissionPolicyStatus represents the status of a ValidatingAdmissionPolicy.", + "v1alpha1.Mutation": { + "description": "Mutation specifies the CEL expression which is used to apply the Mutation.", "properties": { - "conditions": { - "description": "The conditions represent the latest available observations of a policy's current state.", + "applyConfiguration": { + "$ref": "#/definitions/v1alpha1.ApplyConfiguration", + "description": "applyConfiguration defines the desired configuration values of an object. The configuration is applied to the admission object using [structured merge diff](https://github.com/kubernetes-sigs/structured-merge-diff). A CEL expression is used to create apply configuration." + }, + "jsonPatch": { + "$ref": "#/definitions/v1alpha1.JSONPatch", + "description": "jsonPatch defines a [JSON patch](https://jsonpatch.com/) operation to perform a mutation to the object. A CEL expression is used to create the JSON patch." + }, + "patchType": { + "description": "patchType indicates the patch strategy used. Allowed values are \"ApplyConfiguration\" and \"JSONPatch\". Required.", + "type": "string" + } + }, + "required": [ + "patchType" + ], + "type": "object" + }, + "v1alpha1.NamedRuleWithOperations": { + "description": "NamedRuleWithOperations is a tuple of Operations and Resources with ResourceNames.", + "properties": { + "apiGroups": { + "description": "APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required.", "items": { - "$ref": "#/definitions/v1.Condition" + "type": "string" }, "type": "array", - "x-kubernetes-list-map-keys": [ - "type" - ], - "x-kubernetes-list-type": "map" + "x-kubernetes-list-type": "atomic" }, - "observedGeneration": { - "description": "The generation observed by the controller.", - "format": "int64", - "type": "integer" + "apiVersions": { + "description": "APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" }, - "typeChecking": { - "$ref": "#/definitions/v1alpha1.TypeChecking", - "description": "The results of type checking for each expression. Presence of this field indicates the completion of the type checking." + "operations": { + "description": "Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "resourceNames": { + "description": "ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "resources": { + "description": "Resources is a list of resources this rule applies to.\n\nFor example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources.\n\nIf wildcard is present, the validation rule will ensure resources do not overlap with each other.\n\nDepending on the enclosing object, subresources might not be allowed. Required.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "scope": { + "description": "scope specifies the scope of this rule. Valid values are \"Cluster\", \"Namespaced\", and \"*\" \"Cluster\" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. \"Namespaced\" means that only namespaced resources will match this rule. \"*\" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is \"*\".", + "type": "string" } }, - "type": "object" + "type": "object", + "x-kubernetes-map-type": "atomic" }, - "v1alpha1.Validation": { - "description": "Validation specifies the CEL expression which is used to apply the validation.", + "v1alpha1.ParamKind": { + "description": "ParamKind is a tuple of Group Kind and Version.", "properties": { - "expression": { - "description": "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources. - 'variables' - Map of composited variables, from its name to its lazily evaluated value.\n For example, a variable named 'foo' can be accessed as 'variables.foo'.\n- 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.", + "apiVersion": { + "description": "APIVersion is the API group version the resources belong to. In format of \"group/version\". Required.", "type": "string" }, - "message": { - "description": "Message represents the message displayed when validation fails. The message is required if the Expression contains line breaks. The message must not contain line breaks. If unset, the message is \"failed rule: {Rule}\". e.g. \"must be a URL with the host matching spec.host\" If the Expression contains line breaks. Message is required. The message must not contain line breaks. If unset, the message is \"failed Expression: {Expression}\".", + "kind": { + "description": "Kind is the API kind the resources belong to. Required.", + "type": "string" + } + }, + "type": "object", + "x-kubernetes-map-type": "atomic" + }, + "v1alpha1.ParamRef": { + "description": "ParamRef describes how to locate the params to be used as input to expressions of rules applied by a policy binding.", + "properties": { + "name": { + "description": "`name` is the name of the resource being referenced.\n\n`name` and `selector` are mutually exclusive properties. If one is set, the other must be unset.", "type": "string" }, - "messageExpression": { - "description": "messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. Since messageExpression is used as a failure message, it must evaluate to a string. If both message and messageExpression are present on a validation, then messageExpression will be used if validation fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged. messageExpression has access to all the same variables as the `expression` except for 'authorizer' and 'authorizer.requestResource'. Example: \"object.x must be less than max (\"+string(params.max)+\")\"", + "namespace": { + "description": "namespace is the namespace of the referenced resource. Allows limiting the search for params to a specific namespace. Applies to both `name` and `selector` fields.\n\nA per-namespace parameter may be used by specifying a namespace-scoped `paramKind` in the policy and leaving this field empty.\n\n- If `paramKind` is cluster-scoped, this field MUST be unset. Setting this field results in a configuration error.\n\n- If `paramKind` is namespace-scoped, the namespace of the object being evaluated for admission will be used when this field is left unset. Take care that if this is left empty the binding must not match any cluster-scoped resources, which will result in an error.", "type": "string" }, - "reason": { - "description": "Reason represents a machine-readable description of why this validation failed. If this is the first validation in the list to fail, this reason, as well as the corresponding HTTP response code, are used in the HTTP response to the client. The currently supported reasons are: \"Unauthorized\", \"Forbidden\", \"Invalid\", \"RequestEntityTooLarge\". If not set, StatusReasonInvalid is used in the response to the client.", + "parameterNotFoundAction": { + "description": "`parameterNotFoundAction` controls the behavior of the binding when the resource exists, and name or selector is valid, but there are no parameters matched by the binding. If the value is set to `Allow`, then no matched parameters will be treated as successful validation by the binding. If set to `Deny`, then no matched parameters will be subject to the `failurePolicy` of the policy.\n\nAllowed values are `Allow` or `Deny` Default to `Deny`", "type": "string" + }, + "selector": { + "$ref": "#/definitions/v1.LabelSelector", + "description": "selector can be used to match multiple param objects based on their labels. Supply selector: {} to match all resources of the ParamKind.\n\nIf multiple params are found, they are all evaluated with the policy expressions and the results are ANDed together.\n\nOne of `name` or `selector` must be set, but `name` and `selector` are mutually exclusive properties. If one is set, the other must be unset." } }, - "required": [ - "expression" - ], - "type": "object" + "type": "object", + "x-kubernetes-map-type": "atomic" }, "v1alpha1.Variable": { "description": "Variable is the definition of a variable that is used for composition.", @@ -1332,40 +1263,24 @@ ], "type": "object" }, - "v1beta1.AuditAnnotation": { - "description": "AuditAnnotation describes how to produce an audit annotation for an API request.", + "v1beta1.ApplyConfiguration": { + "description": "ApplyConfiguration defines the desired configuration values of an object.", "properties": { - "key": { - "description": "key specifies the audit annotation key. The audit annotation keys of a ValidatingAdmissionPolicy must be unique. The key must be a qualified name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.\n\nThe key is combined with the resource name of the ValidatingAdmissionPolicy to construct an audit annotation key: \"{ValidatingAdmissionPolicy name}/{key}\".\n\nIf an admission webhook uses the same resource name as this ValidatingAdmissionPolicy and the same audit annotation key, the annotation key will be identical. In this case, the first annotation written with the key will be included in the audit event and all subsequent annotations with the same key will be discarded.\n\nRequired.", - "type": "string" - }, - "valueExpression": { - "description": "valueExpression represents the expression which is evaluated by CEL to produce an audit annotation value. The expression must evaluate to either a string or null value. If the expression evaluates to a string, the audit annotation is included with the string value. If the expression evaluates to null or empty string the audit annotation will be omitted. The valueExpression may be no longer than 5kb in length. If the result of the valueExpression is more than 10kb in length, it will be truncated to 10kb.\n\nIf multiple ValidatingAdmissionPolicyBinding resources match an API request, then the valueExpression will be evaluated for each binding. All unique values produced by the valueExpressions will be joined together in a comma-separated list.\n\nRequired.", + "expression": { + "description": "expression will be evaluated by CEL to create an apply configuration. ref: https://github.com/google/cel-spec\n\nApply configurations are declared in CEL using object initialization. For example, this CEL expression returns an apply configuration to set a single field:\n\n\tObject{\n\t spec: Object.spec{\n\t serviceAccountName: \"example\"\n\t }\n\t}\n\nApply configurations may not modify atomic structs, maps or arrays due to the risk of accidental deletion of values not included in the apply configuration.\n\nCEL expressions have access to the object types needed to create apply configurations:\n\n- 'Object' - CEL type of the resource object. - 'Object.' - CEL type of object field (such as 'Object.spec') - 'Object.....` - CEL type of nested field (such as 'Object.spec.containers')\n\nCEL expressions have access to the contents of the API request, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources. - 'variables' - Map of composited variables, from its name to its lazily evaluated value.\n For example, a variable named 'foo' can be accessed as 'variables.foo'.\n- 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Required.", "type": "string" } }, - "required": [ - "key", - "valueExpression" - ], "type": "object" }, - "v1beta1.ExpressionWarning": { - "description": "ExpressionWarning is a warning information that targets a specific expression.", + "v1beta1.JSONPatch": { + "description": "JSONPatch defines a JSON Patch.", "properties": { - "fieldRef": { - "description": "The path to the field that refers the expression. For example, the reference to the expression of the first item of validations is \"spec.validations[0].expression\"", - "type": "string" - }, - "warning": { - "description": "The content of type checking information in a human-readable form. Each line of the warning contains the type that the expression is checked against, followed by the type check error from the compiler.", + "expression": { + "description": "expression will be evaluated by CEL to create a [JSON patch](https://jsonpatch.com/). ref: https://github.com/google/cel-spec\n\nexpression must return an array of JSONPatch values.\n\nFor example, this CEL expression returns a JSON patch to conditionally modify a value:\n\n\t [\n\t JSONPatch{op: \"test\", path: \"/spec/example\", value: \"Red\"},\n\t JSONPatch{op: \"replace\", path: \"/spec/example\", value: \"Green\"}\n\t ]\n\nTo define an object for the patch value, use Object types. For example:\n\n\t [\n\t JSONPatch{\n\t op: \"add\",\n\t path: \"/spec/selector\",\n\t value: Object.spec.selector{matchLabels: {\"environment\": \"test\"}}\n\t }\n\t ]\n\nTo use strings containing '/' and '~' as JSONPatch path keys, use \"jsonpatch.escapeKey\". For example:\n\n\t [\n\t JSONPatch{\n\t op: \"add\",\n\t path: \"/metadata/labels/\" + jsonpatch.escapeKey(\"example.com/environment\"),\n\t value: \"test\"\n\t },\n\t ]\n\nCEL expressions have access to the types needed to create JSON patches and objects:\n\n- 'JSONPatch' - CEL type of JSON Patch operations. JSONPatch has the fields 'op', 'from', 'path' and 'value'.\n See [JSON patch](https://jsonpatch.com/) for more details. The 'value' field may be set to any of: string,\n integer, array, map or object. If set, the 'path' and 'from' fields must be set to a\n [JSON pointer](https://datatracker.ietf.org/doc/html/rfc6901/) string, where the 'jsonpatch.escapeKey()' CEL\n function may be used to escape path keys containing '/' and '~'.\n- 'Object' - CEL type of the resource object. - 'Object.' - CEL type of object field (such as 'Object.spec') - 'Object.....` - CEL type of nested field (such as 'Object.spec.containers')\n\nCEL expressions have access to the contents of the API request, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources. - 'variables' - Map of composited variables, from its name to its lazily evaluated value.\n For example, a variable named 'foo' can be accessed as 'variables.foo'.\n- 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nCEL expressions have access to [Kubernetes CEL function libraries](https://kubernetes.io/docs/reference/using-api/cel/#cel-options-language-features-and-libraries) as well as:\n\n- 'jsonpatch.escapeKey' - Performs JSONPatch key escaping. '~' and '/' are escaped as '~0' and `~1' respectively).\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Required.", "type": "string" } }, - "required": [ - "fieldRef", - "warning" - ], "type": "object" }, "v1beta1.MatchCondition": { @@ -1421,111 +1336,8 @@ "type": "object", "x-kubernetes-map-type": "atomic" }, - "v1beta1.NamedRuleWithOperations": { - "description": "NamedRuleWithOperations is a tuple of Operations and Resources with ResourceNames.", - "properties": { - "apiGroups": { - "description": "APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "apiVersions": { - "description": "APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "operations": { - "description": "Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "resourceNames": { - "description": "ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "resources": { - "description": "Resources is a list of resources this rule applies to.\n\nFor example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources.\n\nIf wildcard is present, the validation rule will ensure resources do not overlap with each other.\n\nDepending on the enclosing object, subresources might not be allowed. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "scope": { - "description": "scope specifies the scope of this rule. Valid values are \"Cluster\", \"Namespaced\", and \"*\" \"Cluster\" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. \"Namespaced\" means that only namespaced resources will match this rule. \"*\" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is \"*\".", - "type": "string" - } - }, - "type": "object", - "x-kubernetes-map-type": "atomic" - }, - "v1beta1.ParamKind": { - "description": "ParamKind is a tuple of Group Kind and Version.", - "properties": { - "apiVersion": { - "description": "APIVersion is the API group version the resources belong to. In format of \"group/version\". Required.", - "type": "string" - }, - "kind": { - "description": "Kind is the API kind the resources belong to. Required.", - "type": "string" - } - }, - "type": "object", - "x-kubernetes-map-type": "atomic" - }, - "v1beta1.ParamRef": { - "description": "ParamRef describes how to locate the params to be used as input to expressions of rules applied by a policy binding.", - "properties": { - "name": { - "description": "name is the name of the resource being referenced.\n\nOne of `name` or `selector` must be set, but `name` and `selector` are mutually exclusive properties. If one is set, the other must be unset.\n\nA single parameter used for all admission requests can be configured by setting the `name` field, leaving `selector` blank, and setting namespace if `paramKind` is namespace-scoped.", - "type": "string" - }, - "namespace": { - "description": "namespace is the namespace of the referenced resource. Allows limiting the search for params to a specific namespace. Applies to both `name` and `selector` fields.\n\nA per-namespace parameter may be used by specifying a namespace-scoped `paramKind` in the policy and leaving this field empty.\n\n- If `paramKind` is cluster-scoped, this field MUST be unset. Setting this field results in a configuration error.\n\n- If `paramKind` is namespace-scoped, the namespace of the object being evaluated for admission will be used when this field is left unset. Take care that if this is left empty the binding must not match any cluster-scoped resources, which will result in an error.", - "type": "string" - }, - "parameterNotFoundAction": { - "description": "`parameterNotFoundAction` controls the behavior of the binding when the resource exists, and name or selector is valid, but there are no parameters matched by the binding. If the value is set to `Allow`, then no matched parameters will be treated as successful validation by the binding. If set to `Deny`, then no matched parameters will be subject to the `failurePolicy` of the policy.\n\nAllowed values are `Allow` or `Deny`\n\nRequired", - "type": "string" - }, - "selector": { - "$ref": "#/definitions/v1.LabelSelector", - "description": "selector can be used to match multiple param objects based on their labels. Supply selector: {} to match all resources of the ParamKind.\n\nIf multiple params are found, they are all evaluated with the policy expressions and the results are ANDed together.\n\nOne of `name` or `selector` must be set, but `name` and `selector` are mutually exclusive properties. If one is set, the other must be unset." - } - }, - "type": "object", - "x-kubernetes-map-type": "atomic" - }, - "v1beta1.TypeChecking": { - "description": "TypeChecking contains results of type checking the expressions in the ValidatingAdmissionPolicy", - "properties": { - "expressionWarnings": { - "description": "The type checking warnings for each expression.", - "items": { - "$ref": "#/definitions/v1beta1.ExpressionWarning" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - } - }, - "type": "object" - }, - "v1beta1.ValidatingAdmissionPolicy": { - "description": "ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it.", + "v1beta1.MutatingAdmissionPolicy": { + "description": "MutatingAdmissionPolicy describes the definition of an admission mutation policy that mutates the object coming into admission chain.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -1540,25 +1352,21 @@ "description": "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata." }, "spec": { - "$ref": "#/definitions/v1beta1.ValidatingAdmissionPolicySpec", - "description": "Specification of the desired behavior of the ValidatingAdmissionPolicy." - }, - "status": { - "$ref": "#/definitions/v1beta1.ValidatingAdmissionPolicyStatus", - "description": "The status of the ValidatingAdmissionPolicy, including warnings that are useful to determine if the policy behaves in the expected way. Populated by the system. Read-only." + "$ref": "#/definitions/v1beta1.MutatingAdmissionPolicySpec", + "description": "Specification of the desired behavior of the MutatingAdmissionPolicy." } }, "type": "object", "x-kubernetes-group-version-kind": [ { "group": "admissionregistration.k8s.io", - "kind": "ValidatingAdmissionPolicy", + "kind": "MutatingAdmissionPolicy", "version": "v1beta1" } ] }, - "v1beta1.ValidatingAdmissionPolicyBinding": { - "description": "ValidatingAdmissionPolicyBinding binds the ValidatingAdmissionPolicy with paramerized resources. ValidatingAdmissionPolicyBinding and parameter CRDs together define how cluster administrators configure policies for clusters.\n\nFor a given admission request, each binding will cause its policy to be evaluated N times, where N is 1 for policies/bindings that don't use params, otherwise N is the number of parameters selected by the binding.\n\nThe CEL expressions of a policy must have a computed CEL cost below the maximum CEL budget. Each evaluation of the policy is given an independent CEL cost budget. Adding/removing policies, bindings, or params can not affect whether a given (policy, binding, param) combination is within its own CEL budget.", + "v1beta1.MutatingAdmissionPolicyBinding": { + "description": "MutatingAdmissionPolicyBinding binds the MutatingAdmissionPolicy with parametrized resources. MutatingAdmissionPolicyBinding and the optional parameter resource together define how cluster administrators configure policies for clusters.\n\nFor a given admission request, each binding will cause its policy to be evaluated N times, where N is 1 for policies/bindings that don't use params, otherwise N is the number of parameters selected by the binding. Each evaluation is constrained by a [runtime cost budget](https://kubernetes.io/docs/reference/using-api/cel/#runtime-cost-budget).\n\nAdding/removing policies, bindings, or params can not affect whether a given (policy, binding, param) combination is within its own CEL budget.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -1573,21 +1381,21 @@ "description": "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata." }, "spec": { - "$ref": "#/definitions/v1beta1.ValidatingAdmissionPolicyBindingSpec", - "description": "Specification of the desired behavior of the ValidatingAdmissionPolicyBinding." + "$ref": "#/definitions/v1beta1.MutatingAdmissionPolicyBindingSpec", + "description": "Specification of the desired behavior of the MutatingAdmissionPolicyBinding." } }, "type": "object", "x-kubernetes-group-version-kind": [ { "group": "admissionregistration.k8s.io", - "kind": "ValidatingAdmissionPolicyBinding", + "kind": "MutatingAdmissionPolicyBinding", "version": "v1beta1" } ] }, - "v1beta1.ValidatingAdmissionPolicyBindingList": { - "description": "ValidatingAdmissionPolicyBindingList is a list of ValidatingAdmissionPolicyBinding.", + "v1beta1.MutatingAdmissionPolicyBindingList": { + "description": "MutatingAdmissionPolicyBindingList is a list of MutatingAdmissionPolicyBinding.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -1596,7 +1404,7 @@ "items": { "description": "List of PolicyBinding.", "items": { - "$ref": "#/definitions/v1beta1.ValidatingAdmissionPolicyBinding" + "$ref": "#/definitions/v1beta1.MutatingAdmissionPolicyBinding" }, "type": "array" }, @@ -1609,43 +1417,38 @@ "description": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds" } }, + "required": [ + "items" + ], "type": "object", "x-kubernetes-group-version-kind": [ { "group": "admissionregistration.k8s.io", - "kind": "ValidatingAdmissionPolicyBindingList", + "kind": "MutatingAdmissionPolicyBindingList", "version": "v1beta1" } ] }, - "v1beta1.ValidatingAdmissionPolicyBindingSpec": { - "description": "ValidatingAdmissionPolicyBindingSpec is the specification of the ValidatingAdmissionPolicyBinding.", + "v1beta1.MutatingAdmissionPolicyBindingSpec": { + "description": "MutatingAdmissionPolicyBindingSpec is the specification of the MutatingAdmissionPolicyBinding.", "properties": { "matchResources": { "$ref": "#/definitions/v1beta1.MatchResources", - "description": "MatchResources declares what resources match this binding and will be validated by it. Note that this is intersected with the policy's matchConstraints, so only requests that are matched by the policy can be selected by this. If this is unset, all resources matched by the policy are validated by this binding When resourceRules is unset, it does not constrain resource matching. If a resource is matched by the other fields of this object, it will be validated. Note that this is differs from ValidatingAdmissionPolicy matchConstraints, where resourceRules are required." + "description": "matchResources limits what resources match this binding and may be mutated by it. Note that if matchResources matches a resource, the resource must also match a policy's matchConstraints and matchConditions before the resource may be mutated. When matchResources is unset, it does not constrain resource matching, and only the policy's matchConstraints and matchConditions must match for the resource to be mutated. Additionally, matchResources.resourceRules are optional and do not constraint matching when unset. Note that this is differs from MutatingAdmissionPolicy matchConstraints, where resourceRules are required. The CREATE, UPDATE and CONNECT operations are allowed. The DELETE operation may not be matched. '*' matches CREATE, UPDATE and CONNECT." }, "paramRef": { "$ref": "#/definitions/v1beta1.ParamRef", - "description": "paramRef specifies the parameter resource used to configure the admission control policy. It should point to a resource of the type specified in ParamKind of the bound ValidatingAdmissionPolicy. If the policy specifies a ParamKind and the resource referred to by ParamRef does not exist, this binding is considered mis-configured and the FailurePolicy of the ValidatingAdmissionPolicy applied. If the policy does not specify a ParamKind then this field is ignored, and the rules are evaluated without a param." + "description": "paramRef specifies the parameter resource used to configure the admission control policy. It should point to a resource of the type specified in spec.ParamKind of the bound MutatingAdmissionPolicy. If the policy specifies a ParamKind and the resource referred to by ParamRef does not exist, this binding is considered mis-configured and the FailurePolicy of the MutatingAdmissionPolicy applied. If the policy does not specify a ParamKind then this field is ignored, and the rules are evaluated without a param." }, "policyName": { - "description": "PolicyName references a ValidatingAdmissionPolicy name which the ValidatingAdmissionPolicyBinding binds to. If the referenced resource does not exist, this binding is considered invalid and will be ignored Required.", + "description": "policyName references a MutatingAdmissionPolicy name which the MutatingAdmissionPolicyBinding binds to. If the referenced resource does not exist, this binding is considered invalid and will be ignored Required.", "type": "string" - }, - "validationActions": { - "description": "validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced. If a validation evaluates to false it is always enforced according to these actions.\n\nFailures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according to these actions only if the FailurePolicy is set to Fail, otherwise the failures are ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.\n\nvalidationActions is declared as a set of action values. Order does not matter. validationActions may not contain duplicates of the same action.\n\nThe supported actions values are:\n\n\"Deny\" specifies that a validation failure results in a denied request.\n\n\"Warn\" specifies that a validation failure is reported to the request client in HTTP Warning headers, with a warning code of 299. Warnings can be sent both for allowed or denied admission responses.\n\n\"Audit\" specifies that a validation failure is included in the published audit event for the request. The audit event will contain a `validation.policy.admission.k8s.io/validation_failure` audit annotation with a value containing the details of the validation failures, formatted as a JSON list of objects, each with the following fields: - message: The validation failure message string - policy: The resource name of the ValidatingAdmissionPolicy - binding: The resource name of the ValidatingAdmissionPolicyBinding - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy - validationActions: The enforcement actions enacted for the validation failure Example audit annotation: `\"validation.policy.admission.k8s.io/validation_failure\": \"[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]\"`\n\nClients should expect to handle additional values by ignoring any values not recognized.\n\n\"Deny\" and \"Warn\" may not be used together since this combination needlessly duplicates the validation failure both in the API response body and the HTTP warning headers.\n\nRequired.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "set" } }, "type": "object" }, - "v1beta1.ValidatingAdmissionPolicyList": { - "description": "ValidatingAdmissionPolicyList is a list of ValidatingAdmissionPolicy.", + "v1beta1.MutatingAdmissionPolicyList": { + "description": "MutatingAdmissionPolicyList is a list of MutatingAdmissionPolicy.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -1654,7 +1457,7 @@ "items": { "description": "List of ValidatingAdmissionPolicy.", "items": { - "$ref": "#/definitions/v1beta1.ValidatingAdmissionPolicy" + "$ref": "#/definitions/v1beta1.MutatingAdmissionPolicy" }, "type": "array" }, @@ -1667,32 +1470,27 @@ "description": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds" } }, + "required": [ + "items" + ], "type": "object", "x-kubernetes-group-version-kind": [ { "group": "admissionregistration.k8s.io", - "kind": "ValidatingAdmissionPolicyList", + "kind": "MutatingAdmissionPolicyList", "version": "v1beta1" } ] }, - "v1beta1.ValidatingAdmissionPolicySpec": { - "description": "ValidatingAdmissionPolicySpec is the specification of the desired behavior of the AdmissionPolicy.", + "v1beta1.MutatingAdmissionPolicySpec": { + "description": "MutatingAdmissionPolicySpec is the specification of the desired behavior of the admission policy.", "properties": { - "auditAnnotations": { - "description": "auditAnnotations contains CEL expressions which are used to produce audit annotations for the audit event of the API request. validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is required.", - "items": { - "$ref": "#/definitions/v1beta1.AuditAnnotation" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, "failurePolicy": { - "description": "failurePolicy defines how to handle failures for the admission policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions or bindings.\n\nA policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource.\n\nfailurePolicy does not define how validations that evaluate to false are handled.\n\nWhen failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions define how failures are enforced.\n\nAllowed values are Ignore or Fail. Defaults to Fail.", + "description": "failurePolicy defines how to handle failures for the admission policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions or bindings.\n\nA policy is invalid if paramKind refers to a non-existent Kind. A binding is invalid if paramRef.name refers to a non-existent resource.\n\nfailurePolicy does not define how validations that evaluate to false are handled.\n\nAllowed values are Ignore or Fail. Defaults to Fail.", "type": "string" }, "matchConditions": { - "description": "MatchConditions is a list of conditions that must be met for a request to be validated. Match conditions filter requests that have already been matched by the rules, namespaceSelector, and objectSelector. An empty list of matchConditions matches all requests. There are a maximum of 64 match conditions allowed.\n\nIf a parameter object is provided, it can be accessed via the `params` handle in the same manner as validation expressions.\n\nThe exact matching logic is (in order):\n 1. If ANY matchCondition evaluates to FALSE, the policy is skipped.\n 2. If ALL matchConditions evaluate to TRUE, the policy is evaluated.\n 3. If any matchCondition evaluates to an error (but none are FALSE):\n - If failurePolicy=Fail, reject the request\n - If failurePolicy=Ignore, the policy is skipped", + "description": "matchConditions is a list of conditions that must be met for a request to be validated. Match conditions filter requests that have already been matched by the matchConstraints. An empty list of matchConditions matches all requests. There are a maximum of 64 match conditions allowed.\n\nIf a parameter object is provided, it can be accessed via the `params` handle in the same manner as validation expressions.\n\nThe exact matching logic is (in order):\n 1. If ANY matchCondition evaluates to FALSE, the policy is skipped.\n 2. If ALL matchConditions evaluate to TRUE, the policy is evaluated.\n 3. If any matchCondition evaluates to an error (but none are FALSE):\n - If failurePolicy=Fail, reject the request\n - If failurePolicy=Ignore, the policy is skipped", "items": { "$ref": "#/definitions/v1beta1.MatchCondition" }, @@ -1706,86 +1504,144 @@ }, "matchConstraints": { "$ref": "#/definitions/v1beta1.MatchResources", - "description": "MatchConstraints specifies what resources this policy is designed to validate. The AdmissionPolicy cares about a request if it matches _all_ Constraints. However, in order to prevent clusters from being put into an unstable state that cannot be recovered from via the API ValidatingAdmissionPolicy cannot match ValidatingAdmissionPolicy and ValidatingAdmissionPolicyBinding. Required." + "description": "matchConstraints specifies what resources this policy is designed to validate. The MutatingAdmissionPolicy cares about a request if it matches _all_ Constraints. However, in order to prevent clusters from being put into an unstable state that cannot be recovered from via the API MutatingAdmissionPolicy cannot match MutatingAdmissionPolicy and MutatingAdmissionPolicyBinding. The CREATE, UPDATE and CONNECT operations are allowed. The DELETE operation may not be matched. '*' matches CREATE, UPDATE and CONNECT. Required." }, - "paramKind": { - "$ref": "#/definitions/v1beta1.ParamKind", - "description": "ParamKind specifies the kind of resources used to parameterize this policy. If absent, there are no parameters for this policy and the param CEL variable will not be provided to validation expressions. If ParamKind refers to a non-existent kind, this policy definition is mis-configured and the FailurePolicy is applied. If paramKind is specified but paramRef is unset in ValidatingAdmissionPolicyBinding, the params variable will be null." - }, - "validations": { - "description": "Validations contain CEL expressions which is used to apply the validation. Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is required.", + "mutations": { + "description": "mutations contain operations to perform on matching objects. mutations may not be empty; a minimum of one mutation is required. mutations are evaluated in order, and are reinvoked according to the reinvocationPolicy. The mutations of a policy are invoked for each binding of this policy and reinvocation of mutations occurs on a per binding basis.", "items": { - "$ref": "#/definitions/v1beta1.Validation" + "$ref": "#/definitions/v1beta1.Mutation" }, "type": "array", "x-kubernetes-list-type": "atomic" }, + "paramKind": { + "$ref": "#/definitions/v1beta1.ParamKind", + "description": "paramKind specifies the kind of resources used to parameterize this policy. If absent, there are no parameters for this policy and the param CEL variable will not be provided to validation expressions. If paramKind refers to a non-existent kind, this policy definition is mis-configured and the FailurePolicy is applied. If paramKind is specified but paramRef is unset in MutatingAdmissionPolicyBinding, the params variable will be null." + }, + "reinvocationPolicy": { + "description": "reinvocationPolicy indicates whether mutations may be called multiple times per MutatingAdmissionPolicyBinding as part of a single admission evaluation. Allowed values are \"Never\" and \"IfNeeded\".\n\nNever: These mutations will not be called more than once per binding in a single admission evaluation.\n\nIfNeeded: These mutations may be invoked more than once per binding for a single admission request and there is no guarantee of order with respect to other admission plugins, admission webhooks, bindings of this policy and admission policies. Mutations are only reinvoked when mutations change the object after this mutation is invoked. Required.", + "type": "string" + }, "variables": { - "description": "Variables contain definitions of variables that can be used in composition of other expressions. Each variable is defined as a named CEL expression. The variables defined here will be available under `variables` in other expressions of the policy except MatchConditions because MatchConditions are evaluated before the rest of the policy.\n\nThe expression of a variable can refer to other variables defined earlier in the list but not those after. Thus, Variables must be sorted by the order of first appearance and acyclic.", + "description": "variables contain definitions of variables that can be used in composition of other expressions. Each variable is defined as a named CEL expression. The variables defined here will be available under `variables` in other expressions of the policy except matchConditions because matchConditions are evaluated before the rest of the policy.\n\nThe expression of a variable can refer to other variables defined earlier in the list but not those after. Thus, variables must be sorted by the order of first appearance and acyclic.", "items": { "$ref": "#/definitions/v1beta1.Variable" }, "type": "array", - "x-kubernetes-list-map-keys": [ - "name" - ], - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge" + "x-kubernetes-list-type": "atomic" } }, "type": "object" }, - "v1beta1.ValidatingAdmissionPolicyStatus": { - "description": "ValidatingAdmissionPolicyStatus represents the status of an admission validation policy.", + "v1beta1.Mutation": { + "description": "Mutation specifies the CEL expression which is used to apply the Mutation.", "properties": { - "conditions": { - "description": "The conditions represent the latest available observations of a policy's current state.", + "applyConfiguration": { + "$ref": "#/definitions/v1beta1.ApplyConfiguration", + "description": "applyConfiguration defines the desired configuration values of an object. The configuration is applied to the admission object using [structured merge diff](https://github.com/kubernetes-sigs/structured-merge-diff). A CEL expression is used to create apply configuration." + }, + "jsonPatch": { + "$ref": "#/definitions/v1beta1.JSONPatch", + "description": "jsonPatch defines a [JSON patch](https://jsonpatch.com/) operation to perform a mutation to the object. A CEL expression is used to create the JSON patch." + }, + "patchType": { + "description": "patchType indicates the patch strategy used. Allowed values are \"ApplyConfiguration\" and \"JSONPatch\". Required.", + "type": "string" + } + }, + "required": [ + "patchType" + ], + "type": "object" + }, + "v1beta1.NamedRuleWithOperations": { + "description": "NamedRuleWithOperations is a tuple of Operations and Resources with ResourceNames.", + "properties": { + "apiGroups": { + "description": "APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required.", "items": { - "$ref": "#/definitions/v1.Condition" + "type": "string" }, "type": "array", - "x-kubernetes-list-map-keys": [ - "type" - ], - "x-kubernetes-list-type": "map" + "x-kubernetes-list-type": "atomic" }, - "observedGeneration": { - "description": "The generation observed by the controller.", - "format": "int64", - "type": "integer" + "apiVersions": { + "description": "APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" }, - "typeChecking": { - "$ref": "#/definitions/v1beta1.TypeChecking", - "description": "The results of type checking for each expression. Presence of this field indicates the completion of the type checking." + "operations": { + "description": "Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "resourceNames": { + "description": "ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "resources": { + "description": "Resources is a list of resources this rule applies to.\n\nFor example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources.\n\nIf wildcard is present, the validation rule will ensure resources do not overlap with each other.\n\nDepending on the enclosing object, subresources might not be allowed. Required.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "scope": { + "description": "scope specifies the scope of this rule. Valid values are \"Cluster\", \"Namespaced\", and \"*\" \"Cluster\" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. \"Namespaced\" means that only namespaced resources will match this rule. \"*\" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is \"*\".", + "type": "string" } }, - "type": "object" + "type": "object", + "x-kubernetes-map-type": "atomic" }, - "v1beta1.Validation": { - "description": "Validation specifies the CEL expression which is used to apply the validation.", + "v1beta1.ParamKind": { + "description": "ParamKind is a tuple of Group Kind and Version.", "properties": { - "expression": { - "description": "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources. - 'variables' - Map of composited variables, from its name to its lazily evaluated value.\n For example, a variable named 'foo' can be accessed as 'variables.foo'.\n- 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.", + "apiVersion": { + "description": "APIVersion is the API group version the resources belong to. In format of \"group/version\". Required.", "type": "string" }, - "message": { - "description": "Message represents the message displayed when validation fails. The message is required if the Expression contains line breaks. The message must not contain line breaks. If unset, the message is \"failed rule: {Rule}\". e.g. \"must be a URL with the host matching spec.host\" If the Expression contains line breaks. Message is required. The message must not contain line breaks. If unset, the message is \"failed Expression: {Expression}\".", + "kind": { + "description": "Kind is the API kind the resources belong to. Required.", + "type": "string" + } + }, + "type": "object", + "x-kubernetes-map-type": "atomic" + }, + "v1beta1.ParamRef": { + "description": "ParamRef describes how to locate the params to be used as input to expressions of rules applied by a policy binding.", + "properties": { + "name": { + "description": "name is the name of the resource being referenced.\n\nOne of `name` or `selector` must be set, but `name` and `selector` are mutually exclusive properties. If one is set, the other must be unset.\n\nA single parameter used for all admission requests can be configured by setting the `name` field, leaving `selector` blank, and setting namespace if `paramKind` is namespace-scoped.", "type": "string" }, - "messageExpression": { - "description": "messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. Since messageExpression is used as a failure message, it must evaluate to a string. If both message and messageExpression are present on a validation, then messageExpression will be used if validation fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged. messageExpression has access to all the same variables as the `expression` except for 'authorizer' and 'authorizer.requestResource'. Example: \"object.x must be less than max (\"+string(params.max)+\")\"", + "namespace": { + "description": "namespace is the namespace of the referenced resource. Allows limiting the search for params to a specific namespace. Applies to both `name` and `selector` fields.\n\nA per-namespace parameter may be used by specifying a namespace-scoped `paramKind` in the policy and leaving this field empty.\n\n- If `paramKind` is cluster-scoped, this field MUST be unset. Setting this field results in a configuration error.\n\n- If `paramKind` is namespace-scoped, the namespace of the object being evaluated for admission will be used when this field is left unset. Take care that if this is left empty the binding must not match any cluster-scoped resources, which will result in an error.", "type": "string" }, - "reason": { - "description": "Reason represents a machine-readable description of why this validation failed. If this is the first validation in the list to fail, this reason, as well as the corresponding HTTP response code, are used in the HTTP response to the client. The currently supported reasons are: \"Unauthorized\", \"Forbidden\", \"Invalid\", \"RequestEntityTooLarge\". If not set, StatusReasonInvalid is used in the response to the client.", + "parameterNotFoundAction": { + "description": "`parameterNotFoundAction` controls the behavior of the binding when the resource exists, and name or selector is valid, but there are no parameters matched by the binding. If the value is set to `Allow`, then no matched parameters will be treated as successful validation by the binding. If set to `Deny`, then no matched parameters will be subject to the `failurePolicy` of the policy.\n\nAllowed values are `Allow` or `Deny`\n\nRequired", "type": "string" + }, + "selector": { + "$ref": "#/definitions/v1.LabelSelector", + "description": "selector can be used to match multiple param objects based on their labels. Supply selector: {} to match all resources of the ParamKind.\n\nIf multiple params are found, they are all evaluated with the policy expressions and the results are ANDed together.\n\nOne of `name` or `selector` must be set, but `name` and `selector` are mutually exclusive properties. If one is set, the other must be unset." } }, - "required": [ - "expression" - ], - "type": "object" + "type": "object", + "x-kubernetes-map-type": "atomic" }, "v1beta1.Variable": { "description": "Variable is the definition of a variable that is used for composition. A variable is defined as a named expression.", @@ -2420,7 +2276,7 @@ "description": "DeploymentStatus is the most recently observed status of the Deployment.", "properties": { "availableReplicas": { - "description": "Total number of available pods (ready for at least minReadySeconds) targeted by this deployment.", + "description": "Total number of available non-terminating pods (ready for at least minReadySeconds) targeted by this deployment.", "format": "int32", "type": "integer" }, @@ -2448,12 +2304,17 @@ "type": "integer" }, "readyReplicas": { - "description": "readyReplicas is the number of pods targeted by this Deployment with a Ready Condition.", + "description": "Total number of non-terminating pods targeted by this Deployment with a Ready Condition.", "format": "int32", "type": "integer" }, "replicas": { - "description": "Total number of non-terminated pods targeted by this deployment (their labels match the selector).", + "description": "Total number of non-terminating pods targeted by this deployment (their labels match the selector).", + "format": "int32", + "type": "integer" + }, + "terminatingReplicas": { + "description": "Total number of terminating pods targeted by this deployment. Terminating pods have a non-null .metadata.deletionTimestamp and have not yet reached the Failed or Succeeded .status.phase.\n\nThis is an alpha field. Enable DeploymentReplicaSetTerminatingReplicas to be able to use this field.", "format": "int32", "type": "integer" }, @@ -2463,7 +2324,7 @@ "type": "integer" }, "updatedReplicas": { - "description": "Total number of non-terminated pods targeted by this deployment that have the desired template spec.", + "description": "Total number of non-terminating pods targeted by this deployment that have the desired template spec.", "format": "int32", "type": "integer" } @@ -2556,7 +2417,7 @@ "type": "string" }, "items": { - "description": "List of ReplicaSets. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller", + "description": "List of ReplicaSets. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset", "items": { "$ref": "#/definitions/v1.ReplicaSet" }, @@ -2592,7 +2453,7 @@ "type": "integer" }, "replicas": { - "description": "Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller", + "description": "Replicas is the number of desired pods. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset", "format": "int32", "type": "integer" }, @@ -2602,7 +2463,7 @@ }, "template": { "$ref": "#/definitions/v1.PodTemplateSpec", - "description": "Template is the object that describes the pod that will be created if insufficient replicas are detected. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template" + "description": "Template is the object that describes the pod that will be created if insufficient replicas are detected. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/#pod-template" } }, "required": [ @@ -2614,7 +2475,7 @@ "description": "ReplicaSetStatus represents the current status of a ReplicaSet.", "properties": { "availableReplicas": { - "description": "The number of available replicas (ready for at least minReadySeconds) for this replica set.", + "description": "The number of available non-terminating pods (ready for at least minReadySeconds) for this replica set.", "format": "int32", "type": "integer" }, @@ -2632,7 +2493,7 @@ "x-kubernetes-patch-strategy": "merge" }, "fullyLabeledReplicas": { - "description": "The number of pods that have labels matching the labels of the pod template of the replicaset.", + "description": "The number of non-terminating pods that have labels matching the labels of the pod template of the replicaset.", "format": "int32", "type": "integer" }, @@ -2642,12 +2503,17 @@ "type": "integer" }, "readyReplicas": { - "description": "readyReplicas is the number of pods targeted by this ReplicaSet with a Ready Condition.", + "description": "The number of non-terminating pods targeted by this ReplicaSet with a Ready Condition.", "format": "int32", "type": "integer" }, "replicas": { - "description": "Replicas is the most recently observed number of replicas. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller", + "description": "Replicas is the most recently observed number of non-terminating pods. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset", + "format": "int32", + "type": "integer" + }, + "terminatingReplicas": { + "description": "The number of terminating pods for this replica set. Terminating pods have a non-null .metadata.deletionTimestamp and have not yet reached the Failed or Succeeded .status.phase.\n\nThis is an alpha field. Enable DeploymentReplicaSetTerminatingReplicas to be able to use this field.", "format": "int32", "type": "integer" } @@ -2662,7 +2528,7 @@ "properties": { "maxSurge": { "$ref": "#/definitions/intstr.IntOrString", - "description": "The maximum number of nodes with an existing available DaemonSet pod that can have an updated DaemonSet pod during during an update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up to a minimum of 1. Default value is 0. Example: when this is set to 30%, at most 30% of the total number of nodes that should be running the daemon pod (i.e. status.desiredNumberScheduled) can have their a new pod created before the old pod is marked as deleted. The update starts by launching new pods on 30% of nodes. Once an updated pod is available (Ready for at least minReadySeconds) the old DaemonSet pod on that node is marked deleted. If the old pod becomes unavailable for any reason (Ready transitions to false, is evicted, or is drained) an updated pod is immediatedly created on that node without considering surge limits. Allowing surge implies the possibility that the resources consumed by the daemonset on any given node can double if the readiness check fails, and so resource intensive daemonsets should take into account that they may cause evictions during disruption." + "description": "The maximum number of nodes with an existing available DaemonSet pod that can have an updated DaemonSet pod during during an update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up to a minimum of 1. Default value is 0. Example: when this is set to 30%, at most 30% of the total number of nodes that should be running the daemon pod (i.e. status.desiredNumberScheduled) can have their a new pod created before the old pod is marked as deleted. The update starts by launching new pods on 30% of nodes. Once an updated pod is available (Ready for at least minReadySeconds) the old DaemonSet pod on that node is marked deleted. If the old pod becomes unavailable for any reason (Ready transitions to false, is evicted, or is drained) an updated pod is immediately created on that node without considering surge limits. Allowing surge implies the possibility that the resources consumed by the daemonset on any given node can double if the readiness check fails, and so resource intensive daemonsets should take into account that they may cause evictions during disruption." }, "maxUnavailable": { "$ref": "#/definitions/intstr.IntOrString", @@ -2834,11 +2700,11 @@ }, "ordinals": { "$ref": "#/definitions/v1.StatefulSetOrdinals", - "description": "ordinals controls the numbering of replica indices in a StatefulSet. The default ordinals behavior assigns a \"0\" index to the first replica and increments the index by one for each additional replica requested. Using the ordinals field requires the StatefulSetStartOrdinal feature gate to be enabled, which is beta." + "description": "ordinals controls the numbering of replica indices in a StatefulSet. The default ordinals behavior assigns a \"0\" index to the first replica and increments the index by one for each additional replica requested." }, "persistentVolumeClaimRetentionPolicy": { "$ref": "#/definitions/v1.StatefulSetPersistentVolumeClaimRetentionPolicy", - "description": "persistentVolumeClaimRetentionPolicy describes the lifecycle of persistent volume claims created from volumeClaimTemplates. By default, all persistent volume claims are created as needed and retained until manually deleted. This policy allows the lifecycle to be altered, for example by deleting persistent volume claims when their stateful set is deleted, or when their pod is scaled down. This requires the StatefulSetAutoDeletePVC feature gate to be enabled, which is alpha. +optional" + "description": "persistentVolumeClaimRetentionPolicy describes the lifecycle of persistent volume claims created from volumeClaimTemplates. By default, all persistent volume claims are created as needed and retained until manually deleted. This policy allows the lifecycle to be altered, for example by deleting persistent volume claims when their stateful set is deleted, or when their pod is scaled down." }, "podManagementPolicy": { "description": "podManagementPolicy controls how pods are created during initial scale up, when replacing pods on nodes, or when scaling down. The default policy is `OrderedReady`, where pods are created in increasing order (pod-0, then pod-1, etc) and the controller will wait until each pod is ready before continuing. When scaling down, the pods are removed in the opposite order. The alternative policy is `Parallel` which will create pods in parallel to match the desired scale without waiting, and on scale down will delete all pods at once.", @@ -2881,8 +2747,7 @@ }, "required": [ "selector", - "template", - "serviceName" + "template" ], "type": "object" }, @@ -3219,80 +3084,38 @@ }, "type": "object" }, - "v1alpha1.SelfSubjectReview": { - "description": "SelfSubjectReview contains the user information that the kube-apiserver has about the user making this request. When using impersonation, users will receive the user info of the user being impersonated. If impersonation or request header authentication is used, any extra keys will have their case ignored and returned as lowercase.", + "v1.FieldSelectorAttributes": { + "description": "FieldSelectorAttributes indicates a field limited access. Webhook authors are encouraged to * ensure rawSelector and requirements are not both set * consider the requirements field if set * not try to parse or consider the rawSelector field if set. This is to avoid another CVE-2022-2880 (i.e. getting different systems to agree on how exactly to parse a query is not something we want), see https://www.oxeye.io/resources/golang-parameter-smuggling-attack for more details. For the *SubjectAccessReview endpoints of the kube-apiserver: * If rawSelector is empty and requirements are empty, the request is not limited. * If rawSelector is present and requirements are empty, the rawSelector will be parsed and limited if the parsing succeeds. * If rawSelector is empty and requirements are present, the requirements should be honored * If rawSelector is present and requirements are present, the request is invalid.", "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "rawSelector": { + "description": "rawSelector is the serialization of a field selector that would be included in a query parameter. Webhook implementations are encouraged to ignore rawSelector. The kube-apiserver's *SubjectAccessReview will parse the rawSelector as long as the requirements are not present.", "type": "string" }, - "metadata": { - "$ref": "#/definitions/v1.ObjectMeta", - "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" - }, - "status": { - "$ref": "#/definitions/v1alpha1.SelfSubjectReviewStatus", - "description": "Status is filled in by the server with the user attributes." - } - }, - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "authentication.k8s.io", - "kind": "SelfSubjectReview", - "version": "v1alpha1" - } - ] - }, - "v1alpha1.SelfSubjectReviewStatus": { - "description": "SelfSubjectReviewStatus is filled by the kube-apiserver and sent back to a user.", - "properties": { - "userInfo": { - "$ref": "#/definitions/v1.UserInfo", - "description": "User attributes of the user making this request." + "requirements": { + "description": "requirements is the parsed interpretation of a field selector. All requirements must be met for a resource instance to match the selector. Webhook implementations should handle requirements, but how to handle them is up to the webhook. Since requirements can only limit the request, it is safe to authorize as unlimited request if the requirements are not understood.", + "items": { + "$ref": "#/definitions/v1.FieldSelectorRequirement" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" } }, "type": "object" }, - "v1beta1.SelfSubjectReview": { - "description": "SelfSubjectReview contains the user information that the kube-apiserver has about the user making this request. When using impersonation, users will receive the user info of the user being impersonated. If impersonation or request header authentication is used, any extra keys will have their case ignored and returned as lowercase.", + "v1.LabelSelectorAttributes": { + "description": "LabelSelectorAttributes indicates a label limited access. Webhook authors are encouraged to * ensure rawSelector and requirements are not both set * consider the requirements field if set * not try to parse or consider the rawSelector field if set. This is to avoid another CVE-2022-2880 (i.e. getting different systems to agree on how exactly to parse a query is not something we want), see https://www.oxeye.io/resources/golang-parameter-smuggling-attack for more details. For the *SubjectAccessReview endpoints of the kube-apiserver: * If rawSelector is empty and requirements are empty, the request is not limited. * If rawSelector is present and requirements are empty, the rawSelector will be parsed and limited if the parsing succeeds. * If rawSelector is empty and requirements are present, the requirements should be honored * If rawSelector is present and requirements are present, the request is invalid.", "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "rawSelector": { + "description": "rawSelector is the serialization of a field selector that would be included in a query parameter. Webhook implementations are encouraged to ignore rawSelector. The kube-apiserver's *SubjectAccessReview will parse the rawSelector as long as the requirements are not present.", "type": "string" }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "$ref": "#/definitions/v1.ObjectMeta", - "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" - }, - "status": { - "$ref": "#/definitions/v1beta1.SelfSubjectReviewStatus", - "description": "Status is filled in by the server with the user attributes." - } - }, - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "authentication.k8s.io", - "kind": "SelfSubjectReview", - "version": "v1beta1" - } - ] - }, - "v1beta1.SelfSubjectReviewStatus": { - "description": "SelfSubjectReviewStatus is filled by the kube-apiserver and sent back to a user.", - "properties": { - "userInfo": { - "$ref": "#/definitions/v1.UserInfo", - "description": "User attributes of the user making this request." + "requirements": { + "description": "requirements is the parsed interpretation of a label selector. All requirements must be met for a resource instance to match the selector. Webhook implementations should handle requirements, but how to handle them is up to the webhook. Since requirements can only limit the request, it is safe to authorize as unlimited request if the requirements are not understood.", + "items": { + "$ref": "#/definitions/v1.LabelSelectorRequirement" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" } }, "type": "object" @@ -3375,10 +3198,18 @@ "v1.ResourceAttributes": { "description": "ResourceAttributes includes the authorization attributes available for resource requests to the Authorizer interface", "properties": { + "fieldSelector": { + "$ref": "#/definitions/v1.FieldSelectorAttributes", + "description": "fieldSelector describes the limitation on access based on field. It can only limit access, not broaden it." + }, "group": { "description": "Group is the API Group of the Resource. \"*\" means all.", "type": "string" }, + "labelSelector": { + "$ref": "#/definitions/v1.LabelSelectorAttributes", + "description": "labelSelector describes the limitation on access based on labels. It can only limit access, not broaden it." + }, "name": { "description": "Name is the name of the resource being requested for a \"get\" or deleted for a \"delete\". \"\" (empty) means all.", "type": "string" @@ -4026,10 +3857,10 @@ "type": "object" }, "v2.HPAScalingRules": { - "description": "HPAScalingRules configures the scaling behavior for one direction. These Rules are applied after calculating DesiredReplicas from metrics for the HPA. They can limit the scaling velocity by specifying scaling policies. They can prevent flapping by specifying the stabilization window, so that the number of replicas is not set instantly, instead, the safest value from the stabilization window is chosen.", + "description": "HPAScalingRules configures the scaling behavior for one direction via scaling Policy Rules and a configurable metric tolerance.\n\nScaling Policy Rules are applied after calculating DesiredReplicas from metrics for the HPA. They can limit the scaling velocity by specifying scaling policies. They can prevent flapping by specifying the stabilization window, so that the number of replicas is not set instantly, instead, the safest value from the stabilization window is chosen.\n\nThe tolerance is applied to the metric values and prevents scaling too eagerly for small metric variations. (Note that setting a tolerance requires enabling the alpha HPAConfigurableTolerance feature gate.)", "properties": { "policies": { - "description": "policies is a list of potential scaling polices which can be used during scaling. At least one policy must be specified, otherwise the HPAScalingRules will be discarded as invalid", + "description": "policies is a list of potential scaling polices which can be used during scaling. If not set, use the default values: - For scale up: allow doubling the number of pods, or an absolute change of 4 pods in a 15s window. - For scale down: allow all pods to be removed in a 15s window.", "items": { "$ref": "#/definitions/v2.HPAScalingPolicy" }, @@ -4044,6 +3875,10 @@ "description": "stabilizationWindowSeconds is the number of seconds for which past recommendations should be considered while scaling up or scaling down. StabilizationWindowSeconds must be greater than or equal to zero and less than or equal to 3600 (one hour). If not set, use the default values: - For scale up: 0 (i.e. no stabilization is done). - For scale down: 300 (i.e. the stabilization window is 300 seconds long).", "format": "int32", "type": "integer" + }, + "tolerance": { + "$ref": "#/definitions/resource.Quantity", + "description": "tolerance is the tolerance on the ratio between the current and desired metric value under which no updates are made to the desired number of replicas (e.g. 0.01 for 1%). Must be greater than or equal to zero. If not set, the default cluster-wide tolerance is applied (by default 10%).\n\nFor example, if autoscaling is configured with a memory consumption target of 100Mi, and scale-down and scale-up tolerances of 5% and 1% respectively, scaling will be triggered when the actual consumption falls below 95Mi or exceeds 101Mi.\n\nThis is an alpha field and requires enabling the HPAConfigurableTolerance feature gate." } }, "type": "object" @@ -4269,7 +4104,7 @@ "properties": { "containerResource": { "$ref": "#/definitions/v2.ContainerResourceMetricSource", - "description": "containerResource refers to a resource metric (such as those specified in requests and limits) known to Kubernetes describing a single container in each pod of the current scale target (e.g. CPU or memory). Such metrics are built in to Kubernetes, and have special scaling options on top of those available to normal per-pod metrics using the \"pods\" source. This is an alpha feature and can be enabled by the HPAContainerMetrics feature flag." + "description": "containerResource refers to a resource metric (such as those specified in requests and limits) known to Kubernetes describing a single container in each pod of the current scale target (e.g. CPU or memory). Such metrics are built in to Kubernetes, and have special scaling options on top of those available to normal per-pod metrics using the \"pods\" source." }, "external": { "$ref": "#/definitions/v2.ExternalMetricSource", @@ -4288,7 +4123,7 @@ "description": "resource refers to a resource metric (such as those specified in requests and limits) known to Kubernetes describing each pod in the current scale target (e.g. CPU or memory). Such metrics are built in to Kubernetes, and have special scaling options on top of those available to normal per-pod metrics using the \"pods\" source." }, "type": { - "description": "type is the type of metric source. It should be one of \"ContainerResource\", \"External\", \"Object\", \"Pods\" or \"Resource\", each mapping to a matching field in the object. Note: \"ContainerResource\" type is available on when the feature-gate HPAContainerMetrics is enabled", + "description": "type is the type of metric source. It should be one of \"ContainerResource\", \"External\", \"Object\", \"Pods\" or \"Resource\", each mapping to a matching field in the object.", "type": "string" } }, @@ -4321,7 +4156,7 @@ "description": "resource refers to a resource metric (such as those specified in requests and limits) known to Kubernetes describing each pod in the current scale target (e.g. CPU or memory). Such metrics are built in to Kubernetes, and have special scaling options on top of those available to normal per-pod metrics using the \"pods\" source." }, "type": { - "description": "type is the type of metric source. It will be one of \"ContainerResource\", \"External\", \"Object\", \"Pods\" or \"Resource\", each corresponds to a matching field in the object. Note: \"ContainerResource\" type is available on when the feature-gate HPAContainerMetrics is enabled", + "description": "type is the type of metric source. It will be one of \"ContainerResource\", \"External\", \"Object\", \"Pods\" or \"Resource\", each corresponds to a matching field in the object.", "type": "string" } }, @@ -4743,12 +4578,12 @@ "type": "integer" }, "backoffLimit": { - "description": "Specifies the number of retries before marking this job failed. Defaults to 6", + "description": "Specifies the number of retries before marking this job failed. Defaults to 6, unless backoffLimitPerIndex (only Indexed Job) is specified. When backoffLimitPerIndex is specified, backoffLimit defaults to 2147483647.", "format": "int32", "type": "integer" }, "backoffLimitPerIndex": { - "description": "Specifies the limit for the number of retries within an index before marking this index as failed. When enabled the number of failures per index is kept in the pod's batch.kubernetes.io/job-index-failure-count annotation. It can only be set when Job's completionMode=Indexed, and the Pod's restart policy is Never. The field is immutable. This field is beta-level. It can be used when the `JobBackoffLimitPerIndex` feature gate is enabled (enabled by default).", + "description": "Specifies the limit for the number of retries within an index before marking this index as failed. When enabled the number of failures per index is kept in the pod's batch.kubernetes.io/job-index-failure-count annotation. It can only be set when Job's completionMode=Indexed, and the Pod's restart policy is Never. The field is immutable.", "format": "int32", "type": "integer" }, @@ -4762,7 +4597,7 @@ "type": "integer" }, "managedBy": { - "description": "ManagedBy field indicates the controller that manages a Job. The k8s Job controller reconciles jobs which don't have this field at all or the field value is the reserved string `kubernetes.io/job-controller`, but skips reconciling Jobs with a custom value for this field. The value must be a valid domain-prefixed path (e.g. acme.io/foo) - all characters before the first \"/\" must be a valid subdomain as defined by RFC 1123. All characters trailing the first \"/\" must be valid HTTP Path characters as defined by RFC 3986. The value cannot exceed 64 characters.\n\nThis field is alpha-level. The job controller accepts setting the field when the feature gate JobManagedBy is enabled (disabled by default).", + "description": "ManagedBy field indicates the controller that manages a Job. The k8s Job controller reconciles jobs which don't have this field at all or the field value is the reserved string `kubernetes.io/job-controller`, but skips reconciling Jobs with a custom value for this field. The value must be a valid domain-prefixed path (e.g. acme.io/foo) - all characters before the first \"/\" must be a valid subdomain as defined by RFC 1123. All characters trailing the first \"/\" must be valid HTTP Path characters as defined by RFC 3986. The value cannot exceed 63 characters. This field is immutable.\n\nThis field is beta-level. The job controller accepts setting the field when the feature gate JobManagedBy is enabled (enabled by default).", "type": "string" }, "manualSelector": { @@ -4770,7 +4605,7 @@ "type": "boolean" }, "maxFailedIndexes": { - "description": "Specifies the maximal number of failed indexes before marking the Job as failed, when backoffLimitPerIndex is set. Once the number of failed indexes exceeds this number the entire Job is marked as Failed and its execution is terminated. When left as null the job continues execution of all of its indexes and is marked with the `Complete` Job condition. It can only be specified when backoffLimitPerIndex is set. It can be null or up to completions. It is required and must be less than or equal to 10^4 when is completions greater than 10^5. This field is beta-level. It can be used when the `JobBackoffLimitPerIndex` feature gate is enabled (enabled by default).", + "description": "Specifies the maximal number of failed indexes before marking the Job as failed, when backoffLimitPerIndex is set. Once the number of failed indexes exceeds this number the entire Job is marked as Failed and its execution is terminated. When left as null the job continues execution of all of its indexes and is marked with the `Complete` Job condition. It can only be specified when backoffLimitPerIndex is set. It can be null or up to completions. It is required and must be less than or equal to 10^4 when is completions greater than 10^5.", "format": "int32", "type": "integer" }, @@ -4781,10 +4616,10 @@ }, "podFailurePolicy": { "$ref": "#/definitions/v1.PodFailurePolicy", - "description": "Specifies the policy of handling failed pods. In particular, it allows to specify the set of actions and conditions which need to be satisfied to take the associated action. If empty, the default behaviour applies - the counter of failed pods, represented by the jobs's .status.failed field, is incremented and it is checked against the backoffLimit. This field cannot be used in combination with restartPolicy=OnFailure.\n\nThis field is beta-level. It can be used when the `JobPodFailurePolicy` feature gate is enabled (enabled by default)." + "description": "Specifies the policy of handling failed pods. In particular, it allows to specify the set of actions and conditions which need to be satisfied to take the associated action. If empty, the default behaviour applies - the counter of failed pods, represented by the jobs's .status.failed field, is incremented and it is checked against the backoffLimit. This field cannot be used in combination with restartPolicy=OnFailure." }, "podReplacementPolicy": { - "description": "podReplacementPolicy specifies when to create replacement Pods. Possible values are: - TerminatingOrFailed means that we recreate pods\n when they are terminating (has a metadata.deletionTimestamp) or failed.\n- Failed means to wait until a previously created Pod is fully terminated (has phase\n Failed or Succeeded) before creating a replacement Pod.\n\nWhen using podFailurePolicy, Failed is the the only allowed value. TerminatingOrFailed and Failed are allowed values when podFailurePolicy is not in use. This is an beta field. To use this, enable the JobPodReplacementPolicy feature toggle. This is on by default.", + "description": "podReplacementPolicy specifies when to create replacement Pods. Possible values are: - TerminatingOrFailed means that we recreate pods\n when they are terminating (has a metadata.deletionTimestamp) or failed.\n- Failed means to wait until a previously created Pod is fully terminated (has phase\n Failed or Succeeded) before creating a replacement Pod.\n\nWhen using podFailurePolicy, Failed is the the only allowed value. TerminatingOrFailed and Failed are allowed values when podFailurePolicy is not in use.", "type": "string" }, "selector": { @@ -4793,7 +4628,7 @@ }, "successPolicy": { "$ref": "#/definitions/v1.SuccessPolicy", - "description": "successPolicy specifies the policy when the Job can be declared as succeeded. If empty, the default behavior applies - the Job is declared as succeeded only when the number of succeeded pods equals to the completions. When the field is specified, it must be immutable and works only for the Indexed Jobs. Once the Job meets the SuccessPolicy, the lingering pods are terminated.\n\nThis field is alpha-level. To use this field, you must enable the `JobSuccessPolicy` feature gate (disabled by default)." + "description": "successPolicy specifies the policy when the Job can be declared as succeeded. If empty, the default behavior applies - the Job is declared as succeeded only when the number of succeeded pods equals to the completions. When the field is specified, it must be immutable and works only for the Indexed Jobs. Once the Job meets the SuccessPolicy, the lingering pods are terminated." }, "suspend": { "description": "suspend specifies whether the Job controller should create Pods or not. If a Job is created with suspend set to true, no Pods are created by the Job controller. If a Job is suspended after creation (i.e. the flag goes from false to true), the Job controller will delete all active Pods associated with this Job. Users must design their workload to gracefully handle this. Suspending a Job will reset the StartTime field of the Job, effectively resetting the ActiveDeadlineSeconds timer too. Defaults to false.", @@ -4847,11 +4682,11 @@ "type": "integer" }, "failedIndexes": { - "description": "FailedIndexes holds the failed indexes when spec.backoffLimitPerIndex is set. The indexes are represented in the text format analogous as for the `completedIndexes` field, ie. they are kept as decimal integers separated by commas. The numbers are listed in increasing order. Three or more consecutive numbers are compressed and represented by the first and last element of the series, separated by a hyphen. For example, if the failed indexes are 1, 3, 4, 5 and 7, they are represented as \"1,3-5,7\". The set of failed indexes cannot overlap with the set of completed indexes.\n\nThis field is beta-level. It can be used when the `JobBackoffLimitPerIndex` feature gate is enabled (enabled by default).", + "description": "FailedIndexes holds the failed indexes when spec.backoffLimitPerIndex is set. The indexes are represented in the text format analogous as for the `completedIndexes` field, ie. they are kept as decimal integers separated by commas. The numbers are listed in increasing order. Three or more consecutive numbers are compressed and represented by the first and last element of the series, separated by a hyphen. For example, if the failed indexes are 1, 3, 4, 5 and 7, they are represented as \"1,3-5,7\". The set of failed indexes cannot overlap with the set of completed indexes.", "type": "string" }, "ready": { - "description": "The number of pods which have a Ready condition.", + "description": "The number of active pods which have a Ready condition and are not terminating (without a deletionTimestamp).", "format": "int32", "type": "integer" }, @@ -4957,7 +4792,7 @@ "description": "PodFailurePolicyRule describes how a pod failure is handled when the requirements are met. One of onExitCodes and onPodConditions, but not both, can be used in each rule.", "properties": { "action": { - "description": "Specifies the action taken on a pod failure when the requirements are satisfied. Possible values are:\n\n- FailJob: indicates that the pod's job is marked as Failed and all\n running pods are terminated.\n- FailIndex: indicates that the pod's index is marked as Failed and will\n not be restarted.\n This value is beta-level. It can be used when the\n `JobBackoffLimitPerIndex` feature gate is enabled (enabled by default).\n- Ignore: indicates that the counter towards the .backoffLimit is not\n incremented and a replacement pod is created.\n- Count: indicates that the pod is handled in the default way - the\n counter towards the .backoffLimit is incremented.\nAdditional values are considered to be added in the future. Clients should react to an unknown action by skipping the rule.", + "description": "Specifies the action taken on a pod failure when the requirements are satisfied. Possible values are:\n\n- FailJob: indicates that the pod's job is marked as Failed and all\n running pods are terminated.\n- FailIndex: indicates that the pod's index is marked as Failed and will\n not be restarted.\n- Ignore: indicates that the counter towards the .backoffLimit is not\n incremented and a replacement pod is created.\n- Count: indicates that the pod is handled in the default way - the\n counter towards the .backoffLimit is incremented.\nAdditional values are considered to be added in the future. Clients should react to an unknown action by skipping the rule.", "type": "string" }, "onExitCodes": { @@ -4982,7 +4817,7 @@ "description": "SuccessPolicy describes when a Job can be declared as succeeded based on the success of some indexes.", "properties": { "rules": { - "description": "rules represents the list of alternative rules for the declaring the Jobs as successful before `.status.succeeded >= .spec.completions`. Once any of the rules are met, the \"SucceededCriteriaMet\" condition is added, and the lingering pods are removed. The terminal state for such a Job has the \"Complete\" condition. Additionally, these rules are evaluated in order; Once the Job meets one of the rules, other rules are ignored. At most 20 elements are allowed.", + "description": "rules represents the list of alternative rules for the declaring the Jobs as successful before `.status.succeeded >= .spec.completions`. Once any of the rules are met, the \"SuccessCriteriaMet\" condition is added, and the lingering pods are removed. The terminal state for such a Job has the \"Complete\" condition. Additionally, these rules are evaluated in order; Once the Job meets one of the rules, other rules are ignored. At most 20 elements are allowed.", "items": { "$ref": "#/definitions/v1.SuccessPolicyRule" }, @@ -5303,6 +5138,259 @@ ], "type": "object" }, + "v1alpha1.PodCertificateRequest": { + "description": "PodCertificateRequest encodes a pod requesting a certificate from a given signer.\n\nKubelets use this API to implement podCertificate projected volumes", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ObjectMeta", + "description": "metadata contains the object metadata." + }, + "spec": { + "$ref": "#/definitions/v1alpha1.PodCertificateRequestSpec", + "description": "spec contains the details about the certificate being requested." + }, + "status": { + "$ref": "#/definitions/v1alpha1.PodCertificateRequestStatus", + "description": "status contains the issued certificate, and a standard set of conditions." + } + }, + "required": [ + "spec" + ], + "type": "object", + "x-kubernetes-group-version-kind": [ + { + "group": "certificates.k8s.io", + "kind": "PodCertificateRequest", + "version": "v1alpha1" + } + ] + }, + "v1alpha1.PodCertificateRequestList": { + "description": "PodCertificateRequestList is a collection of PodCertificateRequest objects", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "items": { + "description": "items is a collection of PodCertificateRequest objects", + "items": { + "$ref": "#/definitions/v1alpha1.PodCertificateRequest" + }, + "type": "array" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ListMeta", + "description": "metadata contains the list metadata." + } + }, + "required": [ + "items" + ], + "type": "object", + "x-kubernetes-group-version-kind": [ + { + "group": "certificates.k8s.io", + "kind": "PodCertificateRequestList", + "version": "v1alpha1" + } + ] + }, + "v1alpha1.PodCertificateRequestSpec": { + "description": "PodCertificateRequestSpec describes the certificate request. All fields are immutable after creation.", + "properties": { + "maxExpirationSeconds": { + "description": "maxExpirationSeconds is the maximum lifetime permitted for the certificate.\n\nIf omitted, kube-apiserver will set it to 86400(24 hours). kube-apiserver will reject values shorter than 3600 (1 hour). The maximum allowable value is 7862400 (91 days).\n\nThe signer implementation is then free to issue a certificate with any lifetime *shorter* than MaxExpirationSeconds, but no shorter than 3600 seconds (1 hour). This constraint is enforced by kube-apiserver. `kubernetes.io` signers will never issue certificates with a lifetime longer than 24 hours.", + "format": "int32", + "type": "integer" + }, + "nodeName": { + "description": "nodeName is the name of the node the pod is assigned to.", + "type": "string" + }, + "nodeUID": { + "description": "nodeUID is the UID of the node the pod is assigned to.", + "type": "string" + }, + "pkixPublicKey": { + "description": "pkixPublicKey is the PKIX-serialized public key the signer will issue the certificate to.\n\nThe key must be one of RSA3072, RSA4096, ECDSAP256, ECDSAP384, ECDSAP521, or ED25519. Note that this list may be expanded in the future.\n\nSigner implementations do not need to support all key types supported by kube-apiserver and kubelet. If a signer does not support the key type used for a given PodCertificateRequest, it must deny the request by setting a status.conditions entry with a type of \"Denied\" and a reason of \"UnsupportedKeyType\". It may also suggest a key type that it does support in the message field.", + "format": "byte", + "type": "string" + }, + "podName": { + "description": "podName is the name of the pod into which the certificate will be mounted.", + "type": "string" + }, + "podUID": { + "description": "podUID is the UID of the pod into which the certificate will be mounted.", + "type": "string" + }, + "proofOfPossession": { + "description": "proofOfPossession proves that the requesting kubelet holds the private key corresponding to pkixPublicKey.\n\nIt is contructed by signing the ASCII bytes of the pod's UID using `pkixPublicKey`.\n\nkube-apiserver validates the proof of possession during creation of the PodCertificateRequest.\n\nIf the key is an RSA key, then the signature is over the ASCII bytes of the pod UID, using RSASSA-PSS from RFC 8017 (as implemented by the golang function crypto/rsa.SignPSS with nil options).\n\nIf the key is an ECDSA key, then the signature is as described by [SEC 1, Version 2.0](https://www.secg.org/sec1-v2.pdf) (as implemented by the golang library function crypto/ecdsa.SignASN1)\n\nIf the key is an ED25519 key, the the signature is as described by the [ED25519 Specification](https://ed25519.cr.yp.to/) (as implemented by the golang library crypto/ed25519.Sign).", + "format": "byte", + "type": "string" + }, + "serviceAccountName": { + "description": "serviceAccountName is the name of the service account the pod is running as.", + "type": "string" + }, + "serviceAccountUID": { + "description": "serviceAccountUID is the UID of the service account the pod is running as.", + "type": "string" + }, + "signerName": { + "description": "signerName indicates the requested signer.\n\nAll signer names beginning with `kubernetes.io` are reserved for use by the Kubernetes project. There is currently one well-known signer documented by the Kubernetes project, `kubernetes.io/kube-apiserver-client-pod`, which will issue client certificates understood by kube-apiserver. It is currently unimplemented.", + "type": "string" + } + }, + "required": [ + "signerName", + "podName", + "podUID", + "serviceAccountName", + "serviceAccountUID", + "nodeName", + "nodeUID", + "pkixPublicKey", + "proofOfPossession" + ], + "type": "object" + }, + "v1alpha1.PodCertificateRequestStatus": { + "description": "PodCertificateRequestStatus describes the status of the request, and holds the certificate data if the request is issued.", + "properties": { + "beginRefreshAt": { + "description": "beginRefreshAt is the time at which the kubelet should begin trying to refresh the certificate. This field is set via the /status subresource, and must be set at the same time as certificateChain. Once populated, this field is immutable.\n\nThis field is only a hint. Kubelet may start refreshing before or after this time if necessary.", + "format": "date-time", + "type": "string" + }, + "certificateChain": { + "description": "certificateChain is populated with an issued certificate by the signer. This field is set via the /status subresource. Once populated, this field is immutable.\n\nIf the certificate signing request is denied, a condition of type \"Denied\" is added and this field remains empty. If the signer cannot issue the certificate, a condition of type \"Failed\" is added and this field remains empty.\n\nValidation requirements:\n 1. certificateChain must consist of one or more PEM-formatted certificates.\n 2. Each entry must be a valid PEM-wrapped, DER-encoded ASN.1 Certificate as\n described in section 4 of RFC5280.\n\nIf more than one block is present, and the definition of the requested spec.signerName does not indicate otherwise, the first block is the issued certificate, and subsequent blocks should be treated as intermediate certificates and presented in TLS handshakes. When projecting the chain into a pod volume, kubelet will drop any data in-between the PEM blocks, as well as any PEM block headers.", + "type": "string" + }, + "conditions": { + "description": "conditions applied to the request.\n\nThe types \"Issued\", \"Denied\", and \"Failed\" have special handling. At most one of these conditions may be present, and they must have status \"True\".\n\nIf the request is denied with `Reason=UnsupportedKeyType`, the signer may suggest a key type that will work in the message field.", + "items": { + "$ref": "#/definitions/v1.Condition" + }, + "type": "array", + "x-kubernetes-list-map-keys": [ + "type" + ], + "x-kubernetes-list-type": "map", + "x-kubernetes-patch-merge-key": "type", + "x-kubernetes-patch-strategy": "merge" + }, + "notAfter": { + "description": "notAfter is the time at which the certificate expires. The value must be the same as the notAfter value in the leaf certificate in certificateChain. This field is set via the /status subresource. Once populated, it is immutable. The signer must set this field at the same time it sets certificateChain.", + "format": "date-time", + "type": "string" + }, + "notBefore": { + "description": "notBefore is the time at which the certificate becomes valid. The value must be the same as the notBefore value in the leaf certificate in certificateChain. This field is set via the /status subresource. Once populated, it is immutable. The signer must set this field at the same time it sets certificateChain.", + "format": "date-time", + "type": "string" + } + }, + "type": "object" + }, + "v1beta1.ClusterTrustBundle": { + "description": "ClusterTrustBundle is a cluster-scoped container for X.509 trust anchors (root certificates).\n\nClusterTrustBundle objects are considered to be readable by any authenticated user in the cluster, because they can be mounted by pods using the `clusterTrustBundle` projection. All service accounts have read access to ClusterTrustBundles by default. Users who only have namespace-level access to a cluster can read ClusterTrustBundles by impersonating a serviceaccount that they have access to.\n\nIt can be optionally associated with a particular assigner, in which case it contains one valid set of trust anchors for that signer. Signers may have multiple associated ClusterTrustBundles; each is an independent set of trust anchors for that signer. Admission control is used to enforce that only users with permissions on the signer can create or modify the corresponding bundle.", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ObjectMeta", + "description": "metadata contains the object metadata." + }, + "spec": { + "$ref": "#/definitions/v1beta1.ClusterTrustBundleSpec", + "description": "spec contains the signer (if any) and trust anchors." + } + }, + "required": [ + "spec" + ], + "type": "object", + "x-kubernetes-group-version-kind": [ + { + "group": "certificates.k8s.io", + "kind": "ClusterTrustBundle", + "version": "v1beta1" + } + ] + }, + "v1beta1.ClusterTrustBundleList": { + "description": "ClusterTrustBundleList is a collection of ClusterTrustBundle objects", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "items": { + "description": "items is a collection of ClusterTrustBundle objects", + "items": { + "$ref": "#/definitions/v1beta1.ClusterTrustBundle" + }, + "type": "array" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ListMeta", + "description": "metadata contains the list metadata." + } + }, + "required": [ + "items" + ], + "type": "object", + "x-kubernetes-group-version-kind": [ + { + "group": "certificates.k8s.io", + "kind": "ClusterTrustBundleList", + "version": "v1beta1" + } + ] + }, + "v1beta1.ClusterTrustBundleSpec": { + "description": "ClusterTrustBundleSpec contains the signer and trust anchors.", + "properties": { + "signerName": { + "description": "signerName indicates the associated signer, if any.\n\nIn order to create or update a ClusterTrustBundle that sets signerName, you must have the following cluster-scoped permission: group=certificates.k8s.io resource=signers resourceName= verb=attest.\n\nIf signerName is not empty, then the ClusterTrustBundle object must be named with the signer name as a prefix (translating slashes to colons). For example, for the signer name `example.com/foo`, valid ClusterTrustBundle object names include `example.com:foo:abc` and `example.com:foo:v1`.\n\nIf signerName is empty, then the ClusterTrustBundle object's name must not have such a prefix.\n\nList/watch requests for ClusterTrustBundles can filter on this field using a `spec.signerName=NAME` field selector.", + "type": "string" + }, + "trustBundle": { + "description": "trustBundle contains the individual X.509 trust anchors for this bundle, as PEM bundle of PEM-wrapped, DER-formatted X.509 certificates.\n\nThe data must consist only of PEM certificate blocks that parse as valid X.509 certificates. Each certificate must include a basic constraints extension with the CA bit set. The API server will reject objects that contain duplicate certificates, or that use PEM block headers.\n\nUsers of ClusterTrustBundles, including Kubelet, are free to reorder and deduplicate certificate blocks in this file according to their own logic, as well as to drop PEM block headers and inter-block data.", + "type": "string" + } + }, + "required": [ + "trustBundle" + ], + "type": "object" + }, "v1.Lease": { "description": "Lease defines a lease concept.", "properties": { @@ -5376,11 +5464,11 @@ "type": "string" }, "holderIdentity": { - "description": "holderIdentity contains the identity of the holder of a current lease.", + "description": "holderIdentity contains the identity of the holder of a current lease. If Coordinated Leader Election is used, the holder identity must be equal to the elected LeaseCandidate.metadata.name field.", "type": "string" }, "leaseDurationSeconds": { - "description": "leaseDurationSeconds is a duration that candidates for a lease need to wait to force acquire it. This is measure against time of last observed renewTime.", + "description": "leaseDurationSeconds is a duration that candidates for a lease need to wait to force acquire it. This is measured against the time of last observed renewTime.", "format": "int32", "type": "integer" }, @@ -5389,12 +5477,222 @@ "format": "int32", "type": "integer" }, + "preferredHolder": { + "description": "PreferredHolder signals to a lease holder that the lease has a more optimal holder and should be given up. This field can only be set if Strategy is also set.", + "type": "string" + }, "renewTime": { "description": "renewTime is a time when the current holder of a lease has last updated the lease.", "format": "date-time", "type": "string" + }, + "strategy": { + "description": "Strategy indicates the strategy for picking the leader for coordinated leader election. If the field is not specified, there is no active coordination for this lease. (Alpha) Using this field requires the CoordinatedLeaderElection feature gate to be enabled.", + "type": "string" + } + }, + "type": "object" + }, + "v1alpha2.LeaseCandidate": { + "description": "LeaseCandidate defines a candidate for a Lease object. Candidates are created such that coordinated leader election will pick the best leader from the list of candidates.", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ObjectMeta", + "description": "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" + }, + "spec": { + "$ref": "#/definitions/v1alpha2.LeaseCandidateSpec", + "description": "spec contains the specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" + } + }, + "type": "object", + "x-kubernetes-group-version-kind": [ + { + "group": "coordination.k8s.io", + "kind": "LeaseCandidate", + "version": "v1alpha2" + } + ] + }, + "v1alpha2.LeaseCandidateList": { + "description": "LeaseCandidateList is a list of Lease objects.", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "items": { + "description": "items is a list of schema objects.", + "items": { + "$ref": "#/definitions/v1alpha2.LeaseCandidate" + }, + "type": "array" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ListMeta", + "description": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" + } + }, + "required": [ + "items" + ], + "type": "object", + "x-kubernetes-group-version-kind": [ + { + "group": "coordination.k8s.io", + "kind": "LeaseCandidateList", + "version": "v1alpha2" + } + ] + }, + "v1alpha2.LeaseCandidateSpec": { + "description": "LeaseCandidateSpec is a specification of a Lease.", + "properties": { + "binaryVersion": { + "description": "BinaryVersion is the binary version. It must be in a semver format without leading `v`. This field is required.", + "type": "string" + }, + "emulationVersion": { + "description": "EmulationVersion is the emulation version. It must be in a semver format without leading `v`. EmulationVersion must be less than or equal to BinaryVersion. This field is required when strategy is \"OldestEmulationVersion\"", + "type": "string" + }, + "leaseName": { + "description": "LeaseName is the name of the lease for which this candidate is contending. This field is immutable.", + "type": "string" + }, + "pingTime": { + "description": "PingTime is the last time that the server has requested the LeaseCandidate to renew. It is only done during leader election to check if any LeaseCandidates have become ineligible. When PingTime is updated, the LeaseCandidate will respond by updating RenewTime.", + "format": "date-time", + "type": "string" + }, + "renewTime": { + "description": "RenewTime is the time that the LeaseCandidate was last updated. Any time a Lease needs to do leader election, the PingTime field is updated to signal to the LeaseCandidate that they should update the RenewTime. Old LeaseCandidate objects are also garbage collected if it has been hours since the last renew. The PingTime field is updated regularly to prevent garbage collection for still active LeaseCandidates.", + "format": "date-time", + "type": "string" + }, + "strategy": { + "description": "Strategy is the strategy that coordinated leader election will use for picking the leader. If multiple candidates for the same Lease return different strategies, the strategy provided by the candidate with the latest BinaryVersion will be used. If there is still conflict, this is a user error and coordinated leader election will not operate the Lease until resolved.", + "type": "string" } }, + "required": [ + "leaseName", + "binaryVersion", + "strategy" + ], + "type": "object" + }, + "v1beta1.LeaseCandidate": { + "description": "LeaseCandidate defines a candidate for a Lease object. Candidates are created such that coordinated leader election will pick the best leader from the list of candidates.", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ObjectMeta", + "description": "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" + }, + "spec": { + "$ref": "#/definitions/v1beta1.LeaseCandidateSpec", + "description": "spec contains the specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" + } + }, + "type": "object", + "x-kubernetes-group-version-kind": [ + { + "group": "coordination.k8s.io", + "kind": "LeaseCandidate", + "version": "v1beta1" + } + ] + }, + "v1beta1.LeaseCandidateList": { + "description": "LeaseCandidateList is a list of Lease objects.", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "items": { + "description": "items is a list of schema objects.", + "items": { + "$ref": "#/definitions/v1beta1.LeaseCandidate" + }, + "type": "array" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ListMeta", + "description": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" + } + }, + "required": [ + "items" + ], + "type": "object", + "x-kubernetes-group-version-kind": [ + { + "group": "coordination.k8s.io", + "kind": "LeaseCandidateList", + "version": "v1beta1" + } + ] + }, + "v1beta1.LeaseCandidateSpec": { + "description": "LeaseCandidateSpec is a specification of a Lease.", + "properties": { + "binaryVersion": { + "description": "BinaryVersion is the binary version. It must be in a semver format without leading `v`. This field is required.", + "type": "string" + }, + "emulationVersion": { + "description": "EmulationVersion is the emulation version. It must be in a semver format without leading `v`. EmulationVersion must be less than or equal to BinaryVersion. This field is required when strategy is \"OldestEmulationVersion\"", + "type": "string" + }, + "leaseName": { + "description": "LeaseName is the name of the lease for which this candidate is contending. The limits on this field are the same as on Lease.name. Multiple lease candidates may reference the same Lease.name. This field is immutable.", + "type": "string" + }, + "pingTime": { + "description": "PingTime is the last time that the server has requested the LeaseCandidate to renew. It is only done during leader election to check if any LeaseCandidates have become ineligible. When PingTime is updated, the LeaseCandidate will respond by updating RenewTime.", + "format": "date-time", + "type": "string" + }, + "renewTime": { + "description": "RenewTime is the time that the LeaseCandidate was last updated. Any time a Lease needs to do leader election, the PingTime field is updated to signal to the LeaseCandidate that they should update the RenewTime. Old LeaseCandidate objects are also garbage collected if it has been hours since the last renew. The PingTime field is updated regularly to prevent garbage collection for still active LeaseCandidates.", + "format": "date-time", + "type": "string" + }, + "strategy": { + "description": "Strategy is the strategy that coordinated leader election will use for picking the leader. If multiple candidates for the same Lease return different strategies, the strategy provided by the candidate with the latest BinaryVersion will be used. If there is still conflict, this is a user error and coordinated leader election will not operate the Lease until resolved.", + "type": "string" + } + }, + "required": [ + "leaseName", + "binaryVersion", + "strategy" + ], "type": "object" }, "v1.AWSElasticBlockStoreVolumeSource": { @@ -5567,7 +5865,7 @@ "type": "object" }, "v1.Binding": { - "description": "Binding ties one object to another; for example, a pod is bound to a node by a scheduler. Deprecated in 1.7, please use the bindings subresource of pods instead.", + "description": "Binding ties one object to another; for example, a pod is bound to a node by a scheduler.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -5599,7 +5897,7 @@ ] }, "v1.CSIPersistentVolumeSource": { - "description": "Represents storage that is managed by an external CSI volume driver (Beta feature)", + "description": "Represents storage that is managed by an external CSI volume driver", "properties": { "controllerExpandSecretRef": { "$ref": "#/definitions/v1.SecretReference", @@ -5829,20 +6127,6 @@ ], "type": "object" }, - "v1.ClaimSource": { - "description": "ClaimSource describes a reference to a ResourceClaim.\n\nExactly one of these fields should be set. Consumers of this type must treat an empty object as if it has an unknown value.", - "properties": { - "resourceClaimName": { - "description": "ResourceClaimName is the name of a ResourceClaim object in the same namespace as this pod.", - "type": "string" - }, - "resourceClaimTemplateName": { - "description": "ResourceClaimTemplateName is the name of a ResourceClaimTemplate object in the same namespace as this pod.\n\nThe template will be used to create a new ResourceClaim, which will be bound to this pod. When this pod is deleted, the ResourceClaim will also be deleted. The pod name and resource name, along with a generated component, will be used to form a unique name for the ResourceClaim, which will be recorded in pod.status.resourceClaimStatuses.\n\nThis field is immutable and no changes will be made to the corresponding ResourceClaim by the control plane after creating the ResourceClaim.", - "type": "string" - } - }, - "type": "object" - }, "v1.ClientIPConfig": { "description": "ClientIPConfig represents the configurations of Client IP based session affinity.", "properties": { @@ -6030,7 +6314,7 @@ "description": "ConfigMapEnvSource selects a ConfigMap to populate the environment variables with.\n\nThe contents of the target ConfigMap's Data field will represent the key-value pairs as environment variables.", "properties": { "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", + "description": "Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", "type": "string" }, "optional": { @@ -6048,7 +6332,7 @@ "type": "string" }, "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", + "description": "Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", "type": "string" }, "optional": { @@ -6140,7 +6424,7 @@ "x-kubernetes-list-type": "atomic" }, "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", + "description": "Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", "type": "string" }, "optional": { @@ -6167,7 +6451,7 @@ "x-kubernetes-list-type": "atomic" }, "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", + "description": "Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", "type": "string" }, "optional": { @@ -6210,7 +6494,7 @@ "x-kubernetes-patch-strategy": "merge" }, "envFrom": { - "description": "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", + "description": "List of sources to populate environment variables in the container. The keys defined within a source may consist of any printable ASCII characters except '='. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", "items": { "$ref": "#/definitions/v1.EnvFromSource" }, @@ -6268,9 +6552,17 @@ "description": "Compute Resources required by this container. Cannot be updated. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/" }, "restartPolicy": { - "description": "RestartPolicy defines the restart behavior of individual containers in a pod. This field may only be set for init containers, and the only allowed value is \"Always\". For non-init containers or when this field is not specified, the restart behavior is defined by the Pod's restart policy and the container type. Setting the RestartPolicy as \"Always\" for the init container will have the following effect: this init container will be continually restarted on exit until all regular containers have terminated. Once all regular containers have completed, all init containers with restartPolicy \"Always\" will be shut down. This lifecycle differs from normal init containers and is often referred to as a \"sidecar\" container. Although this init container still starts in the init container sequence, it does not wait for the container to complete before proceeding to the next init container. Instead, the next init container starts immediately after this init container is started, or after any startupProbe has successfully completed.", + "description": "RestartPolicy defines the restart behavior of individual containers in a pod. This overrides the pod-level restart policy. When this field is not specified, the restart behavior is defined by the Pod's restart policy and the container type. Additionally, setting the RestartPolicy as \"Always\" for the init container will have the following effect: this init container will be continually restarted on exit until all regular containers have terminated. Once all regular containers have completed, all init containers with restartPolicy \"Always\" will be shut down. This lifecycle differs from normal init containers and is often referred to as a \"sidecar\" container. Although this init container still starts in the init container sequence, it does not wait for the container to complete before proceeding to the next init container. Instead, the next init container starts immediately after this init container is started, or after any startupProbe has successfully completed.", "type": "string" }, + "restartPolicyRules": { + "description": "Represents a list of rules to be checked to determine if the container should be restarted on exit. The rules are evaluated in order. Once a rule matches a container exit condition, the remaining rules are ignored. If no rule matches the container exit condition, the Container-level restart policy determines the whether the container is restarted or not. Constraints on the rules: - At most 20 rules are allowed. - Rules can have the same action. - Identical rules are not forbidden in validations. When rules are specified, container MUST set RestartPolicy explicitly even it if matches the Pod's RestartPolicy.", + "items": { + "$ref": "#/definitions/v1.ContainerRestartRule" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, "securityContext": { "$ref": "#/definitions/v1.SecurityContext", "description": "SecurityContext defines the security options the container should be run with. If set, the fields of SecurityContext override the equivalent fields of PodSecurityContext. More info: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/" @@ -6335,6 +6627,29 @@ ], "type": "object" }, + "v1.ContainerExtendedResourceRequest": { + "description": "ContainerExtendedResourceRequest has the mapping of container name, extended resource name to the device request name.", + "properties": { + "containerName": { + "description": "The name of the container requesting resources.", + "type": "string" + }, + "requestName": { + "description": "The name of the request in the special ResourceClaim which corresponds to the extended resource.", + "type": "string" + }, + "resourceName": { + "description": "The name of the extended resource in that container which gets backed by DRA.", + "type": "string" + } + }, + "required": [ + "containerName", + "resourceName", + "requestName" + ], + "type": "object" + }, "v1.ContainerImage": { "description": "Describe a container image", "properties": { @@ -6403,6 +6718,45 @@ ], "type": "object" }, + "v1.ContainerRestartRule": { + "description": "ContainerRestartRule describes how a container exit is handled.", + "properties": { + "action": { + "description": "Specifies the action taken on a container exit if the requirements are satisfied. The only possible value is \"Restart\" to restart the container.", + "type": "string" + }, + "exitCodes": { + "$ref": "#/definitions/v1.ContainerRestartRuleOnExitCodes", + "description": "Represents the exit codes to check on container exits." + } + }, + "required": [ + "action" + ], + "type": "object" + }, + "v1.ContainerRestartRuleOnExitCodes": { + "description": "ContainerRestartRuleOnExitCodes describes the condition for handling an exited container based on its exit codes.", + "properties": { + "operator": { + "description": "Represents the relationship between the container exit code(s) and the specified values. Possible values are: - In: the requirement is satisfied if the container exit code is in the\n set of specified values.\n- NotIn: the requirement is satisfied if the container exit code is\n not in the set of specified values.", + "type": "string" + }, + "values": { + "description": "Specifies the set of values to check for container exit codes. At most 255 elements are allowed.", + "items": { + "format": "int32", + "type": "integer" + }, + "type": "array", + "x-kubernetes-list-type": "set" + } + }, + "required": [ + "operator" + ], + "type": "object" + }, "v1.ContainerState": { "description": "ContainerState holds a possible state of container. Only one of its members may be specified. If none of them is specified, the default one is ContainerStateWaiting.", "properties": { @@ -6497,6 +6851,19 @@ "description": "AllocatedResources represents the compute resources allocated for this container by the node. Kubelet sets this value to Container.Resources.Requests upon successful pod admission and after successfully admitting desired pod resize.", "type": "object" }, + "allocatedResourcesStatus": { + "description": "AllocatedResourcesStatus represents the status of various resources allocated for this Pod.", + "items": { + "$ref": "#/definitions/v1.ResourceStatus" + }, + "type": "array", + "x-kubernetes-list-map-keys": [ + "name" + ], + "x-kubernetes-list-type": "map", + "x-kubernetes-patch-merge-key": "name", + "x-kubernetes-patch-strategy": "merge" + }, "containerID": { "description": "ContainerID is the ID of the container in the format '://'. Where type is a container runtime identifier, returned from Version call of CRI API (for example \"containerd\").", "type": "string" @@ -6538,6 +6905,14 @@ "$ref": "#/definitions/v1.ContainerState", "description": "State holds details about the container's current condition." }, + "stopSignal": { + "description": "StopSignal reports the effective stop signal for this container", + "type": "string" + }, + "user": { + "$ref": "#/definitions/v1.ContainerUser", + "description": "User represents user identity information initially attached to the first process of the container" + }, "volumeMounts": { "description": "Status of volume mounts.", "items": { @@ -6561,6 +6936,16 @@ ], "type": "object" }, + "v1.ContainerUser": { + "description": "ContainerUser represents user identity information", + "properties": { + "linux": { + "$ref": "#/definitions/v1.LinuxContainerUser", + "description": "Linux holds user identity information initially attached to the first process of the containers in Linux. Note that the actual running identity can be changed if the process has enough privilege to do so." + } + }, + "type": "object" + }, "v1.DaemonEndpoint": { "description": "DaemonEndpoint contains information about a single Daemon endpoint.", "properties": { @@ -6649,7 +7034,7 @@ "type": "object" }, "v1.EndpointAddress": { - "description": "EndpointAddress is a tuple that describes single IP address.", + "description": "EndpointAddress is a tuple that describes single IP address. Deprecated: This API is deprecated in v1.33+.", "properties": { "hostname": { "description": "The Hostname of this endpoint", @@ -6675,7 +7060,7 @@ "x-kubernetes-map-type": "atomic" }, "core.v1.EndpointPort": { - "description": "EndpointPort is a tuple that describes a single port.", + "description": "EndpointPort is a tuple that describes a single port. Deprecated: This API is deprecated in v1.33+.", "properties": { "appProtocol": { "description": "The application protocol for this port. This is used as a hint for implementations to offer richer behavior for protocols that they understand. This field follows standard Kubernetes label syntax. Valid values are either:\n\n* Un-prefixed protocol names - reserved for IANA standard service names (as per RFC-6335 and https://www.iana.org/assignments/service-names).\n\n* Kubernetes-defined prefixed names:\n * 'kubernetes.io/h2c' - HTTP/2 prior knowledge over cleartext as described in https://www.rfc-editor.org/rfc/rfc9113.html#name-starting-http-2-with-prior-\n * 'kubernetes.io/ws' - WebSocket over cleartext as described in https://www.rfc-editor.org/rfc/rfc6455\n * 'kubernetes.io/wss' - WebSocket over TLS as described in https://www.rfc-editor.org/rfc/rfc6455\n\n* Other protocols should use implementation-defined prefixed names such as mycompany.com/my-custom-protocol.", @@ -6702,7 +7087,7 @@ "x-kubernetes-map-type": "atomic" }, "v1.EndpointSubset": { - "description": "EndpointSubset is a group of addresses with a common set of ports. The expanded set of endpoints is the Cartesian product of Addresses x Ports. For example, given:\n\n\t{\n\t Addresses: [{\"ip\": \"10.10.1.1\"}, {\"ip\": \"10.10.2.2\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 8675}, {\"name\": \"b\", \"port\": 309}]\n\t}\n\nThe resulting set of endpoints can be viewed as:\n\n\ta: [ 10.10.1.1:8675, 10.10.2.2:8675 ],\n\tb: [ 10.10.1.1:309, 10.10.2.2:309 ]", + "description": "EndpointSubset is a group of addresses with a common set of ports. The expanded set of endpoints is the Cartesian product of Addresses x Ports. For example, given:\n\n\t{\n\t Addresses: [{\"ip\": \"10.10.1.1\"}, {\"ip\": \"10.10.2.2\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 8675}, {\"name\": \"b\", \"port\": 309}]\n\t}\n\nThe resulting set of endpoints can be viewed as:\n\n\ta: [ 10.10.1.1:8675, 10.10.2.2:8675 ],\n\tb: [ 10.10.1.1:309, 10.10.2.2:309 ]\n\nDeprecated: This API is deprecated in v1.33+.", "properties": { "addresses": { "description": "IP addresses which offer the related ports that are marked as ready. These endpoints should be considered safe for load balancers and clients to utilize.", @@ -6732,7 +7117,7 @@ "type": "object" }, "v1.Endpoints": { - "description": "Endpoints is a collection of endpoints that implement the actual service. Example:\n\n\t Name: \"mysvc\",\n\t Subsets: [\n\t {\n\t Addresses: [{\"ip\": \"10.10.1.1\"}, {\"ip\": \"10.10.2.2\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 8675}, {\"name\": \"b\", \"port\": 309}]\n\t },\n\t {\n\t Addresses: [{\"ip\": \"10.10.3.3\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 93}, {\"name\": \"b\", \"port\": 76}]\n\t },\n\t]", + "description": "Endpoints is a collection of endpoints that implement the actual service. Example:\n\n\t Name: \"mysvc\",\n\t Subsets: [\n\t {\n\t Addresses: [{\"ip\": \"10.10.1.1\"}, {\"ip\": \"10.10.2.2\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 8675}, {\"name\": \"b\", \"port\": 309}]\n\t },\n\t {\n\t Addresses: [{\"ip\": \"10.10.3.3\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 93}, {\"name\": \"b\", \"port\": 76}]\n\t },\n\t]\n\nEndpoints is a legacy API and does not contain information about all Service features. Use discoveryv1.EndpointSlice for complete information about Service endpoints.\n\nDeprecated: This API is deprecated in v1.33+. Use discoveryv1.EndpointSlice.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -6765,7 +7150,7 @@ ] }, "v1.EndpointsList": { - "description": "EndpointsList is a list of endpoints.", + "description": "EndpointsList is a list of endpoints. Deprecated: This API is deprecated in v1.33+.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -6800,14 +7185,14 @@ ] }, "v1.EnvFromSource": { - "description": "EnvFromSource represents the source of a set of ConfigMaps", + "description": "EnvFromSource represents the source of a set of ConfigMaps or Secrets", "properties": { "configMapRef": { "$ref": "#/definitions/v1.ConfigMapEnvSource", "description": "The ConfigMap to select from" }, "prefix": { - "description": "An optional identifier to prepend to each key in the ConfigMap. Must be a C_IDENTIFIER.", + "description": "Optional text to prepend to the name of each environment variable. May consist of any printable ASCII characters except '='.", "type": "string" }, "secretRef": { @@ -6821,7 +7206,7 @@ "description": "EnvVar represents an environment variable present in a Container.", "properties": { "name": { - "description": "Name of the environment variable. Must be a C_IDENTIFIER.", + "description": "Name of the environment variable. May consist of any printable ASCII characters except '='.", "type": "string" }, "value": { @@ -6849,6 +7234,10 @@ "$ref": "#/definitions/v1.ObjectFieldSelector", "description": "Selects a field of the pod: supports metadata.name, metadata.namespace, `metadata.labels['']`, `metadata.annotations['']`, spec.nodeName, spec.serviceAccountName, status.hostIP, status.podIP, status.podIPs." }, + "fileKeyRef": { + "$ref": "#/definitions/v1.FileKeySelector", + "description": "FileKeyRef selects a key of the env file. Requires the EnvFiles feature gate to be enabled." + }, "resourceFieldRef": { "$ref": "#/definitions/v1.ResourceFieldSelector", "description": "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, limits.ephemeral-storage, requests.cpu, requests.memory and requests.ephemeral-storage) are currently supported." @@ -6893,7 +7282,7 @@ "x-kubernetes-patch-strategy": "merge" }, "envFrom": { - "description": "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", + "description": "List of sources to populate environment variables in the container. The keys defined within a source may consist of any printable ASCII characters except '='. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", "items": { "$ref": "#/definitions/v1.EnvFromSource" }, @@ -6951,9 +7340,17 @@ "description": "Resources are not allowed for ephemeral containers. Ephemeral containers use spare resources already allocated to the pod." }, "restartPolicy": { - "description": "Restart policy for the container to manage the restart behavior of each container within a pod. This may only be set for init containers. You cannot set this field on ephemeral containers.", + "description": "Restart policy for the container to manage the restart behavior of each container within a pod. You cannot set this field on ephemeral containers.", "type": "string" }, + "restartPolicyRules": { + "description": "Represents a list of rules to be checked to determine if the container should be restarted on exit. You cannot set this field on ephemeral containers.", + "items": { + "$ref": "#/definitions/v1.ContainerRestartRule" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, "securityContext": { "$ref": "#/definitions/v1.SecurityContext", "description": "Optional: SecurityContext defines the security options the ephemeral container should be run with. If set, the fields of SecurityContext override the equivalent fields of PodSecurityContext." @@ -7235,6 +7632,34 @@ }, "type": "object" }, + "v1.FileKeySelector": { + "description": "FileKeySelector selects a key of the env file.", + "properties": { + "key": { + "description": "The key within the env file. An invalid key will prevent the pod from starting. The keys defined within a source may consist of any printable ASCII characters except '='. During Alpha stage of the EnvFiles feature gate, the key size is limited to 128 characters.", + "type": "string" + }, + "optional": { + "description": "Specify whether the file or its key must be defined. If the file or key does not exist, then the env var is not published. If optional is set to true and the specified key does not exist, the environment variable will not be set in the Pod's containers.\n\nIf optional is set to false and the specified key does not exist, an error will be returned during Pod creation.", + "type": "boolean" + }, + "path": { + "description": "The path within the volume from which to select the file. Must be relative and may not contain the '..' path or start with '..'.", + "type": "string" + }, + "volumeName": { + "description": "The name of the volume mount containing the env file.", + "type": "string" + } + }, + "required": [ + "volumeName", + "path", + "key" + ], + "type": "object", + "x-kubernetes-map-type": "atomic" + }, "v1.FlexPersistentVolumeSource": { "description": "FlexPersistentVolumeSource represents a generic persistent volume resource that is provisioned/attached using an exec based plugin.", "properties": { @@ -7340,6 +7765,7 @@ "type": "object" }, "v1.GRPCAction": { + "description": "GRPCAction specifies an action involving a GRPC service.", "properties": { "port": { "description": "Port number of the gRPC service. Number must be in the range 1 to 65535.", @@ -7407,7 +7833,7 @@ "description": "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.", "properties": { "endpoints": { - "description": "endpoints is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", + "description": "endpoints is the endpoint name that details Glusterfs topology.", "type": "string" }, "path": { @@ -7492,6 +7918,9 @@ "type": "string" } }, + "required": [ + "ip" + ], "type": "object" }, "v1.HostIP": { @@ -7502,6 +7931,9 @@ "type": "string" } }, + "required": [ + "ip" + ], "type": "object" }, "v1.HostPathVolumeSource": { @@ -7641,6 +8073,20 @@ ], "type": "object" }, + "v1.ImageVolumeSource": { + "description": "ImageVolumeSource represents a image volume resource.", + "properties": { + "pullPolicy": { + "description": "Policy for pulling OCI objects. Possible values are: Always: the kubelet always attempts to pull the reference. Container creation will fail If the pull fails. Never: the kubelet never pulls the reference and only uses a local image or artifact. Container creation will fail if the reference isn't present. IfNotPresent: the kubelet pulls if the reference isn't already present on disk. Container creation will fail if the reference isn't present and the pull fails. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise.", + "type": "string" + }, + "reference": { + "description": "Required: Image or artifact reference to be used. Behaves in the same way as pod.spec.containers[*].image. Pull secrets will be assembled in the same way as for the container image by looking up node credentials, SA image pull secrets, and pod spec image pull secrets. More info: https://kubernetes.io/docs/concepts/containers/images This field is optional to allow higher level config management to default or override container images in workload controllers like Deployments and StatefulSets.", + "type": "string" + } + }, + "type": "object" + }, "v1.KeyToPath": { "description": "Maps a string key to a path within a volume.", "properties": { @@ -7674,6 +8120,10 @@ "preStop": { "$ref": "#/definitions/v1.LifecycleHandler", "description": "PreStop is called immediately before a container is terminated due to an API request or management event such as liveness/startup probe failure, preemption, resource contention, etc. The handler is not called if the container crashes or exits. The Pod's termination grace period countdown begins before the PreStop hook is executed. Regardless of the outcome of the handler, the container will eventually terminate within the Pod's termination grace period (unless delayed by finalizers). Other management of the container blocks until the hook completes or until the termination grace period is reached. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks" + }, + "stopSignal": { + "description": "StopSignal defines which signal will be sent to a container when it is being stopped. If not specified, the default is defined by the container runtime in use. StopSignal can only be set for Pods with a non-empty .spec.os.name", + "type": "string" } }, "type": "object" @@ -7683,19 +8133,19 @@ "properties": { "exec": { "$ref": "#/definitions/v1.ExecAction", - "description": "Exec specifies the action to take." + "description": "Exec specifies a command to execute in the container." }, "httpGet": { "$ref": "#/definitions/v1.HTTPGetAction", - "description": "HTTPGet specifies the http request to perform." + "description": "HTTPGet specifies an HTTP GET request to perform." }, "sleep": { "$ref": "#/definitions/v1.SleepAction", - "description": "Sleep represents the duration that the container should sleep before being terminated." + "description": "Sleep represents a duration that the container should sleep." }, "tcpSocket": { "$ref": "#/definitions/v1.TCPSocketAction", - "description": "Deprecated. TCPSocket is NOT supported as a LifecycleHandler and kept for the backward compatibility. There are no validation of this field and lifecycle hooks will fail in runtime when tcp handler is specified." + "description": "Deprecated. TCPSocket is NOT supported as a LifecycleHandler and kept for backward compatibility. There is no validation of this field and lifecycle hooks will fail at runtime when it is specified." } }, "type": "object" @@ -7829,6 +8279,35 @@ ], "type": "object" }, + "v1.LinuxContainerUser": { + "description": "LinuxContainerUser represents user identity information in Linux containers", + "properties": { + "gid": { + "description": "GID is the primary gid initially attached to the first process in the container", + "format": "int64", + "type": "integer" + }, + "supplementalGroups": { + "description": "SupplementalGroups are the supplemental groups initially attached to the first process in the container", + "items": { + "format": "int64", + "type": "integer" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "uid": { + "description": "UID is the primary uid initially attached to the first process in the container", + "format": "int64", + "type": "integer" + } + }, + "required": [ + "uid", + "gid" + ], + "type": "object" + }, "v1.LoadBalancerIngress": { "description": "LoadBalancerIngress represents the status of a load-balancer ingress point: traffic intended for the service should be sent to an ingress point.", "properties": { @@ -7873,7 +8352,7 @@ "description": "LocalObjectReference contains enough information to let you locate the referenced object inside the same namespace.", "properties": { "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", + "description": "Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", "type": "string" } }, @@ -7881,7 +8360,7 @@ "x-kubernetes-map-type": "atomic" }, "v1.LocalVolumeSource": { - "description": "Local represents directly-attached storage with node affinity (Beta feature)", + "description": "Local represents directly-attached storage with node affinity", "properties": { "fsType": { "description": "fsType is the filesystem type to mount. It applies only when the Path is a block device. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default value is to auto-select a filesystem if unspecified.", @@ -7973,14 +8452,16 @@ "description": "NamespaceCondition contains details about state of namespace.", "properties": { "lastTransitionTime": { - "description": "Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.", + "description": "Last time the condition transitioned from one status to another.", "format": "date-time", "type": "string" }, "message": { + "description": "Human-readable message indicating details about last transition.", "type": "string" }, "reason": { + "description": "Unique, one-word, CamelCase reason for the condition's last transition.", "type": "string" }, "status": { @@ -8217,6 +8698,16 @@ }, "type": "object" }, + "v1.NodeFeatures": { + "description": "NodeFeatures describes the set of features implemented by the CRI implementation. The features contained in the NodeFeatures should depend only on the cri implementation independent of runtime handlers.", + "properties": { + "supplementalGroupsPolicy": { + "description": "SupplementalGroupsPolicy is set to true if the runtime supports SupplementalGroupsPolicy and ContainerUser.", + "type": "boolean" + } + }, + "type": "object" + }, "v1.NodeList": { "description": "NodeList is the whole list of all Nodes which have been registered with master.", "properties": { @@ -8267,11 +8758,15 @@ "type": "object" }, "v1.NodeRuntimeHandlerFeatures": { - "description": "NodeRuntimeHandlerFeatures is a set of runtime features.", + "description": "NodeRuntimeHandlerFeatures is a set of features implemented by the runtime handler.", "properties": { "recursiveReadOnlyMounts": { "description": "RecursiveReadOnlyMounts is set to true if the runtime handler supports RecursiveReadOnlyMounts.", "type": "boolean" + }, + "userNamespaces": { + "description": "UserNamespaces is set to true if the runtime handler supports UserNamespaces, including for volumes.", + "type": "boolean" } }, "type": "object" @@ -8390,7 +8885,7 @@ "description": "NodeStatus is information about the current status of a node.", "properties": { "addresses": { - "description": "List of addresses reachable to the node. Queried from cloud provider, if available. More info: https://kubernetes.io/docs/concepts/nodes/node/#addresses Note: This field is declared as mergeable, but the merge key is not sufficiently unique, which can cause data corruption when it is merged. Callers should instead use a full-replacement patch. See https://pr.k8s.io/79391 for an example. Consumers should assume that addresses can change during the lifetime of a Node. However, there are some exceptions where this may not be possible, such as Pods that inherit a Node's address in its own status or consumers of the downward API (status.hostIP).", + "description": "List of addresses reachable to the node. Queried from cloud provider, if available. More info: https://kubernetes.io/docs/reference/node/node-status/#addresses Note: This field is declared as mergeable, but the merge key is not sufficiently unique, which can cause data corruption when it is merged. Callers should instead use a full-replacement patch. See https://pr.k8s.io/79391 for an example. Consumers should assume that addresses can change during the lifetime of a Node. However, there are some exceptions where this may not be possible, such as Pods that inherit a Node's address in its own status or consumers of the downward API (status.hostIP).", "items": { "$ref": "#/definitions/v1.NodeAddress" }, @@ -8413,11 +8908,11 @@ "additionalProperties": { "$ref": "#/definitions/resource.Quantity" }, - "description": "Capacity represents the total resources of a node. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#capacity", + "description": "Capacity represents the total resources of a node. More info: https://kubernetes.io/docs/reference/node/node-status/#capacity", "type": "object" }, "conditions": { - "description": "Conditions is an array of current observed node conditions. More info: https://kubernetes.io/docs/concepts/nodes/node/#condition", + "description": "Conditions is an array of current observed node conditions. More info: https://kubernetes.io/docs/reference/node/node-status/#condition", "items": { "$ref": "#/definitions/v1.NodeCondition" }, @@ -8437,6 +8932,10 @@ "$ref": "#/definitions/v1.NodeDaemonEndpoints", "description": "Endpoints of daemons running on the Node." }, + "features": { + "$ref": "#/definitions/v1.NodeFeatures", + "description": "Features describes the set of features implemented by the CRI implementation." + }, "images": { "description": "List of container images on this node", "items": { @@ -8447,7 +8946,7 @@ }, "nodeInfo": { "$ref": "#/definitions/v1.NodeSystemInfo", - "description": "Set of ids/uuids to uniquely identify the node. More info: https://kubernetes.io/docs/concepts/nodes/node/#info" + "description": "Set of ids/uuids to uniquely identify the node. More info: https://kubernetes.io/docs/reference/node/node-status/#info" }, "phase": { "description": "NodePhase is the recently observed lifecycle phase of the node. More info: https://kubernetes.io/docs/concepts/nodes/node/#phase The field is never populated, and now is deprecated.", @@ -8480,6 +8979,17 @@ }, "type": "object" }, + "v1.NodeSwapStatus": { + "description": "NodeSwapStatus represents swap memory information.", + "properties": { + "capacity": { + "description": "Total amount of swap memory in bytes.", + "format": "int64", + "type": "integer" + } + }, + "type": "object" + }, "v1.NodeSystemInfo": { "description": "NodeSystemInfo is a set of ids/uuids to uniquely identify the node.", "properties": { @@ -8500,7 +9010,7 @@ "type": "string" }, "kubeProxyVersion": { - "description": "KubeProxy Version reported by the node.", + "description": "Deprecated: KubeProxy Version reported by the node.", "type": "string" }, "kubeletVersion": { @@ -8519,6 +9029,10 @@ "description": "OS Image reported by the node from /etc/os-release (e.g. Debian GNU/Linux 7 (wheezy)).", "type": "string" }, + "swap": { + "$ref": "#/definitions/v1.NodeSwapStatus", + "description": "Swap Info reported by the node." + }, "systemUUID": { "description": "SystemUUID reported by the node. For unique machine identification MachineID is preferred. This field is specific to Red Hat hosts https://access.redhat.com/documentation/en-us/red_hat_subscription_management/1/html/rhsm/uuid", "type": "string" @@ -8679,9 +9193,11 @@ "type": "string" }, "status": { + "description": "Status is the status of the condition. Can be True, False, Unknown. More info: https://kubernetes.io/docs/reference/kubernetes-api/config-and-storage-resources/persistent-volume-claim-v1/#:~:text=state%20of%20pvc-,conditions.status,-(string)%2C%20required", "type": "string" }, "type": { + "description": "Type is the type of the condition. More info: https://kubernetes.io/docs/reference/kubernetes-api/config-and-storage-resources/persistent-volume-claim-v1/#:~:text=set%20to%20%27ResizeStarted%27.-,PersistentVolumeClaimCondition,-contains%20details%20about", "type": "string" } }, @@ -8758,7 +9274,7 @@ "type": "string" }, "volumeAttributesClassName": { - "description": "volumeAttributesClassName may be used to set the VolumeAttributesClass used by this claim. If specified, the CSI driver will create or update the volume with the attributes defined in the corresponding VolumeAttributesClass. This has a different purpose than storageClassName, it can be changed after the claim is created. An empty string value means that no VolumeAttributesClass will be applied to the claim but it's not allowed to reset this field to empty string once it is set. If unspecified and the PersistentVolumeClaim is unbound, the default VolumeAttributesClass will be set by the persistentvolume controller if it exists. If the resource referred to by volumeAttributesClass does not exist, this PersistentVolumeClaim will be set to a Pending state, as reflected by the modifyVolumeStatus field, until such as a resource exists. More info: https://kubernetes.io/docs/concepts/storage/volume-attributes-classes/ (Alpha) Using this field requires the VolumeAttributesClass feature gate to be enabled.", + "description": "volumeAttributesClassName may be used to set the VolumeAttributesClass used by this claim. If specified, the CSI driver will create or update the volume with the attributes defined in the corresponding VolumeAttributesClass. This has a different purpose than storageClassName, it can be changed after the claim is created. An empty string or nil value indicates that no VolumeAttributesClass will be applied to the claim. If the claim enters an Infeasible error state, this field can be reset to its previous value (including nil) to cancel the modification. If the resource referred to by volumeAttributesClass does not exist, this PersistentVolumeClaim will be set to a Pending state, as reflected by the modifyVolumeStatus field, until such as a resource exists. More info: https://kubernetes.io/docs/concepts/storage/volume-attributes-classes/", "type": "string" }, "volumeMode": { @@ -8819,12 +9335,12 @@ "x-kubernetes-patch-strategy": "merge" }, "currentVolumeAttributesClassName": { - "description": "currentVolumeAttributesClassName is the current name of the VolumeAttributesClass the PVC is using. When unset, there is no VolumeAttributeClass applied to this PersistentVolumeClaim This is an alpha field and requires enabling VolumeAttributesClass feature.", + "description": "currentVolumeAttributesClassName is the current name of the VolumeAttributesClass the PVC is using. When unset, there is no VolumeAttributeClass applied to this PersistentVolumeClaim", "type": "string" }, "modifyVolumeStatus": { "$ref": "#/definitions/v1.ModifyVolumeStatus", - "description": "ModifyVolumeStatus represents the status object of ControllerModifyVolume operation. When this is unset, there is no ModifyVolume operation being attempted. This is an alpha field and requires enabling VolumeAttributesClass feature." + "description": "ModifyVolumeStatus represents the status object of ControllerModifyVolume operation. When this is unset, there is no ModifyVolume operation being attempted." }, "phase": { "description": "phase represents the current phase of PersistentVolumeClaim.", @@ -8915,15 +9431,15 @@ }, "awsElasticBlockStore": { "$ref": "#/definitions/v1.AWSElasticBlockStoreVolumeSource", - "description": "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore" + "description": "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Deprecated: AWSElasticBlockStore is deprecated. All operations for the in-tree awsElasticBlockStore type are redirected to the ebs.csi.aws.com CSI driver. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore" }, "azureDisk": { "$ref": "#/definitions/v1.AzureDiskVolumeSource", - "description": "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod." + "description": "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod. Deprecated: AzureDisk is deprecated. All operations for the in-tree azureDisk type are redirected to the disk.csi.azure.com CSI driver." }, "azureFile": { "$ref": "#/definitions/v1.AzureFilePersistentVolumeSource", - "description": "azureFile represents an Azure File Service mount on the host and bind mount to the pod." + "description": "azureFile represents an Azure File Service mount on the host and bind mount to the pod. Deprecated: AzureFile is deprecated. All operations for the in-tree azureFile type are redirected to the file.csi.azure.com CSI driver." }, "capacity": { "additionalProperties": { @@ -8934,11 +9450,11 @@ }, "cephfs": { "$ref": "#/definitions/v1.CephFSPersistentVolumeSource", - "description": "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime" + "description": "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime. Deprecated: CephFS is deprecated and the in-tree cephfs type is no longer supported." }, "cinder": { "$ref": "#/definitions/v1.CinderPersistentVolumeSource", - "description": "cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md" + "description": "cinder represents a cinder volume attached and mounted on kubelets host machine. Deprecated: Cinder is deprecated. All operations for the in-tree cinder type are redirected to the cinder.csi.openstack.org CSI driver. More info: https://examples.k8s.io/mysql-cinder-pd/README.md" }, "claimRef": { "$ref": "#/definitions/v1.ObjectReference", @@ -8947,7 +9463,7 @@ }, "csi": { "$ref": "#/definitions/v1.CSIPersistentVolumeSource", - "description": "csi represents storage that is handled by an external CSI driver (Beta feature)." + "description": "csi represents storage that is handled by an external CSI driver." }, "fc": { "$ref": "#/definitions/v1.FCVolumeSource", @@ -8955,19 +9471,19 @@ }, "flexVolume": { "$ref": "#/definitions/v1.FlexPersistentVolumeSource", - "description": "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin." + "description": "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin. Deprecated: FlexVolume is deprecated. Consider using a CSIDriver instead." }, "flocker": { "$ref": "#/definitions/v1.FlockerVolumeSource", - "description": "flocker represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running" + "description": "flocker represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running. Deprecated: Flocker is deprecated and the in-tree flocker type is no longer supported." }, "gcePersistentDisk": { "$ref": "#/definitions/v1.GCEPersistentDiskVolumeSource", - "description": "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk" + "description": "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. Deprecated: GCEPersistentDisk is deprecated. All operations for the in-tree gcePersistentDisk type are redirected to the pd.csi.storage.gke.io CSI driver. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk" }, "glusterfs": { "$ref": "#/definitions/v1.GlusterfsPersistentVolumeSource", - "description": "glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. More info: https://examples.k8s.io/volumes/glusterfs/README.md" + "description": "glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. Deprecated: Glusterfs is deprecated and the in-tree glusterfs type is no longer supported. More info: https://examples.k8s.io/volumes/glusterfs/README.md" }, "hostPath": { "$ref": "#/definitions/v1.HostPathVolumeSource", @@ -9003,23 +9519,23 @@ }, "photonPersistentDisk": { "$ref": "#/definitions/v1.PhotonPersistentDiskVolumeSource", - "description": "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine" + "description": "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine. Deprecated: PhotonPersistentDisk is deprecated and the in-tree photonPersistentDisk type is no longer supported." }, "portworxVolume": { "$ref": "#/definitions/v1.PortworxVolumeSource", - "description": "portworxVolume represents a portworx volume attached and mounted on kubelets host machine" + "description": "portworxVolume represents a portworx volume attached and mounted on kubelets host machine. Deprecated: PortworxVolume is deprecated. All operations for the in-tree portworxVolume type are redirected to the pxd.portworx.com CSI driver when the CSIMigrationPortworx feature-gate is on." }, "quobyte": { "$ref": "#/definitions/v1.QuobyteVolumeSource", - "description": "quobyte represents a Quobyte mount on the host that shares a pod's lifetime" + "description": "quobyte represents a Quobyte mount on the host that shares a pod's lifetime. Deprecated: Quobyte is deprecated and the in-tree quobyte type is no longer supported." }, "rbd": { "$ref": "#/definitions/v1.RBDPersistentVolumeSource", - "description": "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md" + "description": "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. Deprecated: RBD is deprecated and the in-tree rbd type is no longer supported. More info: https://examples.k8s.io/volumes/rbd/README.md" }, "scaleIO": { "$ref": "#/definitions/v1.ScaleIOPersistentVolumeSource", - "description": "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes." + "description": "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes. Deprecated: ScaleIO is deprecated and the in-tree scaleIO type is no longer supported." }, "storageClassName": { "description": "storageClassName is the name of StorageClass to which this persistent volume belongs. Empty value means that this volume does not belong to any StorageClass.", @@ -9027,10 +9543,10 @@ }, "storageos": { "$ref": "#/definitions/v1.StorageOSPersistentVolumeSource", - "description": "storageOS represents a StorageOS volume that is attached to the kubelet's host machine and mounted into the pod More info: https://examples.k8s.io/volumes/storageos/README.md" + "description": "storageOS represents a StorageOS volume that is attached to the kubelet's host machine and mounted into the pod. Deprecated: StorageOS is deprecated and the in-tree storageos type is no longer supported. More info: https://examples.k8s.io/volumes/storageos/README.md" }, "volumeAttributesClassName": { - "description": "Name of VolumeAttributesClass to which this persistent volume belongs. Empty value is not allowed. When this field is not set, it indicates that this volume does not belong to any VolumeAttributesClass. This field is mutable and can be changed by the CSI driver after a volume has been updated successfully to a new class. For an unbound PersistentVolume, the volumeAttributesClassName will be matched with unbound PersistentVolumeClaims during the binding process. This is an alpha field and requires enabling VolumeAttributesClass feature.", + "description": "Name of VolumeAttributesClass to which this persistent volume belongs. Empty value is not allowed. When this field is not set, it indicates that this volume does not belong to any VolumeAttributesClass. This field is mutable and can be changed by the CSI driver after a volume has been updated successfully to a new class. For an unbound PersistentVolume, the volumeAttributesClassName will be matched with unbound PersistentVolumeClaims during the binding process.", "type": "string" }, "volumeMode": { @@ -9039,7 +9555,7 @@ }, "vsphereVolume": { "$ref": "#/definitions/v1.VsphereVirtualDiskVolumeSource", - "description": "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine" + "description": "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine. Deprecated: VsphereVolume is deprecated. All operations for the in-tree vsphereVolume type are redirected to the csi.vsphere.vmware.com CSI driver." } }, "type": "object" @@ -9048,7 +9564,7 @@ "description": "PersistentVolumeStatus is the current status of a persistent volume.", "properties": { "lastPhaseTransitionTime": { - "description": "lastPhaseTransitionTime is the time the phase transitioned from one to another and automatically resets to current time everytime a volume phase transitions. This is a beta field and requires the PersistentVolumeLastPhaseTransitionTime feature to be enabled (enabled by default).", + "description": "lastPhaseTransitionTime is the time the phase transitioned from one to another and automatically resets to current time everytime a volume phase transitions.", "format": "date-time", "type": "string" }, @@ -9147,7 +9663,7 @@ "description": "A label query over a set of resources, in this case pods. If it's null, this PodAffinityTerm matches with no Pods." }, "matchLabelKeys": { - "description": "MatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both matchLabelKeys and labelSelector. Also, matchLabelKeys cannot be set when labelSelector isn't set. This is an alpha field and requires enabling MatchLabelKeysInPodAffinity feature gate.", + "description": "MatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both matchLabelKeys and labelSelector. Also, matchLabelKeys cannot be set when labelSelector isn't set.", "items": { "type": "string" }, @@ -9155,7 +9671,7 @@ "x-kubernetes-list-type": "atomic" }, "mismatchLabelKeys": { - "description": "MismatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. Also, mismatchLabelKeys cannot be set when labelSelector isn't set. This is an alpha field and requires enabling MatchLabelKeysInPodAffinity feature gate.", + "description": "MismatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. Also, mismatchLabelKeys cannot be set when labelSelector isn't set.", "items": { "type": "string" }, @@ -9188,7 +9704,7 @@ "description": "Pod anti affinity is a group of inter pod anti affinity scheduling rules.", "properties": { "preferredDuringSchedulingIgnoredDuringExecution": { - "description": "The scheduler will prefer to schedule pods to nodes that satisfy the anti-affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling anti-affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node has pods which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred.", + "description": "The scheduler will prefer to schedule pods to nodes that satisfy the anti-affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling anti-affinity expressions, etc.), compute a sum by iterating through the elements of this field and subtracting \"weight\" from the sum if the node has pods which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred.", "items": { "$ref": "#/definitions/v1.WeightedPodAffinityTerm" }, @@ -9206,6 +9722,41 @@ }, "type": "object" }, + "v1.PodCertificateProjection": { + "description": "PodCertificateProjection provides a private key and X.509 certificate in the pod filesystem.", + "properties": { + "certificateChainPath": { + "description": "Write the certificate chain at this path in the projected volume.\n\nMost applications should use credentialBundlePath. When using keyPath and certificateChainPath, your application needs to check that the key and leaf certificate are consistent, because it is possible to read the files mid-rotation.", + "type": "string" + }, + "credentialBundlePath": { + "description": "Write the credential bundle at this path in the projected volume.\n\nThe credential bundle is a single file that contains multiple PEM blocks. The first PEM block is a PRIVATE KEY block, containing a PKCS#8 private key.\n\nThe remaining blocks are CERTIFICATE blocks, containing the issued certificate chain from the signer (leaf and any intermediates).\n\nUsing credentialBundlePath lets your Pod's application code make a single atomic read that retrieves a consistent key and certificate chain. If you project them to separate files, your application code will need to additionally check that the leaf certificate was issued to the key.", + "type": "string" + }, + "keyPath": { + "description": "Write the key at this path in the projected volume.\n\nMost applications should use credentialBundlePath. When using keyPath and certificateChainPath, your application needs to check that the key and leaf certificate are consistent, because it is possible to read the files mid-rotation.", + "type": "string" + }, + "keyType": { + "description": "The type of keypair Kubelet will generate for the pod.\n\nValid values are \"RSA3072\", \"RSA4096\", \"ECDSAP256\", \"ECDSAP384\", \"ECDSAP521\", and \"ED25519\".", + "type": "string" + }, + "maxExpirationSeconds": { + "description": "maxExpirationSeconds is the maximum lifetime permitted for the certificate.\n\nKubelet copies this value verbatim into the PodCertificateRequests it generates for this projection.\n\nIf omitted, kube-apiserver will set it to 86400(24 hours). kube-apiserver will reject values shorter than 3600 (1 hour). The maximum allowable value is 7862400 (91 days).\n\nThe signer implementation is then free to issue a certificate with any lifetime *shorter* than MaxExpirationSeconds, but no shorter than 3600 seconds (1 hour). This constraint is enforced by kube-apiserver. `kubernetes.io` signers will never issue certificates with a lifetime longer than 24 hours.", + "format": "int32", + "type": "integer" + }, + "signerName": { + "description": "Kubelet's generated CSRs will be addressed to this signer.", + "type": "string" + } + }, + "required": [ + "signerName", + "keyType" + ], + "type": "object" + }, "v1.PodCondition": { "description": "PodCondition contains details for the current condition of this pod.", "properties": { @@ -9223,6 +9774,11 @@ "description": "Human-readable message indicating details about last transition.", "type": "string" }, + "observedGeneration": { + "description": "If set, this represents the .metadata.generation that the pod condition was set based upon. This is an alpha field. Enable PodObservedGenerationTracking to be able to use this field.", + "format": "int64", + "type": "integer" + }, "reason": { "description": "Unique, one-word, CamelCase reason for the condition's last transition.", "type": "string" @@ -9276,13 +9832,36 @@ "description": "PodDNSConfigOption defines DNS resolver options of a pod.", "properties": { "name": { - "description": "Required.", + "description": "Name is this DNS resolver option's name. Required.", "type": "string" }, "value": { + "description": "Value is this DNS resolver option's value.", + "type": "string" + } + }, + "type": "object" + }, + "v1.PodExtendedResourceClaimStatus": { + "description": "PodExtendedResourceClaimStatus is stored in the PodStatus for the extended resource requests backed by DRA. It stores the generated name for the corresponding special ResourceClaim created by the scheduler.", + "properties": { + "requestMappings": { + "description": "RequestMappings identifies the mapping of to device request in the generated ResourceClaim.", + "items": { + "$ref": "#/definitions/v1.ContainerExtendedResourceRequest" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "resourceClaimName": { + "description": "ResourceClaimName is the name of the ResourceClaim that was generated for the Pod in the namespace of the Pod.", "type": "string" } }, + "required": [ + "requestMappings", + "resourceClaimName" + ], "type": "object" }, "v1.PodIP": { @@ -9293,6 +9872,9 @@ "type": "string" } }, + "required": [ + "ip" + ], "type": "object" }, "v1.PodList": { @@ -9357,15 +9939,19 @@ "type": "object" }, "v1.PodResourceClaim": { - "description": "PodResourceClaim references exactly one ResourceClaim through a ClaimSource. It adds a name to it that uniquely identifies the ResourceClaim inside the Pod. Containers that need access to the ResourceClaim reference it with this name.", + "description": "PodResourceClaim references exactly one ResourceClaim, either directly or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim for the pod.\n\nIt adds a name to it that uniquely identifies the ResourceClaim inside the Pod. Containers that need access to the ResourceClaim reference it with this name.", "properties": { "name": { "description": "Name uniquely identifies this resource claim inside the pod. This must be a DNS_LABEL.", "type": "string" }, - "source": { - "$ref": "#/definitions/v1.ClaimSource", - "description": "Source describes where to find the ResourceClaim." + "resourceClaimName": { + "description": "ResourceClaimName is the name of a ResourceClaim object in the same namespace as this pod.\n\nExactly one of ResourceClaimName and ResourceClaimTemplateName must be set.", + "type": "string" + }, + "resourceClaimTemplateName": { + "description": "ResourceClaimTemplateName is the name of a ResourceClaimTemplate object in the same namespace as this pod.\n\nThe template will be used to create a new ResourceClaim, which will be bound to this pod. When this pod is deleted, the ResourceClaim will also be deleted. The pod name and resource name, along with a generated component, will be used to form a unique name for the ResourceClaim, which will be recorded in pod.status.resourceClaimStatuses.\n\nThis field is immutable and no changes will be made to the corresponding ResourceClaim by the control plane after creating the ResourceClaim.\n\nExactly one of ResourceClaimName and ResourceClaimTemplateName must be set.", + "type": "string" } }, "required": [ @@ -9381,7 +9967,7 @@ "type": "string" }, "resourceClaimName": { - "description": "ResourceClaimName is the name of the ResourceClaim that was generated for the Pod in the namespace of the Pod. It this is unset, then generating a ResourceClaim was not necessary. The pod.spec.resourceClaims entry can be ignored in this case.", + "description": "ResourceClaimName is the name of the ResourceClaim that was generated for the Pod in the namespace of the Pod. If this is unset, then generating a ResourceClaim was not necessary. The pod.spec.resourceClaims entry can be ignored in this case.", "type": "string" } }, @@ -9433,6 +10019,10 @@ "format": "int64", "type": "integer" }, + "seLinuxChangePolicy": { + "description": "seLinuxChangePolicy defines how the container's SELinux label is applied to all volumes used by the Pod. It has no effect on nodes that do not support SELinux or to volumes does not support SELinux. Valid values are \"MountOption\" and \"Recursive\".\n\n\"Recursive\" means relabeling of all files on all Pod volumes by the container runtime. This may be slow for large volumes, but allows mixing privileged and unprivileged Pods sharing the same volume on the same node.\n\n\"MountOption\" mounts all eligible Pod volumes with `-o context` mount option. This requires all Pods that share the same volume to use the same SELinux label. It is not possible to share the same volume among privileged and unprivileged Pods. Eligible volumes are in-tree FibreChannel and iSCSI volumes, and all CSI volumes whose CSI driver announces SELinux support by setting spec.seLinuxMount: true in their CSIDriver instance. Other volumes are always re-labelled recursively. \"MountOption\" value is allowed only when SELinuxMount feature gate is enabled.\n\nIf not specified and SELinuxMount feature gate is enabled, \"MountOption\" is used. If not specified and SELinuxMount feature gate is disabled, \"MountOption\" is used for ReadWriteOncePod volumes and \"Recursive\" for all other volumes.\n\nThis field affects only Pods that have SELinux label set, either in PodSecurityContext or in SecurityContext of all containers.\n\nAll Pods that use the same volume should use the same seLinuxChangePolicy, otherwise some pods can get stuck in ContainerCreating state. Note that this field cannot be set when spec.os.name is windows.", + "type": "string" + }, "seLinuxOptions": { "$ref": "#/definitions/v1.SELinuxOptions", "description": "The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. Note that this field cannot be set when spec.os.name is windows." @@ -9442,7 +10032,7 @@ "description": "The seccomp options to use by the containers in this pod. Note that this field cannot be set when spec.os.name is windows." }, "supplementalGroups": { - "description": "A list of groups applied to the first process run in each container, in addition to the container's primary GID, the fsGroup (if specified), and group memberships defined in the container image for the uid of the container process. If unspecified, no additional groups are added to any container. Note that group memberships defined in the container image for the uid of the container process are still effective, even if they are not included in this list. Note that this field cannot be set when spec.os.name is windows.", + "description": "A list of groups applied to the first process run in each container, in addition to the container's primary GID and fsGroup (if specified). If the SupplementalGroupsPolicy feature is enabled, the supplementalGroupsPolicy field determines whether these are in addition to or instead of any group memberships defined in the container image. If unspecified, no additional groups are added, though group memberships defined in the container image may still be used, depending on the supplementalGroupsPolicy field. Note that this field cannot be set when spec.os.name is windows.", "items": { "format": "int64", "type": "integer" @@ -9450,6 +10040,10 @@ "type": "array", "x-kubernetes-list-type": "atomic" }, + "supplementalGroupsPolicy": { + "description": "Defines how supplemental groups of the first container processes are calculated. Valid values are \"Merge\" and \"Strict\". If not specified, \"Merge\" is used. (Alpha) Using the field requires the SupplementalGroupsPolicy feature gate to be enabled and the container runtime must implement support for this feature. Note that this field cannot be set when spec.os.name is windows.", + "type": "string" + }, "sysctls": { "description": "Sysctls hold a list of namespaced sysctls used for the pod. Pods with unsupported sysctls (by the container runtime) might fail to launch. Note that this field cannot be set when spec.os.name is windows.", "items": { @@ -9537,7 +10131,7 @@ "type": "boolean" }, "hostNetwork": { - "description": "Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified. Default to false.", + "description": "Host networking requested for this pod. Use the host's network namespace. When using HostNetwork you should specify ports so the scheduler is aware. When `hostNetwork` is true, specified `hostPort` fields in port definitions must match `containerPort`, and unspecified `hostPort` fields in port definitions are defaulted to match `containerPort`. Default to false.", "type": "boolean" }, "hostPID": { @@ -9552,6 +10146,10 @@ "description": "Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value.", "type": "string" }, + "hostnameOverride": { + "description": "HostnameOverride specifies an explicit override for the pod's hostname as perceived by the pod. This field only specifies the pod's hostname and does not affect its DNS records. When this field is set to a non-empty string: - It takes precedence over the values set in `hostname` and `subdomain`. - The Pod's hostname will be set to this value. - `setHostnameAsFQDN` must be nil or set to false. - `hostNetwork` must be set to false.\n\nThis field must be a valid DNS subdomain as defined in RFC 1123 and contain at most 64 characters. Requires the HostnameOverride feature gate to be enabled.", + "type": "string" + }, "imagePullSecrets": { "description": "ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod", "items": { @@ -9566,7 +10164,7 @@ "x-kubernetes-patch-strategy": "merge" }, "initContainers": { - "description": "List of initialization containers belonging to the pod. Init containers are executed in order prior to containers being started. If any init container fails, the pod is considered to have failed and is handled according to its restartPolicy. The name for an init container or normal container must be unique among all containers. Init containers may not have Lifecycle actions, Readiness probes, Liveness probes, or Startup probes. The resourceRequirements of an init container are taken into account during scheduling by finding the highest request/limit for each resource type, and then using the max of of that value or the sum of the normal containers. Limits are applied to init containers in a similar fashion. Init containers cannot currently be added or removed. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/", + "description": "List of initialization containers belonging to the pod. Init containers are executed in order prior to containers being started. If any init container fails, the pod is considered to have failed and is handled according to its restartPolicy. The name for an init container or normal container must be unique among all containers. Init containers may not have Lifecycle actions, Readiness probes, Liveness probes, or Startup probes. The resourceRequirements of an init container are taken into account during scheduling by finding the highest request/limit for each resource type, and then using the max of that value or the sum of the normal containers. Limits are applied to init containers in a similar fashion. Init containers cannot currently be added or removed. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/", "items": { "$ref": "#/definitions/v1.Container" }, @@ -9579,7 +10177,7 @@ "x-kubernetes-patch-strategy": "merge" }, "nodeName": { - "description": "NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements.", + "description": "NodeName indicates in which node this pod is scheduled. If empty, this pod is a candidate for scheduling by the scheduler defined in schedulerName. Once this field is set, the kubelet for this node becomes responsible for the lifecycle of this pod. This field should not be used to express a desire for the pod to be scheduled on a specific node. https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#nodename", "type": "string" }, "nodeSelector": { @@ -9592,7 +10190,7 @@ }, "os": { "$ref": "#/definitions/v1.PodOS", - "description": "Specifies the OS of the containers in the pod. Some pod and container fields are restricted if this is set.\n\nIf the OS field is set to linux, the following fields must be unset: -securityContext.windowsOptions\n\nIf the OS field is set to windows, following fields must be unset: - spec.hostPID - spec.hostIPC - spec.hostUsers - spec.securityContext.appArmorProfile - spec.securityContext.seLinuxOptions - spec.securityContext.seccompProfile - spec.securityContext.fsGroup - spec.securityContext.fsGroupChangePolicy - spec.securityContext.sysctls - spec.shareProcessNamespace - spec.securityContext.runAsUser - spec.securityContext.runAsGroup - spec.securityContext.supplementalGroups - spec.containers[*].securityContext.appArmorProfile - spec.containers[*].securityContext.seLinuxOptions - spec.containers[*].securityContext.seccompProfile - spec.containers[*].securityContext.capabilities - spec.containers[*].securityContext.readOnlyRootFilesystem - spec.containers[*].securityContext.privileged - spec.containers[*].securityContext.allowPrivilegeEscalation - spec.containers[*].securityContext.procMount - spec.containers[*].securityContext.runAsUser - spec.containers[*].securityContext.runAsGroup" + "description": "Specifies the OS of the containers in the pod. Some pod and container fields are restricted if this is set.\n\nIf the OS field is set to linux, the following fields must be unset: -securityContext.windowsOptions\n\nIf the OS field is set to windows, following fields must be unset: - spec.hostPID - spec.hostIPC - spec.hostUsers - spec.resources - spec.securityContext.appArmorProfile - spec.securityContext.seLinuxOptions - spec.securityContext.seccompProfile - spec.securityContext.fsGroup - spec.securityContext.fsGroupChangePolicy - spec.securityContext.sysctls - spec.shareProcessNamespace - spec.securityContext.runAsUser - spec.securityContext.runAsGroup - spec.securityContext.supplementalGroups - spec.securityContext.supplementalGroupsPolicy - spec.containers[*].securityContext.appArmorProfile - spec.containers[*].securityContext.seLinuxOptions - spec.containers[*].securityContext.seccompProfile - spec.containers[*].securityContext.capabilities - spec.containers[*].securityContext.readOnlyRootFilesystem - spec.containers[*].securityContext.privileged - spec.containers[*].securityContext.allowPrivilegeEscalation - spec.containers[*].securityContext.procMount - spec.containers[*].securityContext.runAsUser - spec.containers[*].securityContext.runAsGroup" }, "overhead": { "additionalProperties": { @@ -9635,6 +10233,10 @@ "x-kubernetes-patch-merge-key": "name", "x-kubernetes-patch-strategy": "merge,retainKeys" }, + "resources": { + "$ref": "#/definitions/v1.ResourceRequirements", + "description": "Resources is the total amount of CPU and Memory resources required by all containers in the pod. It supports specifying Requests and Limits for \"cpu\", \"memory\" and \"hugepages-\" resource names only. ResourceClaims are not supported.\n\nThis field enables fine-grained control over resource allocation for the entire pod, allowing resource sharing among containers in a pod.\n\nThis is an alpha field and requires enabling the PodLevelResources feature gate." + }, "restartPolicy": { "description": "Restart policy for all containers within the pod. One of Always, OnFailure, Never. In some contexts, only a subset of those values may be permitted. Default to Always. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy", "type": "string" @@ -9673,7 +10275,7 @@ "type": "string" }, "setHostnameAsFQDN": { - "description": "If true the pod's hostname will be configured as the pod's FQDN, rather than the leaf name (the default). In Linux containers, this means setting the FQDN in the hostname field of the kernel (the nodename field of struct utsname). In Windows containers, this means setting the registry value of hostname for the registry key HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters to FQDN. If a pod does not have FQDN, this has no effect. Default to false.", + "description": "If true the pod's hostname will be configured as the pod's FQDN, rather than the leaf name (the default). In Linux containers, this means setting the FQDN in the hostname field of the kernel (the nodename field of struct utsname). In Windows containers, this means setting the registry value of hostname for the registry key HKEY_LOCAL_MACHINE\\\\SYSTEM\\\\CurrentControlSet\\\\Services\\\\Tcpip\\\\Parameters to FQDN. If a pod does not have FQDN, this has no effect. Default to false.", "type": "boolean" }, "shareProcessNamespace": { @@ -9747,7 +10349,7 @@ "x-kubernetes-patch-strategy": "merge" }, "containerStatuses": { - "description": "The list has one entry per container in the manifest. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status", + "description": "Statuses of containers in this pod. Each container in the pod should have at most one status in this list, and all statuses should be for containers in the pod. However this is not enforced. If a status for a non-existent container is present in the list, or the list has duplicate names, the behavior of various Kubernetes components is not defined and those statuses might be ignored. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status", "items": { "$ref": "#/definitions/v1.ContainerStatus" }, @@ -9755,13 +10357,17 @@ "x-kubernetes-list-type": "atomic" }, "ephemeralContainerStatuses": { - "description": "Status for any ephemeral containers that have run in this pod.", + "description": "Statuses for any ephemeral containers that have run in this pod. Each ephemeral container in the pod should have at most one status in this list, and all statuses should be for containers in the pod. However this is not enforced. If a status for a non-existent container is present in the list, or the list has duplicate names, the behavior of various Kubernetes components is not defined and those statuses might be ignored. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status", "items": { "$ref": "#/definitions/v1.ContainerStatus" }, "type": "array", "x-kubernetes-list-type": "atomic" }, + "extendedResourceClaimStatus": { + "$ref": "#/definitions/v1.PodExtendedResourceClaimStatus", + "description": "Status of extended resource claim backed by DRA." + }, "hostIP": { "description": "hostIP holds the IP address of the host to which the pod is assigned. Empty if the pod has not started yet. A pod can be assigned to a node that has a problem in kubelet which in turns mean that HostIP will not be updated even if there is a node is assigned to pod", "type": "string" @@ -9777,7 +10383,7 @@ "x-kubernetes-patch-strategy": "merge" }, "initContainerStatuses": { - "description": "The list has one entry per init container in the manifest. The most recent successful init container will have ready = true, the most recently started container will have startTime set. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status", + "description": "Statuses of init containers in this pod. The most recent successful non-restartable init container will have ready = true, the most recently started container will have startTime set. Each init container in the pod should have at most one status in this list, and all statuses should be for containers in the pod. However this is not enforced. If a status for a non-existent container is present in the list, or the list has duplicate names, the behavior of various Kubernetes components is not defined and those statuses might be ignored. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-and-container-status", "items": { "$ref": "#/definitions/v1.ContainerStatus" }, @@ -9792,6 +10398,11 @@ "description": "nominatedNodeName is set only when this pod preempts other pods on the node, but it cannot be scheduled right away as preemption victims receive their graceful termination periods. This field does not guarantee that the pod will be scheduled on this node. Scheduler may decide to place the pod elsewhere if other nodes become available sooner. Scheduler may also decide to give the resources on this node to a higher priority pod that is created after preemption. As a result, this field may be different than PodSpec.nodeName when the pod is scheduled.", "type": "string" }, + "observedGeneration": { + "description": "If set, this represents the .metadata.generation that the pod status was set based upon. This is an alpha field. Enable PodObservedGenerationTracking to be able to use this field.", + "format": "int64", + "type": "integer" + }, "phase": { "description": "The phase of a Pod is a simple, high-level summary of where the Pod is in its lifecycle. The conditions array, the reason and message fields, and the individual container status arrays contain more detail about the pod's status. There are five possible phase values:\n\nPending: The pod has been accepted by the Kubernetes system, but one or more of the container images has not been created. This includes time before being scheduled as well as time spent downloading images over the network, which could take a while. Running: The pod has been bound to a node, and all of the containers have been created. At least one container is still running, or is in the process of starting or restarting. Succeeded: All containers in the pod have terminated in success, and will not be restarted. Failed: All containers in the pod have terminated, and at least one container has terminated in failure. The container either exited with non-zero status or was terminated by the system. Unknown: For some reason the state of the pod could not be obtained, typically due to an error in communicating with the host of the pod.\n\nMore info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-phase", "type": "string" @@ -9822,7 +10433,7 @@ "type": "string" }, "resize": { - "description": "Status of resources resize desired for pod's containers. It is empty if no resources resize is pending. Any changes to container resources will automatically set this to \"Proposed\"", + "description": "Status of resources resize desired for pod's containers. It is empty if no resources resize is pending. Any changes to container resources will automatically set this to \"Proposed\" Deprecated: Resize status is moved to two pod conditions PodResizePending and PodResizeInProgress. PodResizePending will track states where the spec has been resized, but the Kubelet has not yet allocated the resources. PodResizeInProgress will track in-progress resizes, and should be present whenever allocated resources != acknowledged resources.", "type": "string" }, "resourceClaimStatuses": { @@ -9925,6 +10536,7 @@ "type": "object" }, "v1.PortStatus": { + "description": "PortStatus represents the error condition of a service port", "properties": { "error": { "description": "Error is to record the problem with the service port The format of the error shall comply with the following rules: - built-in error values shall be specified in this file and those shall use\n CamelCase names\n- cloud provider specific error values must have names that comply with the\n format foo.example.com/CamelCase.", @@ -9991,7 +10603,7 @@ "properties": { "exec": { "$ref": "#/definitions/v1.ExecAction", - "description": "Exec specifies the action to take." + "description": "Exec specifies a command to execute in the container." }, "failureThreshold": { "description": "Minimum consecutive failures for the probe to be considered failed after having succeeded. Defaults to 3. Minimum value is 1.", @@ -10000,11 +10612,11 @@ }, "grpc": { "$ref": "#/definitions/v1.GRPCAction", - "description": "GRPC specifies an action involving a GRPC port." + "description": "GRPC specifies a GRPC HealthCheckRequest." }, "httpGet": { "$ref": "#/definitions/v1.HTTPGetAction", - "description": "HTTPGet specifies the http request to perform." + "description": "HTTPGet specifies an HTTP GET request to perform." }, "initialDelaySeconds": { "description": "Number of seconds after the container has started before liveness probes are initiated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", @@ -10023,7 +10635,7 @@ }, "tcpSocket": { "$ref": "#/definitions/v1.TCPSocketAction", - "description": "TCPSocket specifies an action involving a TCP port." + "description": "TCPSocket specifies a connection to a TCP port." }, "terminationGracePeriodSeconds": { "description": "Optional duration in seconds the pod needs to terminate gracefully upon probe failure. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. If this value is nil, the pod's terminationGracePeriodSeconds will be used. Otherwise, this value overrides the value provided by the pod spec. Value must be non-negative integer. The value zero indicates stop immediately via the kill signal (no opportunity to shut down). This is a beta field and requires enabling ProbeTerminationGracePeriod feature gate. Minimum value is 1. spec.terminationGracePeriodSeconds is used if unset.", @@ -10047,7 +10659,7 @@ "type": "integer" }, "sources": { - "description": "sources is the list of volume projections", + "description": "sources is the list of volume projections. Each entry in this list handles one source.", "items": { "$ref": "#/definitions/v1.VolumeProjection" }, @@ -10357,12 +10969,16 @@ ], "type": "object" }, - "v1.ResourceClaim": { + "core.v1.ResourceClaim": { "description": "ResourceClaim references one entry in PodSpec.ResourceClaims.", "properties": { "name": { "description": "Name must match the name of one entry in pod.spec.resourceClaims of the Pod where this field is used. It makes that resource available inside a container.", "type": "string" + }, + "request": { + "description": "Request is the name chosen for a request in the referenced claim. If empty, everything from the claim is made available, otherwise only the result of this request.", + "type": "string" } }, "required": [ @@ -10392,6 +11008,23 @@ "type": "object", "x-kubernetes-map-type": "atomic" }, + "v1.ResourceHealth": { + "description": "ResourceHealth represents the health of a resource. It has the latest device health information. This is a part of KEP https://kep.k8s.io/4680.", + "properties": { + "health": { + "description": "Health of the resource. can be one of:\n - Healthy: operates as normal\n - Unhealthy: reported unhealthy. We consider this a temporary health issue\n since we do not have a mechanism today to distinguish\n temporary and permanent issues.\n - Unknown: The status cannot be determined.\n For example, Device Plugin got unregistered and hasn't been re-registered since.\n\nIn future we may want to introduce the PermanentlyUnhealthy Status.", + "type": "string" + }, + "resourceID": { + "description": "ResourceID is the unique identifier of the resource. See the ResourceID type for more information.", + "type": "string" + } + }, + "required": [ + "resourceID" + ], + "type": "object" + }, "v1.ResourceQuota": { "description": "ResourceQuota sets aggregate quota restrictions enforced per namespace", "properties": { @@ -10509,9 +11142,9 @@ "description": "ResourceRequirements describes the compute resource requirements.", "properties": { "claims": { - "description": "Claims lists the names of resources, defined in spec.resourceClaims, that are used by this container.\n\nThis is an alpha field and requires enabling the DynamicResourceAllocation feature gate.\n\nThis field is immutable. It can only be set for containers.", + "description": "Claims lists the names of resources, defined in spec.resourceClaims, that are used by this container.\n\nThis field depends on the DynamicResourceAllocation feature gate.\n\nThis field is immutable. It can only be set for containers.", "items": { - "$ref": "#/definitions/v1.ResourceClaim" + "$ref": "#/definitions/core.v1.ResourceClaim" }, "type": "array", "x-kubernetes-list-map-keys": [ @@ -10536,6 +11169,30 @@ }, "type": "object" }, + "v1.ResourceStatus": { + "description": "ResourceStatus represents the status of a single resource allocated to a Pod.", + "properties": { + "name": { + "description": "Name of the resource. Must be unique within the pod and in case of non-DRA resource, match one of the resources from the pod spec. For DRA resources, the value must be \"claim:/\". When this status is reported about a container, the \"claim_name\" and \"request\" must match one of the claims of this container.", + "type": "string" + }, + "resources": { + "description": "List of unique resources health. Each element in the list contains an unique resource ID and its health. At a minimum, for the lifetime of a Pod, resource ID must uniquely identify the resource allocated to the Pod on the Node. If other Pod on the same Node reports the status with the same resource ID, it must be the same resource they share. See ResourceID type definition for a specific format it has in various use cases.", + "items": { + "$ref": "#/definitions/v1.ResourceHealth" + }, + "type": "array", + "x-kubernetes-list-map-keys": [ + "resourceID" + ], + "x-kubernetes-list-type": "map" + } + }, + "required": [ + "name" + ], + "type": "object" + }, "v1.SELinuxOptions": { "description": "SELinuxOptions are the labels to be applied to the container", "properties": { @@ -10778,7 +11435,7 @@ "description": "SecretEnvSource selects a Secret to populate the environment variables with.\n\nThe contents of the target Secret's Data field will represent the key-value pairs as environment variables.", "properties": { "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", + "description": "Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", "type": "string" }, "optional": { @@ -10796,7 +11453,7 @@ "type": "string" }, "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", + "description": "Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", "type": "string" }, "optional": { @@ -10857,7 +11514,7 @@ "x-kubernetes-list-type": "atomic" }, "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", + "description": "Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", "type": "string" }, "optional": { @@ -10929,7 +11586,7 @@ "type": "boolean" }, "procMount": { - "description": "procMount denotes the type of proc mount to use for the containers. The default is DefaultProcMount which uses the container runtime defaults for readonly paths and masked paths. This requires the ProcMountType feature flag to be enabled. Note that this field cannot be set when spec.os.name is windows.", + "description": "procMount denotes the type of proc mount to use for the containers. The default value is Default which uses the container runtime defaults for readonly paths and masked paths. This requires the ProcMountType feature flag to be enabled. Note that this field cannot be set when spec.os.name is windows.", "type": "string" }, "readOnlyRootFilesystem": { @@ -11026,7 +11683,7 @@ "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" }, "secrets": { - "description": "Secrets is a list of the secrets in the same namespace that pods running using this ServiceAccount are allowed to use. Pods are only limited to this list if this service account has a \"kubernetes.io/enforce-mountable-secrets\" annotation set to \"true\". This field should not be used to find auto-generated service account token secrets for use outside of pods. Instead, tokens can be requested directly using the TokenRequest API, or service account token secrets can be manually created. More info: https://kubernetes.io/docs/concepts/configuration/secret", + "description": "Secrets is a list of the secrets in the same namespace that pods running using this ServiceAccount are allowed to use. Pods are only limited to this list if this service account has a \"kubernetes.io/enforce-mountable-secrets\" annotation set to \"true\". The \"kubernetes.io/enforce-mountable-secrets\" annotation is deprecated since v1.32. Prefer separate namespaces to isolate access to mounted secrets. This field should not be used to find auto-generated service account token secrets for use outside of pods. Instead, tokens can be requested directly using the TokenRequest API, or service account token secrets can be manually created. More info: https://kubernetes.io/docs/concepts/configuration/secret", "items": { "$ref": "#/definitions/v1.ObjectReference" }, @@ -11282,7 +11939,7 @@ "description": "sessionAffinityConfig contains the configurations of session affinity." }, "trafficDistribution": { - "description": "TrafficDistribution offers a way to express preferences for how traffic is distributed to Service endpoints. Implementations can use this field as a hint, but are not required to guarantee strict adherence. If the field is not set, the implementation will apply its default routing strategy. If set to \"PreferClose\", implementations should prioritize endpoints that are topologically close (e.g., same zone).", + "description": "TrafficDistribution offers a way to express preferences for how traffic is distributed to Service endpoints. Implementations can use this field as a hint, but are not required to guarantee strict adherence. If the field is not set, the implementation will apply its default routing strategy. If set to \"PreferClose\", implementations should prioritize endpoints that are in the same zone.", "type": "string" }, "type": { @@ -11438,7 +12095,7 @@ "type": "string" }, "timeAdded": { - "description": "TimeAdded represents the time at which the taint was added. It is only written for NoExecute taints.", + "description": "TimeAdded represents the time at which the taint was added.", "format": "date-time", "type": "string" }, @@ -11543,11 +12200,11 @@ "type": "integer" }, "nodeAffinityPolicy": { - "description": "NodeAffinityPolicy indicates how we will treat Pod's nodeAffinity/nodeSelector when calculating pod topology spread skew. Options are: - Honor: only nodes matching nodeAffinity/nodeSelector are included in the calculations. - Ignore: nodeAffinity/nodeSelector are ignored. All nodes are included in the calculations.\n\nIf this value is nil, the behavior is equivalent to the Honor policy. This is a beta-level feature default enabled by the NodeInclusionPolicyInPodTopologySpread feature flag.", + "description": "NodeAffinityPolicy indicates how we will treat Pod's nodeAffinity/nodeSelector when calculating pod topology spread skew. Options are: - Honor: only nodes matching nodeAffinity/nodeSelector are included in the calculations. - Ignore: nodeAffinity/nodeSelector are ignored. All nodes are included in the calculations.\n\nIf this value is nil, the behavior is equivalent to the Honor policy.", "type": "string" }, "nodeTaintsPolicy": { - "description": "NodeTaintsPolicy indicates how we will treat node taints when calculating pod topology spread skew. Options are: - Honor: nodes without taints, along with tainted nodes for which the incoming pod has a toleration, are included. - Ignore: node taints are ignored. All nodes are included.\n\nIf this value is nil, the behavior is equivalent to the Ignore policy. This is a beta-level feature default enabled by the NodeInclusionPolicyInPodTopologySpread feature flag.", + "description": "NodeTaintsPolicy indicates how we will treat node taints when calculating pod topology spread skew. Options are: - Honor: nodes without taints, along with tainted nodes for which the incoming pod has a toleration, are included. - Ignore: node taints are ignored. All nodes are included.\n\nIf this value is nil, the behavior is equivalent to the Ignore policy.", "type": "string" }, "topologyKey": { @@ -11590,6 +12247,7 @@ "x-kubernetes-map-type": "atomic" }, "v1.TypedObjectReference": { + "description": "TypedObjectReference contains enough information to let you locate the typed referenced object", "properties": { "apiGroup": { "description": "APIGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the core API group. For any other third-party types, APIGroup is required.", @@ -11619,23 +12277,23 @@ "properties": { "awsElasticBlockStore": { "$ref": "#/definitions/v1.AWSElasticBlockStoreVolumeSource", - "description": "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore" + "description": "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Deprecated: AWSElasticBlockStore is deprecated. All operations for the in-tree awsElasticBlockStore type are redirected to the ebs.csi.aws.com CSI driver. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore" }, "azureDisk": { "$ref": "#/definitions/v1.AzureDiskVolumeSource", - "description": "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod." + "description": "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod. Deprecated: AzureDisk is deprecated. All operations for the in-tree azureDisk type are redirected to the disk.csi.azure.com CSI driver." }, "azureFile": { "$ref": "#/definitions/v1.AzureFileVolumeSource", - "description": "azureFile represents an Azure File Service mount on the host and bind mount to the pod." + "description": "azureFile represents an Azure File Service mount on the host and bind mount to the pod. Deprecated: AzureFile is deprecated. All operations for the in-tree azureFile type are redirected to the file.csi.azure.com CSI driver." }, "cephfs": { "$ref": "#/definitions/v1.CephFSVolumeSource", - "description": "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime" + "description": "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime. Deprecated: CephFS is deprecated and the in-tree cephfs type is no longer supported." }, "cinder": { "$ref": "#/definitions/v1.CinderVolumeSource", - "description": "cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md" + "description": "cinder represents a cinder volume attached and mounted on kubelets host machine. Deprecated: Cinder is deprecated. All operations for the in-tree cinder type are redirected to the cinder.csi.openstack.org CSI driver. More info: https://examples.k8s.io/mysql-cinder-pd/README.md" }, "configMap": { "$ref": "#/definitions/v1.ConfigMapVolumeSource", @@ -11643,7 +12301,7 @@ }, "csi": { "$ref": "#/definitions/v1.CSIVolumeSource", - "description": "csi (Container Storage Interface) represents ephemeral storage that is handled by certain external CSI drivers (Beta feature)." + "description": "csi (Container Storage Interface) represents ephemeral storage that is handled by certain external CSI drivers." }, "downwardAPI": { "$ref": "#/definitions/v1.DownwardAPIVolumeSource", @@ -11663,31 +12321,35 @@ }, "flexVolume": { "$ref": "#/definitions/v1.FlexVolumeSource", - "description": "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin." + "description": "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin. Deprecated: FlexVolume is deprecated. Consider using a CSIDriver instead." }, "flocker": { "$ref": "#/definitions/v1.FlockerVolumeSource", - "description": "flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running" + "description": "flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running. Deprecated: Flocker is deprecated and the in-tree flocker type is no longer supported." }, "gcePersistentDisk": { "$ref": "#/definitions/v1.GCEPersistentDiskVolumeSource", - "description": "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk" + "description": "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Deprecated: GCEPersistentDisk is deprecated. All operations for the in-tree gcePersistentDisk type are redirected to the pd.csi.storage.gke.io CSI driver. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk" }, "gitRepo": { "$ref": "#/definitions/v1.GitRepoVolumeSource", - "description": "gitRepo represents a git repository at a particular revision. DEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container." + "description": "gitRepo represents a git repository at a particular revision. Deprecated: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container." }, "glusterfs": { "$ref": "#/definitions/v1.GlusterfsVolumeSource", - "description": "glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/glusterfs/README.md" + "description": "glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. Deprecated: Glusterfs is deprecated and the in-tree glusterfs type is no longer supported." }, "hostPath": { "$ref": "#/definitions/v1.HostPathVolumeSource", "description": "hostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath" }, + "image": { + "$ref": "#/definitions/v1.ImageVolumeSource", + "description": "image represents an OCI object (a container image or artifact) pulled and mounted on the kubelet's host machine. The volume is resolved at pod startup depending on which PullPolicy value is provided:\n\n- Always: the kubelet always attempts to pull the reference. Container creation will fail If the pull fails. - Never: the kubelet never pulls the reference and only uses a local image or artifact. Container creation will fail if the reference isn't present. - IfNotPresent: the kubelet pulls if the reference isn't already present on disk. Container creation will fail if the reference isn't present and the pull fails.\n\nThe volume gets re-resolved if the pod gets deleted and recreated, which means that new remote content will become available on pod recreation. A failure to resolve or pull the image during pod startup will block containers from starting and may add significant latency. Failures will be retried using normal volume backoff and will be reported on the pod reason and message. The types of objects that may be mounted by this volume are defined by the container runtime implementation on a host machine and at minimum must include all valid types supported by the container image field. The OCI object gets mounted in a single directory (spec.containers[*].volumeMounts.mountPath) by merging the manifest layers in the same way as for container images. The volume will be mounted read-only (ro) and non-executable files (noexec). Sub path mounts for containers are not supported (spec.containers[*].volumeMounts.subpath) before 1.33. The field spec.securityContext.fsGroupChangePolicy has no effect on this volume type." + }, "iscsi": { "$ref": "#/definitions/v1.ISCSIVolumeSource", - "description": "iscsi represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://examples.k8s.io/volumes/iscsi/README.md" + "description": "iscsi represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes/#iscsi" }, "name": { "description": "name of the volume. Must be a DNS_LABEL and unique within the pod. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", @@ -11703,11 +12365,11 @@ }, "photonPersistentDisk": { "$ref": "#/definitions/v1.PhotonPersistentDiskVolumeSource", - "description": "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine" + "description": "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine. Deprecated: PhotonPersistentDisk is deprecated and the in-tree photonPersistentDisk type is no longer supported." }, "portworxVolume": { "$ref": "#/definitions/v1.PortworxVolumeSource", - "description": "portworxVolume represents a portworx volume attached and mounted on kubelets host machine" + "description": "portworxVolume represents a portworx volume attached and mounted on kubelets host machine. Deprecated: PortworxVolume is deprecated. All operations for the in-tree portworxVolume type are redirected to the pxd.portworx.com CSI driver when the CSIMigrationPortworx feature-gate is on." }, "projected": { "$ref": "#/definitions/v1.ProjectedVolumeSource", @@ -11715,15 +12377,15 @@ }, "quobyte": { "$ref": "#/definitions/v1.QuobyteVolumeSource", - "description": "quobyte represents a Quobyte mount on the host that shares a pod's lifetime" + "description": "quobyte represents a Quobyte mount on the host that shares a pod's lifetime. Deprecated: Quobyte is deprecated and the in-tree quobyte type is no longer supported." }, "rbd": { "$ref": "#/definitions/v1.RBDVolumeSource", - "description": "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md" + "description": "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. Deprecated: RBD is deprecated and the in-tree rbd type is no longer supported." }, "scaleIO": { "$ref": "#/definitions/v1.ScaleIOVolumeSource", - "description": "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes." + "description": "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes. Deprecated: ScaleIO is deprecated and the in-tree scaleIO type is no longer supported." }, "secret": { "$ref": "#/definitions/v1.SecretVolumeSource", @@ -11731,11 +12393,11 @@ }, "storageos": { "$ref": "#/definitions/v1.StorageOSVolumeSource", - "description": "storageOS represents a StorageOS volume attached and mounted on Kubernetes nodes." + "description": "storageOS represents a StorageOS volume attached and mounted on Kubernetes nodes. Deprecated: StorageOS is deprecated and the in-tree storageos type is no longer supported." }, "vsphereVolume": { "$ref": "#/definitions/v1.VsphereVirtualDiskVolumeSource", - "description": "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine" + "description": "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine. Deprecated: VsphereVolume is deprecated. All operations for the in-tree vsphereVolume type are redirected to the csi.vsphere.vmware.com CSI driver." } }, "required": [ @@ -11836,7 +12498,7 @@ "type": "object" }, "v1.VolumeProjection": { - "description": "Projection that may be projected along with other supported volume types", + "description": "Projection that may be projected along with other supported volume types. Exactly one of these fields must be set.", "properties": { "clusterTrustBundle": { "$ref": "#/definitions/v1.ClusterTrustBundleProjection", @@ -11850,6 +12512,10 @@ "$ref": "#/definitions/v1.DownwardAPIProjection", "description": "downwardAPI information about the downwardAPI data to project" }, + "podCertificate": { + "$ref": "#/definitions/v1.PodCertificateProjection", + "description": "Projects an auto-rotating credential bundle (private key and certificate chain) that the pod can use either as a TLS client or server.\n\nKubelet generates a private key and uses it to send a PodCertificateRequest to the named signer. Once the signer approves the request and issues a certificate chain, Kubelet writes the key and certificate chain to the pod filesystem. The pod does not start until certificates have been issued for each podCertificate projected volume source in its spec.\n\nKubelet will begin trying to rotate the certificate at the time indicated by the signer using the PodCertificateRequest.Status.BeginRefreshAt timestamp.\n\nKubelet can write a single file, indicated by the credentialBundlePath field, or separate files, indicated by the keyPath and certificateChainPath fields.\n\nThe credential bundle is a single file in PEM format. The first PEM entry is the private key (in PKCS#8 format), and the remaining PEM entries are the certificate chain issued by the signer (typically, signers will return their certificate chain in leaf-to-root order).\n\nPrefer using the credential bundle format, since your application code can read it atomically. If you use keyPath and certificateChainPath, your application must make two separate file reads. If these coincide with a certificate rotation, it is possible that the private key and leaf certificate you read may not correspond to each other. Your application will need to check for this condition, and re-read until they are consistent.\n\nThe named signer controls chooses the format of the certificate it issues; consult the signer implementation's documentation to learn how to use the certificates it issues." + }, "secret": { "$ref": "#/definitions/v1.SecretProjection", "description": "secret information about the secret data to project" @@ -11951,7 +12617,7 @@ "description": "Endpoint represents a single logical \"backend\" implementing a service.", "properties": { "addresses": { - "description": "addresses of this endpoint. The contents of this field are interpreted according to the corresponding EndpointSlice addressType field. Consumers must handle different types of addresses in the context of their own capabilities. This must contain at least one address but no more than 100. These are all assumed to be fungible and clients may choose to only use the first element. Refer to: https://issue.k8s.io/106267", + "description": "addresses of this endpoint. For EndpointSlices of addressType \"IPv4\" or \"IPv6\", the values are IP addresses in canonical form. The syntax and semantics of other addressType values are not defined. This must contain at least one address but no more than 100. EndpointSlices generated by the EndpointSlice controller will always have exactly 1 address. No semantics are defined for additional addresses beyond the first, and kube-proxy does not look at them.", "items": { "type": "string" }, @@ -11999,15 +12665,15 @@ "description": "EndpointConditions represents the current condition of an endpoint.", "properties": { "ready": { - "description": "ready indicates that this endpoint is prepared to receive traffic, according to whatever system is managing the endpoint. A nil value indicates an unknown state. In most cases consumers should interpret this unknown state as ready. For compatibility reasons, ready should never be \"true\" for terminating endpoints, except when the normal readiness behavior is being explicitly overridden, for example when the associated Service has set the publishNotReadyAddresses flag.", + "description": "ready indicates that this endpoint is ready to receive traffic, according to whatever system is managing the endpoint. A nil value should be interpreted as \"true\". In general, an endpoint should be marked ready if it is serving and not terminating, though this can be overridden in some cases, such as when the associated Service has set the publishNotReadyAddresses flag.", "type": "boolean" }, "serving": { - "description": "serving is identical to ready except that it is set regardless of the terminating state of endpoints. This condition should be set to true for a ready endpoint that is terminating. If nil, consumers should defer to the ready condition.", + "description": "serving indicates that this endpoint is able to receive traffic, according to whatever system is managing the endpoint. For endpoints backed by pods, the EndpointSlice controller will mark the endpoint as serving if the pod's Ready condition is True. A nil value should be interpreted as \"true\".", "type": "boolean" }, "terminating": { - "description": "terminating indicates that this endpoint is terminating. A nil value indicates an unknown state. Consumers should interpret this unknown state to mean that the endpoint is not terminating.", + "description": "terminating indicates that this endpoint is terminating. A nil value should be interpreted as \"false\".", "type": "boolean" } }, @@ -12016,8 +12682,16 @@ "v1.EndpointHints": { "description": "EndpointHints provides hints describing how an endpoint should be consumed.", "properties": { + "forNodes": { + "description": "forNodes indicates the node(s) this endpoint should be consumed by when using topology aware routing. May contain a maximum of 8 entries. This is an Alpha feature and is only used when the PreferSameTrafficDistribution feature gate is enabled.", + "items": { + "$ref": "#/definitions/v1.ForNode" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, "forZones": { - "description": "forZones indicates the zone(s) this endpoint should be consumed by to enable topology aware routing.", + "description": "forZones indicates the zone(s) this endpoint should be consumed by when using topology aware routing. May contain a maximum of 8 entries.", "items": { "$ref": "#/definitions/v1.ForZone" }, @@ -12039,7 +12713,7 @@ "type": "string" }, "port": { - "description": "port represents the port number of the endpoint. If this is not specified, ports are not restricted and must be interpreted in the context of the specific consumer.", + "description": "port represents the port number of the endpoint. If the EndpointSlice is derived from a Kubernetes service, this must be set to the service's target port. EndpointSlices used for other purposes may have a nil port.", "format": "int32", "type": "integer" }, @@ -12052,10 +12726,10 @@ "x-kubernetes-map-type": "atomic" }, "v1.EndpointSlice": { - "description": "EndpointSlice represents a subset of the endpoints that implement a service. For a given service there may be multiple EndpointSlice objects, selected by labels, which must be joined to produce the full set of endpoints.", + "description": "EndpointSlice represents a set of service endpoints. Most EndpointSlices are created by the EndpointSlice controller to represent the Pods selected by Service objects. For a given service there may be multiple EndpointSlice objects which must be joined to produce the full set of endpoints; you can find all of the slices for a given service by listing EndpointSlices in the service's namespace whose `kubernetes.io/service-name` label contains the service's name.", "properties": { "addressType": { - "description": "addressType specifies the type of address carried by this EndpointSlice. All addresses in this slice must be the same type. This field is immutable after creation. The following address types are currently supported: * IPv4: Represents an IPv4 Address. * IPv6: Represents an IPv6 Address. * FQDN: Represents a Fully Qualified Domain Name.", + "description": "addressType specifies the type of address carried by this EndpointSlice. All addresses in this slice must be the same type. This field is immutable after creation. The following address types are currently supported: * IPv4: Represents an IPv4 Address. * IPv6: Represents an IPv6 Address. * FQDN: Represents a Fully Qualified Domain Name. (Deprecated) The EndpointSlice controller only generates, and kube-proxy only processes, slices of addressType \"IPv4\" and \"IPv6\". No semantics are defined for the \"FQDN\" type.", "type": "string" }, "apiVersion": { @@ -12079,7 +12753,7 @@ "description": "Standard object's metadata." }, "ports": { - "description": "ports specifies the list of network ports exposed by each endpoint in this slice. Each port must have a unique name. When ports is empty, it indicates that there are no defined ports. When a port is defined with a nil port value, it indicates \"all ports\". Each slice may include a maximum of 100 ports.", + "description": "ports specifies the list of network ports exposed by each endpoint in this slice. Each port must have a unique name. Each slice may include a maximum of 100 ports. Services always have at least 1 port, so EndpointSlices generated by the EndpointSlice controller will likewise always have at least 1 port. EndpointSlices used for other purposes may have an empty ports list.", "items": { "$ref": "#/definitions/discovery.v1.EndpointPort" }, @@ -12135,6 +12809,19 @@ } ] }, + "v1.ForNode": { + "description": "ForNode provides information about which nodes should consume this endpoint.", + "properties": { + "name": { + "description": "name represents the name of the node.", + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, "v1.ForZone": { "description": "ForZone provides information about which zones should consume this endpoint.", "properties": { @@ -12877,37 +13564,47 @@ ], "type": "object" }, - "v1beta3.ExemptPriorityLevelConfiguration": { - "description": "ExemptPriorityLevelConfiguration describes the configurable aspects of the handling of exempt requests. In the mandatory exempt configuration object the values in the fields here can be modified by authorized users, unlike the rest of the `spec`.", + "v1.HTTPIngressPath": { + "description": "HTTPIngressPath associates a path with a backend. Incoming urls matching the path are forwarded to the backend.", "properties": { - "lendablePercent": { - "description": "`lendablePercent` prescribes the fraction of the level's NominalCL that can be borrowed by other priority levels. This value of this field must be between 0 and 100, inclusive, and it defaults to 0. The number of seats that other levels can borrow from this level, known as this level's LendableConcurrencyLimit (LendableCL), is defined as follows.\n\nLendableCL(i) = round( NominalCL(i) * lendablePercent(i)/100.0 )", - "format": "int32", - "type": "integer" + "backend": { + "$ref": "#/definitions/v1.IngressBackend", + "description": "backend defines the referenced service endpoint to which the traffic will be forwarded to." }, - "nominalConcurrencyShares": { - "description": "`nominalConcurrencyShares` (NCS) contributes to the computation of the NominalConcurrencyLimit (NominalCL) of this level. This is the number of execution seats nominally reserved for this priority level. This DOES NOT limit the dispatching from this priority level but affects the other priority levels through the borrowing mechanism. The server's concurrency limit (ServerCL) is divided among all the priority levels in proportion to their NCS values:\n\nNominalCL(i) = ceil( ServerCL * NCS(i) / sum_ncs ) sum_ncs = sum[priority level k] NCS(k)\n\nBigger numbers mean a larger nominal concurrency limit, at the expense of every other priority level. This field has a default value of zero.", - "format": "int32", - "type": "integer" + "path": { + "description": "path is matched against the path of an incoming request. Currently it can contain characters disallowed from the conventional \"path\" part of a URL as defined by RFC 3986. Paths must begin with a '/' and must be present when using PathType with value \"Exact\" or \"Prefix\".", + "type": "string" + }, + "pathType": { + "description": "pathType determines the interpretation of the path matching. PathType can be one of the following values: * Exact: Matches the URL path exactly. * Prefix: Matches based on a URL path prefix split by '/'. Matching is\n done on a path element by element basis. A path element refers is the\n list of labels in the path split by the '/' separator. A request is a\n match for path p if every p is an element-wise prefix of p of the\n request path. Note that if the last element of the path is a substring\n of the last element in request path, it is not a match (e.g. /foo/bar\n matches /foo/bar/baz, but does not match /foo/barbaz).\n* ImplementationSpecific: Interpretation of the Path matching is up to\n the IngressClass. Implementations can treat this as a separate PathType\n or treat it identically to Prefix or Exact path types.\nImplementations are required to support all path types.", + "type": "string" } }, + "required": [ + "pathType", + "backend" + ], "type": "object" }, - "v1beta3.FlowDistinguisherMethod": { - "description": "FlowDistinguisherMethod specifies the method of a flow distinguisher.", + "v1.HTTPIngressRuleValue": { + "description": "HTTPIngressRuleValue is a list of http selectors pointing to backends. In the example: http:///? -> backend where where parts of the url correspond to RFC 3986, this resource will be used to match against everything after the last '/' and before the first '?' or '#'.", "properties": { - "type": { - "description": "`type` is the type of flow distinguisher method The supported types are \"ByUser\" and \"ByNamespace\". Required.", - "type": "string" + "paths": { + "description": "paths is a collection of paths that map requests to backends.", + "items": { + "$ref": "#/definitions/v1.HTTPIngressPath" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" } }, "required": [ - "type" + "paths" ], "type": "object" }, - "v1beta3.FlowSchema": { - "description": "FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with similar attributes and is identified by a pair of strings: the name of the FlowSchema and a \"flow distinguisher\".", + "v1.IPAddress": { + "description": "IPAddress represents a single IP of a single IP Family. The object is designed to be used by APIs that operate on IP addresses. The object is used by the Service core API for allocation of IP addresses. An IP address can be represented in different formats, to guarantee the uniqueness of the IP, the name of the object is the IP address in canonical format, four decimal digits separated by dots suppressing leading zeros for IPv4 and the representation defined by RFC 5952 for IPv6. Valid: 192.168.1.5 or 2001:db8::1 or 2001:db8:aaaa:bbbb:cccc:dddd:eeee:1 Invalid: 10.01.2.3 or 2001:db8:0:0:0::1", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -12919,64 +13616,33 @@ }, "metadata": { "$ref": "#/definitions/v1.ObjectMeta", - "description": "`metadata` is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" + "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" }, "spec": { - "$ref": "#/definitions/v1beta3.FlowSchemaSpec", - "description": "`spec` is the specification of the desired behavior of a FlowSchema. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" - }, - "status": { - "$ref": "#/definitions/v1beta3.FlowSchemaStatus", - "description": "`status` is the current status of a FlowSchema. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" + "$ref": "#/definitions/v1.IPAddressSpec", + "description": "spec is the desired state of the IPAddress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" } }, "type": "object", "x-kubernetes-group-version-kind": [ { - "group": "flowcontrol.apiserver.k8s.io", - "kind": "FlowSchema", - "version": "v1beta3" + "group": "networking.k8s.io", + "kind": "IPAddress", + "version": "v1" } ] }, - "v1beta3.FlowSchemaCondition": { - "description": "FlowSchemaCondition describes conditions for a FlowSchema.", - "properties": { - "lastTransitionTime": { - "description": "`lastTransitionTime` is the last time the condition transitioned from one status to another.", - "format": "date-time", - "type": "string" - }, - "message": { - "description": "`message` is a human-readable message indicating details about last transition.", - "type": "string" - }, - "reason": { - "description": "`reason` is a unique, one-word, CamelCase reason for the condition's last transition.", - "type": "string" - }, - "status": { - "description": "`status` is the status of the condition. Can be True, False, Unknown. Required.", - "type": "string" - }, - "type": { - "description": "`type` is the type of the condition. Required.", - "type": "string" - } - }, - "type": "object" - }, - "v1beta3.FlowSchemaList": { - "description": "FlowSchemaList is a list of FlowSchema objects.", + "v1.IPAddressList": { + "description": "IPAddressList contains a list of IPAddress.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", "type": "string" }, "items": { - "description": "`items` is a list of FlowSchemas.", + "description": "items is the list of IPAddresses.", "items": { - "$ref": "#/definitions/v1beta3.FlowSchema" + "$ref": "#/definitions/v1.IPAddress" }, "type": "array" }, @@ -12986,7 +13652,7 @@ }, "metadata": { "$ref": "#/definitions/v1.ListMeta", - "description": "`metadata` is the standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" + "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" } }, "required": [ @@ -12995,185 +13661,48 @@ "type": "object", "x-kubernetes-group-version-kind": [ { - "group": "flowcontrol.apiserver.k8s.io", - "kind": "FlowSchemaList", - "version": "v1beta3" + "group": "networking.k8s.io", + "kind": "IPAddressList", + "version": "v1" } ] }, - "v1beta3.FlowSchemaSpec": { - "description": "FlowSchemaSpec describes how the FlowSchema's specification looks like.", - "properties": { - "distinguisherMethod": { - "$ref": "#/definitions/v1beta3.FlowDistinguisherMethod", - "description": "`distinguisherMethod` defines how to compute the flow distinguisher for requests that match this schema. `nil` specifies that the distinguisher is disabled and thus will always be the empty string." - }, - "matchingPrecedence": { - "description": "`matchingPrecedence` is used to choose among the FlowSchemas that match a given request. The chosen FlowSchema is among those with the numerically lowest (which we take to be logically highest) MatchingPrecedence. Each MatchingPrecedence value must be ranged in [1,10000]. Note that if the precedence is not specified, it will be set to 1000 as default.", - "format": "int32", - "type": "integer" - }, - "priorityLevelConfiguration": { - "$ref": "#/definitions/v1beta3.PriorityLevelConfigurationReference", - "description": "`priorityLevelConfiguration` should reference a PriorityLevelConfiguration in the cluster. If the reference cannot be resolved, the FlowSchema will be ignored and marked as invalid in its status. Required." - }, - "rules": { - "description": "`rules` describes which requests will match this flow schema. This FlowSchema matches a request if and only if at least one member of rules matches the request. if it is an empty slice, there will be no requests matching the FlowSchema.", - "items": { - "$ref": "#/definitions/v1beta3.PolicyRulesWithSubjects" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - } - }, - "required": [ - "priorityLevelConfiguration" - ], - "type": "object" - }, - "v1beta3.FlowSchemaStatus": { - "description": "FlowSchemaStatus represents the current state of a FlowSchema.", - "properties": { - "conditions": { - "description": "`conditions` is a list of the current states of FlowSchema.", - "items": { - "$ref": "#/definitions/v1beta3.FlowSchemaCondition" - }, - "type": "array", - "x-kubernetes-list-map-keys": [ - "type" - ], - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge" - } - }, - "type": "object" - }, - "v1beta3.GroupSubject": { - "description": "GroupSubject holds detailed information for group-kind subject.", + "v1.IPAddressSpec": { + "description": "IPAddressSpec describe the attributes in an IP Address.", "properties": { - "name": { - "description": "name is the user group that matches, or \"*\" to match all user groups. See https://github.com/kubernetes/apiserver/blob/master/pkg/authentication/user/user.go for some well-known group names. Required.", - "type": "string" + "parentRef": { + "$ref": "#/definitions/v1.ParentReference", + "description": "ParentRef references the resource that an IPAddress is attached to. An IPAddress must reference a parent object." } }, "required": [ - "name" + "parentRef" ], "type": "object" }, - "v1beta3.LimitResponse": { - "description": "LimitResponse defines how to handle requests that can not be executed right now.", + "v1.IPBlock": { + "description": "IPBlock describes a particular CIDR (Ex. \"192.168.1.0/24\",\"2001:db8::/64\") that is allowed to the pods matched by a NetworkPolicySpec's podSelector. The except entry describes CIDRs that should not be included within this rule.", "properties": { - "queuing": { - "$ref": "#/definitions/v1beta3.QueuingConfiguration", - "description": "`queuing` holds the configuration parameters for queuing. This field may be non-empty only if `type` is `\"Queue\"`." - }, - "type": { - "description": "`type` is \"Queue\" or \"Reject\". \"Queue\" means that requests that can not be executed upon arrival are held in a queue until they can be executed or a queuing limit is reached. \"Reject\" means that requests that can not be executed upon arrival are rejected. Required.", + "cidr": { + "description": "cidr is a string representing the IPBlock Valid examples are \"192.168.1.0/24\" or \"2001:db8::/64\"", "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object", - "x-kubernetes-unions": [ - { - "discriminator": "type", - "fields-to-discriminateBy": { - "queuing": "Queuing" - } - } - ] - }, - "v1beta3.LimitedPriorityLevelConfiguration": { - "description": "LimitedPriorityLevelConfiguration specifies how to handle requests that are subject to limits. It addresses two issues:\n - How are requests for this priority level limited?\n - What should be done with requests that exceed the limit?", - "properties": { - "borrowingLimitPercent": { - "description": "`borrowingLimitPercent`, if present, configures a limit on how many seats this priority level can borrow from other priority levels. The limit is known as this level's BorrowingConcurrencyLimit (BorrowingCL) and is a limit on the total number of seats that this level may borrow at any one time. This field holds the ratio of that limit to the level's nominal concurrency limit. When this field is non-nil, it must hold a non-negative integer and the limit is calculated as follows.\n\nBorrowingCL(i) = round( NominalCL(i) * borrowingLimitPercent(i)/100.0 )\n\nThe value of this field can be more than 100, implying that this priority level can borrow a number of seats that is greater than its own nominal concurrency limit (NominalCL). When this field is left `nil`, the limit is effectively infinite.", - "format": "int32", - "type": "integer" - }, - "lendablePercent": { - "description": "`lendablePercent` prescribes the fraction of the level's NominalCL that can be borrowed by other priority levels. The value of this field must be between 0 and 100, inclusive, and it defaults to 0. The number of seats that other levels can borrow from this level, known as this level's LendableConcurrencyLimit (LendableCL), is defined as follows.\n\nLendableCL(i) = round( NominalCL(i) * lendablePercent(i)/100.0 )", - "format": "int32", - "type": "integer" - }, - "limitResponse": { - "$ref": "#/definitions/v1beta3.LimitResponse", - "description": "`limitResponse` indicates what to do with requests that can not be executed right now" - }, - "nominalConcurrencyShares": { - "description": "`nominalConcurrencyShares` (NCS) contributes to the computation of the NominalConcurrencyLimit (NominalCL) of this level. This is the number of execution seats available at this priority level. This is used both for requests dispatched from this priority level as well as requests dispatched from other priority levels borrowing seats from this level. The server's concurrency limit (ServerCL) is divided among the Limited priority levels in proportion to their NCS values:\n\nNominalCL(i) = ceil( ServerCL * NCS(i) / sum_ncs ) sum_ncs = sum[priority level k] NCS(k)\n\nBigger numbers mean a larger nominal concurrency limit, at the expense of every other priority level. This field has a default value of 30.", - "format": "int32", - "type": "integer" - } - }, - "type": "object" - }, - "v1beta3.NonResourcePolicyRule": { - "description": "NonResourcePolicyRule is a predicate that matches non-resource requests according to their verb and the target non-resource URL. A NonResourcePolicyRule matches a request if and only if both (a) at least one member of verbs matches the request and (b) at least one member of nonResourceURLs matches the request.", - "properties": { - "nonResourceURLs": { - "description": "`nonResourceURLs` is a set of url prefixes that a user should have access to and may not be empty. For example:\n - \"/healthz\" is legal\n - \"/hea*\" is illegal\n - \"/hea\" is legal but matches nothing\n - \"/hea/*\" also matches nothing\n - \"/healthz/*\" matches all per-component health checks.\n\"*\" matches all non-resource urls. if it is present, it must be the only entry. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "set" }, - "verbs": { - "description": "`verbs` is a list of matching verbs and may not be empty. \"*\" matches all verbs. If it is present, it must be the only entry. Required.", + "except": { + "description": "except is a slice of CIDRs that should not be included within an IPBlock Valid examples are \"192.168.1.0/24\" or \"2001:db8::/64\" Except values will be rejected if they are outside the cidr range", "items": { "type": "string" }, "type": "array", - "x-kubernetes-list-type": "set" - } - }, - "required": [ - "verbs", - "nonResourceURLs" - ], - "type": "object" - }, - "v1beta3.PolicyRulesWithSubjects": { - "description": "PolicyRulesWithSubjects prescribes a test that applies to a request to an apiserver. The test considers the subject making the request, the verb being requested, and the resource to be acted upon. This PolicyRulesWithSubjects matches a request if and only if both (a) at least one member of subjects matches the request and (b) at least one member of resourceRules or nonResourceRules matches the request.", - "properties": { - "nonResourceRules": { - "description": "`nonResourceRules` is a list of NonResourcePolicyRules that identify matching requests according to their verb and the target non-resource URL.", - "items": { - "$ref": "#/definitions/v1beta3.NonResourcePolicyRule" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "resourceRules": { - "description": "`resourceRules` is a slice of ResourcePolicyRules that identify matching requests according to their verb and the target resource. At least one of `resourceRules` and `nonResourceRules` has to be non-empty.", - "items": { - "$ref": "#/definitions/v1beta3.ResourcePolicyRule" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - }, - "subjects": { - "description": "subjects is the list of normal user, serviceaccount, or group that this rule cares about. There must be at least one member in this slice. A slice that includes both the system:authenticated and system:unauthenticated user groups matches every request. Required.", - "items": { - "$ref": "#/definitions/v1beta3.Subject" - }, - "type": "array", "x-kubernetes-list-type": "atomic" } }, "required": [ - "subjects" + "cidr" ], "type": "object" }, - "v1beta3.PriorityLevelConfiguration": { - "description": "PriorityLevelConfiguration represents the configuration of a priority level.", + "v1.Ingress": { + "description": "Ingress is a collection of rules that allow inbound connections to reach the endpoints defined by a backend. An Ingress can be configured to give services externally-reachable urls, load balance traffic, terminate SSL, offer name based virtual hosting etc.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -13185,64 +13714,80 @@ }, "metadata": { "$ref": "#/definitions/v1.ObjectMeta", - "description": "`metadata` is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" + "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" }, "spec": { - "$ref": "#/definitions/v1beta3.PriorityLevelConfigurationSpec", - "description": "`spec` is the specification of the desired behavior of a \"request-priority\". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" + "$ref": "#/definitions/v1.IngressSpec", + "description": "spec is the desired state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" }, "status": { - "$ref": "#/definitions/v1beta3.PriorityLevelConfigurationStatus", - "description": "`status` is the current status of a \"request-priority\". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" + "$ref": "#/definitions/v1.IngressStatus", + "description": "status is the current state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" } }, "type": "object", "x-kubernetes-group-version-kind": [ { - "group": "flowcontrol.apiserver.k8s.io", - "kind": "PriorityLevelConfiguration", - "version": "v1beta3" + "group": "networking.k8s.io", + "kind": "Ingress", + "version": "v1" } ] }, - "v1beta3.PriorityLevelConfigurationCondition": { - "description": "PriorityLevelConfigurationCondition defines the condition of priority level.", + "v1.IngressBackend": { + "description": "IngressBackend describes all endpoints for a given service and port.", "properties": { - "lastTransitionTime": { - "description": "`lastTransitionTime` is the last time the condition transitioned from one status to another.", - "format": "date-time", - "type": "string" + "resource": { + "$ref": "#/definitions/v1.TypedLocalObjectReference", + "description": "resource is an ObjectRef to another Kubernetes resource in the namespace of the Ingress object. If resource is specified, a service.Name and service.Port must not be specified. This is a mutually exclusive setting with \"Service\"." }, - "message": { - "description": "`message` is a human-readable message indicating details about last transition.", + "service": { + "$ref": "#/definitions/v1.IngressServiceBackend", + "description": "service references a service as a backend. This is a mutually exclusive setting with \"Resource\"." + } + }, + "type": "object" + }, + "v1.IngressClass": { + "description": "IngressClass represents the class of the Ingress, referenced by the Ingress Spec. The `ingressclass.kubernetes.io/is-default-class` annotation can be used to indicate that an IngressClass should be considered default. When a single IngressClass resource has this annotation set to true, new Ingress resources without a class specified will be assigned this default class.", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", "type": "string" }, - "reason": { - "description": "`reason` is a unique, one-word, CamelCase reason for the condition's last transition.", + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", "type": "string" }, - "status": { - "description": "`status` is the status of the condition. Can be True, False, Unknown. Required.", - "type": "string" + "metadata": { + "$ref": "#/definitions/v1.ObjectMeta", + "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" }, - "type": { - "description": "`type` is the type of the condition. Required.", - "type": "string" + "spec": { + "$ref": "#/definitions/v1.IngressClassSpec", + "description": "spec is the desired state of the IngressClass. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" } }, - "type": "object" + "type": "object", + "x-kubernetes-group-version-kind": [ + { + "group": "networking.k8s.io", + "kind": "IngressClass", + "version": "v1" + } + ] }, - "v1beta3.PriorityLevelConfigurationList": { - "description": "PriorityLevelConfigurationList is a list of PriorityLevelConfiguration objects.", + "v1.IngressClassList": { + "description": "IngressClassList is a collection of IngressClasses.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", "type": "string" }, "items": { - "description": "`items` is a list of request-priorities.", + "description": "items is the list of IngressClasses.", "items": { - "$ref": "#/definitions/v1beta3.PriorityLevelConfiguration" + "$ref": "#/definitions/v1.IngressClass" }, "type": "array" }, @@ -13252,7 +13797,7 @@ }, "metadata": { "$ref": "#/definitions/v1.ListMeta", - "description": "`metadata` is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" + "description": "Standard list metadata." } }, "required": [ @@ -13261,400 +13806,33 @@ "type": "object", "x-kubernetes-group-version-kind": [ { - "group": "flowcontrol.apiserver.k8s.io", - "kind": "PriorityLevelConfigurationList", - "version": "v1beta3" + "group": "networking.k8s.io", + "kind": "IngressClassList", + "version": "v1" } ] }, - "v1beta3.PriorityLevelConfigurationReference": { - "description": "PriorityLevelConfigurationReference contains information that points to the \"request-priority\" being used.", + "v1.IngressClassParametersReference": { + "description": "IngressClassParametersReference identifies an API object. This can be used to specify a cluster or namespace-scoped resource.", "properties": { + "apiGroup": { + "description": "apiGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the core API group. For any other third-party types, APIGroup is required.", + "type": "string" + }, + "kind": { + "description": "kind is the type of resource being referenced.", + "type": "string" + }, "name": { - "description": "`name` is the name of the priority level configuration being referenced Required.", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "v1beta3.PriorityLevelConfigurationSpec": { - "description": "PriorityLevelConfigurationSpec specifies the configuration of a priority level.", - "properties": { - "exempt": { - "$ref": "#/definitions/v1beta3.ExemptPriorityLevelConfiguration", - "description": "`exempt` specifies how requests are handled for an exempt priority level. This field MUST be empty if `type` is `\"Limited\"`. This field MAY be non-empty if `type` is `\"Exempt\"`. If empty and `type` is `\"Exempt\"` then the default values for `ExemptPriorityLevelConfiguration` apply." - }, - "limited": { - "$ref": "#/definitions/v1beta3.LimitedPriorityLevelConfiguration", - "description": "`limited` specifies how requests are handled for a Limited priority level. This field must be non-empty if and only if `type` is `\"Limited\"`." - }, - "type": { - "description": "`type` indicates whether this priority level is subject to limitation on request execution. A value of `\"Exempt\"` means that requests of this priority level are not subject to a limit (and thus are never queued) and do not detract from the capacity made available to other priority levels. A value of `\"Limited\"` means that (a) requests of this priority level _are_ subject to limits and (b) some of the server's limited capacity is made available exclusively to this priority level. Required.", - "type": "string" - } - }, - "required": [ - "type" - ], - "type": "object", - "x-kubernetes-unions": [ - { - "discriminator": "type", - "fields-to-discriminateBy": { - "exempt": "Exempt", - "limited": "Limited" - } - } - ] - }, - "v1beta3.PriorityLevelConfigurationStatus": { - "description": "PriorityLevelConfigurationStatus represents the current state of a \"request-priority\".", - "properties": { - "conditions": { - "description": "`conditions` is the current state of \"request-priority\".", - "items": { - "$ref": "#/definitions/v1beta3.PriorityLevelConfigurationCondition" - }, - "type": "array", - "x-kubernetes-list-map-keys": [ - "type" - ], - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge" - } - }, - "type": "object" - }, - "v1beta3.QueuingConfiguration": { - "description": "QueuingConfiguration holds the configuration parameters for queuing", - "properties": { - "handSize": { - "description": "`handSize` is a small positive number that configures the shuffle sharding of requests into queues. When enqueuing a request at this priority level the request's flow identifier (a string pair) is hashed and the hash value is used to shuffle the list of queues and deal a hand of the size specified here. The request is put into one of the shortest queues in that hand. `handSize` must be no larger than `queues`, and should be significantly smaller (so that a few heavy flows do not saturate most of the queues). See the user-facing documentation for more extensive guidance on setting this field. This field has a default value of 8.", - "format": "int32", - "type": "integer" - }, - "queueLengthLimit": { - "description": "`queueLengthLimit` is the maximum number of requests allowed to be waiting in a given queue of this priority level at a time; excess requests are rejected. This value must be positive. If not specified, it will be defaulted to 50.", - "format": "int32", - "type": "integer" - }, - "queues": { - "description": "`queues` is the number of queues for this priority level. The queues exist independently at each apiserver. The value must be positive. Setting it to 1 effectively precludes shufflesharding and thus makes the distinguisher method of associated flow schemas irrelevant. This field has a default value of 64.", - "format": "int32", - "type": "integer" - } - }, - "type": "object" - }, - "v1beta3.ResourcePolicyRule": { - "description": "ResourcePolicyRule is a predicate that matches some resource requests, testing the request's verb and the target resource. A ResourcePolicyRule matches a resource request if and only if: (a) at least one member of verbs matches the request, (b) at least one member of apiGroups matches the request, (c) at least one member of resources matches the request, and (d) either (d1) the request does not specify a namespace (i.e., `Namespace==\"\"`) and clusterScope is true or (d2) the request specifies a namespace and least one member of namespaces matches the request's namespace.", - "properties": { - "apiGroups": { - "description": "`apiGroups` is a list of matching API groups and may not be empty. \"*\" matches all API groups and, if present, must be the only entry. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "set" - }, - "clusterScope": { - "description": "`clusterScope` indicates whether to match requests that do not specify a namespace (which happens either because the resource is not namespaced or the request targets all namespaces). If this field is omitted or false then the `namespaces` field must contain a non-empty list.", - "type": "boolean" - }, - "namespaces": { - "description": "`namespaces` is a list of target namespaces that restricts matches. A request that specifies a target namespace matches only if either (a) this list contains that target namespace or (b) this list contains \"*\". Note that \"*\" matches any specified namespace but does not match a request that _does not specify_ a namespace (see the `clusterScope` field for that). This list may be empty, but only if `clusterScope` is true.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "set" - }, - "resources": { - "description": "`resources` is a list of matching resources (i.e., lowercase and plural) with, if desired, subresource. For example, [ \"services\", \"nodes/status\" ]. This list may not be empty. \"*\" matches all resources and, if present, must be the only entry. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "set" - }, - "verbs": { - "description": "`verbs` is a list of matching verbs and may not be empty. \"*\" matches all verbs and, if present, must be the only entry. Required.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "set" - } - }, - "required": [ - "verbs", - "apiGroups", - "resources" - ], - "type": "object" - }, - "v1beta3.ServiceAccountSubject": { - "description": "ServiceAccountSubject holds detailed information for service-account-kind subject.", - "properties": { - "name": { - "description": "`name` is the name of matching ServiceAccount objects, or \"*\" to match regardless of name. Required.", - "type": "string" - }, - "namespace": { - "description": "`namespace` is the namespace of matching ServiceAccount objects. Required.", - "type": "string" - } - }, - "required": [ - "namespace", - "name" - ], - "type": "object" - }, - "v1beta3.Subject": { - "description": "Subject matches the originator of a request, as identified by the request authentication system. There are three ways of matching an originator; by user, group, or service account.", - "properties": { - "group": { - "$ref": "#/definitions/v1beta3.GroupSubject", - "description": "`group` matches based on user group name." - }, - "kind": { - "description": "`kind` indicates which one of the other fields is non-empty. Required", - "type": "string" - }, - "serviceAccount": { - "$ref": "#/definitions/v1beta3.ServiceAccountSubject", - "description": "`serviceAccount` matches ServiceAccounts." - }, - "user": { - "$ref": "#/definitions/v1beta3.UserSubject", - "description": "`user` matches based on username." - } - }, - "required": [ - "kind" - ], - "type": "object", - "x-kubernetes-unions": [ - { - "discriminator": "kind", - "fields-to-discriminateBy": { - "group": "Group", - "serviceAccount": "ServiceAccount", - "user": "User" - } - } - ] - }, - "v1beta3.UserSubject": { - "description": "UserSubject holds detailed information for user-kind subject.", - "properties": { - "name": { - "description": "`name` is the username that matches, or \"*\" to match all usernames. Required.", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "v1.HTTPIngressPath": { - "description": "HTTPIngressPath associates a path with a backend. Incoming urls matching the path are forwarded to the backend.", - "properties": { - "backend": { - "$ref": "#/definitions/v1.IngressBackend", - "description": "backend defines the referenced service endpoint to which the traffic will be forwarded to." - }, - "path": { - "description": "path is matched against the path of an incoming request. Currently it can contain characters disallowed from the conventional \"path\" part of a URL as defined by RFC 3986. Paths must begin with a '/' and must be present when using PathType with value \"Exact\" or \"Prefix\".", - "type": "string" - }, - "pathType": { - "description": "pathType determines the interpretation of the path matching. PathType can be one of the following values: * Exact: Matches the URL path exactly. * Prefix: Matches based on a URL path prefix split by '/'. Matching is\n done on a path element by element basis. A path element refers is the\n list of labels in the path split by the '/' separator. A request is a\n match for path p if every p is an element-wise prefix of p of the\n request path. Note that if the last element of the path is a substring\n of the last element in request path, it is not a match (e.g. /foo/bar\n matches /foo/bar/baz, but does not match /foo/barbaz).\n* ImplementationSpecific: Interpretation of the Path matching is up to\n the IngressClass. Implementations can treat this as a separate PathType\n or treat it identically to Prefix or Exact path types.\nImplementations are required to support all path types.", - "type": "string" - } - }, - "required": [ - "pathType", - "backend" - ], - "type": "object" - }, - "v1.HTTPIngressRuleValue": { - "description": "HTTPIngressRuleValue is a list of http selectors pointing to backends. In the example: http:///? -> backend where where parts of the url correspond to RFC 3986, this resource will be used to match against everything after the last '/' and before the first '?' or '#'.", - "properties": { - "paths": { - "description": "paths is a collection of paths that map requests to backends.", - "items": { - "$ref": "#/definitions/v1.HTTPIngressPath" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - } - }, - "required": [ - "paths" - ], - "type": "object" - }, - "v1.IPBlock": { - "description": "IPBlock describes a particular CIDR (Ex. \"192.168.1.0/24\",\"2001:db8::/64\") that is allowed to the pods matched by a NetworkPolicySpec's podSelector. The except entry describes CIDRs that should not be included within this rule.", - "properties": { - "cidr": { - "description": "cidr is a string representing the IPBlock Valid examples are \"192.168.1.0/24\" or \"2001:db8::/64\"", - "type": "string" - }, - "except": { - "description": "except is a slice of CIDRs that should not be included within an IPBlock Valid examples are \"192.168.1.0/24\" or \"2001:db8::/64\" Except values will be rejected if they are outside the cidr range", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-list-type": "atomic" - } - }, - "required": [ - "cidr" - ], - "type": "object" - }, - "v1.Ingress": { - "description": "Ingress is a collection of rules that allow inbound connections to reach the endpoints defined by a backend. An Ingress can be configured to give services externally-reachable urls, load balance traffic, terminate SSL, offer name based virtual hosting etc.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "$ref": "#/definitions/v1.ObjectMeta", - "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" - }, - "spec": { - "$ref": "#/definitions/v1.IngressSpec", - "description": "spec is the desired state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" - }, - "status": { - "$ref": "#/definitions/v1.IngressStatus", - "description": "status is the current state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" - } - }, - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "networking.k8s.io", - "kind": "Ingress", - "version": "v1" - } - ] - }, - "v1.IngressBackend": { - "description": "IngressBackend describes all endpoints for a given service and port.", - "properties": { - "resource": { - "$ref": "#/definitions/v1.TypedLocalObjectReference", - "description": "resource is an ObjectRef to another Kubernetes resource in the namespace of the Ingress object. If resource is specified, a service.Name and service.Port must not be specified. This is a mutually exclusive setting with \"Service\"." - }, - "service": { - "$ref": "#/definitions/v1.IngressServiceBackend", - "description": "service references a service as a backend. This is a mutually exclusive setting with \"Resource\"." - } - }, - "type": "object" - }, - "v1.IngressClass": { - "description": "IngressClass represents the class of the Ingress, referenced by the Ingress Spec. The `ingressclass.kubernetes.io/is-default-class` annotation can be used to indicate that an IngressClass should be considered default. When a single IngressClass resource has this annotation set to true, new Ingress resources without a class specified will be assigned this default class.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "$ref": "#/definitions/v1.ObjectMeta", - "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" - }, - "spec": { - "$ref": "#/definitions/v1.IngressClassSpec", - "description": "spec is the desired state of the IngressClass. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" - } - }, - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "networking.k8s.io", - "kind": "IngressClass", - "version": "v1" - } - ] - }, - "v1.IngressClassList": { - "description": "IngressClassList is a collection of IngressClasses.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "items": { - "description": "items is the list of IngressClasses.", - "items": { - "$ref": "#/definitions/v1.IngressClass" - }, - "type": "array" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "$ref": "#/definitions/v1.ListMeta", - "description": "Standard list metadata." - } - }, - "required": [ - "items" - ], - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "networking.k8s.io", - "kind": "IngressClassList", - "version": "v1" - } - ] - }, - "v1.IngressClassParametersReference": { - "description": "IngressClassParametersReference identifies an API object. This can be used to specify a cluster or namespace-scoped resource.", - "properties": { - "apiGroup": { - "description": "apiGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the core API group. For any other third-party types, APIGroup is required.", - "type": "string" - }, - "kind": { - "description": "kind is the type of resource being referenced.", - "type": "string" - }, - "name": { - "description": "name is the name of resource being referenced.", - "type": "string" - }, - "namespace": { - "description": "namespace is the namespace of the resource being referenced. This field is required when scope is set to \"Namespace\" and must be unset when scope is set to \"Cluster\".", - "type": "string" - }, - "scope": { - "description": "scope represents if this refers to a cluster or namespace scoped resource. This may be set to \"Cluster\" (default) or \"Namespace\".", + "description": "name is the name of resource being referenced.", + "type": "string" + }, + "namespace": { + "description": "namespace is the namespace of the resource being referenced. This field is required when scope is set to \"Namespace\" and must be unset when scope is set to \"Cluster\".", + "type": "string" + }, + "scope": { + "description": "scope represents if this refers to a cluster or namespace scoped resource. This may be set to \"Cluster\" (default) or \"Namespace\".", "type": "string" } }, @@ -14026,7 +14204,7 @@ }, "podSelector": { "$ref": "#/definitions/v1.LabelSelector", - "description": "podSelector selects the pods to which this NetworkPolicy object applies. The array of ingress rules is applied to any pods selected by this field. Multiple network policies can select the same set of pods. In this case, the ingress rules for each are combined additively. This field is NOT optional and follows standard label selector semantics. An empty podSelector matches all pods in this namespace." + "description": "podSelector selects the pods to which this NetworkPolicy object applies. The array of rules is applied to any pods selected by this field. An empty selector matches all pods in the policy's namespace. Multiple network policies can select the same set of pods. In this case, the ingress rules for each are combined additively. This field is optional. If it is not specified, it defaults to an empty selector." }, "policyTypes": { "description": "policyTypes is a list of rule types that the NetworkPolicy relates to. Valid options are [\"Ingress\"], [\"Egress\"], or [\"Ingress\", \"Egress\"]. If this field is not specified, it will default based on the existence of ingress or egress rules; policies that contain an egress section are assumed to affect egress, and all policies (whether or not they contain an ingress section) are assumed to affect ingress. If you want to write an egress-only policy, you must explicitly specify policyTypes [ \"Egress\" ]. Likewise, if you want to write a policy that specifies that no egress is allowed, you must specify a policyTypes value that include \"Egress\" (since such a policy would not include an egress section and would otherwise default to just [ \"Ingress\" ]). This field is beta-level in 1.8", @@ -14037,8 +14215,31 @@ "x-kubernetes-list-type": "atomic" } }, + "type": "object" + }, + "v1.ParentReference": { + "description": "ParentReference describes a reference to a parent object.", + "properties": { + "group": { + "description": "Group is the group of the object being referenced.", + "type": "string" + }, + "name": { + "description": "Name is the name of the object being referenced.", + "type": "string" + }, + "namespace": { + "description": "Namespace is the namespace of the object being referenced.", + "type": "string" + }, + "resource": { + "description": "Resource is the resource of the object being referenced.", + "type": "string" + } + }, "required": [ - "podSelector" + "resource", + "name" ], "type": "object" }, @@ -14055,9 +14256,111 @@ "type": "integer" } }, + "type": "object", + "x-kubernetes-map-type": "atomic" + }, + "v1.ServiceCIDR": { + "description": "ServiceCIDR defines a range of IP addresses using CIDR format (e.g. 192.168.0.0/24 or 2001:db2::/64). This range is used to allocate ClusterIPs to Service objects.", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ObjectMeta", + "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" + }, + "spec": { + "$ref": "#/definitions/v1.ServiceCIDRSpec", + "description": "spec is the desired state of the ServiceCIDR. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" + }, + "status": { + "$ref": "#/definitions/v1.ServiceCIDRStatus", + "description": "status represents the current state of the ServiceCIDR. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" + } + }, + "type": "object", + "x-kubernetes-group-version-kind": [ + { + "group": "networking.k8s.io", + "kind": "ServiceCIDR", + "version": "v1" + } + ] + }, + "v1.ServiceCIDRList": { + "description": "ServiceCIDRList contains a list of ServiceCIDR objects.", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "items": { + "description": "items is the list of ServiceCIDRs.", + "items": { + "$ref": "#/definitions/v1.ServiceCIDR" + }, + "type": "array" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "$ref": "#/definitions/v1.ListMeta", + "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" + } + }, + "required": [ + "items" + ], + "type": "object", + "x-kubernetes-group-version-kind": [ + { + "group": "networking.k8s.io", + "kind": "ServiceCIDRList", + "version": "v1" + } + ] + }, + "v1.ServiceCIDRSpec": { + "description": "ServiceCIDRSpec define the CIDRs the user wants to use for allocating ClusterIPs for Services.", + "properties": { + "cidrs": { + "description": "CIDRs defines the IP blocks in CIDR notation (e.g. \"192.168.0.0/24\" or \"2001:db8::/64\") from which to assign service cluster IPs. Max of two CIDRs is allowed, one of each IP family. This field is immutable.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + } + }, "type": "object" }, - "v1alpha1.IPAddress": { + "v1.ServiceCIDRStatus": { + "description": "ServiceCIDRStatus describes the current state of the ServiceCIDR.", + "properties": { + "conditions": { + "description": "conditions holds an array of metav1.Condition that describe the state of the ServiceCIDR. Current service state", + "items": { + "$ref": "#/definitions/v1.Condition" + }, + "type": "array", + "x-kubernetes-list-map-keys": [ + "type" + ], + "x-kubernetes-list-type": "map", + "x-kubernetes-patch-merge-key": "type", + "x-kubernetes-patch-strategy": "merge" + } + }, + "type": "object" + }, + "v1beta1.IPAddress": { "description": "IPAddress represents a single IP of a single IP Family. The object is designed to be used by APIs that operate on IP addresses. The object is used by the Service core API for allocation of IP addresses. An IP address can be represented in different formats, to guarantee the uniqueness of the IP, the name of the object is the IP address in canonical format, four decimal digits separated by dots suppressing leading zeros for IPv4 and the representation defined by RFC 5952 for IPv6. Valid: 192.168.1.5 or 2001:db8::1 or 2001:db8:aaaa:bbbb:cccc:dddd:eeee:1 Invalid: 10.01.2.3 or 2001:db8:0:0:0::1", "properties": { "apiVersion": { @@ -14073,7 +14376,7 @@ "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" }, "spec": { - "$ref": "#/definitions/v1alpha1.IPAddressSpec", + "$ref": "#/definitions/v1beta1.IPAddressSpec", "description": "spec is the desired state of the IPAddress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" } }, @@ -14082,11 +14385,11 @@ { "group": "networking.k8s.io", "kind": "IPAddress", - "version": "v1alpha1" + "version": "v1beta1" } ] }, - "v1alpha1.IPAddressList": { + "v1beta1.IPAddressList": { "description": "IPAddressList contains a list of IPAddress.", "properties": { "apiVersion": { @@ -14096,7 +14399,7 @@ "items": { "description": "items is the list of IPAddresses.", "items": { - "$ref": "#/definitions/v1alpha1.IPAddress" + "$ref": "#/definitions/v1beta1.IPAddress" }, "type": "array" }, @@ -14117,15 +14420,15 @@ { "group": "networking.k8s.io", "kind": "IPAddressList", - "version": "v1alpha1" + "version": "v1beta1" } ] }, - "v1alpha1.IPAddressSpec": { + "v1beta1.IPAddressSpec": { "description": "IPAddressSpec describe the attributes in an IP Address.", "properties": { "parentRef": { - "$ref": "#/definitions/v1alpha1.ParentReference", + "$ref": "#/definitions/v1beta1.ParentReference", "description": "ParentRef references the resource that an IPAddress is attached to. An IPAddress must reference a parent object." } }, @@ -14134,7 +14437,7 @@ ], "type": "object" }, - "v1alpha1.ParentReference": { + "v1beta1.ParentReference": { "description": "ParentReference describes a reference to a parent object.", "properties": { "group": { @@ -14160,7 +14463,7 @@ ], "type": "object" }, - "v1alpha1.ServiceCIDR": { + "v1beta1.ServiceCIDR": { "description": "ServiceCIDR defines a range of IP addresses using CIDR format (e.g. 192.168.0.0/24 or 2001:db2::/64). This range is used to allocate ClusterIPs to Service objects.", "properties": { "apiVersion": { @@ -14176,11 +14479,11 @@ "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" }, "spec": { - "$ref": "#/definitions/v1alpha1.ServiceCIDRSpec", + "$ref": "#/definitions/v1beta1.ServiceCIDRSpec", "description": "spec is the desired state of the ServiceCIDR. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" }, "status": { - "$ref": "#/definitions/v1alpha1.ServiceCIDRStatus", + "$ref": "#/definitions/v1beta1.ServiceCIDRStatus", "description": "status represents the current state of the ServiceCIDR. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" } }, @@ -14189,11 +14492,11 @@ { "group": "networking.k8s.io", "kind": "ServiceCIDR", - "version": "v1alpha1" + "version": "v1beta1" } ] }, - "v1alpha1.ServiceCIDRList": { + "v1beta1.ServiceCIDRList": { "description": "ServiceCIDRList contains a list of ServiceCIDR objects.", "properties": { "apiVersion": { @@ -14203,7 +14506,7 @@ "items": { "description": "items is the list of ServiceCIDRs.", "items": { - "$ref": "#/definitions/v1alpha1.ServiceCIDR" + "$ref": "#/definitions/v1beta1.ServiceCIDR" }, "type": "array" }, @@ -14224,11 +14527,11 @@ { "group": "networking.k8s.io", "kind": "ServiceCIDRList", - "version": "v1alpha1" + "version": "v1beta1" } ] }, - "v1alpha1.ServiceCIDRSpec": { + "v1beta1.ServiceCIDRSpec": { "description": "ServiceCIDRSpec define the CIDRs the user wants to use for allocating ClusterIPs for Services.", "properties": { "cidrs": { @@ -14242,7 +14545,7 @@ }, "type": "object" }, - "v1alpha1.ServiceCIDRStatus": { + "v1beta1.ServiceCIDRStatus": { "description": "ServiceCIDRStatus describes the current state of the ServiceCIDR.", "properties": { "conditions": { @@ -14485,7 +14788,7 @@ "x-kubernetes-patch-strategy": "replace" }, "unhealthyPodEvictionPolicy": { - "description": "UnhealthyPodEvictionPolicy defines the criteria for when unhealthy pods should be considered for eviction. Current implementation considers healthy pods, as pods that have status.conditions item with type=\"Ready\",status=\"True\".\n\nValid policies are IfHealthyBudget and AlwaysAllow. If no policy is specified, the default behavior will be used, which corresponds to the IfHealthyBudget policy.\n\nIfHealthyBudget policy means that running pods (status.phase=\"Running\"), but not yet healthy can be evicted only if the guarded application is not disrupted (status.currentHealthy is at least equal to status.desiredHealthy). Healthy pods will be subject to the PDB for eviction.\n\nAlwaysAllow policy means that all running pods (status.phase=\"Running\"), but not yet healthy are considered disrupted and can be evicted regardless of whether the criteria in a PDB is met. This means perspective running pods of a disrupted application might not get a chance to become healthy. Healthy pods will be subject to the PDB for eviction.\n\nAdditional policies may be added in the future. Clients making eviction decisions should disallow eviction of unhealthy pods if they encounter an unrecognized policy in this field.\n\nThis field is beta-level. The eviction API uses this field when the feature gate PDBUnhealthyPodEvictionPolicy is enabled (enabled by default).", + "description": "UnhealthyPodEvictionPolicy defines the criteria for when unhealthy pods should be considered for eviction. Current implementation considers healthy pods, as pods that have status.conditions item with type=\"Ready\",status=\"True\".\n\nValid policies are IfHealthyBudget and AlwaysAllow. If no policy is specified, the default behavior will be used, which corresponds to the IfHealthyBudget policy.\n\nIfHealthyBudget policy means that running pods (status.phase=\"Running\"), but not yet healthy can be evicted only if the guarded application is not disrupted (status.currentHealthy is at least equal to status.desiredHealthy). Healthy pods will be subject to the PDB for eviction.\n\nAlwaysAllow policy means that all running pods (status.phase=\"Running\"), but not yet healthy are considered disrupted and can be evicted regardless of whether the criteria in a PDB is met. This means perspective running pods of a disrupted application might not get a chance to become healthy. Healthy pods will be subject to the PDB for eviction.\n\nAdditional policies may be added in the future. Clients making eviction decisions should disallow eviction of unhealthy pods if they encounter an unrecognized policy in this field.", "type": "string" } }, @@ -14954,112 +15257,246 @@ "type": "object", "x-kubernetes-map-type": "atomic" }, - "v1alpha2.AllocationResult": { - "description": "AllocationResult contains attributes of an allocated resource.", + "v1.AllocatedDeviceStatus": { + "description": "AllocatedDeviceStatus contains the status of an allocated device, if the driver chooses to report it. This may include driver-specific information.\n\nThe combination of Driver, Pool, Device, and ShareID must match the corresponding key in Status.Allocation.Devices.", "properties": { - "availableOnNodes": { - "$ref": "#/definitions/v1.NodeSelector", - "description": "This field will get set by the resource driver after it has allocated the resource to inform the scheduler where it can schedule Pods using the ResourceClaim.\n\nSetting this field is optional. If null, the resource is available everywhere." - }, - "resourceHandles": { - "description": "ResourceHandles contain the state associated with an allocation that should be maintained throughout the lifetime of a claim. Each ResourceHandle contains data that should be passed to a specific kubelet plugin once it lands on a node. This data is returned by the driver after a successful allocation and is opaque to Kubernetes. Driver documentation may explain to users how to interpret this data if needed.\n\nSetting this field is optional. It has a maximum size of 32 entries. If null (or empty), it is assumed this allocation will be processed by a single kubelet plugin with no ResourceHandle data attached. The name of the kubelet plugin invoked will match the DriverName set in the ResourceClaimStatus this AllocationResult is embedded in.", + "conditions": { + "description": "Conditions contains the latest observation of the device's state. If the device has been configured according to the class and claim config references, the `Ready` condition should be True.\n\nMust not contain more than 8 entries.", "items": { - "$ref": "#/definitions/v1alpha2.ResourceHandle" + "$ref": "#/definitions/v1.Condition" }, "type": "array", - "x-kubernetes-list-type": "atomic" + "x-kubernetes-list-map-keys": [ + "type" + ], + "x-kubernetes-list-type": "map" }, - "shareable": { - "description": "Shareable determines whether the resource supports more than one consumer at a time.", - "type": "boolean" + "data": { + "description": "Data contains arbitrary driver-specific data.\n\nThe length of the raw data must be smaller or equal to 10 Ki.", + "type": "object" + }, + "device": { + "description": "Device references one device instance via its name in the driver's resource pool. It must be a DNS label.", + "type": "string" + }, + "driver": { + "description": "Driver specifies the name of the DRA driver whose kubelet plugin should be invoked to process the allocation once the claim is needed on a node.\n\nMust be a DNS subdomain and should end with a DNS domain owned by the vendor of the driver.", + "type": "string" + }, + "networkData": { + "$ref": "#/definitions/v1.NetworkDeviceData", + "description": "NetworkData contains network-related information specific to the device." + }, + "pool": { + "description": "This name together with the driver name and the device name field identify which device was allocated (`//`).\n\nMust not be longer than 253 characters and may contain one or more DNS sub-domains separated by slashes.", + "type": "string" + }, + "shareID": { + "description": "ShareID uniquely identifies an individual allocation share of the device.", + "type": "string" } }, + "required": [ + "driver", + "pool", + "device" + ], "type": "object" }, - "v1alpha2.DriverAllocationResult": { - "description": "DriverAllocationResult contains vendor parameters and the allocation result for one request.", + "v1.AllocationResult": { + "description": "AllocationResult contains attributes of an allocated resource.", "properties": { - "namedResources": { - "$ref": "#/definitions/v1alpha2.NamedResourcesAllocationResult", - "description": "NamedResources describes the allocation result when using the named resources model." + "allocationTimestamp": { + "description": "AllocationTimestamp stores the time when the resources were allocated. This field is not guaranteed to be set, in which case that time is unknown.\n\nThis is an alpha field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gate.", + "format": "date-time", + "type": "string" }, - "vendorRequestParameters": { - "description": "VendorRequestParameters are the per-request configuration parameters from the time that the claim was allocated.", - "type": "object" + "devices": { + "$ref": "#/definitions/v1.DeviceAllocationResult", + "description": "Devices is the result of allocating devices." + }, + "nodeSelector": { + "$ref": "#/definitions/v1.NodeSelector", + "description": "NodeSelector defines where the allocated resources are available. If unset, they are available everywhere." } }, "type": "object" }, - "v1alpha2.DriverRequests": { - "description": "DriverRequests describes all resources that are needed from one particular driver.", + "v1.CELDeviceSelector": { + "description": "CELDeviceSelector contains a CEL expression for selecting a device.", "properties": { - "driverName": { - "description": "DriverName is the name used by the DRA driver kubelet plugin.", + "expression": { + "description": "Expression is a CEL expression which evaluates a single device. It must evaluate to true when the device under consideration satisfies the desired criteria, and false when it does not. Any other result is an error and causes allocation of devices to abort.\n\nThe expression's input is an object named \"device\", which carries the following properties:\n - driver (string): the name of the driver which defines this device.\n - attributes (map[string]object): the device's attributes, grouped by prefix\n (e.g. device.attributes[\"dra.example.com\"] evaluates to an object with all\n of the attributes which were prefixed by \"dra.example.com\".\n - capacity (map[string]object): the device's capacities, grouped by prefix.\n - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device\n (v1.34+ with the DRAConsumableCapacity feature enabled).\n\nExample: Consider a device with driver=\"dra.example.com\", which exposes two attributes named \"model\" and \"ext.example.com/family\" and which exposes one capacity named \"modules\". This input to this expression would have the following fields:\n\n device.driver\n device.attributes[\"dra.example.com\"].model\n device.attributes[\"ext.example.com\"].family\n device.capacity[\"dra.example.com\"].modules\n\nThe device.driver field can be used to check for a specific driver, either as a high-level precondition (i.e. you only want to consider devices from this driver) or as part of a multi-clause expression that is meant to consider devices from different drivers.\n\nThe value type of each attribute is defined by the device definition, and users who write these expressions must consult the documentation for their specific drivers. The value type of each capacity is Quantity.\n\nIf an unknown prefix is used as a lookup in either device.attributes or device.capacity, an empty map will be returned. Any reference to an unknown field will cause an evaluation error and allocation to abort.\n\nA robust expression should check for the existence of attributes before referencing them.\n\nFor ease of use, the cel.bind() function is enabled, and can be used to simplify expressions that access multiple attributes with the same domain. For example:\n\n cel.bind(dra, device.attributes[\"dra.example.com\"], dra.someBool && dra.anotherBool)\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps.", "type": "string" + } + }, + "required": [ + "expression" + ], + "type": "object" + }, + "v1.CapacityRequestPolicy": { + "description": "CapacityRequestPolicy defines how requests consume device capacity.\n\nMust not set more than one ValidRequestValues.", + "properties": { + "default": { + "$ref": "#/definitions/resource.Quantity", + "description": "Default specifies how much of this capacity is consumed by a request that does not contain an entry for it in DeviceRequest's Capacity." }, - "requests": { - "description": "Requests describes all resources that are needed from the driver.", + "validRange": { + "$ref": "#/definitions/v1.CapacityRequestPolicyRange", + "description": "ValidRange defines an acceptable quantity value range in consuming requests.\n\nIf this field is set, Default must be defined and it must fall within the defined ValidRange.\n\nIf the requested amount does not fall within the defined range, the request violates the policy, and this device cannot be allocated.\n\nIf the request doesn't contain this capacity entry, Default value is used." + }, + "validValues": { + "description": "ValidValues defines a set of acceptable quantity values in consuming requests.\n\nMust not contain more than 10 entries. Must be sorted in ascending order.\n\nIf this field is set, Default must be defined and it must be included in ValidValues list.\n\nIf the requested amount does not match any valid value but smaller than some valid values, the scheduler calculates the smallest valid value that is greater than or equal to the request. That is: min(ceil(requestedValue) \u2208 validValues), where requestedValue \u2264 max(validValues).\n\nIf the requested amount exceeds all valid values, the request violates the policy, and this device cannot be allocated.", "items": { - "$ref": "#/definitions/v1alpha2.ResourceRequest" + "$ref": "#/definitions/resource.Quantity" }, "type": "array", "x-kubernetes-list-type": "atomic" + } + }, + "type": "object" + }, + "v1.CapacityRequestPolicyRange": { + "description": "CapacityRequestPolicyRange defines a valid range for consumable capacity values.\n\n - If the requested amount is less than Min, it is rounded up to the Min value.\n - If Step is set and the requested amount is between Min and Max but not aligned with Step,\n it will be rounded up to the next value equal to Min + (n * Step).\n - If Step is not set, the requested amount is used as-is if it falls within the range Min to Max (if set).\n - If the requested or rounded amount exceeds Max (if set), the request does not satisfy the policy,\n and the device cannot be allocated.", + "properties": { + "max": { + "$ref": "#/definitions/resource.Quantity", + "description": "Max defines the upper limit for capacity that can be requested.\n\nMax must be less than or equal to the capacity value. Min and requestPolicy.default must be less than or equal to the maximum." }, - "vendorParameters": { - "description": "VendorParameters are arbitrary setup parameters for all requests of the claim. They are ignored while allocating the claim.", + "min": { + "$ref": "#/definitions/resource.Quantity", + "description": "Min specifies the minimum capacity allowed for a consumption request.\n\nMin must be greater than or equal to zero, and less than or equal to the capacity value. requestPolicy.default must be more than or equal to the minimum." + }, + "step": { + "$ref": "#/definitions/resource.Quantity", + "description": "Step defines the step size between valid capacity amounts within the range.\n\nMax (if set) and requestPolicy.default must be a multiple of Step. Min + Step must be less than or equal to the capacity value." + } + }, + "required": [ + "min" + ], + "type": "object" + }, + "v1.CapacityRequirements": { + "description": "CapacityRequirements defines the capacity requirements for a specific device request.", + "properties": { + "requests": { + "additionalProperties": { + "$ref": "#/definitions/resource.Quantity" + }, + "description": "Requests represent individual device resource requests for distinct resources, all of which must be provided by the device.\n\nThis value is used as an additional filtering condition against the available capacity on the device. This is semantically equivalent to a CEL selector with `device.capacity[]..compareTo(quantity()) >= 0`. For example, device.capacity['test-driver.cdi.k8s.io'].counters.compareTo(quantity('2')) >= 0.\n\nWhen a requestPolicy is defined, the requested amount is adjusted upward to the nearest valid value based on the policy. If the requested amount cannot be adjusted to a valid value\u2014because it exceeds what the requestPolicy allows\u2014 the device is considered ineligible for allocation.\n\nFor any capacity that is not explicitly requested: - If no requestPolicy is set, the default consumed capacity is equal to the full device capacity\n (i.e., the whole device is claimed).\n- If a requestPolicy is set, the default consumed capacity is determined according to that policy.\n\nIf the device allows multiple allocation, the aggregated amount across all requests must not exceed the capacity value. The consumed capacity, which may be adjusted based on the requestPolicy if defined, is recorded in the resource claim\u2019s status.devices[*].consumedCapacity field.", "type": "object" } }, "type": "object" }, - "v1alpha2.NamedResourcesAllocationResult": { - "description": "NamedResourcesAllocationResult is used in AllocationResultModel.", + "v1.Counter": { + "description": "Counter describes a quantity associated with a device.", + "properties": { + "value": { + "$ref": "#/definitions/resource.Quantity", + "description": "Value defines how much of a certain device counter is available." + } + }, + "required": [ + "value" + ], + "type": "object" + }, + "v1.CounterSet": { + "description": "CounterSet defines a named set of counters that are available to be used by devices defined in the ResourceSlice.\n\nThe counters are not allocatable by themselves, but can be referenced by devices. When a device is allocated, the portion of counters it uses will no longer be available for use by other devices.", "properties": { + "counters": { + "additionalProperties": { + "$ref": "#/definitions/v1.Counter" + }, + "description": "Counters defines the set of counters for this CounterSet The name of each counter must be unique in that set and must be a DNS label.\n\nThe maximum number of counters in all sets is 32.", + "type": "object" + }, "name": { - "description": "Name is the name of the selected resource instance.", + "description": "Name defines the name of the counter set. It must be a DNS label.", "type": "string" } }, "required": [ - "name" + "name", + "counters" ], "type": "object" }, - "v1alpha2.NamedResourcesAttribute": { - "description": "NamedResourcesAttribute is a combination of an attribute name and its value.", + "v1.Device": { + "description": "Device represents one individual hardware instance that can be selected based on its attributes. Besides the name, exactly one field must be set.", "properties": { - "bool": { - "description": "BoolValue is a true/false value.", + "allNodes": { + "description": "AllNodes indicates that all nodes have access to the device.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", "type": "boolean" }, - "int": { - "description": "IntValue is a 64-bit integer.", - "format": "int64", - "type": "integer" + "allowMultipleAllocations": { + "description": "AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests.\n\nIf AllowMultipleAllocations is set to true, the device can be allocated more than once, and all of its capacity is consumable, regardless of whether the requestPolicy is defined or not.", + "type": "boolean" + }, + "attributes": { + "additionalProperties": { + "$ref": "#/definitions/v1.DeviceAttribute" + }, + "description": "Attributes defines the set of attributes for this device. The name of each attribute must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", + "type": "object" + }, + "bindingConditions": { + "description": "BindingConditions defines the conditions for proceeding with binding. All of these conditions must be set in the per-device status conditions with a value of True to proceed with binding the pod to the node while scheduling the pod.\n\nThe maximum number of binding conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is an alpha field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "bindingFailureConditions": { + "description": "BindingFailureConditions defines the conditions for binding failure. They may be set in the per-device status conditions. If any is set to \"True\", a binding failure occurred.\n\nThe maximum number of binding failure conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is an alpha field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "bindsToNode": { + "description": "BindsToNode indicates if the usage of an allocation involving this device has to be limited to exactly the node that was chosen when allocating the claim. If set to true, the scheduler will set the ResourceClaim.Status.Allocation.NodeSelector to match the node where the allocation was made.\n\nThis is an alpha field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "type": "boolean" }, - "intSlice": { - "$ref": "#/definitions/v1alpha2.NamedResourcesIntSlice", - "description": "IntSliceValue is an array of 64-bit integers." + "capacity": { + "additionalProperties": { + "$ref": "#/definitions/v1.DeviceCapacity" + }, + "description": "Capacity defines the set of capacities for this device. The name of each capacity must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", + "type": "object" + }, + "consumesCounters": { + "description": "ConsumesCounters defines a list of references to sharedCounters and the set of counters that the device will consume from those counter sets.\n\nThere can only be a single entry per counterSet.\n\nThe total number of device counter consumption entries must be <= 32. In addition, the total number in the entire ResourceSlice must be <= 1024 (for example, 64 devices with 16 counters each).", + "items": { + "$ref": "#/definitions/v1.DeviceCounterConsumption" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" }, "name": { - "description": "Name is unique identifier among all resource instances managed by the driver on the node. It must be a DNS subdomain.", + "description": "Name is unique identifier among all devices managed by the driver in the pool. It must be a DNS label.", "type": "string" }, - "quantity": { - "$ref": "#/definitions/resource.Quantity", - "description": "QuantityValue is a quantity." - }, - "string": { - "description": "StringValue is a string.", + "nodeName": { + "description": "NodeName identifies the node where the device is available.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", "type": "string" }, - "stringSlice": { - "$ref": "#/definitions/v1alpha2.NamedResourcesStringSlice", - "description": "StringSliceValue is an array of strings." + "nodeSelector": { + "$ref": "#/definitions/v1.NodeSelector", + "description": "NodeSelector defines the nodes where the device is available.\n\nMust use exactly one term.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set." }, - "version": { - "description": "VersionValue is a semantic version according to semver.org spec 2.0.0.", - "type": "string" + "taints": { + "description": "If specified, these are the driver-defined taints.\n\nThe maximum number of taints is 4.\n\nThis is an alpha field and requires enabling the DRADeviceTaints feature gate.", + "items": { + "$ref": "#/definitions/v1.DeviceTaint" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" } }, "required": [ @@ -15067,93 +15504,132 @@ ], "type": "object" }, - "v1alpha2.NamedResourcesFilter": { - "description": "NamedResourcesFilter is used in ResourceFilterModel.", - "properties": { - "selector": { - "description": "Selector is a CEL expression which must evaluate to true if a resource instance is suitable. The language is as defined in https://kubernetes.io/docs/reference/using-api/cel/\n\nIn addition, for each type NamedResourcesin AttributeValue there is a map that resolves to the corresponding value of the instance under evaluation. For example:\n\n attributes.quantity[\"a\"].isGreaterThan(quantity(\"0\")) &&\n attributes.stringslice[\"b\"].isSorted()", - "type": "string" - } - }, - "required": [ - "selector" - ], - "type": "object" - }, - "v1alpha2.NamedResourcesInstance": { - "description": "NamedResourcesInstance represents one individual hardware instance that can be selected based on its attributes.", + "v1.DeviceAllocationConfiguration": { + "description": "DeviceAllocationConfiguration gets embedded in an AllocationResult.", "properties": { - "attributes": { - "description": "Attributes defines the attributes of this resource instance. The name of each attribute must be unique.", + "opaque": { + "$ref": "#/definitions/v1.OpaqueDeviceConfiguration", + "description": "Opaque provides driver-specific configuration parameters." + }, + "requests": { + "description": "Requests lists the names of requests where the configuration applies. If empty, its applies to all requests.\n\nReferences to subrequests must include the name of the main request and may include the subrequest using the format
[/]. If just the main request is given, the configuration applies to all subrequests.", "items": { - "$ref": "#/definitions/v1alpha2.NamedResourcesAttribute" + "type": "string" }, "type": "array", "x-kubernetes-list-type": "atomic" }, - "name": { - "description": "Name is unique identifier among all resource instances managed by the driver on the node. It must be a DNS subdomain.", + "source": { + "description": "Source records whether the configuration comes from a class and thus is not something that a normal user would have been able to set or from a claim.", "type": "string" } }, "required": [ - "name" + "source" ], "type": "object" }, - "v1alpha2.NamedResourcesIntSlice": { - "description": "NamedResourcesIntSlice contains a slice of 64-bit integers.", + "v1.DeviceAllocationResult": { + "description": "DeviceAllocationResult is the result of allocating devices.", "properties": { - "ints": { - "description": "Ints is the slice of 64-bit integers.", + "config": { + "description": "This field is a combination of all the claim and class configuration parameters. Drivers can distinguish between those based on a flag.\n\nThis includes configuration parameters for drivers which have no allocated devices in the result because it is up to the drivers which configuration parameters they support. They can silently ignore unknown configuration parameters.", "items": { - "format": "int64", - "type": "integer" + "$ref": "#/definitions/v1.DeviceAllocationConfiguration" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "results": { + "description": "Results lists all allocated devices.", + "items": { + "$ref": "#/definitions/v1.DeviceRequestAllocationResult" }, "type": "array", "x-kubernetes-list-type": "atomic" } }, - "required": [ - "ints" - ], "type": "object" }, - "v1alpha2.NamedResourcesRequest": { - "description": "NamedResourcesRequest is used in ResourceRequestModel.", + "v1.DeviceAttribute": { + "description": "DeviceAttribute must have exactly one field set.", "properties": { - "selector": { - "description": "Selector is a CEL expression which must evaluate to true if a resource instance is suitable. The language is as defined in https://kubernetes.io/docs/reference/using-api/cel/\n\nIn addition, for each type NamedResourcesin AttributeValue there is a map that resolves to the corresponding value of the instance under evaluation. For example:\n\n attributes.quantity[\"a\"].isGreaterThan(quantity(\"0\")) &&\n attributes.stringslice[\"b\"].isSorted()", + "bool": { + "description": "BoolValue is a true/false value.", + "type": "boolean" + }, + "int": { + "description": "IntValue is a number.", + "format": "int64", + "type": "integer" + }, + "string": { + "description": "StringValue is a string. Must not be longer than 64 characters.", "type": "string" + }, + "version": { + "description": "VersionValue is a semantic version according to semver.org spec 2.0.0. Must not be longer than 64 characters.", + "type": "string" + } + }, + "type": "object" + }, + "v1.DeviceCapacity": { + "description": "DeviceCapacity describes a quantity associated with a device.", + "properties": { + "requestPolicy": { + "$ref": "#/definitions/v1.CapacityRequestPolicy", + "description": "RequestPolicy defines how this DeviceCapacity must be consumed when the device is allowed to be shared by multiple allocations.\n\nThe Device must have allowMultipleAllocations set to true in order to set a requestPolicy.\n\nIf unset, capacity requests are unconstrained: requests can consume any amount of capacity, as long as the total consumed across all allocations does not exceed the device's defined capacity. If request is also unset, default is the full capacity value." + }, + "value": { + "$ref": "#/definitions/resource.Quantity", + "description": "Value defines how much of a certain capacity that device has.\n\nThis field reflects the fixed total capacity and does not change. The consumed amount is tracked separately by scheduler and does not affect this value." } }, "required": [ - "selector" + "value" ], "type": "object" }, - "v1alpha2.NamedResourcesResources": { - "description": "NamedResourcesResources is used in ResourceModel.", + "v1.DeviceClaim": { + "description": "DeviceClaim defines how to request devices with a ResourceClaim.", "properties": { - "instances": { - "description": "The list of all individual resources instances currently available.", + "config": { + "description": "This field holds configuration for multiple potential drivers which could satisfy requests in this claim. It is ignored while allocating the claim.", + "items": { + "$ref": "#/definitions/v1.DeviceClaimConfiguration" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "constraints": { + "description": "These constraints must be satisfied by the set of devices that get allocated for the claim.", + "items": { + "$ref": "#/definitions/v1.DeviceConstraint" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "requests": { + "description": "Requests represent individual requests for distinct devices which must all be satisfied. If empty, nothing needs to be allocated.", "items": { - "$ref": "#/definitions/v1alpha2.NamedResourcesInstance" + "$ref": "#/definitions/v1.DeviceRequest" }, "type": "array", "x-kubernetes-list-type": "atomic" } }, - "required": [ - "instances" - ], "type": "object" }, - "v1alpha2.NamedResourcesStringSlice": { - "description": "NamedResourcesStringSlice contains a slice of strings.", + "v1.DeviceClaimConfiguration": { + "description": "DeviceClaimConfiguration is used for configuration parameters in DeviceClaim.", "properties": { - "strings": { - "description": "Strings is the slice of strings.", + "opaque": { + "$ref": "#/definitions/v1.OpaqueDeviceConfiguration", + "description": "Opaque provides driver-specific configuration parameters." + }, + "requests": { + "description": "Requests lists the names of requests where the configuration applies. If empty, it applies to all requests.\n\nReferences to subrequests must include the name of the main request and may include the subrequest using the format
[/]. If just the main request is given, the configuration applies to all subrequests.", "items": { "type": "string" }, @@ -15161,13 +15637,10 @@ "x-kubernetes-list-type": "atomic" } }, - "required": [ - "strings" - ], "type": "object" }, - "v1alpha2.PodSchedulingContext": { - "description": "PodSchedulingContext objects hold information that is needed to schedule a Pod with ResourceClaims that use \"WaitForFirstConsumer\" allocation mode.\n\nThis is an alpha type and requires enabling the DynamicResourceAllocation feature gate.", + "v1.DeviceClass": { + "description": "DeviceClass is a vendor- or admin-provided resource that contains device configuration and selectors. It can be referenced in the device requests of a claim to apply these presets. Cluster scoped.\n\nThis is an alpha type and requires enabling the DynamicResourceAllocation feature gate.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", @@ -15182,12 +15655,8 @@ "description": "Standard object metadata" }, "spec": { - "$ref": "#/definitions/v1alpha2.PodSchedulingContextSpec", - "description": "Spec describes where resources for the Pod are needed." - }, - "status": { - "$ref": "#/definitions/v1alpha2.PodSchedulingContextStatus", - "description": "Status describes where resources for the Pod can be allocated." + "$ref": "#/definitions/v1.DeviceClassSpec", + "description": "Spec defines what can be allocated and how to configure it.\n\nThis is mutable. Consumers have to be prepared for classes changing at any time, either because they get updated or replaced. Claim allocations are done once based on whatever was set in classes at the time of allocation.\n\nChanging the spec automatically increments the metadata.generation number." } }, "required": [ @@ -15197,22 +15666,32 @@ "x-kubernetes-group-version-kind": [ { "group": "resource.k8s.io", - "kind": "PodSchedulingContext", - "version": "v1alpha2" + "kind": "DeviceClass", + "version": "v1" } ] }, - "v1alpha2.PodSchedulingContextList": { - "description": "PodSchedulingContextList is a collection of Pod scheduling objects.", + "v1.DeviceClassConfiguration": { + "description": "DeviceClassConfiguration is used in DeviceClass.", + "properties": { + "opaque": { + "$ref": "#/definitions/v1.OpaqueDeviceConfiguration", + "description": "Opaque provides driver-specific configuration parameters." + } + }, + "type": "object" + }, + "v1.DeviceClassList": { + "description": "DeviceClassList is a collection of classes.", "properties": { "apiVersion": { "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", "type": "string" }, "items": { - "description": "Items is the list of PodSchedulingContext objects.", + "description": "Items is the list of resource classes.", "items": { - "$ref": "#/definitions/v1alpha2.PodSchedulingContext" + "$ref": "#/definitions/v1.DeviceClass" }, "type": "array" }, @@ -15232,48 +15711,371 @@ "x-kubernetes-group-version-kind": [ { "group": "resource.k8s.io", - "kind": "PodSchedulingContextList", - "version": "v1alpha2" + "kind": "DeviceClassList", + "version": "v1" } ] }, - "v1alpha2.PodSchedulingContextSpec": { - "description": "PodSchedulingContextSpec describes where resources for the Pod are needed.", + "v1.DeviceClassSpec": { + "description": "DeviceClassSpec is used in a [DeviceClass] to define what can be allocated and how to configure it.", + "properties": { + "config": { + "description": "Config defines configuration parameters that apply to each device that is claimed via this class. Some classses may potentially be satisfied by multiple drivers, so each instance of a vendor configuration applies to exactly one driver.\n\nThey are passed to the driver, but are not considered while allocating the claim.", + "items": { + "$ref": "#/definitions/v1.DeviceClassConfiguration" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "extendedResourceName": { + "description": "ExtendedResourceName is the extended resource name for the devices of this class. The devices of this class can be used to satisfy a pod's extended resource requests. It has the same format as the name of a pod's extended resource. It should be unique among all the device classes in a cluster. If two device classes have the same name, then the class created later is picked to satisfy a pod's extended resource requests. If two classes are created at the same time, then the name of the class lexicographically sorted first is picked.\n\nThis is an alpha field.", + "type": "string" + }, + "selectors": { + "description": "Each selector must be satisfied by a device which is claimed via this class.", + "items": { + "$ref": "#/definitions/v1.DeviceSelector" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + } + }, + "type": "object" + }, + "v1.DeviceConstraint": { + "description": "DeviceConstraint must have exactly one field set besides Requests.", + "properties": { + "distinctAttribute": { + "description": "DistinctAttribute requires that all devices in question have this attribute and that its type and value are unique across those devices.\n\nThis acts as the inverse of MatchAttribute.\n\nThis constraint is used to avoid allocating multiple requests to the same device by ensuring attribute-level differentiation.\n\nThis is useful for scenarios where resource requests must be fulfilled by separate physical devices. For example, a container requests two network interfaces that must be allocated from two different physical NICs.", + "type": "string" + }, + "matchAttribute": { + "description": "MatchAttribute requires that all devices in question have this attribute and that its type and value are the same across those devices.\n\nFor example, if you specified \"dra.example.com/numa\" (a hypothetical example!), then only devices in the same NUMA node will be chosen. A device which does not have that attribute will not be chosen. All devices should use a value of the same type for this attribute because that is part of its specification, but if one device doesn't, then it also will not be chosen.\n\nMust include the domain qualifier.", + "type": "string" + }, + "requests": { + "description": "Requests is a list of the one or more requests in this claim which must co-satisfy this constraint. If a request is fulfilled by multiple devices, then all of the devices must satisfy the constraint. If this is not specified, this constraint applies to all requests in this claim.\n\nReferences to subrequests must include the name of the main request and may include the subrequest using the format
[/]. If just the main request is given, the constraint applies to all subrequests.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + } + }, + "type": "object" + }, + "v1.DeviceCounterConsumption": { + "description": "DeviceCounterConsumption defines a set of counters that a device will consume from a CounterSet.", + "properties": { + "counterSet": { + "description": "CounterSet is the name of the set from which the counters defined will be consumed.", + "type": "string" + }, + "counters": { + "additionalProperties": { + "$ref": "#/definitions/v1.Counter" + }, + "description": "Counters defines the counters that will be consumed by the device.\n\nThe maximum number counters in a device is 32. In addition, the maximum number of all counters in all devices is 1024 (for example, 64 devices with 16 counters each).", + "type": "object" + } + }, + "required": [ + "counterSet", + "counters" + ], + "type": "object" + }, + "v1.DeviceRequest": { + "description": "DeviceRequest is a request for devices required for a claim. This is typically a request for a single resource like a device, but can also ask for several identical devices. With FirstAvailable it is also possible to provide a prioritized list of requests.", + "properties": { + "exactly": { + "$ref": "#/definitions/v1.ExactDeviceRequest", + "description": "Exactly specifies the details for a single request that must be met exactly for the request to be satisfied.\n\nOne of Exactly or FirstAvailable must be set." + }, + "firstAvailable": { + "description": "FirstAvailable contains subrequests, of which exactly one will be selected by the scheduler. It tries to satisfy them in the order in which they are listed here. So if there are two entries in the list, the scheduler will only check the second one if it determines that the first one can not be used.\n\nDRA does not yet implement scoring, so the scheduler will select the first set of devices that satisfies all the requests in the claim. And if the requirements can be satisfied on more than one node, other scheduling features will determine which node is chosen. This means that the set of devices allocated to a claim might not be the optimal set available to the cluster. Scoring will be implemented later.", + "items": { + "$ref": "#/definitions/v1.DeviceSubRequest" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "name": { + "description": "Name can be used to reference this request in a pod.spec.containers[].resources.claims entry and in a constraint of the claim.\n\nReferences using the name in the DeviceRequest will uniquely identify a request when the Exactly field is set. When the FirstAvailable field is set, a reference to the name of the DeviceRequest will match whatever subrequest is chosen by the scheduler.\n\nMust be a DNS label.", + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "v1.DeviceRequestAllocationResult": { + "description": "DeviceRequestAllocationResult contains the allocation result for one request.", "properties": { - "potentialNodes": { - "description": "PotentialNodes lists nodes where the Pod might be able to run.\n\nThe size of this field is limited to 128. This is large enough for many clusters. Larger clusters may need more attempts to find a node that suits all pending resources. This may get increased in the future, but not reduced.", + "adminAccess": { + "description": "AdminAccess indicates that this device was allocated for administrative access. See the corresponding request field for a definition of mode.\n\nThis is an alpha field and requires enabling the DRAAdminAccess feature gate. Admin access is disabled if this field is unset or set to false, otherwise it is enabled.", + "type": "boolean" + }, + "bindingConditions": { + "description": "BindingConditions contains a copy of the BindingConditions from the corresponding ResourceSlice at the time of allocation.\n\nThis is an alpha field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "bindingFailureConditions": { + "description": "BindingFailureConditions contains a copy of the BindingFailureConditions from the corresponding ResourceSlice at the time of allocation.\n\nThis is an alpha field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", "items": { "type": "string" }, "type": "array", "x-kubernetes-list-type": "atomic" }, - "selectedNode": { - "description": "SelectedNode is the node for which allocation of ResourceClaims that are referenced by the Pod and that use \"WaitForFirstConsumer\" allocation is to be attempted.", + "consumedCapacity": { + "additionalProperties": { + "$ref": "#/definitions/resource.Quantity" + }, + "description": "ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. The consumed amount may differ from the requested amount: it is rounded up to the nearest valid value based on the device\u2019s requestPolicy if applicable (i.e., may not be less than the requested amount).\n\nThe total consumed capacity for each device must not exceed the DeviceCapacity's Value.\n\nThis field is populated only for devices that allow multiple allocations. All capacity entries are included, even if the consumed amount is zero.", + "type": "object" + }, + "device": { + "description": "Device references one device instance via its name in the driver's resource pool. It must be a DNS label.", "type": "string" + }, + "driver": { + "description": "Driver specifies the name of the DRA driver whose kubelet plugin should be invoked to process the allocation once the claim is needed on a node.\n\nMust be a DNS subdomain and should end with a DNS domain owned by the vendor of the driver.", + "type": "string" + }, + "pool": { + "description": "This name together with the driver name and the device name field identify which device was allocated (`//`).\n\nMust not be longer than 253 characters and may contain one or more DNS sub-domains separated by slashes.", + "type": "string" + }, + "request": { + "description": "Request is the name of the request in the claim which caused this device to be allocated. If it references a subrequest in the firstAvailable list on a DeviceRequest, this field must include both the name of the main request and the subrequest using the format
/.\n\nMultiple devices may have been allocated per request.", + "type": "string" + }, + "shareID": { + "description": "ShareID uniquely identifies an individual allocation share of the device, used when the device supports multiple simultaneous allocations. It serves as an additional map key to differentiate concurrent shares of the same device.", + "type": "string" + }, + "tolerations": { + "description": "A copy of all tolerations specified in the request at the time when the device got allocated.\n\nThe maximum number of tolerations is 16.\n\nThis is an alpha field and requires enabling the DRADeviceTaints feature gate.", + "items": { + "$ref": "#/definitions/v1.DeviceToleration" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" } }, + "required": [ + "request", + "driver", + "pool", + "device" + ], "type": "object" }, - "v1alpha2.PodSchedulingContextStatus": { - "description": "PodSchedulingContextStatus describes where resources for the Pod can be allocated.", + "v1.DeviceSelector": { + "description": "DeviceSelector must have exactly one field set.", "properties": { - "resourceClaims": { - "description": "ResourceClaims describes resource availability for each pod.spec.resourceClaim entry where the corresponding ResourceClaim uses \"WaitForFirstConsumer\" allocation mode.", + "cel": { + "$ref": "#/definitions/v1.CELDeviceSelector", + "description": "CEL contains a CEL expression for selecting a device." + } + }, + "type": "object" + }, + "v1.DeviceSubRequest": { + "description": "DeviceSubRequest describes a request for device provided in the claim.spec.devices.requests[].firstAvailable array. Each is typically a request for a single resource like a device, but can also ask for several identical devices.\n\nDeviceSubRequest is similar to ExactDeviceRequest, but doesn't expose the AdminAccess field as that one is only supported when requesting a specific device.", + "properties": { + "allocationMode": { + "description": "AllocationMode and its related fields define how devices are allocated to satisfy this subrequest. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This subrequest is for all of the matching devices in a pool.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other subrequests must specify this field.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", + "type": "string" + }, + "capacity": { + "$ref": "#/definitions/v1.CapacityRequirements", + "description": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request." + }, + "count": { + "description": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.", + "format": "int64", + "type": "integer" + }, + "deviceClassName": { + "description": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this subrequest.\n\nA class is required. Which classes are available depends on the cluster.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", + "type": "string" + }, + "name": { + "description": "Name can be used to reference this subrequest in the list of constraints or the list of configurations for the claim. References must use the format
/.\n\nMust be a DNS label.", + "type": "string" + }, + "selectors": { + "description": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this subrequest. All selectors must be satisfied for a device to be considered.", "items": { - "$ref": "#/definitions/v1alpha2.ResourceClaimSchedulingStatus" + "$ref": "#/definitions/v1.DeviceSelector" }, "type": "array", - "x-kubernetes-list-map-keys": [ - "name" - ], - "x-kubernetes-list-type": "map" + "x-kubernetes-list-type": "atomic" + }, + "tolerations": { + "description": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis is an alpha field and requires enabling the DRADeviceTaints feature gate.", + "items": { + "$ref": "#/definitions/v1.DeviceToleration" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + } + }, + "required": [ + "name", + "deviceClassName" + ], + "type": "object" + }, + "v1.DeviceTaint": { + "description": "The device this taint is attached to has the \"effect\" on any claim which does not tolerate the taint and, through the claim, to pods using the claim.", + "properties": { + "effect": { + "description": "The effect of the taint on claims that do not tolerate the taint and through such claims on the pods using them. Valid effects are NoSchedule and NoExecute. PreferNoSchedule as used for nodes is not valid here.", + "type": "string" + }, + "key": { + "description": "The taint key to be applied to a device. Must be a label name.", + "type": "string" + }, + "timeAdded": { + "description": "TimeAdded represents the time at which the taint was added. Added automatically during create or update if not set.", + "format": "date-time", + "type": "string" + }, + "value": { + "description": "The taint value corresponding to the taint key. Must be a label value.", + "type": "string" + } + }, + "required": [ + "key", + "effect" + ], + "type": "object" + }, + "v1.DeviceToleration": { + "description": "The ResourceClaim this DeviceToleration is attached to tolerates any taint that matches the triple using the matching operator .", + "properties": { + "effect": { + "description": "Effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule and NoExecute.", + "type": "string" + }, + "key": { + "description": "Key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys. Must be a label name.", + "type": "string" + }, + "operator": { + "description": "Operator represents a key's relationship to the value. Valid operators are Exists and Equal. Defaults to Equal. Exists is equivalent to wildcard for value, so that a ResourceClaim can tolerate all taints of a particular category.", + "type": "string" + }, + "tolerationSeconds": { + "description": "TolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system. If larger than zero, the time when the pod needs to be evicted is calculated as