Exemple #1
0
        public async Task LoadAllFromFile()
        {
            var content = @"apiVersion: v1
kind: Pod
metadata:
  name: foo
---
apiVersion: v1
kind: Namespace
metadata:
  name: ns";

            var tempFileName = Path.GetTempFileName();

            try
            {
                await File.WriteAllTextAsync(tempFileName, content).ConfigureAwait(false);

                var objs = await Yaml.LoadAllFromFileAsync(tempFileName).ConfigureAwait(false);

                Assert.Equal(2, objs.Count);
                Assert.IsType <V1Pod>(objs[0]);
                Assert.IsType <V1Namespace>(objs[1]);
                Assert.Equal("foo", ((V1Pod)objs[0]).Metadata.Name);
                Assert.Equal("ns", ((V1Namespace)objs[1]).Metadata.Name);
            }
            finally
            {
                if (File.Exists(tempFileName))
                {
                    File.Delete(tempFileName);
                }
            }
        }
Exemple #2
0
        private async Task <(IngressData, List <Endpoints>)> GetKubernetesInfo(string name)
        {
            var typeMap = new Dictionary <string, Type>();

            typeMap.Add("networking.k8s.io/v1/Ingress", typeof(V1Ingress));
            typeMap.Add("v1/Endpoints", typeof(V1Endpoints));

            var kubeObjects = await Yaml.LoadAllFromFileAsync(Path.Combine("testassets", name, "ingress.yaml"), typeMap).ConfigureAwait(false);

            IngressData ingressData  = default;
            var         endpointList = new List <Endpoints>();

            foreach (var obj in kubeObjects)
            {
                if (obj is V1Ingress ingress)
                {
                    ingressData = new IngressData(ingress);
                }
                else if (obj is V1Endpoints endpoints)
                {
                    endpointList.Add(new Endpoints(endpoints));
                }
            }

            return(ingressData, endpointList);
        }
Exemple #3
0
        public async Task ShouldGenerateDeployment()
        {
            var deployment = (await Yaml.LoadAllFromFileAsync("./kustomize/templates/deployment.yaml")).First() as k8s.Models.V1Deployment;

            deployment.Metadata.NamespaceProperty = _appGroup;
            deployment.Metadata.Name = _appName;

            deployment.Metadata.Labels["app"]     = _appName;
            deployment.Metadata.Labels["release"] = _release;
            deployment.Metadata.Labels["group"]   = _appGroup;

            deployment.Spec.Selector.MatchLabels["app"]   = _appName;
            deployment.Spec.Selector.MatchLabels["group"] = _appGroup;

            deployment.Spec.Template.Metadata.Labels["release"] = _release;
            deployment.Spec.Template.Metadata.Labels["app"]     = _appName;

            var container = deployment.Spec.Template.Spec.Containers.First();

            container.Name  = _appName;
            container.Image = _imageName;

            var deploymentYaml = Yaml.SaveToString(deployment);

            Assert.AreEqual(File.ReadAllText("./data/expected-deployment.yaml").SanitizeYamlForTests(), deploymentYaml.SanitizeYamlForTests());
        }
Exemple #4
0
    private async Task <ICache> GetKubernetesInfo(string name)
    {
        var cache = new IngressCache();

        var typeMap = new Dictionary <string, Type>();

        typeMap.Add("networking.k8s.io/v1/Ingress", typeof(V1Ingress));
        typeMap.Add("v1/Service", typeof(V1Service));
        typeMap.Add("v1/Endpoints", typeof(V1Endpoints));

        var kubeObjects = await Yaml.LoadAllFromFileAsync(Path.Combine("testassets", name, "ingress.yaml"), typeMap).ConfigureAwait(false);

        foreach (var obj in kubeObjects)
        {
            if (obj is V1Ingress ingress)
            {
                cache.Update(WatchEventType.Added, ingress);
            }
            else if (obj is V1Service service)
            {
                cache.Update(WatchEventType.Added, service);
            }
            else if (obj is V1Endpoints endpoints)
            {
                cache.Update(WatchEventType.Added, endpoints);
            }
        }

        return(cache);
    }
Exemple #5
0
        public async Task ShouldGenerateNamespace()
        {
            var @namespace = (await Yaml.LoadAllFromFileAsync("./kustomize/templates/namespace.yaml")).First() as k8s.Models.V1Namespace;

            @namespace.Metadata.Name            = _namespaceName;
            @namespace.Metadata.Labels["group"] = _appGroup;

            var namespaceYaml = Yaml.SaveToString(@namespace);

            Assert.AreEqual(File.ReadAllText("./data/expected-namespace.yaml").SanitizeYamlForTests(), namespaceYaml.SanitizeYamlForTests());
        }
Exemple #6
0
        private async static Task Main(string[] args)
        {
            var typeMap = new Dictionary <String, Type>();

            typeMap.Add("v1/Pod", typeof(V1Pod));
            typeMap.Add("v1/Service", typeof(V1Service));
            typeMap.Add("apps/v1beta1/Deployment", typeof(Appsv1beta1Deployment));

            var objects = await Yaml.LoadAllFromFileAsync(args[0], typeMap);

            foreach (var obj in objects)
            {
                Console.WriteLine(obj);
            }
        }
Exemple #7
0
        public async Task ShouldGenerateService()
        {
            var service = (await Yaml.LoadAllFromFileAsync("./kustomize/templates/service.yaml")).First() as k8s.Models.V1Service;

            service.Metadata.NamespaceProperty = _namespaceName;
            service.Metadata.Name = _serviceName;

            service.Metadata.Labels["app"]     = _appName;
            service.Metadata.Labels["release"] = _release;
            service.Metadata.Labels["group"]   = _appGroup;
            service.Spec.Selector["release"]   = _release;
            service.Spec.Selector["app"]       = _appName;

            var serviceYaml = Yaml.SaveToString(service);

            Assert.AreEqual(File.ReadAllText("./data/expected-service.yaml").SanitizeYamlForTests(), serviceYaml.SanitizeYamlForTests());
        }
Exemple #8
0
        public async Task ShouldGenerateIngress()
        {
            var ingress = (await Yaml.LoadAllFromFileAsync("./kustomize/templates/ingress.yaml")).First() as k8s.Models.V1Ingress;

            ingress.Metadata.Name = $"ingress-{_appName}";
            ingress.Metadata.NamespaceProperty = _appGroup;
            ingress.Metadata.Labels["app"]     = _appName;
            ingress.Metadata.Labels["group"]   = _appGroup;

            var rule = ingress.Spec.Rules.First();
            var path = rule.Http.Paths.First();

            path.Path = "/trades/V1";
            path.Backend.Service.Name = _serviceName;

            var ingressYaml = Yaml.SaveToString(ingress);

            Assert.AreEqual(File.ReadAllText("./data/expected-ingress.yaml").SanitizeYamlForTests(), ingressYaml.SanitizeYamlForTests());
        }
    private async Task <ICache> GetKubernetesInfo(string name, V1IngressClass ingressClass)
    {
        var mockLogger  = new Mock <ILogger <IngressCache> >();
        var mockOptions = new Mock <IOptions <YarpOptions> >();

        mockOptions.SetupGet(o => o.Value).Returns(new YarpOptions {
            ControllerClass = "microsoft.com/ingress-yarp"
        });

        var cache = new IngressCache(mockOptions.Object, mockLogger.Object);

        var typeMap = new Dictionary <string, Type>();

        typeMap.Add("networking.k8s.io/v1/Ingress", typeof(V1Ingress));
        typeMap.Add("v1/Service", typeof(V1Service));
        typeMap.Add("v1/Endpoints", typeof(V1Endpoints));

        if (ingressClass is not null)
        {
            cache.Update(WatchEventType.Added, ingressClass);
        }

        var kubeObjects = await Yaml.LoadAllFromFileAsync(Path.Combine("testassets", name, "ingress.yaml"), typeMap).ConfigureAwait(false);

        foreach (var obj in kubeObjects)
        {
            if (obj is V1Ingress ingress)
            {
                cache.Update(WatchEventType.Added, ingress);
            }
            else if (obj is V1Service service)
            {
                cache.Update(WatchEventType.Added, service);
            }
            else if (obj is V1Endpoints endpoints)
            {
                cache.Update(WatchEventType.Added, endpoints);
            }
        }

        return(cache);
    }
Exemple #10
0
        public async Task <IActionResult> CreateServiceAsync
            ([FromBody] MTAServiceModel serviceBody,
            [FromRoute] string serviceName,
            [FromRoute] string tenantName,
            [FromRoute] string groupName)
        {
            var path         = string.Concat(GetTemplatesPath(), "/template-svc.yaml");
            var servicesList = await Yaml.LoadAllFromFileAsync(path);

            var yamlBody          = servicesList[0] as V1Service;
            var serviceController = new MTAServiceController(serviceName, tenantName, groupName);
            var respondeModel     = await serviceController.CreateServiceAsync
                                        (_k8sClient, yamlBody, serviceBody);

            if (respondeModel.Item2 != null)
            {
                return(BadRequest(respondeModel.Item2));
            }

            return(Created(Url.RouteUrl("CreateService", new { serviceName, groupName }),
                           respondeModel.Item1));
        }
Exemple #11
0
        public async Task <IActionResult> CreateDeploymentAsync
            ([FromBody] MTADeployModel deployBody,
            [FromRoute] string deployName,
            [FromRoute] string tenantName,
            [FromRoute] string groupName)
        {
            var path            = string.Concat(GetTemplatesPath(), "/template-deploy.yaml");
            var deploymentsList = await Yaml.LoadAllFromFileAsync(path);

            var yamlBody         = deploymentsList[0] as V1Deployment;
            var deployController = new MTADeployController(deployName, tenantName, groupName);
            var respondeModel    = await deployController.CreateDeploymentAsync
                                       (_k8sClient, yamlBody, deployBody);

            if (respondeModel.Item2 != null)
            {
                return(BadRequest(respondeModel.Item2));
            }

            return(Created(Url.RouteUrl("CreateDeployment", new { deployName, groupName }),
                           respondeModel.Item1));
        }
Exemple #12
0
        public async Task <IActionResult> CreateHPAAsync
            ([FromBody] MTAHPAModel hpaBody,
            [FromRoute] string hpaName,
            [FromRoute] string tenantName,
            [FromRoute] string groupName)
        {
            var path    = string.Concat(GetTemplatesPath(), "/template-hpa.yaml");
            var hpaList = await Yaml.LoadAllFromFileAsync(path);

            var yamlBody      = hpaList[0] as V1HorizontalPodAutoscaler;
            var deployName    = hpaBody.DeploymentName;
            var hpaController = new MTAHPAController(hpaName, deployName, tenantName, groupName);
            var respondeModel = await hpaController.CreateHPAAsync
                                    (_k8sClient, yamlBody, hpaBody);

            if (respondeModel.Item2 != null)
            {
                return(BadRequest(respondeModel.Item2));
            }

            return(Created(Url.RouteUrl("CreateService", new { hpaName, groupName }),
                           respondeModel.Item1));
        }
        static async Task Main(string[] args)
        {
            if (AnsiConsole.Capabilities.SupportLinks)
            {
                AnsiConsole.MarkupLine(
                    $"[link=https://github.com/bovrhovn/]Demo for working with Kubernetes[/]!");
            }

            HorizontalRule("Connecting to cluster using default load via .kube/config and list namespaces");

            var         config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            IKubernetes client = new Kubernetes(config);

            System.Console.WriteLine($"Listening to master at {config.Host}");

            var namespaces = await client.ListNamespaceAsync();

            foreach (var ns in namespaces.Items)
            {
                System.Console.WriteLine($"{ns.Metadata.Uid} : {ns.Metadata.Name}");
            }

            System.Console.Read(); //break for continue

            HorizontalRule("List pods in namespace - app");

            var listPodInNamespace = await client.ListNamespacedPodAsync("app");

            var table = new Table();

            table.Border(TableBorder.Rounded);

            table.AddColumn("Pod name");
            table.AddColumn(new TableColumn("Labels").Centered());

            foreach (var currentPod in listPodInNamespace.Items)
            {
                string labels = string.Empty;
                foreach (var labelPair in currentPod.Metadata.Labels)
                {
                    labels += $" {labelPair.Key}:{labelPair.Value} ";
                }

                table.AddRow(currentPod.Metadata.Name, labels);
            }

            AnsiConsole.Render(table);

            System.Console.Read(); //break for continue

            HorizontalRule("Creating namespace and pod");
            var namespaceNameForTest = "test";
            var newNamespace         = new V1Namespace {
                Metadata = new V1ObjectMeta {
                    Name = namespaceNameForTest
                }
            };

            var resultNamespaceCreated = await client.CreateNamespaceAsync(newNamespace);

            System.Console.WriteLine(
                $"Namespace {resultNamespaceCreated.Metadata.Name} has been created and it is in {resultNamespaceCreated.Status.Phase} state");

            var pod = new V1Pod
            {
                Metadata = new V1ObjectMeta {
                    Name = "nginx-test"
                },
                Spec = new V1PodSpec
                {
                    Containers = new List <V1Container>
                    {
                        new V1Container
                        {
                            Image = "nginx:1.7.9",
                            Name  = "image-nginx-test",
                            Ports = new List <V1ContainerPort>
                            {
                                new V1ContainerPort {
                                    ContainerPort = 80
                                }
                            }
                        }
                    }
                }
            };

            var createdPodInNamespaceTest = await client.CreateNamespacedPodAsync(pod, namespaceNameForTest);

            System.Console.WriteLine($"Pod in namespace {namespaceNameForTest} has been created with state {createdPodInNamespaceTest.Status.Phase}");

            System.Console.Read(); //break for continue

            HorizontalRule("Exec into pod");

            var webSocket =
                await client.WebSocketNamespacedPodExecAsync(pod.Metadata.Name,
                                                             namespaceNameForTest, "env", pod.Spec.Containers[0].Name);

            var demux = new StreamDemuxer(webSocket);

            demux.Start();

            var buff   = new byte[4096];
            var stream = demux.GetStream(1, 1);
            await stream.ReadAsync(buff, 0, 4096);

            var str = System.Text.Encoding.Default.GetString(buff);

            System.Console.WriteLine(str); //ouput ls command

            System.Console.Read();         //break for continue

            HorizontalRule($"Delete namespace {namespaceNameForTest}");

            var status = await client.DeleteNamespaceAsync(namespaceNameForTest, new V1DeleteOptions());

            System.Console.WriteLine($"Namespace {namespaceNameForTest} has been deleted - status {status.Message} - {status.Status}");

            System.Console.Read(); //break for continue

            HorizontalRule("Load objects from yaml file");

            var typeMap = new Dictionary <string, Type>
            {
                { "v1/Pod", typeof(V1Pod) },
                { "v1/Service", typeof(V1Service) },
                { "apps/v1/Deployment", typeof(V1Deployment) }
            };

            string yamlPath = Path.Join(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location), "my.yaml");
            var    objects  = await Yaml.LoadAllFromFileAsync(yamlPath, typeMap);

            foreach (var obj in objects)
            {
                System.Console.WriteLine(obj);
            }

            System.Console.Read(); //stop and press key to continue

            HorizontalRule("Watching pods - watch pods");

            var podlistResp = client.ListNamespacedPodWithHttpMessagesAsync("default", watch: true);

            using (podlistResp.Watch <V1Pod, V1PodList>((type, item) =>
            {
                System.Console.WriteLine("==on watch event==");
                System.Console.WriteLine(type);
                System.Console.WriteLine(item.Metadata.Name);
                System.Console.WriteLine("==on watch event==");
            }))
            {
                System.Console.WriteLine("press ctrl + c to stop watching");

                var ctrlc = new ManualResetEventSlim(false);
                System.Console.CancelKeyPress += (sender, eventArgs) => ctrlc.Set();
                ctrlc.Wait();
            }

            System.Console.Read(); //press any key to continue
        }