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); }
private void Init() { if (_initialized) { return; } _client = _kubernetesClientFactory.Create(); _initialized = true; }
public async Task GetNamespacedCustomResource() { var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var kubernetes = new Kubernetes(config); var entity = await kubernetes.GetNamespacedCustomResource <ArgoApplicationResource>( "argo", "azl-dev-elysium-api", CancellationToken.None ); }
public KubernetesRepository() { // _client = new Kubernetes( // KubernetesClientConfiguration.InClusterConfig() // ); _config = KubernetesClientConfiguration.BuildDefaultConfig(); _client = new Kubernetes(_config); }
private void StatefulSetsLoader_DoWork(object sender, DoWorkEventArgs e) { var args = e.Argument as ExpandRequest; using var client = new Kubernetes(k8sConfig); e.Result = new ExpandStatefulSetResponse( args.Item1, client.ListNamespacedStatefulSet(args.Item1.Metadata.Name), args.Item2); }
public ActionResult <IEnumerable <string> > GetNamespaces() { // Use the config object to create a client. using (var client = new Kubernetes(k8sConfig)) { var namespaces = client.ListNamespace(); return(namespaces.Items.Select(ns => ns.Metadata.Name).ToArray()); } }
public ActionResult <IEnumerable <string> > GetPods() { // Use the config object to create a client. using (var client = new Kubernetes(k8sConfig)) { var podList = client.ListNamespacedPod("invaders"); return(podList.Items.Select(p => p.Metadata.Name).ToArray()); } }
public async Task ExecDefaultContainerStdOut() { if (!Debugger.IsAttached) { CancellationSource.CancelAfter( TimeSpan.FromSeconds(5)); } await Host.StartAsync(TestCancellation).ConfigureAwait(false); using (Kubernetes client = CreateTestClient()) { testOutput.WriteLine("Invoking exec operation..."); WebSocket clientSocket = await client.WebSocketNamespacedPodExecAsync( name: "mypod", @namespace: "mynamespace", command: new string[] { "/bin/bash" }, container: "mycontainer", stderr: false, stdin: false, stdout: true, webSocketSubProtol: WebSocketProtocol.ChannelWebSocketProtocol, cancellationToken: TestCancellation).ConfigureAwait(false); Assert.Equal( WebSocketProtocol.ChannelWebSocketProtocol, clientSocket.SubProtocol); // For WebSockets, the Kubernetes API defaults to the binary channel (v1) protocol. testOutput.WriteLine( $"Client socket connected (socket state is {clientSocket.State}). Waiting for server-side socket to become available..."); WebSocket serverSocket = await WebSocketTestAdapter.AcceptedPodExecV1Connection; testOutput.WriteLine( $"Server-side socket is now available (socket state is {serverSocket.State}). Sending data to server socket..."); const int STDOUT = 1; const string expectedOutput = "This is text send to STDOUT."; int bytesSent = await SendMultiplexed(serverSocket, STDOUT, expectedOutput).ConfigureAwait(false); testOutput.WriteLine($"Sent {bytesSent} bytes to server socket; receiving from client socket..."); (string receivedText, byte streamIndex, int bytesReceived) = await ReceiveTextMultiplexed(clientSocket).ConfigureAwait(false); testOutput.WriteLine( $"Received {bytesReceived} bytes from client socket ('{receivedText}', stream {streamIndex})."); Assert.Equal(STDOUT, streamIndex); Assert.Equal(expectedOutput, receivedText); await Disconnect(clientSocket, serverSocket, closeStatus: WebSocketCloseStatus.NormalClosure, closeStatusDescription: "Normal Closure").ConfigureAwait(false); WebSocketTestAdapter.CompleteTest(); } }
private static async Task ExecuteAsync(string [] args) { var clusterApiUrl = Environment.GetEnvironmentVariable("AKS_URI"); var adoUrl = Environment.GetEnvironmentVariable("AZDO_ORG_SERVICE_URL"); var pat = Environment.GetEnvironmentVariable("AZDO_PERSONAL_ACCESS_TOKEN"); var adoClient = new AdoClient(adoUrl, pat); var groups = await adoClient.ListGroupsAsync(); var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var client = new Kubernetes(config); var accounts = await client .ListServiceAccountForAllNamespacesAsync(labelSelector : "purpose=ado-automation"); foreach (var account in accounts.Items) { var project = await GetProjectAsync(account.Metadata.Labels["project"], adoClient); var secretName = account.Secrets[0].Name; var secret = await client .ReadNamespacedSecretAsync(secretName, account.Metadata.NamespaceProperty); var endpoint = await adoClient.CreateKubernetesEndpointAsync( project.Id, project.Name, $"Kubernetes-Cluster-Endpoint-{account.Metadata.NamespaceProperty}", $"Service endpoint to the namespace {account.Metadata.NamespaceProperty}", clusterApiUrl, Convert.ToBase64String(secret.Data["ca.crt"]), Convert.ToBase64String(secret.Data["token"])); var environment = await adoClient.CreateEnvironmentAsync(project.Name, $"Kubernetes-Environment-{account.Metadata.NamespaceProperty}", $"Environment scoped to the namespace {account.Metadata.NamespaceProperty}"); await adoClient.CreateKubernetesResourceAsync(project.Name, environment.Id, endpoint.Id, account.Metadata.NamespaceProperty, account.Metadata.ClusterName); var group = groups.FirstOrDefault(g => g.DisplayName .Equals($"[{project.Name}]\\Release Administrators", StringComparison.OrdinalIgnoreCase)); await adoClient.CreateApprovalPolicyAsync(project.Name, group.OriginId, environment.Id); await adoClient.CreateAcrConnectionAsync(project.Name, Environment.GetEnvironmentVariable("ACRName"), $"ACR-Connection", "The connection to the ACR", Environment.GetEnvironmentVariable("SubId"), Environment.GetEnvironmentVariable("SubName"), Environment.GetEnvironmentVariable("ResourceGroup"), Environment.GetEnvironmentVariable("ClientId"), Environment.GetEnvironmentVariable("Secret"), Environment.GetEnvironmentVariable("TenantId")); } }
PatchDeploymentAsync(Kubernetes k8sClient, MTADeployModel patchModel) { var namespaceParams = PrepareNamespaceParams(_groupName); var deployParams = PrepareDeployParams(_deployName); var existingDeployment = await k8sClient.ReadNamespacedDeploymentAsync (deployParams.Item1, namespaceParams); patchModel.Image = existingDeployment.Spec.Template.Spec.Containers[0].Image; patchModel.ImagePullPolicy = existingDeployment.Spec.Template.Spec.Containers[0].ImagePullPolicy; patchModel.Replicas = (int)(existingDeployment.Spec.Replicas); var container = existingDeployment.Spec.Template.Spec.Containers[0]; container.Name = deployParams.Item3; if (patchModel.Env != null) { var v1EnvList = new List <V1EnvVar>(); foreach (var env in patchModel.Env) { var v1Env = new V1EnvVar(env["name"], env["value"]); v1EnvList.Add(v1Env); } container.Env = v1EnvList; } var containerPorts = new List <V1ContainerPort>(); foreach (var port in patchModel.Ports) { var v1ContainerPort = new V1ContainerPort(port); containerPorts.Add(v1ContainerPort); } container.Ports = containerPorts; try { var v1Patch = new V1Patch(patchModel, V1Patch.PatchType.MergePatch); var v1Deployment = await k8sClient.PatchNamespacedDeploymentAsync (v1Patch, _deployName, _groupName); var deployModel = new MTADeployModel(v1Deployment); return(new Tuple <MTADeployModel, MTAErrorModel>(deployModel, null)); } catch (HttpOperationException ex) { var errorModel = new MTAErrorModel(ex); return(new Tuple <MTADeployModel, MTAErrorModel>(null, errorModel)); } catch (Exception) { throw; } }
V1Secret GetSecret(Kubernetes k8s, MSSQLDB db) { try { return(k8s.ReadNamespacedSecret(db.Spec.Credentials, db.Namespace())); } catch (HttpOperationException hoex) when(hoex.Response.StatusCode == System.Net.HttpStatusCode.NotFound) { throw new ApplicationException($"Secret '{db.Spec.Credentials}' not found in namespace {db.Namespace()}"); } }
V1ConfigMap GetConfigMap(Kubernetes k8s, MSSQLDB db) { try { return(k8s.ReadNamespacedConfigMap(db.Spec.ConfigMap, db.Namespace())); } catch (HttpOperationException hoex) when(hoex.Response.StatusCode == System.Net.HttpStatusCode.NotFound) { throw new ApplicationException($"ConfigMap '{db.Spec.ConfigMap}' not found in namespace {db.Namespace()}"); } }
private Tuple <Kubernetes, KubernetesClientConfiguration> PrepareK8s() { var path = Directory.GetCurrentDirectory(); path = string.Concat(path, kConfigPathString); var k8sConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile(path); var k8sClient = new Kubernetes(k8sConfig); return(new Tuple <Kubernetes, KubernetesClientConfiguration>(k8sClient, k8sConfig));; }
static void changeDeploymentReplicas(Kubernetes client, int replicaCount) { var patch = new JsonPatchDocument <V1Deployment>(); patch.Replace(e => e.Spec.Replicas, replicaCount); client.PatchNamespacedDeployment( new V1Patch(patch), "nginx-deployment", "default" ); }
public async Task <string> GetHostNodeExternalIp() { try { _logger.LogDebug("Loading k8s in cluster config..."); var config = KubernetesClientConfiguration.InClusterConfig(); _logger.LogDebug("Init k8s client..."); var client = new Kubernetes(config); _logger.LogDebug("Listing pods for all namespaces..."); var pods = await client.ListPodForAllNamespacesAsync(); _logger.LogInformation($"Found {pods?.Items?.Count} pods for all namespaces"); _logger.LogDebug($"Locating host pod '{_config.Hostname}' ..."); var hostPod = pods.Items.FirstOrDefault(x => x.Metadata.Name == _config.Hostname); var hostIp = hostPod?.Status?.HostIP; if (hostPod == null) { throw new Exception("Unable to found host pod"); } if (hostIp == null) { throw new Exception("Unable to get host ip from pod status"); } _logger.LogInformation($"Found host pod '{_config.Hostname}' with host ip '{hostIp}'"); _logger.LogDebug("Listing nodes..."); var nodes = await client.ListNodeAsync(); _logger.LogInformation($"Found {nodes?.Items?.Count} nodes"); _logger.LogDebug($"Locating host node..."); var hostNode = nodes.Items.FirstOrDefault(x => x.Status.Addresses.Any(y => y.Address == hostIp)); var hostNodeExternalIp = hostNode?.Status?.Addresses.FirstOrDefault(x => x.Type == _config.ExternalIpNodeAddressType)?.Address; if (hostNode == null) { throw new Exception("Unable to found host node"); } if (hostNodeExternalIp == null) { throw new Exception($"Unable to get {_config.ExternalIpNodeAddressType} from host node"); } _logger.LogInformation($"External ip for host node is '{hostNodeExternalIp}'"); return(hostNodeExternalIp); } catch (Exception exc) { _logger.LogError(exc, "Error while getting host node external ip"); throw; } }
static void Main(string[] args) { var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); IKubernetes client = new Kubernetes(config); //ApiClient.setDebugging(true); Console.WriteLine("Starting Request!"); // ListPods(client); //var metaDataDictionary = new Dictionary<string, string>(); //metaDataDictionary.Add("name", "web-pod1"); //metaDataDictionary.Add("namespace", "default"); //client.CreateNamespacedPod(new k8s.Models.V1Pod() //{ // ApiVersion = "v1", // Kind = "Pod", // Metadata = new k8s.Models.V1ObjectMeta() { Labels = metaDataDictionary }, // Spec = new k8s.Models.V1PodSpec() // { // Containers = new List<k8s.Models.V1Container>() { // new k8s.Models.V1Container() { // Image = "abhishekagg24/stableapp:v1", // Name = "web-ctr1", // Ports = new List<k8s.Models.V1ContainerPort>(){ // new k8s.Models.V1ContainerPort() { ContainerPort = 8080 } // } // } // } // }, // //Status = new k8s.Models.V1PodStatus() { } //} //, "default"); //V1Pod obj = CreatePodDefinition(); //client.CreateNamespacedPod(obj, "default"); V1Deployment depl = CreateDeploymentDefinition(); var deployment = client.CreateNamespacedDeployment(depl, "default"); //if (deployment != null) //{ ListPods(client); // } Console.ReadKey(); }
public void ValidCert() { var caCert = new X509Certificate2("assets/ca.crt"); var testCert = new X509Certificate2("assets/ca.crt"); var chain = new X509Chain(); var errors = SslPolicyErrors.RemoteCertificateChainErrors; var result = Kubernetes.CertificateValidationCallBack(this, caCert, testCert, chain, errors); Assert.True(result); }
public ActionResult <string> Get() { var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); var client = new Kubernetes(config); var list1 = client.ListNamespacedPodAsync("default").Result; var list = client.ListNamespace(); var json = JsonConvert.SerializeObject(list); return(json); }
public void WatchAllEvents() { using (var server = new MockKubeApiServer(async httpContext => { await WriteStreamLine(httpContext, MockKubeApiServer.MockPodResponse); await Task.Delay(TimeSpan.FromMilliseconds(100)); await WriteStreamLine(httpContext, MockAddedEventStreamLine); await Task.Delay(TimeSpan.FromMilliseconds(100)); await WriteStreamLine(httpContext, MockDeletedStreamLine); await Task.Delay(TimeSpan.FromMilliseconds(100)); await WriteStreamLine(httpContext, MockModifiedStreamLine); await Task.Delay(TimeSpan.FromMilliseconds(100)); await WriteStreamLine(httpContext, MockErrorStreamLine); await Task.Delay(TimeSpan.FromMilliseconds(100)); // make server alive, cannot set to int.max as of it would block response await Task.Delay(TimeSpan.FromDays(1)); return(false); })) { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString() }); var listTask = client.ListNamespacedPodWithHttpMessagesAsync("default", watch: true).Result; var events = new HashSet <WatchEventType>(); var errors = 0; var watcher = listTask.Watch <V1Pod>( (type, item) => { events.Add(type); }, e => { errors += 1; } ); // wait server yields all events Thread.Sleep(TimeSpan.FromMilliseconds(1000)); Assert.Contains(WatchEventType.Added, events); Assert.Contains(WatchEventType.Deleted, events); Assert.Contains(WatchEventType.Modified, events); Assert.Contains(WatchEventType.Error, events); Assert.Equal(0, errors); Assert.True(watcher.Watching); } }
public void GetExitCodeOrThrowOtherError() { var status = new V1Status() { Metadata = null, Status = "Failure", Reason = "SomethingElse" }; var ex = Assert.Throws <KubernetesException>(() => Kubernetes.GetExitCodeOrThrow(status)); Assert.Equal(status, ex.Status); }
public async Task TestWatchWithHandlers() { AsyncCountdownEvent eventsReceived = new AsyncCountdownEvent(1); AsyncManualResetEvent serverShutdown = new AsyncManualResetEvent(); using (var server = new MockKubeApiServer(testOutput, async httpContext => { await WriteStreamLine(httpContext, MockKubeApiServer.MockPodResponse); await WriteStreamLine(httpContext, MockAddedEventStreamLine); // make server alive, cannot set to int.max as of it would block response await serverShutdown.WaitAsync(); return(false); })) { var handler1 = new DummyHandler(); var handler2 = new DummyHandler(); var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString() }, handler1, handler2); Assert.False(handler1.Called); Assert.False(handler2.Called); var listTask = await client.ListNamespacedPodWithHttpMessagesAsync("default", watch : true); var events = new HashSet <WatchEventType>(); var watcher = listTask.Watch <V1Pod, V1PodList>( (type, item) => { events.Add(type); eventsReceived.Signal(); } ); // wait server yields all events await Task.WhenAny(eventsReceived.WaitAsync(), Task.Delay(TestTimeout)); Assert.True( eventsReceived.CurrentCount == 0, "Timed out waiting for all events / errors to be received." ); Assert.Contains(WatchEventType.Added, events); Assert.True(handler1.Called); Assert.True(handler2.Called); serverShutdown.Set(); } }
private async Task UpdateRecordsetStatus(DnsRecordset recordset, DnsRecordset.Statuses status) { recordset.Metadata.Annotations[DnsRecordset.StatusAnnotationName] = status.ToString(); var patch = new JsonPatchDocument <DnsRecordset>(); patch.Replace(x => x.Metadata.Annotations, recordset.Metadata.Annotations); patch.Operations.ForEach(x => x.path = x.path.ToLower()); var response = await Kubernetes.PatchClusterCustomObjectAsync(new V1Patch(patch), Group, Version, Plural, recordset.Metadata.Name); }
static V1Role GetRole(Kubernetes client, string namespaceName) { var rolesTask = client.ListNamespacedRoleWithHttpMessagesAsync(namespaceName); rolesTask.Wait(); AssertErrors(rolesTask.Result); var fullAccessRole = rolesTask.Result.Body.Items.SingleOrDefault(i => i.Metadata.Name.EndsWith("-fullaccess")); return(fullAccessRole); }
public void InvalidBundleCert() { var caCert = CertUtils.LoadPemFileCert("assets/ca-bundle.crt"); var testCert = new X509Certificate2("assets/ca2.crt"); var chain = new X509Chain(); var errors = SslPolicyErrors.RemoteCertificateChainErrors; var result = Kubernetes.CertificateValidationCallBack(this, caCert, testCert, chain, errors); Assert.False(result); }
public async Task NamespacedPodExecAsyncExitCodeNonZero() { var processStatus = new V1Status() { Metadata = null, Status = "Failure", Message = "command terminated with non-zero exit code: Error executing in Docker Container: 1", Reason = "NonZeroExitCode", Details = new V1StatusDetails() { Causes = new List <V1StatusCause>() { new V1StatusCause() { Reason = "ExitCode", Message = "1" }, }, }, }; var processStatusJson = Encoding.UTF8.GetBytes(SafeJsonConvert.SerializeObject(processStatus)); var handler = new ExecAsyncCallback((stdIn, stdOut, stdError) => Task.CompletedTask); using (MemoryStream stdIn = new MemoryStream()) using (MemoryStream stdOut = new MemoryStream()) using (MemoryStream stdErr = new MemoryStream()) using (MemoryStream errorStream = new MemoryStream(processStatusJson)) { var muxedStream = new Moq.Mock <IStreamDemuxer>(); muxedStream.Setup(m => m.GetStream(null, ChannelIndex.StdIn)).Returns(stdIn); muxedStream.Setup(m => m.GetStream(ChannelIndex.StdOut, null)).Returns(stdOut); muxedStream.Setup(m => m.GetStream(ChannelIndex.StdErr, null)).Returns(stdErr); muxedStream.Setup(m => m.GetStream(ChannelIndex.Error, null)).Returns(errorStream); var kubernetesMock = new Moq.Mock <Kubernetes>( new object[] { Moq.Mock.Of <ServiceClientCredentials>(), new DelegatingHandler[] { } }); var command = new string[] { "/bin/bash", "-c", "echo Hello, World!" }; var exception = new Exception(); kubernetesMock.Setup(m => m.MuxedStreamNamespacedPodExecAsync("pod-name", "pod-namespace", command, "my-container", true, true, true, false, WebSocketProtocol.V4BinaryWebsocketProtocol, null, CancellationToken.None)) .Returns(Task.FromResult(muxedStream.Object)); using (Kubernetes client = kubernetesMock.Object) { var exitCode = await client.NamespacedPodExecAsync("pod-name", "pod-namespace", "my-container", command, false, handler, CancellationToken.None).ConfigureAwait(false); Assert.Equal(1, exitCode); } } }
private static async Task Main(string[] args) { var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); IKubernetes client = new Kubernetes(config); Console.WriteLine("Starting Request!"); var list = client.ListNamespacedPod("default"); var pod = list.Items[0]; await ExecInPod(client, pod); }
private static void ShouldThrowUnauthorized(Kubernetes client) { try { PeelAggregate(() => ExecuteListPods(client)); Assert.True(false, "should not be here"); } catch (HttpOperationException e) { Assert.Equal(HttpStatusCode.Unauthorized, e.Response.StatusCode); } }
public ActionResult <IEnumerable <Tenant> > Get(int id) { var config = KubernetesClientConfiguration.BuildConfigFromConfigFile("/app/config"); IKubernetes client = new Kubernetes(config); var tenants = new List <Tenant>(); var list = client.ListNamespacedPod("default"); var svc = client.ListNamespacedService("default"); foreach (var service in svc.Items) { try { var tenant = new Tenant(); Console.WriteLine(service.Metadata.Name); var svcPort = service.Spec.Ports[0].TargetPort.Value.ToString(); var svcExtIp = service.Status.LoadBalancer.Ingress[0].Ip.ToString(); var rcPort = new string(""); try { rcPort = service.Spec.Ports[1].TargetPort.Value.ToString(); } catch (Exception) { // throw; } tenant.Name = service.Metadata.Name; tenant.Endpoint = new Endpoint { Minecraft = $"{svcExtIp}:{svcPort}", Rcon = $"{svcExtIp}:{rcPort}" }; tenants.Add(tenant); } catch (Exception) { //throw; } } var returnString = $"Pods{Environment.NewLine}"; foreach (var item in list.Items) { returnString += $"{item.Metadata.Name}{Environment.NewLine}"; } if (list.Items.Count == 0) { Console.WriteLine("Empty!"); } return(tenants); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync(context.Request.Host.ToString()); await context.Response.WriteAsync(Environment.NewLine); await context.Response.WriteAsync("Hello from backend!!!"); }); endpoints.MapGet("/env", async context => { context.Response.ContentType = "application/json"; var configuration = context.RequestServices.GetRequiredService <IConfiguration>() as IConfigurationRoot; var vars = Environment.GetEnvironmentVariables() .Cast <DictionaryEntry>() .OrderBy(e => (string)e.Key) .ToDictionary(e => (string)e.Key, e => (string)e.Value); var data = new { version = Environment.Version.ToString(), env = vars, configuration = configuration.AsEnumerable().ToDictionary(c => c.Key, c => c.Value), configurtionDebug = configuration.GetDebugView(), }; await JsonSerializer.SerializeAsync(context.Response.Body, data); }); endpoints.MapGet("/replicas", async context => { context.Response.ContentType = "application/json"; if (!KubernetesClientConfiguration.IsInCluster()) { await JsonSerializer.SerializeAsync(context.Response.Body, new { message = "Not running in k8s" }); return; } var config = KubernetesClientConfiguration.InClusterConfig(); var klient = new Kubernetes(config); var endpointsList = await klient.ListNamespacedEndpointsAsync("default"); await JsonSerializer.SerializeAsync(context.Response.Body, endpointsList.Items); }); }); }
public void Setup() { var config = KubernetesClientConfiguration.BuildConfigFromConfigFile("assets/config"); _client = new Kubernetes(config); _guidNS = Guid.NewGuid().ToString(); _namespace = new V1Namespace { Metadata = new V1ObjectMeta { Name = _guidNS } }; }