using k8s; using ContainerDashboard.Models; using k8s.Models; namespace ContainerDashboard.Repositories; public class KubernetesHandler : IContainerHandler { private readonly KubernetesClientConfiguration _config; private readonly Kubernetes _client; public KubernetesHandler() { try { var configPath = Environment.GetEnvironmentVariable("KUBECONFIG"); _config = KubernetesClientConfiguration.BuildConfigFromConfigFile(Environment.GetEnvironmentVariable("KUBECONFIG")); } catch (ArgumentNullException) { _config = KubernetesClientConfiguration.BuildConfigFromConfigFile(); } _client = new Kubernetes(_config); } public Task GetContainer(string containerName, string? containerNamespace) { throw new NotImplementedException(); } public async Task GetContainers() { var list = await _client.AppsV1.ListDeploymentForAllNamespacesAsync(); var containers = new List(); foreach (var item in list.Items) { if (item.Namespace() == "kube-system") continue; var c = new Container { ContainerNamespace = item.Namespace(), Name = item.Name(), Running = item.Status.ReadyReplicas > 0 }; containers.Add(c); } return containers.ToArray(); } public async Task StartContainer(string containerName, string? containerNamespace) { var container = await _client.AppsV1.ReadNamespacedDeploymentAsync(containerName, containerNamespace); if (container == null) { throw new Exception($"Could not get container {containerName} in namespace {containerNamespace}"); } var patchStr = @" { ""spec"": { ""replicas"": 1 } } "; var patch = new V1Patch(patchStr, V1Patch.PatchType.MergePatch); var result = await _client.AppsV1.PatchNamespacedDeploymentAsync(patch, containerName, containerNamespace, fieldManager: "ContainerDashboard"); if (result == null) { throw new Exception($"Could not update container {containerName} in namespace {containerNamespace}"); } } public async Task StopContainer(string containerName, string? containerNamespace) { var container = await _client.AppsV1.ReadNamespacedDeploymentAsync(containerName, containerNamespace); if (container == null) { throw new Exception($"Could not get container {containerName} in namespace {containerNamespace}"); } var patchStr = @" { ""spec"": { ""replicas"": 0 } } "; var patch = new V1Patch(patchStr, V1Patch.PatchType.MergePatch); var result = await _client.AppsV1.PatchNamespacedDeploymentAsync(patch, containerName, containerNamespace, fieldManager: "ContainerDashboard"); if (result == null) { throw new Exception($"Could not update container {containerName} in namespace {containerNamespace}"); } } }