Beispiel #1
0
        public ActionResult <IEnumerable <string> > CreateNamespace()
        {
            var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            var client = new Kubernetes(config);
            var ns     = new V1Namespace
            {
                Metadata = new V1ObjectMeta
                {
                    Name = "test"
                }
            };
            var result = client.CreateNamespace(ns);

            return(new string[] { "Operation", "Namespace Created" });
        }
        public K8sService(InstrumentationClient instrumentationClient)
        {
            var configFilePath = System.Environment.GetEnvironmentVariable("K8S_CONFIG_FILEPATH");

            if (!string.IsNullOrWhiteSpace(configFilePath))
            {
                k8s = new Kubernetes(KubernetesClientConfiguration.BuildConfigFromConfigFile(configFilePath));
            }
            else
            {
                k8s = new Kubernetes(KubernetesClientConfiguration.BuildConfigFromConfigFile());
            }

            this.Logger = instrumentationClient;
        }
        public void ConnectOnClusterNative()
        {
            var         kubeconfig = new FileInfo("./config");
            var         config     = KubernetesClientConfiguration.BuildConfigFromConfigFile(kubeconfig);
            IKubernetes client     = new k8s.Kubernetes(config);

            var list = client.ListNamespacedPod("kube-system");

            Assert.AreEqual(list.Items.Count > 0, true);

            foreach (var item in list.Items)
            {
                Trace.WriteLine(item.Metadata.Name);
            }
        }
Beispiel #4
0
        public ActionResult <IEnumerable <string> > deleteNamespace()
        {
            var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            var client = new Kubernetes(config);
            var ns     = new V1Namespace
            {
                Metadata = new V1ObjectMeta
                {
                    Name = "test"
                }
            };
            var status = client.DeleteNamespace(new V1DeleteOptions(), ns.Metadata.Name);

            return(new string[] { "Operation", "Namespace Deleted" });
        }
Beispiel #5
0
        public IActionResult K8Service()
        {
            _logger.LogInformation("be4 the K8s Connetion");
#if RELEASE
            var config = KubernetesClientConfiguration.InClusterConfig();
#else
            var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(@"G:\aspcore\MVCCoreDocker\MVCCoreDocker\MVCCoreDocker\bin\Debug\net5.0\config");
#endif
            IKubernetes client = new Kubernetes(config);
            _logger.LogInformation("after the K8s Connetion");

            var list = client.ListServiceForAllNamespaces();
            _logger.LogInformation("after the K8s Pod Call");

            return(View());
        }
        public PodsController(IConfiguration config)
        {
            // Reading configuration to know if running inside a cluster or in local mode.
            var useKubeConfig = bool.Parse(config["UseKubeConfig"]);

            if (!useKubeConfig)
            {
                // Running inside a k8s cluser
                k8sConfig = KubernetesClientConfiguration.InClusterConfig();
            }
            else
            {
                // Running on dev machine
                k8sConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            }
        }
Beispiel #7
0
        private static async Task Main(string[] args)
        {
            var config  = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            var generic = new GenericClient(config, "", "v1", "nodes");
            var node    = await generic.ReadAsync <V1Node>("kube0").ConfigureAwait(false);

            Console.WriteLine(node.Metadata.Name);

            var genericPods = new GenericClient(config, "", "v1", "pods");
            var pods        = await genericPods.ListNamespacedAsync <V1PodList>("default").ConfigureAwait(false);

            foreach (var pod in pods.Items)
            {
                Console.WriteLine(pod.Metadata.Name);
            }
        }
Beispiel #8
0
        public static void DeleteCompute([ActivityTrigger] Compute compute, ExecutionContext context, ILogger log)
        {
            log.LogInformation($"Deleting compute {compute.Key}");

            var name = compute.Key;

            var homeDirectory = context.FunctionAppDirectory;

            var config
                = KubernetesClientConfiguration.BuildConfigFromConfigFile(Path.Combine(homeDirectory, "kubeconfig.json"));
            var client = new Kubernetes(config);

            ///TODO: Exception condition handling
            var deleteStatus = client.DeleteNamespacedDeployment(name, "default");

            deleteStatus = client.DeleteNamespacedService(name, "default");
        }
        static void Main(string[] args)
        {
            // load the k8s config from $HOME/.kube/config if its available
            KubernetesClientConfiguration kubeConfig;
            string kubeConfigPath = Path.Combine(Environment.GetFolderPath(SpecialFolder.UserProfile), ".kube", "config");

            if (File.Exists(kubeConfigPath))
            {
                kubeConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            }
            else
            {
                kubeConfig = KubernetesClientConfiguration.InClusterConfig();
            }

            new Server().Start(new EdgeProvider(new Kubernetes(kubeConfig)));
        }
Beispiel #10
0
        public async Task WatcherTest()
        {
            var cancellationTokenSource = new CancellationTokenSource();

            var config  = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            var factory = new NamespacedResourceWatcherFactory <ArgoApplicationResource>(
                config,
                new[] { new Y(GetLogger()) }
                );

            await factory.Start("argo", cancellationTokenSource.Token);

            Thread.Sleep(TimeSpan.FromMinutes(10));

            cancellationTokenSource.Cancel();
            cancellationTokenSource.Dispose();
        }
Beispiel #11
0
        public PodsController(IConfiguration config)
        {
            var useKubeConfig = bool.Parse(config["UseKubeConfig"]);

            if (!useKubeConfig)
            {
                k8sConfig = KubernetesClientConfiguration.InClusterConfig();
            }
            else
            {
                k8sConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            }

            this.endpoint = config["eventGridEndPoint"].ToString();

            this.restClient = RestClient(config);
        }
Beispiel #12
0
            public SampleAppsFixture()
            {
                BuildNumber = Environment.GetEnvironmentVariable(BUILD_NUMBER_VAR) ?? Guid.NewGuid().ToString();
                BuildNumber = BuildNumber.Replace('.', '_'); // Dots are invalid in Kubernetes service names

                var storageKey = Environment.GetEnvironmentVariable(STORAGE_KEY_VAR);

                Console.WriteLine("Using storage key \"{0}...\" from environment variable \"{1}\"", storageKey.Substring(0, 4), STORAGE_KEY_VAR);

                FolderName = "SampleApps-" + BuildNumber;

                fileShare = CloudStorageAccount.Parse($"DefaultEndpointsProtocol=https;AccountName={STORAGE_ACCOUNT_NAME};AccountKey={storageKey};EndpointSuffix=core.windows.net")
                            .CreateCloudFileClient()
                            .GetShareReference(STORAGE_SHARE_NAME);

                UploadToFileShare(fileShare, FolderName);

                KubernetesClientConfiguration config;
                string kubeConfig = Environment.GetEnvironmentVariable(KUBECONFIG_VAR);

                if (string.IsNullOrEmpty(kubeConfig))
                {
                    config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
                }
                else
                {
                    byte[] configByteArray = System.Text.Encoding.UTF8.GetBytes(kubeConfig);
                    using (var stream = new MemoryStream(configByteArray))
                    {
                        config = KubernetesClientConfiguration.BuildConfigFromConfigFile(stream);
                    }
                }
                Client = new Kubernetes(config);

                // Create a PV for our Azure File share and a corresponding claim if they don't already exist
                // If these fail, make sure that they don't already exist in the cluster: `kubectl delete -n default pvc,pv --all`
                storage      = Client.CreatePersistentVolume(Specs.BuildVolume.GetSpec(VOLUME_NAME, STORAGE_REQUESTED_CAPACITY, STORAGE_SHARE_NAME));
                storageClaim = Client.CreateNamespacedPersistentVolumeClaim(Specs.BuildVolumeClaim.GetSpec(STORAGE_REQUESTED_CAPACITY), NAMESPACE);
                Console.WriteLine("Created PersistentVolume and corresponding PersistentVolumeClaim");

                // Create the build pod
                var podSpec = Specs.BuildPod.GetSpec(BUILD_POD_NAME, VOLUME_NAME, storageClaim.Metadata.Name);

                BuildPod = k8sHelpers.CreatePodAndWait(Client, podSpec, NAMESPACE, k8sHelpers.IsPodRunning).Result;
                Console.WriteLine("Build pod is up & running");
            }
Beispiel #13
0
        public WatchedResourceTests()
        {
            var config    = Config.Configuration();
            var k8SConfig = config.GetSection("K8s").Get <K8SConfig>();

            var c = KubernetesClientConfiguration.BuildConfigFromConfigFile(k8SConfig.KubeConfig);

            _k8S = new Kubernetes(c);

            using var loggerFactory = LoggerFactory.Create(builder =>
                                                           builder.AddSimpleConsole(options =>
            {
                options.IncludeScopes   = true;
                options.SingleLine      = true;
                options.TimestampFormat = "hh:mm:ss ";
            }).SetMinimumLevel(LogLevel.Debug));
        }
Beispiel #14
0
        public async Task <IActionResult> K8s()
        {
            _logger.LogInformation("be4 the K8s Connetion");
#if RELEASE
            var config = KubernetesClientConfiguration.InClusterConfig();
#else
            var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(@"G:\aspcore\MVCCoreDocker\MVCCoreDocker\MVCCoreDocker\bin\Debug\net5.0\config");
#endif
            IKubernetes client = new Kubernetes(config);
            _logger.LogInformation("after the K8s Connetion");

            var list = client.ListNamespacedPod("default");
            _logger.LogInformation("after the K8s Pod Call");

            List <k8sClass> k8 = new List <k8sClass>();

            string ip = null;
            foreach (var item in list.Items)
            {
                k8sClass k = new k8sClass();
                k.PodName = item.Metadata.Name + " " + item.Metadata.GenerateName + "  " + "PodIP: " + item.Status.PodIP;
                k8.Add(k);
                ip = item.Status.PodIP;
                //Console.WriteLine(item.Metadata.Name);
            }

            if (list.Items.Count == 0)
            {
                // Console.WriteLine("Empty!");
            }

            // need to make a nginx pod
            Uri myUri = new Uri("http://" + ip);

            HttpClient clienthttp = new HttpClient();

            clienthttp.BaseAddress = myUri;
            clienthttp.DefaultRequestHeaders.Accept.Clear();
            clienthttp.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            var st = await clienthttp.GetAsync(myUri);

            ViewData["k8"] = k8;
            return(View());
        }
Beispiel #15
0
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "kube/status")] HttpRequest req,
                                        TraceWriter log, ExecutionContext context)
        {
            string configFile = Path.Combine(context.FunctionAppDirectory, configPath);

            FileInfo file = new FileInfo(configFile);

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

            if (client != null)
            {
                return(new OkObjectResult("Kube online"));
            }

            return(new OkObjectResult("Kube offline"));
        }
        private Kubernetes GetKubernetes()
        {
            KubernetesClientConfiguration config;

            // determine where to load config from
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_HOST")))
            {
                config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            }
            else
            {
                config = KubernetesClientConfiguration.InClusterConfig();
            }

            // setup the kubernetes client
            return(new Kubernetes(config));
        }
Beispiel #17
0
        public virtual IActionResult ServersDelete(string servername)
        {
            try
            {
                var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();

                IKubernetes client = new Kubernetes(config);

                var v1Status = client.DeleteNamespacedDeployment(body: new V1DeleteOptions(apiVersion: "apps/v1"), name: servername, namespaceParameter: "default");

                return(new ObjectResult(v1Status));
            }
            catch (Exception ex)
            {
                return(new ObjectResult(ex));
            }
        }
Beispiel #18
0
        private static List <Server> GetServers()
        {
            List <Server> servers = new List <Server>();

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


            var listDeploy   = client.ListNamespacedDeployment("default");
            var listServices = client.ListNamespacedService("default");



            foreach (var deploy in listDeploy.Items)
            {
                string ipExternal = "";


                var service = listServices.Items.Where(a => a.Metadata.Name == deploy.Metadata.Name).FirstOrDefault();

                if (service != null)
                {
                    if (service.Status.LoadBalancer != null && service.Status.LoadBalancer.Ingress != null && service.Status.LoadBalancer.Ingress.Count() > 0)
                    {
                        ipExternal = service.Status.LoadBalancer.Ingress.First().Ip;
                    }


                    string exampleJson = null;
                    exampleJson = "{\n  \"endpoints\" : {\n    \"minecraft\" : \"minecraft\",\n    \"rcon\" : \"rcon\"\n  },\n  \"name\" : \"name\"\n}";

                    var server = exampleJson != null
                    ? JsonConvert.DeserializeObject <Server>(exampleJson)
                    : default(Server);

                    server.Name = deploy.Metadata.Name;
                    server.Endpoints.Minecraft = ipExternal + ":25565";
                    server.Endpoints.Rcon      = ipExternal + ":25575";

                    servers.Add(server);
                }
            }

            return(servers);
        }
Beispiel #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);


            if (
                string.IsNullOrWhiteSpace(Configuration["KUBERNETES_SERVICE_HOST"]) == false &&
                string.IsNullOrWhiteSpace(Configuration["KUBERNETES_SERVICE_PORT"]) == false
                )
            {
                services.AddTransient <IKubernetes>(serviceProvider =>
                                                    new Kubernetes(KubernetesClientConfiguration.InClusterConfig()));
            }
            else
            {
                services.AddTransient <IKubernetes>(serviceProvider =>
                                                    new Kubernetes(KubernetesClientConfiguration.BuildConfigFromConfigFile()));
            }


            services = AddPersistenceRepository(services);

            services.AddTransient <IConfigMapService, ConfigMapService>();
            services.AddTransient <IAwsAuthConfigMapRepository, AwsAuthConfigMapRepository>();
            services.AddTransient <IAddRoleRequestValidator, AddRoleRequestValidator>();
            services.AddTransient <IAddNamespaceRequestValidator, AddNamespaceRequestValidator>();
            services.AddTransient <INamespaceRespoitory, NamespaceRespoitory>();
            services.AddTransient <IRoleRepository, RoleRepository>();
            services.AddTransient <IRoleBindingRepository, RoleBindingRepository>();
            services.AddTransient <IKubernetesWrapper, KubernetesWrapper>();

            // Event handlers
            services.AddTransient <IEventHandler <CapabilityRegisteredEvent>, CapabilityRegisteredEventHandler>();

            services.AddHostedService <MetricHostedService>();

            services.AddHealthChecks()
            .AddCheck("self", () => HealthCheckResult.Healthy())
            .AddCheck <S3BucketHealthCheck>("S3 bucket");


            ConfigureDomainEvents(services);

            services.AddHostedService <KafkaConsumerHostedService>();
        }
        public Controller(T crd, IOperationHandler <T> handler, string k8sNamespace = "")
        {
            KubernetesClientConfiguration config;

            if (KubernetesClientConfiguration.IsInCluster())
            {
                config = KubernetesClientConfiguration.InClusterConfig();
            }
            else
            {
                config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            }

            Kubernetes     = new Kubernetes(config);
            m_k8sNamespace = k8sNamespace;
            m_crd          = crd;
            m_handler      = handler;
        }
        public async Task <string> GetClusterNameAsync()
        {
            try
            {
                logger.LogInformation("Getting cluster information - client - GetClusterNameAsync");
                var stream = await storageWorker.DownloadFileAsync(kubekOptions.ConfigFileName);

                var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(stream);
                logger.LogInformation("Getting host name from config file");
                return(config.Host);
            }
            catch (Exception e)
            {
                logger.LogError(e.Message);
            }

            return(string.Empty);
        }
 public static KubernetesClientConfiguration Configure()
 {
     if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("KUBECONFIG")))
     {
         return(KubernetesClientConfiguration.BuildConfigFromConfigFile((string)null, Environment.GetEnvironmentVariable("KUBECONFIG")));
     }
     if (File.Exists("minikube.config"))
     {
         // If you're using minikube, things can get akward if you import the root CA in the Trusted Root Certificate Authorities list
         // and re-create your cluster. Certificates issued will be rejected by Windows because the DN of the root CA doesn't change;
         // yet the certificate will have a different signature.
         return(KubernetesClientConfiguration.BuildConfigFromConfigFile((string)null, "minikube.config"));
     }
     else
     {
         throw new NotSupportedException();
     }
 }
Beispiel #23
0
        public async Task Crd_Equality_test()
        {
            var config     = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            var kubernetes = new Kubernetes(config);
            var entity1    = await kubernetes.GetNamespacedCustomResource <ArgoApplicationResource>(
                "argo",
                "azl-dev-elysium-api",
                CancellationToken.None
                );

            var entity2 = await kubernetes.GetNamespacedCustomResource <ArgoApplicationResource>(
                "argo",
                "azl-dev-elysium-api",
                CancellationToken.None
                );

            entity1.Should().BeEquivalentTo(entity2);
        }
        private V1ServiceList LoadKubernetesServices()
        {
            try
            {
                var config =
                    string.IsNullOrEmpty(Environment.GetEnvironmentVariable("KUBERNETES_PORT"))
                    ? KubernetesClientConfiguration.BuildConfigFromConfigFile()
                    : KubernetesClientConfiguration.InClusterConfig();

                var client = new Kubernetes(config);
                return(client.ListNamespacedService("default"));
            }
            catch (KubeConfigException ex)
            {
                _logger.LogError(ex, "This is not a FATAL error. It only means that K8S service discovery is off.");
                return(null);
            }
        }
Beispiel #25
0
        private static void Main(string[] args)
        {
            var         config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            IKubernetes client = new Kubernetes(config);

            Console.WriteLine("Starting Request!");

            var list = client.ListNamespacedPod("default");

            foreach (var item in list.Items)
            {
                Console.WriteLine(item.Metadata.Name);
            }
            if (list.Items.Count == 0)
            {
                Console.WriteLine("Empty!");
            }
        }
        public void DeletedConfigurationFile()
        {
            var assetFileInfo = new FileInfo("assets/kubeconfig.yml");
            var tempFileInfo  = new FileInfo(Path.GetTempFileName());

            File.Copy(assetFileInfo.FullName, tempFileInfo.FullName, /* overwrite: */ true);

            KubernetesClientConfiguration config;

            try
            {
                config = KubernetesClientConfiguration.BuildConfigFromConfigFile(tempFileInfo, useRelativePaths: false);
            }
            finally
            {
                File.Delete(tempFileInfo.FullName);
            }
        }
Beispiel #27
0
        private static KubernetesClientConfiguration LocateKubeConfig()
        {
            // Attempt to dynamically determine between in-cluster and host (debug) development...
            var serviceHost = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_HOST");
            var servicePort = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_PORT");

            // Locate from environment variables directly. Unlike IConfiguration, which could be overridden.
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("POD_NAME")) || string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("POD_NAMESPACE")))
            {
                throw new InvalidOperationException("Failed to detect current pod information. Check POD_NAME and POD_NAMESPACE environment variables.");
            }

            if (!string.IsNullOrWhiteSpace(serviceHost) && !string.IsNullOrWhiteSpace(servicePort))
            {
                return(KubernetesClientConfiguration.InClusterConfig());
            }

            return(KubernetesClientConfiguration.BuildConfigFromConfigFile());
        }
Beispiel #28
0
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "servers/{name}")] HttpRequest req, TraceWriter log, ExecutionContext context, string name)
        {
            IActionResult result = null;

            try
            {
                var config = KubernetesClientConfiguration.BuildConfigFromConfigFile($@"{context.FunctionAppDirectory}\config\config.txt");

                new Minecraft(config).Delete(req.Query["name"]);

                result = new NoContentResult();
            }
            catch (Exception e)
            {
                result = new OkObjectResult(new { name, error = e.Message });
            }

            return(result as ActionResult);
        }
        public async Task <Kubernetes> LoadBasedOnConfigurationAsync()
        {
            try
            {
                logger.LogInformation("Getting config file from Azure Storage");
                var stream = await storageWorker.DownloadFileAsync(kubekOptions.ConfigFileName);

                logger.LogInformation("Getting cluster information - client - LoadBasedOnConfigurationAsync");
                var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(stream);
                var client = new Kubernetes(config);
                return(client);
            }
            catch (Exception e)
            {
                logger.LogError(e.Message);
            }

            return(null);
        }
        public static async Task Main()
        {
            var crd = new CustomResourceDefinition()
            {
                ApiVersion = "engineerd.dev/v1alpha1",
                PluralName = "examples",
                Kind       = "Example",
                Namespace  = "kubecontroller"
            };

            var controller = new Controller <ExampleCRD>(
                new Kubernetes(KubernetesClientConfiguration.BuildConfigFromConfigFile()),
                crd,
                (WatchEventType eventType, ExampleCRD example) =>
                Console.WriteLine("Event type: {0} for {1}", eventType, example.Metadata.Name));

            var cts = new CancellationTokenSource();
            await controller.StartAsync(cts.Token).ConfigureAwait(false);
        }