/// <summary>
        ///     Create and configure a <see cref="KubeApiClient"/> using the specified options.
        /// </summary>
        /// <param name="options">
        ///     The <see cref="KubeClientOptions"/> used to configure the client.
        /// </param>
        /// <param name="loggerFactory">
        ///     An optional <see cref="ILoggerFactory"/> used to create loggers for client components.
        /// </param>
        /// <returns>
        ///     The configured <see cref="KubeApiClient"/>.
        /// </returns>
        public static KubeApiClient Create(KubeClientOptions options, ILoggerFactory loggerFactory = null)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            options.EnsureValid();

            var clientBuilder = new ClientBuilder();

            if (!String.IsNullOrWhiteSpace(options.AccessToken))
            {
                clientBuilder = clientBuilder.AddHandler(
                    () => new BearerTokenHandler(options.AccessToken)
                    );
            }

            if (options.AllowInsecure)
            {
                clientBuilder = clientBuilder.AcceptAnyServerCertificate();
            }
            else if (options.CertificationAuthorityCertificate != null)
            {
                clientBuilder = clientBuilder.WithServerCertificate(options.CertificationAuthorityCertificate);
            }

            if (options.ClientCertificate != null)
            {
                clientBuilder = clientBuilder.WithClientCertificate(options.ClientCertificate);
            }

            if (loggerFactory != null)
            {
                LogMessageComponents logComponents = LogMessageComponents.Basic;
                if (options.LogHeaders)
                {
                    logComponents |= LogMessageComponents.Headers;
                }
                if (options.LogPayloads)
                {
                    logComponents |= LogMessageComponents.Body;
                }

                clientBuilder = clientBuilder.WithLogging(
                    logger: loggerFactory.CreateLogger(
                        typeof(KubeApiClient).FullName + ".Http"
                        ),
                    requestComponents: logComponents,
                    responseComponents: logComponents
                    );
            }

            HttpClient httpClient = clientBuilder.CreateClient(options.ApiEndPoint);

            return(new KubeApiClient(httpClient, options, loggerFactory));
        }
        /// <summary>
        ///		 Create a new <see cref="CloudControlClient"/>.
        /// </summary>
        /// <param name="baseUri">
        ///     The base URI for the CloudControl API.
        /// </param>
        /// <param name="credentials">
        ///     The network credentials used to authenticate to CloudControl.
        /// </param>
        /// <returns>
        ///     The configured <see cref="CloudControlClient"/>.
        /// </returns>
        public static CloudControlClient Create(Uri baseUri, NetworkCredential credentials)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException(nameof(baseUri));
            }

            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            return(new CloudControlClient(
                       HttpClientBuilder.CreateClient(baseUri, new HttpClientHandler
            {
                Credentials = credentials,
                PreAuthenticate = true
            })
                       ));
        }
Esempio n. 3
0
        /// <summary>
        ///     Create and configure a <see cref="KubeApiClient"/> using the specified options.
        /// </summary>
        /// <param name="options">
        ///     The <see cref="KubeClientOptions"/> used to configure the client.
        /// </param>
        /// <param name="loggerFactory">
        ///     An optional <see cref="ILoggerFactory"/> used to create loggers for client components.
        /// </param>
        /// <returns>
        ///     The configured <see cref="KubeApiClient"/>.
        /// </returns>
        public static KubeApiClient Create(KubeClientOptions options, ILoggerFactory loggerFactory = null)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            options.EnsureValid();

            var clientBuilder = new ClientBuilder();

            switch (options.AuthStrategy)
            {
            case KubeAuthStrategy.BearerToken:
            {
                clientBuilder = clientBuilder.AddHandler(
                    () => new StaticBearerTokenHandler(options.AccessToken)
                    );

                break;
            }

            case KubeAuthStrategy.BearerTokenProvider:
            {
                clientBuilder = clientBuilder.AddHandler(
                    () => new CommandBearerTokenHandler(
                        accessTokenCommand: options.AccessTokenCommand,
                        accessTokenCommandArguments: options.AccessTokenCommandArguments,
                        accessTokenSelector: options.AccessTokenSelector,
                        accessTokenExpirySelector: options.AccessTokenExpirySelector,
                        initialAccessToken: options.InitialAccessToken,
                        initialTokenExpiryUtc: options.InitialTokenExpiryUtc
                        )
                    );

                break;
            }

            case KubeAuthStrategy.ClientCertificate:
            {
                if (options.ClientCertificate == null)
                {
                    throw new KubeClientException("Cannot specify ClientCertificate authentication strategy without supplying a client certificate.");
                }

                clientBuilder = clientBuilder.WithClientCertificate(options.ClientCertificate);

                break;
            }
            }

            if (options.AllowInsecure)
            {
                clientBuilder = clientBuilder.AcceptAnyServerCertificate();
            }
            else if (options.CertificationAuthorityCertificate != null)
            {
                clientBuilder = clientBuilder.WithServerCertificate(options.CertificationAuthorityCertificate);
            }

            if (loggerFactory != null)
            {
                LogMessageComponents logComponents = LogMessageComponents.Basic;
                if (options.LogHeaders)
                {
                    logComponents |= LogMessageComponents.Headers;
                }
                if (options.LogPayloads)
                {
                    logComponents |= LogMessageComponents.Body;
                }

                clientBuilder = clientBuilder.WithLogging(
                    logger: loggerFactory.CreateLogger(
                        typeof(KubeApiClient).FullName + ".Http"
                        ),
                    requestComponents: logComponents,
                    responseComponents: logComponents
                    );
            }

            HttpClient httpClient = clientBuilder.CreateClient(options.ApiEndPoint);

            return(new KubeApiClient(httpClient, options, loggerFactory));
        }
        public async Task PodsV1_GetByName_NotFound()
        {
            var logEntries = new List <LogEntry>();

            TestLogger logger = new TestLogger(LogLevel.Information);

            logger.LogEntries.Subscribe(
                logEntry => logEntries.Add(logEntry)
                );

            ClientBuilder clientBuilder = new ClientBuilder()
                                          .WithLogging(logger);

            HttpClient httpClient = clientBuilder.CreateClient("http://localhost:1234", TestHandlers.RespondWith(request =>
            {
                return(request.CreateResponse(HttpStatusCode.NotFound,
                                              responseBody: JsonConvert.SerializeObject(new StatusV1
                {
                    Reason = "NotFound"
                }),
                                              WellKnownMediaTypes.Json
                                              ));
            }));

            KubeClientOptions clientOptions = new KubeClientOptions("http://localhost:1234");

            using (KubeApiClient kubeClient = KubeApiClient.Create(httpClient, clientOptions))
            {
                PodV1 pod = await kubeClient.PodsV1().Get(name: "foo");

                Assert.Null(pod);
            }

            Assert.Equal(2, logEntries.Count);

            LogEntry logEntry1 = logEntries[0];

            Assert.Equal(LogEventIds.BeginRequest, logEntry1.EventId);
            Assert.Equal("Performing GET request to 'http://localhost:1234/api/v1/namespaces/default/pods/foo'.",
                         logEntry1.Message
                         );
            Assert.Equal("GET",
                         logEntry1.Properties["Method"]
                         );
            Assert.Equal(new Uri("http://localhost:1234/api/v1/namespaces/default/pods/foo"),
                         logEntry1.Properties["RequestUri"]
                         );

            LogEntry logEntry2 = logEntries[1];

            Assert.Equal(LogEventIds.EndRequest, logEntry2.EventId);
            Assert.Equal("Completed GET request to 'http://localhost:1234/api/v1/namespaces/default/pods/foo' (NotFound).",
                         logEntry2.Message
                         );
            Assert.Equal("GET",
                         logEntry2.Properties["Method"]
                         );
            Assert.Equal(new Uri("http://localhost:1234/api/v1/namespaces/default/pods/foo"),
                         logEntry2.Properties["RequestUri"]
                         );
            Assert.Equal(HttpStatusCode.NotFound,
                         logEntry2.Properties["StatusCode"]
                         );
        }