From ae79be6665a2f3423cf2e443c298ca57fce83499 Mon Sep 17 00:00:00 2001 From: Boshi Lian Date: Tue, 29 Apr 2025 16:55:55 -0700 Subject: [PATCH] Clean up warnings in examples (#1628) * Refactor examples to streamline code structure and improve readability * Update LangVersion to 13.0 for improved compatibility --- Directory.Build.props | 2 +- examples/attach/Attach.cs | 53 +++---- examples/csrApproval/Program.cs | 4 +- examples/exec/Exec.cs | 47 +++---- examples/generic/Generic.cs | 30 ++-- examples/labels/PodList.cs | 71 +++++----- examples/logs/Logs.cs | 42 +++--- examples/metrics/Program.cs | 89 ++++++------ examples/namespace/NamespaceExample.cs | 131 ++++++++---------- examples/openTelemetryConsole/Program.cs | 2 +- examples/patch/Program.cs | 43 +++--- examples/portforward/PortForward.cs | 115 +++++++-------- examples/simple/PodList.cs | 33 ++--- examples/watch/Program.cs | 70 ++++------ ...endencyInjectionOnConstructorController.cs | 13 +- ...leDependencyInjectionOnMethodController.cs | 8 +- examples/yaml/Program.cs | 28 ++-- 17 files changed, 335 insertions(+), 446 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 10ec5bf..3d3e1cf 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -26,7 +26,7 @@ snupkg true $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb - 11.0 + 13.0 diff --git a/examples/attach/Attach.cs b/examples/attach/Attach.cs index a53b5da..cfdce7d 100755 --- a/examples/attach/Attach.cs +++ b/examples/attach/Attach.cs @@ -3,38 +3,29 @@ using k8s.Models; using System; using System.Threading.Tasks; -namespace attach +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); + +async Task AttachToPod(IKubernetes client, V1Pod pod) { - internal class Attach + var webSocket = + await client.WebSocketNamespacedPodAttachAsync(pod.Metadata.Name, "default", + pod.Spec.Containers[0].Name).ConfigureAwait(false); + + var demux = new StreamDemuxer(webSocket); + demux.Start(); + + var buff = new byte[4096]; + var stream = demux.GetStream(1, 1); + while (true) { - private static async Task Main(string[] args) - { - 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); - } - - 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); - - 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 read = stream.Read(buff, 0, 4096); + var str = System.Text.Encoding.Default.GetString(buff); + Console.WriteLine(str); } } diff --git a/examples/csrApproval/Program.cs b/examples/csrApproval/Program.cs index a16a9d5..fc94ae9 100644 --- a/examples/csrApproval/Program.cs +++ b/examples/csrApproval/Program.cs @@ -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" + @@ -67,7 +67,7 @@ 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 ("True", "Approved", DateTime.UtcNow, DateTime.UtcNow, "This certificate was approved by k8s client", "Approve"), }; readCert.Status.Conditions = replace; diff --git a/examples/exec/Exec.cs b/examples/exec/Exec.cs index 9fdfc73..20bbd21 100755 --- a/examples/exec/Exec.cs +++ b/examples/exec/Exec.cs @@ -3,35 +3,26 @@ using k8s.Models; using System; using System.Threading.Tasks; -namespace exec +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); + +async Task ExecInPod(IKubernetes client, V1Pod pod) { - internal class Exec - { - private static async Task Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - IKubernetes client = new Kubernetes(config); - Console.WriteLine("Starting Request!"); + var webSocket = + await client.WebSocketNamespacedPodExecAsync(pod.Metadata.Name, "default", "ls", + pod.Spec.Containers[0].Name).ConfigureAwait(false); - var list = client.CoreV1.ListNamespacedPod("default"); - var pod = list.Items[0]; - await ExecInPod(client, pod).ConfigureAwait(false); - } + var demux = new StreamDemuxer(webSocket); + demux.Start(); - 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); - - 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 41f91b3..f65fb94 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 +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) { - 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 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); - } - } - } + Console.WriteLine(pod.Metadata.Name); } diff --git a/examples/labels/PodList.cs b/examples/labels/PodList.cs index 2d59e90..0c5df00 100755 --- a/examples/labels/PodList.cs +++ b/examples/labels/PodList.cs @@ -2,47 +2,38 @@ using k8s; 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); - } - - 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); - } - - if (podList.Items.Count == 0) - { - Console.WriteLine("Empty!"); - } - - Console.WriteLine(); - } - } + continue; } + + var labels = new List(); + foreach (var key in item.Spec.Selector) + { + labels.Add(key.Key + "=" + key.Value); + } + + 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); + } + + if (podList.Items.Count == 0) + { + Console.WriteLine("Empty!"); + } + + Console.WriteLine(); } diff --git a/examples/logs/Logs.cs b/examples/logs/Logs.cs index ea23fa0..5293de5 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 +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +IKubernetes client = new Kubernetes(config); +Console.WriteLine("Starting Request!"); + +var list = client.CoreV1.ListNamespacedPod("default"); +if (list.Items.Count == 0) { - internal class Logs - { - private static async Task Main(string[] args) - { - 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 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()); - } - } + Console.WriteLine("No pods!"); + return; } + +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()); diff --git a/examples/metrics/Program.cs b/examples/metrics/Program.cs index 33a779f..f823bf5 100644 --- a/examples/metrics/Program.cs +++ b/examples/metrics/Program.cs @@ -3,58 +3,49 @@ using System; 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); - - foreach (var item in nodesMetrics.Items) - { - Console.WriteLine(item.Metadata.Name); - - foreach (var metric in item.Usage) - { - Console.WriteLine($"{metric.Key}: {metric.Value}"); - } - } - } - - private static async Task PodsMetrics(IKubernetes client) - { - var podsMetrics = await client.GetKubernetesPodsMetricsAsync().ConfigureAwait(false); - - if (!podsMetrics.Items.Any()) - { - Console.WriteLine("Empty"); - } - - foreach (var item in podsMetrics.Items) - { - 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); - } - } - - 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.WriteLine($"{metric.Key}: {metric.Value}"); } } } + +async Task PodsMetrics(IKubernetes client) +{ + var podsMetrics = await client.GetKubernetesPodsMetricsAsync().ConfigureAwait(false); + + if (!podsMetrics.Items.Any()) + { + Console.WriteLine("Empty"); + } + + foreach (var item in podsMetrics.Items) + { + 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); + } +} + +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 22ad06c..06e8757 100644 --- a/examples/namespace/NamespaceExample.cs +++ b/examples/namespace/NamespaceExample.cs @@ -4,52 +4,37 @@ using System; 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!"); + } +} + +async Task DeleteAsync(IKubernetes client, string name, int delayMillis) +{ + while (true) + { + await Task.Delay(delayMillis).ConfigureAwait(false); + try + { + await client.CoreV1.ReadNamespaceAsync(name).ConfigureAwait(false); } - - private static async Task DeleteAsync(IKubernetes client, string name, int delayMillis) + catch (AggregateException ex) { - while (true) + foreach (var innerEx in ex.InnerExceptions) { - await Task.Delay(delayMillis).ConfigureAwait(false); - try + if (innerEx is k8s.Autorest.HttpOperationException exception) { - 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 (ex.Response.StatusCode == HttpStatusCode.NotFound) + var code = exception.Response.StatusCode; + if (code == HttpStatusCode.NotFound) { return; } @@ -58,41 +43,47 @@ namespace @namespace } } } - - private static void Delete(IKubernetes client, string name, int delayMillis) + catch (k8s.Autorest.HttpOperationException ex) { - DeleteAsync(client, name, delayMillis).Wait(); - } - - private static void Main(string[] args) - { - var k8SClientConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile(); - IKubernetes client = new Kubernetes(k8SClientConfig); - - ListNamespaces(client); - - var ns = new V1Namespace { Metadata = new V1ObjectMeta { Name = "test" } }; - - var result = client.CoreV1.CreateNamespace(ns); - Console.WriteLine(result); - - ListNamespaces(client); - - var status = client.CoreV1.DeleteNamespace(ns.Metadata.Name, new V1DeleteOptions()); - - if (status.HasObject) + if (ex.Response.StatusCode == HttpStatusCode.NotFound) { - var obj = status.ObjectView(); - Console.WriteLine(obj.Status.Phase); - - Delete(client, ns.Metadata.Name, 3 * 1000); - } - else - { - Console.WriteLine(status.Message); + return; } - ListNamespaces(client); + throw; } } } + +void Delete(IKubernetes client, string name, int delayMillis) +{ + DeleteAsync(client, name, delayMillis).Wait(); +} + +var k8SClientConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile(); +IKubernetes client = new Kubernetes(k8SClientConfig); + +ListNamespaces(client); + +var ns = new V1Namespace { Metadata = new V1ObjectMeta { Name = "test" } }; + +var result = client.CoreV1.CreateNamespace(ns); +Console.WriteLine(result); + +ListNamespaces(client); + +var status = client.CoreV1.DeleteNamespace(ns.Metadata.Name, new V1DeleteOptions()); + +if (status.HasObject) +{ + var obj = status.ObjectView(); + Console.WriteLine(obj.Status.Phase); + + 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 4587d76..4b7406b 100644 --- a/examples/openTelemetryConsole/Program.cs +++ b/examples/openTelemetryConsole/Program.cs @@ -24,7 +24,7 @@ IKubernetes client = new Kubernetes(config); // 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); diff --git a/examples/patch/Program.cs b/examples/patch/Program.cs index 7958fcc..f8cefa6 100644 --- a/examples/patch/Program.cs +++ b/examples/patch/Program.cs @@ -3,21 +3,15 @@ using k8s.Models; 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 @@ namespace patch } }"; - client.CoreV1.PatchNamespacedPod(new V1Patch(patchStr, V1Patch.PatchType.MergePatch), name, "default"); - PrintLabels(client.CoreV1.ReadNamespacedPod(name, "default")); - } +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}"); - } - - 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 ed1bd02..ee095e0 100644 --- a/examples/portforward/PortForward.cs +++ b/examples/portforward/PortForward.cs @@ -6,75 +6,66 @@ using System.Net.Sockets; using System.Text; using System.Threading.Tasks; -namespace portforward +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).ConfigureAwait(false); + +async Task Forward(IKubernetes client, V1Pod pod) { - internal class Portforward + // 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(); + + var stream = demux.GetStream((byte?)0, (byte?)0); + + 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); + + Socket handler = null; + + // Note this will only accept a single connection + var accept = Task.Run(() => { - private static async Task Main(string[] args) + while (true) { - 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).ConfigureAwait(false); - } - - 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").ConfigureAwait(false); - var demux = new StreamDemuxer(webSocket, StreamType.PortForward); - demux.Start(); - - var stream = demux.GetStream((byte?)0, (byte?)0); - - 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); - - Socket handler = null; - - // Note this will only accept a single connection - var accept = Task.Run(() => + handler = listener.Accept(); + var bytes = new byte[4096]; + while (true) { - while (true) + int bytesRec = handler.Receive(bytes); + stream.Write(bytes, 0, bytesRec); + if (bytesRec == 0 || Encoding.ASCII.GetString(bytes, 0, bytesRec).IndexOf("") > -1) { - 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; - } - } + break; } - }); - - 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(); } + }); + + 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/simple/PodList.cs b/examples/simple/PodList.cs index b9eb3cd..751622c 100755 --- a/examples/simple/PodList.cs +++ b/examples/simple/PodList.cs @@ -1,26 +1,17 @@ using k8s; using System; -namespace simple +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) { - internal class PodList - { - private static void Main(string[] args) - { - 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); - } - - if (list.Items.Count == 0) - { - Console.WriteLine("Empty!"); - } - } - } + Console.WriteLine(item.Metadata.Name); +} + +if (list.Items.Count == 0) +{ + Console.WriteLine("Empty!"); } diff --git a/examples/watch/Program.cs b/examples/watch/Program.cs index d5452e2..f21f8f8 100644 --- a/examples/watch/Program.cs +++ b/examples/watch/Program.cs @@ -4,49 +4,37 @@ using System; using System.Threading; using System.Threading.Tasks; -namespace watch +var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); + +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().ConfigureAwait(false)) { - internal class Program + Console.WriteLine("==on watch event=="); + Console.WriteLine(type); + Console.WriteLine(item.Metadata.Name); + Console.WriteLine("==on watch event=="); +} + +#pragma warning disable CS8321 // Remove unused private members +void WatchUsingCallback(IKubernetes client) +#pragma warning restore CS8321 // Remove unused private members +{ + var podlistResp = client.CoreV1.ListNamespacedPodWithHttpMessagesAsync("default", watch: true); + using (podlistResp.Watch((type, item) => { - private static async Task Main(string[] args) - { - var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); + 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"); - 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().ConfigureAwait(false)) - { - Console.WriteLine("==on watch event=="); - Console.WriteLine(type); - Console.WriteLine(item.Metadata.Name); - Console.WriteLine("==on watch event=="); - } - - // uncomment if you prefer callback api - // WatchUsingCallback(client); - } - -#pragma warning disable IDE0051 // Remove unused private members - private static void WatchUsingCallback(IKubernetes client) -#pragma warning restore IDE0051 // Remove unused private members - { - 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"); - - 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(); } } diff --git a/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnConstructorController.cs b/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnConstructorController.cs index 30fd265..6bff6df 100644 --- a/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnConstructorController.cs +++ b/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnConstructorController.cs @@ -10,22 +10,23 @@ namespace webApiDependencyInjection.Controllers 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 0a831be..84427f5 100644 --- a/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnMethodController.cs +++ b/examples/webApiDependencyInjection/Controllers/ExampleDependencyInjectionOnMethodController.cs @@ -10,11 +10,13 @@ namespace webApiDependencyInjection.Controllers /// /// 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/yaml/Program.cs b/examples/yaml/Program.cs index ef7feba..47b70bd 100644 --- a/examples/yaml/Program.cs +++ b/examples/yaml/Program.cs @@ -2,27 +2,17 @@ using k8s; 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).ConfigureAwait(false); +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); }