コード例 #1
0
        public async Task ReturnsPodOnSuccessGettingPod()
        {
            var hostname = "kubernetes1-7d7c8ff84f-76mkq";

            Environment.SetEnvironmentVariable("HOSTNAME", hostname);
            var podListRsp             = "{\"kind\":\"PodList\",\"apiVersion\":\"v1\",\"metadata\":{\"selfLink\":\"/api/v1/namespaces/default/pods\",\"resourceVersion\":\"8541208\"},\"items\":[{\"metadata\":{\"name\":\"kubernetes1-7d7c8ff84f-76mkq\",\"generateName\":\"kubernetes1-7d7c8ff84f-\",\"namespace\":\"default\",\"selfLink\":\"/api/v1/namespaces/default/pods/kubernetes1-7d7c8ff84f-76mkq\",\"uid\":\"989ef5d3-c2bd-4179-a1ab-9925e15d202a\",\"resourceVersion\":\"8523457\",\"creationTimestamp\":\"2020-05-28T18:32:37Z\",\"labels\":{ \"app\":\"kubernetes1\"},\"annotations\":{\"buildID\":\"\"},\"ownerReferences\":[],\"containers\":[{\"name\":\"kubernetes1\",\"image\":\"kubernetes1:x01725c8eb04d86fc\",\"command\":[],\"ports\":[],\"resources\":{},\"volumeMounts\":[],\"terminationMessagePath\":\"/dev/termination-log\",\"terminationMessagePolicy\":\"File\",\"imagePullPolicy\":\"Never\"}],\"restartPolicy\":\"Always\",\"terminationGracePeriodSeconds\":0,\"dnsPolicy\":\"ClusterFirst\",\"serviceAccountName\":\"default\",\"serviceAccount\":\"default\",\"nodeName\":\"agentpool\",\"securityContext\":{},\"schedulerName\":\"default-scheduler\",\"tolerations\":[{\"key\":\"node.kubernetes.io/not-ready\",\"operator\":\"Exists\",\"effect\":\"NoExecute\",\"tolerationSeconds\":300},{\"key\":\"node.kubernetes.io/unreachable\",\"operator\":\"Exists\",\"effect\":\"NoExecute\",\"tolerationSeconds\":300}],\"priority\":0,\"enableServiceLinks\":true},\"spec\":{\"serviceAccountName\": \"default\", \"serviceAccount\": \"default\", \"nodeName\": \"agentpool\"},\"status\":{\"phase\":\"Running\",\"conditions\":[{\"type\":\"Initialized\",\"status\":\"True\",\"lastProbeTime\":null,\"lastTransitionTime\":\"2020-05-28T18:33:19Z\"},{\"type\":\"Ready\",\"status\":\"True\",\"lastProbeTime\":null,\"lastTransitionTime\":\"2020-05-28T18:33:20Z\"},{\"type\":\"ContainersReady\",\"status\":\"True\",\"lastProbeTime\":null,\"lastTransitionTime\":\"2020-05-28T18:33:20Z\"},{\"type\":\"PodScheduled\",\"status\":\"True\",\"lastProbeTime\":null,\"lastTransitionTime\":\"2020-05-28T18:32:37Z\"}],\"hostIP\":\"10.240.0.4\",\"podIP\":\"10.244.1.128\",\"podIPs\":[{\"ip\":\"10.244.1.128\"}],\"startTime\":\"2020-05-28T18:32:37Z\",\"initContainerStatuses\":[],\"containerStatuses\":[],\"qosClass\":\"BestEffort\"}}]}\n";
            var mockHttpMessageHandler = new MockHttpMessageHandler();

            mockHttpMessageHandler.Expect(HttpMethod.Get, "*").Respond(HttpStatusCode.OK, new StringContent(podListRsp));

            var appOptions = new KubernetesApplicationOptions(new ConfigurationBuilder().Build());

            using var client = new k8s.Kubernetes(new KubernetesClientConfiguration { Host = "http://localhost" }, httpClient: mockHttpMessageHandler.ToHttpClient());
            var utils = new StandardPodUtilities(appOptions, null, client);

            var getPodResult = await utils.GetCurrentPodAsync();

            Assert.NotNull(getPodResult);
            Assert.Equal("default", getPodResult.Metadata.NamespaceProperty);
            Assert.Equal(hostname, getPodResult.Metadata.Name);
            Assert.Equal("10.244.1.128", getPodResult.Status.PodIP);
            Assert.Equal("default", getPodResult.Spec.ServiceAccountName);
            Assert.Equal("agentpool", getPodResult.Spec.NodeName);
            Assert.Equal("10.240.0.4", getPodResult.Status.HostIP);
            Environment.SetEnvironmentVariable("HOSTNAME", null);
        }
コード例 #2
0
        public void AssemblyNameIsDefaultAppName()
        {
            var config = new ConfigurationBuilder().Build();

            var appInfo = new KubernetesApplicationOptions(config);

            Assert.Equal(Assembly.GetEntryAssembly().GetName().Name, appInfo.Name);
        }
コード例 #3
0
        public void Spring_Application_Name__UsedInAppName()
        {
            var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary <string, string> {
                { "spring:application:name", "springappname" }
            }).Build();

            var appInfo = new KubernetesApplicationOptions(config);

            Assert.Equal("springappname", appInfo.Name);
        }
コード例 #4
0
        public StandardPodUtilities(KubernetesApplicationOptions kubernetesApplicationOptions, ILogger logger = null, IKubernetes kubernetes = null)
        {
            if (kubernetesApplicationOptions is null)
            {
                throw new ArgumentNullException(nameof(kubernetesApplicationOptions));
            }

            _applicationOptions = kubernetesApplicationOptions;
            _logger             = logger;
            _kubernetes         = kubernetes ?? KubernetesClientHelpers.GetKubernetesClient(_applicationOptions);
        }
        /// <summary>
        /// Add configuration providers for ConfigMaps and Secrets
        /// </summary>
        /// <param name="configurationBuilder"><see cref="IConfigurationBuilder"/></param>
        /// <param name="kubernetesClientConfiguration">Kubernetes client configuration customization</param>
        /// <param name="loggerFactory"><see cref="ILoggerFactory"/> for logging within config providers</param>
        public static IConfigurationBuilder AddKubernetes(this IConfigurationBuilder configurationBuilder, Action <KubernetesClientConfiguration> kubernetesClientConfiguration = null, ILoggerFactory loggerFactory = null)
        {
            if (configurationBuilder == null)
            {
                throw new ArgumentNullException(nameof(configurationBuilder));
            }

            var logger = loggerFactory?.CreateLogger("Steeltoe.Extensions.Configuration.Kubernetes");

            var appInfo = new KubernetesApplicationOptions(configurationBuilder.Build());

            if (appInfo.Enabled && (appInfo.Config.Enabled || appInfo.Secrets.Enabled))
            {
                logger?.LogTrace("Steeltoe Kubernetes is enabled");

                var lowercaseAppName    = appInfo.Name.ToLowerInvariant();
                var lowercaseAppEnvName = (appInfo.Name + appInfo.NameEnvironmentSeparator + appInfo.EnvironmentName).ToLowerInvariant();

                var k8sClient = KubernetesClientHelpers.GetKubernetesClient(appInfo, kubernetesClientConfiguration, logger);

                if (appInfo.Config.Enabled)
                {
                    var configMapProviderLogger = loggerFactory?.CreateLogger <KubernetesConfigMapProvider>();

                    configurationBuilder
                    .Add(new KubernetesConfigMapSource(k8sClient, new KubernetesConfigSourceSettings(appInfo.NameSpace, lowercaseAppName, appInfo.Reload, configMapProviderLogger)))
                    .Add(new KubernetesConfigMapSource(k8sClient, new KubernetesConfigSourceSettings(appInfo.NameSpace, lowercaseAppEnvName, appInfo.Reload, configMapProviderLogger)));

                    foreach (var configmap in appInfo.Config.Sources)
                    {
                        configurationBuilder.Add(new KubernetesConfigMapSource(k8sClient, new KubernetesConfigSourceSettings(configmap.Namespace, configmap.Name, appInfo.Reload, configMapProviderLogger)));
                    }
                }

                if (appInfo.Secrets.Enabled)
                {
                    var secretProviderLogger = loggerFactory?.CreateLogger <KubernetesSecretProvider>();

                    configurationBuilder
                    .Add(new KubernetesSecretSource(k8sClient, new KubernetesConfigSourceSettings(appInfo.NameSpace, lowercaseAppName, appInfo.Reload, secretProviderLogger)))
                    .Add(new KubernetesSecretSource(k8sClient, new KubernetesConfigSourceSettings(appInfo.NameSpace, lowercaseAppEnvName, appInfo.Reload, secretProviderLogger)));
                    foreach (var secret in appInfo.Secrets.Sources)
                    {
                        configurationBuilder.Add(new KubernetesSecretSource(k8sClient, new KubernetesConfigSourceSettings(secret.Namespace, secret.Name, appInfo.Reload, secretProviderLogger)));
                    }
                }
            }

            return(configurationBuilder);
        }
コード例 #6
0
        public async Task ReturnsNullOnFailureToGetCurrentPod()
        {
            var mockHttpMessageHandler = new MockHttpMessageHandler();

            mockHttpMessageHandler.Expect(HttpMethod.Get, "*").Respond(HttpStatusCode.NotFound);
            var appOptions = new KubernetesApplicationOptions(new ConfigurationBuilder().Build());

            using var client = new k8s.Kubernetes(new KubernetesClientConfiguration { Host = "http://localhost" }, httpClient: mockHttpMessageHandler.ToHttpClient());
            var utils = new StandardPodUtilities(appOptions, null, client);

            var getPodResult = await utils.GetCurrentPodAsync();

            Assert.Null(getPodResult);
        }
コード例 #7
0
        public StandardPodUtilities(KubernetesApplicationOptions kubernetesApplicationOptions, ILogger logger = null, IKubernetes kubernetes = null)
        {
            if (kubernetesApplicationOptions is null)
            {
                throw new ArgumentNullException(nameof(kubernetesApplicationOptions));
            }

            if (kubernetes is null)
            {
                throw new ArgumentNullException(nameof(kubernetes), "A Kubernetes client is required");
            }

            _applicationOptions = kubernetesApplicationOptions;
            _logger             = logger;
            _kubernetes         = kubernetes;
        }
コード例 #8
0
        public void ConstructorBindsValuesFromConfig()
        {
            // arrange
            var json   = @"
            {
                ""spring"": {
                    ""application"": {
                        ""name"": ""springappname""
                    },
                    ""cloud"": {
                        ""kubernetes"": {
                            ""name"": ""testapp"",
                            ""namespace"": ""not-default"",
                            ""config"": {
                                ""enabled"": false,
                                ""paths"": [
                                    ""some/local/path""
                                ],
                                ""sources"": [
                                    {
                                        ""name"": ""testapp.extra"",
                                        ""namespace"": ""not-default1""
                                    }
                                ]
                            },
                            ""secrets"": {
                                ""enabled"": false,
                                ""sources"": [
                                    {
                                        ""name"": ""testapp.extrasecret"",
                                        ""namespace"": ""not-default2""
                                    }
                                ]
                            },
                            ""reload"": {
                                ""secrets"": true,
                                ""configmaps"": true,
                                ""mode"": ""event"",
                                ""period"": 30
                            }
                        }
                    }
                }
            }";
            var config = new ConfigurationBuilder().AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(json))).Build();

            // act
            var appInfo = new KubernetesApplicationOptions(config);

            // assert
            Assert.Equal("testapp", appInfo.Name);
            Assert.Equal("not-default", appInfo.NameSpace);
            Assert.Single(appInfo.Config.Paths);
            Assert.Equal("some/local/path", appInfo.Config.Paths.First());
            Assert.Single(appInfo.Config.Sources);
            Assert.False(appInfo.Config.Enabled);
            Assert.Equal("testapp.extra", appInfo.Config.Sources.First().Name);
            Assert.Equal("not-default1", appInfo.Config.Sources.First().Namespace);
            Assert.False(appInfo.Secrets.Enabled);
            Assert.Single(appInfo.Secrets.Sources);
            Assert.Equal("testapp.extrasecret", appInfo.Secrets.Sources.First().Name);
            Assert.Equal("not-default2", appInfo.Secrets.Sources.First().Namespace);
            Assert.True(appInfo.Reload.Secrets);
            Assert.True(appInfo.Reload.ConfigMaps);
            Assert.Equal(ReloadMethods.Event, appInfo.Reload.Mode);
            Assert.Equal(30, appInfo.Reload.Period);
        }