public void CreatedFromPreLoadedConfig()
        {
            var k8sConfig = KubernetesClientConfiguration.LoadKubeConfig(new FileInfo("assets/kubeconfig.yml"), useRelativePaths: false);
            var cfg       = KubernetesClientConfiguration.BuildConfigFromConfigObject(k8sConfig);

            Assert.NotNull(cfg.Host);
        }
Exemplo n.º 2
0
        public IIoTK8SClient(string kubeConfigContent)
        {
            _k8sConfiguration       = Yaml.LoadFromString <K8SConfiguration>(kubeConfigContent);
            _k8sClientConfiguration = KubernetesClientConfiguration
                                      .BuildConfigFromConfigObject(_k8sConfiguration);

            _k8sClient = new Kubernetes(_k8sClientConfiguration);
        }
Exemplo n.º 3
0
        public virtual async Task <Kubernetes> Get()
        {
            var configFile = await _kubeConfigLoader.Get();

            configFile.CurrentContext = await _currentContext.Get();

            var config = KubernetesClientConfiguration.BuildConfigFromConfigObject(configFile);

            return(new Kubernetes(config));
        }
Exemplo n.º 4
0
    private IKubernetes GetKubernetesClient(K8SConfiguration kubernetesConfiguration)
    {
        if (kubernetesConfiguration is null)
        {
            throw new ArgumentNullException(nameof(kubernetesConfiguration));
        }

        var clientConfiguration = KubernetesClientConfiguration.BuildConfigFromConfigObject(kubernetesConfiguration);

        return(new KubernetesClient(clientConfiguration));
        //return new KubernetesClient(clientConfiguration, FlurlHttp.GlobalSettings.HttpClientFactory.CreateHttpClient(), false);
    }
Exemplo n.º 5
0
        /// <summary>
        /// Constructor of IIoTK8SClient.
        /// </summary>
        /// <param name="kubeConfigContent"></param>
        public IIoTK8SClient(string kubeConfigContent)
        {
            if (string.IsNullOrEmpty(kubeConfigContent))
            {
                throw new ArgumentNullException(nameof(kubeConfigContent));
            }

            _k8sConfiguration       = Yaml.LoadFromString <K8SConfiguration>(kubeConfigContent);
            _k8sClientConfiguration = KubernetesClientConfiguration
                                      .BuildConfigFromConfigObject(_k8sConfiguration);

            _k8sClient = new Kubernetes(_k8sClientConfiguration);
        }
Exemplo n.º 6
0
        public void ExternalToken()
        {
            const string token
                = "testingtoken";
            const string name
                = "testing_irrelevant";

            using (var server
                       = new MockKubeApiServer(testOutput, cxt =>
            {
                var header
                    = cxt.Request.Headers["Authorization"].FirstOrDefault();

                var expect
                    = new AuthenticationHeaderValue("Bearer", token).ToString();

                if (header != expect)
                {
                    cxt.Response.StatusCode
                        = (int)HttpStatusCode.Unauthorized;
                    return(Task.FromResult(false));
                }

                return(Task.FromResult(true));
            }))
            {
                {
                    var kubernetesConfig
                        = GetK8SConfiguration(server.Uri.ToString(), token, name);
                    var clientConfig
                        = KubernetesClientConfiguration.BuildConfigFromConfigObject(kubernetesConfig, name);
                    var client
                        = new Kubernetes(clientConfig);
                    var listTask
                        = ExecuteListPods(client);
                    Assert.True(listTask.Response.IsSuccessStatusCode);
                    Assert.Equal(1, listTask.Body.Items.Count);
                }
                {
                    var kubernetesConfig
                        = GetK8SConfiguration(server.Uri.ToString(), "wrong token", name);
                    var clientConfig
                        = KubernetesClientConfiguration.BuildConfigFromConfigObject(kubernetesConfig, name);
                    var client
                        = new Kubernetes(clientConfig);
                    var listTask
                        = ExecuteListPods(client);
                    Assert.Equal(HttpStatusCode.Unauthorized, listTask.Response.StatusCode);
                }
            }
        }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();


            try
            {
                KubernetesClientConfiguration.LoadKubeConfig();
            }
            catch (Exception e)
            {
                _hasStartupFailed      = true;
                _startupFailureMessage = e.ToString();
            }

            if (_hasStartupFailed)
            {
                return;
            }

            services.AddTransient(provider =>
            {
                var configFile = KubernetesClientConfiguration.LoadKubeConfig();

                configFile.CurrentContext =
                    InMemoryUserPreferencesStore.CurrentContextName ?? configFile.CurrentContext;
                var config = KubernetesClientConfiguration.BuildConfigFromConfigObject(configFile);

                return(new Kubernetes(config));
            });
            services.AddSingleton <KubernetesHelper>();
            services.AddSingleton <EntityReferenceUrlBuilder>();
            services.AddSingleton <KubernetesCommandLineBuilder>();
            services.AddBlazoredSessionStorage();
            services.AddClipboard();

            services.AddBootstrapCss();
            var fusion = services.AddFusion();

            services.AddSingleton(c => new UpdateDelayer.Options()
            {
                // Default update delayer options
                Delay = TimeSpan.FromSeconds(0.1),
            });
            fusion.AddComputeService <IKubeConfigLoader, KubeConfigLoader>();
            RegisterFusionDb(fusion);
            services.AttributeBased().AddServicesFrom(Assembly.GetExecutingAssembly());
        }
        public void CreatedFromIConfiguration()
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("assets/app.settings.json")
                         .Build();

            var serviceProvider = new ServiceCollection()
                                  .AddSingleton(typeof(IConfiguration), config)
                                  .AddSingleton <IK8SConfiguration, K8SConfigurationOverload>()
                                  .BuildServiceProvider();

            var cfg = KubernetesClientConfiguration.BuildConfigFromConfigObject(serviceProvider.GetService <IK8SConfiguration>());

            Assert.NotNull(cfg.Host);
        }
Exemplo n.º 9
0
    public static async Task <KubernetesClientConfiguration> CreateClientConfigAsync(this IKubernetes kubernetes, V1ServiceAccount serviceAccount)
    {
        if (kubernetes is null)
        {
            throw new ArgumentNullException(nameof(kubernetes));
        }

        if (serviceAccount is null)
        {
            throw new ArgumentNullException(nameof(serviceAccount));
        }

        var clusterConfig = await kubernetes
                            .CreateClusterConfigAsync(serviceAccount)
                            .ConfigureAwait(false);

        return(KubernetesClientConfiguration.BuildConfigFromConfigObject(clusterConfig));
    }
Exemplo n.º 10
0
        static async Task <List <Pod> > GetAllPods(string[] excludeClusters, int timeoutSeconds)
        {
            var config   = KubernetesClientConfiguration.LoadKubeConfig();
            var clusters = new List <string>();

            foreach (var context in config.Contexts.OrderBy(c => c.Name))
            {
                if (excludeClusters.Any(e => context.Name.Contains(e)))
                {
                    Console.WriteLine($"Excluding cluster: '{context.Name}'");
                    continue;
                }
                clusters.Add(context.Name);
            }

            var allpods = new List <Task <List <Pod> > >();

            foreach (var cluster in clusters)
            {
                KubernetesClientConfiguration clientConfig;
                try
                {
                    clientConfig = KubernetesClientConfiguration.BuildConfigFromConfigObject(config, cluster);
                }
                catch (KubeConfigException ex)
                {
                    Console.WriteLine($"Ignoring cluster (invalid config): '{cluster}': {ex.Message}");
                    continue;
                }

                Console.WriteLine($"Connecting to: {clientConfig.Host} ({cluster})");
                IKubernetes client = new Kubernetes(clientConfig);

                allpods.Add(GetPods(client, cluster, timeoutSeconds));
            }

            await Task.WhenAll(allpods);

            return(allpods.SelectMany(t => t.Result).ToList());
        }
Exemplo n.º 11
0
        public ITestClusterHost Build()
        {
            if (string.IsNullOrEmpty(ServerUrl))
            {
                ServerUrl = $"http://{IPAddress.Loopback}:{AvailablePort()}";
            }

            _hostBuilder.ConfigureWebHostDefaults(web =>
            {
                web
                .UseStartup <TestClusterStartup>()
                .UseUrls(ServerUrl);
            });

            var host = _hostBuilder.Build();

            var kubeConfig = new K8SConfiguration
            {
                ApiVersion     = "v1",
                Kind           = "Config",
                CurrentContext = "test-context",
                Contexts       = new[]
                {
                    new Context
                    {
                        Name           = "test-context",
                        ContextDetails = new ContextDetails
                        {
                            Namespace = "test-namespace",
                            Cluster   = "test-cluster",
                            User      = "******",
                        }
                    }
                },
                Clusters = new[]
                {
                    new Cluster
                    {
                        Name            = "test-cluster",
                        ClusterEndpoint = new ClusterEndpoint
                        {
                            Server = ServerUrl,
                        }
                    }
                },
                Users = new[]
                {
                    new User
                    {
                        Name            = "test-user",
                        UserCredentials = new UserCredentials
                        {
                            Token = "test-token",
                        }
                    }
                },
            };

            var clientConfiguration = KubernetesClientConfiguration.BuildConfigFromConfigObject(kubeConfig);

            var client = new k8s.Kubernetes(clientConfiguration);

            return(new TestClusterHost(host, kubeConfig, client));
        }
Exemplo n.º 12
0
        public void ExternalCertificate()
        {
            const string name = "testing_irrelevant";

            var serverCertificateData = Convert.FromBase64String(File.ReadAllText("assets/apiserver-pfx-data.txt"));

            var clientCertificateKeyData = Convert.FromBase64String(File.ReadAllText("assets/client-key-data.txt"));
            var clientCertificateData    = Convert.FromBase64String(File.ReadAllText("assets/client-certificate-data.txt"));

            X509Certificate2 serverCertificate = null;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                using (var serverCertificateStream = new MemoryStream(serverCertificateData))
                {
                    serverCertificate = OpenCertificateStore(serverCertificateStream);
                }
            }
            else
            {
                serverCertificate = new X509Certificate2(serverCertificateData, "");
            }

            var clientCertificate = new X509Certificate2(clientCertificateData, "");

            var clientCertificateValidationCalled = false;

            using (var server = new MockKubeApiServer(testOutput, listenConfigure: options =>
            {
                options.UseHttps(new HttpsConnectionAdapterOptions
                {
                    ServerCertificate = serverCertificate,
                    ClientCertificateMode = ClientCertificateMode.RequireCertificate,
                    ClientCertificateValidation = (certificate, chain, valid) =>
                    {
                        clientCertificateValidationCalled = true;
                        return(clientCertificate.Equals(certificate));
                    },
                });
            }))
            {
                {
                    var clientCertificateText    = Encoding.ASCII.GetString(clientCertificateData).Replace("\n", "\\n");
                    var clientCertificateKeyText = Encoding.ASCII.GetString(clientCertificateKeyData).Replace("\n", "\\n");
                    var responseJson             = $"{{\"apiVersion\":\"testingversion\",\"status\":{{\"clientCertificateData\":\"{clientCertificateText}\",\"clientKeyData\":\"{clientCertificateKeyText}\"}}}}";
                    var kubernetesConfig         = GetK8SConfiguration(server.Uri.ToString(), responseJson, name);
                    var clientConfig             = KubernetesClientConfiguration.BuildConfigFromConfigObject(kubernetesConfig, name);
                    var client   = new Kubernetes(clientConfig);
                    var listTask = ExecuteListPods(client);
                    Assert.True(listTask.Response.IsSuccessStatusCode);
                    Assert.Equal(1, listTask.Body.Items.Count);
                }

                {
                    var clientCertificateText    = File.ReadAllText("assets/client.crt").Replace("\n", "\\n");
                    var clientCertificateKeyText = File.ReadAllText("assets/client.key").Replace("\n", "\\n");
                    var responseJson             = $"{{\"apiVersion\":\"testingversion\",\"status\":{{\"clientCertificateData\":\"{clientCertificateText}\",\"clientKeyData\":\"{clientCertificateKeyText}\"}}}}";
                    var kubernetesConfig         = GetK8SConfiguration(server.Uri.ToString(), responseJson, name);
                    var clientConfig             = KubernetesClientConfiguration.BuildConfigFromConfigObject(kubernetesConfig, name);
                    var client = new Kubernetes(clientConfig);
                    Assert.ThrowsAny <Exception>(() => ExecuteListPods(client));
                    Assert.True(clientCertificateValidationCalled);
                }
            }
        }
Exemplo n.º 13
0
        private KubernetesClientConfiguration BuildEksConfiguration(KubernetesConnectionDetails connectionDetails)
        {
            var processStartOptions = new ProcessStartInfo()
            {
                Arguments              = $"token -i {connectionDetails.Eks.Name}",
                FileName               = "aws-iam-authenticator",
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                Environment            =
                {
                    new KeyValuePair <string, string>("AWS_ACCESS_KEY_ID",     connectionDetails.Eks.AccessKey),
                    new KeyValuePair <string, string>("AWS_SECRET_ACCESS_KEY", connectionDetails.Eks.SecretKey),
                    new KeyValuePair <string, string>("AWS_DEFAULT_REGION",    connectionDetails.Eks.Region)
                }
            };
            var processInfo = Process.Start(processStartOptions);

            processInfo.WaitForExit();
            Debug.Assert(processInfo.ExitCode == 0);


            var jsonOutput = processInfo.StandardOutput.ReadToEnd();
            var response   = JsonConvert.DeserializeObject <K8sAuthTokenResponse>(jsonOutput);


            var c = new K8SConfiguration
            {
                CurrentContext = connectionDetails.Eks.Name,
                Clusters       = new[]
                {
                    new Cluster
                    {
                        Name            = connectionDetails.Eks.Name,
                        ClusterEndpoint = new ClusterEndpoint
                        {
                            CertificateAuthorityData = connectionDetails.Eks.CA,
                            Server = connectionDetails.Eks.Endpoint
                        }
                    }
                },
                Contexts = new[]
                {
                    new Context()
                    {
                        Name           = connectionDetails.Eks.Name,
                        ContextDetails = new ContextDetails()
                        {
                            Cluster = connectionDetails.Eks.Name,
                            User    = "******"
                        }
                    }
                },
                Users = new[]
                {
                    new User
                    {
                        Name            = "user",
                        UserCredentials = new UserCredentials
                        {
                            Token = response.Status.Token
                        }
                    }
                }
            };

            return(KubernetesClientConfiguration.BuildConfigFromConfigObject(c));
        }