diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fac20b7c6f..b122d5473c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,13 @@ * Fix #3593: Add support for Istio extension #### _**Note**_: Breaking changes in the API +* Refactoring #3547: due to an abstraction layer added over okHttp, the following api changes were made: + * OperationContext withOkHttpClient was removed, it should be needed to be directly called + * PatchType.getMediaType was replaced with PatchType.getContentType + * ExecListener no longer passes the okhttp3.Response to onOpen. onFailure will pass a simplified ExecListener.Response when possible. + * okhttp3.TlsVersions has been replaced by io.fabric8.kubernetes.client.http.TlsVersion + * HttpClientUtils.createHttpClient(config, additionalConfig) has been deprecated and now returns an OkHttpClientImpl + * The client is no longer adaptable to an OkHttpClient, use Client.getHttpClient instead ### 5.10.1 (2021-11-12) diff --git a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/CamelKExtensionAdapter.java b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/CamelKExtensionAdapter.java index b98f66934d4..3c5b0db793d 100644 --- a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/CamelKExtensionAdapter.java +++ b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/CamelKExtensionAdapter.java @@ -15,20 +15,19 @@ */ package io.fabric8.camelk.client; -import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.ExtensionAdapter; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import java.net.URL; -import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; public class CamelKExtensionAdapter extends ExtensionAdapterSupport implements ExtensionAdapter { static final ConcurrentMap IS_CAMELK = new ConcurrentHashMap<>(); static final ConcurrentMap USES_CAMELK_APIGROUPS = new ConcurrentHashMap<>(); - + @Override public Class getExtensionType() { return CamelKClient.class; @@ -41,7 +40,7 @@ public Boolean isAdaptable(Client client) { @Override public CamelKClient adapt(Client client) { - return new DefaultCamelKClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DefaultCamelKClient(client); } - + } diff --git a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/DefaultCamelKClient.java b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/DefaultCamelKClient.java index 220eb666ef7..02dc43348a6 100644 --- a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/DefaultCamelKClient.java +++ b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/DefaultCamelKClient.java @@ -15,15 +15,15 @@ */ package io.fabric8.camelk.client; -import io.fabric8.camelk.client.dsl.V1alpha1APIGroupDSL; import io.fabric8.camelk.client.dsl.V1APIGroupDSL; -import okhttp3.OkHttpClient; +import io.fabric8.camelk.client.dsl.V1alpha1APIGroupDSL; +import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; +import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.RequestConfig; import io.fabric8.kubernetes.client.WithRequestCallable; import io.fabric8.kubernetes.client.dsl.FunctionCallable; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; public class DefaultCamelKClient extends BaseClient implements NamespacedCamelKClient { @@ -35,8 +35,8 @@ public DefaultCamelKClient(Config configuration) { super(configuration); } - public DefaultCamelKClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public DefaultCamelKClient(ClientContext clientContext) { + super(clientContext); } @Override @@ -50,10 +50,10 @@ public NamespacedCamelKClient inNamespace(String namespace) { .withNamespace(namespace) .build(); - return new DefaultCamelKClient(getHttpClient(), updated); + return new DefaultCamelKClient(newState(updated)); } - @Override +@Override public FunctionCallable withRequestConfig(RequestConfig requestConfig) { return new WithRequestCallable<>(this, requestConfig); } diff --git a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1APIGroupClient.java b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1APIGroupClient.java index 7704c95ba62..23e2ed19a12 100644 --- a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1APIGroupClient.java +++ b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1APIGroupClient.java @@ -15,12 +15,6 @@ */ package io.fabric8.camelk.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.Handlers; -import io.fabric8.kubernetes.client.dsl.MixedOperation; -import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; -import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.camelk.client.dsl.V1APIGroupDSL; import io.fabric8.camelk.v1.Build; import io.fabric8.camelk.v1.BuildList; @@ -32,40 +26,44 @@ import io.fabric8.camelk.v1.IntegrationList; import io.fabric8.camelk.v1.IntegrationPlatform; import io.fabric8.camelk.v1.IntegrationPlatformList; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; +import io.fabric8.kubernetes.client.Handlers; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.Resource; public class V1APIGroupClient extends BaseClient implements V1APIGroupDSL { public V1APIGroupClient() { super(); } - public V1APIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1APIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> builds() { - return Handlers.getOperation(Build.class, BuildList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Build.class, BuildList.class, this); } @Override public MixedOperation> camelCatalogs() { - return Handlers.getOperation(CamelCatalog.class, CamelCatalogList.class, httpClient, getConfiguration()); + return Handlers.getOperation(CamelCatalog.class, CamelCatalogList.class, this); } @Override public MixedOperation> integrations() { - return Handlers.getOperation(Integration.class, IntegrationList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Integration.class, IntegrationList.class, this); } @Override public MixedOperation> integrationKits() { - return Handlers.getOperation(IntegrationKit.class, IntegrationKitList.class, httpClient, getConfiguration()); + return Handlers.getOperation(IntegrationKit.class, IntegrationKitList.class, this); } @Override public MixedOperation> integrationPlatforms() { - return Handlers.getOperation(IntegrationPlatform.class, IntegrationPlatformList.class, httpClient, getConfiguration()); + return Handlers.getOperation(IntegrationPlatform.class, IntegrationPlatformList.class, this); } } diff --git a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1APIGroupExtensionAdapter.java b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1APIGroupExtensionAdapter.java index 6d862a96b38..487890a7023 100644 --- a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1APIGroupExtensionAdapter.java +++ b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1APIGroupClient newInstance(Client client) { - return new V1APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1APIGroupClient(client); } } diff --git a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1alpha1APIGroupClient.java b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1alpha1APIGroupClient.java index eb27de05ad1..1524aeb75ca 100644 --- a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1alpha1APIGroupClient.java +++ b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1alpha1APIGroupClient.java @@ -15,15 +15,14 @@ */ package io.fabric8.camelk.client; +import io.fabric8.camelk.client.dsl.V1alpha1APIGroupDSL; +import io.fabric8.camelk.v1alpha1.Kamelet; +import io.fabric8.camelk.v1alpha1.KameletList; import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import io.fabric8.camelk.client.dsl.V1alpha1APIGroupDSL; -import io.fabric8.camelk.v1alpha1.Kamelet; -import io.fabric8.camelk.v1alpha1.KameletList; -import okhttp3.OkHttpClient; public class V1alpha1APIGroupClient extends BaseClient implements V1alpha1APIGroupDSL { @@ -31,12 +30,12 @@ public V1alpha1APIGroupClient() { super(); } - public V1alpha1APIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1alpha1APIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> kamelets() { - return Handlers.getOperation(Kamelet.class, KameletList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Kamelet.class, KameletList.class, this); } } diff --git a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1alpha1APIGroupExtensionAdapter.java b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1alpha1APIGroupExtensionAdapter.java index 143946b6183..fb978cc7fd3 100644 --- a/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1alpha1APIGroupExtensionAdapter.java +++ b/extensions/camel-k/client/src/main/java/io/fabric8/camelk/client/V1alpha1APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1alpha1APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1alpha1APIGroupClient newInstance(Client client) { - return new V1alpha1APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1alpha1APIGroupClient(client); } } diff --git a/extensions/camel-k/mock/src/main/java/io/fabric8/camelk/mock/CamelKMockServer.java b/extensions/camel-k/mock/src/main/java/io/fabric8/camelk/mock/CamelKMockServer.java index f0985b80b32..aeb3555f077 100644 --- a/extensions/camel-k/mock/src/main/java/io/fabric8/camelk/mock/CamelKMockServer.java +++ b/extensions/camel-k/mock/src/main/java/io/fabric8/camelk/mock/CamelKMockServer.java @@ -15,26 +15,19 @@ */ package io.fabric8.camelk.mock; +import io.fabric8.camelk.client.DefaultCamelKClient; import io.fabric8.camelk.client.NamespacedCamelKClient; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import io.fabric8.mockwebserver.Context; import io.fabric8.mockwebserver.ServerRequest; import io.fabric8.mockwebserver.ServerResponse; -import io.fabric8.camelk.client.DefaultCamelKClient; -import io.fabric8.camelk.client.CamelKClient; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockWebServer; import java.util.Map; import java.util.Queue; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; -import static okhttp3.TlsVersion.TLS_1_2; - public class CamelKMockServer extends KubernetesMockServer { - private boolean disableApiGroupCheck = true; public CamelKMockServer() { super(); @@ -54,12 +47,6 @@ public String[] getRootPaths() { } public NamespacedCamelKClient createCamelKClient() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); - return new DefaultCamelKClient(createHttpClientForMockServer(config), config); + return new DefaultCamelKClient(getMockConfiguration()); } } diff --git a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/CertManagerExtensionAdapter.java b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/CertManagerExtensionAdapter.java index 39eb00eebbd..d757b3aa3ac 100644 --- a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/CertManagerExtensionAdapter.java +++ b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/CertManagerExtensionAdapter.java @@ -15,10 +15,9 @@ */ package io.fabric8.certmanager.client; -import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.ExtensionAdapter; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import java.net.URL; import java.util.concurrent.ConcurrentHashMap; @@ -42,6 +41,6 @@ public Boolean isAdaptable(Client client) { @Override public CertManagerClient adapt(Client client) { - return new DefaultCertManagerClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DefaultCertManagerClient(client); } } diff --git a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/DefaultCertManagerClient.java b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/DefaultCertManagerClient.java index 8b466b072d1..eeeb47e9d70 100644 --- a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/DefaultCertManagerClient.java +++ b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/DefaultCertManagerClient.java @@ -19,9 +19,13 @@ import io.fabric8.certmanager.client.dsl.V1alpha2APIGroupDSL; import io.fabric8.certmanager.client.dsl.V1alpha3APIGroupDSL; import io.fabric8.certmanager.client.dsl.V1beta1APIGroupDSL; -import io.fabric8.kubernetes.client.*; +import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ConfigBuilder; +import io.fabric8.kubernetes.client.RequestConfig; +import io.fabric8.kubernetes.client.WithRequestCallable; import io.fabric8.kubernetes.client.dsl.FunctionCallable; -import okhttp3.OkHttpClient; public class DefaultCertManagerClient extends BaseClient implements NamespacedCertManagerClient { @@ -33,8 +37,8 @@ public DefaultCertManagerClient(Config configuration) { super(configuration); } - public DefaultCertManagerClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public DefaultCertManagerClient(ClientContext clientContext) { + super(clientContext); } @Override @@ -48,7 +52,7 @@ public NamespacedCertManagerClient inNamespace(String namespace) { .withNamespace(namespace) .build(); - return new DefaultCertManagerClient(getHttpClient(), updated); + return new DefaultCertManagerClient(newState(updated)); } @Override diff --git a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1APIGroupClient.java b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1APIGroupClient.java index 5f85db4e1c2..b76d1cbdebb 100644 --- a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1APIGroupClient.java +++ b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1APIGroupClient.java @@ -19,50 +19,56 @@ import io.fabric8.certmanager.api.model.acme.v1.ChallengeList; import io.fabric8.certmanager.api.model.acme.v1.Order; import io.fabric8.certmanager.api.model.acme.v1.OrderList; -import io.fabric8.certmanager.api.model.v1.*; +import io.fabric8.certmanager.api.model.v1.Certificate; +import io.fabric8.certmanager.api.model.v1.CertificateList; +import io.fabric8.certmanager.api.model.v1.CertificateRequest; +import io.fabric8.certmanager.api.model.v1.CertificateRequestList; +import io.fabric8.certmanager.api.model.v1.ClusterIssuer; +import io.fabric8.certmanager.api.model.v1.ClusterIssuerList; +import io.fabric8.certmanager.api.model.v1.Issuer; +import io.fabric8.certmanager.api.model.v1.IssuerList; import io.fabric8.certmanager.client.dsl.V1APIGroupDSL; import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1APIGroupClient extends BaseClient implements V1APIGroupDSL { public V1APIGroupClient() {super();} - public V1APIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1APIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> certificates() { - return Handlers.getOperation(Certificate.class, CertificateList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Certificate.class, CertificateList.class, this); } @Override public MixedOperation> certificateRequests() { - return Handlers.getOperation(CertificateRequest.class, CertificateRequestList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(CertificateRequest.class, CertificateRequestList.class, this); } @Override public MixedOperation> issuers() { - return Handlers.getOperation(Issuer.class, IssuerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Issuer.class, IssuerList.class, this); } @Override public NonNamespaceOperation> clusterIssuers() { - return Handlers.getOperation(ClusterIssuer.class, ClusterIssuerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ClusterIssuer.class, ClusterIssuerList.class, this); } @Override public MixedOperation> challenges() { - return Handlers.getOperation(Challenge.class, ChallengeList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Challenge.class, ChallengeList.class, this); } @Override public MixedOperation> orders() { - return Handlers.getOperation(Order.class, OrderList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Order.class, OrderList.class, this); } } diff --git a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1APIGroupExtensionAdapter.java b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1APIGroupExtensionAdapter.java index 2b67e42c51e..3786f0c0d16 100644 --- a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1APIGroupExtensionAdapter.java +++ b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1APIGroupClient newInstance(Client client) { - return new V1APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1APIGroupClient(client); } } diff --git a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha2APIGroupClient.java b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha2APIGroupClient.java index a5c37b11143..f0633c54d2a 100644 --- a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha2APIGroupClient.java +++ b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha2APIGroupClient.java @@ -19,52 +19,58 @@ import io.fabric8.certmanager.api.model.acme.v1alpha2.ChallengeList; import io.fabric8.certmanager.api.model.acme.v1alpha2.Order; import io.fabric8.certmanager.api.model.acme.v1alpha2.OrderList; -import io.fabric8.certmanager.api.model.v1alpha2.*; +import io.fabric8.certmanager.api.model.v1alpha2.Certificate; +import io.fabric8.certmanager.api.model.v1alpha2.CertificateList; +import io.fabric8.certmanager.api.model.v1alpha2.CertificateRequest; +import io.fabric8.certmanager.api.model.v1alpha2.CertificateRequestList; +import io.fabric8.certmanager.api.model.v1alpha2.ClusterIssuer; +import io.fabric8.certmanager.api.model.v1alpha2.ClusterIssuerList; +import io.fabric8.certmanager.api.model.v1alpha2.Issuer; +import io.fabric8.certmanager.api.model.v1alpha2.IssuerList; import io.fabric8.certmanager.client.dsl.V1alpha2APIGroupDSL; import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1alpha2APIGroupClient extends BaseClient implements V1alpha2APIGroupDSL { public V1alpha2APIGroupClient() { super(); } - public V1alpha2APIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1alpha2APIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> certificates() { - return Handlers.getOperation(Certificate.class, CertificateList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Certificate.class, CertificateList.class, this); } @Override public MixedOperation> certificateRequests() { - return Handlers.getOperation(CertificateRequest.class, CertificateRequestList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(CertificateRequest.class, CertificateRequestList.class, this); } @Override public MixedOperation> issuers() { - return Handlers.getOperation(Issuer.class, IssuerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Issuer.class, IssuerList.class, this); } @Override public NonNamespaceOperation> clusterIssuers() { - return Handlers.getOperation(ClusterIssuer.class, ClusterIssuerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ClusterIssuer.class, ClusterIssuerList.class, this); } @Override public MixedOperation> challenges() { - return Handlers.getOperation(Challenge.class, ChallengeList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Challenge.class, ChallengeList.class, this); } @Override public MixedOperation> orders() { - return Handlers.getOperation(Order.class, OrderList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Order.class, OrderList.class, this); } } diff --git a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha2APIGroupExtensionAdapter.java b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha2APIGroupExtensionAdapter.java index ac807876ca5..65245525d45 100644 --- a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha2APIGroupExtensionAdapter.java +++ b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha2APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1alpha2APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1alpha2APIGroupClient newInstance(Client client) { - return new V1alpha2APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1alpha2APIGroupClient(client); } } diff --git a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha3APIGroupClient.java b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha3APIGroupClient.java index 158359b0aaa..80dbfa2a6ab 100644 --- a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha3APIGroupClient.java +++ b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha3APIGroupClient.java @@ -19,52 +19,58 @@ import io.fabric8.certmanager.api.model.acme.v1alpha3.ChallengeList; import io.fabric8.certmanager.api.model.acme.v1alpha3.Order; import io.fabric8.certmanager.api.model.acme.v1alpha3.OrderList; -import io.fabric8.certmanager.api.model.v1alpha3.*; +import io.fabric8.certmanager.api.model.v1alpha3.Certificate; +import io.fabric8.certmanager.api.model.v1alpha3.CertificateList; +import io.fabric8.certmanager.api.model.v1alpha3.CertificateRequest; +import io.fabric8.certmanager.api.model.v1alpha3.CertificateRequestList; +import io.fabric8.certmanager.api.model.v1alpha3.ClusterIssuer; +import io.fabric8.certmanager.api.model.v1alpha3.ClusterIssuerList; +import io.fabric8.certmanager.api.model.v1alpha3.Issuer; +import io.fabric8.certmanager.api.model.v1alpha3.IssuerList; import io.fabric8.certmanager.client.dsl.V1alpha3APIGroupDSL; import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1alpha3APIGroupClient extends BaseClient implements V1alpha3APIGroupDSL { public V1alpha3APIGroupClient() { super(); } - public V1alpha3APIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1alpha3APIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> certificates() { - return Handlers.getOperation(Certificate.class, CertificateList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Certificate.class, CertificateList.class, this); } @Override public MixedOperation> certificateRequests() { - return Handlers.getOperation(CertificateRequest.class, CertificateRequestList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(CertificateRequest.class, CertificateRequestList.class, this); } @Override public MixedOperation> issuers() { - return Handlers.getOperation(Issuer.class, IssuerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Issuer.class, IssuerList.class, this); } @Override public NonNamespaceOperation> clusterIssuers() { - return Handlers.getOperation(ClusterIssuer.class, ClusterIssuerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ClusterIssuer.class, ClusterIssuerList.class, this); } @Override public MixedOperation> challenges() { - return Handlers.getOperation(Challenge.class, ChallengeList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Challenge.class, ChallengeList.class, this); } @Override public MixedOperation> orders() { - return Handlers.getOperation(Order.class, OrderList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Order.class, OrderList.class, this); } } diff --git a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha3APIGroupExtensionAdapter.java b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha3APIGroupExtensionAdapter.java index f0f5b2868b9..f2b1b71a13a 100644 --- a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha3APIGroupExtensionAdapter.java +++ b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1alpha3APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1alpha3APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1alpha3APIGroupClient newInstance(Client client) { - return new V1alpha3APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1alpha3APIGroupClient(client); } } diff --git a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1beta1APIGroupClient.java b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1beta1APIGroupClient.java index 52eb1228c4b..224aef969de 100644 --- a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1beta1APIGroupClient.java +++ b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1beta1APIGroupClient.java @@ -29,49 +29,48 @@ import io.fabric8.certmanager.api.model.v1beta1.IssuerList; import io.fabric8.certmanager.client.dsl.V1beta1APIGroupDSL; import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1beta1APIGroupClient extends BaseClient implements V1beta1APIGroupDSL { public V1beta1APIGroupClient() { super(); } - public V1beta1APIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1APIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> certificates() { - return Handlers.getOperation(Certificate.class, CertificateList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Certificate.class, CertificateList.class, this); } @Override public MixedOperation> certificateRequests() { - return Handlers.getOperation(CertificateRequest.class, CertificateRequestList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(CertificateRequest.class, CertificateRequestList.class, this); } @Override public MixedOperation> issuers() { - return Handlers.getOperation(Issuer.class, IssuerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Issuer.class, IssuerList.class, this); } @Override public NonNamespaceOperation> clusterIssuers() { - return Handlers.getOperation(ClusterIssuer.class, ClusterIssuerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ClusterIssuer.class, ClusterIssuerList.class, this); } @Override public MixedOperation> challenges() { - return Handlers.getOperation(Challenge.class, ChallengeList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Challenge.class, ChallengeList.class, this); } @Override public MixedOperation> orders() { - return Handlers.getOperation(Order.class, OrderList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Order.class, OrderList.class, this); } } diff --git a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1beta1APIGroupExtensionAdapter.java b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1beta1APIGroupExtensionAdapter.java index 69daee548ee..e6ab1477452 100644 --- a/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1beta1APIGroupExtensionAdapter.java +++ b/extensions/certmanager/client/src/main/java/io/fabric8/certmanager/client/V1beta1APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1beta1APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1beta1APIGroupClient newInstance(Client client) { - return new V1beta1APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1APIGroupClient(client); } } diff --git a/extensions/certmanager/mock/src/main/java/io/fabric8/certmanager/server/mock/CertManagerMockServer.java b/extensions/certmanager/mock/src/main/java/io/fabric8/certmanager/server/mock/CertManagerMockServer.java index 66b0f7ebc0e..d2c5cad7570 100644 --- a/extensions/certmanager/mock/src/main/java/io/fabric8/certmanager/server/mock/CertManagerMockServer.java +++ b/extensions/certmanager/mock/src/main/java/io/fabric8/certmanager/server/mock/CertManagerMockServer.java @@ -15,25 +15,20 @@ */ package io.fabric8.certmanager.server.mock; +import io.fabric8.certmanager.client.DefaultCertManagerClient; import io.fabric8.certmanager.client.NamespacedCertManagerClient; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import io.fabric8.mockwebserver.Context; import io.fabric8.mockwebserver.ServerRequest; import io.fabric8.mockwebserver.ServerResponse; -import io.fabric8.certmanager.client.DefaultCertManagerClient; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockWebServer; import java.util.Map; import java.util.Queue; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; -import static okhttp3.TlsVersion.TLS_1_2; - public class CertManagerMockServer extends KubernetesMockServer { - private boolean disableApiGroupCheck = true; public CertManagerMockServer() { super(); @@ -53,12 +48,7 @@ public String[] getRootPaths() { } public NamespacedCertManagerClient createCertManager() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); - return new DefaultCertManagerClient(createHttpClientForMockServer(config), config); + Config config = getMockConfiguration(); + return new DefaultCertManagerClient(config); } } diff --git a/extensions/chaosmesh/client/src/main/java/io/fabric8/chaosmesh/client/ChaosMeshExtensionAdapter.java b/extensions/chaosmesh/client/src/main/java/io/fabric8/chaosmesh/client/ChaosMeshExtensionAdapter.java index 427bd80ab18..3da7f2ded72 100644 --- a/extensions/chaosmesh/client/src/main/java/io/fabric8/chaosmesh/client/ChaosMeshExtensionAdapter.java +++ b/extensions/chaosmesh/client/src/main/java/io/fabric8/chaosmesh/client/ChaosMeshExtensionAdapter.java @@ -18,7 +18,6 @@ import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.ExtensionAdapter; import io.fabric8.kubernetes.client.ExtensionAdapterSupport; -import okhttp3.OkHttpClient; import java.net.URL; import java.util.concurrent.ConcurrentHashMap; @@ -28,7 +27,7 @@ public class ChaosMeshExtensionAdapter extends ExtensionAdapterSupport implement static final ConcurrentMap IS_CHAOS_MESH = new ConcurrentHashMap<>(); static final ConcurrentMap USES_CHAOS_MESH_APIGROUPS = new ConcurrentHashMap<>(); - + @Override public Class getExtensionType() { return ChaosMeshClient.class; @@ -41,6 +40,6 @@ public Boolean isAdaptable(Client client) { @Override public ChaosMeshClient adapt(Client client) { - return new DefaultChaosMeshClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DefaultChaosMeshClient(client); } } diff --git a/extensions/chaosmesh/client/src/main/java/io/fabric8/chaosmesh/client/DefaultChaosMeshClient.java b/extensions/chaosmesh/client/src/main/java/io/fabric8/chaosmesh/client/DefaultChaosMeshClient.java index 5d3140ee241..b478d6486b0 100644 --- a/extensions/chaosmesh/client/src/main/java/io/fabric8/chaosmesh/client/DefaultChaosMeshClient.java +++ b/extensions/chaosmesh/client/src/main/java/io/fabric8/chaosmesh/client/DefaultChaosMeshClient.java @@ -40,6 +40,7 @@ import io.fabric8.chaosmesh.v1alpha1.TimeChaos; import io.fabric8.chaosmesh.v1alpha1.TimeChaosList; import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.Handlers; @@ -48,7 +49,6 @@ import io.fabric8.kubernetes.client.dsl.FunctionCallable; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class DefaultChaosMeshClient extends BaseClient implements NamespacedChaosMeshClient { @@ -60,8 +60,8 @@ public DefaultChaosMeshClient(Config configuration) { super(configuration); } - public DefaultChaosMeshClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public DefaultChaosMeshClient(ClientContext clientContext) { + super(clientContext); } @Override @@ -73,7 +73,7 @@ public NamespacedChaosMeshClient inAnyNamespace() { public NamespacedChaosMeshClient inNamespace(String namespace) { Config updated = new ConfigBuilder(getConfiguration()).withNamespace(namespace).build(); - return new DefaultChaosMeshClient(getHttpClient(), updated); + return new DefaultChaosMeshClient(newState(updated)); } @Override @@ -84,63 +84,63 @@ public FunctionCallable withRequestConfig(RequestConf @Override public MixedOperation> ioChaos() { - return Handlers.getOperation(IoChaos.class, IoChaosList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(IoChaos.class, IoChaosList.class, this); } @Override public MixedOperation> kernelChaos() { - return Handlers.getOperation(KernelChaos.class, KernelChaosList.class, httpClient, getConfiguration()); + return Handlers.getOperation(KernelChaos.class, KernelChaosList.class, this); } @Override public MixedOperation> networkChaos() { - return Handlers.getOperation(NetworkChaos.class, NetworkChaosList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(NetworkChaos.class, NetworkChaosList.class, this); } @Override public MixedOperation> podChaos() { - return Handlers.getOperation(PodChaos.class, PodChaosList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(PodChaos.class, PodChaosList.class, this); } @Override public MixedOperation> podIoChaos() { - return Handlers.getOperation(PodIoChaos.class, PodIoChaosList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(PodIoChaos.class, PodIoChaosList.class, this); } @Override public MixedOperation> podNetworkChaos() { - return Handlers.getOperation(PodNetworkChaos.class, PodNetworkChaosList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(PodNetworkChaos.class, PodNetworkChaosList.class, this); } @Override public MixedOperation> stressChaos() { - return Handlers.getOperation(StressChaos.class, StressChaosList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(StressChaos.class, StressChaosList.class, this); } @Override public MixedOperation> timeChaos() { - return Handlers.getOperation(TimeChaos.class, TimeChaosList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(TimeChaos.class, TimeChaosList.class, this); } @Override public MixedOperation> jvmChaos() { - return Handlers.getOperation(JVMChaos.class, JVMChaosList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(JVMChaos.class, JVMChaosList.class, this); } @Override public MixedOperation> httpChaos() { - return Handlers.getOperation(HTTPChaos.class, HTTPChaosList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(HTTPChaos.class, HTTPChaosList.class, this); } @Override public MixedOperation> dnsChaos() { - return Handlers.getOperation(DNSChaos.class, DNSChaosList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(DNSChaos.class, DNSChaosList.class, this); } @Override public MixedOperation> awsChaos() { - return Handlers.getOperation(AwsChaos.class, AwsChaosList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(AwsChaos.class, AwsChaosList.class, this); } } diff --git a/extensions/chaosmesh/mock/src/main/java/io/fabric8/chaosmesh/server/mock/ChaosMeshMockServer.java b/extensions/chaosmesh/mock/src/main/java/io/fabric8/chaosmesh/server/mock/ChaosMeshMockServer.java index 4ad39298a32..bce0c9c3519 100644 --- a/extensions/chaosmesh/mock/src/main/java/io/fabric8/chaosmesh/server/mock/ChaosMeshMockServer.java +++ b/extensions/chaosmesh/mock/src/main/java/io/fabric8/chaosmesh/server/mock/ChaosMeshMockServer.java @@ -15,11 +15,8 @@ */ package io.fabric8.chaosmesh.server.mock; -import io.fabric8.chaosmesh.client.ChaosMeshClient; import io.fabric8.chaosmesh.client.DefaultChaosMeshClient; import io.fabric8.chaosmesh.client.NamespacedChaosMeshClient; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import io.fabric8.mockwebserver.Context; import io.fabric8.mockwebserver.ServerRequest; @@ -30,8 +27,6 @@ import java.util.Map; import java.util.Queue; -import static okhttp3.TlsVersion.TLS_1_2; - public class ChaosMeshMockServer extends KubernetesMockServer { public ChaosMeshMockServer() { super(); @@ -51,12 +46,6 @@ public String[] getRootPaths() { } public NamespacedChaosMeshClient createChaosMeshClient() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); - return new DefaultChaosMeshClient(config); + return new DefaultChaosMeshClient(getMockConfiguration()); } } diff --git a/extensions/istio/client/src/main/java/io/fabric8/istio/client/DefaultIstioClient.java b/extensions/istio/client/src/main/java/io/fabric8/istio/client/DefaultIstioClient.java index 0e916e53fb7..a1c2fe99ff8 100644 --- a/extensions/istio/client/src/main/java/io/fabric8/istio/client/DefaultIstioClient.java +++ b/extensions/istio/client/src/main/java/io/fabric8/istio/client/DefaultIstioClient.java @@ -16,12 +16,12 @@ package io.fabric8.istio.client; import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.RequestConfig; import io.fabric8.kubernetes.client.WithRequestCallable; import io.fabric8.kubernetes.client.dsl.FunctionCallable; -import okhttp3.OkHttpClient; public class DefaultIstioClient extends BaseClient implements NamespacedIstioClient { @@ -33,8 +33,8 @@ public DefaultIstioClient(Config configuration) { super(configuration); } - public DefaultIstioClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public DefaultIstioClient(ClientContext clientContext) { + super(clientContext); } @Override @@ -48,7 +48,7 @@ public NamespacedIstioClient inNamespace(String namespace) { .withNamespace(namespace) .build(); - return new DefaultIstioClient(getHttpClient(), updated); + return new DefaultIstioClient(newState(updated)); } @Override diff --git a/extensions/istio/client/src/main/java/io/fabric8/istio/client/IstioExtensionAdapter.java b/extensions/istio/client/src/main/java/io/fabric8/istio/client/IstioExtensionAdapter.java index 7f734f11764..982aae6d6e6 100644 --- a/extensions/istio/client/src/main/java/io/fabric8/istio/client/IstioExtensionAdapter.java +++ b/extensions/istio/client/src/main/java/io/fabric8/istio/client/IstioExtensionAdapter.java @@ -15,14 +15,13 @@ */ package io.fabric8.istio.client; -import java.net.URL; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.ExtensionAdapter; import io.fabric8.kubernetes.client.ExtensionAdapterSupport; -import okhttp3.OkHttpClient; + +import java.net.URL; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; public class IstioExtensionAdapter extends ExtensionAdapterSupport implements ExtensionAdapter { @@ -41,6 +40,6 @@ public Boolean isAdaptable(Client client) { @Override public IstioClient adapt(Client client) { - return new DefaultIstioClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DefaultIstioClient(client); } } diff --git a/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1alpha3APIGroupClient.java b/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1alpha3APIGroupClient.java index b9b3571e666..8a8ab163f7b 100644 --- a/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1alpha3APIGroupClient.java +++ b/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1alpha3APIGroupClient.java @@ -30,11 +30,11 @@ import io.fabric8.istio.api.networking.v1alpha3.WorkloadEntry; import io.fabric8.istio.api.networking.v1alpha3.WorkloadEntryList; import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1alpha3APIGroupClient extends BaseClient implements V1alpha3APIGroupDSL { @@ -46,46 +46,44 @@ public V1alpha3APIGroupClient(Config configuration) { super(configuration); } - public V1alpha3APIGroupClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public V1alpha3APIGroupClient(ClientContext clientContext) { + super(clientContext); } // networking @Override public MixedOperation> destinationRules() { - return Handlers.getOperation(DestinationRule.class, DestinationRuleList.class, this.getHttpClient(), - this.getConfiguration()); + return Handlers.getOperation(DestinationRule.class, DestinationRuleList.class, this); } @Override public MixedOperation> envoyFilters() { - return Handlers.getOperation(EnvoyFilter.class, EnvoyFilterList.class, this.getHttpClient(), - this.getConfiguration()); + return Handlers.getOperation(EnvoyFilter.class, EnvoyFilterList.class, this); } @Override public MixedOperation> gateways() { - return Handlers.getOperation(Gateway.class, GatewayList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Gateway.class, GatewayList.class, this); } @Override public MixedOperation> serviceEntries() { - return Handlers.getOperation(ServiceEntry.class, ServiceEntryList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ServiceEntry.class, ServiceEntryList.class, this); } @Override public MixedOperation> sidecars() { - return Handlers.getOperation(Sidecar.class, SidecarList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Sidecar.class, SidecarList.class, this); } @Override public MixedOperation> virtualServices() { - return Handlers.getOperation(VirtualService.class, VirtualServiceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(VirtualService.class, VirtualServiceList.class, this); } @Override public MixedOperation> workloadEntries() { - return Handlers.getOperation(WorkloadEntry.class, WorkloadEntryList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(WorkloadEntry.class, WorkloadEntryList.class, this); } } diff --git a/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1alpha3APIGroupExtensionAdapter.java b/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1alpha3APIGroupExtensionAdapter.java index f77b68a96d6..35da5d7edc3 100644 --- a/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1alpha3APIGroupExtensionAdapter.java +++ b/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1alpha3APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1alpha3APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1alpha3APIGroupClient newInstance(Client client) { - return new V1alpha3APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1alpha3APIGroupClient(client); } } diff --git a/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1beta1APIGroupClient.java b/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1beta1APIGroupClient.java index 5ec3ad19d0d..d86ee9e0683 100644 --- a/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1beta1APIGroupClient.java +++ b/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1beta1APIGroupClient.java @@ -34,11 +34,11 @@ import io.fabric8.istio.api.security.v1beta1.RequestAuthentication; import io.fabric8.istio.api.security.v1beta1.RequestAuthenticationList; import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1beta1APIGroupClient extends BaseClient implements V1beta1APIGroupDSL { @@ -50,59 +50,55 @@ public V1beta1APIGroupClient(Config configuration) { super(configuration); } - public V1beta1APIGroupClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public V1beta1APIGroupClient(ClientContext clientContext) { + super(clientContext); } // networking @Override public MixedOperation> destinationRules() { - return Handlers.getOperation(DestinationRule.class, DestinationRuleList.class, this.getHttpClient(), - this.getConfiguration()); + return Handlers.getOperation(DestinationRule.class, DestinationRuleList.class, this); } @Override public MixedOperation> gateways() { - return Handlers.getOperation(Gateway.class, GatewayList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Gateway.class, GatewayList.class, this); } @Override public MixedOperation> serviceEntries() { - return Handlers.getOperation(ServiceEntry.class, ServiceEntryList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ServiceEntry.class, ServiceEntryList.class, this); } @Override public MixedOperation> sidecars() { - return Handlers.getOperation(Sidecar.class, SidecarList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Sidecar.class, SidecarList.class, this); } @Override public MixedOperation> virtualServices() { - return Handlers.getOperation(VirtualService.class, VirtualServiceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(VirtualService.class, VirtualServiceList.class, this); } @Override public MixedOperation> workloadEntries() { - return Handlers.getOperation(WorkloadEntry.class, WorkloadEntryList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(WorkloadEntry.class, WorkloadEntryList.class, this); } // security @Override public MixedOperation> peerAuthentications() { - return Handlers.getOperation(PeerAuthentication.class, PeerAuthenticationList.class, this.getHttpClient(), - this.getConfiguration()); + return Handlers.getOperation(PeerAuthentication.class, PeerAuthenticationList.class, this); } @Override public MixedOperation> requestAuthentications() { - return Handlers.getOperation(RequestAuthentication.class, RequestAuthenticationList.class, this.getHttpClient(), - this.getConfiguration()); + return Handlers.getOperation(RequestAuthentication.class, RequestAuthenticationList.class, this); } @Override public MixedOperation> authorizationPolicies() { - return Handlers.getOperation(AuthorizationPolicy.class, AuthorizationPolicyList.class, this.getHttpClient(), - this.getConfiguration()); + return Handlers.getOperation(AuthorizationPolicy.class, AuthorizationPolicyList.class, this); } } diff --git a/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1beta1APIGroupExtensionAdapter.java b/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1beta1APIGroupExtensionAdapter.java index b246b631592..9ff5d973438 100644 --- a/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1beta1APIGroupExtensionAdapter.java +++ b/extensions/istio/client/src/main/java/io/fabric8/istio/client/V1beta1APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1beta1APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1beta1APIGroupClient newInstance(Client client) { - return new V1beta1APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1APIGroupClient(client); } } diff --git a/extensions/istio/mock/src/main/java/io/fabric8/istio/mock/IstioMockServer.java b/extensions/istio/mock/src/main/java/io/fabric8/istio/mock/IstioMockServer.java index ce238fc9c7f..89151638a0a 100644 --- a/extensions/istio/mock/src/main/java/io/fabric8/istio/mock/IstioMockServer.java +++ b/extensions/istio/mock/src/main/java/io/fabric8/istio/mock/IstioMockServer.java @@ -15,16 +15,9 @@ */ package io.fabric8.istio.mock; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; -import static okhttp3.TlsVersion.TLS_1_2; - -import java.util.Map; -import java.util.Queue; - import io.fabric8.istio.client.DefaultIstioClient; import io.fabric8.istio.client.NamespacedIstioClient; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import io.fabric8.mockwebserver.Context; import io.fabric8.mockwebserver.ServerRequest; @@ -32,6 +25,9 @@ import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockWebServer; +import java.util.Map; +import java.util.Queue; + public class IstioMockServer extends KubernetesMockServer { public IstioMockServer() { super(); @@ -51,12 +47,7 @@ public String[] getRootPaths() { } public NamespacedIstioClient createIstio() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); - return new DefaultIstioClient(createHttpClientForMockServer(config), config); + Config config = getMockConfiguration(); + return new DefaultIstioClient(config); } } diff --git a/extensions/knative/client/src/main/java/io/fabric8/knative/client/DefaultKnativeClient.java b/extensions/knative/client/src/main/java/io/fabric8/knative/client/DefaultKnativeClient.java index b3d274a64ec..a4cf397ff03 100644 --- a/extensions/knative/client/src/main/java/io/fabric8/knative/client/DefaultKnativeClient.java +++ b/extensions/knative/client/src/main/java/io/fabric8/knative/client/DefaultKnativeClient.java @@ -68,6 +68,7 @@ import io.fabric8.knative.sources.v1.SinkBinding; import io.fabric8.knative.sources.v1.SinkBindingList; import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.Handlers; @@ -76,7 +77,6 @@ import io.fabric8.kubernetes.client.dsl.FunctionCallable; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class DefaultKnativeClient extends BaseClient implements NamespacedKnativeClient { @@ -88,8 +88,8 @@ public DefaultKnativeClient(Config configuration) { super(configuration); } - public DefaultKnativeClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public DefaultKnativeClient(ClientContext clientContext) { + super(clientContext); } @Override @@ -101,7 +101,7 @@ public NamespacedKnativeClient inAnyNamespace() { public NamespacedKnativeClient inNamespace(String namespace) { Config updated = new ConfigBuilder(getConfiguration()).withNamespace(namespace).build(); - return new DefaultKnativeClient(getHttpClient(), updated); + return new DefaultKnativeClient(newState(updated)); } @Override @@ -111,131 +111,131 @@ public FunctionCallable withRequestConfig(RequestConfig @Override public MixedOperation> services() { - return Handlers.getOperation(Service.class, ServiceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Service.class, ServiceList.class, this); } @Override public MixedOperation> routes() { - return Handlers.getOperation(Route.class, RouteList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Route.class, RouteList.class, this); } @Override public MixedOperation> revisions() { - return Handlers.getOperation(Revision.class, RevisionList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Revision.class, RevisionList.class, this); } @Override public MixedOperation> configurations() { - return Handlers.getOperation(Configuration.class, ConfigurationList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Configuration.class, ConfigurationList.class, this); } @Override public MixedOperation> brokers() { - return Handlers.getOperation(Broker.class, BrokerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Broker.class, BrokerList.class, this); } @Override public MixedOperation> triggers() { - return Handlers.getOperation(Trigger.class, TriggerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Trigger.class, TriggerList.class, this); } @Override public MixedOperation> channels() { - return Handlers.getOperation(Channel.class, ChannelList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Channel.class, ChannelList.class, this); } @Override public MixedOperation> subscriptions() { - return Handlers.getOperation(Subscription.class, SubscriptionList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Subscription.class, SubscriptionList.class, this); } @Override public MixedOperation> eventTypes() { - return Handlers.getOperation(EventType.class, EventTypeList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(EventType.class, EventTypeList.class, this); } @Override public MixedOperation> sequences() { - return Handlers.getOperation(Sequence.class, SequenceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Sequence.class, SequenceList.class, this); } @Override public MixedOperation> parallels() { - return Handlers.getOperation(Parallel.class, ParallelList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Parallel.class, ParallelList.class, this); } @Override public MixedOperation> inMemoryChannels() { - return Handlers.getOperation(InMemoryChannel.class, InMemoryChannelList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(InMemoryChannel.class, InMemoryChannelList.class, this); } @Override public MixedOperation> pingSources() { - return Handlers.getOperation(PingSource.class, PingSourceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(PingSource.class, PingSourceList.class, this); } @Override public MixedOperation> sinkBindings() { - return Handlers.getOperation(SinkBinding.class, SinkBindingList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(SinkBinding.class, SinkBindingList.class, this); } @Override public MixedOperation> containerSources() { - return Handlers.getOperation(ContainerSource.class, ContainerSourceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ContainerSource.class, ContainerSourceList.class, this); } @Override public MixedOperation> apiServerSources() { - return Handlers.getOperation(ApiServerSource.class, ApiServerSourceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ApiServerSource.class, ApiServerSourceList.class, this); } @Override public MixedOperation> awsSqsSources() { - return Handlers.getOperation(AwsSqsSource.class, AwsSqsSourceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(AwsSqsSource.class, AwsSqsSourceList.class, this); } @Override public MixedOperation> couchDbSources() { - return Handlers.getOperation(CouchDbSource.class, CouchDbSourceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(CouchDbSource.class, CouchDbSourceList.class, this); } @Override public MixedOperation> gitHubSources() { - return Handlers.getOperation(GitHubSource.class, GitHubSourceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(GitHubSource.class, GitHubSourceList.class, this); } @Override public MixedOperation> gitHubBindings() { - return Handlers.getOperation(GitHubBinding.class, GitHubBindingList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(GitHubBinding.class, GitHubBindingList.class, this); } @Override public MixedOperation> gitLabSources() { - return Handlers.getOperation(GitLabSource.class, GitLabSourceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(GitLabSource.class, GitLabSourceList.class, this); } @Override public MixedOperation> gitLabBindings() { - return Handlers.getOperation(GitLabBinding.class, GitLabBindingList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(GitLabBinding.class, GitLabBindingList.class, this); } @Override public MixedOperation> prometheusSources() { - return Handlers.getOperation(PrometheusSource.class, PrometheusSourceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(PrometheusSource.class, PrometheusSourceList.class, this); } @Override public MixedOperation> kafkaChannels() { - return Handlers.getOperation(KafkaChannel.class, KafkaChannelList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(KafkaChannel.class, KafkaChannelList.class, this); } @Override public MixedOperation> kafkasSources() { - return Handlers.getOperation(KafkaSource.class, KafkaSourceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(KafkaSource.class, KafkaSourceList.class, this); } @Override public MixedOperation> kafkaBindings() { - return Handlers.getOperation(KafkaBinding.class, KafkaBindingList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(KafkaBinding.class, KafkaBindingList.class, this); } } diff --git a/extensions/knative/client/src/main/java/io/fabric8/knative/client/KnativeExtensionAdapter.java b/extensions/knative/client/src/main/java/io/fabric8/knative/client/KnativeExtensionAdapter.java index ef70966393d..306b5e7e6b9 100644 --- a/extensions/knative/client/src/main/java/io/fabric8/knative/client/KnativeExtensionAdapter.java +++ b/extensions/knative/client/src/main/java/io/fabric8/knative/client/KnativeExtensionAdapter.java @@ -15,10 +15,9 @@ */ package io.fabric8.knative.client; -import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.ExtensionAdapter; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import java.net.URL; import java.util.concurrent.ConcurrentHashMap; @@ -28,7 +27,7 @@ public class KnativeExtensionAdapter extends ExtensionAdapterSupport implements static final ConcurrentMap IS_TEKTON = new ConcurrentHashMap<>(); static final ConcurrentMap USES_TEKTON_APIGROUPS = new ConcurrentHashMap<>(); - + @Override public Class getExtensionType() { return KnativeClient.class; @@ -41,6 +40,6 @@ public Boolean isAdaptable(Client client) { @Override public KnativeClient adapt(Client client) { - return new DefaultKnativeClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DefaultKnativeClient(client); } } diff --git a/extensions/knative/client/src/main/java/io/fabric8/knative/client/serving/v1/DefaultServingV1Client.java b/extensions/knative/client/src/main/java/io/fabric8/knative/client/serving/v1/DefaultServingV1Client.java index aaec2b41309..fd06263874b 100644 --- a/extensions/knative/client/src/main/java/io/fabric8/knative/client/serving/v1/DefaultServingV1Client.java +++ b/extensions/knative/client/src/main/java/io/fabric8/knative/client/serving/v1/DefaultServingV1Client.java @@ -15,7 +15,16 @@ */ package io.fabric8.knative.client.serving.v1; +import io.fabric8.knative.serving.v1.Configuration; +import io.fabric8.knative.serving.v1.ConfigurationList; +import io.fabric8.knative.serving.v1.Revision; +import io.fabric8.knative.serving.v1.RevisionList; +import io.fabric8.knative.serving.v1.Route; +import io.fabric8.knative.serving.v1.RouteList; +import io.fabric8.knative.serving.v1.Service; +import io.fabric8.knative.serving.v1.ServiceList; import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.Handlers; @@ -24,8 +33,6 @@ import io.fabric8.kubernetes.client.dsl.FunctionCallable; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import io.fabric8.knative.serving.v1.*; -import okhttp3.OkHttpClient; public class DefaultServingV1Client extends BaseClient implements NamespacedServingV1Client { @@ -37,8 +44,8 @@ public DefaultServingV1Client(Config configuration) { super(configuration); } - public DefaultServingV1Client(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public DefaultServingV1Client(ClientContext clientContext) { + super(clientContext); } @Override @@ -50,7 +57,7 @@ public NamespacedServingV1Client inAnyNamespace() { public NamespacedServingV1Client inNamespace(String namespace) { Config updated = new ConfigBuilder(getConfiguration()).withNamespace(namespace).build(); - return new DefaultServingV1Client(getHttpClient(), updated); + return new DefaultServingV1Client(newState(updated)); } @Override @@ -60,22 +67,22 @@ public FunctionCallable withRequestConfig(RequestConf @Override public MixedOperation> services() { - return Handlers.getOperation(Service.class, ServiceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Service.class, ServiceList.class, this); } @Override public MixedOperation> routes() { - return Handlers.getOperation(Route.class, RouteList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Route.class, RouteList.class, this); } @Override public MixedOperation> revisions() { - return Handlers.getOperation(Revision.class, RevisionList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Revision.class, RevisionList.class, this); } @Override public MixedOperation> configurations() { - return Handlers.getOperation(Configuration.class, ConfigurationList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Configuration.class, ConfigurationList.class, this); } } diff --git a/extensions/knative/client/src/main/java/io/fabric8/knative/client/serving/v1/ServingV1ExtensionAdapter.java b/extensions/knative/client/src/main/java/io/fabric8/knative/client/serving/v1/ServingV1ExtensionAdapter.java index 66fd421a572..b549cc5ea06 100644 --- a/extensions/knative/client/src/main/java/io/fabric8/knative/client/serving/v1/ServingV1ExtensionAdapter.java +++ b/extensions/knative/client/src/main/java/io/fabric8/knative/client/serving/v1/ServingV1ExtensionAdapter.java @@ -15,10 +15,9 @@ */ package io.fabric8.knative.client.serving.v1; -import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.ExtensionAdapter; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import java.net.URL; import java.util.concurrent.ConcurrentHashMap; @@ -28,7 +27,7 @@ public class ServingV1ExtensionAdapter extends ExtensionAdapterSupport implement static final ConcurrentMap IS_KNATIVE = new ConcurrentHashMap<>(); static final ConcurrentMap USES_KNATIVE_APIGROUPS = new ConcurrentHashMap<>(); - + @Override public Class getExtensionType() { return ServingV1Client.class; @@ -41,6 +40,6 @@ public Boolean isAdaptable(Client client) { @Override public ServingV1Client adapt(Client client) { - return new DefaultServingV1Client(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DefaultServingV1Client(client); } } diff --git a/extensions/knative/mock/src/main/java/io/fabric8/knative/mock/KnativeMockServer.java b/extensions/knative/mock/src/main/java/io/fabric8/knative/mock/KnativeMockServer.java index 242a40cf755..c89b3691565 100644 --- a/extensions/knative/mock/src/main/java/io/fabric8/knative/mock/KnativeMockServer.java +++ b/extensions/knative/mock/src/main/java/io/fabric8/knative/mock/KnativeMockServer.java @@ -15,26 +15,20 @@ */ package io.fabric8.knative.mock; +import io.fabric8.knative.client.DefaultKnativeClient; import io.fabric8.knative.client.NamespacedKnativeClient; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import io.fabric8.mockwebserver.Context; import io.fabric8.mockwebserver.ServerRequest; import io.fabric8.mockwebserver.ServerResponse; -import io.fabric8.knative.client.DefaultKnativeClient; -import io.fabric8.knative.client.KnativeClient; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockWebServer; import java.util.Map; import java.util.Queue; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; -import static okhttp3.TlsVersion.TLS_1_2; - public class KnativeMockServer extends KubernetesMockServer { - private boolean disableApiGroupCheck = true; public KnativeMockServer() { super(); @@ -54,12 +48,7 @@ public String[] getRootPaths() { } public NamespacedKnativeClient createKnative() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); - return new DefaultKnativeClient(createHttpClientForMockServer(config), config); + Config config = getMockConfiguration(); + return new DefaultKnativeClient(config); } } diff --git a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/DefaultServiceCatalogClient.java b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/DefaultServiceCatalogClient.java index f260e8f1d92..3409941c0cf 100644 --- a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/DefaultServiceCatalogClient.java +++ b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/DefaultServiceCatalogClient.java @@ -15,14 +15,43 @@ */ package io.fabric8.servicecatalog.client; -import io.fabric8.kubernetes.client.*; +import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ConfigBuilder; +import io.fabric8.kubernetes.client.Handlers; +import io.fabric8.kubernetes.client.RequestConfig; +import io.fabric8.kubernetes.client.WithRequestCallable; import io.fabric8.kubernetes.client.dsl.FunctionCallable; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import io.fabric8.servicecatalog.client.internal.*; -import io.fabric8.servicecatalog.api.model.*; -import okhttp3.OkHttpClient; +import io.fabric8.servicecatalog.api.model.ClusterServiceBroker; +import io.fabric8.servicecatalog.api.model.ClusterServiceBrokerList; +import io.fabric8.servicecatalog.api.model.ClusterServiceClass; +import io.fabric8.servicecatalog.api.model.ClusterServiceClassList; +import io.fabric8.servicecatalog.api.model.ClusterServicePlan; +import io.fabric8.servicecatalog.api.model.ClusterServicePlanList; +import io.fabric8.servicecatalog.api.model.ServiceBinding; +import io.fabric8.servicecatalog.api.model.ServiceBindingList; +import io.fabric8.servicecatalog.api.model.ServiceBroker; +import io.fabric8.servicecatalog.api.model.ServiceBrokerList; +import io.fabric8.servicecatalog.api.model.ServiceClass; +import io.fabric8.servicecatalog.api.model.ServiceClassList; +import io.fabric8.servicecatalog.api.model.ServiceInstance; +import io.fabric8.servicecatalog.api.model.ServiceInstanceList; +import io.fabric8.servicecatalog.api.model.ServicePlan; +import io.fabric8.servicecatalog.api.model.ServicePlanList; +import io.fabric8.servicecatalog.client.internal.ClusterServiceBrokerOperationsImpl; +import io.fabric8.servicecatalog.client.internal.ClusterServiceBrokerResource; +import io.fabric8.servicecatalog.client.internal.ClusterServiceClassOperationsImpl; +import io.fabric8.servicecatalog.client.internal.ClusterServiceClassResource; +import io.fabric8.servicecatalog.client.internal.ClusterServicePlanOperationsImpl; +import io.fabric8.servicecatalog.client.internal.ClusterServicePlanResource; +import io.fabric8.servicecatalog.client.internal.ServiceBindingOperationsImpl; +import io.fabric8.servicecatalog.client.internal.ServiceBindingResource; +import io.fabric8.servicecatalog.client.internal.ServiceInstanceOperationsImpl; +import io.fabric8.servicecatalog.client.internal.ServiceInstanceResource; public class DefaultServiceCatalogClient extends BaseClient implements NamespacedServiceCatalogClient { @@ -34,48 +63,48 @@ public DefaultServiceCatalogClient(Config configuration) { super(configuration); } - public DefaultServiceCatalogClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public DefaultServiceCatalogClient(ClientContext clientContext) { + super(clientContext); } @Override public NonNamespaceOperation clusterServiceBrokers() { - return new ClusterServiceBrokerOperationsImpl(this.getHttpClient(), this.getConfiguration()); + return new ClusterServiceBrokerOperationsImpl(this); } @Override public NonNamespaceOperation clusterServiceClasses() { - return new ClusterServiceClassOperationsImpl(this.getHttpClient(), this.getConfiguration()); + return new ClusterServiceClassOperationsImpl(this); } @Override public NonNamespaceOperation clusterServicePlans() { - return new ClusterServicePlanOperationsImpl(this.getHttpClient(), this.getConfiguration()); + return new ClusterServicePlanOperationsImpl(this); } @Override public MixedOperation serviceInstances() { - return new ServiceInstanceOperationsImpl(this.getHttpClient(), this.getConfiguration()); + return new ServiceInstanceOperationsImpl(this); } @Override public MixedOperation serviceBindings() { - return new ServiceBindingOperationsImpl(this.getHttpClient(), this.getConfiguration()); + return new ServiceBindingOperationsImpl(this); } @Override public MixedOperation> serviceBrokers() { - return Handlers.getOperation(ServiceBroker.class, ServiceBrokerList.class, httpClient, getConfiguration()); + return Handlers.getOperation(ServiceBroker.class, ServiceBrokerList.class, this); } @Override public MixedOperation> serviceClasses() { - return Handlers.getOperation(ServiceClass.class, ServiceClassList.class, httpClient, getConfiguration()); + return Handlers.getOperation(ServiceClass.class, ServiceClassList.class, this); } @Override public MixedOperation> servicePlans() { - return Handlers.getOperation(ServicePlan.class, ServicePlanList.class, httpClient, getConfiguration()); + return Handlers.getOperation(ServicePlan.class, ServicePlanList.class, this); } @Override @@ -89,7 +118,7 @@ public NamespacedServiceCatalogClient inNamespace(String namespace) { .withNamespace(namespace) .build(); - return new DefaultServiceCatalogClient(getHttpClient(), updated); + return new DefaultServiceCatalogClient(newState(updated)); } @Override diff --git a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/ServiceCatalogExtensionAdapter.java b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/ServiceCatalogExtensionAdapter.java index 266de5d0902..f6883e7a15f 100644 --- a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/ServiceCatalogExtensionAdapter.java +++ b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/ServiceCatalogExtensionAdapter.java @@ -19,6 +19,7 @@ import io.fabric8.kubernetes.client.ExtensionAdapter; import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import io.fabric8.kubernetes.client.Handlers; +import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.servicecatalog.api.model.ClusterServiceBroker; import io.fabric8.servicecatalog.api.model.ClusterServiceClass; import io.fabric8.servicecatalog.api.model.ClusterServicePlan; @@ -29,7 +30,6 @@ import io.fabric8.servicecatalog.client.internal.ClusterServicePlanOperationsImpl; import io.fabric8.servicecatalog.client.internal.ServiceBindingOperationsImpl; import io.fabric8.servicecatalog.client.internal.ServiceInstanceOperationsImpl; -import okhttp3.OkHttpClient; import java.net.URL; import java.util.concurrent.ConcurrentHashMap; @@ -60,6 +60,6 @@ public Boolean isAdaptable(Client client) { @Override public ServiceCatalogClient adapt(Client client) { - return new DefaultServiceCatalogClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DefaultServiceCatalogClient(client); } } diff --git a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServiceBrokerOperationsImpl.java b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServiceBrokerOperationsImpl.java index 076beb06356..ca8ab31a4c8 100644 --- a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServiceBrokerOperationsImpl.java +++ b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServiceBrokerOperationsImpl.java @@ -15,12 +15,16 @@ */ package io.fabric8.servicecatalog.client.internal; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; -import io.fabric8.servicecatalog.api.model.*; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; +import io.fabric8.servicecatalog.api.model.ClusterServiceBroker; +import io.fabric8.servicecatalog.api.model.ClusterServiceBrokerList; +import io.fabric8.servicecatalog.api.model.ClusterServiceClass; +import io.fabric8.servicecatalog.api.model.ClusterServiceClassList; +import io.fabric8.servicecatalog.api.model.ClusterServicePlanList; import java.util.HashMap; import java.util.List; @@ -29,8 +33,8 @@ public class ClusterServiceBrokerOperationsImpl extends HasMetadataOperation implements ClusterServiceBrokerResource { - public ClusterServiceBrokerOperationsImpl(OkHttpClient client, Config config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public ClusterServiceBrokerOperationsImpl(ClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public ClusterServiceBrokerOperationsImpl(OperationContext context) { diff --git a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServiceClassOperationsImpl.java b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServiceClassOperationsImpl.java index 37bab0e9d4f..e8186034b60 100644 --- a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServiceClassOperationsImpl.java +++ b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServiceClassOperationsImpl.java @@ -15,12 +15,17 @@ */ package io.fabric8.servicecatalog.client.internal; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; -import io.fabric8.servicecatalog.api.model.*; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; +import io.fabric8.servicecatalog.api.model.ClusterServiceClass; +import io.fabric8.servicecatalog.api.model.ClusterServiceClassList; +import io.fabric8.servicecatalog.api.model.ClusterServicePlan; +import io.fabric8.servicecatalog.api.model.ClusterServicePlanList; +import io.fabric8.servicecatalog.api.model.ServiceInstance; +import io.fabric8.servicecatalog.api.model.ServiceInstanceBuilder; import java.util.HashMap; import java.util.List; @@ -30,8 +35,8 @@ public class ClusterServiceClassOperationsImpl extends HasMetadataOperation implements ClusterServiceClassResource { - public ClusterServiceClassOperationsImpl(OkHttpClient client, Config config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public ClusterServiceClassOperationsImpl(ClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public ClusterServiceClassOperationsImpl(OperationContext ctx) { diff --git a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServicePlanOperationsImpl.java b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServicePlanOperationsImpl.java index 39b6c5eb684..ba5277a78f2 100644 --- a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServicePlanOperationsImpl.java +++ b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ClusterServicePlanOperationsImpl.java @@ -15,19 +15,22 @@ */ package io.fabric8.servicecatalog.client.internal; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; -import io.fabric8.servicecatalog.api.model.*; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; +import io.fabric8.servicecatalog.api.model.ClusterServicePlan; +import io.fabric8.servicecatalog.api.model.ClusterServicePlanList; +import io.fabric8.servicecatalog.api.model.ServiceInstance; +import io.fabric8.servicecatalog.api.model.ServiceInstanceBuilder; public class ClusterServicePlanOperationsImpl extends HasMetadataOperation implements ClusterServicePlanResource { - public ClusterServicePlanOperationsImpl(OkHttpClient client, Config config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public ClusterServicePlanOperationsImpl(ClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public ClusterServicePlanOperationsImpl(OperationContext ctx) { diff --git a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ServiceBindingOperationsImpl.java b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ServiceBindingOperationsImpl.java index d602342fb41..c81fd41f832 100644 --- a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ServiceBindingOperationsImpl.java +++ b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ServiceBindingOperationsImpl.java @@ -17,20 +17,20 @@ import io.fabric8.kubernetes.api.model.Secret; import io.fabric8.kubernetes.api.model.SecretList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.servicecatalog.api.model.ServiceBinding; import io.fabric8.servicecatalog.api.model.ServiceBindingList; -import okhttp3.OkHttpClient; public class ServiceBindingOperationsImpl extends HasMetadataOperation implements ServiceBindingResource { - public ServiceBindingOperationsImpl(OkHttpClient client, Config config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public ServiceBindingOperationsImpl(ClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public ServiceBindingOperationsImpl(OperationContext ctx) { @@ -51,7 +51,7 @@ public boolean isResourceNamespaced() { @Override public Secret getSecret() { ServiceBinding instance = get(); - return Handlers.getOperation(Secret.class, SecretList.class, client, getConfig()) + return Handlers.getOperation(Secret.class, SecretList.class, context) .newInstance(context.withItem(null).withName(instance.getSpec().getSecretName())).get(); } } diff --git a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ServiceInstanceOperationsImpl.java b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ServiceInstanceOperationsImpl.java index 6ae458cfe5d..cdcc51bc478 100644 --- a/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ServiceInstanceOperationsImpl.java +++ b/extensions/service-catalog/client/src/main/java/io/fabric8/servicecatalog/client/internal/ServiceInstanceOperationsImpl.java @@ -15,17 +15,20 @@ */ package io.fabric8.servicecatalog.client.internal; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; -import io.fabric8.servicecatalog.api.model.*; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; +import io.fabric8.servicecatalog.api.model.ServiceBinding; +import io.fabric8.servicecatalog.api.model.ServiceBindingBuilder; +import io.fabric8.servicecatalog.api.model.ServiceInstance; +import io.fabric8.servicecatalog.api.model.ServiceInstanceList; public class ServiceInstanceOperationsImpl extends HasMetadataOperation implements ServiceInstanceResource { - public ServiceInstanceOperationsImpl(OkHttpClient client, Config config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public ServiceInstanceOperationsImpl(ClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public ServiceInstanceOperationsImpl(OperationContext ctx) { diff --git a/extensions/service-catalog/mock/src/main/java/io/fabric8/servicecatalog/server/mock/ServiceCatalogMockServer.java b/extensions/service-catalog/mock/src/main/java/io/fabric8/servicecatalog/server/mock/ServiceCatalogMockServer.java index dbf5b98d23f..183d9f67fb8 100644 --- a/extensions/service-catalog/mock/src/main/java/io/fabric8/servicecatalog/server/mock/ServiceCatalogMockServer.java +++ b/extensions/service-catalog/mock/src/main/java/io/fabric8/servicecatalog/server/mock/ServiceCatalogMockServer.java @@ -16,7 +16,6 @@ package io.fabric8.servicecatalog.server.mock; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import io.fabric8.mockwebserver.Context; import io.fabric8.mockwebserver.ServerRequest; @@ -29,10 +28,7 @@ import java.util.Map; import java.util.Queue; -import static okhttp3.TlsVersion.TLS_1_2; - public class ServiceCatalogMockServer extends KubernetesMockServer { - private boolean disableApiGroupCheck = true; public ServiceCatalogMockServer() { super(); @@ -52,12 +48,7 @@ public String[] getRootPaths() { } public NamespacedServiceCatalogClient createServiceCatalog() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); + Config config = getMockConfiguration(); return new DefaultServiceCatalogClient(config); } } diff --git a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/DefaultTektonClient.java b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/DefaultTektonClient.java index b1d3508df74..737f8cf2983 100644 --- a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/DefaultTektonClient.java +++ b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/DefaultTektonClient.java @@ -15,15 +15,15 @@ */ package io.fabric8.tekton.client; -import io.fabric8.tekton.client.dsl.V1alpha1APIGroupDSL; -import io.fabric8.tekton.client.dsl.V1beta1APIGroupDSL; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; +import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.RequestConfig; import io.fabric8.kubernetes.client.WithRequestCallable; import io.fabric8.kubernetes.client.dsl.FunctionCallable; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.tekton.client.dsl.V1alpha1APIGroupDSL; +import io.fabric8.tekton.client.dsl.V1beta1APIGroupDSL; public class DefaultTektonClient extends BaseClient implements NamespacedTektonClient { @@ -35,8 +35,8 @@ public DefaultTektonClient(Config configuration) { super(configuration); } - public DefaultTektonClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public DefaultTektonClient(ClientContext clientContext) { + super(clientContext); } @Override @@ -50,7 +50,7 @@ public NamespacedTektonClient inNamespace(String namespace) { .withNamespace(namespace) .build(); - return new DefaultTektonClient(getHttpClient(), updated); + return new DefaultTektonClient(newState(updated)); } @Override diff --git a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/TektonExtensionAdapter.java b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/TektonExtensionAdapter.java index b0c4643be43..cd27cb24a2c 100644 --- a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/TektonExtensionAdapter.java +++ b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/TektonExtensionAdapter.java @@ -15,20 +15,19 @@ */ package io.fabric8.tekton.client; -import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.ExtensionAdapter; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import java.net.URL; -import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; public class TektonExtensionAdapter extends ExtensionAdapterSupport implements ExtensionAdapter { static final ConcurrentMap IS_TEKTON = new ConcurrentHashMap<>(); static final ConcurrentMap USES_TEKTON_APIGROUPS = new ConcurrentHashMap<>(); - + @Override public Class getExtensionType() { return TektonClient.class; @@ -41,6 +40,6 @@ public Boolean isAdaptable(Client client) { @Override public TektonClient adapt(Client client) { - return new DefaultTektonClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DefaultTektonClient(client); } } diff --git a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1alpha1APIGroupClient.java b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1alpha1APIGroupClient.java index 3f514ec5092..bf3198b481d 100644 --- a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1alpha1APIGroupClient.java +++ b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1alpha1APIGroupClient.java @@ -16,89 +16,110 @@ package io.fabric8.tekton.client; import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.tekton.client.dsl.V1alpha1APIGroupDSL; -import io.fabric8.tekton.pipeline.v1alpha1.*; +import io.fabric8.tekton.pipeline.v1alpha1.ClusterTask; +import io.fabric8.tekton.pipeline.v1alpha1.ClusterTaskList; +import io.fabric8.tekton.pipeline.v1alpha1.Condition; +import io.fabric8.tekton.pipeline.v1alpha1.ConditionList; +import io.fabric8.tekton.pipeline.v1alpha1.Pipeline; +import io.fabric8.tekton.pipeline.v1alpha1.PipelineList; +import io.fabric8.tekton.pipeline.v1alpha1.PipelineRun; +import io.fabric8.tekton.pipeline.v1alpha1.PipelineRunList; +import io.fabric8.tekton.pipeline.v1alpha1.Task; +import io.fabric8.tekton.pipeline.v1alpha1.TaskList; +import io.fabric8.tekton.pipeline.v1alpha1.TaskRun; +import io.fabric8.tekton.pipeline.v1alpha1.TaskRunList; import io.fabric8.tekton.resource.v1alpha1.PipelineResource; import io.fabric8.tekton.resource.v1alpha1.PipelineResourceList; -import io.fabric8.tekton.triggers.v1alpha1.*; -import okhttp3.OkHttpClient; +import io.fabric8.tekton.triggers.v1alpha1.ClusterInterceptor; +import io.fabric8.tekton.triggers.v1alpha1.ClusterInterceptorList; +import io.fabric8.tekton.triggers.v1alpha1.ClusterTriggerBinding; +import io.fabric8.tekton.triggers.v1alpha1.ClusterTriggerBindingList; +import io.fabric8.tekton.triggers.v1alpha1.EventListener; +import io.fabric8.tekton.triggers.v1alpha1.EventListenerList; +import io.fabric8.tekton.triggers.v1alpha1.Trigger; +import io.fabric8.tekton.triggers.v1alpha1.TriggerBinding; +import io.fabric8.tekton.triggers.v1alpha1.TriggerBindingList; +import io.fabric8.tekton.triggers.v1alpha1.TriggerList; +import io.fabric8.tekton.triggers.v1alpha1.TriggerTemplate; +import io.fabric8.tekton.triggers.v1alpha1.TriggerTemplateList; public class V1alpha1APIGroupClient extends BaseClient implements V1alpha1APIGroupDSL { public V1alpha1APIGroupClient() { super(); } - public V1alpha1APIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1alpha1APIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> pipelines() { - return Handlers.getOperation(Pipeline.class, PipelineList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Pipeline.class, PipelineList.class, this); } @Override public MixedOperation> pipelineRuns() { - return Handlers.getOperation(PipelineRun.class, PipelineRunList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(PipelineRun.class, PipelineRunList.class, this); } @Override public MixedOperation> pipelineResources() { - return Handlers.getOperation(PipelineResource.class, PipelineResourceList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(PipelineResource.class, PipelineResourceList.class, this); } @Override public MixedOperation> tasks() { - return Handlers.getOperation(Task.class, TaskList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Task.class, TaskList.class, this); } @Override public MixedOperation> taskRuns() { - return Handlers.getOperation(TaskRun.class, TaskRunList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(TaskRun.class, TaskRunList.class, this); } @Override public MixedOperation> conditions() { - return Handlers.getOperation(Condition.class, ConditionList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Condition.class, ConditionList.class, this); } @Override public MixedOperation> triggerTemplates() { - return Handlers.getOperation(TriggerTemplate.class, TriggerTemplateList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(TriggerTemplate.class, TriggerTemplateList.class, this); } @Override public MixedOperation> triggerBindings() { - return Handlers.getOperation(TriggerBinding.class, TriggerBindingList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(TriggerBinding.class, TriggerBindingList.class, this); } @Override public MixedOperation> triggers() { - return Handlers.getOperation(Trigger.class, TriggerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Trigger.class, TriggerList.class, this); } @Override public MixedOperation> eventListeners() { - return Handlers.getOperation(EventListener.class, EventListenerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(EventListener.class, EventListenerList.class, this); } @Override public NonNamespaceOperation> clusterTasks() { - return Handlers.getOperation(ClusterTask.class, ClusterTaskList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ClusterTask.class, ClusterTaskList.class, this); } @Override public NonNamespaceOperation> clusterTriggerBindings() { - return Handlers.getOperation(ClusterTriggerBinding.class, ClusterTriggerBindingList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ClusterTriggerBinding.class, ClusterTriggerBindingList.class, this); } @Override public NonNamespaceOperation> clusterInterceptors() { - return Handlers.getOperation(ClusterInterceptor.class, ClusterInterceptorList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ClusterInterceptor.class, ClusterInterceptorList.class, this); } } diff --git a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1alpha1APIGroupExtensionAdapter.java b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1alpha1APIGroupExtensionAdapter.java index 2948772ee3c..796f0e76281 100644 --- a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1alpha1APIGroupExtensionAdapter.java +++ b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1alpha1APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1alpha1APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1alpha1APIGroupClient newInstance(Client client) { - return new V1alpha1APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1alpha1APIGroupClient(client); } } diff --git a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1beta1APIGroupClient.java b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1beta1APIGroupClient.java index 213ccd1330b..091eaba4673 100644 --- a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1beta1APIGroupClient.java +++ b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1beta1APIGroupClient.java @@ -16,7 +16,7 @@ package io.fabric8.tekton.client; import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; @@ -32,39 +32,38 @@ import io.fabric8.tekton.pipeline.v1beta1.TaskList; import io.fabric8.tekton.pipeline.v1beta1.TaskRun; import io.fabric8.tekton.pipeline.v1beta1.TaskRunList; -import okhttp3.OkHttpClient; public class V1beta1APIGroupClient extends BaseClient implements V1beta1APIGroupDSL { public V1beta1APIGroupClient() { super(); } - public V1beta1APIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1APIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> pipelines() { - return Handlers.getOperation(Pipeline.class, PipelineList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Pipeline.class, PipelineList.class, this); } @Override public MixedOperation> pipelineRuns() { - return Handlers.getOperation(PipelineRun.class, PipelineRunList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(PipelineRun.class, PipelineRunList.class, this); } @Override public MixedOperation> tasks() { - return Handlers.getOperation(Task.class, TaskList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Task.class, TaskList.class, this); } @Override public MixedOperation> taskRuns() { - return Handlers.getOperation(TaskRun.class, TaskRunList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(TaskRun.class, TaskRunList.class, this); } @Override public NonNamespaceOperation> clusterTasks() { - return Handlers.getOperation(ClusterTask.class, ClusterTaskList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(ClusterTask.class, ClusterTaskList.class, this); } } diff --git a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1beta1APIGroupExtensionAdapter.java b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1beta1APIGroupExtensionAdapter.java index ea1e974b17d..f8ef9d94b1b 100644 --- a/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1beta1APIGroupExtensionAdapter.java +++ b/extensions/tekton/client/src/main/java/io/fabric8/tekton/client/V1beta1APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1beta1APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1beta1APIGroupClient newInstance(Client client) { - return new V1beta1APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1APIGroupClient(client); } } diff --git a/extensions/tekton/mock/src/main/java/io/fabric8/tekton/mock/TektonMockServer.java b/extensions/tekton/mock/src/main/java/io/fabric8/tekton/mock/TektonMockServer.java index 6669c5133e5..dfa20bc6a27 100644 --- a/extensions/tekton/mock/src/main/java/io/fabric8/tekton/mock/TektonMockServer.java +++ b/extensions/tekton/mock/src/main/java/io/fabric8/tekton/mock/TektonMockServer.java @@ -16,7 +16,6 @@ package io.fabric8.tekton.mock; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import io.fabric8.mockwebserver.Context; import io.fabric8.mockwebserver.ServerRequest; @@ -29,11 +28,7 @@ import java.util.Map; import java.util.Queue; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; -import static okhttp3.TlsVersion.TLS_1_2; - public class TektonMockServer extends KubernetesMockServer { - private boolean disableApiGroupCheck = true; public TektonMockServer() { super(); @@ -53,12 +48,7 @@ public String[] getRootPaths() { } public NamespacedTektonClient createTekton() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); - return new DefaultTektonClient(createHttpClientForMockServer(config), config); + Config config = getMockConfiguration(); + return new DefaultTektonClient(config); } } diff --git a/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/DefaultVerticalPodAutoscalerClient.java b/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/DefaultVerticalPodAutoscalerClient.java index d2a44cb06d6..bcdefaa975b 100644 --- a/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/DefaultVerticalPodAutoscalerClient.java +++ b/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/DefaultVerticalPodAutoscalerClient.java @@ -15,10 +15,14 @@ */ package io.fabric8.verticalpodautoscaler.client; -import io.fabric8.verticalpodautoscaler.client.dsl.V1APIGroupDSL; -import io.fabric8.kubernetes.client.*; +import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ConfigBuilder; +import io.fabric8.kubernetes.client.RequestConfig; +import io.fabric8.kubernetes.client.WithRequestCallable; import io.fabric8.kubernetes.client.dsl.FunctionCallable; -import okhttp3.OkHttpClient; +import io.fabric8.verticalpodautoscaler.client.dsl.V1APIGroupDSL; public class DefaultVerticalPodAutoscalerClient extends BaseClient implements NamespacedVerticalPodAutoscalerClient { @@ -30,8 +34,8 @@ public DefaultVerticalPodAutoscalerClient(Config configuration) { super(configuration); } - public DefaultVerticalPodAutoscalerClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public DefaultVerticalPodAutoscalerClient(ClientContext clientContext) { + super(clientContext); } @Override @@ -45,7 +49,7 @@ public NamespacedVerticalPodAutoscalerClient inNamespace(String namespace) { .withNamespace(namespace) .build(); - return new DefaultVerticalPodAutoscalerClient(getHttpClient(), updated); + return new DefaultVerticalPodAutoscalerClient(newState(updated)); } @Override diff --git a/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/V1APIGroupClient.java b/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/V1APIGroupClient.java index ce0763fbbfc..883db921f08 100644 --- a/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/V1APIGroupClient.java +++ b/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/V1APIGroupClient.java @@ -16,31 +16,30 @@ package io.fabric8.verticalpodautoscaler.client; import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import io.fabric8.verticalpodautoscaler.client.dsl.V1APIGroupDSL; import io.fabric8.verticalpodautoscaler.api.model.v1.VerticalPodAutoscaler; import io.fabric8.verticalpodautoscaler.api.model.v1.VerticalPodAutoscalerCheckpoint; import io.fabric8.verticalpodautoscaler.api.model.v1.VerticalPodAutoscalerCheckpointList; import io.fabric8.verticalpodautoscaler.api.model.v1.VerticalPodAutoscalerList; -import okhttp3.OkHttpClient; +import io.fabric8.verticalpodautoscaler.client.dsl.V1APIGroupDSL; public class V1APIGroupClient extends BaseClient implements V1APIGroupDSL { public V1APIGroupClient() {super();} - public V1APIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1APIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> verticalpodautoscalers() { - return Handlers.getOperation(VerticalPodAutoscaler.class, VerticalPodAutoscalerList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(VerticalPodAutoscaler.class, VerticalPodAutoscalerList.class, this); } @Override public MixedOperation> verticalpodautoscalercheckpoints() { - return Handlers.getOperation(VerticalPodAutoscalerCheckpoint.class, VerticalPodAutoscalerCheckpointList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(VerticalPodAutoscalerCheckpoint.class, VerticalPodAutoscalerCheckpointList.class, this); } } diff --git a/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/V1APIGroupExtensionAdapter.java b/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/V1APIGroupExtensionAdapter.java index ac8f8f15d97..84b230fe333 100644 --- a/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/V1APIGroupExtensionAdapter.java +++ b/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/V1APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1APIGroupClient newInstance(Client client) { - return new V1APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1APIGroupClient(client); } } diff --git a/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/VerticalPodAutoscalerExtensionAdapter.java b/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/VerticalPodAutoscalerExtensionAdapter.java index 6a5a439f92e..b3bbbab42e4 100644 --- a/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/VerticalPodAutoscalerExtensionAdapter.java +++ b/extensions/verticalpodautoscaler/client/src/main/java/io/fabric8/verticalpodautoscaler/client/VerticalPodAutoscalerExtensionAdapter.java @@ -18,7 +18,6 @@ import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.ExtensionAdapter; import io.fabric8.kubernetes.client.ExtensionAdapterSupport; -import okhttp3.OkHttpClient; import java.net.URL; import java.util.concurrent.ConcurrentHashMap; @@ -42,6 +41,6 @@ public Boolean isAdaptable(Client client) { @Override public VerticalPodAutoscalerClient adapt(Client client) { - return new DefaultVerticalPodAutoscalerClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DefaultVerticalPodAutoscalerClient(client); } } diff --git a/extensions/verticalpodautoscaler/mock/src/main/java/io/fabric8/verticalpodautoscaler/server/mock/VerticalPodAutoscalerMockServer.java b/extensions/verticalpodautoscaler/mock/src/main/java/io/fabric8/verticalpodautoscaler/server/mock/VerticalPodAutoscalerMockServer.java index bce4606edb9..498a793c844 100644 --- a/extensions/verticalpodautoscaler/mock/src/main/java/io/fabric8/verticalpodautoscaler/server/mock/VerticalPodAutoscalerMockServer.java +++ b/extensions/verticalpodautoscaler/mock/src/main/java/io/fabric8/verticalpodautoscaler/server/mock/VerticalPodAutoscalerMockServer.java @@ -15,23 +15,19 @@ */ package io.fabric8.verticalpodautoscaler.server.mock; -import io.fabric8.verticalpodautoscaler.client.NamespacedVerticalPodAutoscalerClient; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import io.fabric8.mockwebserver.Context; import io.fabric8.mockwebserver.ServerRequest; import io.fabric8.mockwebserver.ServerResponse; import io.fabric8.verticalpodautoscaler.client.DefaultVerticalPodAutoscalerClient; +import io.fabric8.verticalpodautoscaler.client.NamespacedVerticalPodAutoscalerClient; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockWebServer; import java.util.Map; import java.util.Queue; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; -import static okhttp3.TlsVersion.TLS_1_2; - public class VerticalPodAutoscalerMockServer extends KubernetesMockServer { public VerticalPodAutoscalerMockServer() { @@ -52,12 +48,7 @@ public String[] getRootPaths() { } public NamespacedVerticalPodAutoscalerClient createVerticalPodAutoscaler() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); - return new DefaultVerticalPodAutoscalerClient(createHttpClientForMockServer(config), config); + Config config = getMockConfiguration(); + return new DefaultVerticalPodAutoscalerClient(config); } } diff --git a/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/DefaultVolcanoClient.java b/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/DefaultVolcanoClient.java index 69276024aab..8836bc73347 100644 --- a/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/DefaultVolcanoClient.java +++ b/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/DefaultVolcanoClient.java @@ -15,7 +15,13 @@ */ package io.fabric8.volcano.client; -import io.fabric8.kubernetes.client.*; +import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ConfigBuilder; +import io.fabric8.kubernetes.client.Handlers; +import io.fabric8.kubernetes.client.RequestConfig; +import io.fabric8.kubernetes.client.WithRequestCallable; import io.fabric8.kubernetes.client.dsl.FunctionCallable; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; @@ -24,7 +30,6 @@ import io.fabric8.volcano.scheduling.v1beta1.PodGroupList; import io.fabric8.volcano.scheduling.v1beta1.Queue; import io.fabric8.volcano.scheduling.v1beta1.QueueList; -import okhttp3.OkHttpClient; public class DefaultVolcanoClient extends BaseClient implements NamespacedVolcanoClient { @@ -36,8 +41,8 @@ public DefaultVolcanoClient(Config configuration) { super(configuration); } - public DefaultVolcanoClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public DefaultVolcanoClient(ClientContext clientContext) { + super(clientContext); } @Override @@ -50,7 +55,7 @@ public NamespacedVolcanoClient inNamespace(String namespace) { Config updated = new ConfigBuilder(getConfiguration()) .withNamespace(namespace) .build(); - return new DefaultVolcanoClient(getHttpClient(), updated); + return new DefaultVolcanoClient(newState(updated)); } @Override @@ -61,13 +66,13 @@ public FunctionCallable withRequestConfig(RequestConfig @Override public MixedOperation> podGroups() { // By default, client.podGroups() use v1beta1 version, - return Handlers.getOperation(PodGroup.class, PodGroupList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(PodGroup.class, PodGroupList.class, this); } @Override public MixedOperation> queues() { // By default, client.podGroups() use v1beta1 version, - return Handlers.getOperation(Queue.class, QueueList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Queue.class, QueueList.class, this); } diff --git a/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/V1beta1APIGroupClient.java b/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/V1beta1APIGroupClient.java index 76cae553f78..d54898c1e25 100644 --- a/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/V1beta1APIGroupClient.java +++ b/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/V1beta1APIGroupClient.java @@ -16,7 +16,7 @@ package io.fabric8.volcano.client; import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; @@ -25,21 +25,20 @@ import io.fabric8.volcano.scheduling.v1beta1.PodGroupList; import io.fabric8.volcano.scheduling.v1beta1.Queue; import io.fabric8.volcano.scheduling.v1beta1.QueueList; -import okhttp3.OkHttpClient; public class V1beta1APIGroupClient extends BaseClient implements V1beta1APIGroupDSL { - public V1beta1APIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1APIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> podGroups() { - return Handlers.getOperation(PodGroup.class, PodGroupList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(PodGroup.class, PodGroupList.class, this); } @Override public MixedOperation> queues() { - return Handlers.getOperation(Queue.class, QueueList.class, this.getHttpClient(), this.getConfiguration()); + return Handlers.getOperation(Queue.class, QueueList.class, this); } } diff --git a/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/V1beta1APIGroupExtensionAdapter.java b/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/V1beta1APIGroupExtensionAdapter.java index ae08e4fb659..199ffd6d635 100644 --- a/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/V1beta1APIGroupExtensionAdapter.java +++ b/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/V1beta1APIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1beta1APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1beta1APIGroupClient newInstance(Client client) { - return new V1beta1APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1APIGroupClient(client); } } diff --git a/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/VolcanoExtensionAdapter.java b/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/VolcanoExtensionAdapter.java index 6c91d7666a1..885e01cb412 100644 --- a/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/VolcanoExtensionAdapter.java +++ b/extensions/volcano/client/src/main/java/io/fabric8/volcano/client/VolcanoExtensionAdapter.java @@ -18,7 +18,6 @@ import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.ExtensionAdapter; import io.fabric8.kubernetes.client.ExtensionAdapterSupport; -import okhttp3.OkHttpClient; import java.net.URL; import java.util.concurrent.ConcurrentHashMap; @@ -42,6 +41,6 @@ public Boolean isAdaptable(Client client) { @Override public VolcanoClient adapt(Client client) { - return new DefaultVolcanoClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DefaultVolcanoClient(client); } } diff --git a/extensions/volcano/mock/src/main/java/io/fabric8/volcano/server/mock/VolcanoMockServer.java b/extensions/volcano/mock/src/main/java/io/fabric8/volcano/server/mock/VolcanoMockServer.java index 1d5d43c89c2..9c0eb0e3b2b 100644 --- a/extensions/volcano/mock/src/main/java/io/fabric8/volcano/server/mock/VolcanoMockServer.java +++ b/extensions/volcano/mock/src/main/java/io/fabric8/volcano/server/mock/VolcanoMockServer.java @@ -15,23 +15,19 @@ */ package io.fabric8.volcano.server.mock; -import io.fabric8.volcano.client.NamespacedVolcanoClient; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import io.fabric8.mockwebserver.Context; import io.fabric8.mockwebserver.ServerRequest; import io.fabric8.mockwebserver.ServerResponse; import io.fabric8.volcano.client.DefaultVolcanoClient; +import io.fabric8.volcano.client.NamespacedVolcanoClient; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockWebServer; import java.util.Map; import java.util.Queue; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; -import static okhttp3.TlsVersion.TLS_1_2; - public class VolcanoMockServer extends KubernetesMockServer { public VolcanoMockServer() { @@ -52,12 +48,7 @@ public String[] getRootPaths() { } public NamespacedVolcanoClient createVolcano() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); - return new DefaultVolcanoClient(createHttpClientForMockServer(config), config); + Config config = getMockConfiguration(); + return new DefaultVolcanoClient(config); } } diff --git a/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/DefaultVolumeSnapshotClient.java b/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/DefaultVolumeSnapshotClient.java index 9527ffe547c..2d76be86325 100644 --- a/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/DefaultVolumeSnapshotClient.java +++ b/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/DefaultVolumeSnapshotClient.java @@ -16,6 +16,7 @@ package io.fabric8.volumesnapshot.client; import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.RequestConfig; @@ -35,7 +36,6 @@ import io.fabric8.volumesnapshot.client.internal.VolumeSnapshotContentResource; import io.fabric8.volumesnapshot.client.internal.VolumeSnapshotOperationsImpl; import io.fabric8.volumesnapshot.client.internal.VolumeSnapshotResource; -import okhttp3.OkHttpClient; public class DefaultVolumeSnapshotClient extends BaseClient implements NamespacedVolumeSnapshotClient { @@ -47,20 +47,23 @@ public DefaultVolumeSnapshotClient(Config configuration) { super(configuration); } - public DefaultVolumeSnapshotClient(OkHttpClient httpClient, Config configuration) { - super(httpClient, configuration); + public DefaultVolumeSnapshotClient(ClientContext clientContext) { + super(clientContext); } - public NonNamespaceOperation volumeSnapshotClasses() { - return new VolumeSnapshotClassOperationsImpl(this.getHttpClient(), this.getConfiguration()); + @Override +public NonNamespaceOperation volumeSnapshotClasses() { + return new VolumeSnapshotClassOperationsImpl(this); } - public NonNamespaceOperation volumeSnapshotContents() { - return new VolumeSnapshotContentOperationsImpl(this.getHttpClient(), this.getConfiguration()); + @Override +public NonNamespaceOperation volumeSnapshotContents() { + return new VolumeSnapshotContentOperationsImpl(this); } - public MixedOperation volumeSnapshots() { - return new VolumeSnapshotOperationsImpl(this.getHttpClient(), this.getConfiguration()); + @Override +public MixedOperation volumeSnapshots() { + return new VolumeSnapshotOperationsImpl(this); } @Override @@ -74,7 +77,7 @@ public NamespacedVolumeSnapshotClient inNamespace(String namespace) { .withNamespace(namespace) .build(); - return new DefaultVolumeSnapshotClient(getHttpClient(), updated); + return new DefaultVolumeSnapshotClient(newState(updated)); } @Override diff --git a/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/VolumeSnapshotExtensionAdapter.java b/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/VolumeSnapshotExtensionAdapter.java index d5b1fdf0514..f2a20c2fdf9 100644 --- a/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/VolumeSnapshotExtensionAdapter.java +++ b/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/VolumeSnapshotExtensionAdapter.java @@ -19,13 +19,13 @@ import io.fabric8.kubernetes.client.ExtensionAdapter; import io.fabric8.kubernetes.client.ExtensionAdapterSupport; import io.fabric8.kubernetes.client.Handlers; +import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.volumesnapshot.api.model.VolumeSnapshot; import io.fabric8.volumesnapshot.api.model.VolumeSnapshotClass; import io.fabric8.volumesnapshot.api.model.VolumeSnapshotContent; import io.fabric8.volumesnapshot.client.internal.VolumeSnapshotClassOperationsImpl; import io.fabric8.volumesnapshot.client.internal.VolumeSnapshotContentOperationsImpl; import io.fabric8.volumesnapshot.client.internal.VolumeSnapshotOperationsImpl; -import okhttp3.OkHttpClient; import java.net.URL; import java.util.concurrent.ConcurrentHashMap; @@ -55,7 +55,7 @@ public Boolean isAdaptable(Client client) { @Override public VolumeSnapshotClient adapt(Client client) { - return new DefaultVolumeSnapshotClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DefaultVolumeSnapshotClient(client); } } diff --git a/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotClassOperationsImpl.java b/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotClassOperationsImpl.java index 5d38c94c03a..6ef8a314cca 100644 --- a/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotClassOperationsImpl.java +++ b/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotClassOperationsImpl.java @@ -16,15 +16,15 @@ package io.fabric8.volumesnapshot.client.internal; import io.fabric8.kubernetes.api.builder.Visitor; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.volumesnapshot.api.model.VolumeSnapshotClass; import io.fabric8.volumesnapshot.api.model.VolumeSnapshotClassBuilder; import io.fabric8.volumesnapshot.api.model.VolumeSnapshotClassList; import io.fabric8.volumesnapshot.api.model.VolumeSnapshotList; -import okhttp3.OkHttpClient; import java.util.HashMap; import java.util.Map; @@ -32,8 +32,8 @@ public class VolumeSnapshotClassOperationsImpl extends HasMetadataOperation implements VolumeSnapshotClassResource { - public VolumeSnapshotClassOperationsImpl(OkHttpClient client, Config config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public VolumeSnapshotClassOperationsImpl(ClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public VolumeSnapshotClassOperationsImpl(OperationContext context) { diff --git a/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotContentOperationsImpl.java b/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotContentOperationsImpl.java index 332eed3b771..b878647435d 100644 --- a/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotContentOperationsImpl.java +++ b/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotContentOperationsImpl.java @@ -16,20 +16,20 @@ package io.fabric8.volumesnapshot.client.internal; import io.fabric8.kubernetes.api.builder.Visitor; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.volumesnapshot.api.model.VolumeSnapshotContent; import io.fabric8.volumesnapshot.api.model.VolumeSnapshotContentBuilder; import io.fabric8.volumesnapshot.api.model.VolumeSnapshotContentList; -import okhttp3.OkHttpClient; public class VolumeSnapshotContentOperationsImpl extends HasMetadataOperation implements VolumeSnapshotContentResource { - public VolumeSnapshotContentOperationsImpl(OkHttpClient client, Config config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public VolumeSnapshotContentOperationsImpl(ClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public VolumeSnapshotContentOperationsImpl(OperationContext context) { diff --git a/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotOperationsImpl.java b/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotOperationsImpl.java index ef87b3e8828..22f1a355bd2 100644 --- a/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotOperationsImpl.java +++ b/extensions/volumesnapshot/client/src/main/java/io/fabric8/volumesnapshot/client/internal/VolumeSnapshotOperationsImpl.java @@ -15,18 +15,18 @@ */ package io.fabric8.volumesnapshot.client.internal; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.volumesnapshot.api.model.VolumeSnapshot; import io.fabric8.volumesnapshot.api.model.VolumeSnapshotList; -import okhttp3.OkHttpClient; public class VolumeSnapshotOperationsImpl extends HasMetadataOperation implements VolumeSnapshotResource { - public VolumeSnapshotOperationsImpl(OkHttpClient client, Config config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public VolumeSnapshotOperationsImpl(ClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public VolumeSnapshotOperationsImpl(OperationContext ctx) { diff --git a/extensions/volumesnapshot/mock/src/main/java/io/fabric8/volumesnapshot/server/mock/VolumeSnapshotMockServer.java b/extensions/volumesnapshot/mock/src/main/java/io/fabric8/volumesnapshot/server/mock/VolumeSnapshotMockServer.java index f4ff6d43f70..817b4729968 100644 --- a/extensions/volumesnapshot/mock/src/main/java/io/fabric8/volumesnapshot/server/mock/VolumeSnapshotMockServer.java +++ b/extensions/volumesnapshot/mock/src/main/java/io/fabric8/volumesnapshot/server/mock/VolumeSnapshotMockServer.java @@ -16,7 +16,6 @@ package io.fabric8.volumesnapshot.server.mock; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import io.fabric8.mockwebserver.Context; import io.fabric8.mockwebserver.ServerRequest; @@ -29,8 +28,6 @@ import java.util.Map; import java.util.Queue; -import static okhttp3.TlsVersion.TLS_1_2; - public class VolumeSnapshotMockServer extends KubernetesMockServer { public VolumeSnapshotMockServer() { super(); @@ -50,13 +47,7 @@ public String[] getRootPaths() { } public NamespacedVolumeSnapshotClient createVolumeSnapshot() { - // FIXME - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); + Config config = getMockConfiguration(); return new DefaultVolumeSnapshotClient(config); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/APIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/APIGroupExtensionAdapter.java index 3bead729e24..1c037ce03a2 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/APIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/APIGroupExtensionAdapter.java @@ -15,10 +15,6 @@ */ package io.fabric8.kubernetes.client; -import io.fabric8.kubernetes.api.model.RootPaths; - -import java.util.List; - public abstract class APIGroupExtensionAdapter implements ExtensionAdapter { abstract protected String getAPIGroupName(); diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Adapters.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Adapters.java index 0a1600e1006..d37659c82ce 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Adapters.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Adapters.java @@ -28,8 +28,6 @@ import java.util.ServiceLoader; import java.util.Set; -import okhttp3.OkHttpClient; - public final class Adapters { private static final Logger LOGGER = LoggerFactory.getLogger(Adapters.class); @@ -37,31 +35,9 @@ public final class Adapters { private static final Set CLASS_LOADERS = new HashSet<>(); private static final Map EXTENSION_ADAPTER_MAP = new HashMap<>(); - private static final ExtensionAdapter OK_HTTP_CLIENT_EXTENSION_ADAPTER = new ExtensionAdapter() { - - @Override - public Class getExtensionType() { - return OkHttpClient.class; - } - - @Override - public Boolean isAdaptable(Client client) { - return client instanceof HttpClientAware; - } - - @Override - public OkHttpClient adapt(Client client) { - if (client instanceof HttpClientAware) { - return ((HttpClientAware)client).getHttpClient().newBuilder().build(); - } - throw new IllegalArgumentException("This adapter only supports instances of HttpClientAware."); - } - }; - static { //Register adapters discoverServices(Adapters.class.getClassLoader()); - register(OK_HTTP_CLIENT_EXTENSION_ADAPTER); } private Adapters() { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AdmissionRegistrationAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AdmissionRegistrationAPIGroupClient.java index 8f5e1c3705b..71dfe140817 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AdmissionRegistrationAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AdmissionRegistrationAPIGroupClient.java @@ -15,15 +15,13 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class AdmissionRegistrationAPIGroupClient extends BaseClient implements AdmissionRegistrationAPIGroupDSL { public AdmissionRegistrationAPIGroupClient() { super(); } - public AdmissionRegistrationAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public AdmissionRegistrationAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AdmissionRegistrationAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AdmissionRegistrationAPIGroupExtensionAdapter.java index 048ae32208c..9e549e9a4bc 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AdmissionRegistrationAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AdmissionRegistrationAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class AdmissionRegistrationAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected AdmissionRegistrationAPIGroupClient newInstance(Client client) { - return new AdmissionRegistrationAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new AdmissionRegistrationAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ApiextensionsAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ApiextensionsAPIGroupClient.java index f4a92bc8040..10e7f36d24a 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ApiextensionsAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ApiextensionsAPIGroupClient.java @@ -16,15 +16,14 @@ package io.fabric8.kubernetes.client; import io.fabric8.kubernetes.client.dsl.ApiextensionsAPIGroupDSL; -import okhttp3.OkHttpClient; public class ApiextensionsAPIGroupClient extends BaseClient implements ApiextensionsAPIGroupDSL { public ApiextensionsAPIGroupClient() { super(); } - public ApiextensionsAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public ApiextensionsAPIGroupClient(ClientContext clientContext) { + super(clientContext); } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ApiextensionsAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ApiextensionsAPIGroupExtensionAdapter.java index e3b05fe06a5..f70080feb06 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ApiextensionsAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ApiextensionsAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class ApiextensionsAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -31,7 +29,7 @@ public Class getExtensionType() { @Override protected ApiextensionsAPIGroupClient newInstance(Client client) { - return new ApiextensionsAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new ApiextensionsAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AppsAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AppsAPIGroupClient.java index d699178e514..fe321dc511f 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AppsAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AppsAPIGroupClient.java @@ -25,48 +25,46 @@ import io.fabric8.kubernetes.api.model.apps.ReplicaSetList; import io.fabric8.kubernetes.api.model.apps.StatefulSet; import io.fabric8.kubernetes.api.model.apps.StatefulSetList; -import io.fabric8.kubernetes.client.dsl.RollableScalableResource; -import io.fabric8.kubernetes.client.dsl.Resource; -import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.AppsAPIGroupDSL; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.Resource; +import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.internal.apps.v1.DeploymentOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.apps.v1.ReplicaSetOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.apps.v1.StatefulSetOperationsImpl; -import okhttp3.OkHttpClient; - public class AppsAPIGroupClient extends BaseClient implements AppsAPIGroupDSL { public AppsAPIGroupClient() { super(); } - public AppsAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public AppsAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> daemonSets() { - return Handlers.getOperation(DaemonSet.class, DaemonSetList.class, httpClient, getConfiguration()); + return Handlers.getOperation(DaemonSet.class, DaemonSetList.class, this); } @Override public MixedOperation> deployments() { - return new DeploymentOperationsImpl(httpClient, getConfiguration()); + return new DeploymentOperationsImpl(this); } @Override public MixedOperation> replicaSets() { - return new ReplicaSetOperationsImpl(httpClient, getConfiguration()); + return new ReplicaSetOperationsImpl(this); } @Override public MixedOperation> statefulSets() { - return new StatefulSetOperationsImpl(httpClient, getConfiguration()); + return new StatefulSetOperationsImpl(this); } @Override public MixedOperation> controllerRevisions() { - return Handlers.getOperation(ControllerRevision.class, ControllerRevisionList.class, httpClient, getConfiguration()); + return Handlers.getOperation(ControllerRevision.class, ControllerRevisionList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AppsAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AppsAPIGroupExtensionAdapter.java index 839951394db..06ac89d3e99 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AppsAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AppsAPIGroupExtensionAdapter.java @@ -15,7 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; @@ -35,7 +34,7 @@ public Class getExtensionType() { @Override protected AppsAPIGroupClient newInstance(Client client) { - return new AppsAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new AppsAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AuthorizationAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AuthorizationAPIGroupClient.java index fb2ea572123..fbdeea12f42 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AuthorizationAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AuthorizationAPIGroupClient.java @@ -16,15 +16,14 @@ package io.fabric8.kubernetes.client; import io.fabric8.kubernetes.client.dsl.AuthorizationAPIGroupDSL; -import okhttp3.OkHttpClient; public class AuthorizationAPIGroupClient extends BaseClient implements AuthorizationAPIGroupDSL { public AuthorizationAPIGroupClient() { super(); } - public AuthorizationAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public AuthorizationAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AuthorizationAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AuthorizationAPIGroupExtensionAdapter.java index 8ded9dc151f..db0c13c5807 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AuthorizationAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AuthorizationAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class AuthorizationAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -31,7 +29,7 @@ public Class getExtensionType() { @Override protected AuthorizationAPIGroupClient newInstance(Client client) { - return new AuthorizationAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new AuthorizationAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoAdaptableKubernetesClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoAdaptableKubernetesClient.java index 5f54120505d..bb9b4aef5cc 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoAdaptableKubernetesClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoAdaptableKubernetesClient.java @@ -48,7 +48,6 @@ import io.fabric8.kubernetes.api.model.ServiceAccountList; import io.fabric8.kubernetes.api.model.ServiceList; import io.fabric8.kubernetes.client.extended.run.RunOperations; -import okhttp3.OkHttpClient; import java.io.InputStream; import java.net.URL; @@ -61,8 +60,8 @@ public AutoAdaptableKubernetesClient() { delegate = adapt(new DefaultKubernetesClient()); } - public AutoAdaptableKubernetesClient(OkHttpClient httpClient, Config config) { - delegate = adapt(new DefaultKubernetesClient(httpClient, config)); + public AutoAdaptableKubernetesClient(ClientContext clientContext) { + delegate = adapt(new DefaultKubernetesClient(clientContext)); } public AutoAdaptableKubernetesClient(Config config) { @@ -87,7 +86,7 @@ public static KubernetesClient adapt(KubernetesClient initial) { @Override public NamespacedKubernetesClient inNamespace(String namespace) { Config updated = new ConfigBuilder(getConfiguration()).withNamespace(namespace).build(); - return new AutoAdaptableKubernetesClient(httpClient, updated); + return new AutoAdaptableKubernetesClient(newState(updated)); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoscalingAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoscalingAPIGroupClient.java index 98544440790..da930cd4bd0 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoscalingAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoscalingAPIGroupClient.java @@ -15,8 +15,7 @@ */ package io.fabric8.kubernetes.client; -import io.fabric8.kubernetes.client.dsl.*; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.dsl.AutoscalingAPIGroupDSL; public class AutoscalingAPIGroupClient extends BaseClient implements AutoscalingAPIGroupDSL { @@ -24,8 +23,8 @@ public AutoscalingAPIGroupClient() { super(); } - public AutoscalingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public AutoscalingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoscalingAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoscalingAPIGroupExtensionAdapter.java index c770579416e..1c59bfa3698 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoscalingAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/AutoscalingAPIGroupExtensionAdapter.java @@ -15,7 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; @@ -35,7 +34,7 @@ public Class getExtensionType() { @Override protected AutoscalingAPIGroupClient newInstance(Client client) { - return new AutoscalingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new AutoscalingAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BaseClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BaseClient.java index 269b2f62394..6d4dd7391db 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BaseClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BaseClient.java @@ -17,9 +17,7 @@ package io.fabric8.kubernetes.client; import io.fabric8.kubernetes.client.dsl.base.OperationSupport; -import okhttp3.ConnectionPool; -import okhttp3.Dispatcher; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.kubernetes.api.model.APIGroup; import io.fabric8.kubernetes.api.model.APIGroupList; import io.fabric8.kubernetes.api.model.APIResourceList; @@ -29,17 +27,14 @@ import java.net.URL; import java.util.List; -import java.util.concurrent.ExecutorService; -public class BaseClient implements Client, HttpClientAware { +public class BaseClient extends SimpleClientContext implements Client { public static final String APIS = "/apis"; - protected OkHttpClient httpClient; private URL masterUrl; private String apiVersion; private String namespace; - private Config configuration; public BaseClient() { this(new ConfigBuilder().build()); @@ -53,10 +48,15 @@ public BaseClient(final Config config) { this(HttpClientUtils.createHttpClient(config), config); } - public BaseClient(final OkHttpClient httpClient, Config config) { + public BaseClient(final HttpClient httpClient, Config config) { + this(new SimpleClientContext(config, httpClient)); + } + + public BaseClient(ClientContext clientContext) { try { - this.configuration = config; - this.httpClient = adaptOkHttpClient(httpClient); + this.config = clientContext.getConfiguration(); + this.httpClient = clientContext.getHttpClient(); + adaptState(); this.namespace = config.getNamespace(); this.apiVersion = config.getApiVersion(); if (config.getMasterUrl() == null) { @@ -72,21 +72,7 @@ public BaseClient(final OkHttpClient httpClient, Config config) { @Override public void close() { - ConnectionPool connectionPool = httpClient.connectionPool(); - Dispatcher dispatcher = httpClient.dispatcher(); - ExecutorService executorService = httpClient.dispatcher() != null ? httpClient.dispatcher().executorService() : null; - - if (dispatcher != null) { - dispatcher.cancelAll(); - } - - if (connectionPool != null) { - connectionPool.evictAll(); - } - - if (executorService != null) { - executorService.shutdownNow(); - } + httpClient.close(); } @Override @@ -104,17 +90,6 @@ public String getNamespace() { return namespace; } - - @Override - public Config getConfiguration() { - return configuration; - } - - @Override - public OkHttpClient getHttpClient() { - return httpClient; - } - @Override public Boolean isAdaptable(Class type) { ExtensionAdapter adapter = Adapters.get(type); @@ -136,7 +111,7 @@ public C adapt(Class type) { @Override public RootPaths rootPaths() { - return new OperationSupport(httpClient, configuration).restCall(RootPaths.class); + return new OperationSupport(httpClient, config).restCall(RootPaths.class); } @Override @@ -157,24 +132,31 @@ public boolean supportsApiPath(String apiPath) { @Override public APIGroupList getApiGroups() { - return new OperationSupport(httpClient, configuration).restCall(APIGroupList.class, APIS); + return new OperationSupport(httpClient, config).restCall(APIGroupList.class, APIS); } @Override public APIGroup getApiGroup(String name) { - return new OperationSupport(httpClient, configuration).restCall(APIGroup.class, APIS, name); + return new OperationSupport(httpClient, config).restCall(APIGroup.class, APIS, name); } @Override public APIResourceList getApiResources(String groupVersion) { - return new OperationSupport(httpClient, configuration).restCall(APIResourceList.class, APIS, groupVersion); + return new OperationSupport(httpClient, config).restCall(APIResourceList.class, APIS, groupVersion); } protected VersionInfo getVersionInfo(String path) { return new OperationSupport(this.httpClient, this.getConfiguration()).restCall(VersionInfo.class, path); } - protected OkHttpClient adaptOkHttpClient(OkHttpClient okHttpClient) { - return okHttpClient; + /** + * For subclasses to adapt the client state + */ + protected void adaptState() { + // nothing by default + } + + protected SimpleClientContext newState(Config updated) { + return new SimpleClientContext(updated, httpClient); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BaseKubernetesClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BaseKubernetesClient.java index 2b1b1105e69..92f40febeff 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BaseKubernetesClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BaseKubernetesClient.java @@ -112,9 +112,9 @@ import io.fabric8.kubernetes.client.dsl.internal.certificates.v1.CertificateSigningRequestOperationsImpl; import io.fabric8.kubernetes.client.extended.run.RunConfigBuilder; import io.fabric8.kubernetes.client.extended.run.RunOperations; +import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.kubernetes.client.informers.SharedInformerFactory; import io.fabric8.kubernetes.client.utils.Serialization; -import okhttp3.OkHttpClient; import java.io.InputStream; import java.util.ArrayList; @@ -159,16 +159,20 @@ protected BaseKubernetesClient(Config config) { super(config); } - protected BaseKubernetesClient(OkHttpClient httpClient, Config config) { + protected BaseKubernetesClient(HttpClient httpClient, Config config) { super(httpClient, config); } + + protected BaseKubernetesClient(ClientContext clientContext) { + super(clientContext); + } /** * {@inheritDoc} */ @Override public NonNamespaceOperation> componentstatuses() { - return new ComponentStatusOperationsImpl(httpClient, getConfiguration()); + return new ComponentStatusOperationsImpl(this); } /** @@ -188,7 +192,7 @@ public NamespaceListVisitFromServerGetDeleteRecreateWaitApplicable } public NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl resourceListFor(Object item) { - return new NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(httpClient, getConfiguration(), item); + return new NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(this, item); } /** @@ -220,7 +224,7 @@ public ParameterNamespaceListVisitFromServerGetDeleteRecreateWaitApplicable resource(HasMetadata item) { - return new NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl(httpClient, getConfiguration(), item); + return new NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl(this, item); } /** @@ -236,7 +240,7 @@ public NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicable */ @Override public MixedOperation, Resource> bindings() { - return new BindingOperationsImpl(httpClient, getConfiguration()); + return new BindingOperationsImpl(this); } /** @@ -244,7 +248,7 @@ public MixedOperation, Resource> endpoints() { - return Handlers.getOperation(Endpoints.class, EndpointsList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Endpoints.class, EndpointsList.class, this); } /** @@ -252,7 +256,7 @@ public MixedOperation> endpoints() */ @Override public NonNamespaceOperation> namespaces() { - return Handlers.getOperation(Namespace.class, NamespaceList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Namespace.class, NamespaceList.class, this); } /** @@ -260,7 +264,7 @@ public NonNamespaceOperation> name */ @Override public NonNamespaceOperation> nodes() { - return Handlers.getOperation(Node.class, NodeList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Node.class, NodeList.class, this); } /** @@ -268,7 +272,7 @@ public NonNamespaceOperation> nodes() { */ @Override public NonNamespaceOperation> persistentVolumes() { - return Handlers.getOperation(PersistentVolume.class, PersistentVolumeList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PersistentVolume.class, PersistentVolumeList.class, this); } /** @@ -276,7 +280,7 @@ public NonNamespaceOperation> persistentVolumeClaims() { - return Handlers.getOperation(PersistentVolumeClaim.class, PersistentVolumeClaimList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PersistentVolumeClaim.class, PersistentVolumeClaimList.class, this); } /** @@ -284,7 +288,7 @@ public MixedOperation> pods() { - return new PodOperationsImpl(httpClient, getConfiguration()); + return new PodOperationsImpl(this); } /** @@ -292,7 +296,7 @@ public MixedOperation> pods() { */ @Override public MixedOperation> replicationControllers() { - return new ReplicationControllerOperationsImpl(httpClient, getConfiguration()); + return new ReplicationControllerOperationsImpl(this); } /** @@ -300,7 +304,7 @@ public MixedOperation> resourceQuotas() { - return Handlers.getOperation(ResourceQuota.class, ResourceQuotaList.class, httpClient, getConfiguration()); + return Handlers.getOperation(ResourceQuota.class, ResourceQuotaList.class, this); } /** @@ -313,7 +317,7 @@ public SchedulingAPIGroupDSL scheduling() { @Override public MixedOperation> secrets() { - return Handlers.getOperation(Secret.class, SecretList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Secret.class, SecretList.class, this); } /** @@ -321,7 +325,7 @@ public MixedOperation> secrets() { */ @Override public MixedOperation> services() { - return new ServiceOperationsImpl(httpClient, getConfiguration()); + return new ServiceOperationsImpl(this); } /** @@ -329,7 +333,7 @@ public MixedOperation> services() */ @Override public MixedOperation> serviceAccounts() { - return Handlers.getOperation(ServiceAccount.class, ServiceAccountList.class, httpClient, getConfiguration()); + return Handlers.getOperation(ServiceAccount.class, ServiceAccountList.class, this); } /** @@ -337,7 +341,7 @@ public MixedOperation> apiServices() { - return Handlers.getOperation(APIService.class, APIServiceList.class, httpClient, getConfiguration()); + return Handlers.getOperation(APIService.class, APIServiceList.class, this); } /** @@ -345,7 +349,7 @@ public NonNamespaceOperation> a */ @Override public KubernetesListMixedOperation lists() { - return new KubernetesListOperationsImpl(httpClient, getConfiguration()); + return new KubernetesListOperationsImpl(this); } /** @@ -353,7 +357,7 @@ public KubernetesListMixedOperation lists() { */ @Override public MixedOperation> configMaps() { - return Handlers.getOperation(ConfigMap.class, ConfigMapList.class, httpClient, getConfiguration()); + return Handlers.getOperation(ConfigMap.class, ConfigMapList.class, this); } /** @@ -361,7 +365,7 @@ public MixedOperation> configMaps( */ @Override public MixedOperation> limitRanges() { - return Handlers.getOperation(LimitRange.class, LimitRangeList.class, httpClient, getConfiguration()); + return Handlers.getOperation(LimitRange.class, LimitRangeList.class, this); } /** @@ -377,7 +381,7 @@ public ApiextensionsAPIGroupDSL apiextensions() { */ @Override public NonNamespaceOperation> certificateSigningRequests() { - return Handlers.getOperation(CertificateSigningRequest.class, CertificateSigningRequestList.class, httpClient, getConfiguration()); + return Handlers.getOperation(CertificateSigningRequest.class, CertificateSigningRequestList.class, this); } @Override @@ -398,7 +402,7 @@ public AuthorizationAPIGroupDSL authorization() { */ @Override public InOutCreateable tokenReviews() { - return Handlers.getNonListingOperation(TokenReview.class, httpClient, getConfiguration()); + return Handlers.getNonListingOperation(TokenReview.class, this); } /** @@ -432,7 +436,7 @@ public MixedOperation> HasMetadataOperation> resources( Class resourceType, Class listClass) { try { - return Handlers.getOperation(resourceType, listClass, httpClient, getConfiguration()); + return Handlers.getOperation(resourceType, listClass, this); } catch (Exception e) { //may be the wrong list type, try more general return customResources(ResourceDefinitionContext.fromResourceType(resourceType), resourceType, listClass); @@ -444,7 +448,7 @@ public > HasMetadataO */ @Override public > HasMetadataOperationsImpl customResources(ResourceDefinitionContext rdContext, Class resourceType, Class listClass) { - return new HasMetadataOperationsImpl<>(httpClient, getConfiguration(), rdContext, resourceType, listClass); + return new HasMetadataOperationsImpl<>(this, rdContext, resourceType, listClass); } /** @@ -452,7 +456,7 @@ public > HasMetadataO */ @Override public RawCustomResourceOperationsImpl customResource(CustomResourceDefinitionContext customResourceDefinition) { - return new RawCustomResourceOperationsImpl(httpClient, getConfiguration(), customResourceDefinition); + return new RawCustomResourceOperationsImpl(this, customResourceDefinition); } @Override @@ -588,7 +592,7 @@ public SharedInformerFactory informers(ExecutorService executorService) { */ @Override public MixedOperation> leases() { - return Handlers.getOperation(Lease.class, LeaseList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Lease.class, LeaseList.class, this); } /** @@ -596,7 +600,7 @@ public MixedOperation> leases() { */ @Override public RunOperations run() { - return new RunOperations(httpClient, getConfiguration(), getNamespace(), new RunConfigBuilder()); + return new RunOperations(this, getNamespace(), new RunConfigBuilder()); } /** @@ -604,7 +608,7 @@ public RunOperations run() { */ @Override public NonNamespaceOperation> runtimeClasses() { - return Handlers.getOperation(RuntimeClass.class, RuntimeClassList.class, httpClient, getConfiguration()); + return Handlers.getOperation(RuntimeClass.class, RuntimeClassList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BatchAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BatchAPIGroupClient.java index 6eb01facb95..4287df03b04 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BatchAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BatchAPIGroupClient.java @@ -27,7 +27,6 @@ import io.fabric8.kubernetes.client.dsl.V1beta1BatchAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.internal.batch.v1beta1.CronJobOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.batch.v1.JobOperationsImpl; -import okhttp3.OkHttpClient; public class BatchAPIGroupClient extends BaseClient implements BatchAPIGroupDSL { @@ -35,18 +34,18 @@ public BatchAPIGroupClient() { super(); } - public BatchAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public BatchAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> jobs() { - return new JobOperationsImpl(httpClient, getConfiguration()); + return new JobOperationsImpl(this); } @Override public MixedOperation> cronjobs() { - return new CronJobOperationsImpl(httpClient, getConfiguration()); + return new CronJobOperationsImpl(this); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BatchAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BatchAPIGroupExtensionAdapter.java index a8bb1a13bd4..cbba26fe804 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BatchAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/BatchAPIGroupExtensionAdapter.java @@ -15,7 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; @@ -35,6 +34,6 @@ public Class getExtensionType() { @Override protected BatchAPIGroupClient newInstance(Client client) { - return new BatchAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new BatchAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/CertificatesAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/CertificatesAPIGroupClient.java index 6f93352d354..3bd65b0fedf 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/CertificatesAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/CertificatesAPIGroupClient.java @@ -18,7 +18,6 @@ import io.fabric8.kubernetes.client.dsl.CertificatesAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.V1CertificatesAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.V1beta1CertificatesAPIGroupDSL; -import okhttp3.OkHttpClient; public class CertificatesAPIGroupClient extends BaseClient implements CertificatesAPIGroupDSL { @@ -26,8 +25,8 @@ public CertificatesAPIGroupClient() { super(); } - public CertificatesAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public CertificatesAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/CertificatesAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/CertificatesAPIGroupExtensionAdapter.java index cf21cb910b6..703e98cb08e 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/CertificatesAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/CertificatesAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class CertificatesAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected CertificatesAPIGroupClient newInstance(Client client) { - return new CertificatesAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new CertificatesAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Client.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Client.java index 27289795b69..0551e7d5dbb 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Client.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Client.java @@ -24,7 +24,7 @@ import java.io.Closeable; import java.net.URL; -public interface Client extends ConfigAware, Closeable { +public interface Client extends ClientContext, Closeable { /** * Checks if the client can be adapted to an other client type. diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/AdaptTest.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ClientContext.java similarity index 58% rename from kubernetes-client/src/test/java/io/fabric8/kubernetes/client/AdaptTest.java rename to kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ClientContext.java index 657be64d361..f7fe47f23ce 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/AdaptTest.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ClientContext.java @@ -16,18 +16,10 @@ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -public class AdaptTest { - - @Test - public void testAdaptToHttpClient() { - KubernetesClient client = new DefaultKubernetesClient(); - assertTrue(client.isAdaptable(OkHttpClient.class)); - assertNotNull(client.adapt(OkHttpClient.class)); - } +/** + * Provides the {@link Config} and any derived state necessary for a {@link Client} to function + *
Generally users will not need to implement this interface, nor use constructors that reference it. + */ +public interface ClientContext extends HttpClientAware, ConfigAware { + } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Config.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Config.java index fe37457146c..df98eb53b51 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Config.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Config.java @@ -28,6 +28,7 @@ import io.fabric8.kubernetes.api.model.ExecConfig; import io.fabric8.kubernetes.api.model.ExecEnvVar; import io.fabric8.kubernetes.api.model.NamedContext; +import io.fabric8.kubernetes.client.http.TlsVersion; import io.fabric8.kubernetes.client.internal.CertUtils; import io.fabric8.kubernetes.client.internal.KubeConfigUtils; import io.fabric8.kubernetes.client.internal.SSLUtils; @@ -36,7 +37,6 @@ import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.kubernetes.client.utils.Utils; import io.sundr.builder.annotations.Buildable; -import okhttp3.TlsVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,8 +54,6 @@ import java.util.Locale; import java.util.Map; -import static okhttp3.TlsVersion.TLS_1_2; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true, allowGetters = true, allowSetters = true) public class Config { @@ -218,7 +216,7 @@ public class Config { private String proxyPassword; private String[] noProxy; private String userAgent; - private TlsVersion[] tlsVersions = new TlsVersion[]{TLS_1_2}; + private TlsVersion[] tlsVersions = new TlsVersion[]{TlsVersion.TLS_1_2}; private Map errorMessages = new HashMap<>(); diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DefaultKubernetesClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DefaultKubernetesClient.java index cb2715a8699..da2fb0df13f 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DefaultKubernetesClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DefaultKubernetesClient.java @@ -17,6 +17,8 @@ import io.fabric8.kubernetes.client.dsl.FunctionCallable; import io.fabric8.kubernetes.client.extended.leaderelection.LeaderElectorBuilder; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.okhttp.OkHttpClientImpl; import io.fabric8.kubernetes.client.utils.Serialization; import okhttp3.OkHttpClient; @@ -39,10 +41,23 @@ public DefaultKubernetesClient(String masterUrl) { public DefaultKubernetesClient(Config config) { super(config); } - + + /** + * @deprecated use {@link DefaultKubernetesClient#DefaultKubernetesClient(HttpClient, Config)} instead. + * use {@link OkHttpClientImpl#OkHttpClientImpl(OkHttpClient)} to wrap the client. + */ + @Deprecated public DefaultKubernetesClient(OkHttpClient httpClient, Config config) { + super(new OkHttpClientImpl(httpClient), config); + } + + public DefaultKubernetesClient(HttpClient httpClient, Config config) { super(httpClient, config); } + + public DefaultKubernetesClient(ClientContext clientContext) { + super(clientContext); + } public static DefaultKubernetesClient fromConfig(String config) { return new DefaultKubernetesClient(Serialization.unmarshal(config, Config.class)); @@ -55,7 +70,7 @@ public static DefaultKubernetesClient fromConfig(InputStream is) { @Override public NamespacedKubernetesClient inNamespace(String name) { Config updated = new ConfigBuilder(getConfiguration()).withNamespace(name).build(); - return new DefaultKubernetesClient(httpClient, updated); + return new DefaultKubernetesClient(newState(updated)); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DiscoveryAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DiscoveryAPIGroupClient.java index bc8bd815ae0..c1a7045088a 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DiscoveryAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DiscoveryAPIGroupClient.java @@ -18,15 +18,14 @@ import io.fabric8.kubernetes.client.dsl.DiscoveryAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.V1DiscoveryAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.V1beta1DiscoveryAPIGroupDSL; -import okhttp3.OkHttpClient; public class DiscoveryAPIGroupClient extends BaseClient implements DiscoveryAPIGroupDSL { public DiscoveryAPIGroupClient() { super(); } - public DiscoveryAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public DiscoveryAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DiscoveryAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DiscoveryAPIGroupExtensionAdapter.java index b3907d6b344..eb4a509d735 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DiscoveryAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/DiscoveryAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class DiscoveryAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -31,6 +29,6 @@ public Class getExtensionType() { @Override protected DiscoveryAPIGroupClient newInstance(Client client) { - return new DiscoveryAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new DiscoveryAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/EventingAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/EventingAPIGroupClient.java index 1d41d54ee89..badef31b79d 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/EventingAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/EventingAPIGroupClient.java @@ -18,15 +18,14 @@ import io.fabric8.kubernetes.client.dsl.EventingAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.V1EventingAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.V1beta1EventingAPIGroupDSL; -import okhttp3.OkHttpClient; public class EventingAPIGroupClient extends BaseClient implements EventingAPIGroupDSL { public EventingAPIGroupClient() { super(); } - public EventingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public EventingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/EventingAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/EventingAPIGroupExtensionAdapter.java index 033e57148b3..7e28f49b10e 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/EventingAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/EventingAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class EventingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -31,7 +29,7 @@ public Class getExtensionType() { @Override protected EventingAPIGroupClient newInstance(Client client) { - return new EventingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new EventingAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ExtensionsAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ExtensionsAPIGroupClient.java index 4356146619a..ec531f39cd6 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ExtensionsAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ExtensionsAPIGroupClient.java @@ -15,29 +15,28 @@ */ package io.fabric8.kubernetes.client; +import io.fabric8.kubernetes.api.model.batch.v1.Job; +import io.fabric8.kubernetes.api.model.batch.v1.JobList; import io.fabric8.kubernetes.api.model.extensions.DaemonSet; import io.fabric8.kubernetes.api.model.extensions.DaemonSetList; import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentList; -import io.fabric8.kubernetes.api.model.extensions.ReplicaSet; -import io.fabric8.kubernetes.api.model.extensions.ReplicaSetList; -import io.fabric8.kubernetes.api.model.batch.v1.Job; -import io.fabric8.kubernetes.api.model.batch.v1.JobList; import io.fabric8.kubernetes.api.model.extensions.Ingress; import io.fabric8.kubernetes.api.model.extensions.IngressList; import io.fabric8.kubernetes.api.model.extensions.NetworkPolicy; import io.fabric8.kubernetes.api.model.extensions.NetworkPolicyList; +import io.fabric8.kubernetes.api.model.extensions.ReplicaSet; +import io.fabric8.kubernetes.api.model.extensions.ReplicaSetList; import io.fabric8.kubernetes.api.model.policy.v1beta1.PodSecurityPolicy; import io.fabric8.kubernetes.api.model.policy.v1beta1.PodSecurityPolicyList; +import io.fabric8.kubernetes.client.dsl.ExtensionsAPIGroupDSL; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.ScalableResource; -import io.fabric8.kubernetes.client.dsl.Resource; -import io.fabric8.kubernetes.client.dsl.MixedOperation; -import io.fabric8.kubernetes.client.dsl.ExtensionsAPIGroupDSL; -import io.fabric8.kubernetes.client.dsl.internal.extensions.v1beta1.DeploymentOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.batch.v1.JobOperationsImpl; +import io.fabric8.kubernetes.client.dsl.internal.extensions.v1beta1.DeploymentOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.extensions.v1beta1.ReplicaSetOperationsImpl; -import okhttp3.OkHttpClient; public class ExtensionsAPIGroupClient extends BaseClient implements ExtensionsAPIGroupDSL { @@ -45,20 +44,20 @@ public ExtensionsAPIGroupClient() { super(); } - public ExtensionsAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public ExtensionsAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override @Deprecated public MixedOperation> daemonSets() { - return Handlers.getOperation(DaemonSet.class, DaemonSetList.class, httpClient, getConfiguration()); + return Handlers.getOperation(DaemonSet.class, DaemonSetList.class, this); } @Override @Deprecated public MixedOperation> deployments() { - return new DeploymentOperationsImpl(httpClient, getConfiguration()); + return new DeploymentOperationsImpl(this); } @Override @@ -69,19 +68,19 @@ public MixedOperation> ingress() { @Override public MixedOperation> ingresses() { - return Handlers.getOperation(Ingress.class, IngressList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Ingress.class, IngressList.class, this); } @Override @Deprecated public MixedOperation> jobs() { - return new JobOperationsImpl(httpClient, getConfiguration()); + return new JobOperationsImpl(this); } @Override @Deprecated public MixedOperation> networkPolicies() { - return Handlers.getOperation(NetworkPolicy.class, NetworkPolicyList.class, httpClient, getConfiguration()); + return Handlers.getOperation(NetworkPolicy.class, NetworkPolicyList.class, this); } @Override @@ -90,13 +89,13 @@ public MixedOperation> * @deprecated Replaced by {@link PolicyAPIGroupClient#podSecurityPolicies()} */ public MixedOperation> podSecurityPolicies() { - return Handlers.getOperation(PodSecurityPolicy.class, PodSecurityPolicyList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PodSecurityPolicy.class, PodSecurityPolicyList.class, this); } @Override @Deprecated public MixedOperation> replicaSets() { - return new ReplicaSetOperationsImpl(httpClient, getConfiguration()); + return new ReplicaSetOperationsImpl(this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ExtensionsAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ExtensionsAPIGroupExtensionAdapter.java index 40690f48bc7..aa5f2df7cf2 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ExtensionsAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ExtensionsAPIGroupExtensionAdapter.java @@ -15,7 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; @@ -35,7 +34,7 @@ public Class getExtensionType() { @Override protected ExtensionsAPIGroupClient newInstance(Client client) { - return new ExtensionsAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new ExtensionsAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/FlowControlAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/FlowControlAPIGroupClient.java index a31757edd13..e2edd6fd71f 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/FlowControlAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/FlowControlAPIGroupClient.java @@ -17,15 +17,14 @@ import io.fabric8.kubernetes.client.dsl.FlowControlAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.V1beta1FlowControlAPIGroupDSL; -import okhttp3.OkHttpClient; public class FlowControlAPIGroupClient extends BaseClient implements FlowControlAPIGroupDSL { public FlowControlAPIGroupClient() { super(); } - public FlowControlAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public FlowControlAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/FlowControlAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/FlowControlAPIGroupExtensionAdapter.java index a8830a3be86..5e2edf33500 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/FlowControlAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/FlowControlAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class FlowControlAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected FlowControlAPIGroupClient newInstance(Client client) { - return new FlowControlAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new FlowControlAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Handlers.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Handlers.java index abe9ee8fbb0..d7f35637c25 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Handlers.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/Handlers.java @@ -29,13 +29,12 @@ import io.fabric8.kubernetes.client.utils.ApiVersionUtil; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; import io.fabric8.kubernetes.client.utils.Serialization; -import okhttp3.OkHttpClient; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import java.util.function.BiFunction; +import java.util.function.Function; public final class Handlers { @@ -46,7 +45,7 @@ private Handlers() { //Utility } - public static , R extends Resource> void register(Class type, BiFunction> operationConstructor) { + public static , R extends Resource> void register(Class type, Function> operationConstructor) { if (RESOURCE_HANDLER_MAP.put(type, new ResourceHandlerImpl(type, operationConstructor)) != null) { throw new AssertionError(String.format("%s already registered", type.getName())); } @@ -130,16 +129,16 @@ private static > Resourc return (ResourceHandler) RESOURCE_HANDLER_MAP.computeIfAbsent(type, k -> new ResourceHandlerImpl<>(type, null)); } - public static , R extends Resource> HasMetadataOperation getOperation(Class type, Class listType, OkHttpClient client, Config config) { + public static , R extends Resource> HasMetadataOperation getOperation(Class type, Class listType, ClientContext clientContext) { ResourceHandler resourceHandler = get(type); if (resourceHandler == null) { throw new IllegalStateException(); } - return (HasMetadataOperation) resourceHandler.operation(client, config, listType); + return (HasMetadataOperation) resourceHandler.operation(clientContext, listType); } - public static HasMetadataOperation> getNonListingOperation(Class type, OkHttpClient client, Config config) { - return getOperation(type, KubernetesResourceUtil.inferListType(type), client, config); + public static HasMetadataOperation> getNonListingOperation(Class type, ClientContext clientContext) { + return getOperation(type, KubernetesResourceUtil.inferListType(type), clientContext); } public static boolean shouldRegister(Class type) { @@ -147,8 +146,8 @@ public static boolean shouldRegister(Class type) { return !RESOURCE_HANDLER_MAP.isEmpty() && (handler == null || !handler.hasOperation()); } - public static NamespacedInOutCreateable getNamespacedHasMetadataCreateOnlyOperation(Class type, OkHttpClient client, Config config) { - HasMetadataOperation> operation = getNonListingOperation(type, client, config); + public static NamespacedInOutCreateable getNamespacedHasMetadataCreateOnlyOperation(Class type, ClientContext clientContext) { + HasMetadataOperation> operation = getNonListingOperation(type, clientContext); return operation::inNamespace; } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/HttpClientAware.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/HttpClientAware.java index 6cc6227c86c..0b904377c2f 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/HttpClientAware.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/HttpClientAware.java @@ -16,9 +16,9 @@ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.http.HttpClient; public interface HttpClientAware { - OkHttpClient getHttpClient(); + HttpClient getHttpClient(); } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/MetricAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/MetricAPIGroupClient.java index 357e7dbcf65..95c9633b656 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/MetricAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/MetricAPIGroupClient.java @@ -18,25 +18,24 @@ import io.fabric8.kubernetes.client.dsl.MetricAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.internal.NodeMetricOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.PodMetricOperationsImpl; -import okhttp3.OkHttpClient; public class MetricAPIGroupClient extends BaseClient implements MetricAPIGroupDSL { public MetricAPIGroupClient() { super(); } - public MetricAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public MetricAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public PodMetricOperationsImpl pods() { - return new PodMetricOperationsImpl(httpClient, getConfiguration()); + return new PodMetricOperationsImpl(this); } @Override public NodeMetricOperationsImpl nodes() { - return new NodeMetricOperationsImpl(httpClient, getConfiguration()); + return new NodeMetricOperationsImpl(this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/MetricAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/MetricAPIGroupExtensionAdapter.java index b3025080669..9b98381b9ac 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/MetricAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/MetricAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class MetricAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -31,6 +29,6 @@ public Class getExtensionType() { @Override protected MetricAPIGroupClient newInstance(Client client) { - return new MetricAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new MetricAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/NetworkAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/NetworkAPIGroupClient.java index 47926fb795d..f1326f16490 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/NetworkAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/NetworkAPIGroupClient.java @@ -22,7 +22,6 @@ import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NetworkAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class NetworkAPIGroupClient extends BaseClient implements NetworkAPIGroupDSL { @@ -30,8 +29,8 @@ public NetworkAPIGroupClient() { super(); } - public NetworkAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public NetworkAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override @@ -46,7 +45,7 @@ public V1beta1NetworkAPIGroupDSL v1beta1() { @Override public MixedOperation> networkPolicies() { - return Handlers.getOperation(NetworkPolicy.class, NetworkPolicyList.class, httpClient, getConfiguration()); + return Handlers.getOperation(NetworkPolicy.class, NetworkPolicyList.class, this); } @Override @@ -56,6 +55,6 @@ public MixedOperation> ingress() { @Override public MixedOperation> ingresses() { - return Handlers.getOperation(Ingress.class, IngressList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Ingress.class, IngressList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/NetworkAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/NetworkAPIGroupExtensionAdapter.java index 2005ee47ec8..d84a73b092d 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/NetworkAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/NetworkAPIGroupExtensionAdapter.java @@ -15,7 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; @@ -35,7 +34,7 @@ public Class getExtensionType() { @Override protected NetworkAPIGroupClient newInstance(Client client) { - return new NetworkAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new NetworkAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/PolicyAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/PolicyAPIGroupClient.java index ca35292abe2..d7487f0af4c 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/PolicyAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/PolicyAPIGroupClient.java @@ -24,22 +24,21 @@ import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1PolicyAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.V1beta1PolicyAPIGroupDSL; -import okhttp3.OkHttpClient; public class PolicyAPIGroupClient extends BaseClient implements PolicyAPIGroupDSL { - public PolicyAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public PolicyAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> podDisruptionBudget() { - return Handlers.getOperation(PodDisruptionBudget.class, PodDisruptionBudgetList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PodDisruptionBudget.class, PodDisruptionBudgetList.class, this); } @Override public MixedOperation> podSecurityPolicies() { - return Handlers.getOperation(PodSecurityPolicy.class, PodSecurityPolicyList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PodSecurityPolicy.class, PodSecurityPolicyList.class, this); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/PolicyAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/PolicyAPIGroupExtensionAdapter.java index a3b4e9db001..ad4256b2e2c 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/PolicyAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/PolicyAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class PolicyAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -31,6 +29,6 @@ public Class getExtensionType() { @Override protected PolicyAPIGroupClient newInstance(Client client) { - return new PolicyAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new PolicyAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/RbacAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/RbacAPIGroupClient.java index febff3888b9..c7f92973f54 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/RbacAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/RbacAPIGroupClient.java @@ -15,12 +15,18 @@ */ package io.fabric8.kubernetes.client; -import io.fabric8.kubernetes.api.model.rbac.*; +import io.fabric8.kubernetes.api.model.rbac.ClusterRole; +import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding; +import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBindingList; +import io.fabric8.kubernetes.api.model.rbac.ClusterRoleList; +import io.fabric8.kubernetes.api.model.rbac.Role; +import io.fabric8.kubernetes.api.model.rbac.RoleBinding; +import io.fabric8.kubernetes.api.model.rbac.RoleBindingList; +import io.fabric8.kubernetes.api.model.rbac.RoleList; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.RbacAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class RbacAPIGroupClient extends BaseClient implements RbacAPIGroupDSL { @@ -28,27 +34,27 @@ public RbacAPIGroupClient() { super(); } - public RbacAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public RbacAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> roles() { - return Handlers.getOperation(Role.class, RoleList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Role.class, RoleList.class, this); } @Override public MixedOperation> roleBindings() { - return Handlers.getOperation(RoleBinding.class, RoleBindingList.class, httpClient, getConfiguration()); + return Handlers.getOperation(RoleBinding.class, RoleBindingList.class, this); } @Override public NonNamespaceOperation> clusterRoles() { - return Handlers.getOperation(ClusterRole.class, ClusterRoleList.class, httpClient, getConfiguration()); + return Handlers.getOperation(ClusterRole.class, ClusterRoleList.class, this); } @Override public NonNamespaceOperation> clusterRoleBindings() { - return Handlers.getOperation(ClusterRoleBinding.class, ClusterRoleBindingList.class, httpClient, getConfiguration()); + return Handlers.getOperation(ClusterRoleBinding.class, ClusterRoleBindingList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/RbacAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/RbacAPIGroupExtensionAdapter.java index 144a6b475a6..f77f8932d01 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/RbacAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/RbacAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class RbacAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -31,6 +29,6 @@ public Class getExtensionType() { @Override protected RbacAPIGroupClient newInstance(Client client) { - return new RbacAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new RbacAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ResourceHandler.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ResourceHandler.java index 15ab126b00e..3cc2b7514ea 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ResourceHandler.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ResourceHandler.java @@ -16,12 +16,11 @@ package io.fabric8.kubernetes.client; +import io.fabric8.kubernetes.api.builder.VisitableBuilder; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; -import okhttp3.OkHttpClient; -import io.fabric8.kubernetes.api.builder.VisitableBuilder; public interface ResourceHandler> { @@ -34,12 +33,11 @@ public interface ResourceHandler> HasMetadataOperation> operation(OkHttpClient client, Config config, Class listType); + > HasMetadataOperation> operation(ClientContext clientContext, Class listType); /** * @return true if there is a specialized operation associated with this handler diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ResourceHandlerImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ResourceHandlerImpl.java index 77d2cd559bd..351f8ce0957 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ResourceHandlerImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ResourceHandlerImpl.java @@ -25,10 +25,9 @@ import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.OkHttpClient; import java.lang.reflect.InvocationTargetException; -import java.util.function.BiFunction; +import java.util.function.Function; class ResourceHandlerImpl> implements ResourceHandler { @@ -36,9 +35,9 @@ class ResourceHandlerImpl type; private final Class builderClass; private final Class> defaultListClass; - private final BiFunction>> operationConstructor; + private final Function>> operationConstructor; - ResourceHandlerImpl(Class type, BiFunction>> operationConstructor) { + ResourceHandlerImpl(Class type, Function>> operationConstructor) { this.type = type; this.context = ResourceDefinitionContext.fromResourceType(type); this.builderClass = KubernetesResourceUtil.inferBuilderType(type); @@ -68,14 +67,14 @@ public V edit(T item) { } @Override - public > HasMetadataOperation> operation(OkHttpClient client, Config config, Class listType) { + public > HasMetadataOperation> operation(ClientContext clientContext, Class listType) { if (operationConstructor != null) { if (listType != null && !listType.isAssignableFrom(defaultListClass)) { throw new IllegalArgumentException(String.format("Handler type %s with list %s not compatible with %s", type, defaultListClass.getName(), listType.getName())); } - return (HasMetadataOperation>) operationConstructor.apply(client, config); + return (HasMetadataOperation>) operationConstructor.apply(clientContext); } - return new HasMetadataOperationsImpl<>(client, config, context, type, (Class)Utils.getNonNullOrElse(listType, defaultListClass)); + return new HasMetadataOperationsImpl<>(clientContext, context, type, (Class)Utils.getNonNullOrElse(listType, defaultListClass)); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/SchedulingAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/SchedulingAPIGroupClient.java index ac3477b3b8d..792369bedf7 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/SchedulingAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/SchedulingAPIGroupClient.java @@ -22,16 +22,15 @@ import io.fabric8.kubernetes.client.dsl.SchedulingAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.V1SchedulingAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.V1beta1SchedulingAPIGroupDSL; -import okhttp3.OkHttpClient; public class SchedulingAPIGroupClient extends BaseClient implements SchedulingAPIGroupDSL { - public SchedulingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public SchedulingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> priorityClass() { - return Handlers.getOperation(PriorityClass.class, PriorityClassList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PriorityClass.class, PriorityClassList.class, this); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/SchedulingAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/SchedulingAPIGroupExtensionAdapter.java index 98cb8138f48..e5cf78ca5d9 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/SchedulingAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/SchedulingAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class SchedulingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -28,6 +26,6 @@ public Class getExtensionType() { } @Override protected SchedulingAPIGroupClient newInstance(Client client) { - return new SchedulingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new SchedulingAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/SimpleClientContext.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/SimpleClientContext.java new file mode 100644 index 00000000000..c8861550954 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/SimpleClientContext.java @@ -0,0 +1,44 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client; + +import io.fabric8.kubernetes.client.http.HttpClient; + +public class SimpleClientContext implements ClientContext { + + protected Config config; + protected HttpClient httpClient; + + public SimpleClientContext() { + + } + + public SimpleClientContext(Config config, HttpClient httpClient) { + this.config = config; + this.httpClient = httpClient; + } + + @Override + public Config getConfiguration() { + return config; + } + + @Override + public HttpClient getHttpClient() { + return httpClient; + } +} \ No newline at end of file diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/StorageAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/StorageAPIGroupClient.java index beef4c51742..dcf463763ee 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/StorageAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/StorageAPIGroupClient.java @@ -29,7 +29,6 @@ import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.StorageAPIGroupDSL; -import okhttp3.OkHttpClient; public class StorageAPIGroupClient extends BaseClient implements StorageAPIGroupDSL { @@ -37,32 +36,32 @@ public StorageAPIGroupClient() { super(); } - public StorageAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public StorageAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> storageClasses() { - return Handlers.getOperation(StorageClass.class, StorageClassList.class, httpClient, getConfiguration()); + return Handlers.getOperation(StorageClass.class, StorageClassList.class, this); } @Override public NonNamespaceOperation> csiDrivers() { - return Handlers.getOperation(CSIDriver.class, CSIDriverList.class, httpClient, getConfiguration()); + return Handlers.getOperation(CSIDriver.class, CSIDriverList.class, this); } @Override public NonNamespaceOperation> csiNodes() { - return Handlers.getOperation(CSINode.class, CSINodeList.class, httpClient, getConfiguration()); + return Handlers.getOperation(CSINode.class, CSINodeList.class, this); } @Override public MixedOperation> csiStorageCapacities() { - return Handlers.getOperation(CSIStorageCapacity.class, CSIStorageCapacityList.class, httpClient, getConfiguration()); + return Handlers.getOperation(CSIStorageCapacity.class, CSIStorageCapacityList.class, this); } @Override public NonNamespaceOperation> volumeAttachments() { - return Handlers.getOperation(VolumeAttachment.class, VolumeAttachmentList.class, httpClient, getConfiguration()); + return Handlers.getOperation(VolumeAttachment.class, VolumeAttachmentList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/StorageAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/StorageAPIGroupExtensionAdapter.java index a6139e11144..6af3d0edf5d 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/StorageAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/StorageAPIGroupExtensionAdapter.java @@ -15,7 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; @@ -35,7 +34,7 @@ public Class getExtensionType() { @Override protected StorageAPIGroupClient newInstance(Client client) { - return new StorageAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new StorageAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1APIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1APIGroupClient.java index 36848bc2505..21b890d872e 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1APIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1APIGroupClient.java @@ -22,24 +22,23 @@ import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1APIGroupDSL; -import okhttp3.OkHttpClient; public class V1APIGroupClient extends BaseClient implements V1APIGroupDSL { public V1APIGroupClient() { super(); } - public V1APIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1APIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> podTemplates() { - return Handlers.getOperation(PodTemplate.class, PodTemplateList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PodTemplate.class, PodTemplateList.class, this); } @Override public MixedOperation> events() { - return Handlers.getOperation(Event.class, EventList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Event.class, EventList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1APIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1APIGroupExtensionAdapter.java index fa566afa88d..08e0407b6ca 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1APIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1APIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1APIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1APIGroupClient newInstance(Client client) { - return new V1APIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1APIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AdmissionRegistrationAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AdmissionRegistrationAPIGroupClient.java index 651f51e043f..5b485697858 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AdmissionRegistrationAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AdmissionRegistrationAPIGroupClient.java @@ -22,24 +22,23 @@ import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1AdmissionRegistrationAPIGroupClient extends BaseClient implements V1AdmissionRegistrationAPIGroupDSL { public V1AdmissionRegistrationAPIGroupClient() { super(); } - public V1AdmissionRegistrationAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1AdmissionRegistrationAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public NonNamespaceOperation> validatingWebhookConfigurations() { - return Handlers.getOperation(ValidatingWebhookConfiguration.class, ValidatingWebhookConfigurationList.class, httpClient, getConfiguration()); + return Handlers.getOperation(ValidatingWebhookConfiguration.class, ValidatingWebhookConfigurationList.class, this); } @Override public MixedOperation> mutatingWebhookConfigurations() { - return Handlers.getOperation(MutatingWebhookConfiguration.class, MutatingWebhookConfigurationList.class, httpClient, getConfiguration()); + return Handlers.getOperation(MutatingWebhookConfiguration.class, MutatingWebhookConfigurationList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AdmissionRegistrationAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AdmissionRegistrationAPIGroupExtensionAdapter.java index 25b1c4c21c5..50c3182d9b9 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AdmissionRegistrationAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AdmissionRegistrationAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1AdmissionRegistrationAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1AdmissionRegistrationAPIGroupClient newInstance(Client client) { - return new V1AdmissionRegistrationAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1AdmissionRegistrationAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1ApiextensionsAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1ApiextensionsAPIGroupClient.java index 2bbd44f6447..2707c63bcfd 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1ApiextensionsAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1ApiextensionsAPIGroupClient.java @@ -19,18 +19,18 @@ import io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinitionList; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1ApiextensionsAPIGroupClient extends BaseClient implements V1ApiextensionAPIGroupDSL { public V1ApiextensionsAPIGroupClient() { super(); } - public V1ApiextensionsAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1ApiextensionsAPIGroupClient(ClientContext clientContext) { + super(clientContext); } + @Override public MixedOperation> customResourceDefinitions() { - return Handlers.getOperation(CustomResourceDefinition.class, CustomResourceDefinitionList.class, httpClient, getConfiguration()); + return Handlers.getOperation(CustomResourceDefinition.class, CustomResourceDefinitionList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1ApiextensionsAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1ApiextensionsAPIGroupExtensionAdapter.java index 0a3df11dfdf..8f1097eb64e 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1ApiextensionsAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1ApiextensionsAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1ApiextensionsAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1ApiextensionsAPIGroupClient newInstance(Client client) { - return new V1ApiextensionsAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1ApiextensionsAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AuthorizationAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AuthorizationAPIGroupClient.java index 5af91ea99d0..7a6aaf94212 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AuthorizationAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AuthorizationAPIGroupClient.java @@ -21,7 +21,6 @@ import io.fabric8.kubernetes.api.model.authorization.v1.SubjectAccessReview; import io.fabric8.kubernetes.client.dsl.InOutCreateable; import io.fabric8.kubernetes.client.dsl.NamespacedInOutCreateable; -import okhttp3.OkHttpClient; public class V1AuthorizationAPIGroupClient extends BaseClient implements V1AuthorizationAPIGroupDSL { public static final String AUTHORIZATION_APIGROUP = "authorization.k8s.io"; @@ -31,27 +30,27 @@ public V1AuthorizationAPIGroupClient() { super(); } - public V1AuthorizationAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1AuthorizationAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public InOutCreateable selfSubjectAccessReview() { - return Handlers.getNonListingOperation(SelfSubjectAccessReview.class, httpClient, getConfiguration()); + return Handlers.getNonListingOperation(SelfSubjectAccessReview.class, this); } @Override public InOutCreateable subjectAccessReview() { - return Handlers.getNonListingOperation(SubjectAccessReview.class, httpClient, getConfiguration()); + return Handlers.getNonListingOperation(SubjectAccessReview.class, this); } @Override public NamespacedInOutCreateable localSubjectAccessReview() { - return Handlers.getNamespacedHasMetadataCreateOnlyOperation(LocalSubjectAccessReview.class, httpClient, getConfiguration()); + return Handlers.getNamespacedHasMetadataCreateOnlyOperation(LocalSubjectAccessReview.class, this); } @Override public InOutCreateable selfSubjectRulesReview() { - return Handlers.getNonListingOperation(SelfSubjectRulesReview.class, httpClient, getConfiguration()); + return Handlers.getNonListingOperation(SelfSubjectRulesReview.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AuthorizationAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AuthorizationAPIGroupExtensionAdapter.java index c6c7a45c350..7d1e7a0d671 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AuthorizationAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AuthorizationAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1AuthorizationAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1AuthorizationAPIGroupClient newInstance(Client client) { - return new V1AuthorizationAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1AuthorizationAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AutoscalingAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AutoscalingAPIGroupClient.java index 486f89915ec..f206c1f1c62 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AutoscalingAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AutoscalingAPIGroupClient.java @@ -19,7 +19,6 @@ import io.fabric8.kubernetes.api.model.autoscaling.v1.HorizontalPodAutoscalerList; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1AutoscalingAPIGroupClient extends BaseClient implements V1AutoscalingAPIGroupDSL { @@ -27,11 +26,12 @@ public V1AutoscalingAPIGroupClient() { super(); } - public V1AutoscalingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1AutoscalingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } + @Override public MixedOperation> horizontalPodAutoscalers() { - return Handlers.getOperation(HorizontalPodAutoscaler.class, HorizontalPodAutoscalerList.class, httpClient, getConfiguration()); + return Handlers.getOperation(HorizontalPodAutoscaler.class, HorizontalPodAutoscalerList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AutoscalingAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AutoscalingAPIGroupExtensionAdapter.java index 3afcd59099b..54a3d258e15 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AutoscalingAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1AutoscalingAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1AutoscalingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -31,7 +29,7 @@ public Class getExtensionType() { @Override protected V1AutoscalingAPIGroupClient newInstance(Client client) { - return new V1AutoscalingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1AutoscalingAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1BatchAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1BatchAPIGroupClient.java index b9cf583b99f..5f1198d3f4d 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1BatchAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1BatchAPIGroupClient.java @@ -24,25 +24,24 @@ import io.fabric8.kubernetes.client.dsl.ScalableResource; import io.fabric8.kubernetes.client.dsl.V1BatchAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.internal.batch.v1.JobOperationsImpl; -import okhttp3.OkHttpClient; public class V1BatchAPIGroupClient extends BaseClient implements V1BatchAPIGroupDSL { public V1BatchAPIGroupClient() { super(); } - public V1BatchAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1BatchAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> jobs() { - return new JobOperationsImpl(httpClient, getConfiguration()); + return new JobOperationsImpl(this); } @Override public MixedOperation> cronjobs() { - return Handlers.getOperation(CronJob.class, CronJobList.class, httpClient, getConfiguration()); + return Handlers.getOperation(CronJob.class, CronJobList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1BatchAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1BatchAPIGroupExtensionAdapter.java index b1956a62df5..56a518c94ff 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1BatchAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1BatchAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1BatchAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1BatchAPIGroupClient newInstance(Client client) { - return new V1BatchAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1BatchAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1CertificatesAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1CertificatesAPIGroupClient.java index 66362dd198d..477039745e4 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1CertificatesAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1CertificatesAPIGroupClient.java @@ -20,20 +20,19 @@ import io.fabric8.kubernetes.client.dsl.CertificateSigningRequestResource; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.V1CertificatesAPIGroupDSL; -import okhttp3.OkHttpClient; public class V1CertificatesAPIGroupClient extends BaseClient implements V1CertificatesAPIGroupDSL { public V1CertificatesAPIGroupClient() { super(); } - public V1CertificatesAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1CertificatesAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public NonNamespaceOperation> certificateSigningRequests() { - return Handlers.getOperation(CertificateSigningRequest.class, CertificateSigningRequestList.class, httpClient, getConfiguration()); + return Handlers.getOperation(CertificateSigningRequest.class, CertificateSigningRequestList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1CertificatesAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1CertificatesAPIGroupExtensionAdapter.java index a55721480f7..f4bd701ba82 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1CertificatesAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1CertificatesAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1CertificatesAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1CertificatesAPIGroupClient newInstance(Client client) { - return new V1CertificatesAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1CertificatesAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1DiscoveryAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1DiscoveryAPIGroupClient.java index fa233e3ae5d..bc7ca33e946 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1DiscoveryAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1DiscoveryAPIGroupClient.java @@ -20,19 +20,18 @@ import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1DiscoveryAPIGroupDSL; -import okhttp3.OkHttpClient; public class V1DiscoveryAPIGroupClient extends BaseClient implements V1DiscoveryAPIGroupDSL { public V1DiscoveryAPIGroupClient() { super(); } - public V1DiscoveryAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1DiscoveryAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> endpointSlices() { - return Handlers.getOperation(EndpointSlice.class, EndpointSliceList.class, httpClient, getConfiguration()); + return Handlers.getOperation(EndpointSlice.class, EndpointSliceList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1DiscoveryAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1DiscoveryAPIGroupExtensionAdapter.java index 028f52401b3..622f1368afc 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1DiscoveryAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1DiscoveryAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1DiscoveryAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1DiscoveryAPIGroupClient newInstance(Client client) { - return new V1DiscoveryAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1DiscoveryAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1EventingAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1EventingAPIGroupClient.java index 4a91b65cffb..7562eb7719c 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1EventingAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1EventingAPIGroupClient.java @@ -20,19 +20,18 @@ import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1EventingAPIGroupDSL; -import okhttp3.OkHttpClient; public class V1EventingAPIGroupClient extends BaseClient implements V1EventingAPIGroupDSL { public V1EventingAPIGroupClient() { super(); } - public V1EventingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1EventingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> events() { - return Handlers.getOperation(Event.class, EventList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Event.class, EventList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1EventingAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1EventingAPIGroupExtensionAdapter.java index 2918d7324a0..f91f28d2743 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1EventingAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1EventingAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1EventingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1EventingAPIGroupClient newInstance(Client client) { - return new V1EventingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1EventingAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1NetworkAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1NetworkAPIGroupClient.java index 15515cb580b..b138a5a6927 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1NetworkAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1NetworkAPIGroupClient.java @@ -23,29 +23,28 @@ import io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyList; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1NetworkAPIGroupClient extends BaseClient implements V1NetworkAPIGroupDSL { public V1NetworkAPIGroupClient() { super(); } - public V1NetworkAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1NetworkAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> networkPolicies() { - return Handlers.getOperation(NetworkPolicy.class, NetworkPolicyList.class, httpClient, getConfiguration()); + return Handlers.getOperation(NetworkPolicy.class, NetworkPolicyList.class, this); } @Override public MixedOperation> ingresses() { - return Handlers.getOperation(Ingress.class, IngressList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Ingress.class, IngressList.class, this); } @Override public MixedOperation> ingressClasses() { - return Handlers.getOperation(IngressClass.class, IngressClassList.class, httpClient, getConfiguration()); + return Handlers.getOperation(IngressClass.class, IngressClassList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1NetworkAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1NetworkAPIGroupExtensionAdapter.java index 74b676b0644..240f945e987 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1NetworkAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1NetworkAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1NetworkAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1NetworkAPIGroupClient newInstance(Client client) { - return new V1NetworkAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1NetworkAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1PolicyAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1PolicyAPIGroupClient.java index bfe699ab34f..3db83e2c455 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1PolicyAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1PolicyAPIGroupClient.java @@ -20,19 +20,18 @@ import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1PolicyAPIGroupDSL; -import okhttp3.OkHttpClient; public class V1PolicyAPIGroupClient extends BaseClient implements V1PolicyAPIGroupDSL { public V1PolicyAPIGroupClient() { super(); } - public V1PolicyAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1PolicyAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> podDisruptionBudget() { - return Handlers.getOperation(PodDisruptionBudget.class, PodDisruptionBudgetList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PodDisruptionBudget.class, PodDisruptionBudgetList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1PolicyAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1PolicyAPIGroupExtensionAdapter.java index 71d310a55a6..79f448b5b92 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1PolicyAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1PolicyAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1PolicyAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1PolicyAPIGroupClient newInstance(Client client) { - return new V1PolicyAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1PolicyAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1SchedulingAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1SchedulingAPIGroupClient.java index 57cc9d57802..b4c0471e24d 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1SchedulingAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1SchedulingAPIGroupClient.java @@ -20,7 +20,6 @@ import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1SchedulingAPIGroupDSL; -import okhttp3.OkHttpClient; public class V1SchedulingAPIGroupClient extends BaseClient implements V1SchedulingAPIGroupDSL { @@ -28,11 +27,12 @@ public V1SchedulingAPIGroupClient() { super(); } - public V1SchedulingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1SchedulingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } + @Override public NonNamespaceOperation> priorityClasses() { - return Handlers.getOperation(PriorityClass.class, PriorityClassList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PriorityClass.class, PriorityClassList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1SchedulingAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1SchedulingAPIGroupExtensionAdapter.java index e578dda5773..9cef723b6f7 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1SchedulingAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1SchedulingAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1SchedulingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1SchedulingAPIGroupClient newInstance(Client client) { - return new V1SchedulingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1SchedulingAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AdmissionRegistrationAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AdmissionRegistrationAPIGroupClient.java index c7edc6ed914..fd908a16c4c 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AdmissionRegistrationAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AdmissionRegistrationAPIGroupClient.java @@ -22,24 +22,23 @@ import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1beta1AdmissionRegistrationAPIGroupClient extends BaseClient implements V1beta1AdmissionRegistrationAPIGroupDSL { public V1beta1AdmissionRegistrationAPIGroupClient() { super(); } - public V1beta1AdmissionRegistrationAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1AdmissionRegistrationAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> validatingWebhookConfigurations() { - return Handlers.getOperation(ValidatingWebhookConfiguration.class, ValidatingWebhookConfigurationList.class, httpClient, getConfiguration()); + return Handlers.getOperation(ValidatingWebhookConfiguration.class, ValidatingWebhookConfigurationList.class, this); } @Override public NonNamespaceOperation> mutatingWebhookConfigurations() { - return Handlers.getOperation(MutatingWebhookConfiguration.class, MutatingWebhookConfigurationList.class, httpClient, getConfiguration()); + return Handlers.getOperation(MutatingWebhookConfiguration.class, MutatingWebhookConfigurationList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AdmissionRegistrationAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AdmissionRegistrationAPIGroupExtensionAdapter.java index d8ece040cb2..4f2788f6108 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AdmissionRegistrationAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AdmissionRegistrationAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1beta1AdmissionRegistrationAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1beta1AdmissionRegistrationAPIGroupClient newInstance(Client client) { - return new V1beta1AdmissionRegistrationAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1AdmissionRegistrationAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1ApiextensionsAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1ApiextensionsAPIGroupClient.java index 55d42bf0e2e..6f090b15160 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1ApiextensionsAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1ApiextensionsAPIGroupClient.java @@ -19,18 +19,18 @@ import io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinitionList; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1beta1ApiextensionsAPIGroupClient extends BaseClient implements V1beta1ApiextensionAPIGroupDSL { public V1beta1ApiextensionsAPIGroupClient() { super(); } - public V1beta1ApiextensionsAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1ApiextensionsAPIGroupClient(ClientContext clientContext) { + super(clientContext); } + @Override public MixedOperation> customResourceDefinitions() { - return Handlers.getOperation(CustomResourceDefinition.class, CustomResourceDefinitionList.class, httpClient, getConfiguration()); + return Handlers.getOperation(CustomResourceDefinition.class, CustomResourceDefinitionList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1ApiextensionsAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1ApiextensionsAPIGroupExtensionAdapter.java index 1055924946c..cdee631f359 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1ApiextensionsAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1ApiextensionsAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1beta1ApiextensionsAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1beta1ApiextensionsAPIGroupClient newInstance(Client client) { - return new V1beta1ApiextensionsAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1ApiextensionsAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AuthorizationAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AuthorizationAPIGroupClient.java index 0582ad0daa0..800d8715dd4 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AuthorizationAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AuthorizationAPIGroupClient.java @@ -21,7 +21,6 @@ import io.fabric8.kubernetes.api.model.authorization.v1beta1.SubjectAccessReview; import io.fabric8.kubernetes.client.dsl.InOutCreateable; import io.fabric8.kubernetes.client.dsl.NamespacedInOutCreateable; -import okhttp3.OkHttpClient; public class V1beta1AuthorizationAPIGroupClient extends BaseClient implements V1beta1AuthorizationAPIGroupDSL { @@ -32,27 +31,27 @@ public V1beta1AuthorizationAPIGroupClient() { super(); } - public V1beta1AuthorizationAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1AuthorizationAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public InOutCreateable selfSubjectAccessReview() { - return Handlers.getNonListingOperation(SelfSubjectAccessReview.class, getHttpClient(), getConfiguration()); + return Handlers.getNonListingOperation(SelfSubjectAccessReview.class, this); } @Override public InOutCreateable subjectAccessReview() { - return Handlers.getNonListingOperation(SubjectAccessReview.class, getHttpClient(), getConfiguration()); + return Handlers.getNonListingOperation(SubjectAccessReview.class, this); } @Override public NamespacedInOutCreateable localSubjectAccessReview() { - return Handlers.getNamespacedHasMetadataCreateOnlyOperation(LocalSubjectAccessReview.class, getHttpClient(), getConfiguration()); + return Handlers.getNamespacedHasMetadataCreateOnlyOperation(LocalSubjectAccessReview.class, this); } @Override public InOutCreateable selfSubjectRulesReview() { - return Handlers.getNonListingOperation(SelfSubjectRulesReview.class, getHttpClient(), getConfiguration()); + return Handlers.getNonListingOperation(SelfSubjectRulesReview.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AuthorizationAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AuthorizationAPIGroupExtensionAdapter.java index 2e76513d744..c71a0854d25 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AuthorizationAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1AuthorizationAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1beta1AuthorizationAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1beta1AuthorizationAPIGroupClient newInstance(Client client) { - return new V1beta1AuthorizationAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1AuthorizationAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1BatchAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1BatchAPIGroupClient.java index 08911f62587..f2f846073c8 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1BatchAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1BatchAPIGroupClient.java @@ -21,19 +21,18 @@ import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1beta1BatchAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.internal.batch.v1beta1.CronJobOperationsImpl; -import okhttp3.OkHttpClient; public class V1beta1BatchAPIGroupClient extends BaseClient implements V1beta1BatchAPIGroupDSL { public V1beta1BatchAPIGroupClient() { super(); } - public V1beta1BatchAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1BatchAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> cronjobs() { - return new CronJobOperationsImpl(httpClient, getConfiguration()); + return new CronJobOperationsImpl(this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1BatchAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1BatchAPIGroupExtensionAdapter.java index feb7162d7ea..71552960794 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1BatchAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1BatchAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1beta1BatchAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1beta1BatchAPIGroupClient newInstance(Client client) { - return new V1beta1BatchAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1BatchAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1CertificatesAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1CertificatesAPIGroupClient.java index 02986e5e902..817a955e04d 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1CertificatesAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1CertificatesAPIGroupClient.java @@ -20,19 +20,18 @@ import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1beta1CertificatesAPIGroupDSL; -import okhttp3.OkHttpClient; public class V1beta1CertificatesAPIGroupClient extends BaseClient implements V1beta1CertificatesAPIGroupDSL { public V1beta1CertificatesAPIGroupClient() { super(); } - public V1beta1CertificatesAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1CertificatesAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public NonNamespaceOperation> certificateSigningRequests() { - return Handlers.getOperation(CertificateSigningRequest.class, CertificateSigningRequestList.class, httpClient, getConfiguration()); + return Handlers.getOperation(CertificateSigningRequest.class, CertificateSigningRequestList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1CertificatesAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1CertificatesAPIGroupExtensionAdapter.java index 3b6d53c96a1..aa830a227ca 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1CertificatesAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1CertificatesAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1beta1CertificatesAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1beta1CertificatesAPIGroupClient newInstance(Client client) { - return new V1beta1CertificatesAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1CertificatesAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1DiscoveryAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1DiscoveryAPIGroupClient.java index da78bc07793..da051df5340 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1DiscoveryAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1DiscoveryAPIGroupClient.java @@ -20,19 +20,18 @@ import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1beta1DiscoveryAPIGroupDSL; -import okhttp3.OkHttpClient; public class V1beta1DiscoveryAPIGroupClient extends BaseClient implements V1beta1DiscoveryAPIGroupDSL { public V1beta1DiscoveryAPIGroupClient() { super(); } - public V1beta1DiscoveryAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1DiscoveryAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> endpointSlices() { - return Handlers.getOperation(EndpointSlice.class, EndpointSliceList.class, httpClient, getConfiguration()); + return Handlers.getOperation(EndpointSlice.class, EndpointSliceList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1DiscoveryAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1DiscoveryAPIGroupExtensionAdapter.java index 5f1cef268aa..32a32f6799a 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1DiscoveryAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1DiscoveryAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1beta1DiscoveryAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1beta1DiscoveryAPIGroupClient newInstance(Client client) { - return new V1beta1DiscoveryAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1DiscoveryAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1EventingAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1EventingAPIGroupClient.java index a46d54c60f0..42b8a08ec35 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1EventingAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1EventingAPIGroupClient.java @@ -20,19 +20,18 @@ import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1beta1EventingAPIGroupDSL; -import okhttp3.OkHttpClient; public class V1beta1EventingAPIGroupClient extends BaseClient implements V1beta1EventingAPIGroupDSL { public V1beta1EventingAPIGroupClient() { super(); } - public V1beta1EventingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1EventingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> events() { - return Handlers.getOperation(Event.class, EventList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Event.class, EventList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1EventingAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1EventingAPIGroupExtensionAdapter.java index f4cda0cbdd0..60668b3eb6b 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1EventingAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1EventingAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1beta1EventingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1beta1EventingAPIGroupClient newInstance(Client client) { - return new V1beta1EventingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1EventingAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1FlowControlAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1FlowControlAPIGroupClient.java index 6a0693793db..dc8586207ab 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1FlowControlAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1FlowControlAPIGroupClient.java @@ -22,24 +22,23 @@ import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1beta1FlowControlAPIGroupDSL; -import okhttp3.OkHttpClient; public class V1beta1FlowControlAPIGroupClient extends BaseClient implements V1beta1FlowControlAPIGroupDSL { public V1beta1FlowControlAPIGroupClient() { super(); } - public V1beta1FlowControlAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1FlowControlAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public NonNamespaceOperation> flowSchema() { - return Handlers.getOperation(FlowSchema.class, FlowSchemaList.class, httpClient, getConfiguration()); + return Handlers.getOperation(FlowSchema.class, FlowSchemaList.class, this); } @Override public NonNamespaceOperation> priorityLevelConfigurations() { - return Handlers.getOperation(PriorityLevelConfiguration.class, PriorityLevelConfigurationList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PriorityLevelConfiguration.class, PriorityLevelConfigurationList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1FlowControlAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1FlowControlAPIGroupExtensionAdapter.java index fdf7942e23d..7c16fdaf977 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1FlowControlAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1FlowControlAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1beta1FlowControlAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,7 +28,7 @@ public Class getExtensionType() { @Override protected V1beta1FlowControlAPIGroupClient newInstance(Client client) { - return new V1beta1FlowControlAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1FlowControlAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1NetworkAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1NetworkAPIGroupClient.java index 06133952a95..35c2d2758f2 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1NetworkAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1NetworkAPIGroupClient.java @@ -21,24 +21,23 @@ import io.fabric8.kubernetes.api.model.networking.v1beta1.IngressList; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V1beta1NetworkAPIGroupClient extends BaseClient implements V1beta1NetworkAPIGroupDSL { public V1beta1NetworkAPIGroupClient() { super(); } - public V1beta1NetworkAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1NetworkAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> ingresses() { - return Handlers.getOperation(Ingress.class, IngressList.class, httpClient, getConfiguration()); + return Handlers.getOperation(Ingress.class, IngressList.class, this); } @Override public MixedOperation> ingressClasses() { - return Handlers.getOperation(IngressClass.class, IngressClassList.class, httpClient, getConfiguration()); + return Handlers.getOperation(IngressClass.class, IngressClassList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1NetworkAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1NetworkAPIGroupExtensionAdapter.java index 4c7beb70184..70dcde6d27b 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1NetworkAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1NetworkAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1beta1NetworkAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1beta1NetworkAPIGroupClient newInstance(Client client) { - return new V1beta1NetworkAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1NetworkAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1PolicyAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1PolicyAPIGroupClient.java index 36378aa68fb..4436e11f0b7 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1PolicyAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1PolicyAPIGroupClient.java @@ -22,24 +22,23 @@ import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1beta1PolicyAPIGroupDSL; -import okhttp3.OkHttpClient; public class V1beta1PolicyAPIGroupClient extends BaseClient implements V1beta1PolicyAPIGroupDSL { public V1beta1PolicyAPIGroupClient() { super(); } - public V1beta1PolicyAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1PolicyAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> podSecurityPolicies() { - return Handlers.getOperation(PodSecurityPolicy.class, PodSecurityPolicyList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PodSecurityPolicy.class, PodSecurityPolicyList.class, this); } @Override public MixedOperation> podDisruptionBudget() { - return Handlers.getOperation(PodDisruptionBudget.class, PodDisruptionBudgetList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PodDisruptionBudget.class, PodDisruptionBudgetList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1PolicyAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1PolicyAPIGroupExtensionAdapter.java index 604cf48f344..b383aa1c2e6 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1PolicyAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1PolicyAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1beta1PolicyAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,7 +28,7 @@ public Class getExtensionType() { @Override protected V1beta1PolicyAPIGroupClient newInstance(Client client) { - return new V1beta1PolicyAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1PolicyAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1SchedulingAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1SchedulingAPIGroupClient.java index 0a0d9d35fba..76d41616afd 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1SchedulingAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1SchedulingAPIGroupClient.java @@ -20,7 +20,6 @@ import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.V1beta1SchedulingAPIGroupDSL; -import okhttp3.OkHttpClient; public class V1beta1SchedulingAPIGroupClient extends BaseClient implements V1beta1SchedulingAPIGroupDSL { @@ -28,11 +27,12 @@ public V1beta1SchedulingAPIGroupClient() { super(); } - public V1beta1SchedulingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1SchedulingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } + @Override public NonNamespaceOperation> priorityClasses() { - return Handlers.getOperation(PriorityClass.class, PriorityClassList.class, httpClient, getConfiguration()); + return Handlers.getOperation(PriorityClass.class, PriorityClassList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1SchedulingAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1SchedulingAPIGroupExtensionAdapter.java index fbb6d9251e7..ee6aa8e9076 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1SchedulingAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V1beta1SchedulingAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V1beta1SchedulingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override protected String getAPIGroupName() { @@ -30,6 +28,6 @@ public Class getExtensionType() { @Override protected V1beta1SchedulingAPIGroupClient newInstance(Client client) { - return new V1beta1SchedulingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1SchedulingAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta1AutoscalingAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta1AutoscalingAPIGroupClient.java index 5af4060cf44..f00deeb0050 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta1AutoscalingAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta1AutoscalingAPIGroupClient.java @@ -19,7 +19,6 @@ import io.fabric8.kubernetes.api.model.autoscaling.v2beta1.HorizontalPodAutoscalerList; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V2beta1AutoscalingAPIGroupClient extends BaseClient implements V2beta1AutoscalingAPIGroupDSL { @@ -27,11 +26,12 @@ public V2beta1AutoscalingAPIGroupClient() { super(); } - public V2beta1AutoscalingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V2beta1AutoscalingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } + @Override public MixedOperation> horizontalPodAutoscalers() { - return Handlers.getOperation(HorizontalPodAutoscaler.class, HorizontalPodAutoscalerList.class, httpClient, getConfiguration()); + return Handlers.getOperation(HorizontalPodAutoscaler.class, HorizontalPodAutoscalerList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta1AutoscalingAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta1AutoscalingAPIGroupExtensionAdapter.java index aea9d19c604..4c16682ddc9 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta1AutoscalingAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta1AutoscalingAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V2beta1AutoscalingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -31,7 +29,7 @@ public Class getExtensionType() { @Override protected V2beta1AutoscalingAPIGroupClient newInstance(Client client) { - return new V2beta1AutoscalingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V2beta1AutoscalingAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta2AutoscalingAPIGroupClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta2AutoscalingAPIGroupClient.java index 868ba9097a4..37a425bbfe2 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta2AutoscalingAPIGroupClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta2AutoscalingAPIGroupClient.java @@ -19,7 +19,6 @@ import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerList; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import okhttp3.OkHttpClient; public class V2beta2AutoscalingAPIGroupClient extends BaseClient implements V2beta2AutoscalingAPIGroupDSL { @@ -27,11 +26,12 @@ public V2beta2AutoscalingAPIGroupClient() { super(); } - public V2beta2AutoscalingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V2beta2AutoscalingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } + @Override public MixedOperation> horizontalPodAutoscalers() { - return Handlers.getOperation(HorizontalPodAutoscaler.class, HorizontalPodAutoscalerList.class, httpClient, getConfiguration()); + return Handlers.getOperation(HorizontalPodAutoscaler.class, HorizontalPodAutoscalerList.class, this); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta2AutoscalingAPIGroupExtensionAdapter.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta2AutoscalingAPIGroupExtensionAdapter.java index 69822151e7c..2114f31f633 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta2AutoscalingAPIGroupExtensionAdapter.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/V2beta2AutoscalingAPIGroupExtensionAdapter.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client; -import okhttp3.OkHttpClient; - public class V2beta2AutoscalingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -31,7 +29,7 @@ public Class getExtensionType() { @Override protected V2beta2AutoscalingAPIGroupClient newInstance(Client client) { - return new V2beta2AutoscalingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V2beta2AutoscalingAPIGroupClient(client); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/ExecListener.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/ExecListener.java index b9ae6beeb92..eea39b724f2 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/ExecListener.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/ExecListener.java @@ -15,32 +15,38 @@ */ package io.fabric8.kubernetes.client.dsl; -import okhttp3.Response; - +import java.io.IOException; public interface ExecListener { + + public interface Response { + + int code(); + + /** + * May be null if not provided by the underlying implementation. + * @return the body as a String + * @throws IOException + */ + String body() throws IOException; + + } /** * Called when the request has successfully been upgraded to a web socket. - * - * @param response OkHttp response object */ - void onOpen( Response response); - - /** - * Called when the transport or protocol layer of this web socket errors during communication. - * - * @param t Throwable - * @param response Present when the failure is a direct result of the response (e.g., failed - * upgrade, non-101 response code, etc.). {@code null} otherwise. - */ - void onFailure(Throwable t, Response response); + default void onOpen() {} + /** + * Called when the transport or protocol layer of this web socket errors during communication. + * + * @param t Throwable + * @param failureResponse non-null if the failure is caused by the handshake + */ + default void onFailure(Throwable t, Response failureResponse) {} /** - * Called when the server sends a close message. This may have been initiated - * from a call to {@link okhttp3.WebSocket#close(int, String) close()} or as an unprompted - * message from the server. + * Called when the server sends a close message. * * @param code The RFC-compliant * status code. diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/BaseOperation.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/BaseOperation.java index f139a01356b..6e569b90c36 100755 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/BaseOperation.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/BaseOperation.java @@ -15,6 +15,10 @@ */ package io.fabric8.kubernetes.client.dsl.base; +import io.fabric8.kubernetes.api.model.ObjectReference; +import io.fabric8.kubernetes.client.dsl.WritableOperation; +import io.fabric8.kubernetes.client.utils.CreateOrReplaceHelper; + import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.builder.Visitor; import io.fabric8.kubernetes.api.model.DeletionPropagation; @@ -23,7 +27,6 @@ import io.fabric8.kubernetes.api.model.LabelSelector; import io.fabric8.kubernetes.api.model.ListOptions; import io.fabric8.kubernetes.api.model.ListOptionsBuilder; -import io.fabric8.kubernetes.api.model.ObjectReference; import io.fabric8.kubernetes.api.model.Status; import io.fabric8.kubernetes.api.model.autoscaling.v1.Scale; import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback; @@ -44,22 +47,19 @@ import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.ReplaceDeletable; import io.fabric8.kubernetes.client.dsl.Resource; -import io.fabric8.kubernetes.client.dsl.WritableOperation; import io.fabric8.kubernetes.client.dsl.internal.DefaultOperationInfo; import io.fabric8.kubernetes.client.dsl.internal.WatchConnectionManager; import io.fabric8.kubernetes.client.dsl.internal.WatchHTTPManager; +import io.fabric8.kubernetes.client.http.HttpRequest; import io.fabric8.kubernetes.client.informers.ListerWatcher; import io.fabric8.kubernetes.client.informers.ResourceEventHandler; import io.fabric8.kubernetes.client.informers.SharedIndexInformer; import io.fabric8.kubernetes.client.informers.impl.DefaultSharedIndexInformer; import io.fabric8.kubernetes.client.internal.readiness.Readiness; -import io.fabric8.kubernetes.client.utils.CreateOrReplaceHelper; -import io.fabric8.kubernetes.client.utils.HttpClientUtils; import io.fabric8.kubernetes.client.utils.URLUtils; +import io.fabric8.kubernetes.client.utils.URLUtils.URLBuilder; import io.fabric8.kubernetes.client.utils.Utils; import io.fabric8.kubernetes.client.utils.WatcherToggle; -import okhttp3.HttpUrl; -import okhttp3.Request; import java.io.File; import java.io.FileInputStream; @@ -73,7 +73,6 @@ import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; @@ -89,6 +88,7 @@ public class BaseOperation, ListerWatcher { + private static final String WATCH = "watch"; private static final String READ_ONLY_UPDATE_EXCEPTION_MESSAGE = "Cannot update read-only resources"; private static final String READ_ONLY_EDIT_EXCEPTION_MESSAGE = "Cannot edit read-only resources"; @@ -127,22 +127,20 @@ public BaseOperation newInstance(OperationContext context) { */ private L listRequestHelper(URL url) { try { - HttpUrl.Builder requestUrlBuilder = HttpUrl.get(url).newBuilder(); - - Request.Builder requestBuilder = new Request.Builder().get().url(requestUrlBuilder.build()); + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().url(url); L answer = handleResponse(requestBuilder, listType); updateApiVersion(answer); return answer; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(forOperationType("list"), ie); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(forOperationType("list"), e); } } - protected URL fetchListUrl(URL url, ListOptions listOptions) throws MalformedURLException { - return new URL(HttpClientUtils.appendListOptionParams(HttpUrl.get(url.toString()).newBuilder(), listOptions).toString()); + protected URL fetchListUrl(URL url, ListOptions listOptions) { + return appendListOptionParams(url, listOptions); } @Override @@ -185,7 +183,7 @@ public T getMandatory() { } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(forOperationType("get"), ie); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(forOperationType("get"), e); } } @@ -505,7 +503,7 @@ public T updateStatus(T item) { } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(forOperationType("statusUpdate"), ie); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(forOperationType("statusUpdate"), e); } @@ -561,7 +559,7 @@ public Watch watch(ListOptions options, final Watcher watcher) { WatchConnectionManager watch = null; try { watch = new WatchConnectionManager<>( - client, + httpClient, this, options, watcherToggle, @@ -572,7 +570,7 @@ public Watch watch(ListOptions options, final Watcher watcher) { watch.waitUntilReady(); return watch; } catch (MalformedURLException e) { - throw KubernetesClientException.launderThrowable(forOperationType("watch"), e); + throw KubernetesClientException.launderThrowable(forOperationType(WATCH), e); } catch (KubernetesClientException ke) { List furtherProcessedCodes = Arrays.asList(200, 503); if (!furtherProcessedCodes.contains(ke.getCode())) { @@ -595,7 +593,7 @@ public Watch watch(ListOptions options, final Watcher watcher) { // websockets. Issue: https://github.com/kubernetes/kubernetes/issues/25126 try { return new WatchHTTPManager<>( - client, + httpClient, this, options, watcher, @@ -604,7 +602,7 @@ public Watch watch(ListOptions options, final Watcher watcher) { config.getConnectionTimeout() ); } catch (MalformedURLException e) { - throw KubernetesClientException.launderThrowable(forOperationType("watch"), e); + throw KubernetesClientException.launderThrowable(forOperationType(WATCH), e); } } } @@ -634,27 +632,27 @@ public boolean isResourceNamespaced() { return Utils.isResourceNamespaced(getType()); } - protected T handleResponse(Request.Builder requestBuilder) throws ExecutionException, InterruptedException, IOException { + protected T handleResponse(HttpRequest.Builder requestBuilder) throws InterruptedException, IOException { return handleResponse(requestBuilder, getType()); } @Override - protected T handleCreate(T resource) throws ExecutionException, InterruptedException, IOException { + protected T handleCreate(T resource) throws InterruptedException, IOException { updateApiVersion(resource); return handleCreate(resource, getType()); } - protected T handleUpdate(T updated, boolean status) throws ExecutionException, InterruptedException, IOException { + protected T handleUpdate(T updated, boolean status) throws InterruptedException, IOException { updateApiVersion(updated); return handleUpdate(updated, getType(), status); } - protected T handlePatch(PatchContext context, T current, T updated, boolean status) throws ExecutionException, InterruptedException, IOException { + protected T handlePatch(PatchContext context, T current, T updated, boolean status) throws InterruptedException, IOException { updateApiVersion(updated); return handlePatch(context, current, updated, getType(), status); } - protected T handlePatch(T current, Map patchedUpdate) throws ExecutionException, InterruptedException, IOException { + protected T handlePatch(T current, Map patchedUpdate) throws InterruptedException, IOException { updateApiVersion(current); return handlePatch(current, patchedUpdate, getType()); } @@ -665,7 +663,7 @@ protected T sendPatchedObject(T oldObject, T updatedObject) { } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(interruptedException); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(e); } } @@ -676,7 +674,7 @@ protected Scale handleScale(Scale scaleParam) { } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(forOperationType("scale"), ie); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(forOperationType("scale"), e); } @@ -688,13 +686,13 @@ protected Status handleDeploymentRollback(DeploymentRollback deploymentRollback) } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(forOperationType("rollback"), ie); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(forOperationType("rollback"), e); } } - protected T handleGet(URL resourceUrl) throws InterruptedException, ExecutionException, IOException { + protected T handleGet(URL resourceUrl) throws InterruptedException, IOException { T answer = handleGet(resourceUrl, getType()); updateApiVersion(answer); return answer; @@ -966,5 +964,44 @@ private DefaultSharedIndexInformer createInformer(long resync) { } return informer; } + + public static URL appendListOptionParams(URL base, ListOptions listOptions) { + if (listOptions == null) { + return base; + } + URLBuilder urlBuilder = new URLBuilder(base); + if (listOptions.getLimit() != null) { + urlBuilder.addQueryParameter("limit", listOptions.getLimit().toString()); + } + if (listOptions.getContinue() != null) { + urlBuilder.addQueryParameter("continue", listOptions.getContinue()); + } + + if (listOptions.getFieldSelector() != null) { + urlBuilder.addQueryParameter("fieldSelector", listOptions.getFieldSelector()); + } + + if (listOptions.getLabelSelector() != null) { + urlBuilder.addQueryParameter("labelSelector", listOptions.getLabelSelector()); + } + + if (listOptions.getResourceVersion() != null) { + urlBuilder.addQueryParameter("resourceVersion", listOptions.getResourceVersion()); + } + + if (listOptions.getTimeoutSeconds() != null) { + urlBuilder.addQueryParameter("timeoutSeconds", listOptions.getTimeoutSeconds().toString()); + } + + if (listOptions.getAllowWatchBookmarks() != null) { + urlBuilder.addQueryParameter("allowWatchBookmarks", listOptions.getAllowWatchBookmarks().toString()); + } + + if (listOptions.getWatch() != null) { + urlBuilder.addQueryParameter(WATCH, listOptions.getWatch().toString()); + } + return urlBuilder.build(); + } + } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/HasMetadataOperation.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/HasMetadataOperation.java index aecc83abe99..d4a52b664ba 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/HasMetadataOperation.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/HasMetadataOperation.java @@ -33,7 +33,6 @@ import io.fabric8.kubernetes.client.utils.Utils; import java.io.IOException; -import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Supplier; @@ -48,7 +47,7 @@ public class HasMetadataOperation type, Class listType) { super(ctx); this.type = type; @@ -89,7 +88,7 @@ public T accept(Consumer consumer) { } protected > VisitableBuilder createVisitableBuilder(T item) { - ResourceHandler handler = Handlers.get(item, new BaseClient(this.client, this.config)); + ResourceHandler handler = Handlers.get(item, new BaseClient(context)); if (handler != null) { return handler.edit(item); } @@ -266,7 +265,7 @@ public T patch(PatchContext patchContext, String patch) { } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(forOperationType(PATCH_OPERATION), interruptedException); - } catch (IOException | ExecutionException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(forOperationType(PATCH_OPERATION), e); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationContext.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationContext.java index 9709b81cd2f..83a082b3a35 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationContext.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationContext.java @@ -17,9 +17,10 @@ import io.fabric8.kubernetes.api.model.DeletionPropagation; import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.SimpleClientContext; +import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.kubernetes.client.utils.ApiVersionUtil; import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.OkHttpClient; import java.util.Arrays; import java.util.HashMap; @@ -28,10 +29,8 @@ import java.util.function.BiFunction; import java.util.stream.Collectors; -public class OperationContext { +public class OperationContext extends SimpleClientContext { - protected OkHttpClient client; - protected Config config; protected Object item; protected String resourceVersion; protected String plural; @@ -67,16 +66,16 @@ public OperationContext() { } public OperationContext(OperationContext other) { - this(other.client, other.config, other.plural, other.namespace, other.name, other.apiGroupName, other.apiGroupVersion, other.cascading, other.item, other.labels, other.labelsNot, other.labelsIn, other.labelsNotIn, other.fields, other.fieldsNot, other.resourceVersion, other.reloadingFromServer, other.gracePeriodSeconds, other.propagationPolicy, other.namespaceFromGlobalConfig, other.dryRun, other.selectorAsString); + this(other.httpClient, other.config, other.plural, other.namespace, other.name, other.apiGroupName, other.apiGroupVersion, other.cascading, other.item, other.labels, other.labelsNot, other.labelsIn, other.labelsNotIn, other.fields, other.fieldsNot, other.resourceVersion, other.reloadingFromServer, other.gracePeriodSeconds, other.propagationPolicy, other.namespaceFromGlobalConfig, other.dryRun, other.selectorAsString); } - public OperationContext(OkHttpClient client, Config config, String plural, String namespace, String name, + public OperationContext(HttpClient client, Config config, String plural, String namespace, String name, String apiGroupName, String apiGroupVersion, boolean cascading, Object item, Map labels, Map labelsNot, Map labelsIn, Map labelsNotIn, Map fields, Map fieldsNot, String resourceVersion, boolean reloadingFromServer, long gracePeriodSeconds, DeletionPropagation propagationPolicy, boolean namespaceFromGlobalConfig, boolean dryRun, String selectorAsString) { - this.client = client; + this.httpClient = client; this.config = config; this.item = item; this.plural = plural; @@ -136,8 +135,8 @@ private void setNamespace(String namespace) { this.namespace = Utils.isNotNullOrEmpty(namespace) ? namespace : (config != null ? config.getNamespace() : null); } - public OkHttpClient getClient() { - return client; + public HttpClient getClient() { + return httpClient; } public Config getConfig() { @@ -282,12 +281,12 @@ public OperationContext copy() { return new OperationContext(this); } - public OperationContext withOkhttpClient(OkHttpClient client) { - if (this.client == client) { + public OperationContext withHttpClient(HttpClient client) { + if (this.httpClient == client) { return this; } final OperationContext context = new OperationContext(this); - context.client = client; + context.httpClient = client; return context; } @@ -510,5 +509,5 @@ public OperationContext withOperationContext(OperationContext context) { Utils.getNonNullOrElse(context.selectorAsString, selectorAsString) ); } - + } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationSupport.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationSupport.java index 7012ab5f36f..964087e93d2 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationSupport.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationSupport.java @@ -28,6 +28,9 @@ import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.KubernetesClientException; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; import io.fabric8.kubernetes.client.internal.VersionUsageUtils; import io.fabric8.kubernetes.client.utils.ExponentialBackoffIntervalCalculator; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; @@ -35,12 +38,6 @@ import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.kubernetes.client.utils.Utils; import io.fabric8.zjsonpatch.JsonDiff; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,19 +46,20 @@ import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.concurrent.ExecutionException; import static io.fabric8.kubernetes.client.internal.PatchUtils.patchMapper; public class OperationSupport { - public static final MediaType JSON = MediaType.parse("application/json"); - public static final MediaType JSON_PATCH = MediaType.parse("application/json-patch+json"); - public static final MediaType STRATEGIC_MERGE_JSON_PATCH = MediaType.parse("application/strategic-merge-patch+json"); - public static final MediaType JSON_MERGE_PATCH = MediaType.parse("application/merge-patch+json"); + public static final String JSON = "application/json"; + public static final String JSON_PATCH = "application/json-patch+json"; + public static final String STRATEGIC_MERGE_JSON_PATCH = "application/strategic-merge-patch+json"; + public static final String JSON_MERGE_PATCH = "application/merge-patch+json"; + protected static final ObjectMapper JSON_MAPPER = Serialization.jsonMapper(); protected static final ObjectMapper YAML_MAPPER = Serialization.yamlMapper(); private static final Logger LOG = LoggerFactory.getLogger(OperationSupport.class); @@ -69,7 +67,7 @@ public class OperationSupport { private static final int maxRetryIntervalExponent = 5; protected OperationContext context; - protected final OkHttpClient client; + protected final HttpClient httpClient; protected final Config config; protected final String resourceT; protected String namespace; @@ -84,17 +82,13 @@ public OperationSupport() { this (new OperationContext()); } - public OperationSupport(OkHttpClient client, Config config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); - } - - public OperationSupport(OkHttpClient client, Config config, String namespace, DeletionPropagation propagationPolicy, long gracePeriodInSeconds) { - this(new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(propagationPolicy).withGracePeriodSeconds(gracePeriodInSeconds)); + public OperationSupport(HttpClient client, Config config) { + this(new OperationContext().withHttpClient(client).withConfig(config)); } public OperationSupport(OperationContext ctx) { this.context = ctx; - this.client = ctx.getClient(); + this.httpClient = ctx.getClient(); this.config = ctx.getConfig(); this.resourceT = ctx.getPlural(); this.namespace = ctx.getNamespace(); @@ -257,19 +251,17 @@ protected String checkName(T item) { throw new KubernetesClientException("Name mismatch. Item name:" + itemName + ". Operation name:" + operationName + "."); } - protected T handleMetric(String resourceUrl, Class type) throws InterruptedException, IOException, ExecutionException { - Request.Builder requestBuilder = new Request.Builder() - .get() - .url(resourceUrl); + protected T handleMetric(String resourceUrl, Class type) throws InterruptedException, IOException { + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() + .uri(resourceUrl); return handleResponse(requestBuilder, type); } - protected void handleDelete(T resource, long gracePeriodSeconds, DeletionPropagation propagationPolicy, String resourceVersion, boolean cascading) throws ExecutionException, InterruptedException, IOException { + protected void handleDelete(T resource, long gracePeriodSeconds, DeletionPropagation propagationPolicy, String resourceVersion, boolean cascading) throws InterruptedException, IOException { handleDelete(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(resource), checkName(resource))), gracePeriodSeconds, propagationPolicy, resourceVersion, cascading); } - protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPropagation propagationPolicy, String resourceVersion, boolean cascading) throws ExecutionException, InterruptedException, IOException { - RequestBody requestBody = null; + protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPropagation propagationPolicy, String resourceVersion, boolean cascading) throws InterruptedException, IOException { DeleteOptions deleteOptions = new DeleteOptions(); if (gracePeriodSeconds >= 0) { deleteOptions.setGracePeriodSeconds(gracePeriodSeconds); @@ -289,9 +281,8 @@ protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPro if (dryRun) { deleteOptions.setDryRun(Collections.singletonList("All")); } - requestBody = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(deleteOptions)); - Request.Builder requestBuilder = new Request.Builder().delete(requestBody).url(requestUrl); + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().delete(JSON, JSON_MAPPER.writeValueAsString(deleteOptions)).url(requestUrl); handleResponse(requestBuilder, null, Collections.emptyMap()); } @@ -305,13 +296,13 @@ protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPro * @param template argument for resource * * @return returns de-serialized version of apiserver response in form of type provided - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ - protected T handleCreate(I resource, Class outputType) throws ExecutionException, InterruptedException, IOException { - RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(resource)); - Request.Builder requestBuilder = new Request.Builder().post(body).url(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(resource), null))); + protected T handleCreate(I resource, Class outputType) throws InterruptedException, IOException { + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() + .post(JSON, JSON_MAPPER.writeValueAsString(resource)) + .url(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(resource), null))); return handleResponse(requestBuilder, outputType, Collections.emptyMap()); } @@ -325,11 +316,10 @@ protected T handleCreate(I resource, Class outputType) throws Executio * @param template argument provided * * @return returns de-serialized version of api server response - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ - protected T handleUpdate(T updated, Class type, boolean status) throws ExecutionException, InterruptedException, IOException { + protected T handleUpdate(T updated, Class type, boolean status) throws InterruptedException, IOException { return handleUpdate(updated, type, Collections.emptyMap(), status); } @@ -343,13 +333,13 @@ protected T handleUpdate(T updated, Class type, boolean status) throws Ex * @param template argument provided * * @return returns de-serialized version of api server response. - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ - protected T handleUpdate(T updated, Class type, Map parameters, boolean status) throws ExecutionException, InterruptedException, IOException { - RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(updated)); - Request.Builder requestBuilder = new Request.Builder().put(body).url(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(updated), checkName(updated), status))); + protected T handleUpdate(T updated, Class type, Map parameters, boolean status) throws InterruptedException, IOException { + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() + .put(JSON, JSON_MAPPER.writeValueAsString(updated)) + .url(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(updated), checkName(updated), status))); return handleResponse(requestBuilder, type, parameters); } @@ -366,11 +356,10 @@ protected T handleUpdate(T updated, Class type, Map param * @param template argument provided * * @return returns de-serialized version of api server response - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ - protected T handlePatch(PatchContext patchContext, T current, T updated, Class type, boolean status) throws ExecutionException, InterruptedException, IOException { + protected T handlePatch(PatchContext patchContext, T current, T updated, Class type, boolean status) throws InterruptedException, IOException { String patchForUpdate = null; if (current != null && (patchContext == null || patchContext.getPatchType() == PatchType.JSON)) { patchForUpdate = JSON_MAPPER.writeValueAsString(JsonDiff.asJson(patchMapper().valueToTree(current), patchMapper().valueToTree(updated))); @@ -393,11 +382,10 @@ protected T handlePatch(PatchContext patchContext, T current, T updated, Cla * @param template argument provided * * @return returns de-serialized version of api server response - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ - protected T handlePatch(T current, Map patchForUpdate, Class type) throws ExecutionException, InterruptedException, IOException { + protected T handlePatch(T current, Map patchForUpdate, Class type) throws InterruptedException, IOException { return handlePatch(new PatchContext.Builder().withPatchType(PatchType.STRATEGIC_MERGE).build(), current, JSON_MAPPER.writeValueAsString(patchForUpdate), type, false); } @@ -412,14 +400,15 @@ protected T handlePatch(T current, Map patchForUpdate, Class * @param status if this is only the status subresource * @param template argument provided * @return returns de-serialized version of api server response - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException in case of network errors */ - protected T handlePatch(PatchContext patchContext, T current, String patchForUpdate, Class type, boolean status) throws ExecutionException, InterruptedException, IOException { - MediaType bodyMediaType = getMediaTypeFromPatchContextOrDefault(patchContext); - RequestBody body = RequestBody.create(bodyMediaType, patchForUpdate); - Request.Builder requestBuilder = new Request.Builder().patch(body).url(getResourceURLForPatchOperation(getResourceUrl(checkNamespace(current), checkName(current), status), patchContext)); + protected T handlePatch(PatchContext patchContext, T current, String patchForUpdate, Class type, boolean status) throws InterruptedException, IOException { + String bodyContentType = getContentTypeFromPatchContextOrDefault(patchContext); + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() + .patch(bodyContentType, patchForUpdate) + .url(getResourceURLForPatchOperation(getResourceUrl(checkNamespace(current), checkName(current), status), + patchContext)); return handleResponse(requestBuilder, type, Collections.emptyMap()); } @@ -429,17 +418,13 @@ protected T handlePatch(PatchContext patchContext, T current, String patchFo * @param resourceUrl Kubernetes resource URL * @param scale Scale object which we want to inject * @return updated Scale object - * @throws ExecutionException in case of any execution exception * @throws InterruptedException in case thread is interrupted * @throws IOException in some other I/O problem */ - protected Scale handleScale(String resourceUrl, Scale scale) throws ExecutionException, InterruptedException, IOException { - Request.Builder requestBuilder; + protected Scale handleScale(String resourceUrl, Scale scale) throws InterruptedException, IOException { + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().uri(resourceUrl + "/scale"); if (scale != null) { - RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(scale)); - requestBuilder = new Request.Builder().put(body).url(resourceUrl + "/scale"); - } else { - requestBuilder = new Request.Builder().get().url(resourceUrl + "/scale"); + requestBuilder.put(JSON, JSON_MAPPER.writeValueAsString(scale)); } return handleResponse(requestBuilder, Scale.class); } @@ -450,13 +435,11 @@ protected Scale handleScale(String resourceUrl, Scale scale) throws ExecutionExc * @param resourceUrl resource url * @param deploymentRollback DeploymentRollback resource * @return Status - * @throws ExecutionException in case of any execution exception * @throws InterruptedException in case thread is interrupted * @throws IOException in some other I/O problem */ - protected Status handleDeploymentRollback(String resourceUrl, DeploymentRollback deploymentRollback) throws ExecutionException, InterruptedException, IOException { - RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(deploymentRollback)); - Request.Builder requestBuilder = new Request.Builder().post(body).url(resourceUrl + "/rollback"); + protected Status handleDeploymentRollback(String resourceUrl, DeploymentRollback deploymentRollback) throws InterruptedException, IOException { + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().uri(resourceUrl + "/rollback").post(JSON, JSON_MAPPER.writeValueAsString(deploymentRollback)); return handleResponse(requestBuilder, Status.class); } @@ -468,13 +451,25 @@ protected Status handleDeploymentRollback(String resourceUrl, DeploymentRollback * @param template argument provided * * @return returns a deserialized object as api server response of provided type. - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ - protected T handleGet(URL resourceUrl, Class type) throws ExecutionException, InterruptedException, IOException { + protected T handleGet(URL resourceUrl, Class type) throws InterruptedException, IOException { return handleGet(resourceUrl, type, Collections.emptyMap()); } + + /** + * Send a raw get - where the type should be one of String, Reader, InputStream + *
+ * NOTE: Currently does not utilize the retry logic + */ + protected T handleRawGet(URL resourceUrl, Class type) throws IOException{ + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().url(resourceUrl); + HttpRequest request = requestBuilder.build(); + HttpResponse response = httpClient.send(request, type); + assertResponseCode(request, response); + return response.body(); + } /** * Send an http, optionally performing placeholder substitution to the response. @@ -485,12 +480,11 @@ protected T handleGet(URL resourceUrl, Class type) throws ExecutionExcept * @param template argument provided * * @return Returns a deserialized object as api server response of provided type. - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ - protected T handleGet(URL resourceUrl, Class type, Map parameters) throws ExecutionException, InterruptedException, IOException { - Request.Builder requestBuilder = new Request.Builder().get().url(resourceUrl); + protected T handleGet(URL resourceUrl, Class type, Map parameters) throws InterruptedException, IOException { + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().url(resourceUrl); return handleResponse(requestBuilder, type, parameters); } @@ -502,11 +496,10 @@ protected T handleGet(URL resourceUrl, Class type, Map pa * @param template argument provided * * @return Returns a de-serialized object as api server response of provided type. - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ - protected T handleResponse(Request.Builder requestBuilder, Class type) throws ExecutionException, InterruptedException, IOException { + protected T handleResponse(HttpRequest.Builder requestBuilder, Class type) throws InterruptedException, IOException { return handleResponse(requestBuilder, type, Collections.emptyMap()); } @@ -519,55 +512,50 @@ protected T handleResponse(Request.Builder requestBuilder, Class type) th * @param template argument provided * * @return Returns a de-serialized object as api server response of provided type. - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ - protected T handleResponse(Request.Builder requestBuilder, Class type, Map parameters) throws ExecutionException, InterruptedException, IOException { - return handleResponse(client, requestBuilder, type, parameters); + protected T handleResponse(HttpRequest.Builder requestBuilder, Class type, Map parameters) throws InterruptedException, IOException { + return handleResponse(httpClient, requestBuilder, type, parameters); } /** * Send an http request and handle the response. * - * @param client OkHttp client object + * @param client the client * @param requestBuilder request builder * @param type type of object * @param template argument provided * * @return Returns a de-serialized object as api server response of provided type. - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ - protected T handleResponse(OkHttpClient client, Request.Builder requestBuilder, Class type) throws ExecutionException, InterruptedException, IOException { + protected T handleResponse(HttpClient client, HttpRequest.Builder requestBuilder, Class type) throws InterruptedException, IOException { return handleResponse(client, requestBuilder, type, Collections.emptyMap()); } /** * Send an http request and handle the response, optionally performing placeholder substitution to the response. * - * @param client OkHttp client provided + * @param client the client * @param requestBuilder Request builder * @param type Type of object provided * @param parameters A hashmap containing parameters * @param Template argument provided * * @return Returns a de-serialized object as api server response of provided type. - * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ - protected T handleResponse(OkHttpClient client, Request.Builder requestBuilder, Class type, Map parameters) throws ExecutionException, InterruptedException, IOException { + protected T handleResponse(HttpClient client, HttpRequest.Builder requestBuilder, Class type, Map parameters) throws InterruptedException, IOException { VersionUsageUtils.log(this.resourceT, this.apiGroupVersion); - Request request = requestBuilder.build(); - Response response = retryWithExponentialBackoff(client, request); - try (ResponseBody body = response.body()) { + HttpRequest request = requestBuilder.build(); + HttpResponse response = retryWithExponentialBackoff(client, request); + try (InputStream bodyInputStream = response.body()) { assertResponseCode(request, response); if (type != null) { - try (InputStream bodyInputStream = body.byteStream()) { - return Serialization.unmarshal(bodyInputStream, type, parameters); - } + return Serialization.unmarshal(bodyInputStream, type, parameters); } else { return null; } @@ -576,22 +564,18 @@ protected T handleResponse(OkHttpClient client, Request.Builder requestBuild throw e; } throw requestException(request, e); - } finally { - if(response != null && response.body() != null) { - response.body().close(); - } } } - protected Response retryWithExponentialBackoff(OkHttpClient client, Request request) throws InterruptedException, IOException { + protected HttpResponse retryWithExponentialBackoff(HttpClient client, HttpRequest request) throws InterruptedException, IOException { int numRetries = 0; long retryInterval; while (true) { try { - Response response = client.newCall(request).execute(); + HttpResponse response = client.send(request, InputStream.class); if (numRetries < requestRetryBackoffLimit && response.code() >= 500) { retryInterval = retryIntervalCalculator.getInterval(numRetries); - LOG.debug("HTTP operation on url: {} should be retried as the response code was {}, retrying after {} millis", request.url(), response.code(), retryInterval); + LOG.debug("HTTP operation on url: {} should be retried as the response code was {}, retrying after {} millis", request.uri(), response.code(), retryInterval); if (response.body() != null) { response.body().close(); } @@ -601,7 +585,7 @@ protected Response retryWithExponentialBackoff(OkHttpClient client, Request requ } catch (IOException ie) { if (numRetries < requestRetryBackoffLimit) { retryInterval = retryIntervalCalculator.getInterval(numRetries); - LOG.debug(String.format("HTTP operation on url: %s should be retried after %d millis because of IOException", request.url(), retryInterval), ie); + LOG.debug(String.format("HTTP operation on url: %s should be retried after %d millis because of IOException", request.uri(), retryInterval), ie); } else { throw ie; } @@ -614,10 +598,10 @@ protected Response retryWithExponentialBackoff(OkHttpClient client, Request requ /** * Checks if the response status code is the expected and throws the appropriate KubernetesClientException if not. * - * @param request The {#link Request} object. - * @param response The {@link Response} object. + * @param request The {#link HttpRequest} object. + * @param response The {@link HttpResponse} object. */ - protected void assertResponseCode(Request request, Response response) { + protected void assertResponseCode(HttpRequest request, HttpResponse response) { int statusCode = response.code(); String customMessage = config.getErrorMessages().get(statusCode); @@ -640,27 +624,29 @@ private String combineMessages(String customMessage, Status defaultStatus) { return customMessage; } - - public static Status createStatus(Response response) { + public static Status createStatus(HttpResponse response) { String statusMessage = ""; - ResponseBody body = response != null ? response.body() : null; int statusCode = response != null ? response.code() : 0; - try { - if (response == null) { - statusMessage = "No response"; - } else if (body != null) { - statusMessage = body.string(); - } else if (response.message() != null) { - statusMessage = response.message(); + if (response == null) { + statusMessage = "No response"; + } else { + try { + String bodyString = response.bodyString(); + if (Utils.isNotNullOrEmpty(bodyString)) { + Status status = JSON_MAPPER.readValue(bodyString, Status.class); + if (status.getCode() == null) { + status = new StatusBuilder(status).withCode(statusCode).build(); + } + return status; + } + } catch (IOException e) { + // ignored } - Status status = JSON_MAPPER.readValue(statusMessage, Status.class); - if (status.getCode() == null) { - status = new StatusBuilder(status).withCode(statusCode).build(); + if (response.message() != null) { + statusMessage = response.message(); } - return status; - } catch (IOException e) { - return createStatus(statusCode, statusMessage); } + return createStatus(statusCode, statusMessage); } public static Status createStatus(int statusCode, String message) { @@ -672,18 +658,18 @@ public static Status createStatus(int statusCode, String message) { return status; } - public static KubernetesClientException requestFailure(Request request, Status status) { + public static KubernetesClientException requestFailure(HttpRequest request, Status status) { return requestFailure(request, status, null); } - public static KubernetesClientException requestFailure(Request request, Status status, String message) { + public static KubernetesClientException requestFailure(HttpRequest request, Status status, String message) { StringBuilder sb = new StringBuilder(); if(message != null && !message.isEmpty()) { sb.append(message).append(". "); } sb.append("Failure executing: ").append(request.method()) - .append(" at: ").append(request.url()).append("."); + .append(" at: ").append(request.uri()).append("."); if (status.getMessage() != null && !status.getMessage().isEmpty()) { sb.append(" Message: ").append(status.getMessage()).append("."); @@ -697,21 +683,21 @@ public static KubernetesClientException requestFailure(Request request, Status s return new KubernetesClientException(sb.toString(), status.getCode(), status, metadata.group, metadata.version, metadata.plural, metadata.namespace); } - public static KubernetesClientException requestException(Request request, Throwable e, String message) { + public static KubernetesClientException requestException(HttpRequest request, Throwable e, String message) { StringBuilder sb = new StringBuilder(); if (message != null && !message.isEmpty()) { sb.append(message).append(". "); } sb.append("Error executing: ").append(request.method()) - .append(" at: ").append(request.url()) + .append(" at: ").append(request.uri()) .append(". Cause: ").append(e.getMessage()); final RequestMetadata metadata = RequestMetadata.from(request); return new KubernetesClientException(sb.toString(), e, metadata.group, metadata.version, metadata.plural, metadata.namespace); } - public static KubernetesClientException requestException(Request request, Exception e) { + public static KubernetesClientException requestException(HttpRequest request, Exception e) { return requestException(request, e, null); } @@ -729,8 +715,8 @@ private RequestMetadata(String group, String version, String plural, String name this.namespace = namespace; } - static RequestMetadata from(Request request) { - final List segments = request.url().pathSegments(); + static RequestMetadata from(HttpRequest request) { + final List segments = Arrays.asList(request.uri().getRawPath().split("\\/")); switch (segments.size()) { case 4: // cluster URL @@ -764,9 +750,9 @@ public Config getConfig() { return config; } - private MediaType getMediaTypeFromPatchContextOrDefault(PatchContext patchContext) { + private String getContentTypeFromPatchContextOrDefault(PatchContext patchContext) { if (patchContext != null && patchContext.getPatchType() != null) { - return patchContext.getPatchType().getMediaType(); + return patchContext.getPatchType().getContentType(); } return STRATEGIC_MERGE_JSON_PATCH; } @@ -778,7 +764,7 @@ public R1 restCall(Class result, String... path) { if (path != null && path.length > 0) { url = URLUtils.join(url, URLUtils.pathJoin(path)); } - Request.Builder req = new Request.Builder().get().url(url); + HttpRequest.Builder req = httpClient.newHttpRequestBuilder().uri(url); return handleResponse(req, result); } catch (KubernetesClientException e) { if (e.getCode() != HttpURLConnection.HTTP_NOT_FOUND) { @@ -788,7 +774,7 @@ public R1 restCall(Class result, String... path) { } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(ie); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(e); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/PatchType.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/PatchType.java index e530ce8fd19..57e5867d8e5 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/PatchType.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/PatchType.java @@ -15,8 +15,6 @@ */ package io.fabric8.kubernetes.client.dsl.base; -import okhttp3.MediaType; - import static io.fabric8.kubernetes.client.dsl.base.OperationSupport.JSON_PATCH; import static io.fabric8.kubernetes.client.dsl.base.OperationSupport.JSON_MERGE_PATCH; import static io.fabric8.kubernetes.client.dsl.base.OperationSupport.STRATEGIC_MERGE_JSON_PATCH; @@ -29,13 +27,13 @@ public enum PatchType { JSON_MERGE(JSON_MERGE_PATCH), STRATEGIC_MERGE(STRATEGIC_MERGE_JSON_PATCH); - private final MediaType mediaType; + private final String contentType; - PatchType(MediaType mediaType) { - this.mediaType = mediaType; + PatchType(String mediaType) { + this.contentType = mediaType; } - public MediaType getMediaType() { - return this.mediaType; + public String getContentType() { + return this.contentType; } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManager.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManager.java index ce6fde449e1..a915909c86a 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManager.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManager.java @@ -19,24 +19,26 @@ import io.fabric8.kubernetes.api.model.KubernetesResource; import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.api.model.ListOptions; -import io.fabric8.kubernetes.client.utils.ExponentialBackoffIntervalCalculator; import io.fabric8.kubernetes.api.model.Status; import io.fabric8.kubernetes.api.model.WatchEvent; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.Watch; import io.fabric8.kubernetes.client.Watcher; -import io.fabric8.kubernetes.client.WatcherException; import io.fabric8.kubernetes.client.Watcher.Action; +import io.fabric8.kubernetes.client.WatcherException; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.utils.ExponentialBackoffIntervalCalculator; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.OkHttpClient; -import okhttp3.Request; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -59,13 +61,15 @@ public abstract class AbstractWatchManager implements Wat final AtomicInteger currentReconnectAttempt; private ScheduledFuture reconnectAttempt; - private final BaseOperationRequestBuilder requestBuilder; - protected final OkHttpClient client; + protected final HttpClient client; + private BaseOperation baseOperation; + private ListOptions listOptions; + private URL requestUrl; private final AtomicBoolean reconnectPending = new AtomicBoolean(false); AbstractWatchManager( - Watcher watcher, BaseOperation baseOperation, ListOptions listOptions, int reconnectLimit, int reconnectInterval, int maxIntervalExponent, Supplier clientSupplier + Watcher watcher, BaseOperation baseOperation, ListOptions listOptions, int reconnectLimit, int reconnectInterval, int maxIntervalExponent, Supplier clientSupplier ) throws MalformedURLException { this.watcher = watcher; this.reconnectLimit = reconnectLimit; @@ -73,13 +77,15 @@ public abstract class AbstractWatchManager implements Wat this.resourceVersion = new AtomicReference<>(listOptions.getResourceVersion()); this.currentReconnectAttempt = new AtomicInteger(0); this.forceClosed = new AtomicBoolean(); - this.requestBuilder = new BaseOperationRequestBuilder<>(baseOperation, listOptions); + this.baseOperation = baseOperation; + this.requestUrl = baseOperation.getNamespacedUrl(); + this.listOptions = listOptions; this.client = clientSupplier.get(); runWatch(); } - protected abstract void run(Request request); + protected abstract void run(URL url, Map headers); protected abstract void closeRequest(); @@ -180,8 +186,8 @@ boolean isForceClosed() { void eventReceived(Watcher.Action action, HasMetadata resource) { // the WatchEvent deserialization is not specifically typed // modify the type here if needed - if (resource != null && !requestBuilder.getBaseOperation().getType().isAssignableFrom(resource.getClass())) { - resource = (HasMetadata) Serialization.jsonMapper().convertValue(resource, requestBuilder.getBaseOperation().getType()); + if (resource != null && !baseOperation.getType().isAssignableFrom(resource.getClass())) { + resource = Serialization.jsonMapper().convertValue(resource, baseOperation.getType()); } watcher.eventReceived(action, (T)resource); } @@ -191,11 +197,21 @@ void updateResourceVersion(final String newResourceVersion) { } protected void runWatch() { - final Request request = requestBuilder.build(resourceVersion.get()); - logger.debug("Watching {}...", request.url()); + listOptions.setResourceVersion(resourceVersion.get()); + URL url = BaseOperation.appendListOptionParams(requestUrl, listOptions); + + String origin = requestUrl.getProtocol() + "://" + requestUrl.getHost(); + if (requestUrl.getPort() != -1) { + origin += ":" + requestUrl.getPort(); + } + + Map headers = new HashMap<>(); + headers.put("Origin", origin); + + logger.debug("Watching {}...", url); closeRequest(); // only one can be active at a time - run(request); + run(url, headers); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/BaseOperationRequestBuilder.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/BaseOperationRequestBuilder.java deleted file mode 100644 index e27f1ebd7af..00000000000 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/BaseOperationRequestBuilder.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright (C) 2015 Red Hat, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.fabric8.kubernetes.client.dsl.internal; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Map; -import java.util.Objects; - -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.fabric8.kubernetes.api.model.KubernetesResourceList; -import io.fabric8.kubernetes.api.model.ListOptions; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.dsl.base.BaseOperation; -import io.fabric8.kubernetes.client.utils.HttpClientUtils; -import okhttp3.HttpUrl; -import okhttp3.Request; - -class BaseOperationRequestBuilder> { - private final URL requestUrl; - private final BaseOperation baseOperation; - private final ListOptions listOptions; - - public BaseOperationRequestBuilder(BaseOperation baseOperation, ListOptions listOptions) throws MalformedURLException { - this.baseOperation = baseOperation; - this.requestUrl = baseOperation.getNamespacedUrl(); - this.listOptions = listOptions; - } - - public BaseOperation getBaseOperation() { - return baseOperation; - } - - public Request build(final String resourceVersion) { - HttpUrl.Builder httpUrlBuilder = HttpUrl.get(requestUrl).newBuilder(); - - listOptions.setResourceVersion(resourceVersion); - HttpClientUtils.appendListOptionParams(httpUrlBuilder, listOptions); - - String origin = requestUrl.getProtocol() + "://" + requestUrl.getHost(); - if (requestUrl.getPort() != -1) { - origin += ":" + requestUrl.getPort(); - } - - Request.Builder requestBuilder = new Request.Builder() - .get() - .url(httpUrlBuilder.build()) - .addHeader("Origin", origin); - - Config config = baseOperation.getConfig(); - if (Objects.nonNull(config)) { - Map customHeaders = config.getCustomHeaders(); - if (Objects.nonNull(customHeaders) && !customHeaders.isEmpty()) { - for (String key : customHeaders.keySet()) { - requestBuilder.addHeader(key, customHeaders.get(key)); - } - } - } - - return requestBuilder.build(); - } -} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/CreateOnlyResourceOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/CreateOnlyResourceOperationsImpl.java index 797cb3df981..48caccaa210 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/CreateOnlyResourceOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/CreateOnlyResourceOperationsImpl.java @@ -16,20 +16,19 @@ package io.fabric8.kubernetes.client.dsl.internal; import io.fabric8.kubernetes.api.model.KubernetesResource; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.NamespacedInOutCreateable; import io.fabric8.kubernetes.client.dsl.base.CreateOnlyResourceOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; import io.fabric8.kubernetes.client.dsl.base.ResourceDefinitionContext; -import okhttp3.OkHttpClient; public class CreateOnlyResourceOperationsImpl extends CreateOnlyResourceOperation implements NamespacedInOutCreateable { private final ResourceDefinitionContext rdc; private Class inputType; - public CreateOnlyResourceOperationsImpl(OkHttpClient client, Config config, ResourceDefinitionContext rdc, Class inputType, Class outputType) { - this(HasMetadataOperationsImpl.defaultContext(new OperationContext(), client, config), rdc, inputType, outputType); + public CreateOnlyResourceOperationsImpl(ClientContext clientContext, ResourceDefinitionContext rdc, Class inputType, Class outputType) { + this(HasMetadataOperationsImpl.defaultContext(clientContext), rdc, inputType, outputType); } public CreateOnlyResourceOperationsImpl(OperationContext context, ResourceDefinitionContext rdc, Class inputType, Class outputType) { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/ExecWebSocketListener.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/ExecWebSocketListener.java index 1d2918c4979..745d64f08af 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/ExecWebSocketListener.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/ExecWebSocketListener.java @@ -18,36 +18,34 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.kubernetes.api.model.Status; -import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.ExecListener; import io.fabric8.kubernetes.client.dsl.ExecWatch; +import io.fabric8.kubernetes.client.dsl.ExecListener.Response; import io.fabric8.kubernetes.client.dsl.base.OperationSupport; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.http.WebSocket; +import io.fabric8.kubernetes.client.http.WebSocketHandshakeException; import io.fabric8.kubernetes.client.utils.InputStreamPumper; -import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.Response; -import okhttp3.WebSocket; -import okhttp3.WebSocketListener; -import okio.ByteString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; +import java.nio.ByteBuffer; +import java.nio.channels.Channels; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; -import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static io.fabric8.kubernetes.client.utils.Utils.closeQuietly; /** - * A {@link WebSocketListener} for exec operations. + * A {@link WebSocket.Listener} for exec operations. * * This listener, is only responsible for the resources it creates. Externally passed resource, will not get closed, * by this listener. @@ -58,13 +56,30 @@ * Failures that propagate after a close() operation will not be propagated. * */ -public class ExecWebSocketListener extends WebSocketListener implements ExecWatch, AutoCloseable { +public class ExecWebSocketListener implements ExecWatch, AutoCloseable, WebSocket.Listener { + + private final class SimpleResponse implements Response { + private final HttpResponse response; + + private SimpleResponse(HttpResponse response) { + this.response = response; + } + + @Override + public int code() { + return response.code(); + } + + @Override + public String body() throws IOException { + return response.bodyString(); + } + } private static final Logger LOGGER = LoggerFactory.getLogger(ExecWebSocketListener.class); private static final String HEIGHT = "Height"; private static final String WIDTH = "Width"; - private final Config config; private final InputStream in; private final OutputStream out; private final OutputStream err; @@ -78,7 +93,6 @@ public class ExecWebSocketListener extends WebSocketListener implements ExecWatc private final AtomicReference webSocketRef = new AtomicReference<>(); private final ExecutorService executorService = Executors.newSingleThreadExecutor(); - private final CompletableFuture startedFuture = new CompletableFuture<>(); private final ExecListener listener; private final AtomicBoolean explicitlyClosed = new AtomicBoolean(false); @@ -91,8 +105,7 @@ public class ExecWebSocketListener extends WebSocketListener implements ExecWatc private ObjectMapper objectMapper; - public ExecWebSocketListener(Config config, InputStream in, OutputStream out, OutputStream err, OutputStream errChannel, PipedOutputStream inputPipe, PipedInputStream outputPipe, PipedInputStream errorPipe, PipedInputStream errorChannelPipe, ExecListener listener, Integer bufferSize) { - this.config = config; + public ExecWebSocketListener(InputStream in, OutputStream out, OutputStream err, OutputStream errChannel, PipedOutputStream inputPipe, PipedInputStream outputPipe, PipedInputStream errorPipe, PipedInputStream errorChannelPipe, ExecListener listener, Integer bufferSize) { this.listener = listener; this.in = inputStreamOrPipe(in, inputPipe, toClose, bufferSize); this.out = outputStreamOrPipe(out, outputPipe, toClose); @@ -113,15 +126,11 @@ public void close() { } public void close(int code, String reason) { - close(webSocketRef.get(), code, reason); + explicitlyClosed.set(true); + closeWebSocketOnce(code, reason); + onClosed(code, reason); } - private void close(WebSocket ws, int code, String reason) { - explicitlyClosed.set(true); - closeWebSocketOnce(code, reason); - onClosed(ws, code, reason); - } - /** * Performs the cleanup tasks: * 1. cancels the InputStream pumper @@ -147,19 +156,15 @@ private void closeWebSocketOnce(int code, String reason) { try { WebSocket ws = webSocketRef.get(); if (ws != null) { - ws.close(code, reason); + ws.sendClose(code, reason); } } catch (Throwable t) { LOGGER.debug("Error closing WebSocket.", t); } } - public void waitUntilReady() { - Utils.waitUntilReadyOrFail(startedFuture, config.getWebsocketTimeout(), TimeUnit.MILLISECONDS); - } - @Override - public void onOpen(WebSocket webSocket, Response response) { + public void onOpen(WebSocket webSocket) { try { if (in instanceof PipedInputStream && input != null) { input.connect((PipedInputStream) in); @@ -179,62 +184,69 @@ public void onOpen(WebSocket webSocket, Response response) { // the task will be cancelled via shutdownNow InputStreamPumper.pump(InputStreamPumper.asInterruptible(in), this::send, executorService); } - startedFuture.complete(null); } catch (IOException e) { - startedFuture.completeExceptionally(new KubernetesClientException(OperationSupport.createStatus(response))); + onError(webSocket, e); } finally { if (listener != null) { - listener.onOpen(response); + listener.onOpen(); } } } @Override - public void onFailure(WebSocket webSocket, Throwable t, Response response) { + public void onError(WebSocket webSocket, Throwable t) { //If we already called onClosed() or onFailed() before, we need to abort. if (explicitlyClosed.get() || closed.get() || !failed.compareAndSet(false, true) ) { //We are not going to notify the listener, sicne we've already called onClose(), so let's log a debug/warning. - if (LOGGER.isDebugEnabled()) { + if (LOGGER.isWarnEnabled()) { LOGGER.warn("Received [{}], with message:[{}] after ExecWebSocketListener is closed, Ignoring.",t.getClass().getCanonicalName(),t.getMessage()); } return; } + HttpResponse response = null; try { + if (t instanceof WebSocketHandshakeException) { + response = ((WebSocketHandshakeException)t).getResponse(); + } Status status = OperationSupport.createStatus(response); - LOGGER.error("Exec Failure: HTTP:" + status.getCode() + ". Message:" + status.getMessage(), t); - startedFuture.completeExceptionally(new KubernetesClientException(status)); - + status.setMessage(t.getMessage()); + LOGGER.error("Exec Failure", t); cleanUpOnce(); } finally { if (listener != null) { - listener.onFailure(t, response); + ExecListener.Response execResponse = null; + if (response != null) { + execResponse = new SimpleResponse(response); + } + listener.onFailure(t, execResponse); } } } - @Override - public void onMessage(WebSocket webSocket, ByteString bytes) { + @Override + public void onMessage(WebSocket webSocket, ByteBuffer bytes) { try { - byte streamID = bytes.getByte(0); - ByteString byteString = bytes.substring(1); - if (byteString.size() > 0) { + byte streamID = bytes.get(0); + bytes.position(1); + ByteBuffer byteString = bytes.slice(); + if (byteString.remaining() > 0) { switch (streamID) { case 1: if (out != null) { - out.write(byteString.toByteArray()); - out.flush(); + Channels.newChannel(out).write(byteString); + out.flush(); } break; case 2: if (err != null) { - err.write(byteString.toByteArray()); + Channels.newChannel(err).write(byteString); } break; case 3: if (errChannel != null) { - errChannel.write(byteString.toByteArray()); + Channels.newChannel(errChannel).write(byteString); } break; default: @@ -247,12 +259,11 @@ public void onMessage(WebSocket webSocket, ByteString bytes) { } @Override - public void onClosing(WebSocket webSocket, int code, String reason) { - ExecWebSocketListener.this.close(webSocket, code, reason); + public void onClose(WebSocket webSocket, int code, String reason) { + ExecWebSocketListener.this.close(code, reason); } - @Override - public void onClosed(WebSocket webSocket, int code, String reason) { + private void onClosed(int code, String reason) { //If we already called onClosed() or onFailed() before, we need to abort. if (!closed.compareAndSet(false, true) || failed.get()) { return; @@ -312,7 +323,7 @@ private void send(byte[] bytes, int offset, int length, byte flag) { byte[] toSend = new byte[length + 1]; toSend[0] = flag; System.arraycopy(bytes, offset, toSend, 1, length); - ws.send(ByteString.of(toSend)); + ws.send(ByteBuffer.wrap(toSend)); } } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/HasMetadataOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/HasMetadataOperationsImpl.java index e8c19b2442a..7db57dd9973 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/HasMetadataOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/HasMetadataOperationsImpl.java @@ -15,13 +15,11 @@ */ package io.fabric8.kubernetes.client.dsl.internal; -import static io.fabric8.kubernetes.client.utils.KubernetesResourceUtil.inferListType; - import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesResource; import io.fabric8.kubernetes.api.model.KubernetesResourceList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; @@ -29,20 +27,25 @@ import io.fabric8.kubernetes.client.dsl.base.ResourceDefinitionContext; import io.fabric8.kubernetes.client.utils.ApiVersionUtil; import io.fabric8.kubernetes.internal.KubernetesDeserializer; -import okhttp3.OkHttpClient; + +import static io.fabric8.kubernetes.client.utils.KubernetesResourceUtil.inferListType; public class HasMetadataOperationsImpl> extends HasMetadataOperation> implements MixedOperation> { private final ResourceDefinitionContext rdc; - public HasMetadataOperationsImpl(OkHttpClient client, Config config, ResourceDefinitionContext rdc, Class type, Class listType) { - this(defaultContext(new OperationContext(), client, config), rdc, type, listType); - } - - public static OperationContext defaultContext(OperationContext context, OkHttpClient client, Config config) { - return context.withOkhttpClient(client).withConfig(config).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY); + public HasMetadataOperationsImpl(ClientContext clientContext, ResourceDefinitionContext rdc, Class type, Class listType) { + this(defaultContext(clientContext), rdc, type, listType); } + public static OperationContext defaultContext(OperationContext context, ClientContext clientContext) { + return context.withHttpClient(clientContext.getHttpClient()).withConfig(clientContext.getConfiguration()).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY); + } + + public static OperationContext defaultContext(ClientContext clientContext) { + return defaultContext(new OperationContext(), clientContext); + } + public HasMetadataOperationsImpl(OperationContext context, ResourceDefinitionContext rdc, Class type, Class listType) { super(context.withApiGroupName(rdc.getGroup()) .withApiGroupVersion(rdc.getVersion()) diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/KubernetesListOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/KubernetesListOperationsImpl.java index 683d0f2d33e..47d603ca172 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/KubernetesListOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/KubernetesListOperationsImpl.java @@ -15,19 +15,19 @@ */ package io.fabric8.kubernetes.client.dsl.internal; -import io.fabric8.kubernetes.client.dsl.KubernetesListMixedOperation; -import io.fabric8.kubernetes.client.dsl.KubernetesListOperation; -import io.fabric8.kubernetes.client.dsl.Loadable; -import okhttp3.OkHttpClient; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesList; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.ResourceHandler; -import io.fabric8.kubernetes.client.dsl.KubernetesListNonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Createable; import io.fabric8.kubernetes.client.dsl.Gettable; +import io.fabric8.kubernetes.client.dsl.KubernetesListMixedOperation; +import io.fabric8.kubernetes.client.dsl.KubernetesListNonNamespaceOperation; +import io.fabric8.kubernetes.client.dsl.KubernetesListOperation; +import io.fabric8.kubernetes.client.dsl.Loadable; import io.fabric8.kubernetes.client.dsl.RecreateFromServerGettable; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; @@ -52,8 +52,8 @@ public class KubernetesListOperationsImpl private final boolean deletingExisting; private final OperationContext context; - public KubernetesListOperationsImpl(OkHttpClient client, Config config) { - this.context = HasMetadataOperationsImpl.defaultContext(new OperationContext(), client, config); + public KubernetesListOperationsImpl(ClientContext clientContext) { + this.context = HasMetadataOperationsImpl.defaultContext(clientContext); this.deletingExisting = false; } @@ -126,7 +126,7 @@ public KubernetesList get() { private Resource getResource(HasMetadata resource) { ResourceHandler handler = NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl.handlerOf(resource, context); - return handler.operation(context.getClient(), context.getConfig(), null).newInstance(context.withItem(resource)); + return handler.operation(this.context, null).newInstance(context.withItem(resource)); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/LogWatchCallback.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/LogWatchCallback.java index 1a4b40be486..e185cc935da 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/LogWatchCallback.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/LogWatchCallback.java @@ -18,11 +18,11 @@ import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.LogWatch; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; import io.fabric8.kubernetes.client.utils.InputStreamPumper; import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,6 +32,7 @@ import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; +import java.net.URL; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; @@ -39,10 +40,11 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BiConsumer; import static io.fabric8.kubernetes.client.utils.Utils.closeQuietly; -public class LogWatchCallback implements LogWatch, Callback, AutoCloseable { +public class LogWatchCallback implements LogWatch, AutoCloseable, BiConsumer, Throwable> { private static final Logger LOGGER = LoggerFactory.getLogger(LogWatchCallback.class); @@ -51,15 +53,9 @@ public class LogWatchCallback implements LogWatch, Callback, AutoCloseable { private final PipedInputStream output; private final Set toClose = new LinkedHashSet<>(); - private final CompletableFuture startedFuture = new CompletableFuture<>(); private final ExecutorService executorService = Executors.newSingleThreadExecutor(); private final AtomicBoolean closed = new AtomicBoolean(false); - @Deprecated - public LogWatchCallback(OutputStream out) { - this(new Config(), out); - } - public LogWatchCallback(Config config, OutputStream out) { this.config = config; if (out == null) { @@ -106,42 +102,54 @@ private void cleanUp() { closeQuietly(toClose); } - public void waitUntilReady() { - if (!Utils.waitUntilReady(startedFuture, config.getRequestTimeout(), TimeUnit.MILLISECONDS)) { - if (LOGGER.isDebugEnabled()) { + public LogWatchCallback callAndWait(HttpClient client, URL url) { + HttpRequest request = client.newHttpRequestBuilder().url(url).build(); + HttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build(); + CompletableFuture> future = clone.sendAsync(request, InputStream.class).whenComplete(this); + + if (!Utils.waitUntilReady(future, config.getRequestTimeout(), TimeUnit.MILLISECONDS)) { + if (LOGGER.isWarnEnabled()) { LOGGER.warn("Log watch request has not been opened within: {} millis.",config.getRequestTimeout()); } } + return this; } @Override public InputStream getOutput() { return output; } - + @Override - public void onFailure(Call call, IOException ioe) { + public void accept(HttpResponse t, Throwable u) { + if (u != null) { + onFailure(u); + } + if (t != null) { + onResponse(t); + } + } + + public void onFailure(Throwable u) { //If we have closed the watch ignore everything if (closed.get()) { return; } - LOGGER.error("Log Callback Failure.", ioe); + LOGGER.error("Log Callback Failure.", u); cleanUp(); - startedFuture.completeExceptionally(ioe); } - @Override - public void onResponse(Call call, final Response response) throws IOException { + public void onResponse(final HttpResponse response) { + InputStream body = response.body(); if (!executorService.isShutdown()) { // the task will be cancelled via shutdownNow - InputStreamPumper.pump(response.body().byteStream(), out::write, executorService).whenComplete((o, t) -> { + InputStreamPumper.pump(body, out::write, executorService).whenComplete((o, t) -> { cleanUp(); - response.close(); + Utils.closeQuietly(body); }); - startedFuture.complete(null); } else { - response.close(); + Utils.closeQuietly(body); } } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/MetricOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/MetricOperationsImpl.java index f0db5db952a..f338d53959c 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/MetricOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/MetricOperationsImpl.java @@ -15,19 +15,16 @@ */ package io.fabric8.kubernetes.client.dsl.internal; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.Nameable; -import io.fabric8.kubernetes.client.dsl.base.OperationContext; import io.fabric8.kubernetes.client.dsl.base.OperationSupport; import io.fabric8.kubernetes.client.utils.URLUtils; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.utils.URLUtils.URLBuilder; import java.io.IOException; import java.util.HashMap; import java.util.Map; -import java.util.concurrent.ExecutionException; public class MetricOperationsImpl extends OperationSupport implements Nameable> { public static final String METRIC_ENDPOINT_URL = "apis/metrics.k8s.io/v1beta1/"; @@ -38,8 +35,8 @@ public class MetricOperationsImpl extends OperationSupport implements Name private final String configuredName; private final Map configuredLabels; - public MetricOperationsImpl(OkHttpClient client, Config config, String configuredName, String configuredNamespace, String plural, Map configuredLabels, Class apiTypeClass, Class apiTypeListClass) { - super(new OperationContext().withOkhttpClient(client).withConfig(config)); + public MetricOperationsImpl(ClientContext client, String configuredName, String configuredNamespace, String plural, Map configuredLabels, Class apiTypeClass, Class apiTypeListClass) { + super(HasMetadataOperationsImpl.defaultContext(client)); this.plural = plural; this.apiTypeClass = apiTypeClass; this.apiTypeListClass = apiTypeListClass; @@ -50,7 +47,7 @@ public MetricOperationsImpl(OkHttpClient client, Config config, String configure @Override public MetricOperationsImpl withName(String name) { - return new MetricOperationsImpl<>(client, config, name, configuredNamespace, plural, configuredLabels, apiTypeClass, apiTypeListClass); + return new MetricOperationsImpl<>(context, name, configuredNamespace, plural, configuredLabels, apiTypeClass, apiTypeListClass); } /** @@ -60,7 +57,7 @@ public MetricOperationsImpl withName(String name) { * @return {@link MetricOperationsImpl} with which you can call metrics() for getting filtered Metrics */ public MetricOperationsImpl withLabels(Map labels) { - return new MetricOperationsImpl<>(client, config, name, configuredNamespace, plural, labels, apiTypeClass, apiTypeListClass); + return new MetricOperationsImpl<>(context, name, configuredNamespace, plural, labels, apiTypeClass, apiTypeListClass); } /** @@ -71,7 +68,7 @@ public MetricOperationsImpl withLabels(Map labels) { public L metrics() { try { return handleMetric(getMetricEndpointUrl(), apiTypeListClass); - } catch (IOException | ExecutionException exception) { + } catch (IOException exception) { throw KubernetesClientException.launderThrowable(exception); } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); @@ -87,7 +84,7 @@ public L metrics() { public T metric() { try { return handleMetric(getMetricEndpointUrl(), apiTypeClass); - } catch (IOException | ExecutionException exception) { + } catch (IOException exception) { throw KubernetesClientException.launderThrowable(exception); } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); @@ -128,7 +125,7 @@ private String getMetricEndpointUrl() { } private String getUrlWithLabels(String baseUrl, Map labels) { - HttpUrl.Builder httpUrlBuilder = HttpUrl.get(baseUrl).newBuilder(); + URLBuilder httpUrlBuilder = new URLBuilder(baseUrl); StringBuilder sb = new StringBuilder(); for(Map.Entry entry : labels.entrySet()) { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl.java index bd68d4dea9f..a50d9f03b51 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl.java @@ -15,27 +15,15 @@ */ package io.fabric8.kubernetes.client.dsl.internal; -import io.fabric8.kubernetes.api.model.DeletionPropagation; -import io.fabric8.kubernetes.api.model.ListOptions; -import io.fabric8.kubernetes.client.dsl.VisitFromServerWritable; -import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; -import okhttp3.OkHttpClient; - -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.function.UnaryOperator; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; - import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.builder.VisitableBuilder; import io.fabric8.kubernetes.api.builder.Visitor; +import io.fabric8.kubernetes.api.model.DeletionPropagation; import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.ListOptions; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.ResourceHandler; @@ -49,10 +37,20 @@ import io.fabric8.kubernetes.client.dsl.Readiable; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.VisitFromServerGetWatchDeleteRecreateWaitApplicable; +import io.fabric8.kubernetes.client.dsl.VisitFromServerWritable; import io.fabric8.kubernetes.client.dsl.Waitable; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; import io.fabric8.kubernetes.client.internal.readiness.Readiness; +import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; import static io.fabric8.kubernetes.client.utils.DeleteAndCreateHelper.deleteAndCreateItem; @@ -89,8 +87,8 @@ public NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl(Operatio this.namespaceVisitOperationContext = namespaceVisitOperationContext; } - public NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl(OkHttpClient httpClient, Config configuration, HasMetadata item) { - this(HasMetadataOperationsImpl.defaultContext(new OperationContext(), httpClient, configuration).withItem(item), new NamespaceVisitOperationContext()); + public NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl(ClientContext clientContext, HasMetadata item) { + this(HasMetadataOperationsImpl.defaultContext(clientContext).withItem(item), new NamespaceVisitOperationContext()); handlerOf(item, this.context); // validate the handler } @@ -186,7 +184,7 @@ public Watch watch(ListOptions options, Watcher watcher) { Resource getResource() { HasMetadata meta = (HasMetadata) context.getItem(); ResourceHandler handler = handlerOf(meta, context); - HasMetadataOperation> operation = handler.operation(context.getClient(), context.getConfig(), null); + HasMetadataOperation> operation = handler.operation(context, null); return operation.newInstance(context).inNamespace(KubernetesResourceUtil.getNamespace(meta)).withName(KubernetesResourceUtil.getName(meta)); } @@ -257,7 +255,7 @@ static HasMetadata acceptVisitors(HasMetadata item, List visitors, Stri } static > ResourceHandler handlerOf(T item, OperationContext context) { - ResourceHandler result = Handlers.get(item, new BaseClient(context.getClient(), context.getConfig())); + ResourceHandler result = Handlers.get(item, new BaseClient(context)); if (result == null) { throw new KubernetesClientException("Could not find a registered handler for item: [" + item + "]."); } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java index 97e3d4ae55d..e2553d0f1dc 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java @@ -22,16 +22,17 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesList; import io.fabric8.kubernetes.api.model.KubernetesResourceList; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.KubernetesClientTimeoutException; import io.fabric8.kubernetes.client.dsl.*; +import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.kubernetes.client.internal.readiness.Readiness; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.kubernetes.client.utils.Utils; - -import okhttp3.OkHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -65,8 +66,8 @@ public NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(Oper this.context = context; } - public NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(OkHttpClient client, Config config, Object item) { - this(HasMetadataOperationsImpl.defaultContext(new OperationContext(), client, config).withItem(item), new NamespaceVisitOperationContext()); + public NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(ClientContext clientContext, Object item) { + this(HasMetadataOperationsImpl.defaultContext(clientContext).withItem(item), new NamespaceVisitOperationContext()); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NodeMetricOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NodeMetricOperationsImpl.java index c52bf9b4f70..5c8f7739b6e 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NodeMetricOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NodeMetricOperationsImpl.java @@ -17,12 +17,11 @@ import io.fabric8.kubernetes.api.model.metrics.v1beta1.NodeMetrics; import io.fabric8.kubernetes.api.model.metrics.v1beta1.NodeMetricsList; -import io.fabric8.kubernetes.client.Config; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.ClientContext; public class NodeMetricOperationsImpl extends MetricOperationsImpl { - public NodeMetricOperationsImpl(OkHttpClient client, Config config) { - super(client, config, null, null, "nodes", null, NodeMetrics.class, NodeMetricsList.class); + public NodeMetricOperationsImpl(ClientContext clientContext) { + super(clientContext, null, null, "nodes", null, NodeMetrics.class, NodeMetricsList.class); } /** diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PodMetricOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PodMetricOperationsImpl.java index 8b591af45bb..00397e0a13c 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PodMetricOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PodMetricOperationsImpl.java @@ -17,17 +17,16 @@ import io.fabric8.kubernetes.api.model.metrics.v1beta1.PodMetrics; import io.fabric8.kubernetes.api.model.metrics.v1beta1.PodMetricsList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.Namespaceable; -import okhttp3.OkHttpClient; public class PodMetricOperationsImpl extends MetricOperationsImpl implements Namespaceable { - public PodMetricOperationsImpl(OkHttpClient client, Config config) { - super(client, config, null, null, "pods", null, PodMetrics.class, PodMetricsList.class); + public PodMetricOperationsImpl(ClientContext clientContext) { + super(clientContext, null, null, "pods", null, PodMetrics.class, PodMetricsList.class); } - private PodMetricOperationsImpl(OkHttpClient client, Config config, String name, String namespace) { - super(client, config, name, namespace, "pods", null, PodMetrics.class, PodMetricsList.class); + private PodMetricOperationsImpl(ClientContext clientContext, String name, String namespace) { + super(clientContext, name, namespace, "pods", null, PodMetrics.class, PodMetricsList.class); } /** @@ -53,6 +52,6 @@ public PodMetricsList metrics(String namespace) { @Override public PodMetricOperationsImpl inNamespace(String namespace) { - return new PodMetricOperationsImpl(client, config, null, namespace); + return new PodMetricOperationsImpl(context, null, namespace); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PortForwarderWebsocket.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PortForwarderWebsocket.java index 498206487a7..d0bd458794f 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PortForwarderWebsocket.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/PortForwarderWebsocket.java @@ -19,6 +19,7 @@ import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.URI; import java.net.URL; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; @@ -29,6 +30,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -37,18 +39,13 @@ import io.fabric8.kubernetes.client.LocalPortForward; import io.fabric8.kubernetes.client.PortForward; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.WebSocket; import io.fabric8.kubernetes.client.utils.URLUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.WebSocket; -import okhttp3.WebSocketListener; -import okio.ByteString; - /** * A port-forwarder using the websocket protocol. * It requires Kubernetes 1.6+ (previous versions support the SPDY protocol only). @@ -57,9 +54,9 @@ public class PortForwarderWebsocket implements PortForwarder { private static final Logger LOG = LoggerFactory.getLogger(PortForwarderWebsocket.class); - private final OkHttpClient client; + private final HttpClient client; - public PortForwarderWebsocket(OkHttpClient client) { + public PortForwarderWebsocket(HttpClient client) { this.client = client; } @@ -184,19 +181,13 @@ public PortForward forward(URL resourceBaseUrl, int port, final ReadableByteChan final Collection serverThrowables = Collections.synchronizedCollection(new ArrayList<>()); final String logPrefix = "FWD"; - Request request = new Request.Builder() - .get() - .url(URLUtils.join(resourceBaseUrl.toString(), "portforward?ports=" + port)) - .build(); - - final WebSocket socket = client.newWebSocket(request, new WebSocketListener() { - + WebSocket.Listener listener = new WebSocket.Listener() { private int messagesRead = 0; private final ExecutorService pumperService = Executors.newSingleThreadExecutor(); @Override - public void onOpen(final WebSocket webSocket, Response response) { + public void onOpen(final WebSocket webSocket) { LOG.debug("{}: onOpen", logPrefix); if (in != null) { @@ -210,8 +201,7 @@ public void onOpen(final WebSocket webSocket, Response response) { read = in.read(buffer); if (read > 0) { buffer.flip(); - ByteString data = ByteString.of(buffer); - webSocket.send(data); + webSocket.send(buffer); } } while (alive.get() && read >= 0); @@ -230,15 +220,10 @@ public void onOpen(final WebSocket webSocket, Response response) { public void onMessage(WebSocket webSocket, String text) { LOG.debug("{}: onMessage(String)", logPrefix); onMessage(webSocket, ByteBuffer.wrap(text.getBytes(StandardCharsets.UTF_8))); - } - - @Override - public void onMessage(WebSocket webSocket, ByteString bytes) { - LOG.debug("{}: onMessage(ByteString)", logPrefix); - onMessage(webSocket, bytes.asByteBuffer()); } - private void onMessage(WebSocket webSocket, ByteBuffer buffer) { + @Override + public void onMessage(WebSocket webSocket, ByteBuffer buffer) { messagesRead++; if (messagesRead <= 2) { // skip the first two messages, containing the ports used internally @@ -278,23 +263,15 @@ private void onMessage(WebSocket webSocket, ByteBuffer buffer) { } @Override - public void onClosing(WebSocket webSocket, int code, String reason) { - LOG.debug("{}: onClosing. Code={}, Reason={}", logPrefix, code, reason); - if (alive.get()) { - closeForwarder(); - } - } - - @Override - public void onClosed(WebSocket webSocket, int code, String reason) { - LOG.debug("{}: onClosed. Code={}, Reason={}", logPrefix, code, reason); + public void onClose(WebSocket webSocket, int code, String reason) { + LOG.debug("{}: onClose. Code={}, Reason={}", logPrefix, code, reason); if (alive.get()) { closeForwarder(); } } @Override - public void onFailure(WebSocket webSocket, Throwable t, Response response) { + public void onError(WebSocket webSocket, Throwable t) { LOG.debug("{}: onFailure", logPrefix); if (alive.get()) { serverThrowables.add(t); @@ -307,7 +284,7 @@ private void closeBothWays(WebSocket webSocket, int code, String message) { LOG.debug("{}: Closing with code {} and reason: {}", logPrefix, code, message); alive.set(false); try { - webSocket.close(code, message); + webSocket.sendClose(code, message); } catch (Exception e) { serverThrowables.add(e); LOG.error("Error while closing the websocket", e); @@ -333,13 +310,25 @@ private void closeForwarder() { } closeExecutor(pumperService); } - + }; + CompletableFuture socket = client + .newWebSocketBuilder() + .uri(URI.create(URLUtils.join(resourceBaseUrl.toString(), "portforward?ports=" + port))) + .buildAsync(listener); + + socket.whenComplete((w, t) -> { + if (t != null) { + listener.onError(w, t); + } }); - + return new PortForward() { @Override public void close() throws IOException { - socket.close(1001, "User closing"); + socket.cancel(true); + socket.whenComplete((w, t) -> { if (w != null) { + w.sendClose(1001, "User closing"); + }}); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/RawCustomResourceOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/RawCustomResourceOperationsImpl.java index 00008abcb6b..162812ebb2e 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/RawCustomResourceOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/RawCustomResourceOperationsImpl.java @@ -23,6 +23,7 @@ import io.fabric8.kubernetes.api.model.GenericKubernetesResourceList; import io.fabric8.kubernetes.api.model.ListOptions; import io.fabric8.kubernetes.api.model.ListOptionsBuilder; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.GracePeriodConfigurable; import io.fabric8.kubernetes.client.PropagationPolicyConfigurable; @@ -38,11 +39,9 @@ import io.fabric8.kubernetes.client.dsl.Namespaceable; import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext; import io.fabric8.kubernetes.client.dsl.base.OperationContext; -import io.fabric8.kubernetes.client.dsl.base.OperationSupport; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.kubernetes.client.utils.Utils; import io.fabric8.kubernetes.model.Scope; -import okhttp3.OkHttpClient; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -62,7 +61,7 @@ * Right now it supports basic operations like GET, POST, PUT, DELETE. * */ -public class RawCustomResourceOperationsImpl extends OperationSupport implements Nameable, +public class RawCustomResourceOperationsImpl implements Nameable, Namespaceable, AnyNamespaceable, Listable>, @@ -75,19 +74,17 @@ public class RawCustomResourceOperationsImpl extends OperationSupport implements private final GenericKubernetesResourceOperationsImpl delegate; private final CustomResourceDefinitionContext customResourceDefinition; - private RawCustomResourceOperationsImpl(OkHttpClient client, GenericKubernetesResourceOperationsImpl delegate, CustomResourceDefinitionContext crdContext) { - super(client, delegate.getConfig()); + private RawCustomResourceOperationsImpl(GenericKubernetesResourceOperationsImpl delegate, CustomResourceDefinitionContext crdContext) { this.delegate = delegate; this.customResourceDefinition = crdContext; } - public RawCustomResourceOperationsImpl(OkHttpClient client, Config config, CustomResourceDefinitionContext customResourceDefinition) { + public RawCustomResourceOperationsImpl(ClientContext clientContext, CustomResourceDefinitionContext customResourceDefinition) { this( - client, new GenericKubernetesResourceOperationsImpl( new OperationContext() - .withOkhttpClient(client) - .withConfig(config) + .withHttpClient(clientContext.getHttpClient()) + .withConfig(clientContext.getConfiguration()) .withNamespace(null) .withName(null) .withGracePeriodSeconds(-1L) @@ -105,41 +102,40 @@ public RawCustomResourceOperationsImpl(OkHttpClient client, Config config, Custo @Override public RawCustomResourceOperationsImpl withName(String name) { - return new RawCustomResourceOperationsImpl(client, (GenericKubernetesResourceOperationsImpl) delegate.withName(name), customResourceDefinition); + return new RawCustomResourceOperationsImpl((GenericKubernetesResourceOperationsImpl) delegate.withName(name), customResourceDefinition); } @Override public RawCustomResourceOperationsImpl inNamespace(String namespace) { - return new RawCustomResourceOperationsImpl(client, (GenericKubernetesResourceOperationsImpl) delegate.inNamespace(namespace), customResourceDefinition); + return new RawCustomResourceOperationsImpl((GenericKubernetesResourceOperationsImpl) delegate.inNamespace(namespace), customResourceDefinition); } @Override public RawCustomResourceOperationsImpl inAnyNamespace() { - return new RawCustomResourceOperationsImpl(client, (GenericKubernetesResourceOperationsImpl) delegate.inAnyNamespace(), customResourceDefinition); + return new RawCustomResourceOperationsImpl((GenericKubernetesResourceOperationsImpl) delegate.inAnyNamespace(), customResourceDefinition); } @Override public RawCustomResourceOperationsImpl withGracePeriod(long gracePeriodSeconds) { - return new RawCustomResourceOperationsImpl(client, (GenericKubernetesResourceOperationsImpl) delegate.withGracePeriod(gracePeriodSeconds), customResourceDefinition); + return new RawCustomResourceOperationsImpl((GenericKubernetesResourceOperationsImpl) delegate.withGracePeriod(gracePeriodSeconds), customResourceDefinition); } @Override public RawCustomResourceOperationsImpl withPropagationPolicy(DeletionPropagation propagationPolicy) { - return new RawCustomResourceOperationsImpl(client, (GenericKubernetesResourceOperationsImpl) delegate.withPropagationPolicy(propagationPolicy), customResourceDefinition); + return new RawCustomResourceOperationsImpl((GenericKubernetesResourceOperationsImpl) delegate.withPropagationPolicy(propagationPolicy), customResourceDefinition); } @Override public RawCustomResourceOperationsImpl dryRun(boolean isDryRun) { - return new RawCustomResourceOperationsImpl(client, (GenericKubernetesResourceOperationsImpl) delegate.dryRun(isDryRun), customResourceDefinition); + return new RawCustomResourceOperationsImpl((GenericKubernetesResourceOperationsImpl) delegate.dryRun(isDryRun), customResourceDefinition); } - @Override public Config getConfig() { return delegate.getConfig(); } private RawCustomResourceOperationsImpl withDeleteOptions(DeleteOptions deleteOptions) { - return new RawCustomResourceOperationsImpl(client, (GenericKubernetesResourceOperationsImpl) delegate.withGracePeriod(resolveGracePeriod(deleteOptions.getGracePeriodSeconds())).withPropagationPolicy(resolvePropagationPolicy(deleteOptions.getPropagationPolicy())), customResourceDefinition); + return new RawCustomResourceOperationsImpl((GenericKubernetesResourceOperationsImpl) delegate.withGracePeriod(resolveGracePeriod(deleteOptions.getGracePeriodSeconds())).withPropagationPolicy(resolvePropagationPolicy(deleteOptions.getPropagationPolicy())), customResourceDefinition); } /** diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchConnectionManager.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchConnectionManager.java index b4c62f6d929..9307c17d471 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchConnectionManager.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchConnectionManager.java @@ -18,18 +18,30 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.api.model.ListOptions; +import io.fabric8.kubernetes.api.model.Status; +import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.Watcher; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.WebSocket; +import io.fabric8.kubernetes.client.dsl.base.OperationSupport; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.http.WebSocket; +import io.fabric8.kubernetes.client.http.WebSocket.Builder; +import io.fabric8.kubernetes.client.http.WebSocketHandshakeException; +import io.fabric8.kubernetes.client.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.util.Map; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; +import static java.net.HttpURLConnection.HTTP_OK; +import static java.net.HttpURLConnection.HTTP_UNAVAILABLE; + /** * Manages a WebSocket and listener per request */ @@ -38,13 +50,14 @@ public class WatchConnectionManager listener; + private CompletableFuture websocketFuture; private WebSocket websocket; static void closeWebSocket(WebSocket webSocket) { if (webSocket != null) { logger.debug("Closing websocket {}", webSocket); try { - if (!webSocket.close(1000, null)) { + if (!webSocket.sendClose(1000, null)) { logger.debug("Websocket already closed {}", webSocket); } } catch (IllegalStateException e) { @@ -53,19 +66,13 @@ static void closeWebSocket(WebSocket webSocket) { } } - static void closeBody(Response response) { - if (response != null && response.body() != null) { - response.body().close(); - } - } - - public WatchConnectionManager(final OkHttpClient client, final BaseOperation baseOperation, final ListOptions listOptions, final Watcher watcher, final int reconnectInterval, final int reconnectLimit, long websocketTimeout, int maxIntervalExponent) throws MalformedURLException { + public WatchConnectionManager(final HttpClient client, final BaseOperation baseOperation, final ListOptions listOptions, final Watcher watcher, final int reconnectInterval, final int reconnectLimit, long websocketTimeout, int maxIntervalExponent) throws MalformedURLException { super(watcher, baseOperation, listOptions, reconnectLimit, reconnectInterval, maxIntervalExponent, () -> client.newBuilder() .readTimeout(websocketTimeout, TimeUnit.MILLISECONDS) .build()); } - public WatchConnectionManager(final OkHttpClient client, final BaseOperation baseOperation, final ListOptions listOptions, final Watcher watcher, final int reconnectInterval, final int reconnectLimit, long websocketTimeout) throws MalformedURLException { + public WatchConnectionManager(final HttpClient client, final BaseOperation baseOperation, final ListOptions listOptions, final Watcher watcher, final int reconnectInterval, final int reconnectLimit, long websocketTimeout) throws MalformedURLException { // Default max 32x slowdown from base interval this(client, baseOperation, listOptions, watcher, reconnectInterval, reconnectLimit, websocketTimeout, 5); } @@ -73,21 +80,53 @@ public WatchConnectionManager(final OkHttpClient client, final BaseOperation { + if (w != null) { + closeWebSocket(w); + } + }); + websocketFuture = null; + } } public void waitUntilReady() { - getListener().waitUntilReady(); + Utils.waitUntilReadyOrFail(websocketFuture, 10, TimeUnit.SECONDS); + this.websocket = websocketFuture.getNow(null); } synchronized WatcherWebSocketListener getListener() { return listener; } - + @Override - protected synchronized void run(Request request) { + protected void run(URL url, Map headers) { this.listener = new WatcherWebSocketListener<>(this); - this.websocket = client.newWebSocket(request, this.listener); + Builder builder = client.newWebSocketBuilder(); + headers.forEach(builder::header); + builder.uri(URI.create(url.toString())); + + this.websocketFuture = builder.buildAsync(this.listener).handle((w, t) -> { + if (t != null) { + if (t instanceof WebSocketHandshakeException) { + WebSocketHandshakeException wshe = (WebSocketHandshakeException)t; + HttpResponse response = wshe.getResponse(); + final int code = response.code(); + // We do not expect a 200 in response to the websocket connection. If it occurs, we throw + // an exception and try the watch via a persistent HTTP Get. + // Newer Kubernetes might also return 503 Service Unavailable in case WebSockets are not supported + if (HTTP_OK == code || HTTP_UNAVAILABLE == code) { + throw OperationSupport.requestFailure(client.newHttpRequestBuilder().url(url).build(), null, "Received " + code + " on websocket"); + } + Status status = OperationSupport.createStatus(response); + logger.warn("Exec Failure: HTTP {}, Status: {} - {}", code, status.getCode(), status.getMessage()); + t = OperationSupport.requestFailure(client.newHttpRequestBuilder().url(url).build(), status); + } + listener.onError(w, t); + throw KubernetesClientException.launderThrowable(t); + } + return w; + }); } - + } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java index 87ccc2e8577..1a48ba74261 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java @@ -15,8 +15,14 @@ */ package io.fabric8.kubernetes.client.dsl.internal; -import java.io.IOException; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; import java.net.MalformedURLException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import io.fabric8.kubernetes.api.model.HasMetadata; @@ -25,22 +31,17 @@ import io.fabric8.kubernetes.client.Watcher; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; import io.fabric8.kubernetes.client.dsl.base.OperationSupport; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.logging.HttpLoggingInterceptor; -import okio.BufferedSource; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WatchHTTPManager> extends AbstractWatchManager { private static final Logger logger = LoggerFactory.getLogger(WatchHTTPManager.class); - private Call call; + private CompletableFuture> call; - public WatchHTTPManager(final OkHttpClient client, + public WatchHTTPManager(final HttpClient client, final BaseOperation baseOperation, final ListOptions listOptions, final Watcher watcher, final int reconnectInterval, final int reconnectLimit, long connectTimeout) @@ -49,63 +50,49 @@ public WatchHTTPManager(final OkHttpClient client, this(client, baseOperation, listOptions, watcher, reconnectInterval, reconnectLimit, connectTimeout, 5); } - public WatchHTTPManager(final OkHttpClient client, + public WatchHTTPManager(final HttpClient client, final BaseOperation baseOperation, final ListOptions listOptions, final Watcher watcher, final int reconnectInterval, final int reconnectLimit, long connectTimeout, int maxIntervalExponent) throws MalformedURLException { super( - watcher, baseOperation, listOptions, reconnectLimit, reconnectInterval, maxIntervalExponent, () -> { - final OkHttpClient clonedClient = client.newBuilder() - .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS) - .readTimeout(0, TimeUnit.MILLISECONDS) - .cache(null) - .build(); - // If we set the HttpLoggingInterceptor's logging level to Body (as it is by default), it does - // not let us stream responses from the server. - for (Interceptor i : clonedClient.networkInterceptors()) { - if (i instanceof HttpLoggingInterceptor) { - HttpLoggingInterceptor interceptor = (HttpLoggingInterceptor) i; - interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); - } - } - return clonedClient; - }); + watcher, baseOperation, listOptions, reconnectLimit, reconnectInterval, maxIntervalExponent, + () -> client.newBuilder() + .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS) + .readTimeout(0, TimeUnit.MILLISECONDS) + .forStreaming() + .build()); } @Override - protected synchronized void run(Request request) { - call = client.newCall(request); - call.enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - logger.info("Watch connection failed. reason: {}", e.getMessage()); - scheduleReconnect(); + protected synchronized void run(URL url, Map headers) { + HttpRequest.Builder builder = client.newHttpRequestBuilder().url(url); + headers.forEach(builder::header); + call = client.sendAsync(builder.build(), InputStream.class); + call.whenComplete((response, t) -> { + if (!call.isCancelled() && t != null) { + logger.info("Watch connection failed. reason: {}", t.getMessage()); } - - @Override - public void onResponse(Call call, Response response) throws IOException { - try { + if (response != null) { + try (InputStream body = response.body()){ resetReconnectAttempts(); if (!response.isSuccessful() && onStatus(OperationSupport.createStatus(response.code(), response.message()))) { return; } - BufferedSource source = response.body().source(); - while (!source.exhausted()) { - String message = source.readUtf8LineStrict(); + BufferedReader source = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); + String message = null; + while ((message = source.readLine()) != null) { onMessage(message); } } catch (Exception e) { logger.info("Watch terminated unexpectedly. reason: {}", e.getMessage()); - } finally { - WatchConnectionManager.closeBody(response); } - - // if we get here, the source is exhausted, so, we have lost our "watch". - // we must reconnect. + } + + if (!call.isCancelled()) { scheduleReconnect(); } }); @@ -114,8 +101,9 @@ && onStatus(OperationSupport.createStatus(response.code(), response.message()))) @Override protected synchronized void closeRequest() { if (call != null) { - call.cancel(); + call.cancel(true); call = null; } } + } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatcherWebSocketListener.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatcherWebSocketListener.java index 4c4897f4f98..e9ec99fd07a 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatcherWebSocketListener.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatcherWebSocketListener.java @@ -16,25 +16,15 @@ package io.fabric8.kubernetes.client.dsl.internal; import io.fabric8.kubernetes.api.model.HasMetadata; -import io.fabric8.kubernetes.api.model.Status; -import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.WatcherException; -import io.fabric8.kubernetes.client.dsl.base.OperationSupport; -import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.Response; -import okhttp3.WebSocket; -import okhttp3.WebSocketListener; -import okio.ByteString; +import io.fabric8.kubernetes.client.http.WebSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; -import static java.net.HttpURLConnection.HTTP_OK; -import static java.net.HttpURLConnection.HTTP_UNAVAILABLE; - -class WatcherWebSocketListener extends WebSocketListener { +class WatcherWebSocketListener implements WebSocket.Listener { protected static final Logger logger = LoggerFactory.getLogger(WatcherWebSocketListener.class); // don't allow for concurrent failure and message processing @@ -42,7 +32,6 @@ class WatcherWebSocketListener extends WebSocketListener // or worse additional reconnection attempts while the previous threads are still held private final Object reconnectLock = new Object(); - private final CompletableFuture startedFuture = new CompletableFuture<>(); protected final AbstractWatchManager manager; protected WatcherWebSocketListener(AbstractWatchManager manager) { @@ -50,39 +39,17 @@ protected WatcherWebSocketListener(AbstractWatchManager manager) { } @Override - public void onOpen(final WebSocket webSocket, Response response) { - WatchConnectionManager.closeBody(response); + public void onOpen(final WebSocket webSocket) { logger.debug("WebSocket successfully opened"); manager.resetReconnectAttempts(); - startedFuture.complete(null); } + @Override - public void onFailure(WebSocket webSocket, Throwable t, Response response) { - try { - if (manager.isForceClosed()) { - logger.debug("Ignoring onFailure for already closed/closing websocket", t); - return; - } - - if (response != null) { - final int code = response.code(); - // We do not expect a 200 in response to the websocket connection. If it occurs, we throw - // an exception and try the watch via a persistent HTTP Get. - // Newer Kubernetes might also return 503 Service Unavailable in case WebSockets are not supported - if (HTTP_OK == code || HTTP_UNAVAILABLE == code) { - pushException(OperationSupport.requestFailure(response.request(), null, "Received " + code + " on websocket")); - return; - } - Status status = OperationSupport.createStatus(response); - logger.warn("Exec Failure: HTTP {}, Status: {} - {}", code, status.getCode(), status.getMessage()); - pushException(OperationSupport.requestFailure(response.request(), status)); - } else { - logger.warn("Exec Failure {} {}", t.getClass().getName(), t.getMessage()); - pushException(new KubernetesClientException("Failed to start websocket", t)); - } - } finally { - WatchConnectionManager.closeBody(response); + public void onError(WebSocket webSocket, Throwable t) { + if (manager.isForceClosed()) { + logger.debug("Ignoring onFailure for already closed/closing websocket", t); + return; } if (manager.cannotReconnect()) { @@ -102,30 +69,16 @@ public void onMessage(WebSocket webSocket, String text) { } } - private void pushException(KubernetesClientException exception) { - if (!startedFuture.completeExceptionally(exception)) { - logger.debug("Couldn't report exception", exception); - } - } - @Override - public void onMessage(WebSocket webSocket, ByteString bytes) { - onMessage(webSocket, bytes.utf8()); + public void onMessage(WebSocket webSocket, ByteBuffer bytes) { + onMessage(webSocket, StandardCharsets.UTF_8.decode(bytes).toString()); } @Override - public void onClosing(WebSocket webSocket, int code, String reason) { - logger.debug("Socket closing: {}", reason); - webSocket.close(code, reason); - } - - @Override - public void onClosed(WebSocket webSocket, int code, String reason) { + public void onClose(WebSocket webSocket, int code, String reason) { logger.debug("WebSocket close received. code: {}, reason: {}", code, reason); + webSocket.sendClose(code, reason); manager.scheduleReconnect(); } - protected void waitUntilReady() { - Utils.waitUntilReadyOrFail(startedFuture, 10, TimeUnit.SECONDS); - } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/DeploymentOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/DeploymentOperationsImpl.java index 391045ab65c..6c7930f7c60 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/DeploymentOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/DeploymentOperationsImpl.java @@ -18,20 +18,22 @@ import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.OwnerReference; import io.fabric8.kubernetes.api.model.Status; +import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.fabric8.kubernetes.api.model.apps.DeploymentList; import io.fabric8.kubernetes.api.model.apps.ReplicaSet; import io.fabric8.kubernetes.api.model.apps.ReplicaSetList; import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback; -import io.fabric8.kubernetes.client.dsl.*; +import io.fabric8.kubernetes.client.ClientContext; +import io.fabric8.kubernetes.client.KubernetesClientException; +import io.fabric8.kubernetes.client.KubernetesClientTimeoutException; +import io.fabric8.kubernetes.client.dsl.LogWatch; +import io.fabric8.kubernetes.client.dsl.RollableScalableResource; +import io.fabric8.kubernetes.client.dsl.TimeoutImageEditReplacePatchable; import io.fabric8.kubernetes.client.dsl.base.OperationContext; import io.fabric8.kubernetes.client.dsl.base.PatchContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.RollingOperationContext; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; -import okhttp3.OkHttpClient; -import io.fabric8.kubernetes.api.model.apps.Deployment; -import io.fabric8.kubernetes.api.model.apps.DeploymentList; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.KubernetesClientException; -import io.fabric8.kubernetes.client.KubernetesClientTimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,10 +46,9 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.function.Consumer; -import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; import java.util.function.UnaryOperator; public class DeploymentOperationsImpl extends RollableScalableResourceOperation> @@ -56,8 +57,8 @@ public class DeploymentOperationsImpl extends RollableScalableResourceOperation< static final transient Logger LOG = LoggerFactory.getLogger(DeploymentOperationsImpl.class); public static final String DEPLOYMENT_KUBERNETES_IO_REVISION = "deployment.kubernetes.io/revision"; - public DeploymentOperationsImpl(OkHttpClient client, Config config) { - this(new RollingOperationContext(), new OperationContext().withOkhttpClient(client).withConfig(config).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public DeploymentOperationsImpl(ClientContext clientContext) { + this(new RollingOperationContext(), HasMetadataOperationsImpl.defaultContext(clientContext)); } public DeploymentOperationsImpl(RollingOperationContext context, OperationContext superContext) { @@ -130,7 +131,7 @@ public Status rollback(DeploymentRollback rollback) { @Override public RollingUpdater getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit) { - return new DeploymentRollingUpdater(client, config, getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); + return new DeploymentRollingUpdater(context, getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); } @Override @@ -328,13 +329,13 @@ private Deployment sendPatchedDeployment(Map patchedUpdate) { } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(interruptedException); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(e); } } private ReplicaSetList getReplicaSetListForDeployment(Deployment deployment) { - return new ReplicaSetOperationsImpl(client, config, getNamespace()).withLabels(deployment.getSpec().getSelector().getMatchLabels()).list(); + return new ReplicaSetOperationsImpl(context, getNamespace()).withLabels(deployment.getSpec().getSelector().getMatchLabels()).list(); } static Map getDeploymentSelectorLabels(Deployment deployment) { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/DeploymentRollingUpdater.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/DeploymentRollingUpdater.java index 7da6b20d2a9..82caa123321 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/DeploymentRollingUpdater.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/DeploymentRollingUpdater.java @@ -15,25 +15,24 @@ */ package io.fabric8.kubernetes.client.dsl.internal.apps.v1; -import okhttp3.OkHttpClient; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodList; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; import io.fabric8.kubernetes.api.model.apps.DeploymentList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.Operation; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.WatchListDeletable; class DeploymentRollingUpdater extends RollingUpdater { - DeploymentRollingUpdater(OkHttpClient client, Config config, String namespace) { - super(client, config, namespace); + DeploymentRollingUpdater(ClientContext clientContext, String namespace) { + super(clientContext, namespace); } - DeploymentRollingUpdater(OkHttpClient client, Config config, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { - super(client, config, namespace, rollingTimeoutMillis, loggingIntervalMillis); + DeploymentRollingUpdater(ClientContext clientContext, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { + super(clientContext, namespace, rollingTimeoutMillis, loggingIntervalMillis); } @Override @@ -86,6 +85,6 @@ protected Deployment setReplicas(Deployment obj, int replicas) { @Override protected Operation> resources() { - return new DeploymentOperationsImpl(client, config); + return new DeploymentOperationsImpl(this.clientContext); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/ReplicaSetOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/ReplicaSetOperationsImpl.java index 00be8572b41..50f9f28315b 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/ReplicaSetOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/ReplicaSetOperationsImpl.java @@ -21,16 +21,16 @@ import io.fabric8.kubernetes.api.model.apps.ReplicaSet; import io.fabric8.kubernetes.api.model.apps.ReplicaSetList; import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.LogWatch; import io.fabric8.kubernetes.client.dsl.PodResource; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.TimeoutImageEditReplacePatchable; import io.fabric8.kubernetes.client.dsl.base.OperationContext; -import io.fabric8.kubernetes.client.utils.PodOperationUtil; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.RollingOperationContext; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.utils.PodOperationUtil; import java.io.OutputStream; import java.io.Reader; @@ -43,12 +43,12 @@ public class ReplicaSetOperationsImpl extends RollableScalableResourceOperation> implements TimeoutImageEditReplacePatchable { - public ReplicaSetOperationsImpl(OkHttpClient client, Config config) { - this(client, config, null); + public ReplicaSetOperationsImpl(ClientContext clientContext) { + this(clientContext, null); } - public ReplicaSetOperationsImpl(OkHttpClient client, Config config, String namespace) { - this(new RollingOperationContext(), new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public ReplicaSetOperationsImpl(ClientContext clientContext, String namespace) { + this(new RollingOperationContext(), HasMetadataOperationsImpl.defaultContext(clientContext).withNamespace(namespace)); } public ReplicaSetOperationsImpl(RollingOperationContext context, OperationContext superContext) { @@ -132,7 +132,7 @@ public ReplicaSet withReplicas(int count) { @Override public RollingUpdater getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit) { - return new ReplicaSetRollingUpdater(client, config, getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); + return new ReplicaSetRollingUpdater(context, getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/ReplicaSetRollingUpdater.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/ReplicaSetRollingUpdater.java index 2489aba2ddd..6587006669f 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/ReplicaSetRollingUpdater.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/ReplicaSetRollingUpdater.java @@ -20,20 +20,19 @@ import io.fabric8.kubernetes.api.model.apps.ReplicaSet; import io.fabric8.kubernetes.api.model.apps.ReplicaSetBuilder; import io.fabric8.kubernetes.api.model.apps.ReplicaSetList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.Operation; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.WatchListDeletable; -import okhttp3.OkHttpClient; class ReplicaSetRollingUpdater extends RollingUpdater { - ReplicaSetRollingUpdater(OkHttpClient client, Config config, String namespace) { - super(client, config, namespace); + ReplicaSetRollingUpdater(ClientContext clientContext, String namespace) { + super(clientContext, namespace); } - ReplicaSetRollingUpdater(OkHttpClient client, Config config, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { - super(client, config, namespace, rollingTimeoutMillis, loggingIntervalMillis); + ReplicaSetRollingUpdater(ClientContext clientContext, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { + super(clientContext, namespace, rollingTimeoutMillis, loggingIntervalMillis); } @Override @@ -86,6 +85,6 @@ protected ReplicaSet setReplicas(ReplicaSet obj, int replicas) { @Override protected Operation> resources() { - return new ReplicaSetOperationsImpl(client, config); + return new ReplicaSetOperationsImpl(this.clientContext); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/RollingUpdater.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/RollingUpdater.java index f3d6864b393..6e5d9875c2b 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/RollingUpdater.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/RollingUpdater.java @@ -16,15 +16,13 @@ package io.fabric8.kubernetes.client.dsl.internal.apps.v1; import com.fasterxml.jackson.core.JsonProcessingException; -import io.fabric8.kubernetes.client.dsl.internal.core.v1.PodOperationsImpl; -import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.OkHttpClient; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.LabelSelector; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodBuilder; import io.fabric8.kubernetes.api.model.PodCondition; import io.fabric8.kubernetes.api.model.PodList; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.FilterWatchListDeletable; @@ -32,6 +30,8 @@ import io.fabric8.kubernetes.client.dsl.PodResource; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.WatchListDeletable; +import io.fabric8.kubernetes.client.dsl.internal.core.v1.PodOperationsImpl; +import io.fabric8.kubernetes.client.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -61,19 +61,17 @@ public abstract class RollingUpdater { private static final transient Logger LOG = LoggerFactory.getLogger(RollingUpdater.class); - protected final OkHttpClient client; - protected final Config config; + protected final ClientContext clientContext; protected final String namespace; private final long rollingTimeoutMillis; private final long loggingIntervalMillis; - public RollingUpdater(OkHttpClient client, Config config, String namespace) { - this(client, config, namespace, DEFAULT_ROLLING_TIMEOUT, Config.DEFAULT_LOGGING_INTERVAL); + protected RollingUpdater(ClientContext clientContext, String namespace) { + this(clientContext, namespace, DEFAULT_ROLLING_TIMEOUT, Config.DEFAULT_LOGGING_INTERVAL); } - public RollingUpdater(OkHttpClient client, Config config, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { - this.client = client; - this.config = config; + protected RollingUpdater(ClientContext clientContext, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { + this.clientContext = clientContext; this.namespace = namespace; this.rollingTimeoutMillis = rollingTimeoutMillis; this.loggingIntervalMillis = loggingIntervalMillis; @@ -265,11 +263,11 @@ private String md5sum(HasMetadata obj) throws NoSuchAlgorithmException, JsonProc protected abstract Operation> resources(); protected Operation> pods() { - return new PodOperationsImpl(client, config); + return new PodOperationsImpl(clientContext); } protected FilterWatchListDeletable selectedPodLister(LabelSelector selector) { return pods().inNamespace(namespace).withLabelSelector(selector); } - + } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/StatefulSetOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/StatefulSetOperationsImpl.java index 02b80ee1fdd..ad60b04fd05 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/StatefulSetOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/StatefulSetOperationsImpl.java @@ -24,7 +24,7 @@ import io.fabric8.kubernetes.api.model.apps.StatefulSet; import io.fabric8.kubernetes.api.model.apps.StatefulSetList; import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.LogWatch; @@ -32,9 +32,9 @@ import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.TimeoutImageEditReplacePatchable; import io.fabric8.kubernetes.client.dsl.base.OperationContext; -import io.fabric8.kubernetes.client.utils.PodOperationUtil; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.RollingOperationContext; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.utils.PodOperationUtil; import java.io.IOException; import java.io.OutputStream; @@ -43,18 +43,17 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; public class StatefulSetOperationsImpl extends RollableScalableResourceOperation> implements TimeoutImageEditReplacePatchable { - public StatefulSetOperationsImpl(OkHttpClient client, Config config) { - this(client, config, null); + public StatefulSetOperationsImpl(ClientContext clientContext) { + this(clientContext, null); } - public StatefulSetOperationsImpl(OkHttpClient client, Config config, String namespace) { - this(new RollingOperationContext(), new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public StatefulSetOperationsImpl(ClientContext clientContext, String namespace) { + this(new RollingOperationContext(), HasMetadataOperationsImpl.defaultContext(clientContext).withNamespace(namespace)); } public StatefulSetOperationsImpl(RollingOperationContext context, OperationContext superContext) { @@ -80,7 +79,7 @@ public StatefulSet withReplicas(int count) { @Override public RollingUpdater getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit) { - return new StatefulSetRollingUpdater(client, config, getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); + return new StatefulSetRollingUpdater(context, getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); } @Override @@ -216,7 +215,7 @@ private StatefulSet sendPatchedStatefulSet(Map patchedUpdate) { } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(interruptedException); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(e); } } @@ -226,7 +225,7 @@ private StatefulSet sendPatchedStatefulSetData(HasMetadata patchedUpdate) { } private ControllerRevisionList getControllerRevisionListForStatefulSet(StatefulSet statefulSet) { - return Handlers.getOperation(ControllerRevision.class, ControllerRevisionList.class, client, config).inNamespace(namespace).withLabels(statefulSet.getSpec().getSelector().getMatchLabels()).list(); + return Handlers.getOperation(ControllerRevision.class, ControllerRevisionList.class, this.context).inNamespace(namespace).withLabels(statefulSet.getSpec().getSelector().getMatchLabels()).list(); } static Map getStatefulSetSelectorLabels(StatefulSet statefulSet) { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/StatefulSetRollingUpdater.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/StatefulSetRollingUpdater.java index 8ba93f440a3..0dabb969350 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/StatefulSetRollingUpdater.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/apps/v1/StatefulSetRollingUpdater.java @@ -20,20 +20,19 @@ import io.fabric8.kubernetes.api.model.apps.StatefulSet; import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder; import io.fabric8.kubernetes.api.model.apps.StatefulSetList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.Operation; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.WatchListDeletable; -import okhttp3.OkHttpClient; class StatefulSetRollingUpdater extends RollingUpdater { - StatefulSetRollingUpdater(OkHttpClient client, Config config, String namespace) { - super(client, config, namespace); + StatefulSetRollingUpdater(ClientContext clientContext, String namespace) { + super(clientContext, namespace); } - StatefulSetRollingUpdater(OkHttpClient client, Config config, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { - super(client, config, namespace, rollingTimeoutMillis, loggingIntervalMillis); + StatefulSetRollingUpdater(ClientContext clientContext, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { + super(clientContext, namespace, rollingTimeoutMillis, loggingIntervalMillis); } @Override @@ -91,6 +90,6 @@ protected StatefulSet setReplicas(StatefulSet obj, int replicas) { @Override protected Operation> resources() { - return new StatefulSetOperationsImpl(client, config); + return new StatefulSetOperationsImpl(this.clientContext); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/batch/v1/JobOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/batch/v1/JobOperationsImpl.java index a83ef4c62f2..174fed96166 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/batch/v1/JobOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/batch/v1/JobOperationsImpl.java @@ -17,19 +17,19 @@ import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.autoscaling.v1.Scale; +import io.fabric8.kubernetes.api.model.batch.v1.Job; +import io.fabric8.kubernetes.api.model.batch.v1.JobList; +import io.fabric8.kubernetes.client.ClientContext; +import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.LogWatch; import io.fabric8.kubernetes.client.dsl.Loggable; import io.fabric8.kubernetes.client.dsl.PodResource; +import io.fabric8.kubernetes.client.dsl.ScalableResource; +import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.PodControllerOperationContext; import io.fabric8.kubernetes.client.utils.PodOperationUtil; -import okhttp3.OkHttpClient; -import io.fabric8.kubernetes.api.model.batch.v1.Job; -import io.fabric8.kubernetes.api.model.batch.v1.JobList; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.KubernetesClientException; -import io.fabric8.kubernetes.client.dsl.ScalableResource; -import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,12 +49,12 @@ public class JobOperationsImpl extends HasMetadataOperation> { - public CronJobOperationsImpl(OkHttpClient client, Config config) { - this(client, config, null); + public CronJobOperationsImpl(ClientContext clientContext) { + this(clientContext, null); } - public CronJobOperationsImpl(OkHttpClient client, Config config, String namespace) { - this(new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public CronJobOperationsImpl(ClientContext clientContext, String namespace) { + this(HasMetadataOperationsImpl.defaultContext(clientContext).withNamespace(namespace)); } public CronJobOperationsImpl(OperationContext context) { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/certificates/v1/CertificateSigningRequestOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/certificates/v1/CertificateSigningRequestOperationsImpl.java index e052ca347b1..2b13a4c847c 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/certificates/v1/CertificateSigningRequestOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/certificates/v1/CertificateSigningRequestOperationsImpl.java @@ -21,27 +21,24 @@ import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequestList; import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequestStatus; import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequestStatusBuilder; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.CertificateSigningRequestResource; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; +import io.fabric8.kubernetes.client.http.HttpRequest; import io.fabric8.kubernetes.client.utils.URLUtils; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; import java.io.IOException; -import java.net.URL; -import java.util.concurrent.ExecutionException; public class CertificateSigningRequestOperationsImpl extends HasMetadataOperation> implements CertificateSigningRequestResource { - public CertificateSigningRequestOperationsImpl(OkHttpClient client, Config config) { - this(client, config, null); + public CertificateSigningRequestOperationsImpl(ClientContext clientContext) { + this(clientContext, null); } - public CertificateSigningRequestOperationsImpl(OkHttpClient client, Config config, String namespace) { - this(new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public CertificateSigningRequestOperationsImpl(ClientContext clientContext, String namespace) { + this(HasMetadataOperationsImpl.defaultContext(clientContext).withNamespace(namespace)); } public CertificateSigningRequestOperationsImpl(OperationContext context) { @@ -70,14 +67,13 @@ private CertificateSigningRequest approveOrDeny(CertificateSigningRequestConditi try { CertificateSigningRequest fromServerCsr = fromServer().get(); fromServerCsr.setStatus(createCertificateSigningRequestStatus(csrCondition)); - RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(fromServerCsr)); - URL url = new URL(URLUtils.join(getResourceUrl(null, fromServerCsr.getMetadata().getName(), false).toString(), "approval")); - Request.Builder requestBuilder = new Request.Builder().put(body).url(url); + String uri = URLUtils.join(getResourceUrl(null, fromServerCsr.getMetadata().getName(), false).toString(), "approval"); + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().put(JSON, JSON_MAPPER.writeValueAsString(fromServerCsr)).uri(uri); return handleResponse(requestBuilder, CertificateSigningRequest.class); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(forOperationType("CeritificateSigningRequest " + type), ie); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(forOperationType("CertificateSigningRequest " + type), e); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/BindingOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/BindingOperationsImpl.java index 69975322080..46e10142f4b 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/BindingOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/BindingOperationsImpl.java @@ -19,19 +19,19 @@ import com.fasterxml.jackson.databind.type.TypeFactory; import io.fabric8.kubernetes.api.model.Binding; import io.fabric8.kubernetes.api.model.KubernetesResourceList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; public class BindingOperationsImpl extends HasMetadataOperation, Resource> { - public BindingOperationsImpl(OkHttpClient client, Config config) { - this(client, config, null); + public BindingOperationsImpl(ClientContext clientContext) { + this(clientContext, null); } - public BindingOperationsImpl(OkHttpClient client, Config config, String namespace) { - this(new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public BindingOperationsImpl(ClientContext clientContext, String namespace) { + this(HasMetadataOperationsImpl.defaultContext(clientContext).withNamespace(namespace)); } public BindingOperationsImpl(OperationContext context) { @@ -40,6 +40,7 @@ public BindingOperationsImpl(OperationContext context) { .withPlural("bindings"), Binding.class, (Class>) TypeFactory.rawClass(new TypeReference>(){}.getType())); } + @Override public BindingOperationsImpl newInstance(OperationContext context) { return new BindingOperationsImpl(context); } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ComponentStatusOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ComponentStatusOperationsImpl.java index 40c21e09db8..682dd1092f2 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ComponentStatusOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ComponentStatusOperationsImpl.java @@ -15,24 +15,23 @@ */ package io.fabric8.kubernetes.client.dsl.internal.core.v1; -import io.fabric8.kubernetes.client.dsl.Resource; -import io.fabric8.kubernetes.client.dsl.base.OperationContext; -import okhttp3.OkHttpClient; - import io.fabric8.kubernetes.api.model.ComponentStatus; import io.fabric8.kubernetes.api.model.ComponentStatusList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; +import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; +import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; public class ComponentStatusOperationsImpl extends HasMetadataOperation> { - public ComponentStatusOperationsImpl(OkHttpClient client, Config config) { - this(client, config, null); + public ComponentStatusOperationsImpl(ClientContext clientContext) { + this(clientContext, null); } - public ComponentStatusOperationsImpl(OkHttpClient client, Config config, String namespace) { - this(new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public ComponentStatusOperationsImpl(ClientContext clientContext, String namespace) { + this(HasMetadataOperationsImpl.defaultContext(clientContext).withNamespace(namespace)); } public ComponentStatusOperationsImpl(OperationContext context) { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/PodOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/PodOperationsImpl.java index a26467db224..bede1591f5b 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/PodOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/PodOperationsImpl.java @@ -25,6 +25,7 @@ import java.io.PipedOutputStream; import java.io.Reader; import java.net.HttpURLConnection; +import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; @@ -33,7 +34,7 @@ import java.nio.file.StandardCopyOption; import java.util.Collections; import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import io.fabric8.kubernetes.api.model.DeleteOptions; @@ -42,7 +43,7 @@ import io.fabric8.kubernetes.api.model.PodList; import io.fabric8.kubernetes.api.model.policy.v1beta1.Eviction; import io.fabric8.kubernetes.api.model.policy.v1beta1.EvictionBuilder; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.LocalPortForward; import io.fabric8.kubernetes.client.PortForward; @@ -66,19 +67,18 @@ import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; import io.fabric8.kubernetes.client.dsl.internal.ExecWebSocketListener; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.LogWatchCallback; import io.fabric8.kubernetes.client.dsl.internal.PodOperationContext; import io.fabric8.kubernetes.client.utils.PodOperationUtil; import io.fabric8.kubernetes.client.dsl.internal.PortForwarderWebsocket; import io.fabric8.kubernetes.client.dsl.internal.uploadable.PodUpload; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.WebSocket; import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; +import io.fabric8.kubernetes.client.utils.URLUtils.URLBuilder; import io.fabric8.kubernetes.client.lib.FilenameUtils; public class PodOperationsImpl extends HasMetadataOperation> implements PodResource,CopyOrReadable { @@ -109,12 +109,12 @@ public class PodOperationsImpl extends HasMetadataOperation T doGetLog(Class type){ try { URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters())); - Request.Builder requestBuilder = new Request.Builder().get().url(url); - Request request = requestBuilder.build(); - Response response = client.newCall(request).execute(); - ResponseBody body = response.body(); - assertResponseCode(request, response); - return body; + return handleRawGet(url, type); } catch (IOException ioException) { throw KubernetesClientException.launderThrowable(forOperationType("doGetLog"), ioException); } @@ -192,11 +187,7 @@ protected ResponseBody doGetLog(){ @Override public String getLog() { - try(ResponseBody body = doGetLog()) { - return body.string(); - } catch (IOException e) { - throw KubernetesClientException.launderThrowable(forOperationType("getLog"), e); - } + return doGetLog(String.class); } /** @@ -205,7 +196,7 @@ public String getLog() { */ @Override public Reader getLogReader() { - return doGetLog().charStream(); + return doGetLog(Reader.class); } @Override @@ -225,12 +216,8 @@ public LogWatch watchLog(OutputStream out) { getContext().getLogWaitTimeout() : DEFAULT_POD_LOG_WAIT_TIMEOUT); // Issue Pod Logs HTTP request URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters() + "&follow=true")); - Request request = new Request.Builder().url(url).get().build(); - final LogWatchCallback callback = new LogWatchCallback(out); - OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build(); - clone.newCall(request).enqueue(callback); - callback.waitUntilReady(); - return callback; + final LogWatchCallback callback = new LogWatchCallback(config, out); + return callback.callAndWait(httpClient, url); } catch (IOException ioException) { throw KubernetesClientException.launderThrowable(forOperationType("watchLog"), ioException); } @@ -244,7 +231,7 @@ public Loggable withLogWaitTimeout(Integer logWaitTimeout) { @Override public PortForward portForward(int port, ReadableByteChannel in, WritableByteChannel out) { try { - return new PortForwarderWebsocket(client).forward(getResourceUrl(), port, in, out); + return new PortForwarderWebsocket(httpClient).forward(getResourceUrl(), port, in, out); } catch (Throwable t) { throw KubernetesClientException.launderThrowable(t); } @@ -253,7 +240,7 @@ public PortForward portForward(int port, ReadableByteChannel in, WritableByteCha @Override public LocalPortForward portForward(int port) { try { - return new PortForwarderWebsocket(client).forward(getResourceUrl(), port); + return new PortForwarderWebsocket(httpClient).forward(getResourceUrl(), port); } catch (Throwable t) { throw KubernetesClientException.launderThrowable(t); } @@ -262,7 +249,7 @@ public LocalPortForward portForward(int port) { @Override public LocalPortForward portForward(int port, int localPort) { try { - return new PortForwarderWebsocket(client).forward(getResourceUrl(), port, localPort); + return new PortForwarderWebsocket(httpClient).forward(getResourceUrl(), port, localPort); } catch (Throwable t) { throw KubernetesClientException.launderThrowable(t); } @@ -293,10 +280,9 @@ private Boolean handleEvict(HasMetadata eviction) { if (Utils.isNullOrEmpty(eviction.getMetadata().getName())) { throw new KubernetesClientException("Name not specified, but operation requires it."); } - RequestBody requestBody = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(eviction)); URL requestUrl = new URL(URLUtils.join(getResourceUrl().toString(), "eviction")); - Request.Builder requestBuilder = new Request.Builder().post(requestBody).url(requestUrl); + HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().post(JSON, JSON_MAPPER.writeValueAsString(eviction)).url(requestUrl); handleResponse(requestBuilder, null, Collections.emptyMap()); return true; } catch (KubernetesClientException e) { @@ -304,7 +290,7 @@ private Boolean handleEvict(HasMetadata eviction) { throw e; } return false; - } catch (ExecutionException | IOException exception) { + } catch (IOException exception) { throw KubernetesClientException.launderThrowable(forOperationType("evict"), exception); } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); @@ -321,23 +307,32 @@ public ContainerResource= 1 ? command : EMPTY_COMMAND; try { - URL url = getURLWithCommandParams(HttpUrl.get(getResourceUrl()).newBuilder(), actualCommands); - Request.Builder r = new Request.Builder().url(url).header("Sec-WebSocket-Protocol", "v4.channel.k8s.io").get(); - OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build(); - final ExecWebSocketListener execWebSocketListener = new ExecWebSocketListener(getConfig(), in, out, err, errChannel, inPipe, outPipe, errPipe, errChannelPipe, execListener, bufferSize); - clone.newWebSocket(r.build(), execWebSocketListener); - execWebSocketListener.waitUntilReady(); + URL url = getURLWithCommandParams(actualCommands); + HttpClient clone = httpClient.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build(); + final ExecWebSocketListener execWebSocketListener = new ExecWebSocketListener(in, out, err, errChannel, inPipe, outPipe, errPipe, errChannelPipe, execListener, bufferSize); + CompletableFuture startedFuture = clone.newWebSocketBuilder() + .setHeader("Sec-WebSocket-Protocol", "v4.channel.k8s.io") + .uri(url.toURI()) + .buildAsync(execWebSocketListener); + startedFuture.whenComplete((w, t) -> { + if (t != null) { + execWebSocketListener.onError(w, t); + } + }); + Utils.waitUntilReadyOrFail(startedFuture, config.getWebsocketTimeout(), TimeUnit.MILLISECONDS); return execWebSocketListener; } catch (Throwable t) { throw KubernetesClientException.launderThrowable(forOperationType("exec"), t); } } - URL getURLWithCommandParams(HttpUrl.Builder httpUrlBuilder, String[] commands) { - httpUrlBuilder.addPathSegment("exec"); + URL getURLWithCommandParams(String[] commands) throws MalformedURLException { + String url = URLUtils.join(getResourceUrl().toString(), "exec"); + + URLBuilder httpUrlBuilder = new URLBuilder(url); for (String cmd : commands) { - httpUrlBuilder.addQueryParameter("command", cmd); + httpUrlBuilder.addQueryParameter("command", cmd); } if (containerId != null && !containerId.isEmpty()) { @@ -355,7 +350,7 @@ URL getURLWithCommandParams(HttpUrl.Builder httpUrlBuilder, String[] commands) { if (err != null || errPipe != null) { httpUrlBuilder.addQueryParameter("stderr", "true"); } - return httpUrlBuilder.build().url(); + return httpUrlBuilder.build(); } @Override @@ -388,7 +383,7 @@ public Boolean copy(Path destination) { public Boolean upload(Path path) { return wrapRunWithOptionalDependency(() -> { try { - return PodUpload.upload(client, getContext(), this, path); + return PodUpload.upload(httpClient, getContext(), this, path); } catch (Exception ex) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(ex); @@ -419,19 +414,7 @@ public InputStream call() { try { PipedOutputStream out = new PipedOutputStream(); PipedInputStream in = new PipedInputStream(out, 1024); - ExecWatch watch = writingOutput(out).usingListener(new ExecListener() { - @Override - public void onOpen(Response response) { - - } - - @Override - public void onFailure(Throwable t, Response response) { - - } - - @Override - public void onClose(int code, String reason) { + ExecWatch watch = writingOutput(out).usingListener((int code, String reason) -> { try { out.flush(); out.close(); @@ -439,8 +422,14 @@ public void onClose(int code, String reason) { e.printStackTrace(); } } - }).exec("sh", "-c", String.format("cat %s | base64", PodUpload.shellQuote(source))); - return new org.apache.commons.codec.binary.Base64InputStream(in); + ).exec("sh", "-c", String.format("cat %s | base64", PodUpload.shellQuote(source))); + return new org.apache.commons.codec.binary.Base64InputStream(in) { + @Override + public void close() throws IOException { + watch.close(); + super.close(); + } + }; } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } @@ -493,19 +482,7 @@ public InputStream call() throws Exception { try { PipedOutputStream out = new PipedOutputStream(); PipedInputStream in = new PipedInputStream(out, 1024); - ExecWatch watch = writingOutput(out).usingListener(new ExecListener() { - @Override - public void onOpen(Response response) { - - } - - @Override - public void onFailure(Throwable t, Response response) { - - } - - @Override - public void onClose(int code, String reason) { + ExecWatch watch = writingOutput(out).usingListener((int code, String reason) -> { try { out.flush(); out.close(); @@ -513,8 +490,14 @@ public void onClose(int code, String reason) { e.printStackTrace(); } } - }).exec("sh", "-c", "tar -cf - " + source + "|" + "base64"); - return new org.apache.commons.codec.binary.Base64InputStream(in); + ).exec("sh", "-c", "tar -cf - " + source + "|" + "base64"); + return new org.apache.commons.codec.binary.Base64InputStream(in) { + @Override + public void close() throws IOException { + watch.close(); + super.close(); + } + }; } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } catch (NoClassDefFoundError n) { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ReplicationControllerOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ReplicationControllerOperationsImpl.java index aec769a7e2e..c79f85b62d0 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ReplicationControllerOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ReplicationControllerOperationsImpl.java @@ -21,18 +21,18 @@ import io.fabric8.kubernetes.api.model.ReplicationControllerList; import io.fabric8.kubernetes.api.model.Status; import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.LogWatch; import io.fabric8.kubernetes.client.dsl.PodResource; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.TimeoutImageEditReplacePatchable; import io.fabric8.kubernetes.client.dsl.base.OperationContext; -import io.fabric8.kubernetes.client.utils.PodOperationUtil; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.RollingOperationContext; import io.fabric8.kubernetes.client.dsl.internal.apps.v1.RollableScalableResourceOperation; import io.fabric8.kubernetes.client.dsl.internal.apps.v1.RollingUpdater; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.utils.PodOperationUtil; import java.io.InputStream; import java.io.OutputStream; @@ -46,12 +46,12 @@ public class ReplicationControllerOperationsImpl extends RollableScalableResourceOperation> implements TimeoutImageEditReplacePatchable { - public ReplicationControllerOperationsImpl(OkHttpClient client, Config config) { - this(client, config, null); + public ReplicationControllerOperationsImpl(ClientContext clientContext) { + this(clientContext, null); } - public ReplicationControllerOperationsImpl(OkHttpClient client, Config config, String namespace) { - this(new RollingOperationContext(), new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public ReplicationControllerOperationsImpl(ClientContext clientContext, String namespace) { + this(new RollingOperationContext(), HasMetadataOperationsImpl.defaultContext(clientContext).withNamespace(namespace)); } public ReplicationControllerOperationsImpl(RollingOperationContext context, OperationContext superContext) { @@ -81,7 +81,7 @@ public ReplicationController withReplicas(int count) { @Override public RollingUpdater getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit) { - return new ReplicationControllerRollingUpdater(client, config, namespace, rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); + return new ReplicationControllerRollingUpdater(context, namespace, rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ReplicationControllerRollingUpdater.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ReplicationControllerRollingUpdater.java index c36a1666da2..b8476112273 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ReplicationControllerRollingUpdater.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ReplicationControllerRollingUpdater.java @@ -15,26 +15,25 @@ */ package io.fabric8.kubernetes.client.dsl.internal.core.v1; -import io.fabric8.kubernetes.client.dsl.internal.apps.v1.RollingUpdater; -import okhttp3.OkHttpClient; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodList; import io.fabric8.kubernetes.api.model.ReplicationController; import io.fabric8.kubernetes.api.model.ReplicationControllerBuilder; import io.fabric8.kubernetes.api.model.ReplicationControllerList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.Operation; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.WatchListDeletable; +import io.fabric8.kubernetes.client.dsl.internal.apps.v1.RollingUpdater; class ReplicationControllerRollingUpdater extends RollingUpdater { - ReplicationControllerRollingUpdater(OkHttpClient client, Config config, String namespace) { - super(client, config, namespace); + ReplicationControllerRollingUpdater(ClientContext clientContext, String namespace) { + super(clientContext, namespace); } - ReplicationControllerRollingUpdater(OkHttpClient client, Config config, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { - super(client, config, namespace, rollingTimeoutMillis, loggingIntervalMillis); + ReplicationControllerRollingUpdater(ClientContext clientContext, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { + super(clientContext, namespace, rollingTimeoutMillis, loggingIntervalMillis); } @Override @@ -92,6 +91,6 @@ protected ReplicationController setReplicas(ReplicationController obj, int repli @Override protected Operation> resources() { - return new ReplicationControllerOperationsImpl(client, config); + return new ReplicationControllerOperationsImpl(this.clientContext); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ServiceOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ServiceOperationsImpl.java index c8c1dcbf502..0a3e0687ce1 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ServiceOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/ServiceOperationsImpl.java @@ -15,19 +15,35 @@ */ package io.fabric8.kubernetes.client.dsl.internal.core.v1; -import io.fabric8.kubernetes.api.model.*; -import io.fabric8.kubernetes.client.*; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.api.model.Endpoints; +import io.fabric8.kubernetes.api.model.EndpointsList; +import io.fabric8.kubernetes.api.model.Pod; +import io.fabric8.kubernetes.api.model.PodList; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceBuilder; +import io.fabric8.kubernetes.api.model.ServiceList; +import io.fabric8.kubernetes.client.ClientContext; +import io.fabric8.kubernetes.client.DefaultKubernetesClient; +import io.fabric8.kubernetes.client.Handlers; +import io.fabric8.kubernetes.client.LocalPortForward; +import io.fabric8.kubernetes.client.PortForward; +import io.fabric8.kubernetes.client.ServiceToURLProvider; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.ServiceResource; import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.utils.URLUtils; -import okhttp3.OkHttpClient; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.ServiceLoader; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; @@ -35,12 +51,12 @@ public class ServiceOperationsImpl extends HasMetadataOperation> endpointsOperation = (HasMetadataOperation>) Handlers - .getOperation(Endpoints.class, EndpointsList.class, client, config) + .getOperation(Endpoints.class, EndpointsList.class, this.context) .newInstance(context); endpointsOperation.waitUntilReady(remaining, TimeUnit.MILLISECONDS); return get(); } + @Override public String getURL(String portName) { String clusterIP = getMandatory().getSpec().getClusterIP(); if ("None".equals(clusterIP)) { @@ -92,7 +109,7 @@ private String getUrlHelper(String portName) { // Sort all loaded implementations according to priority Collections.sort(servicesList, new ServiceToUrlSortComparator()); for (ServiceToURLProvider serviceToURLProvider : servicesList) { - String url = serviceToURLProvider.getURL(getMandatory(), portName, namespace, new DefaultKubernetesClient(client, getConfig())); + String url = serviceToURLProvider.getURL(getMandatory(), portName, namespace, new DefaultKubernetesClient(context)); if (url != null && URLUtils.isValidURL(url)) { return url; } @@ -104,14 +121,14 @@ private String getUrlHelper(String portName) { private Pod matchingPod() { Service item = requireFromServer(); Map labels = item.getSpec().getSelector(); - PodList list = new PodOperationsImpl(client, config).inNamespace(item.getMetadata().getNamespace()).withLabels(labels).list(); + PodList list = new PodOperationsImpl(context).inNamespace(item.getMetadata().getNamespace()).withLabels(labels).list(); return list.getItems().stream().findFirst().orElseThrow(() -> new IllegalStateException("Could not find matching pod for service:" + item + ".")); } @Override public PortForward portForward(int port, ReadableByteChannel in, WritableByteChannel out) { Pod m = matchingPod(); - return new PodOperationsImpl(client, config) + return new PodOperationsImpl(context) .inNamespace(m.getMetadata().getNamespace()) .withName(m.getMetadata().getName()) .portForward(port, in, out); @@ -120,7 +137,7 @@ public PortForward portForward(int port, ReadableByteChannel in, WritableByteCha @Override public LocalPortForward portForward(int port, int localPort) { Pod m = matchingPod(); - return new PodOperationsImpl(client, config) + return new PodOperationsImpl(context) .inNamespace(m.getMetadata().getNamespace()) .withName(m.getMetadata().getName()) .portForward(port, localPort); @@ -129,13 +146,14 @@ public LocalPortForward portForward(int port, int localPort) { @Override public LocalPortForward portForward(int port) { Pod m = matchingPod(); - return new PodOperationsImpl(client, config) + return new PodOperationsImpl(context) .inNamespace(m.getMetadata().getNamespace()) .withName(m.getMetadata().getName()) .portForward(port); } public class ServiceToUrlSortComparator implements Comparator { + @Override public int compare(ServiceToURLProvider first, ServiceToURLProvider second) { return first.getPriority() - second.getPriority(); } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/DeploymentOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/DeploymentOperationsImpl.java index 07b0ac82b0d..354123942dd 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/DeploymentOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/DeploymentOperationsImpl.java @@ -23,7 +23,7 @@ import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback; import io.fabric8.kubernetes.api.model.extensions.ReplicaSet; import io.fabric8.kubernetes.api.model.extensions.ReplicaSetList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.KubernetesClientTimeoutException; import io.fabric8.kubernetes.client.dsl.LogWatch; @@ -31,11 +31,11 @@ import io.fabric8.kubernetes.client.dsl.TimeoutImageEditReplacePatchable; import io.fabric8.kubernetes.client.dsl.base.OperationContext; import io.fabric8.kubernetes.client.dsl.base.PatchContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.RollingOperationContext; import io.fabric8.kubernetes.client.dsl.internal.apps.v1.RollableScalableResourceOperation; import io.fabric8.kubernetes.client.dsl.internal.apps.v1.RollingUpdater; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; -import okhttp3.OkHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,10 +48,9 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.function.Consumer; -import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; import java.util.function.UnaryOperator; public class DeploymentOperationsImpl extends RollableScalableResourceOperation> @@ -60,8 +59,8 @@ public class DeploymentOperationsImpl extends RollableScalableResourceOperation< static final transient Logger LOG = LoggerFactory.getLogger(DeploymentOperationsImpl.class); public static final String DEPLOYMENT_KUBERNETES_IO_REVISION = "deployment.kubernetes.io/revision"; - public DeploymentOperationsImpl(OkHttpClient client, Config config) { - this(new RollingOperationContext(), new OperationContext().withOkhttpClient(client).withConfig(config).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public DeploymentOperationsImpl(ClientContext clientContext) { + this(new RollingOperationContext(), HasMetadataOperationsImpl.defaultContext(clientContext)); } public DeploymentOperationsImpl(RollingOperationContext context, OperationContext superContext) { @@ -129,7 +128,7 @@ public Status rollback(DeploymentRollback rollback) { @Override public RollingUpdater getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit) { - return new DeploymentRollingUpdater(client, config, getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); + return new DeploymentRollingUpdater(context, getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); } @Override @@ -327,13 +326,13 @@ private Deployment sendPatchedDeployment(Map patchedUpdate) { } catch (InterruptedException interruptedException) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(interruptedException); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(e); } } private ReplicaSetList getReplicaSetListForDeployment(Deployment deployment) { - return new ReplicaSetOperationsImpl(client, config, getNamespace()).withLabels(deployment.getSpec().getSelector().getMatchLabels()).list(); + return new ReplicaSetOperationsImpl(context, getNamespace()).withLabels(deployment.getSpec().getSelector().getMatchLabels()).list(); } static Map getDeploymentSelectorLabels(Deployment deployment) { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/DeploymentRollingUpdater.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/DeploymentRollingUpdater.java index e7bea578bb0..02ce055da18 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/DeploymentRollingUpdater.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/DeploymentRollingUpdater.java @@ -20,21 +20,20 @@ import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder; import io.fabric8.kubernetes.api.model.extensions.DeploymentList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.Operation; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.WatchListDeletable; import io.fabric8.kubernetes.client.dsl.internal.apps.v1.RollingUpdater; -import okhttp3.OkHttpClient; class DeploymentRollingUpdater extends RollingUpdater { - DeploymentRollingUpdater(OkHttpClient client, Config config, String namespace) { - super(client, config, namespace); + DeploymentRollingUpdater(ClientContext clientContext, String namespace) { + super(clientContext, namespace); } - DeploymentRollingUpdater(OkHttpClient client, Config config, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { - super(client, config, namespace, rollingTimeoutMillis, loggingIntervalMillis); + DeploymentRollingUpdater(ClientContext clientContext, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { + super(clientContext, namespace, rollingTimeoutMillis, loggingIntervalMillis); } @Override @@ -91,6 +90,6 @@ protected Deployment setReplicas(Deployment obj, int replicas) { @Override protected Operation> resources() { - return new DeploymentOperationsImpl(client, config); + return new DeploymentOperationsImpl(this.clientContext); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/ReplicaSetOperationsImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/ReplicaSetOperationsImpl.java index 860f8515ce5..9a524cc56a8 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/ReplicaSetOperationsImpl.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/ReplicaSetOperationsImpl.java @@ -21,18 +21,18 @@ import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback; import io.fabric8.kubernetes.api.model.extensions.ReplicaSet; import io.fabric8.kubernetes.api.model.extensions.ReplicaSetList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.LogWatch; import io.fabric8.kubernetes.client.dsl.PodResource; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.TimeoutImageEditReplacePatchable; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.RollingOperationContext; import io.fabric8.kubernetes.client.dsl.internal.apps.v1.RollableScalableResourceOperation; import io.fabric8.kubernetes.client.dsl.internal.apps.v1.RollingUpdater; import io.fabric8.kubernetes.client.utils.PodOperationUtil; -import okhttp3.OkHttpClient; import java.io.OutputStream; import java.io.Reader; @@ -45,12 +45,12 @@ public class ReplicaSetOperationsImpl extends RollableScalableResourceOperation> implements TimeoutImageEditReplacePatchable { - public ReplicaSetOperationsImpl(OkHttpClient client, Config config) { - this(client, config, null); + public ReplicaSetOperationsImpl(ClientContext clientContext) { + this(clientContext, null); } - public ReplicaSetOperationsImpl(OkHttpClient client, Config config, String namespace) { - this(new RollingOperationContext(), new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public ReplicaSetOperationsImpl(ClientContext clientContext, String namespace) { + this(new RollingOperationContext(), HasMetadataOperationsImpl.defaultContext(clientContext).withNamespace(namespace)); } public ReplicaSetOperationsImpl(RollingOperationContext context, OperationContext superContext) { @@ -134,7 +134,7 @@ public ReplicaSet withReplicas(int count) { @Override public RollingUpdater getRollingUpdater(long rollingTimeout, TimeUnit rollingTimeUnit) { - return new ReplicaSetRollingUpdater(client, config, getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); + return new ReplicaSetRollingUpdater(context, getNamespace(), rollingTimeUnit.toMillis(rollingTimeout), config.getLoggingInterval()); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/ReplicaSetRollingUpdater.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/ReplicaSetRollingUpdater.java index c5850e761ac..b19dc220a7d 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/ReplicaSetRollingUpdater.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/extensions/v1beta1/ReplicaSetRollingUpdater.java @@ -20,21 +20,20 @@ import io.fabric8.kubernetes.api.model.extensions.ReplicaSet; import io.fabric8.kubernetes.api.model.extensions.ReplicaSetBuilder; import io.fabric8.kubernetes.api.model.extensions.ReplicaSetList; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.Operation; import io.fabric8.kubernetes.client.dsl.RollableScalableResource; import io.fabric8.kubernetes.client.dsl.WatchListDeletable; import io.fabric8.kubernetes.client.dsl.internal.apps.v1.RollingUpdater; -import okhttp3.OkHttpClient; class ReplicaSetRollingUpdater extends RollingUpdater { - ReplicaSetRollingUpdater(OkHttpClient client, Config config, String namespace) { - super(client, config, namespace); + ReplicaSetRollingUpdater(ClientContext clientContext, String namespace) { + super(clientContext, namespace); } - ReplicaSetRollingUpdater(OkHttpClient client, Config config, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { - super(client, config, namespace, rollingTimeoutMillis, loggingIntervalMillis); + ReplicaSetRollingUpdater(ClientContext clientContext, String namespace, long rollingTimeoutMillis, long loggingIntervalMillis) { + super(clientContext, namespace, rollingTimeoutMillis, loggingIntervalMillis); } @Override @@ -89,6 +88,6 @@ protected ReplicaSet setReplicas(ReplicaSet obj, int replicas) { @Override protected Operation> resources() { - return new ReplicaSetOperationsImpl(client, config); + return new ReplicaSetOperationsImpl(clientContext); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUpload.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUpload.java index 0103ac081f2..10c6285bae3 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUpload.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUpload.java @@ -21,13 +21,14 @@ import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; -import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; +import java.net.URI; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -39,10 +40,10 @@ import io.fabric8.kubernetes.client.dsl.base.OperationSupport; import io.fabric8.kubernetes.client.dsl.internal.PodOperationContext; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.WebSocket; import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.OkHttpClient; -import okhttp3.Request; import org.apache.commons.codec.binary.Base64InputStream; import org.apache.commons.codec.binary.Base64OutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; @@ -56,7 +57,7 @@ public class PodUpload { private PodUpload() { } - public static boolean upload(OkHttpClient client, PodOperationContext context, + public static boolean upload(HttpClient client, PodOperationContext context, OperationSupport operationSupport, Path pathToUpload) throws IOException, InterruptedException { @@ -68,7 +69,7 @@ public static boolean upload(OkHttpClient client, PodOperationContext context, throw new IllegalArgumentException("Provided arguments are not valid (file, directory, path)"); } - private static boolean uploadFile(OkHttpClient client, PodOperationContext context, + private static boolean uploadFile(HttpClient client, PodOperationContext context, OperationSupport operationSupport, Path pathToUpload) throws IOException, InterruptedException { @@ -93,7 +94,7 @@ public static String shellQuote(String value) { return "'" + value.replaceAll("'", "'\\\\''") + "'"; } - private static boolean uploadDirectory(OkHttpClient client, PodOperationContext context, + private static boolean uploadDirectory(HttpClient client, PodOperationContext context, OperationSupport operationSupport, Path pathToUpload) throws IOException, InterruptedException { @@ -164,17 +165,23 @@ private static void addFileToTar(String rootTarPath, File file, TarArchiveOutput } } - private static PodUploadWebSocketListener initWebSocket(URL url, OkHttpClient client) { + private static PodUploadWebSocketListener initWebSocket(URL url, HttpClient client) { final PodUploadWebSocketListener podUploadWebSocketListener = new PodUploadWebSocketListener(); - final Request.Builder request = new Request.Builder().url(url) - .header("Sec-WebSocket-Protocol", "v4.channel.k8s.io").get(); - final OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build(); - clone.newWebSocket(request.build(), podUploadWebSocketListener); + final HttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build(); + CompletableFuture startedFuture = clone.newWebSocketBuilder() + .setHeader("Sec-WebSocket-Protocol", "v4.channel.k8s.io") + .uri(URI.create(url.toString())) + .buildAsync(podUploadWebSocketListener); + startedFuture.whenComplete((w, t) -> { + if (t != null) { + podUploadWebSocketListener.onError(w, t); + } + }); return podUploadWebSocketListener; } private static URL buildCommandUrl(String command, PodOperationContext context, OperationSupport operationSupport) - throws UnsupportedEncodingException, MalformedURLException { + throws MalformedURLException { final StringBuilder commandBuilder = new StringBuilder(); commandBuilder.append("exec?"); diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadWebSocketListener.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadWebSocketListener.java index 558680e453c..d500278a1bb 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadWebSocketListener.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadWebSocketListener.java @@ -16,18 +16,16 @@ package io.fabric8.kubernetes.client.dsl.internal.uploadable; import io.fabric8.kubernetes.client.KubernetesClientException; -import okhttp3.Response; -import okhttp3.WebSocket; -import okhttp3.WebSocketListener; -import okio.ByteString; +import io.fabric8.kubernetes.client.http.WebSocket; import java.io.IOException; -import java.util.Optional; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -public class PodUploadWebSocketListener extends WebSocketListener { +public class PodUploadWebSocketListener implements WebSocket.Listener { private static final byte FLAG_STDIN = (byte) 0; private static final long MAX_QUEUE_SIZE = 16 * 1024 * 1024L; @@ -45,39 +43,28 @@ public class PodUploadWebSocketListener extends WebSocketListener { } @Override - public void onOpen(WebSocket webSocket, Response response) { + public void onOpen(WebSocket webSocket) { webSocketRef.set(webSocket); } @Override - public void onMessage(WebSocket webSocket, ByteString bytes) { - if (readyLatch.getCount() > 0 && bytes.size() == 1) { + public void onMessage(WebSocket webSocket, ByteBuffer bytes) { + if (readyLatch.getCount() > 0 && bytes.remaining() == 1) { readyLatch.countDown(); - } else if (bytes.size() > 1) { - error.set(bytes.substring(1).toString()); + } else if (bytes.remaining() > 1) { + bytes.position(1); + error.set(StandardCharsets.UTF_8.decode(bytes).toString()); } } - + @Override - public void onClosed(WebSocket webSocket, int code, String reason) { + public void onClose(WebSocket webSocket, int code, String reason) { completeLatch.countDown(); } @Override - public void onFailure(WebSocket webSocket, Throwable t, Response response) { - if (response != null) { - final String responseBody = Optional.ofNullable(response.body()) - .map(rb -> { - try { - return rb.string(); - } catch (IOException e) { - return e.getMessage(); - } - }).orElse(""); - error.set(String.format("%s - %s%n%s", response.code(), response.message(), responseBody)); - } else { - error.set("PodUploadWebSocketListener failed with no response"); - } + public void onError(WebSocket webSocket, Throwable t) { + error.set(String.format("PodUploadWebSocketListener failed with - %s", t.getMessage())); while (readyLatch.getCount() > 0) { readyLatch.countDown(); } @@ -104,7 +91,7 @@ final void waitUntilComplete(int timeoutMilliseconds) throws IOException, Interr checkError(); Thread.sleep(50); } - webSocketRef.get().close(1000, "Operation completed"); + webSocketRef.get().sendClose(1000, "Operation completed"); if (!completeLatch.await(timeoutMilliseconds, TimeUnit.MILLISECONDS)) { throw new IOException("Upload operation timed out before completing"); } @@ -117,7 +104,7 @@ final void send(byte[] data, int length) { byte[] toSend = new byte[length + 1]; toSend[0] = FLAG_STDIN; System.arraycopy(data, 0, toSend, 1, length); - webSocketRef.get().send(ByteString.of(toSend)); + webSocketRef.get().send(ByteBuffer.wrap(toSend)); } final void waitForQueue(int length) { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/extended/run/RunOperations.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/extended/run/RunOperations.java index 6ad99244cc2..87987d3a004 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/extended/run/RunOperations.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/extended/run/RunOperations.java @@ -17,19 +17,16 @@ import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodBuilder; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.internal.core.v1.PodOperationsImpl; -import okhttp3.OkHttpClient; public class RunOperations { - private final OkHttpClient client; - private final Config config; + private final ClientContext clientContext; private final String namespace; private final RunConfigBuilder runConfigBuilder; - public RunOperations(OkHttpClient client, Config config, String namespace, RunConfigBuilder runConfigBuilder) { - this.client = client; - this.config = config; + public RunOperations(ClientContext clientContext, String namespace, RunConfigBuilder runConfigBuilder) { + this.clientContext = clientContext; this.namespace = namespace; this.runConfigBuilder = runConfigBuilder; } @@ -41,7 +38,7 @@ public RunOperations(OkHttpClient client, Config config, String namespace, RunCo * @return {@link RunOperations} with injected namespace */ public RunOperations inNamespace(String namespace) { - return new RunOperations(client, config, namespace, runConfigBuilder); + return new RunOperations(clientContext, namespace, runConfigBuilder); } /** @@ -51,7 +48,7 @@ public RunOperations inNamespace(String namespace) { * @return {@link RunOperations} with image injected into {@link RunConfig} */ public RunOperations withImage(String image) { - return new RunOperations(client, config, namespace, runConfigBuilder.withImage(image)); + return new RunOperations(clientContext, namespace, runConfigBuilder.withImage(image)); } /** @@ -61,7 +58,7 @@ public RunOperations withImage(String image) { * @return {@link RunOperations} with name injected into {@link RunConfig} */ public RunOperations withName(String name) { - return new RunOperations(client, config, namespace, runConfigBuilder.withName(name)); + return new RunOperations(clientContext, namespace, runConfigBuilder.withName(name)); } /** @@ -71,7 +68,7 @@ public RunOperations withName(String name) { * @return {@link RunOperations} with specified configuration */ public RunOperations withRunConfig(RunConfig generatorRunConfig) { - return new RunOperations(client, config, namespace, new RunConfigBuilder(generatorRunConfig)); + return new RunOperations(clientContext, namespace, new RunConfigBuilder(generatorRunConfig)); } /** @@ -80,7 +77,7 @@ public RunOperations withRunConfig(RunConfig generatorRunConfig) { * @return Pod which got created from the operation */ public Pod done() { - return new PodOperationsImpl(client, config, namespace).create(convertRunConfigIntoPod()); + return new PodOperationsImpl(clientContext, namespace).create(convertRunConfigIntoPod()); } Pod convertRunConfigIntoPod() { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/BasicBuilder.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/BasicBuilder.java new file mode 100644 index 00000000000..6576b172a48 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/BasicBuilder.java @@ -0,0 +1,41 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.http; + +import java.net.URI; + +public interface BasicBuilder { + + BasicBuilder uri(URI uri); + + /** + * Add the key value pair. Will append to an existing key. + * @param k key + * @param v value + * @return the builder + */ + BasicBuilder header(String k, String v); + + /** + * Set the key value pair. Will overwrite an existing key. + * @param k key + * @param v value + * @return the builder + */ + BasicBuilder setHeader(String k, String v); + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpClient.java new file mode 100644 index 00000000000..4607f9d5bc8 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpClient.java @@ -0,0 +1,100 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.http; + +import io.fabric8.kubernetes.client.Config; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +public interface HttpClient extends AutoCloseable { + + public interface Factory { + + HttpClient createHttpClient(Config config); + + HttpClient.Builder newBuilder(); + + } + + public interface Builder { + + HttpClient build(); + + Builder readTimeout(long readTimeout, TimeUnit unit); + + Builder connectTimeout(long connectTimeout, TimeUnit unit); + + Builder forStreaming(); + + Builder writeTimeout(long timeout, TimeUnit timeoutUnit); + + Builder addOrReplaceInterceptor(String name, Interceptor interceptor); + + Builder authenticatorNone(); + + Builder sslContext(SSLContext context, TrustManager[] trustManagers); + + Builder followAllRedirects(); + + Builder proxyAddress(InetSocketAddress proxyAddress); + + Builder proxyAuthorization(String credentials); + + Builder tlsVersions(TlsVersion[] tlsVersions); + + Builder preferHttp11(); + } + + @Override + void close(); + + /** + * Create a builder that starts with the same state as this client + * @return a new builder + */ + Builder newBuilder(); + + /** + * Send a request an wait for the result + * @param return type + * @param request + * @param type one of InputStream, Reader, String + * @return + * @throws IOException + */ + HttpResponse send(HttpRequest request, Class type) throws IOException; + + /** + * Send an async request + * @param return type + * @param request + * @param type one of InputStream, Reader, String + * @return + */ + CompletableFuture> sendAsync(HttpRequest request, Class type); + + WebSocket.Builder newWebSocketBuilder(); + + HttpRequest.Builder newHttpRequestBuilder(); + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ClientAware.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpHeaders.java similarity index 81% rename from kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ClientAware.java rename to kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpHeaders.java index 9257439b83d..a53e818f7f1 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/ClientAware.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpHeaders.java @@ -14,10 +14,12 @@ * limitations under the License. */ -package io.fabric8.kubernetes.client; +package io.fabric8.kubernetes.client.http; -@Deprecated -public interface ClientAware { +import java.util.List; - C getClient(); +public interface HttpHeaders { + + List headers(String key); + } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpRequest.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpRequest.java new file mode 100644 index 00000000000..4a566bb68e8 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpRequest.java @@ -0,0 +1,100 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.http; + +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.stream.Collectors; + +public interface HttpRequest extends HttpHeaders { + + public interface Builder extends BasicBuilder { + + HttpRequest build(); + + Builder uri(String uri); + + Builder url(URL url); + + @Override + Builder uri(URI uri); + + default Builder put(String contentType, String writeValueAsString) { + return method("PUT", contentType, writeValueAsString); + } + + default Builder post(String contentType, String writeValueAsString) { + return method("POST", contentType, writeValueAsString); + } + + Builder post(String contentType, byte[] writeValueAsBytes); + + Builder post(String contentType, InputStream stream, long length); + + default Builder delete(String contentType, String writeValueAsString) { + return method("DELETE", contentType, writeValueAsString); + } + + default Builder patch(String contentType, String patchForUpdate) { + return method("PATCH", contentType, patchForUpdate); + } + + Builder method(String method, String contentType, String body); + + @Override + Builder header(String k, String v); + + @Override + Builder setHeader(String k, String v); + + default Builder post(Map formData) { + return post("application/x-www-form-urlencoded", + formData.entrySet() + .stream() + .map(e -> formURLEncode(e.getKey()) + "=" + formURLEncode(e.getValue())) + .collect(Collectors.joining("&"))); + } + + Builder expectContinue(); + + } + + static String formURLEncode(String value) { + try { + return URLEncoder.encode(value, StandardCharsets.UTF_8.displayName()); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + URI uri(); + + String method(); + + /** + * Return the body as a string, but only if one of the String valued {@link Builder} methods were used + * otherwise null + * @return the body + */ + String bodyString(); + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpResponse.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpResponse.java new file mode 100644 index 00000000000..ef0b60b242f --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpResponse.java @@ -0,0 +1,75 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.http; + +import io.fabric8.kubernetes.client.utils.IOHelpers; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.util.Optional; + +import static java.nio.charset.StandardCharsets.UTF_8; + +public interface HttpResponse extends HttpHeaders { + + default boolean isSuccessful() { + return isSuccessful(code()); + } + + public static boolean isSuccessful(int code) { + return code >= 200 && code < 300; + } + + int code(); + + default String message() { + return HttpStatusMessage.getMessageForStatus(code()); + } + + /** + * Get the body. If the body is {@link Closeable}, it should be closed by the caller. + * @return the body + */ + T body(); + + /** + * Return the body as a String. Or an empty String if there was no body (possibly discarded). + *
If the body is an {@link InputStream}, it will be read as UTF-8. + * @return the body + * @throws IOException + */ + default String bodyString() throws IOException { + Object body = body(); + if (body == null) { + return ""; + } + if (body instanceof String) { + return (String)body; + } + if (body instanceof Reader) { + return IOHelpers.readFully((Reader)body); + } + return IOHelpers.readFully((InputStream)body, UTF_8); + } + + HttpRequest request(); + + public Optional> previousResponse(); + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpStatusMessage.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpStatusMessage.java new file mode 100644 index 00000000000..e25739c88d2 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/HttpStatusMessage.java @@ -0,0 +1,116 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.http; + +import java.util.HashMap; +import java.util.Map; + +/** + * Adapted from https://stackoverflow.com/questions/67345954/how-do-i-get-the-http-status-message-from-responses-on-java-net-httpclient-reque + */ +public class HttpStatusMessage { + + private static final String UNKNOWN_STATUS = "Unknown Status"; + + private static final Map REASONS = new HashMap<>(); + static { + // informational + entry(100, "Continue"); + entry(101, "Switching Protocol"); + entry(102, "Processing"); + entry(103, "Early Hints"); + + // successful + entry(200, "OK"); + entry(201, "Created"); + entry(202, "Accepted"); + entry(203, "Non-Authoritative Information"); + entry(204, "No Content"); + entry(205, "Reset Content"); + entry(206, "Partial Content"); + entry(207, "Multi Status"); + entry(208, "Already Reported"); + entry(226, "IM Used"); + + // redirection + entry(300, "Multiple Choice"); + entry(301, "Moved Permanently"); + entry(302, "Found"); + entry(303, "See Other"); + entry(304, "Not Modified"); + entry(305, "Use Proxy"); // deprecated + entry(307, "Temporary Redirect"); + entry(308, "Permanent Redirect"); + + // client error + entry(400, "Bad Request"); + entry(401, "Unauthorized"); + entry(402, "Payment Required"); + entry(403, "Forbidden"); + entry(404, "Not Found"); + entry(405, "Method Not Allowed"); + entry(406, "Not Acceptable"); + entry(407, "Proxy Authentication Required"); + entry(408, "Request Timeout"); + entry(409, "Conflict"); + entry(410, "Gone"); + entry(411, "Length Required"); + entry(412, "Precondition Failed"); + entry(413, "Payload Too Long"); + entry(414, "URI Too Long"); + entry(415, "Unsupported Media Type"); + entry(416, "Range Not Satisfiable"); + entry(417, "Expectation Failed"); + entry(418, "I'm a Teapot"); + entry(421, "Misdirected Request"); + entry(422, "Unprocessable Entity"); + entry(423, "Locked"); + entry(424, "Failed Dependency"); + entry(425, "Too Early"); + entry(426, "Upgrade Required"); + entry(428, "Precondition Required"); + entry(429, "Too Many Requests"); + entry(431, "Request Header Fields Too Large"); + entry(451, "Unavailable for Legal Reasons"); + + // server error + entry(500, "Internal Server Error"); + entry(501, "Not Implemented"); + entry(502, "Bad Gateway"); + entry(503, "Service Unavailable"); + entry(504, "Gateway Timeout"); + entry(505, "HTTP Version Not Supported"); + entry(506, "Variant Also Negotiates"); + entry(507, "Insufficient Storage"); + entry(508, "Loop Detected"); + entry(510, "Not Extended"); + entry(511, "Network Authentication Required"); + } + + private static void entry(int i, String string) { + REASONS.put(i, string); + } + + public static String getMessageForStatus(int status) { + return REASONS.getOrDefault(status, UNKNOWN_STATUS); + } + + private HttpStatusMessage() { + // utility + } + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/Interceptor.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/Interceptor.java new file mode 100644 index 00000000000..415dab8c7bc --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/Interceptor.java @@ -0,0 +1,54 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.http; + +import java.util.concurrent.Future; + +/** + * TODO: consider if after should return a {@link Future} rather + * than be blocking + */ +public interface Interceptor { + + /** + * Called before a request to allow for the manipulation of the request + * @param builder used to modify the request + * @param headers the current headers + */ + default void before(BasicBuilder builder, HttpHeaders headers) {} + + /** + * Called after a websocket failure or by default from a normal request + * @param builder used to modify the request + * @param response the failed response + * @return true if the builder should be used to execute a new request + */ + default boolean afterFailure(BasicBuilder builder, HttpResponse response) { + return false; + } + + /** + * Called after a non-websocket failure + * @param builder used to modify the request + * @param response the failed response + * @return true if the builder should be used to execute a new request + */ + default boolean afterFailure(HttpRequest.Builder builder, HttpResponse response) { + return afterFailure((BasicBuilder)builder, response); + } + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/TlsVersion.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/TlsVersion.java new file mode 100644 index 00000000000..6df3309c543 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/TlsVersion.java @@ -0,0 +1,53 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.http; + +/** + * TODO: determine if java names should be used here as well or instead + * + * Replacement for okhttp3.TlsVersion + */ +public enum TlsVersion { + + TLS_1_3("TLSv1.3"), + TLS_1_2("TLSv1.2"), + TLS_1_1("TLSv1.1"), + TLS_1_0("TLSv1"), + SSL_3_0("SSLv3"), + ; + + final String javaName; + + TlsVersion(String javaName) { + this.javaName = javaName; + } + + public static TlsVersion forJavaName(String string) { + if (string.equals("SSLv3")) { + return SSL_3_0; + } + if (string.equals("TLSv1")) { + return TLS_1_0; + } + return TlsVersion.valueOf(string.replaceAll("[v.]", "_")); + } + + public String javaName() { + return javaName; + } + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/WebSocket.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/WebSocket.java new file mode 100644 index 00000000000..2b13292c024 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/WebSocket.java @@ -0,0 +1,72 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.http; + +import java.net.URI; +import java.nio.ByteBuffer; +import java.util.concurrent.CompletableFuture; + +public interface WebSocket { + + public interface Listener { + + default void onOpen(WebSocket webSocket) { } + + default void onMessage(WebSocket webSocket, String text) {} + + default void onMessage(WebSocket webSocket, ByteBuffer bytes) {} + + default void onClose(WebSocket webSocket, int code, String reason) {} + + default void onError(WebSocket webSocket, Throwable error) {} + + } + + public interface Builder extends BasicBuilder { + + CompletableFuture buildAsync(Listener listener); + + @Override + Builder header(String name, String value); + + @Override + Builder setHeader(String k, String v); + + @Override + Builder uri(URI uri); + + } + + /** + * Send some data + * @return true if the message was successfully enqueued. + */ + boolean send(ByteBuffer buffer); + + /** + * Send a close message + * @return true if the message was successfully enqueued. + */ + boolean sendClose(int code, String reason); + + /** + * Returns the size in bytes of all messages enqueued to be transmitted to the server. This + * doesn't include framing overhead. + */ + long queueSize(); + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/WebSocketHandshakeException.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/WebSocketHandshakeException.java new file mode 100644 index 00000000000..e6478f3aa46 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/http/WebSocketHandshakeException.java @@ -0,0 +1,42 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.http; + +import java.io.IOException; + +public final class WebSocketHandshakeException extends IOException { + + private final transient HttpResponse response; + + public WebSocketHandshakeException(HttpResponse response) { + this.response = response; + } + + /** + * Get the response, which includes the code of failure. + * @return the response, never null + */ + public HttpResponse getResponse() { + return response; + } + + @Override + public synchronized WebSocketHandshakeException initCause(Throwable cause) { + return (WebSocketHandshakeException) super.initCause(cause); + } + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/SharedInformerFactory.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/SharedInformerFactory.java index 2cebc155f4c..ca0e3b8f2cb 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/SharedInformerFactory.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/SharedInformerFactory.java @@ -67,7 +67,7 @@ public SharedInformerFactory(BaseKubernetesClient client) { // ideally this should be bounded. The current implication is that there // can be 1 thread used (not dedicated to) per informer - which // could be problematic for a large number of informers. however - // there is already a superceding issue there of thread utilization by okhttp + // if okhttp is in use, it will use two threads per watch this(client, Utils.getCommonExecutorSerive()); this.allowShutdown = false; } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/internal/SSLUtils.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/internal/SSLUtils.java index 06faa0221c9..fa4ffbc2022 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/internal/SSLUtils.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/internal/SSLUtils.java @@ -17,9 +17,25 @@ import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; import io.fabric8.kubernetes.client.utils.HttpClientUtils; +import io.fabric8.kubernetes.client.utils.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509ExtendedTrustManager; + import java.io.IOException; import java.io.InputStream; +import java.net.Socket; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; @@ -29,20 +45,6 @@ import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import static io.fabric8.kubernetes.client.internal.CertUtils.createKeyStore; import static io.fabric8.kubernetes.client.internal.CertUtils.createTrustStore; @@ -61,18 +63,15 @@ public static boolean isHttpsAvailable(Config config) { .withRequestTimeout(1000) .withConnectionTimeout(1000) .build(); - OkHttpClient client = HttpClientUtils.createHttpClient(config); - try { - Request request = new Request.Builder().get().url(sslConfig.getMasterUrl()) + + try (HttpClient client = HttpClientUtils.createHttpClient(config)) { + HttpRequest request = client.newHttpRequestBuilder().uri(sslConfig.getMasterUrl()) .build(); - Response response = client.newCall(request).execute(); - try (ResponseBody body = response.body()) { - return response.isSuccessful(); - } + HttpResponse response = client.send(request, InputStream.class); + response.body().close(); + return response.isSuccessful(); } catch (Throwable t) { LOG.warn("SSL handshake failed. Falling back to insecure connection."); - } finally { - HttpClientUtils.close(client); } return false; } @@ -96,19 +95,45 @@ public static TrustManager[] trustManagers(String certData, String certFile, boo KeyStore trustStore = null; if (isTrustCerts) { return new TrustManager[]{ - new X509TrustManager() { + new X509ExtendedTrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String s) { + //not needed } @Override public void checkServerTrusted(X509Certificate[] chain, String s) { + //not needed } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) + throws CertificateException { + //not needed + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) + throws CertificateException { + //not needed + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) + throws CertificateException { + //not needed + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) + throws CertificateException { + //not needed + } } }; } else if (Utils.isNotNullOrEmpty(certData) || Utils.isNotNullOrEmpty(certFile)) { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpClientBuilderImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpClientBuilderImpl.java new file mode 100644 index 00000000000..212c670bc50 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpClientBuilderImpl.java @@ -0,0 +1,207 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.okhttp; + +import io.fabric8.kubernetes.client.http.HttpClient.Builder; +import io.fabric8.kubernetes.client.okhttp.OkHttpClientImpl.OkHttpResponseImpl; +import io.fabric8.kubernetes.client.http.TlsVersion; +import okhttp3.Authenticator; +import okhttp3.ConnectionSpec; +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.logging.HttpLoggingInterceptor; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static okhttp3.ConnectionSpec.CLEARTEXT; + +class OkHttpClientBuilderImpl implements Builder { + + static final class InteceptorAdapter implements Interceptor { + private final io.fabric8.kubernetes.client.http.Interceptor interceptor; + private final String name; + + private InteceptorAdapter(io.fabric8.kubernetes.client.http.Interceptor interceptor, String name) { + this.interceptor = interceptor; + this.name = name; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request.Builder requestBuilder = chain.request().newBuilder(); + OkHttpRequestImpl.BuilderImpl builderImpl = new OkHttpRequestImpl.BuilderImpl(requestBuilder); + interceptor.before(new OkHttpRequestImpl.BuilderImpl(requestBuilder), new OkHttpRequestImpl(chain.request())); + Response response = chain.proceed(requestBuilder.build()); + if (!response.isSuccessful()) { + boolean call = interceptor.afterFailure(builderImpl, new OkHttpResponseImpl<>(response, InputStream.class)); + if (call) { + return chain.proceed(requestBuilder.build()); + } + } + return response; + } + + public String getName() { + return name; + } + } + + private boolean streaming; + private OkHttpClient.Builder builder; + + public OkHttpClientBuilderImpl(okhttp3.OkHttpClient.Builder newBuilder) { + this.builder = newBuilder; + } + + @Override + public OkHttpClientImpl build() { + OkHttpClient client = builder.build(); + + if (streaming) { + // If we set the HttpLoggingInterceptor's logging level to Body (as it is by default), it does + // not let us stream responses from the server. + for (Interceptor i : client.networkInterceptors()) { + if (i instanceof HttpLoggingInterceptor) { + HttpLoggingInterceptor interceptor = (HttpLoggingInterceptor) i; + interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); + } + } + } + + return new OkHttpClientImpl(client); + } + + @Override + public Builder readTimeout(long readTimeout, TimeUnit unit) { + builder.readTimeout(readTimeout, unit); + return this; + } + + @Override + public Builder connectTimeout(long connectTimeout, TimeUnit unit) { + builder.connectTimeout(connectTimeout, unit); + return this; + } + + @Override + public Builder writeTimeout(long timeout, TimeUnit timeoutUnit) { + builder.writeTimeout(timeout, timeoutUnit); + return this; + } + + @Override + public Builder forStreaming() { + builder.cache(null); + this.streaming = true; + return this; + } + + @Override + public Builder addOrReplaceInterceptor(String name, io.fabric8.kubernetes.client.http.Interceptor interceptor) { + List interceptors = builder.interceptors(); + for (int i = 0; i < interceptors.size(); i++) { + Interceptor exiting = interceptors.get(i); + if (exiting instanceof InteceptorAdapter) { + InteceptorAdapter adapter = (InteceptorAdapter)exiting; + if (adapter.getName().equals(name)) { + if (interceptor == null) { + interceptors.remove(i); + } else { + interceptors.set(i, new InteceptorAdapter(interceptor, name)); + } + return this; + } + } + } + if (interceptor != null) { + builder.addInterceptor(new InteceptorAdapter(interceptor, name)); + } + return this; + } + + @Override + public Builder authenticatorNone() { + builder.authenticator(Authenticator.NONE); + return this; + } + + @Override + public Builder sslContext(SSLContext context, TrustManager[] trustManagers) { + X509TrustManager trustManager = null; + if (trustManagers != null && trustManagers.length == 1) { + trustManager = (X509TrustManager) trustManagers[0]; + } + builder.sslSocketFactory(context.getSocketFactory(), trustManager); + return this; + } + + @Override + public Builder followAllRedirects() { + builder.followRedirects(true).followSslRedirects(true); + return this; + } + + @Override + public Builder proxyAddress(InetSocketAddress proxyAddress) { + if (proxyAddress == null) { + builder.proxy(Proxy.NO_PROXY); + } else { + builder.proxy(new Proxy(Proxy.Type.HTTP, proxyAddress)); + } + return this; + } + + @Override + public Builder proxyAuthorization(String credentials) { + builder.proxyAuthenticator( + (route, response) -> response.request().newBuilder().header("Proxy-Authorization", credentials).build()); + return this; + } + + @Override + public Builder tlsVersions(TlsVersion[] tlsVersions) { + ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) + .tlsVersions(Arrays.asList(tlsVersions) + .stream() + .map(tls -> okhttp3.TlsVersion.valueOf(tls.name())) + .toArray(okhttp3.TlsVersion[]::new)) + .build(); + builder.connectionSpecs(Arrays.asList(spec, CLEARTEXT)); + return this; + } + + @Override + public Builder preferHttp11() { + builder.protocols(Collections.singletonList(Protocol.HTTP_1_1)); + return this; + } + +} \ No newline at end of file diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpClientFactory.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpClientFactory.java new file mode 100644 index 00000000000..bc3a68ff3a5 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpClientFactory.java @@ -0,0 +1,114 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.okhttp; + +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.KubernetesClientException; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpClient.Builder; +import io.fabric8.kubernetes.client.utils.HttpClientUtils; +import okhttp3.Dispatcher; +import okhttp3.OkHttpClient; +import okhttp3.logging.HttpLoggingInterceptor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.TimeUnit; + +public class OkHttpClientFactory implements HttpClient.Factory { + + /** + * Subclasses may use this to apply a base configuration to the builder + */ + protected OkHttpClient.Builder newOkHttpClientBuilder() { + return new OkHttpClient.Builder(); + } + + /** + * Subclasses may use this to apply additional configuration after the Config has been applied + * This method is only called for clients constructed using the Config. + * @param builder + */ + protected void additionalConfig(OkHttpClient.Builder builder) { + + } + + @Override + public Builder newBuilder() { + return new OkHttpClientBuilderImpl(newOkHttpClientBuilder()); + } + + /** + * Creates an HTTP client configured to access the Kubernetes API. + * @param config Kubernetes API client config + * @return returns an HTTP client + */ + @Override + public OkHttpClientImpl createHttpClient(Config config) { + try { + OkHttpClient.Builder httpClientBuilder = newOkHttpClientBuilder(); + + if (config.isTrustCerts() || config.isDisableHostnameVerification()) { + httpClientBuilder.hostnameVerifier((s, sslSession) -> true); + } + + Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class); + if (reqLogger.isTraceEnabled()) { + HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); + httpClientBuilder.addNetworkInterceptor(loggingInterceptor); + } + + if (config.getWebsocketPingInterval() > 0) { + httpClientBuilder.pingInterval(config.getWebsocketPingInterval(), TimeUnit.MILLISECONDS); + } + + if (config.getMaxConcurrentRequests() > 0 && config.getMaxConcurrentRequestsPerHost() > 0) { + Dispatcher dispatcher = new Dispatcher(); + dispatcher.setMaxRequests(config.getMaxConcurrentRequests()); + dispatcher.setMaxRequestsPerHost(config.getMaxConcurrentRequestsPerHost()); + httpClientBuilder.dispatcher(dispatcher); + } + + OkHttpClientBuilderImpl builderWrapper = new OkHttpClientBuilderImpl(httpClientBuilder); + + HttpClientUtils.applyCommonConfiguration(config, builderWrapper, this); + + if (shouldDisableHttp2() && !config.isHttp2Disable()) { + builderWrapper.preferHttp11(); + } + + additionalConfig(httpClientBuilder); + + return builderWrapper.build(); + } catch (Exception e) { + throw KubernetesClientException.launderThrowable(e); + } + } + + /** + * OkHttp wrongfully detects > JDK8u251 as okhttp3.internal.platform.Jdk9Platform which enables Http2 + * unsupported for JDK8. + * + * @return true if JDK8 is detected, false otherwise- + * @see #2212 + */ + protected boolean shouldDisableHttp2() { + return System.getProperty("java.version", "").startsWith("1.8"); + } + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpClientImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpClientImpl.java new file mode 100644 index 00000000000..89e0527e98f --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpClientImpl.java @@ -0,0 +1,184 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.okhttp; + +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Response; +import okhttp3.ResponseBody; + +import java.io.IOException; +import java.io.Reader; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; + +public class OkHttpClientImpl implements HttpClient { + + static final Map MEDIA_TYPES = new ConcurrentHashMap<>(); + + public static final MediaType JSON = parseMediaType("application/json"); + public static final MediaType JSON_PATCH = parseMediaType("application/json-patch+json"); + public static final MediaType STRATEGIC_MERGE_JSON_PATCH = parseMediaType("application/strategic-merge-patch+json"); + public static final MediaType JSON_MERGE_PATCH = parseMediaType("application/merge-patch+json"); + + static MediaType parseMediaType(String contentType) { + MediaType result = MediaType.parse(contentType); + MEDIA_TYPES.put(contentType, result); + return result; + } + + static class OkHttpResponseImpl implements HttpResponse { + + private final Response response; + private T body; + private Class type; + + public OkHttpResponseImpl(Response response, Class type) throws IOException { + this.response = response; + this.type = type; + ResponseBody responseBody = response.body(); + if (responseBody != null) { + if (type == null) { + responseBody.close(); + } else if (type == String.class) { + body = (T) responseBody.string(); + } else if (type == Reader.class) { + body = (T) responseBody.charStream(); + } else { + body = (T) responseBody.byteStream(); + } + } + } + + @Override + public int code() { + return response.code(); + } + + @Override + public T body() { + return body; + } + + @Override + public HttpRequest request() { + return new OkHttpRequestImpl(response.request()); + } + + @Override + public Optional> previousResponse() { + Response previous = response.priorResponse() != null ? response.priorResponse() : response; + previous = previous.networkResponse() != null ? previous.networkResponse() : previous; + try { + return Optional.ofNullable(previous == response ? null : new OkHttpResponseImpl<>(previous, type)); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + @Override + public List headers(String key) { + return response.headers(key); + } + + } + + private final okhttp3.OkHttpClient httpClient; + + public OkHttpClientImpl(OkHttpClient httpClient) { + this.httpClient = httpClient; + } + + @Override + public void close() { + ConnectionPool connectionPool = httpClient.connectionPool(); + Dispatcher dispatcher = httpClient.dispatcher(); + ExecutorService executorService = httpClient.dispatcher() != null ? httpClient.dispatcher().executorService() : null; + + if (dispatcher != null) { + dispatcher.cancelAll(); + } + + if (connectionPool != null) { + connectionPool.evictAll(); + } + + if (executorService != null) { + executorService.shutdownNow(); + } + } + + @Override + public HttpResponse send(HttpRequest request, Class type) throws IOException { + return new OkHttpResponseImpl<>(httpClient.newCall(((OkHttpRequestImpl)request).getRequest()).execute(), type); + } + + @Override + public Builder newBuilder() { + return new OkHttpClientBuilderImpl(httpClient.newBuilder()); + } + + @Override + public CompletableFuture> sendAsync(HttpRequest request, Class type) { + CompletableFuture> future = new CompletableFuture<>(); + Call call = httpClient.newCall(((OkHttpRequestImpl)request).getRequest()); + call.enqueue(new Callback() { + + @Override + public void onResponse(Call call, Response response) throws IOException { + future.complete(new OkHttpResponseImpl<>(response, type)); + } + + @Override + public void onFailure(Call call, IOException e) { + future.completeExceptionally(e); + } + }); + future.whenComplete((r, t) -> { + if (future.isCancelled()) { + call.cancel(); + } + }); + return future; + } + + @Override + public io.fabric8.kubernetes.client.http.WebSocket.Builder newWebSocketBuilder() { + return new OkHttpWebSocketImpl.BuilderImpl(this.httpClient); + } + + public okhttp3.OkHttpClient getOkHttpClient() { + return httpClient; + } + + @Override + public HttpRequest.Builder newHttpRequestBuilder() { + return new OkHttpRequestImpl.BuilderImpl(); + } + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpRequestImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpRequestImpl.java new file mode 100644 index 00000000000..cf4aa7ea7a1 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpRequestImpl.java @@ -0,0 +1,173 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.okhttp; + +import io.fabric8.kubernetes.client.http.HttpRequest; +import okhttp3.MediaType; +import okhttp3.Request; +import okhttp3.RequestBody; +import okio.Buffer; +import okio.BufferedSink; +import okio.Okio; +import okio.Source; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.util.List; + +class OkHttpRequestImpl implements HttpRequest { + + static class BuilderImpl implements Builder { + + private Request.Builder builder; + + public BuilderImpl() { + this(new Request.Builder()); + } + + public BuilderImpl(Request.Builder builder) { + this.builder = builder; + } + + @Override + public HttpRequest build() { + return new OkHttpRequestImpl(builder.build()); + } + + @Override + public Builder uri(String uri) { + builder.url(uri); + return this; + } + + @Override + public Builder url(URL resourceUrl) { + builder.url(resourceUrl); + return this; + } + + @Override + public Builder method(String method, String contentType, String body) { + builder.method(method, RequestBody.create(OkHttpClientImpl.parseMediaType(contentType), body)); + return this; + } + + @Override + public Builder post(String contentType, byte[] writeValueAsBytes) { + builder.post(RequestBody.create(OkHttpClientImpl.parseMediaType(contentType), writeValueAsBytes)); + return this; + } + + @Override + public Builder post(String contentType, InputStream inputStream, long length) { + builder.post(new RequestBody() { + + @Override + public void writeTo(BufferedSink sink) throws IOException { + try (final BufferedInputStream bis = new BufferedInputStream(inputStream); + final Source source = Okio.source(bis)) { + sink.writeAll(source); + } + } + + @Override + public MediaType contentType() { + return OkHttpClientImpl.parseMediaType(contentType); + } + + @Override + public long contentLength() throws IOException { + return length; + } + }); + return this; + } + + @Override + public Builder header(String k, String v) { + builder.addHeader(k, v); + return this; + } + + @Override + public Builder setHeader(String k, String v) { + builder.header(k, v); + return this; + } + + @Override + public Builder uri(URI uri) { + try { + builder.url(uri.toURL()); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(uri.toString(), e); + } + return this; + } + + @Override + public Builder expectContinue() { + builder.header("Expect", "100-continue"); + return this; + } + + } + + private Request request; + + public OkHttpRequestImpl(Request request) { + this.request = request; + } + + @Override + public URI uri() { + return request.url().uri(); + } + + @Override + public String method() { + return request.method(); + } + + public Request getRequest() { + return request; + } + + @Override + public List headers(String key) { + return request.headers(key); + } + + @Override + public String bodyString() { + if (request.body() == null) { + return null; + } + Buffer buffer = new Buffer(); + try { + request.body().writeTo(buffer); + } catch (IOException e) { + return null; + } + return buffer.readUtf8(); + } + +} diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpWebSocketImpl.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpWebSocketImpl.java new file mode 100644 index 00000000000..ea2de572c18 --- /dev/null +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpWebSocketImpl.java @@ -0,0 +1,139 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.okhttp; + +import io.fabric8.kubernetes.client.http.WebSocket; +import io.fabric8.kubernetes.client.http.WebSocketHandshakeException; +import io.fabric8.kubernetes.client.okhttp.OkHttpClientImpl.OkHttpResponseImpl; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.WebSocketListener; +import okio.ByteString; + +import java.io.IOException; +import java.net.URI; +import java.nio.ByteBuffer; +import java.util.concurrent.CompletableFuture; + +class OkHttpWebSocketImpl implements WebSocket { + + static class BuilderImpl implements WebSocket.Builder { + + private Request.Builder builder = new Request.Builder(); + private OkHttpClient httpClient; + + public BuilderImpl(OkHttpClient httpClient) { + this.httpClient = httpClient; + } + + @Override + public Builder uri(URI uri) { + builder.url(HttpUrl.get(uri)); + return this; + } + + @Override + public CompletableFuture buildAsync(Listener listener) { + Request request = builder.build(); + CompletableFuture future = new CompletableFuture<>(); + httpClient.newWebSocket(request, new WebSocketListener() { + private volatile boolean opened; + + @Override + public void onFailure(okhttp3.WebSocket webSocket, Throwable t, Response response) { + if (response != null) { + response.close(); + } + if (!opened && response != null) { + try { + future.completeExceptionally(new WebSocketHandshakeException(new OkHttpResponseImpl<>(response, null)).initCause(t)); + } catch (IOException e) { + // can't happen + } + } else { + listener.onError(new OkHttpWebSocketImpl(webSocket), t); + } + } + + @Override + public void onOpen(okhttp3.WebSocket webSocket, Response response) { + opened = true; + if (response != null) { + response.close(); + } + OkHttpWebSocketImpl value = new OkHttpWebSocketImpl(webSocket); + future.complete(value); + listener.onOpen(value); + } + + @Override + public void onMessage(okhttp3.WebSocket webSocket, ByteString bytes) { + listener.onMessage(new OkHttpWebSocketImpl(webSocket), bytes.asByteBuffer()); + } + + @Override + public void onMessage(okhttp3.WebSocket webSocket, String text) { + listener.onMessage(new OkHttpWebSocketImpl(webSocket), text); + } + + @Override + public void onClosing(okhttp3.WebSocket webSocket, int code, String reason) { + listener.onClose(new OkHttpWebSocketImpl(webSocket), code, reason); + } + + }); + return future; + } + + @Override + public WebSocket.Builder header(String name, String value) { + builder = builder.addHeader(name, value); + return this; + } + + @Override + public WebSocket.Builder setHeader(String k, String v) { + builder = builder.header(k, v); + return this; + } + + } + + private okhttp3.WebSocket webSocket; + + public OkHttpWebSocketImpl(okhttp3.WebSocket webSocket) { + this.webSocket = webSocket; + } + + @Override + public boolean send(ByteBuffer buffer) { + return webSocket.send(ByteString.of(buffer)); + } + + @Override + public boolean sendClose(int code, String reason) { + return webSocket.close(code, reason); + } + + @Override + public long queueSize() { + return webSocket.queueSize(); + } + +} \ No newline at end of file diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/osgi/ManagedKubernetesClient.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/osgi/ManagedKubernetesClient.java index 770dbe2a28e..4cffb6be9e5 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/osgi/ManagedKubernetesClient.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/osgi/ManagedKubernetesClient.java @@ -585,7 +585,7 @@ public FunctionCallable withRequestConfig(RequestCon @Override public RunOperations run() { - return new RunOperations(httpClient, getConfiguration(), getNamespace(), new RunConfigBuilder()); + return new RunOperations(this, getNamespace(), new RunConfigBuilder()); } @Override diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/BackwardsCompatibilityInterceptor.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/BackwardsCompatibilityInterceptor.java index 887ead0a330..be4dbc10b32 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/BackwardsCompatibilityInterceptor.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/BackwardsCompatibilityInterceptor.java @@ -17,14 +17,14 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.client.dsl.base.OperationSupport; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okio.Buffer; +import io.fabric8.kubernetes.client.http.BasicBuilder; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.http.Interceptor; +import io.fabric8.kubernetes.client.http.HttpRequest.Builder; -import java.io.IOException; import java.net.HttpURLConnection; +import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -32,6 +32,8 @@ import java.util.regex.Matcher; public class BackwardsCompatibilityInterceptor implements Interceptor { + + public static final String NAME = "BACKWARDS"; private static final int API_GROUP = 1; private static final int API_VERSION = 2; @@ -127,28 +129,63 @@ public int hashCode() { openshiftOAPITransformations.put("imagestreamtags", new ResourceKey("ImageStream", "imagestreamtags", "image.openshift.io", "v1")); openshiftOAPITransformations.put("securitycontextconstraints", new ResourceKey("SecurityContextConstraints", "securitycontextconstraints", "security.openshift.io", "v1")); } + + @Override + public boolean afterFailure(Builder builder, HttpResponse response) { + ResourceKey target = findNewTarget(builder, response); + if (target == null) { + return false; + } + + HttpRequest request = response.request(); + if (request.bodyString() != null && !request.method().equalsIgnoreCase(PATCH)) { + Object object = Serialization.unmarshal(request.bodyString()); + if (object instanceof HasMetadata) { + HasMetadata h = (HasMetadata) object; + h.setApiVersion(target.group + "/" + target.version); + switch (request.method()) { + case "POST": + builder.post(OperationSupport.JSON, Serialization.asJson(h)); + break; + case "PUT": + builder.put(OperationSupport.JSON, Serialization.asJson(h)); + break; + case "DELETE": + builder.delete(OperationSupport.JSON, Serialization.asJson(h)); + break; + default: + return false; + } + } + } - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - Response response = chain.proceed(request); + return true; + } + + public ResourceKey findNewTarget(BasicBuilder basicBuilder, HttpResponse response) { + HttpRequest request = response.request(); if (isDeprecatedOpenshiftOapiRequest(request)) { - return handleOpenshiftOapiRequests(request, response, chain); + return handleOpenshiftOapiRequests(basicBuilder, request, response); } else if (!response.isSuccessful() && responseCodeToTransformations.keySet().contains(response.code())) { - String url = request.url().toString(); + String url = request.uri().toString(); Matcher matcher = getMatcher(url); ResourceKey key = getKey(matcher); ResourceKey target = responseCodeToTransformations.get(response.code()).get(key); if (target != null) { - response.close(); // At this point, we know we won't reuse or return the response; so close it to avoid a connection leak. String newUrl = new StringBuilder(url) .replace(matcher.start(API_VERSION), matcher.end(API_VERSION), target.version) // Order matters: We need to substitute right to left, so that former substitution don't affect the indexes of later. .replace(matcher.start(API_GROUP), matcher.end(API_GROUP), target.group) .toString(); - - return handleNewRequestAndProceed(request, newUrl, target, chain); + basicBuilder.uri(URI.create(newUrl)); + return target; } } - return response; + return null; + } + + @Override + public boolean afterFailure(BasicBuilder basicBuilder, HttpResponse response) { + return findNewTarget(basicBuilder, response) != null; } private static Matcher getMatcher(String url) { @@ -168,47 +205,23 @@ private static ResourceKey getKey(Matcher m) { return m != null ? new ResourceKey(null, m.group(PATH), m.group(API_GROUP), m.group(API_VERSION)) : null; } - private static Response handleOpenshiftOapiRequests(Request request, Response response, Chain chain) throws IOException{ + private static ResourceKey handleOpenshiftOapiRequests(BasicBuilder builder, HttpRequest request, HttpResponse response) { if (!response.isSuccessful() && response.code() == HttpURLConnection.HTTP_NOT_FOUND) { - String requestUrl = request.url().toString(); + String requestUrl = request.uri().toString(); // handle case when /oapi is not available String[] parts = requestUrl.split("/"); String resourcePath = parts[parts.length - 1]; ResourceKey target = openshiftOAPITransformations.get(resourcePath); if (target != null) { requestUrl = requestUrl.replace("/oapi", "/apis/" + target.getGroup()); - return handleNewRequestAndProceed(request, requestUrl, target, chain); + builder.uri(URI.create(requestUrl)); + return target; } } - return response; - } - - private static Response handleNewRequestAndProceed(Request request, String newUrl, ResourceKey target, Chain chain) throws IOException { - Request.Builder newRequest = request.newBuilder() - .url(newUrl); - - if (request.body() != null && !request.method().equalsIgnoreCase(PATCH)) { - try (Buffer buffer = new Buffer()) { - request.body().writeTo(buffer); - - Object object = Serialization.unmarshal(buffer.inputStream()); - if (object instanceof HasMetadata) { - HasMetadata h = (HasMetadata) object; - if (target != null) { - h.setApiVersion(target.group + "/" + target.version); - } - newRequest = newRequest.method(request.method(), RequestBody.create(OperationSupport.JSON, Serialization.asJson(h))); - } - } - } - - return chain.proceed(newRequest.build()); + return null; } - private static boolean isDeprecatedOpenshiftOapiRequest(Request request) { - if (request != null && request.url() != null) { - return request.url().toString().contains("oapi"); - } - return false; + private static boolean isDeprecatedOpenshiftOapiRequest(HttpRequest request) { + return request.uri().toString().contains("oapi"); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/HttpClientUtils.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/HttpClientUtils.java index 6d9b8aa5557..3cc0020f57e 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/HttpClientUtils.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/HttpClientUtils.java @@ -15,40 +15,40 @@ */ package io.fabric8.kubernetes.client.utils; -import io.fabric8.kubernetes.api.model.ListOptions; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.KubernetesClientException; +import io.fabric8.kubernetes.client.http.BasicBuilder; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpHeaders; +import io.fabric8.kubernetes.client.http.Interceptor; import io.fabric8.kubernetes.client.internal.SSLUtils; -import okhttp3.*; -import okhttp3.logging.HttpLoggingInterceptor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import io.fabric8.kubernetes.client.okhttp.OkHttpClientFactory; +import io.fabric8.kubernetes.client.okhttp.OkHttpClientImpl; +import okhttp3.OkHttpClient; +import okhttp3.OkHttpClient.Builder; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; + import java.net.InetSocketAddress; import java.net.MalformedURLException; -import java.net.Proxy; import java.net.URL; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; -import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; -import static okhttp3.ConnectionSpec.CLEARTEXT; - public class HttpClientUtils { + + public static final String HEADER_INTERCEPTOR = "HEADER"; + private HttpClientUtils() { } private static Pattern VALID_IPV4_PATTERN = null; @@ -63,198 +63,26 @@ private HttpClientUtils() { } } } - public static void close(OkHttpClient httpClient) { - ConnectionPool connectionPool = httpClient.connectionPool(); - Dispatcher dispatcher = httpClient.dispatcher(); - ExecutorService executorService = httpClient.dispatcher() != null ? httpClient.dispatcher().executorService() : null; - - if (dispatcher != null) { - dispatcher.cancelAll(); - } - - if (connectionPool != null) { - connectionPool.evictAll(); - } - - if (executorService != null) { - executorService.shutdownNow(); - } - } - - public static OkHttpClient createHttpClient(final Config config) { - return createHttpClient(config, (b) -> {}); - } - - public static OkHttpClient createHttpClientForMockServer(final Config config) { - return createHttpClient(config, b -> b.protocols(Collections.singletonList(Protocol.HTTP_1_1))); - } - - public static HttpUrl.Builder appendListOptionParams(HttpUrl.Builder urlBuilder, ListOptions listOptions) { - if (listOptions == null) { - return urlBuilder; - } - if (listOptions.getLimit() != null) { - urlBuilder.addQueryParameter("limit", listOptions.getLimit().toString()); - } - if (listOptions.getContinue() != null) { - urlBuilder.addQueryParameter("continue", listOptions.getContinue()); - } - - if (listOptions.getFieldSelector() != null) { - urlBuilder.addQueryParameter("fieldSelector", listOptions.getFieldSelector()); - } - - if (listOptions.getLabelSelector() != null) { - urlBuilder.addQueryParameter("labelSelector", listOptions.getLabelSelector()); - } - - if (listOptions.getResourceVersion() != null) { - urlBuilder.addQueryParameter("resourceVersion", listOptions.getResourceVersion()); - } - - if (listOptions.getTimeoutSeconds() != null) { - urlBuilder.addQueryParameter("timeoutSeconds", listOptions.getTimeoutSeconds().toString()); - } - - if (listOptions.getAllowWatchBookmarks() != null) { - urlBuilder.addQueryParameter("allowWatchBookmarks", listOptions.getAllowWatchBookmarks().toString()); - } - - if (listOptions.getWatch() != null) { - urlBuilder.addQueryParameter("watch", listOptions.getWatch().toString()); - } - return urlBuilder; - } - /** * Creates an HTTP client configured to access the Kubernetes API. * @param config Kubernetes API client config * @param additionalConfig a consumer that allows overriding HTTP client properties * @return returns an HTTP client + * @deprecated subclass {@link OkHttpClientFactory} and implement the additionalConfig method */ - public static OkHttpClient createHttpClient(final Config config, final Consumer additionalConfig) { - try { - OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); - - // Follow any redirects - httpClientBuilder.followRedirects(true); - httpClientBuilder.followSslRedirects(true); - - if (config.isTrustCerts() || config.isDisableHostnameVerification()) { - httpClientBuilder.hostnameVerifier((s, sslSession) -> true); - } - - TrustManager[] trustManagers = SSLUtils.trustManagers(config); - KeyManager[] keyManagers = SSLUtils.keyManagers(config); - - if (keyManagers != null || trustManagers != null || config.isTrustCerts()) { - X509TrustManager trustManager = null; - if (trustManagers != null && trustManagers.length == 1) { - trustManager = (X509TrustManager) trustManagers[0]; - } - - try { - SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers); - httpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), trustManager); - } catch (GeneralSecurityException e) { - throw new AssertionError(); // The system has no TLS. Just give up. - } - } else { - SSLContext context = SSLContext.getInstance("TLSv1.2"); - context.init(keyManagers, trustManagers, null); - httpClientBuilder.sslSocketFactory(context.getSocketFactory(), (X509TrustManager) trustManagers[0]); - } - - List interceptors = createApplicableInterceptors(config); - interceptors.forEach(httpClientBuilder::addInterceptor); - Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class); - if (reqLogger.isTraceEnabled()) { - HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); - httpClientBuilder.addNetworkInterceptor(loggingInterceptor); - } - - if (config.getConnectionTimeout() > 0) { - httpClientBuilder.connectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS); - } - - if (config.getRequestTimeout() > 0) { - httpClientBuilder.readTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS); - } - - if (config.getWebsocketPingInterval() > 0) { - httpClientBuilder.pingInterval(config.getWebsocketPingInterval(), TimeUnit.MILLISECONDS); - } - - if (config.getMaxConcurrentRequests() > 0 && config.getMaxConcurrentRequestsPerHost() > 0) { - Dispatcher dispatcher = new Dispatcher(); - dispatcher.setMaxRequests(config.getMaxConcurrentRequests()); - dispatcher.setMaxRequestsPerHost(config.getMaxConcurrentRequestsPerHost()); - httpClientBuilder.dispatcher(dispatcher); - } - - // Only check proxy if it's a full URL with protocol - if (config.getMasterUrl().toLowerCase(Locale.ROOT).startsWith(Config.HTTP_PROTOCOL_PREFIX) || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) { - try { - URL proxyUrl = getProxyUrl(config); - if (proxyUrl != null) { - httpClientBuilder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort()))); - - if (config.getProxyUsername() != null) { - httpClientBuilder.proxyAuthenticator((route, response) -> { - - String credential = Credentials.basic(config.getProxyUsername(), config.getProxyPassword()); - return response.request().newBuilder().header("Proxy-Authorization", credential).build(); - }); - } - } else { - httpClientBuilder.proxy(Proxy.NO_PROXY); - } - - } catch (MalformedURLException e) { - throw new KubernetesClientException("Invalid proxy server configuration", e); - } - } - - if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) { - httpClientBuilder.addNetworkInterceptor(chain -> { - Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent()).build(); - return chain.proceed(agent); - }); - } - - if (config.getTlsVersions() != null && config.getTlsVersions().length > 0) { - ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) - .tlsVersions(config.getTlsVersions()) - .build(); - httpClientBuilder.connectionSpecs(Arrays.asList(spec, CLEARTEXT)); - } - - if (shouldDisableHttp2() || config.isHttp2Disable()) { - httpClientBuilder.protocols(Collections.singletonList(Protocol.HTTP_1_1)); - } - - if(additionalConfig != null) { - additionalConfig.accept(httpClientBuilder); - } - - if (config.getCustomHeaders() != null && !config.getCustomHeaders().isEmpty()) { - httpClientBuilder.addNetworkInterceptor(chain -> { - Request.Builder agent = chain.request().newBuilder(); - for (Map.Entry entry : config.getCustomHeaders().entrySet()) { - agent.addHeader(entry.getKey(),entry.getValue()); - } - return chain.proceed(agent.build()); - }); - } - - return httpClientBuilder.build(); - } catch (Exception e) { - throw KubernetesClientException.launderThrowable(e); + @Deprecated + public static OkHttpClientImpl createHttpClient(final Config config, final Consumer additionalConfig) { + return new OkHttpClientFactory() { + @Override + protected void additionalConfig(Builder builder) { + if (additionalConfig != null) { + additionalConfig.accept(builder); } - } + } + }.createHttpClient(config); + } - private static URL getProxyUrl(Config config) throws MalformedURLException { + public static URL getProxyUrl(Config config) throws MalformedURLException { URL master = new URL(config.getMasterUrl()); String host = master.getHost(); if (config.getNoProxy() != null) { @@ -285,41 +113,103 @@ private static boolean isIpAddress(String ipAddress) { return ipMatcher.matches(); } - /** - * OkHttp wrongfully detects >JDK8u251 as {@link okhttp3.internal.platform.Jdk9Platform} which enables Http2 - * unsupported for JDK8. - * - * @return true if JDK8 is detected, false otherwise- - * @see #2212 - */ - private static boolean shouldDisableHttp2() { - return System.getProperty("java.version", "").startsWith("1.8"); - } - - static List createApplicableInterceptors(Config config) { - List interceptors = new ArrayList<>(); + public static Map createApplicableInterceptors(Config config, HttpClient.Factory factory) { + Map interceptors = new LinkedHashMap<>(); + // Header Interceptor - interceptors.add(chain -> { - Request request = chain.request(); - if (Utils.isNotNullOrEmpty(config.getUsername()) && Utils.isNotNullOrEmpty(config.getPassword())) { - Request authReq = chain.request().newBuilder().addHeader("Authorization", Credentials.basic(config.getUsername(), config.getPassword())).build(); - return chain.proceed(authReq); - } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) { - Request authReq = chain.request().newBuilder().addHeader("Authorization", "Bearer " + config.getOauthToken()).build(); - return chain.proceed(authReq); + interceptors.put(HEADER_INTERCEPTOR, new Interceptor() { + + @Override + public void before(BasicBuilder builder, HttpHeaders headers) { + if (Utils.isNotNullOrEmpty(config.getUsername()) && Utils.isNotNullOrEmpty(config.getPassword())) { + builder.header("Authorization", basicCredentials(config.getUsername(), config.getPassword())); + } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) { + builder.header("Authorization", "Bearer " + config.getOauthToken()); + } + if (config.getCustomHeaders() != null && !config.getCustomHeaders().isEmpty()) { + for (Map.Entry entry : config.getCustomHeaders().entrySet()) { + builder.header(entry.getKey(),entry.getValue()); + } + } + if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) { + builder.setHeader("User-Agent", config.getUserAgent()); + } } - return chain.proceed(request); }); // Impersonator Interceptor - interceptors.add(new ImpersonatorInterceptor(config)); + interceptors.put(ImpersonatorInterceptor.NAME, new ImpersonatorInterceptor(config)); // Token Refresh Interceptor - interceptors.add(new TokenRefreshInterceptor(config)); + interceptors.put(TokenRefreshInterceptor.NAME, new TokenRefreshInterceptor(config, factory)); // Backwards Compatibility Interceptor String shouldDisableBackwardsCompatibilityInterceptor = Utils.getSystemPropertyOrEnvVar(KUBERNETES_BACKWARDS_COMPATIBILITY_INTERCEPTOR_DISABLE, "false"); if (!Boolean.parseBoolean(shouldDisableBackwardsCompatibilityInterceptor)) { - interceptors.add(new BackwardsCompatibilityInterceptor()); + interceptors.put(BackwardsCompatibilityInterceptor.NAME, new BackwardsCompatibilityInterceptor()); } return interceptors; } + + public static String basicCredentials(String username, String password) { + String usernameAndPassword = username + ":" + password; + String encoded = Base64.getEncoder().encodeToString(usernameAndPassword.getBytes(StandardCharsets.ISO_8859_1)); + return "Basic " + encoded; + } + + public static HttpClient createHttpClient(Config config) { + // TODO: replace with reflection / service load and factory interface + return new OkHttpClientFactory().createHttpClient(config); + } + + public static void applyCommonConfiguration(Config config, HttpClient.Builder builder, HttpClient.Factory factory) { + builder.followAllRedirects(); + + if (config.getConnectionTimeout() > 0) { + builder.connectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS); + } + + if (config.getRequestTimeout() > 0) { + builder.readTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS); + } + + if (config.isHttp2Disable()) { + builder.preferHttp11(); + } + + try { + + // Only check proxy if it's a full URL with protocol + if (config.getMasterUrl().toLowerCase(Locale.ROOT).startsWith(Config.HTTP_PROTOCOL_PREFIX) + || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) { + try { + URL proxyUrl = HttpClientUtils.getProxyUrl(config); + if (proxyUrl != null) { + builder.proxyAddress(new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())); + + if (config.getProxyUsername() != null) { + builder.proxyAuthorization(basicCredentials(config.getProxyUsername(), config.getProxyPassword())); + } + } else { + builder.proxyAddress(null); + } + } catch (MalformedURLException e) { + throw new KubernetesClientException("Invalid proxy server configuration", e); + } + } + + TrustManager[] trustManagers = SSLUtils.trustManagers(config); + KeyManager[] keyManagers = SSLUtils.keyManagers(config); + + SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers); + builder.sslContext(sslContext, trustManagers); + + if (config.getTlsVersions() != null && config.getTlsVersions().length > 0) { + builder.tlsVersions(config.getTlsVersions()); + } + + } catch (Exception e) { + KubernetesClientException.launderThrowable(e); + } + HttpClientUtils.createApplicableInterceptors(config, factory).forEach(builder::addOrReplaceInterceptor); + } + } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/IOHelpers.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/IOHelpers.java index ffd3df258cb..39a81bb5158 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/IOHelpers.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/IOHelpers.java @@ -25,6 +25,7 @@ import java.io.Reader; import java.io.StringWriter; import java.io.Writer; +import java.nio.charset.Charset; /** */ @@ -32,9 +33,14 @@ public class IOHelpers { private IOHelpers() { throw new IllegalStateException("Utility class"); } + + public static String readFully(InputStream in, Charset charset) throws IOException { + Reader r = new BufferedReader(new InputStreamReader(in, charset)); + return readFully(r); + } + public static String readFully(InputStream in) throws IOException { - Reader r = new BufferedReader(new InputStreamReader(in)); - return readFully(r); + return readFully(in, Charset.defaultCharset()); } public static String readFully(Reader r) throws IOException { diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/ImpersonatorInterceptor.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/ImpersonatorInterceptor.java index 7116c4d4c94..d51390d16ac 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/ImpersonatorInterceptor.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/ImpersonatorInterceptor.java @@ -17,11 +17,10 @@ import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.RequestConfig; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; +import io.fabric8.kubernetes.client.http.BasicBuilder; +import io.fabric8.kubernetes.client.http.HttpHeaders; +import io.fabric8.kubernetes.client.http.Interceptor; -import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; @@ -29,24 +28,25 @@ import static io.fabric8.kubernetes.client.utils.Utils.isNotNullOrEmpty; public class ImpersonatorInterceptor implements Interceptor { + + public static final String NAME = "IMPERSONATOR"; + private final Config config; public ImpersonatorInterceptor(Config config) { this.config = config; } - + @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); + public void before(BasicBuilder builder, HttpHeaders headers) { RequestConfig requestConfig = config.getRequestConfig(); if (isNotNullOrEmpty(requestConfig.getImpersonateUsername())) { - Request.Builder requestBuilder = chain.request().newBuilder(); - requestBuilder.addHeader("Impersonate-User", requestConfig.getImpersonateUsername()); + builder.header("Impersonate-User", requestConfig.getImpersonateUsername()); String[] impersonateGroups = requestConfig.getImpersonateGroups(); if (isNotNullOrEmpty(impersonateGroups)) { for (String group : impersonateGroups) { - requestBuilder.addHeader("Impersonate-Group", group); + builder.header("Impersonate-Group", group); } } @@ -57,14 +57,11 @@ public Response intercept(Chain chain) throws IOException { List values = impersonateExtras.get(key); if(values != null) { for (String value : values) { - requestBuilder.addHeader("Impersonate-Extra-" + key, value); + builder.header("Impersonate-Extra-" + key, value); } } } } - - request = requestBuilder.build(); } - return chain.proceed(request); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtils.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtils.java index 429922625f5..fa3caf37698 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtils.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtils.java @@ -17,25 +17,20 @@ import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.kubernetes.api.model.NamedContext; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; import io.fabric8.kubernetes.client.internal.KubeConfigUtils; import io.fabric8.kubernetes.client.internal.SSLUtils; -import okhttp3.FormBody; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; + import java.io.File; import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.KeyStoreException; @@ -44,6 +39,7 @@ import java.security.cert.CertificateException; import java.security.spec.InvalidKeySpecException; import java.util.Collections; +import java.util.LinkedHashMap; import java.util.Map; /** @@ -78,7 +74,7 @@ private OpenIDConnectionUtils() { } * @param currentAuthProviderConfig current AuthInfo's AuthProvider config as a map * @return access token for interacting with Kubernetes API */ - public static String resolveOIDCTokenFromAuthConfig(Map currentAuthProviderConfig) { + public static String resolveOIDCTokenFromAuthConfig(Map currentAuthProviderConfig, HttpClient.Builder clientBuilder) { String accessToken = currentAuthProviderConfig.get(ID_TOKEN_KUBECONFIG); String issuer = currentAuthProviderConfig.get(ISSUER_KUBECONFIG); String clientId = currentAuthProviderConfig.get(CLIENT_ID_KUBECONFIG); @@ -86,7 +82,7 @@ public static String resolveOIDCTokenFromAuthConfig(Map currentA String clientSecret = currentAuthProviderConfig.getOrDefault(CLIENT_SECRET_KUBECONFIG, ""); String idpCert = currentAuthProviderConfig.get(IDP_CERT_DATA); if (isTokenRefreshSupported(currentAuthProviderConfig)) { - return getOIDCProviderTokenEndpointAndRefreshToken(issuer, clientId, refreshToken, clientSecret, accessToken, idpCert); + return getOIDCProviderTokenEndpointAndRefreshToken(issuer, clientId, refreshToken, clientSecret, accessToken, idpCert, clientBuilder); } return accessToken; } @@ -94,7 +90,7 @@ public static String resolveOIDCTokenFromAuthConfig(Map currentA /** * Get OIDC Provider discovery token_endpoint and issue refresh request * - * @param client OkHttp Client + * @param client Http Client * @param wellKnownOpenIdConfiguration OIDC Provider Discovery Document * @param clientId client id as string * @param refreshToken refresh token @@ -103,7 +99,7 @@ public static String resolveOIDCTokenFromAuthConfig(Map currentA * @param shouldPersistUpdatedTokenInKubeConfig boolean value whether to modify kubeconfig file in disc or not * @return returns access token(either updated or old) depending upon response from provider */ - static String getOIDCProviderTokenEndpointAndRefreshToken(OkHttpClient client, Map wellKnownOpenIdConfiguration, String clientId, String refreshToken, String clientSecret, String accessToken, boolean shouldPersistUpdatedTokenInKubeConfig) { + static String getOIDCProviderTokenEndpointAndRefreshToken(HttpClient client, Map wellKnownOpenIdConfiguration, String clientId, String refreshToken, String clientSecret, String accessToken, boolean shouldPersistUpdatedTokenInKubeConfig) { String oidcTokenEndpoint = getParametersFromDiscoveryResponse(wellKnownOpenIdConfiguration, TOKEN_ENDPOINT_PARAM); try { String freshAccessToken = OpenIDConnectionUtils.refreshToken(client, oidcTokenEndpoint, clientId, refreshToken, clientSecret, shouldPersistUpdatedTokenInKubeConfig); @@ -130,7 +126,7 @@ static boolean isTokenRefreshSupported(Map currentAuthProviderCo /** * Issue Token refresh request * - * @param client okhttp client + * @param client http client * @param oidcTokenEndpoint OIDC provider token endpoint * @param clientId client id * @param refreshToken refresh token for token refreshing @@ -138,7 +134,7 @@ static boolean isTokenRefreshSupported(Map currentAuthProviderCo * @param shouldPersistUpdatedTokenInKubeConfig boolean value whether to update local kubeconfig file or not * @return access token received from OpenID Connection provider */ - static String refreshToken(OkHttpClient client, String oidcTokenEndpoint, String clientId, String refreshToken, String clientSecret, boolean shouldPersistUpdatedTokenInKubeConfig) { + static String refreshToken(HttpClient client, String oidcTokenEndpoint, String clientId, String refreshToken, String clientSecret, boolean shouldPersistUpdatedTokenInKubeConfig) { try { Map response = refreshOidcToken(client, clientId, refreshToken, clientSecret, oidcTokenEndpoint); @@ -163,7 +159,7 @@ static String refreshToken(OkHttpClient client, String oidcTokenEndpoint, String /** * Issue Token Refresh HTTP Request to OIDC Provider * - * @param client OkHttp Client for issuing HTTP request + * @param client Http Client for issuing HTTP request * @param clientId client id * @param refreshToken refresh token * @param clientSecret client secret @@ -171,19 +167,18 @@ static String refreshToken(OkHttpClient client, String oidcTokenEndpoint, String * @return response as HashMap * @throws IOException in case of any error in contacting OIDC provider */ - static Map refreshOidcToken(OkHttpClient client, String clientId, String refreshToken, String clientSecret, String tokenURL) throws IOException { - try (Response response = client.newCall(getTokenRefreshHttpRequest(tokenURL, clientId, refreshToken, clientSecret)).execute()) { - String responseBody; - if (response.body() != null) { - // Get response body as string - responseBody = response.body().string(); - if (response.isSuccessful()) { - // Deserialize response body into a Map and return - return convertJsonStringToMap(responseBody); - } else { - // Log error response body - LOGGER.warn("Response: {}", responseBody); - } + static Map refreshOidcToken(HttpClient client, String clientId, String refreshToken, String clientSecret, String tokenURL) throws IOException { + HttpRequest request = getTokenRefreshHttpRequest(client, tokenURL, clientId, refreshToken, clientSecret); + HttpResponse response = client.send(request, String.class); + String body = response.body(); + if (body != null) { + // Get response body as string + if (response.isSuccessful()) { + // Deserialize response body into a Map and return + return convertJsonStringToMap(body); + } else { + // Log error response body + LOGGER.warn("Response: {}", body); } } return Collections.emptyMap(); @@ -194,17 +189,19 @@ static Map refreshOidcToken(OkHttpClient client, String clientId * at a well-known URL which looks like this: https://[base-server-url]/.well-known/openid-configuration * This method performs an Http Get at this public URL and fetches response as a HashMap * - * @param client OkHttpClient for doing HTTP Get to well known URL of OpenID provider + * @param client HttpClient for doing HTTP Get to well known URL of OpenID provider * @param issuer OpenID Connect provider issuer URL * @return a HashMap of Discovery document */ - static Map getOIDCDiscoveryDocumentAsMap(OkHttpClient client, String issuer) { - try (Response response = client.newCall(getDiscoveryDocumentHttpRequest(issuer)).execute()) { + static Map getOIDCDiscoveryDocumentAsMap(HttpClient client, String issuer) { + HttpRequest request = client.newHttpRequestBuilder().uri(getWellKnownUrlForOpenIDIssuer(issuer)).build(); + try { + HttpResponse response = client.send(request, String.class); if (response.isSuccessful() && response.body() != null) { - return convertJsonStringToMap(response.body().string()); + return convertJsonStringToMap(response.body()); } else { // Don't produce an error that's too huge (e.g. if we get HTML back for some reason). - String responseBody = response.body() != null ? response.body().string() : null; + String responseBody = response.body(); LOGGER.warn("oidc: failed to query metadata endpoint: {} {}", response.code(), responseBody); } } catch (IOException e) { @@ -279,87 +276,57 @@ private static Map convertJsonStringToMap(String jsonString) thr return Serialization.jsonMapper().readValue(jsonString, Map.class); } - private static SSLContext getSSLContext(String idpCert) { + private static HttpClient getDefaultHttpClientWithPemCert(String idpCert, HttpClient.Builder clientBuilder) { SSLContext sslContext = null; + TrustManager[] trustManagers = null; + // fist, lets get the pem + String pemCert = new String(java.util.Base64.getDecoder().decode(idpCert)); - if (idpCert != null) { - // fist, lets get the pem - String pemCert = new String(java.util.Base64.getDecoder().decode(idpCert)); - - try { - TrustManager[] trustManagers = SSLUtils.trustManagers(pemCert, null, false, null, null); - KeyManager[] keyManagers = SSLUtils.keyManagers(pemCert, null, null, null, null, null, null, null); - sslContext = SSLUtils.sslContext(keyManagers, trustManagers); - } catch (KeyStoreException | - KeyManagementException | - InvalidKeySpecException | - NoSuchAlgorithmException | - IOException | - UnrecoverableKeyException | - CertificateException e) { - throw new RuntimeException("Could not import idp certificate", e); - } + try { + trustManagers = SSLUtils.trustManagers(pemCert, null, false, null, null); + KeyManager[] keyManagers = SSLUtils.keyManagers(pemCert, null, null, null, null, null, null, null); + sslContext = SSLUtils.sslContext(keyManagers, trustManagers); + } catch (KeyStoreException | + KeyManagementException | + InvalidKeySpecException | + NoSuchAlgorithmException | + IOException | + UnrecoverableKeyException | + CertificateException e) { + throw new RuntimeException("Could not import idp certificate", e); } - return sslContext; - } - - private static OkHttpClient getOkHttpClient(SSLContext sslContext, String pemCert) { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); + if (sslContext != null) { - clientBuilder.sslSocketFactory(sslContext.getSocketFactory(), getTrustManagerForAllCerts(pemCert)); + clientBuilder.sslContext(sslContext, trustManagers); } return clientBuilder.build(); } - private static X509TrustManager getTrustManagerForAllCerts(String pemCert) { - X509TrustManager trustManager = null; - try { - TrustManager[] trustManagers = SSLUtils.trustManagers(pemCert, null, false, null, null); - if (trustManagers != null && trustManagers.length == 1) { - trustManager = (X509TrustManager) trustManagers[0]; - } - } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException e) { - LOGGER.warn("Could not get trust manager"); - } - return trustManager; - } + private static HttpRequest getTokenRefreshHttpRequest(HttpClient client, String tokenEndpointUrl, String clientId, String refreshToken, String clientSecret) { + HttpRequest.Builder httpRequestBuilder = client.newHttpRequestBuilder().uri(tokenEndpointUrl); - private static Request getTokenRefreshHttpRequest(String tokenEndpointUrl, String clientId, String refreshToken, String clientSecret) throws JsonProcessingException { - HttpUrl.Builder httpUrlBuilder = HttpUrl.get(tokenEndpointUrl).newBuilder(); - - RequestBody requestBody = getRequestBodyContentForRefresh(clientId, refreshToken, clientSecret); - Request.Builder requestBuilder = new Request.Builder().post(requestBody).url(httpUrlBuilder.build()); + Map requestBody = getRequestBodyContentForRefresh(clientId, refreshToken, clientSecret); String credentials = java.util.Base64.getEncoder() .encodeToString((clientId + ':' + clientSecret).getBytes(StandardCharsets.UTF_8)); - requestBuilder.addHeader("Authorization", "Basic " + credentials); - requestBuilder.addHeader("Content-Type", "application/x-www-form-urlencoded"); - return requestBuilder.build(); - } - - private static Request getDiscoveryDocumentHttpRequest(String issuer) throws MalformedURLException { - URL wellKnown = new URL(getWellKnownUrlForOpenIDIssuer(issuer)); - return new Request.Builder() - .url(wellKnown) - .build(); + httpRequestBuilder.header("Authorization", "Basic " + credentials); + httpRequestBuilder.post(requestBody); + return httpRequestBuilder.build(); } - private static RequestBody getRequestBodyContentForRefresh(String clientId, String refreshToken, String clientSecret) { - return new FormBody.Builder() - .add(REFRESH_TOKEN_PARAM, refreshToken) - .add(GRANT_TYPE_PARAM, GRANT_TYPE_REFRESH_TOKEN) - .add(CLIENT_ID_PARAM, clientId) - .add(CLIENT_SECRET_PARAM, clientSecret) - .build(); + private static Map getRequestBodyContentForRefresh(String clientId, String refreshToken, String clientSecret) { + Map result = new LinkedHashMap<>(); + result.put(REFRESH_TOKEN_PARAM, refreshToken); + result.put(GRANT_TYPE_PARAM, GRANT_TYPE_REFRESH_TOKEN); + result.put(CLIENT_ID_PARAM, clientId); + result.put(CLIENT_SECRET_PARAM, clientSecret); + return result; } - private static String getOIDCProviderTokenEndpointAndRefreshToken(String issuer, String clientId, String refreshToken, String clientSecret, String accessToken, String idpCert) { - OkHttpClient okHttpClient = getOkHttpClient(getSSLContext(idpCert), idpCert); - try { - Map wellKnownOpenIdConfiguration = getOIDCDiscoveryDocumentAsMap(okHttpClient, issuer); - return getOIDCProviderTokenEndpointAndRefreshToken(okHttpClient, wellKnownOpenIdConfiguration, clientId, refreshToken, clientSecret, accessToken, true); - } finally { - HttpClientUtils.close(okHttpClient); + private static String getOIDCProviderTokenEndpointAndRefreshToken(String issuer, String clientId, String refreshToken, String clientSecret, String accessToken, String idpCert, HttpClient.Builder clientBuilder) { + try (HttpClient newClient = getDefaultHttpClientWithPemCert(idpCert, clientBuilder)) { + Map wellKnownOpenIdConfiguration = getOIDCDiscoveryDocumentAsMap(newClient, issuer); + return getOIDCProviderTokenEndpointAndRefreshToken(newClient, wellKnownOpenIdConfiguration, clientId, refreshToken, clientSecret, accessToken, true); } } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/TokenRefreshInterceptor.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/TokenRefreshInterceptor.java index 14a998363ab..83301aa4a80 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/TokenRefreshInterceptor.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/TokenRefreshInterceptor.java @@ -16,26 +16,31 @@ package io.fabric8.kubernetes.client.utils; import io.fabric8.kubernetes.client.Config; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; +import io.fabric8.kubernetes.client.http.BasicBuilder; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.http.Interceptor; -import java.io.IOException; import java.net.HttpURLConnection; /** * Interceptor for handling expired OIDC tokens. */ public class TokenRefreshInterceptor implements Interceptor { + + public static final String NAME = "TOKEN"; + private final Config config; - public TokenRefreshInterceptor(Config config) { + private HttpClient.Factory factory; + + public TokenRefreshInterceptor(Config config, HttpClient.Factory factory) { this.config = config; + this.factory = factory; } - + @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - Response response = chain.proceed(request); + public boolean afterFailure(BasicBuilder headerBuilder, HttpResponse response) { + boolean resubmit = false; if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) { String currentContextName = null; String newAccessToken = null; @@ -45,20 +50,20 @@ public Response intercept(Chain chain) throws IOException { } Config newestConfig = Config.autoConfigure(currentContextName); if (newestConfig.getAuthProvider() != null && newestConfig.getAuthProvider().getName().equalsIgnoreCase("oidc")) { - newAccessToken = OpenIDConnectionUtils.resolveOIDCTokenFromAuthConfig(newestConfig.getAuthProvider().getConfig()); + newAccessToken = OpenIDConnectionUtils.resolveOIDCTokenFromAuthConfig(newestConfig.getAuthProvider().getConfig(), factory.newBuilder()); } else { newAccessToken = newestConfig.getOauthToken(); } if (newAccessToken != null) { - response.close(); // Delete old Authorization header and append new one - Request authReqWithUpdatedToken = chain.request().newBuilder() - .header("Authorization", "Bearer " + newAccessToken).build(); + headerBuilder + .setHeader("Authorization", "Bearer " + newAccessToken); config.setOauthToken(newAccessToken); - response = chain.proceed(authReqWithUpdatedToken); + resubmit = true; } } - return response; + return resubmit; } + } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/URLUtils.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/URLUtils.java index 6c0c614b411..1fcf3e62b1e 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/URLUtils.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/URLUtils.java @@ -15,13 +15,52 @@ */ package io.fabric8.kubernetes.client.utils; -import java.io.UnsupportedEncodingException; +import io.fabric8.kubernetes.client.http.HttpRequest; + +import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; +import java.net.URL; public class URLUtils { + + public static class URLBuilder { + + private StringBuilder url; + + public URLBuilder(String url) { + this.url = new StringBuilder(url); + } + + public URLBuilder(URL url) { + this(url.toString()); + } + + public URLBuilder addQueryParameter(String key, String value) { + if (url.indexOf("?") == -1) { + url.append("?"); + } else { + url.append("&"); + } + url.append(encodeToUTF(key).replaceAll("[+]", "%20")).append("=").append(encodeToUTF(value).replaceAll("[+]", "%20")); + return this; + } + + public URL build() { + try { + return new URL(this.url.toString()); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e.getMessage(), e); + } + } + + @Override + public String toString() { + return build().toString(); + } + + } + private URLUtils() { throw new IllegalStateException("Utility class"); } @@ -154,7 +193,7 @@ public static boolean isValidURL(String url) { } } - public static String encodeToUTF(String url) throws UnsupportedEncodingException { - return URLEncoder.encode(url, StandardCharsets.UTF_8.displayName()); + public static String encodeToUTF(String url) { + return HttpRequest.formURLEncode(url); } } diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/ConfigTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/ConfigTest.java index ce027d4ce05..28d89c696b5 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/ConfigTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/ConfigTest.java @@ -18,11 +18,10 @@ import io.fabric8.kubernetes.api.model.ExecConfig; import io.fabric8.kubernetes.api.model.ExecConfigBuilder; +import io.fabric8.kubernetes.client.http.TlsVersion; import io.fabric8.kubernetes.client.lib.FileSystem; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.OkHttpClient; -import okhttp3.TlsVersion; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -42,13 +41,11 @@ import java.util.List; import java.util.Map; -import static okhttp3.TlsVersion.TLS_1_1; -import static okhttp3.TlsVersion.TLS_1_2; -import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -179,7 +176,7 @@ void testWithBuilder() { .withUploadConnectionTimeout(60000) .withUploadRequestTimeout(600000) .withHttpProxy("httpProxy") - .withTlsVersions(TLS_1_2, TLS_1_1) + .withTlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1) .withTrustStoreFile("/path/to/truststore") .withTrustStorePassphrase("truststorePassphrase") .withKeyStoreFile("/path/to/keystore") @@ -462,32 +459,6 @@ void shouldInstantiateClientUsingSerializeDeserialize() { assertEquals(original.getConfiguration().getPassword(), copy.getConfiguration().getPassword()); } - @Test - void shouldRespectMaxRequests() { - Config config = new ConfigBuilder() - .withMaxConcurrentRequests(120) - .build(); - - KubernetesClient client = new DefaultKubernetesClient(); - assertEquals(64, client.adapt(OkHttpClient.class).dispatcher().getMaxRequests()); - - client = new DefaultKubernetesClient(config); - assertEquals(120, client.adapt(OkHttpClient.class).dispatcher().getMaxRequests()); - } - - @Test - void shouldRespectMaxRequestsPerHost() { - Config config = new ConfigBuilder() - .withMaxConcurrentRequestsPerHost(20) - .build(); - - KubernetesClient client = new DefaultKubernetesClient(); - assertEquals(5, client.adapt(OkHttpClient.class).dispatcher().getMaxRequestsPerHost()); - - client = new DefaultKubernetesClient(config); - assertEquals(20, client.adapt(OkHttpClient.class).dispatcher().getMaxRequestsPerHost()); - } - @Test void shouldPropagateImpersonateSettings() { @@ -615,7 +586,7 @@ private void assertConfig(Config config) { assertEquals(60000, config.getRequestConfig().getUploadConnectionTimeout()); assertEquals(600000, config.getRequestConfig().getUploadRequestTimeout()); - assertArrayEquals(new TlsVersion[]{TLS_1_2, TLS_1_1}, config.getTlsVersions()); + assertArrayEquals(new TlsVersion[]{TlsVersion.TLS_1_2, TlsVersion.TLS_1_1}, config.getTlsVersions()); assertEquals("/path/to/truststore", config.getTrustStoreFile()); assertEquals("truststorePassphrase", config.getTrustStorePassphrase()); diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/DefaultKubernetesClientTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/DefaultKubernetesClientTest.java index 9da8be0c5d2..5ee94dd29d7 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/DefaultKubernetesClientTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/DefaultKubernetesClientTest.java @@ -18,10 +18,14 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.fabric8.kubernetes.client.http.BasicBuilder; +import io.fabric8.kubernetes.client.http.HttpHeaders; +import io.fabric8.kubernetes.client.utils.HttpClientUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.io.File; @@ -58,18 +62,19 @@ void testInitClientWithCustomHeaderConfiguration() { customHeaders.put("cluster-id", "test-cluster"); final Config configWithCustomerHeaders = new ConfigBuilder().withCustomHeaders(customHeaders).build(); - final DefaultKubernetesClient customHeaderConfigClient = new DefaultKubernetesClient(configWithCustomerHeaders); - - assertThat(customHeaderConfigClient.getHttpClient().networkInterceptors()).hasSize(1); + BasicBuilder basicBuilder = Mockito.mock(BasicBuilder.class); + HttpClientUtils.createApplicableInterceptors(configWithCustomerHeaders, null).get(HttpClientUtils.HEADER_INTERCEPTOR).before(basicBuilder, Mockito.mock(HttpHeaders.class)); + Mockito.verify(basicBuilder, Mockito.times(1)).header("user-id", "test-user"); } @Test void testInitClientWithDefaultConfiguration() { final Config defaultEmptyConfig = new ConfigBuilder().build(); - DefaultKubernetesClient defaultConfigClient = new DefaultKubernetesClient(defaultEmptyConfig); + BasicBuilder basicBuilder = Mockito.mock(BasicBuilder.class); + HttpClientUtils.createApplicableInterceptors(defaultEmptyConfig, null).get(HttpClientUtils.HEADER_INTERCEPTOR).before(basicBuilder, Mockito.mock(HttpHeaders.class)); - assertThat(defaultConfigClient.getHttpClient().networkInterceptors()).isEmpty(); + Mockito.verify(basicBuilder, Mockito.never()).header("user-id", "test-user"); } @Test diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/DryRunTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/DryRunTest.java index cee45f96323..053e80bb429 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/DryRunTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/DryRunTest.java @@ -20,209 +20,204 @@ import io.fabric8.kubernetes.api.model.PodBuilder; import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.ServiceBuilder; -import okhttp3.Call; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpRequest.Builder; +import io.fabric8.kubernetes.client.http.HttpResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import java.io.IOException; +import java.io.InputStream; import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class DryRunTest { - private OkHttpClient mockClient; + private HttpClient mockClient; private KubernetesClient kubernetesClient; + private List builders = new ArrayList<>(); @BeforeEach public void setUp() throws IOException { - this.mockClient = Mockito.mock(OkHttpClient.class, Mockito.RETURNS_DEEP_STUBS); + builders.clear(); + this.mockClient = Mockito.mock(HttpClient.class, Mockito.RETURNS_DEEP_STUBS); Config config = new ConfigBuilder().withMasterUrl("https://localhost:8443/").build(); - Call mockCall = mock(Call.class); - Response mockResponse = new Response.Builder() - .request(new Request.Builder().url("http://mock").build()) - .protocol(Protocol.HTTP_1_1) - .code(HttpURLConnection.HTTP_OK) - .body(ResponseBody.create(MediaType.get("application/json"), "{}")) - .message("mock") - .build(); - when(mockCall.execute()) - .thenReturn(mockResponse); - when(mockClient.newCall(any())).thenReturn(mockCall); + HttpResponse mockResponse = MockHttpClientUtils.buildResponse(HttpURLConnection.HTTP_OK, "{}"); + when(mockClient.send(any(), Mockito.eq(InputStream.class))).thenReturn(mockResponse); kubernetesClient = new DefaultKubernetesClient(mockClient, config); + Mockito.when(mockClient.newHttpRequestBuilder()).thenAnswer(answer -> { + HttpRequest.Builder result = Mockito.mock(HttpRequest.Builder.class, Mockito.RETURNS_SELF); + builders.add(result); + return result; + }); } @Test - void testDryRunDisable() { - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); - + void testDryRunDisable() throws IOException { // When Pod pod = kubernetesClient.pods().inNamespace("ns1").withName("foo").dryRun(false).create(getPod("pod1")); // Then - verify(mockClient).newCall(captor.capture()); - assertRequest(captor.getValue(), "POST", "/api/v1/namespaces/ns1/pods", null); + verify(mockClient).send(any(), any()); + assertRequest("POST", "/api/v1/namespaces/ns1/pods", null); assertNotNull(pod); } @Test - void testDryRunEnable() { - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); - + void testDryRunEnable() throws IOException { // When Pod pod = kubernetesClient.pods().inNamespace("ns1").withName("foo").dryRun(true).create(getPod("pod1")); // Then - verify(mockClient).newCall(captor.capture()); - assertRequest(captor.getValue(), "POST", "/api/v1/namespaces/ns1/pods", "dryRun=All"); + verify(mockClient).send(any(), any()); + assertRequest("POST", "/api/v1/namespaces/ns1/pods", "dryRun=All"); assertNotNull(pod); } @Test - void testCreate() { + void testCreate() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When Pod pod = kubernetesClient.pods().inNamespace("ns1").withName("foo").dryRun().create(getPod("pod1")); // Then - verify(mockClient).newCall(captor.capture()); - assertRequest(captor.getValue(), "POST", "/api/v1/namespaces/ns1/pods", "dryRun=All"); + verify(mockClient).send(any(), any()); + assertRequest("POST", "/api/v1/namespaces/ns1/pods", "dryRun=All"); assertNotNull(pod); } @Test - void testCreateOrReplace() { + void testCreateOrReplace() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When Pod pod = kubernetesClient.pods().inNamespace("ns1").withName("foo").dryRun().createOrReplace(getPod("pod1")); // Then - verify(mockClient).newCall(captor.capture()); + verify(mockClient).send(any(), any()); assertNotNull(pod); - assertRequest(captor.getValue(), "POST", "/api/v1/namespaces/ns1/pods", "dryRun=All"); + assertRequest("POST", "/api/v1/namespaces/ns1/pods", "dryRun=All"); } @Test - void testPatch() { + void testPatch() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When kubernetesClient.pods().inNamespace("ns1").withName("pod1").dryRun().patch(getPod("pod1")); // Then - verify(mockClient, times(2)).newCall(captor.capture()); - assertRequest(captor.getValue(), "PATCH", "/api/v1/namespaces/ns1/pods/pod1", "dryRun=All"); + verify(mockClient, times(2)).send(any(), any()); + assertRequest(1, "PATCH", "/api/v1/namespaces/ns1/pods/pod1", "dryRun=All"); } @Test - void testReplace() { + void testReplace() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When kubernetesClient.pods().inNamespace("ns1").withName("pod1").dryRun().replace(getPod("pod1")); // Then - verify(mockClient, times(2)).newCall(captor.capture()); - assertRequest(captor.getValue(), "PUT", "/api/v1/namespaces/ns1/pods/pod1", "dryRun=All"); + verify(mockClient, times(2)).send(any(), any()); + assertRequest(1, "PUT", "/api/v1/namespaces/ns1/pods/pod1", "dryRun=All"); } @Test - void testDelete() { + void testDelete() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When kubernetesClient.pods().inNamespace("ns1").withName("pod1").dryRun().withPropagationPolicy(DeletionPropagation.BACKGROUND).delete(); // Then - verify(mockClient).newCall(captor.capture()); - assertRequest(captor.getValue(), "DELETE", "/api/v1/namespaces/ns1/pods/pod1", "dryRun=All"); + verify(mockClient).send(any(), any()); + assertRequest("DELETE", "/api/v1/namespaces/ns1/pods/pod1", "dryRun=All"); } @Test - void testResourceCreateOrReplace() { + void testResourceCreateOrReplace() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When kubernetesClient.resource(getPod("pod1")).inNamespace("ns1").dryRun().createOrReplace(); // Then - verify(mockClient, times(1)).newCall(captor.capture()); - assertRequest(captor.getValue(), "POST", "/api/v1/namespaces/ns1/pods", "dryRun=All"); + verify(mockClient).send(any(), any()); + assertRequest("POST", "/api/v1/namespaces/ns1/pods", "dryRun=All"); } @Test - void testResourceDelete() { + void testResourceDelete() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When kubernetesClient.resource(getPod("pod1")).inNamespace("ns1").dryRun().withPropagationPolicy(DeletionPropagation.BACKGROUND).delete(); // Then - verify(mockClient).newCall(captor.capture()); - assertRequest(captor.getValue(), "DELETE", "/api/v1/namespaces/ns1/pods/pod1", "dryRun=All"); + verify(mockClient).send(any(), any()); + assertRequest("DELETE", "/api/v1/namespaces/ns1/pods/pod1", "dryRun=All"); } @Test - void testResourceListCreateOrReplace() { + void testResourceListCreateOrReplace() throws IOException { // Given Pod pod = getPod("pod1"); Service svc = new ServiceBuilder().withNewMetadata().withName("svc1").endMetadata().build(); - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When kubernetesClient.resourceList(pod, svc).inNamespace("ns1").dryRun().createOrReplace(); // Then - verify(mockClient, times(2)).newCall(captor.capture()); - assertRequest(captor.getAllValues().get(0), "POST", "/api/v1/namespaces/ns1/services", "dryRun=All"); - assertRequest(captor.getAllValues().get(1), "POST", "/api/v1/namespaces/ns1/pods", "dryRun=All"); + verify(mockClient, times(2)).send(any(), any()); + assertRequest("POST", "/api/v1/namespaces/ns1/services", "dryRun=All"); + assertRequest(1, "POST", "/api/v1/namespaces/ns1/pods", "dryRun=All"); } @Test - void testResourceListDelete() { + void testResourceListDelete() throws IOException { // Given Pod pod = getPod("pod1"); Service svc = new ServiceBuilder().withNewMetadata().withName("svc1").endMetadata().build(); - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When kubernetesClient.resourceList(pod, svc).inNamespace("ns1").dryRun().withPropagationPolicy(DeletionPropagation.BACKGROUND).delete(); // Then - verify(mockClient, times(2)).newCall(captor.capture()); - assertRequest(captor.getAllValues().get(0), "DELETE", "/api/v1/namespaces/ns1/services/svc1", "dryRun=All"); - assertRequest(captor.getAllValues().get(1), "DELETE", "/api/v1/namespaces/ns1/pods/pod1", "dryRun=All"); + verify(mockClient, times(2)).send(any(), any()); + assertRequest("DELETE", "/api/v1/namespaces/ns1/services/svc1", "dryRun=All"); + assertRequest(1, "DELETE", "/api/v1/namespaces/ns1/pods/pod1", "dryRun=All"); } private Pod getPod(String name) { return new PodBuilder().withNewMetadata().withName(name).endMetadata().build(); } - private void assertRequest(Request request, String method, String url, String queryParam) { - assertEquals(url, request.url().encodedPath()); - assertEquals(method, request.method()); - assertEquals(queryParam, request.url().encodedQuery()); + private void assertRequest(String method, String url, String queryParam) { + assertRequest(0, method, url, queryParam); + } + + private void assertRequest(int index, String method, String url, String queryParam) { + ArgumentCaptor urlCaptor = ArgumentCaptor.forClass(URL.class); + Builder mock = builders.get(index); + verify(mock).url(urlCaptor.capture()); + + URL capturedURL = urlCaptor.getValue(); + assertEquals(url, capturedURL.getPath()); + PatchTest.validateMethod(method, null, mock); + + assertEquals(queryParam, capturedURL.getQuery()); } } diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/HandlersTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/HandlersTest.java index b1400288323..83bb81801a0 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/HandlersTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/HandlersTest.java @@ -21,7 +21,6 @@ import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; -import okhttp3.OkHttpClient; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; @@ -35,7 +34,7 @@ static class MyPod extends Pod { static class MyPodOperationsImpl extends HasMetadataOperation, Resource> { - public MyPodOperationsImpl(OkHttpClient client, Config config) { + public MyPodOperationsImpl(ClientContext clientContext) { super(new OperationContext(), MyPod.class, null); } @@ -45,10 +44,10 @@ public MyPodOperationsImpl(OkHttpClient client, Config config) { public void testRegister() { Handlers.register(MyPod.class, MyPodOperationsImpl::new); - assertThat(Handlers.get(new MyPod(), null).operation(null, null, null), Matchers.instanceOf(MyPodOperationsImpl.class)); + assertThat(Handlers.get(new MyPod(), null).operation(new SimpleClientContext(), null), Matchers.instanceOf(MyPodOperationsImpl.class)); Handlers.unregister(MyPod.class); - assertThat(Handlers.get(new MyPod(), null).operation(null, null, null), Matchers.instanceOf(HasMetadataOperationsImpl.class)); + assertThat(Handlers.get(new MyPod(), null).operation(new SimpleClientContext(), null), Matchers.instanceOf(HasMetadataOperationsImpl.class)); } } diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/MockHttpClientUtils.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/MockHttpClientUtils.java new file mode 100644 index 00000000000..33c88731aa8 --- /dev/null +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/MockHttpClientUtils.java @@ -0,0 +1,50 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.fabric8.kubernetes.client; + +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.http.HttpStatusMessage; +import org.mockito.Mockito; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; + +import static org.mockito.Mockito.when; + +public class MockHttpClientUtils { + + public static HttpResponse buildResponse(int code, String body) { + HttpResponse response = Mockito.mock(HttpResponse.class, Mockito.CALLS_REAL_METHODS); + when(response.code()).thenReturn(code); + when(response.body()).thenReturn(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8))); + HttpRequest mockRequest = buildRequest(); + when(response.request()).thenReturn(mockRequest); + return response; + } + + public static HttpRequest buildRequest() { + HttpRequest mockRequest = Mockito.mock(HttpRequest.class, Mockito.RETURNS_DEEP_STUBS); + when(mockRequest.uri()).thenReturn(URI.create("http://mock:8443")); + return mockRequest; + } + + public static HttpResponse buildResponse(int code) { + return buildResponse(code, "{\"kind\":\"Status\",\"status\":\""+HttpStatusMessage.getMessageForStatus(code)+"\"}"); + } +} diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/PatchTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/PatchTest.java index 2b5246b1666..78964ffff0b 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/PatchTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/PatchTest.java @@ -17,77 +17,75 @@ import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.client.dsl.PodResource; +import io.fabric8.kubernetes.client.dsl.base.OperationSupport; import io.fabric8.kubernetes.client.dsl.base.PatchContext; import io.fabric8.kubernetes.client.dsl.base.PatchType; -import okhttp3.Call; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.assertj.core.api.AssertionsForClassTypes; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpRequest.Builder; +import io.fabric8.kubernetes.client.http.HttpResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import java.io.IOException; +import java.io.InputStream; import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URL; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class PatchTest { - private Call mockCall; - private OkHttpClient mockClient; + private HttpClient mockClient; private KubernetesClient kubernetesClient; + private List builders = new ArrayList<>(); @BeforeEach public void setUp() throws IOException { - this.mockClient = Mockito.mock(OkHttpClient.class, Mockito.RETURNS_DEEP_STUBS); + // TODO: fully mocking makes this logic more difficult and basically copied in other tests, we may want to rely on an actual implementation instead + builders.clear(); + this.mockClient = Mockito.mock(HttpClient.class, Mockito.RETURNS_DEEP_STUBS); Config config = new ConfigBuilder().withMasterUrl("https://localhost:8443/").build(); - mockCall = mock(Call.class); - Response mockResponse = new Response.Builder() - .request(new Request.Builder().url("http://mock").build()) - .protocol(Protocol.HTTP_1_1) - .code(HttpURLConnection.HTTP_OK) - .body(ResponseBody.create(MediaType.get("application/json"), "{\"metadata\":{\"name\":\"foo\"}}")) - .message("mock") - .build(); - when(mockCall.execute()) - .thenReturn(mockResponse, mockResponse); - when(mockClient.newCall(any())).thenReturn(mockCall); + HttpResponse mockResponse = MockHttpClientUtils.buildResponse(HttpURLConnection.HTTP_OK, "{}"); + when(mockClient.send(any(), Mockito.eq(InputStream.class))).thenReturn(mockResponse); kubernetesClient = new DefaultKubernetesClient(mockClient, config); + Mockito.when(mockClient.newHttpRequestBuilder()).thenAnswer(answer -> { + HttpRequest.Builder result = Mockito.mock(HttpRequest.Builder.class, Mockito.RETURNS_SELF); + HttpRequest request = Mockito.mock(HttpRequest.class, Mockito.RETURNS_DEEP_STUBS); + Mockito.when(request.uri()).thenReturn(URI.create("https://localhost:8443/")); + Mockito.when(result.build()).thenReturn(request); + builders.add(result); + return result; + }); } @Test - void testJsonPatch() { + void testJsonPatch() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When kubernetesClient.pods().inNamespace("ns1").withName("foo") .patch("{\"metadata\":{\"annotations\":{\"bob\":\"martin\"}}}"); // Then - verify(mockClient, times(2)).newCall(captor.capture()); - assertRequest(captor.getAllValues().get(0), "GET", "/api/v1/namespaces/ns1/pods/foo", null); - assertRequest(captor.getAllValues().get(1), "PATCH", "/api/v1/namespaces/ns1/pods/foo", null); - assertBodyContentType("strategic-merge-patch+json", captor.getAllValues().get(1)); + verify(mockClient, times(2)).send(any(), any()); + assertRequest("GET", "/api/v1/namespaces/ns1/pods/foo", null); + assertRequest(1, "PATCH", "/api/v1/namespaces/ns1/pods/foo", null, OperationSupport.STRATEGIC_MERGE_JSON_PATCH); } @Test - void testJsonMergePatch() { + void testJsonMergePatch() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); PatchContext patchContext = new PatchContext.Builder() .withPatchType(PatchType.JSON_MERGE) .build(); @@ -97,38 +95,29 @@ void testJsonMergePatch() { .patch(patchContext, "{\"metadata\":{\"annotations\":{\"bob\":\"martin\"}}}"); // Then - verify(mockClient, times(2)).newCall(captor.capture()); - assertRequest(captor.getAllValues().get(0), "GET", "/api/v1/namespaces/ns1/pods/foo", null); - assertRequest(captor.getAllValues().get(1), "PATCH", "/api/v1/namespaces/ns1/pods/foo", null); - assertBodyContentType("merge-patch+json", captor.getAllValues().get(1)); + verify(mockClient, times(2)).send(any(), any()); + assertRequest("GET", "/api/v1/namespaces/ns1/pods/foo", null); + assertRequest(1, "PATCH", "/api/v1/namespaces/ns1/pods/foo", null, OperationSupport.JSON_MERGE_PATCH); } @Test - void testYamlPatchConvertedToJson() { + void testYamlPatchConvertedToJson() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When kubernetesClient.pods().inNamespace("ns1").withName("foo").patch("metadata:\n annotations:\n bob: martin"); // Then - verify(mockClient, times(2)).newCall(captor.capture()); - assertRequest(captor.getAllValues().get(0), "GET", "/api/v1/namespaces/ns1/pods/foo", null); - assertRequest(captor.getAllValues().get(1), "PATCH", "/api/v1/namespaces/ns1/pods/foo", null); - assertBodyContentType("strategic-merge-patch+json", captor.getAllValues().get(1)); + verify(mockClient, times(2)).send(any(), any()); + assertRequest("GET", "/api/v1/namespaces/ns1/pods/foo", null); + assertRequest(1, "PATCH", "/api/v1/namespaces/ns1/pods/foo", null, OperationSupport.STRATEGIC_MERGE_JSON_PATCH); } @Test void testPatchThrowExceptionWhenResourceNotFound() throws IOException { // Given - when(mockCall.execute()).thenReturn(new Response.Builder() - .request(new Request.Builder().url("http://mock").build()) - .protocol(Protocol.HTTP_1_1) - .code(HttpURLConnection.HTTP_NOT_FOUND) - .body(ResponseBody.create(MediaType.get("application/json"), "{}")) - .message("mock") - .build()); - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + HttpResponse mockResponse = MockHttpClientUtils.buildResponse(HttpURLConnection.HTTP_NOT_FOUND, "{}"); + when(mockClient.send(any(), Mockito.eq(InputStream.class))).thenReturn(mockResponse); // When PodResource podResource = kubernetesClient.pods() @@ -138,15 +127,14 @@ void testPatchThrowExceptionWhenResourceNotFound() throws IOException { () -> podResource.patch("{\"metadata\":{\"annotations\":{\"bob\":\"martin\"}}}")); // Then - verify(mockClient, times(1)).newCall(captor.capture()); - assertRequest(captor.getValue(), "GET", "/api/v1/namespaces/ns1/pods/foo", null); + verify(mockClient).send(any(), any()); + assertRequest("GET", "/api/v1/namespaces/ns1/pods/foo", null); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, e.getCode()); } @Test - void testJsonPatchWithPositionalArrays() { + void testJsonPatchWithPositionalArrays() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); PatchContext patchContext = new PatchContext.Builder().withPatchType(PatchType.JSON).build(); // When @@ -154,16 +142,14 @@ void testJsonPatchWithPositionalArrays() { .patch(patchContext, "[{\"op\": \"replace\", \"path\":\"/spec/containers/0/image\", \"value\":\"foo/gb-frontend:v4\"}]"); // Then - verify(mockClient, times(2)).newCall(captor.capture()); - assertRequest(captor.getAllValues().get(0), "GET", "/api/v1/namespaces/ns1/pods/foo", null); - assertRequest(captor.getAllValues().get(1), "PATCH", "/api/v1/namespaces/ns1/pods/foo", null); - assertBodyContentType("json-patch+json", captor.getAllValues().get(1)); + verify(mockClient, times(2)).send(any(), any()); + assertRequest("GET", "/api/v1/namespaces/ns1/pods/foo", null); + assertRequest(1, "PATCH", "/api/v1/namespaces/ns1/pods/foo", null, OperationSupport.JSON_PATCH); } @Test - void testPatchWithPatchOptions() { + void testPatchWithPatchOptions() throws IOException { // Given - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); // When kubernetesClient.pods().inNamespace("ns1").withName("foo") @@ -173,21 +159,50 @@ void testPatchWithPatchOptions() { .build(), "{\"metadata\":{\"annotations\":{\"bob\":\"martin\"}}}"); // Then - verify(mockClient, times(2)).newCall(captor.capture()); - assertRequest(captor.getAllValues().get(0), "GET", "/api/v1/namespaces/ns1/pods/foo", null); - assertRequest(captor.getAllValues().get(1), "PATCH", "/api/v1/namespaces/ns1/pods/foo", "fieldManager=fabric8&dryRun=All"); - assertBodyContentType("strategic-merge-patch+json", captor.getAllValues().get(1)); + verify(mockClient, times(2)).send(any(), any()); + assertRequest("GET", "/api/v1/namespaces/ns1/pods/foo", null); + assertRequest(1, "PATCH", "/api/v1/namespaces/ns1/pods/foo", "fieldManager=fabric8&dryRun=All", OperationSupport.STRATEGIC_MERGE_JSON_PATCH); } - private void assertRequest(Request request, String method, String url, String queryParam) { - assertThat(request.url().encodedPath()).isEqualTo(url); - assertThat(request.method()).isEqualTo(method); - assertThat(request.url().encodedQuery()).isEqualTo(queryParam); + private void assertRequest(String method, String url, String queryParam) { + assertRequest(0, method, url, queryParam, null); + } + + private void assertRequest(int index, String method, String url, String queryParam, String contentType) { + ArgumentCaptor urlCaptor = ArgumentCaptor.forClass(URL.class); + Builder mock = builders.get(index); + verify(mock).url(urlCaptor.capture()); + URL capturedURL = urlCaptor.getValue(); + assertEquals(url, capturedURL.getPath()); + + validateMethod(method, contentType, mock); + + assertEquals(queryParam, capturedURL.getQuery()); } - private void assertBodyContentType(String expectedContentSubtype, Request request) { - AssertionsForClassTypes.assertThat(request.body().contentType()).isNotNull(); - AssertionsForClassTypes.assertThat(request.body().contentType().type()).isEqualTo("application"); - AssertionsForClassTypes.assertThat(request.body().contentType().subtype()).isEqualTo(expectedContentSubtype); + static void validateMethod(String method, String contentType, Builder mock) { + ArgumentCaptor contentTypeCaptor = ArgumentCaptor.forClass(String.class); + switch (method) { + case "DELETE": + Mockito.verify(mock).delete(contentTypeCaptor.capture(), any()); + break; + case "POST": + Mockito.verify(mock).post(contentTypeCaptor.capture(), any(String.class)); + break; + case "PUT": + Mockito.verify(mock).put(contentTypeCaptor.capture(), any()); + break; + case "PATCH": + Mockito.verify(mock).patch(contentTypeCaptor.capture(), any()); + break; + default: + break; //TODO: validate GET, but that explicit call was removed + } + + if (contentType != null) { + assertEquals(contentType, contentTypeCaptor.getValue()); + } } + + } diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/base/BaseOperationTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/base/BaseOperationTest.java index 1ca52dcc85d..105a130e0a1 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/base/BaseOperationTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/base/BaseOperationTest.java @@ -15,57 +15,54 @@ */ package io.fabric8.kubernetes.client.dsl.base; -import static okhttp3.Protocol.HTTP_1_1; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Predicate; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - import io.fabric8.kubernetes.api.model.DeletionPropagation; import io.fabric8.kubernetes.api.model.ListOptionsBuilder; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodBuilder; import io.fabric8.kubernetes.api.model.PodList; import io.fabric8.kubernetes.client.ConfigBuilder; -import io.fabric8.kubernetes.client.dsl.EditReplacePatchDeletable; -import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.KubernetesClientTimeoutException; +import io.fabric8.kubernetes.client.MockHttpClientUtils; +import io.fabric8.kubernetes.client.dsl.EditReplacePatchDeletable; +import io.fabric8.kubernetes.client.dsl.Resource; +import io.fabric8.kubernetes.client.dsl.internal.PodOperationContext; +import io.fabric8.kubernetes.client.dsl.internal.core.v1.PodOperationsImpl; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.Call; -import okhttp3.MediaType; import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; -import io.fabric8.kubernetes.client.dsl.internal.PodOperationContext; -import io.fabric8.kubernetes.client.dsl.internal.core.v1.PodOperationsImpl; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; class BaseOperationTest { @@ -237,29 +234,25 @@ void testGetWriteOperationUrlWithDryRunDisabled() throws MalformedURLException { assertEquals("https://172.17.0.2:8443/api/v1/namespaces/ns1/pods/foo", result.toString()); } - private OkHttpClient newHttpClientWithSomeFailures(final AtomicInteger httpExecutionCounter, final int numFailures) { - OkHttpClient mockClient = mock(OkHttpClient.class); - when(mockClient.newCall(any())).thenAnswer( + private HttpClient newHttpClientWithSomeFailures(final AtomicInteger httpExecutionCounter, final int numFailures) throws IOException { + HttpClient mockClient = mock(HttpClient.class, Mockito.RETURNS_DEEP_STUBS); + HttpRequest.Builder mockRequestBuilder = mock(HttpRequest.Builder.class, Mockito.RETURNS_SELF); + HttpRequest request = MockHttpClientUtils.buildRequest(); + when(mockClient.newHttpRequestBuilder()).thenReturn(mockRequestBuilder); + when(mockRequestBuilder.build()).thenReturn(request); + when(mockClient.send(Mockito.any(), Mockito.eq(InputStream.class))).thenAnswer( invocation -> { - Call mockCall = mock(Call.class); - Request req = invocation.getArgument(0); - when(mockCall.execute()).thenAnswer(i -> { - int count = httpExecutionCounter.getAndIncrement(); - if (count < numFailures) { - // Altering the type of the error for each call: - // even numbered calls (including the first call) fail with an IOException and odd numbered calls fail with HTTP response 500 - if (count % 2 == 0) { - throw new IOException("For example java.net.ConnectException"); - } else { - return new Response.Builder().request(req).message("Internal Server Error").protocol(HTTP_1_1).code(500).build(); - } - } else { - Pod podNoLabels = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build(); - ResponseBody body = ResponseBody.create(MediaType.get("application/json"), Serialization.asJson(podNoLabels)); - return new Response.Builder().request(req).protocol(HTTP_1_1).body(body).message("OK").code(HttpURLConnection.HTTP_OK).build(); + int count = httpExecutionCounter.getAndIncrement(); + if (count < numFailures) { + // Altering the type of the error for each call: + // even numbered calls (including the first call) fail with an IOException and odd numbered calls fail with HTTP response 500 + if (count % 2 == 0) { + throw new IOException("For example java.net.ConnectException"); } - }); - return mockCall; + return MockHttpClientUtils.buildResponse(500); + } + Pod podNoLabels = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build(); + return MockHttpClientUtils.buildResponse(HttpURLConnection.HTTP_OK, Serialization.asJson(podNoLabels)); } ); return mockClient; @@ -268,12 +261,12 @@ private OkHttpClient newHttpClientWithSomeFailures(final AtomicInteger httpExecu @Test void testNoHttpRetryWithDefaultConfig() throws MalformedURLException, IOException { final AtomicInteger httpExecutionCounter = new AtomicInteger(0); - OkHttpClient mockClient = newHttpClientWithSomeFailures(httpExecutionCounter, 1000); + HttpClient mockClient = newHttpClientWithSomeFailures(httpExecutionCounter, 1000); BaseOperation> baseOp = new BaseOperation(new OperationContext() .withConfig(new ConfigBuilder().withMasterUrl("https://172.17.0.2:8443").build()) .withPlural("pods") .withName("test-pod") - .withOkhttpClient(mockClient)); + .withHttpClient(mockClient)); baseOp.setType(Pod.class); // When @@ -290,12 +283,12 @@ void testNoHttpRetryWithDefaultConfig() throws MalformedURLException, IOExceptio @Test void testHttpRetryWithMoreFailuresThanRetries() throws MalformedURLException, IOException { final AtomicInteger httpExecutionCounter = new AtomicInteger(0); - OkHttpClient mockClient = newHttpClientWithSomeFailures(httpExecutionCounter, 1000); + HttpClient mockClient = newHttpClientWithSomeFailures(httpExecutionCounter, 1000); BaseOperation> baseOp = new BaseOperation(new OperationContext() .withConfig(new ConfigBuilder().withMasterUrl("https://172.17.0.2:8443").withRequestRetryBackoffLimit(3).build()) .withPlural("pods") .withName("test-pod") - .withOkhttpClient(mockClient)); + .withHttpClient(mockClient)); baseOp.setType(Pod.class); // When @@ -312,12 +305,12 @@ void testHttpRetryWithMoreFailuresThanRetries() throws MalformedURLException, IO @Test void testHttpRetryWithLessFailuresThanRetries() throws MalformedURLException, IOException { final AtomicInteger httpExecutionCounter = new AtomicInteger(0); - OkHttpClient mockClient = newHttpClientWithSomeFailures(httpExecutionCounter, 2); + HttpClient mockClient = newHttpClientWithSomeFailures(httpExecutionCounter, 2); BaseOperation> baseOp = new BaseOperation(new OperationContext() .withConfig(new ConfigBuilder().withMasterUrl("https://172.17.0.2:8443").withRequestRetryBackoffLimit(3).build()) .withPlural("pods") .withName("test-pod") - .withOkhttpClient(mockClient)); + .withHttpClient(mockClient)); baseOp.setType(Pod.class); // When @@ -331,13 +324,13 @@ void testHttpRetryWithLessFailuresThanRetries() throws MalformedURLException, IO @Test void testWaitUntilFailureCompletion() throws MalformedURLException, IOException { final AtomicInteger httpExecutionCounter = new AtomicInteger(0); - OkHttpClient mockClient = newHttpClientWithSomeFailures(httpExecutionCounter, 2); + HttpClient mockClient = newHttpClientWithSomeFailures(httpExecutionCounter, 2); CompletableFuture> future = new CompletableFuture<>(); BaseOperation> baseOp = new BaseOperation(new OperationContext() .withConfig(new ConfigBuilder().withMasterUrl("https://172.17.0.2:8443").build()) .withPlural("pods") .withName("test-pod") - .withOkhttpClient(mockClient)) { + .withHttpClient(mockClient)) { @Override public CompletableFuture> informOnCondition(Predicate condition) { diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/base/OperationContextTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/base/OperationContextTest.java index 27d81fb99f4..758e574dfb1 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/base/OperationContextTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/base/OperationContextTest.java @@ -19,7 +19,7 @@ import io.fabric8.kubernetes.api.model.batch.v1.Job; import io.fabric8.kubernetes.api.model.batch.v1.JobBuilder; import io.fabric8.kubernetes.client.Config; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.http.HttpClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -34,12 +34,12 @@ import static org.mockito.Mockito.when; class OperationContextTest { - private OkHttpClient okHttpClient; + private HttpClient httpClient; private Config config; @BeforeEach public void setUp() { - this.okHttpClient = Mockito.mock(OkHttpClient.class, Mockito.RETURNS_DEEP_STUBS); + this.httpClient = Mockito.mock(HttpClient.class, Mockito.RETURNS_DEEP_STUBS); this.config = Mockito.mock(Config.class, Mockito.RETURNS_DEEP_STUBS); } @@ -71,7 +71,7 @@ void testCompleteOperationContext() { .withConfig(config) .withApiGroupName("batch") .withApiGroupVersion("v1") - .withOkhttpClient(okHttpClient) + .withHttpClient(httpClient) .withPlural("jobs") .withItem(new JobBuilder().withNewMetadata().withName("testItem").endMetadata().build()) .withCascading(false) diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManagerTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManagerTest.java index 99449a2c9a0..86a7620b6ad 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManagerTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManagerTest.java @@ -20,15 +20,16 @@ import io.fabric8.kubernetes.client.Watcher; import io.fabric8.kubernetes.client.WatcherException; import io.fabric8.kubernetes.client.dsl.base.BaseOperation; +import io.fabric8.kubernetes.client.http.WebSocket; import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.Request; -import okhttp3.WebSocket; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import java.net.MalformedURLException; +import java.net.URL; +import java.util.Map; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicInteger; @@ -98,7 +99,7 @@ void closeWebSocket() { // When WatchConnectionManager.closeWebSocket(webSocket); // Then - verify(webSocket, times(1)).close(1000, null); + verify(webSocket, times(1)).sendClose(1000, null); } @Test @@ -201,9 +202,9 @@ public WatchManager(Watcher watcher, ListOptions listOptions, int reconnectLi } @Override - protected void run(Request request) { - + protected void run(URL url, Map headers) { } + @Override protected void closeRequest() { diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/RawCustomResourceOperationsImplTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/RawCustomResourceOperationsImplTest.java index be49431400c..634de087430 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/RawCustomResourceOperationsImplTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/RawCustomResourceOperationsImplTest.java @@ -21,21 +21,16 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; +import io.fabric8.kubernetes.client.SimpleClientContext; import io.fabric8.kubernetes.client.Watch; import io.fabric8.kubernetes.client.Watcher; import io.fabric8.kubernetes.client.WatcherException; import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.http.WebSocket; import io.fabric8.kubernetes.client.utils.Serialization; -import okhttp3.Call; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import okhttp3.WebSocket; -import okhttp3.WebSocketListener; -import okio.Buffer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -44,37 +39,54 @@ import org.mockito.invocation.InvocationOnMock; import java.io.IOException; +import java.io.InputStream; import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URL; import java.util.Collections; import java.util.Map; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; +import static io.fabric8.kubernetes.client.MockHttpClientUtils.buildResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class RawCustomResourceOperationsImplTest { - private OkHttpClient mockClient; + private HttpClient mockClient; + private HttpRequest.Builder mockRequestBuilder; + private HttpRequest mockRequest; private Config config; private CustomResourceDefinitionContext namespacedCustomResourceDefinitionContext; private RawCustomResourceOperationsImpl namespacedOperations; private RawCustomResourceOperationsImpl clusterOperations; - private ArgumentCaptor captor; + private ArgumentCaptor requestCaptor; + private ArgumentCaptor urlCaptor; + private ArgumentCaptor bodyCaptor; @BeforeEach public void setUp() throws IOException { - mockClient = Mockito.mock(OkHttpClient.class, Mockito.RETURNS_DEEP_STUBS); + mockClient = Mockito.mock(HttpClient.class, Mockito.RETURNS_DEEP_STUBS); + mockRequestBuilder = Mockito.mock(HttpRequest.Builder.class, Mockito.RETURNS_SELF); + mockRequest = Mockito.mock(HttpRequest.class); + when(mockRequest.uri()).thenAnswer(uri -> { + ArgumentCaptor urlCaptor = ArgumentCaptor.forClass(URL.class); + verify(mockRequestBuilder, atLeastOnce()).url(urlCaptor.capture()); + return urlCaptor.getValue().toURI(); + }); + when(mockRequestBuilder.build()).thenReturn(mockRequest); + when(mockClient.newHttpRequestBuilder()).thenReturn(mockRequestBuilder); config = new ConfigBuilder().withMasterUrl("https://localhost:8443/").build(); namespacedCustomResourceDefinitionContext = new CustomResourceDefinitionContext.Builder() .withGroup("test.fabric8.io") @@ -90,9 +102,11 @@ public void setUp() throws IOException { .withScope("Cluster") .withVersion("v1alpha1") .build(); - namespacedOperations = new RawCustomResourceOperationsImpl(mockClient, config, namespacedCustomResourceDefinitionContext); - clusterOperations = new RawCustomResourceOperationsImpl(mockClient, config, clusterCustomResourceDefinitionContext); - captor = ArgumentCaptor.forClass(Request.class); + namespacedOperations = new RawCustomResourceOperationsImpl(new SimpleClientContext(config, mockClient), namespacedCustomResourceDefinitionContext); + clusterOperations = new RawCustomResourceOperationsImpl(new SimpleClientContext(config, mockClient), clusterCustomResourceDefinitionContext); + requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); + urlCaptor = ArgumentCaptor.forClass(URL.class); + bodyCaptor = ArgumentCaptor.forClass(String.class); } @Test @@ -271,7 +285,7 @@ void testCreateOrReplaceWithConflict() throws IOException { .isNotNull() .hasFieldOrPropertyWithValue("metadata.resourceVersion", "replaced"); assertRequestCaptured(0, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos", "POST"); - assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/myresource", "PUT"); + assertRequestCaptured(1, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/myresource", "PUT"); } @Test @@ -305,7 +319,7 @@ void testDeleteWithNamespaceForNonExistentResource() throws IOException { // Then assertTrue(result); // delete()->deleteList() always returns true assertRequestCaptured(0, "/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos", "GET"); - assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos/hello", "DELETE"); + assertRequestCaptured(1, "/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos/hello", "DELETE"); } @Test @@ -326,7 +340,7 @@ void testDeleteWithNamespaceAndCascadingForNonExistentResource() throws IOExcept // Then assertTrue(result); // delete()->deleteList() always returns true assertRequestCaptured(0, "/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos", "GET"); - assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos/hello", "DELETE"); + assertRequestCaptured(1, "/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos/hello", "DELETE"); } @Test @@ -347,7 +361,7 @@ void testDeleteWithNamespaceAndDeleteOptionsForNonExistentResource() throws IOEx // Then assertTrue(result); // delete()->deleteList() always returns true assertRequestCaptured(0, "/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos", "GET"); - assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos/hello", "DELETE"); + assertRequestCaptured(1, "/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos/hello", "DELETE"); } @Test @@ -438,7 +452,7 @@ void testGetConfigShouldNotReturnNull() { .withWatchReconnectLimit(1) .withWatchReconnectInterval(10) .build(); - RawCustomResourceOperationsImpl rawOp = new RawCustomResourceOperationsImpl(mockClient, config, namespacedCustomResourceDefinitionContext); + RawCustomResourceOperationsImpl rawOp = new RawCustomResourceOperationsImpl(new SimpleClientContext(config, mockClient), namespacedCustomResourceDefinitionContext); // When Config configFromRawOp = rawOp.getConfig(); @@ -464,7 +478,7 @@ void testDryRunDelete() throws IOException { // Then assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/myresource", "DELETE"); - assertEquals("dryRun=All", captor.getValue().url().encodedQuery()); + assertEquals("dryRun=All", urlCaptor.getValue().getQuery()); } @Test @@ -476,9 +490,7 @@ void deleteWithGracePeriod() throws IOException { namespacedOperations.inNamespace("myns").withName("myresource").withGracePeriod(1337L).delete(); // Then assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/myresource", "DELETE"); - final Buffer b = new Buffer(); - captor.getValue().body().writeTo(b); - assertThat(b.readUtf8()).contains("\"gracePeriodSeconds\":1337"); + assertThat(bodyCaptor.getValue()).contains("\"gracePeriodSeconds\":1337"); } @Test @@ -491,9 +503,7 @@ void deleteWithPropagationPolicy() throws IOException { .withPropagationPolicy(DeletionPropagation.FOREGROUND).delete(); // Then assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/myresource", "DELETE"); - final Buffer b = new Buffer(); - captor.getValue().body().writeTo(b); - assertThat(b.readUtf8()).contains("\"propagationPolicy\":\"Foreground\""); + assertThat(bodyCaptor.getValue()).contains("\"propagationPolicy\":\"Foreground\""); } @Test @@ -506,7 +516,7 @@ void testDryRunCreate() throws IOException { // Then assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos", "POST"); - assertEquals("dryRun=All", captor.getValue().url().encodedQuery()); + assertEquals("dryRun=All", urlCaptor.getValue().getQuery()); } @Test @@ -543,7 +553,7 @@ void testListWithLimitAndContinue() throws IOException { // Then assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos", "GET"); - assertEquals("limit=4&continue=eyJ2IjoibWV0YS5rOHMuaW8vdj", captor.getValue().url().encodedQuery()); + assertEquals("limit=4&continue=eyJ2IjoibWV0YS5rOHMuaW8vdj", urlCaptor.getValue().getQuery()); } @Test @@ -556,7 +566,7 @@ void testListWithListOptions() throws IOException { // Then assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos", "GET"); - assertEquals("limit=4", captor.getValue().url().encodedQuery()); + assertEquals("limit=4", urlCaptor.getValue().getQuery()); } @Test @@ -569,7 +579,7 @@ void testListWithLabels() throws IOException { // Then assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos", "GET"); - assertEquals("labelSelector=foo%3Dbar", captor.getValue().url().encodedQuery()); + assertEquals("labelSelector=foo%3Dbar", urlCaptor.getValue().getQuery()); } @Test @@ -591,7 +601,7 @@ void testDeleteInSpecifiedNamespace() throws IOException { // Then assertRequestCaptured(0, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos", "GET"); assertRequestCaptured(1, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/one", "DELETE"); - assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/two", "DELETE"); + assertRequestCaptured(2, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/two", "DELETE"); } @Test @@ -613,7 +623,7 @@ void testDeleteInAllNamespaces() throws IOException { // Then assertRequestCaptured(0, "/apis/test.fabric8.io/v1alpha1/hellos", "GET"); assertRequestCaptured(1, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/one", "DELETE"); - assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/two", "DELETE"); + assertRequestCaptured(2, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/two", "DELETE"); } @Test @@ -647,7 +657,7 @@ void testClusterScopeDeletionAll() throws IOException { // Then assertRequestCaptured(0, "/apis/test.fabric8.io/v1alpha1/hellos", "GET"); assertRequestCaptured(1, "/apis/test.fabric8.io/v1alpha1/hellos/one", "DELETE"); - assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/hellos/two", "DELETE"); + assertRequestCaptured(2, "/apis/test.fabric8.io/v1alpha1/hellos/two", "DELETE"); } @Test @@ -669,7 +679,7 @@ void testDeleteByNamespaceOrNameWithNamespacedScopedCRD() throws IOException { // Then assertRequestCaptured(0, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos", "GET"); assertRequestCaptured(1, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/one", "DELETE"); - assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/two", "DELETE"); + assertRequestCaptured(2, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/two", "DELETE"); } @Test @@ -691,7 +701,7 @@ void testDeleteByNamespaceOrNameWithCascadingWithNamespacedScopedCRD() throws IO // Then assertRequestCaptured(0, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos", "GET"); assertRequestCaptured(1, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/one", "DELETE"); - assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/two", "DELETE"); + assertRequestCaptured(2, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/two", "DELETE"); } @Test @@ -714,7 +724,7 @@ void testDeleteByNamespaceOrNameWithDeleteOptionsWithNamespacedScopedCRD() throw // Then assertRequestCaptured(0, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos", "GET"); assertRequestCaptured(1, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/one", "DELETE"); - assertRequestCaptured("/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/two", "DELETE"); + assertRequestCaptured(2, "/apis/test.fabric8.io/v1alpha1/namespaces/myns/hellos/two", "DELETE"); } @Test @@ -765,7 +775,7 @@ void testGetConfigmap() throws IOException { .withScope("Namespaced") .withKind("ConfigMap") .build(); - RawCustomResourceOperationsImpl rawOp = new RawCustomResourceOperationsImpl(mockClient, config, configMapContext); + RawCustomResourceOperationsImpl rawOp = new RawCustomResourceOperationsImpl(new SimpleClientContext(config, mockClient), configMapContext); // When Map unstructuredConfigMap = rawOp.inNamespace("default").withName("game-config").get(); @@ -793,12 +803,14 @@ void testEditCR() throws IOException { void watch() throws IOException { // Given final AtomicReference eventReceived = new AtomicReference<>(); - when(mockClient.newBuilder().readTimeout(anyLong(), any()).build().newWebSocket(any(), any())).thenAnswer(i -> { + WebSocket.Builder builder = Mockito.mock(WebSocket.Builder.class, Mockito.RETURNS_SELF); + when(mockClient.newBuilder().readTimeout(anyLong(), any()).build().newWebSocketBuilder()).thenReturn(builder); + when(builder.buildAsync(any())).thenAnswer(i -> { final WebSocket webSocket = mock(WebSocket.class); - ((WebSocketListener)i.getArguments()[1]).onOpen(webSocket, mock(Response.class)); - ((WebSocketListener)i.getArguments()[1]) + ((WebSocket.Listener)i.getArguments()[0]).onOpen(webSocket); + ((WebSocket.Listener)i.getArguments()[0]) .onMessage(webSocket, "{\"type\":\"ADDED\", \"object\":{\"kind\": \"Hello\", \"metadata\": {\"name\": \"test\"}}}"); - return webSocket; + return CompletableFuture.completedFuture(webSocket); }); // When final Watch result = clusterOperations.watch(new Watcher() { @@ -813,12 +825,9 @@ public void onClose(WatcherException cause) { } }); // Then - verify(mockClient.newBuilder().readTimeout(anyLong(), any()).build(), times(1)) - .newWebSocket(captor.capture(), any()); assertThat(eventReceived).hasValue("{\"kind\":\"Hello\",\"metadata\":{\"name\":\"test\"}}"); assertThat(result).isNotNull(); - assertThat(captor.getValue().url()) - .hasToString("https://localhost:8443/apis/test.fabric8.io/v1alpha1/hellos?watch=true"); + verify(builder, Mockito.times(1)).uri(URI.create("https://localhost:8443/apis/test.fabric8.io/v1alpha1/hellos?watch=true")); } private void mockCallWithResponse(int code) throws IOException { @@ -831,11 +840,10 @@ private void mockCallWithResponse(int code, String body) throws IOException { @SafeVarargs private final void mockCallWithResponse( - Function response, Function... responses) + Function> response, Function>... responses) throws IOException { - Call mockCall = mock(Call.class); final AtomicInteger invocationCount = new AtomicInteger(-1); - when(mockCall.execute()).thenAnswer(invocation -> { + when(mockClient.send(any(), any())).thenAnswer(invocation -> { final int current = invocationCount.getAndIncrement(); if (current == -1 || responses.length == 0){ return response.apply(invocation); @@ -844,32 +852,30 @@ private final void mockCallWithResponse( } return responses[responses.length - 1].apply(invocation); }); - when(mockClient.newCall(any())).thenReturn(mockCall); - } - - private Response buildResponse(int code) { - return buildResponse(code, "{\"kind\":\"Status\",\"status\":\"Success\"}"); - } - - private Response buildResponse(int code, String body) { - return new Response.Builder() - .request(new Request.Builder().url("http://mock").build()) - .protocol(Protocol.HTTP_1_1) - .code(code) - .body(ResponseBody.create(MediaType.get("application/json"), body)) - .message("mock") - .build(); - } - - private void assertRequestCaptured(int order, String url, String method) { - verify(mockClient, atLeastOnce()).newCall(captor.capture()); - assertEquals(url, captor.getAllValues().get(order).url().encodedPath()); - assertEquals(method, captor.getAllValues().get(order).method()); } - private void assertRequestCaptured(String url, String method) { - verify(mockClient, atLeastOnce()).newCall(captor.capture()); - assertEquals(url, captor.getValue().url().encodedPath()); - assertEquals(method, captor.getValue().method()); + private void assertRequestCaptured(int order, String url, String method) throws IOException { + verify(mockClient, atLeastOnce()).send(requestCaptor.capture(), any()); + switch (method) { + case "PUT": + verify(mockRequestBuilder, atLeastOnce()).put(any(), bodyCaptor.capture()); + break; + case "POST": + verify(mockRequestBuilder, atLeastOnce()).post(any(), bodyCaptor.capture()); + break; + case "GET": + break; + case "DELETE": + verify(mockRequestBuilder, atLeastOnce()).delete(any(), bodyCaptor.capture()); + break; + default: + throw new AssertionError(); + } + verify(mockRequestBuilder, atLeastOnce()).url(urlCaptor.capture()); + assertEquals(url, urlCaptor.getAllValues().get(order).getPath()); + } + + private void assertRequestCaptured(String url, String method) throws IOException { + assertRequestCaptured(0, url, method); } } diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/BindingOperationsImplTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/BindingOperationsImplTest.java index 02a3533c70d..4d25dba04a6 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/BindingOperationsImplTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/core/v1/BindingOperationsImplTest.java @@ -15,6 +15,7 @@ */ package io.fabric8.kubernetes.client.dsl.internal.core.v1; +import io.fabric8.kubernetes.client.SimpleClientContext; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -24,7 +25,7 @@ class BindingOperationsImplTest { @Test void canBeInstantiated() { // When - final BindingOperationsImpl result = new BindingOperationsImpl(null, null); + final BindingOperationsImpl result = new BindingOperationsImpl(new SimpleClientContext(), null); // Then assertThat(result).isNotNull(); } diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadTest.java index af4e190fdbd..65bf7bf95e2 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadTest.java @@ -20,17 +20,18 @@ import java.io.File; import java.io.IOException; import java.net.URL; +import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.Arrays; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.ObjIntConsumer; import io.fabric8.kubernetes.client.dsl.base.OperationSupport; import io.fabric8.kubernetes.client.dsl.internal.PodOperationContext; -import okhttp3.OkHttpClient; -import okhttp3.WebSocket; -import okio.ByteString; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.WebSocket; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -51,7 +52,7 @@ class PodUploadTest { - private OkHttpClient mockClient; + private HttpClient mockClient; private PodOperationContext mockContext; private OperationSupport operationSupport; private Path mockPathToUpload; @@ -59,7 +60,7 @@ class PodUploadTest { @BeforeEach void setUp() throws IOException { - mockClient = Mockito.mock(OkHttpClient.class, Mockito.RETURNS_DEEP_STUBS); + mockClient = Mockito.mock(HttpClient.class, Mockito.RETURNS_DEEP_STUBS); mockContext = Mockito.mock(PodOperationContext.class, Mockito.RETURNS_DEEP_STUBS); operationSupport = Mockito.mock(OperationSupport.class, Mockito.RETURNS_DEEP_STUBS); mockPathToUpload = Mockito.mock(Path.class, Mockito.RETURNS_DEEP_STUBS); @@ -92,31 +93,32 @@ void testUploadFileHappyScenarioShouldUploadFile() throws Exception { when(mockContext.getFile()).thenReturn("/mock/dir/file"); when(mockPathToUpload.toFile()) .thenReturn(new File(PodUpload.class.getResource("/upload/upload-sample.txt").getFile())); - when(mockClient.newWebSocket(any(), any())).thenAnswer(newWebSocket -> { - final PodUploadWebSocketListener wsl = newWebSocket.getArgument(1, PodUploadWebSocketListener.class); + WebSocket.Builder builder = Mockito.mock(WebSocket.Builder.class, Mockito.RETURNS_SELF); + when(builder.buildAsync(any())).thenAnswer(newWebSocket -> { + final PodUploadWebSocketListener wsl = newWebSocket.getArgument(0, PodUploadWebSocketListener.class); // Set ready status - wsl.onOpen(mockWebSocket, null); - wsl.onMessage(mockWebSocket, ByteString.of((byte) 0)); + wsl.onOpen(mockWebSocket); + wsl.onMessage(mockWebSocket, ByteBuffer.wrap(new byte[] {(byte) 0})); // Set complete status - when(mockWebSocket.close(anyInt(), anyString())).thenAnswer(close -> { - wsl.onClosed(mockWebSocket, close.getArgument(0), close.getArgument(1)); - return true; - }); - return mockWebSocket; + Mockito.doAnswer(close -> { + wsl.onClose(mockWebSocket, close.getArgument(0), close.getArgument(1)); + return null; + }).when(mockWebSocket).sendClose(anyInt(), anyString()); + return CompletableFuture.completedFuture(mockWebSocket); }); + when(mockClient.newWebSocketBuilder()).thenReturn(builder); final boolean result = PodUpload.upload(mockClient, mockContext, operationSupport, mockPathToUpload); assertThat(result, equalTo(true)); verify(mockPathToUpload, atLeast(1)).toFile(); - verify(mockClient, times(1)).newWebSocket(argThat(request -> { - assertThat(request.url().toString(), equalTo("https://openshift.com:8443/api/v1/namespaces/default/pods/mock-pod/exec?command=sh&command=-c&command=mkdir+-p+%27%2Fmock%2Fdir%27+%26%26+base64+-d+-+%3E+%27%2Fmock%2Fdir%2Ffile%27&stdin=true&stderr=true")); + verify(builder, times(1)).uri(argThat(request -> { + assertThat(request.toString(), equalTo("https://openshift.com:8443/api/v1/namespaces/default/pods/mock-pod/exec?command=sh&command=-c&command=mkdir+-p+%27%2Fmock%2Fdir%27+%26%26+base64+-d+-+%3E+%27%2Fmock%2Fdir%2Ffile%27&stdin=true&stderr=true")); return true; - }), any(PodUploadWebSocketListener.class)); - verify(mockWebSocket, atLeast(1)).send(any(ByteString.class)); - verify(mockWebSocket, times(0)).send(anyString()); + })); + verify(mockWebSocket, atLeast(1)).send(any(ByteBuffer.class)); } - + @Test void testUploadDirectoryHappyScenarioShouldUploadDirectory() throws Exception { uploadDirectoryAndVerify("/upload"); @@ -131,29 +133,30 @@ private void uploadDirectoryAndVerify(String resourcePath) throws IOException, I when(mockContext.getDir()).thenReturn("/mock/dir"); when(mockPathToUpload.toFile()) .thenReturn(new File(PodUpload.class.getResource(resourcePath).getFile())); - when(mockClient.newWebSocket(any(), any())).thenAnswer(newWebSocket -> { - final PodUploadWebSocketListener wsl = newWebSocket.getArgument(1, PodUploadWebSocketListener.class); + WebSocket.Builder builder = Mockito.mock(WebSocket.Builder.class, Mockito.RETURNS_SELF); + when(builder.buildAsync(any())).thenAnswer(newWebSocket -> { + final PodUploadWebSocketListener wsl = newWebSocket.getArgument(0, PodUploadWebSocketListener.class); // Set ready status - wsl.onOpen(mockWebSocket, null); - wsl.onMessage(mockWebSocket, ByteString.of((byte) 0)); + wsl.onOpen(mockWebSocket); + wsl.onMessage(mockWebSocket, ByteBuffer.wrap(new byte[] {(byte) 0})); // Set complete status - when(mockWebSocket.close(anyInt(), anyString())).thenAnswer(close -> { - wsl.onClosed(mockWebSocket, close.getArgument(0), close.getArgument(1)); - return true; - }); - return mockWebSocket; + Mockito.doAnswer(close -> { + wsl.onClose(mockWebSocket, close.getArgument(0), close.getArgument(1)); + return null; + }).when(mockWebSocket).sendClose(anyInt(), anyString()); + return CompletableFuture.completedFuture(mockWebSocket); }); + when(mockClient.newWebSocketBuilder()).thenReturn(builder); final boolean result = PodUpload.upload(mockClient, mockContext, operationSupport, mockPathToUpload); assertThat(result, equalTo(true)); verify(mockPathToUpload, atLeast(1)).toFile(); - verify(mockClient, times(1)).newWebSocket(argThat(request -> { - assertThat(request.url().toString(), equalTo("https://openshift.com:8443/api/v1/namespaces/default/pods/mock-pod/exec?command=sh&command=-c&command=mkdir+-p+%27%2Fmock%2Fdir%27+%26%26+base64+-d+-+%7C+tar+-C+%27%2Fmock%2Fdir%27+-xzf+-&stdin=true&stderr=true")); + verify(builder, times(1)).uri(argThat(request -> { + assertThat(request.toString(), equalTo("https://openshift.com:8443/api/v1/namespaces/default/pods/mock-pod/exec?command=sh&command=-c&command=mkdir+-p+%27%2Fmock%2Fdir%27+%26%26+base64+-d+-+%7C+tar+-C+%27%2Fmock%2Fdir%27+-xzf+-&stdin=true&stderr=true")); return true; - }), any(PodUploadWebSocketListener.class)); - verify(mockWebSocket, atLeast(1)).send(any(ByteString.class)); - verify(mockWebSocket, times(0)).send(anyString()); + })); + verify(mockWebSocket, atLeast(1)).send(any(ByteBuffer.class)); } @Test diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadWebSocketListenerTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadWebSocketListenerTest.java index b640a86bf66..6a3b23ce887 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadWebSocketListenerTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/uploadable/PodUploadWebSocketListenerTest.java @@ -16,18 +16,18 @@ package io.fabric8.kubernetes.client.dsl.internal.uploadable; import io.fabric8.kubernetes.client.KubernetesClientException; -import okhttp3.Response; -import okhttp3.WebSocket; -import okio.ByteString; +import io.fabric8.kubernetes.client.http.WebSocket; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.io.IOException; +import java.nio.ByteBuffer; + import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.times; class PodUploadWebSocketListenerTest { @@ -47,30 +47,25 @@ void tearDown() { @Test void testSendShouldTruncateAndSendFlaggedWebSocketData() { final WebSocket mockedWebSocket = Mockito.mock(WebSocket.class); - podUploadWebSocketListener.onOpen(mockedWebSocket, null); + podUploadWebSocketListener.onOpen(mockedWebSocket); final byte[] toSend = new byte[]{1, 3, 3, 7, 0}; podUploadWebSocketListener.send(toSend, 4); verify(mockedWebSocket, times(1)) - .send(eq(ByteString.of((byte) 0, (byte) 1, (byte) 3, (byte) 3, (byte) 7))); + .send(eq(ByteBuffer.wrap(new byte[] {(byte) 0, (byte) 1, (byte) 3, (byte) 3, (byte) 7}))); } @Test() void testCheckErrorHasErrorFromMessageShouldThrowException() { - podUploadWebSocketListener.onMessage(null, ByteString.encodeUtf8("ACK")); - podUploadWebSocketListener.onMessage(null, ByteString.encodeUtf8("![\"I'M AN ERROR\"]")); + podUploadWebSocketListener.onMessage(null, ByteBuffer.wrap("Error".getBytes())); assertThrows(KubernetesClientException.class, () -> podUploadWebSocketListener.checkError()); } @Test() void testCheckErrorHasErrorFromFailureShouldThrowException() { - final Response mockResponse = Mockito.mock(Response.class, Mockito.RETURNS_DEEP_STUBS); - when(mockResponse.code()).thenReturn(1337); - when(mockResponse.message()).thenReturn("Error"); - when(mockResponse.body().toString()).thenReturn("Detailed error description"); - podUploadWebSocketListener.onFailure(null, null, mockResponse); + podUploadWebSocketListener.onError(null, new IOException("here")); assertThrows(KubernetesClientException.class, () -> podUploadWebSocketListener.checkError()); } diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/extended/run/RunOperationsTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/extended/run/RunOperationsTest.java index 0030a0407bf..4d7420f52f3 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/extended/run/RunOperationsTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/extended/run/RunOperationsTest.java @@ -19,7 +19,8 @@ import io.fabric8.kubernetes.api.model.Quantity; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.SimpleClientContext; +import io.fabric8.kubernetes.client.http.HttpClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -32,12 +33,12 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; class RunOperationsTest { - private OkHttpClient mockClient; + private HttpClient mockClient; private Config config; @BeforeEach public void init() { - this.mockClient = Mockito.mock(OkHttpClient.class, Mockito.RETURNS_DEEP_STUBS); + this.mockClient = Mockito.mock(HttpClient.class, Mockito.RETURNS_DEEP_STUBS); this.config = new ConfigBuilder().withMasterUrl("https://localhost:8443/").build(); } @@ -64,7 +65,7 @@ void testConvertRunConfigIntoPod() { .withPort(5701) .withLimits(limits) .withRequests(requests); - RunOperations deploymentGenerator = new RunOperations(mockClient, config, "ns1", generatorRunConfig); + RunOperations deploymentGenerator = new RunOperations(new SimpleClientContext(config, mockClient), "ns1", generatorRunConfig); // When Pod pod = deploymentGenerator.convertRunConfigIntoPod(); diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/informers/SharedInformerFactoryTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/informers/SharedInformerFactoryTest.java index cfa4a34c311..8cac50f71ee 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/informers/SharedInformerFactoryTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/informers/SharedInformerFactoryTest.java @@ -15,15 +15,12 @@ */ package io.fabric8.kubernetes.client.informers; -import com.fasterxml.jackson.databind.jsontype.DefaultBaseTypeLimitingValidator; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.Secret; import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.client.BaseKubernetesClient; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext; @@ -33,7 +30,6 @@ import io.fabric8.kubernetes.model.annotation.Plural; import io.fabric8.kubernetes.model.annotation.ShortNames; import io.fabric8.kubernetes.model.annotation.Version; -import okhttp3.OkHttpClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/internal/okhttp/OkHttpClientFactoryTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/internal/okhttp/OkHttpClientFactoryTest.java new file mode 100644 index 00000000000..b4378b7ed4a --- /dev/null +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/internal/okhttp/OkHttpClientFactoryTest.java @@ -0,0 +1,59 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.kubernetes.client.internal.okhttp; + +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ConfigBuilder; +import io.fabric8.kubernetes.client.okhttp.OkHttpClientFactory; +import io.fabric8.kubernetes.client.okhttp.OkHttpClientImpl; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class OkHttpClientFactoryTest { + + @Test + void shouldRespectMaxRequests() { + OkHttpClientImpl client = new OkHttpClientFactory().createHttpClient(new ConfigBuilder().build()); + + assertEquals(64, client.getOkHttpClient().dispatcher().getMaxRequests()); + + Config config = new ConfigBuilder() + .withMaxConcurrentRequests(120) + .build(); + + client = new OkHttpClientFactory().createHttpClient(config); + assertEquals(120, client.getOkHttpClient().dispatcher().getMaxRequests()); + } + + @Test + void shouldRespectMaxRequestsPerHost() { + OkHttpClientImpl client = new OkHttpClientFactory().createHttpClient(new ConfigBuilder().build()); + + assertEquals(5, client.getOkHttpClient().dispatcher().getMaxRequestsPerHost()); + + Config config = new ConfigBuilder() + .withMaxConcurrentRequestsPerHost(20) + .build(); + + client = new OkHttpClientFactory().createHttpClient(config); + + assertEquals(20, client.getOkHttpClient().dispatcher().getMaxRequestsPerHost()); + } + + +} diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/HttpClientUtilsTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/HttpClientUtilsTest.java index 398d75f6c4a..9e93c6b26ed 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/HttpClientUtilsTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/HttpClientUtilsTest.java @@ -17,10 +17,10 @@ import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; -import okhttp3.Interceptor; +import io.fabric8.kubernetes.client.http.Interceptor; import org.junit.jupiter.api.Test; -import java.util.List; +import java.util.Collection; import static io.fabric8.kubernetes.client.utils.HttpClientUtils.KUBERNETES_BACKWARDS_COMPATIBILITY_INTERCEPTOR_DISABLE; import static org.assertj.core.api.Assertions.assertThat; @@ -32,7 +32,7 @@ void testCreateApplicableInterceptors() { Config config = new ConfigBuilder().build(); // When - List interceptorList = HttpClientUtils.createApplicableInterceptors(config); + Collection interceptorList = HttpClientUtils.createApplicableInterceptors(config, null).values(); // Then assertThat(interceptorList) @@ -50,7 +50,7 @@ void testCreateApplicableInterceptorsWithBackwardsCompatibilityDisabled() { System.setProperty(KUBERNETES_BACKWARDS_COMPATIBILITY_INTERCEPTOR_DISABLE, "true"); // When - List interceptorList = HttpClientUtils.createApplicableInterceptors(config); + Collection interceptorList = HttpClientUtils.createApplicableInterceptors(config, null).values(); // Then assertThat(interceptorList) diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/IpAddressMatcherTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/IpAddressMatcherTest.java index 3d856440d0d..5ec46ffadf2 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/IpAddressMatcherTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/IpAddressMatcherTest.java @@ -16,13 +16,14 @@ package io.fabric8.kubernetes.client.utils; import io.fabric8.kubernetes.client.Config; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class IpAddressMatcherTest { @Test diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsTest.java index 57c87f2a93c..7fc20f17a85 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsTest.java @@ -16,14 +16,9 @@ package io.fabric8.kubernetes.client.utils; import io.fabric8.kubernetes.api.model.NamedContext; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpResponse; import io.fabric8.kubernetes.client.internal.KubeConfigUtils; -import okhttp3.Call; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -48,11 +43,10 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class OpenIDConnectionUtilsTest { - OkHttpClient mockClient = Mockito.mock(OkHttpClient.class, Mockito.RETURNS_DEEP_STUBS); + HttpClient mockClient = Mockito.mock(HttpClient.class, Mockito.RETURNS_DEEP_STUBS); @Test void testLoadTokenURL() throws IOException { @@ -174,7 +168,7 @@ void testResolveOIDCTokenFromAuthConfigShouldReturnOldTokenWhenRefreshNotSupport currentAuthProviderConfig.put(ID_TOKEN_KUBECONFIG, "id-token"); // When - String token = OpenIDConnectionUtils.resolveOIDCTokenFromAuthConfig(currentAuthProviderConfig); + String token = OpenIDConnectionUtils.resolveOIDCTokenFromAuthConfig(currentAuthProviderConfig, null); // Then assertEquals("id-token", token); @@ -194,20 +188,14 @@ void testgetParametersFromDiscoveryResponse() { } private void mockOkHttpClient(int responseCode, String responseAsStr) throws IOException { - Call mockCall = mock(Call.class); - Response mockSuccessResponse = mockResponse(responseCode, responseAsStr); - when(mockCall.execute()) - .thenReturn(mockSuccessResponse); - when(mockClient.newCall(any())).thenReturn(mockCall); + HttpResponse mockSuccessResponse = mockResponse(responseCode, responseAsStr); + when(mockClient.send(any(), Mockito.eq(String.class))).thenReturn(mockSuccessResponse); } - private Response mockResponse(int responseCode, String responseBody) { - return new Response.Builder() - .request(new Request.Builder().url("http://mock").build()) - .protocol(Protocol.HTTP_1_1) - .code(responseCode) - .body(ResponseBody.create(MediaType.get("application/json"), responseBody)) - .message("mock") - .build(); + private HttpResponse mockResponse(int responseCode, String responseBody) { + HttpResponse response = Mockito.mock(HttpResponse.class, Mockito.CALLS_REAL_METHODS); + Mockito.when(response.code()).thenReturn(responseCode); + Mockito.when(response.body()).thenReturn(responseBody); + return response; } } diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/TokenRefreshInterceptorTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/TokenRefreshInterceptorTest.java index 886245e7e08..ce6a059d7d5 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/TokenRefreshInterceptorTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/utils/TokenRefreshInterceptorTest.java @@ -16,12 +16,8 @@ package io.fabric8.kubernetes.client.utils; import io.fabric8.kubernetes.client.Config; -import okhttp3.Interceptor; -import okhttp3.MediaType; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -33,10 +29,15 @@ import java.nio.file.StandardCopyOption; import java.util.Objects; -import static io.fabric8.kubernetes.client.Config.KUBERNETES_KUBECONFIG_FILE; import static io.fabric8.kubernetes.client.Config.KUBERNETES_AUTH_SERVICEACCOUNT_TOKEN_FILE_SYSTEM_PROPERTY; import static io.fabric8.kubernetes.client.Config.KUBERNETES_AUTH_TRYKUBECONFIG_SYSTEM_PROPERTY; +import static io.fabric8.kubernetes.client.Config.KUBERNETES_KUBECONFIG_FILE; +import static io.fabric8.kubernetes.client.MockHttpClientUtils.buildResponse; +import static org.junit.jupiter.api.Assertions.assertTrue; +/** + * Ignoring for now - the token refresh should be based upon the java 11 client or the provided client library and not okhttp + */ public class TokenRefreshInterceptorTest { @Test @@ -47,20 +48,12 @@ public void shouldAutoconfigureAfter401() throws IOException { Files.copy(Objects.requireNonNull(getClass().getResourceAsStream("/test-kubeconfig-tokeninterceptor")), Paths.get(tempFile.getPath()), StandardCopyOption.REPLACE_EXISTING); System.setProperty(KUBERNETES_KUBECONFIG_FILE, tempFile.getAbsolutePath()); - // Prepare http call - Interceptor.Chain chain = Mockito.mock(Interceptor.Chain.class, Mockito.RETURNS_DEEP_STUBS); - Request req = new Request.Builder().url("http://mock").build(); - Mockito.when(chain.request()).thenReturn(req); - final Response.Builder responseBuilder = new Response.Builder() - .request(req) - .protocol(Protocol.HTTP_1_1) - .message("") - .body(ResponseBody.create(MediaType.parse("text"), "foo")); - Mockito.when(chain.proceed(Mockito.any())).thenReturn(responseBuilder.code(HttpURLConnection.HTTP_UNAUTHORIZED).build(), responseBuilder.code(HttpURLConnection.HTTP_OK).build()); + HttpRequest.Builder builder = Mockito.mock(HttpRequest.Builder.class, Mockito.RETURNS_SELF); // Call - new TokenRefreshInterceptor(Config.autoConfigure(null)).intercept(chain); - Mockito.verify(chain).proceed(Mockito.argThat(argument -> "Bearer token".equals(argument.header("Authorization")))); + boolean reissue = new TokenRefreshInterceptor(Config.autoConfigure(null), null).afterFailure(builder, buildResponse(HttpURLConnection.HTTP_UNAUTHORIZED, "foo")); + Mockito.verify(builder).setHeader("Authorization", "Bearer token"); + assertTrue(reissue); } finally { // Remove any side effect System.clearProperty(KUBERNETES_KUBECONFIG_FILE); @@ -77,29 +70,18 @@ void shouldReloadInClusterServiceAccount() throws IOException { System.setProperty(KUBERNETES_AUTH_SERVICEACCOUNT_TOKEN_FILE_SYSTEM_PROPERTY, tokenFile.getAbsolutePath()); System.setProperty(KUBERNETES_AUTH_TRYKUBECONFIG_SYSTEM_PROPERTY, "false"); - // Prepare HTTP call that will fail with 401 Unauthorized to trigger service account token reload. - Interceptor.Chain chain = Mockito.mock(Interceptor.Chain.class, Mockito.RETURNS_DEEP_STUBS); - Request req = new Request.Builder().url("http://mock").build(); - Mockito.when(chain.request()).thenReturn(req); - final Response.Builder responseBuilder = new Response.Builder() - .request(req) - .protocol(Protocol.HTTP_1_1) - .message("") - .body(ResponseBody.create(MediaType.parse("text"), "foo")); - Mockito.when(chain.proceed(Mockito.any())).thenReturn( - responseBuilder.code(HttpURLConnection.HTTP_UNAUTHORIZED).build(), - responseBuilder.code(HttpURLConnection.HTTP_OK).build()); + HttpRequest.Builder builder = Mockito.mock(HttpRequest.Builder.class, Mockito.RETURNS_SELF); // The expired token will be read at auto configure. - TokenRefreshInterceptor interceptor = new TokenRefreshInterceptor(Config.autoConfigure(null)); + TokenRefreshInterceptor interceptor = new TokenRefreshInterceptor(Config.autoConfigure(null), null); // Write new value to token file to simulate renewal. Files.write(tokenFile.toPath(), "renewed".getBytes()); - interceptor.intercept(chain); + boolean reissue = interceptor.afterFailure(builder, buildResponse(HttpURLConnection.HTTP_UNAUTHORIZED, "foo")); // Make the call and check that renewed token was read at 401 Unauthorized. - Mockito.verify(chain) - .proceed(Mockito.argThat(argument -> "Bearer renewed".equals(argument.header("Authorization")))); + Mockito.verify(builder).setHeader("Authorization", "Bearer renewed"); + assertTrue(reissue); } finally { // Remove any side effect System.clearProperty(KUBERNETES_AUTH_SERVICEACCOUNT_TOKEN_FILE_SYSTEM_PROPERTY); @@ -117,16 +99,7 @@ void shouldRefreshOIDCToken() throws IOException { System.setProperty(KUBERNETES_KUBECONFIG_FILE, tempFile.getAbsolutePath()); // Prepare HTTP call that will fail with 401 Unauthorized to trigger OIDC token renewal. - Interceptor.Chain chain = Mockito.mock(Interceptor.Chain.class, Mockito.RETURNS_DEEP_STUBS); - Request req = new Request.Builder().url("http://mock").build(); - Mockito.when(chain.request()).thenReturn(req); - final Response.Builder responseBuilder = new Response.Builder() - .request(req).protocol(Protocol.HTTP_1_1) - .message("") - .body(ResponseBody.create(MediaType.parse("text"), "foo")); - Mockito.when(chain.proceed(Mockito.any())).thenReturn( - responseBuilder.code(HttpURLConnection.HTTP_UNAUTHORIZED).build(), - responseBuilder.code(HttpURLConnection.HTTP_OK).build()); + HttpRequest.Builder builder = Mockito.mock(HttpRequest.Builder.class, Mockito.RETURNS_SELF); // Loads the initial kubeconfig, including initial token value. Config config = Config.autoConfigure(null); @@ -140,11 +113,12 @@ void shouldRefreshOIDCToken() throws IOException { Files.copy(Objects.requireNonNull(getClass().getResourceAsStream("/test-kubeconfig-tokeninterceptor-oidc")), Paths.get(tempFile.getPath()), StandardCopyOption.REPLACE_EXISTING); - new TokenRefreshInterceptor(config).intercept(chain); + TokenRefreshInterceptor interceptor = new TokenRefreshInterceptor(config, Mockito.mock(HttpClient.Factory.class)); + boolean reissue = interceptor.afterFailure(builder, buildResponse(HttpURLConnection.HTTP_UNAUTHORIZED, "foo")); // Make the call and check that renewed token was read at 401 Unauthorized. - Mockito.verify(chain) - .proceed(Mockito.argThat(argument -> "Bearer renewed".equals(argument.header("Authorization")))); + Mockito.verify(builder).setHeader("Authorization", "Bearer renewed"); + assertTrue(reissue); } finally { // Remove any side effect. System.clearProperty(KUBERNETES_KUBECONFIG_FILE); diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/server/mock/KubernetesMockServer.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/server/mock/KubernetesMockServer.java index 50519d2ff81..fb2cef1bfac 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/server/mock/KubernetesMockServer.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/server/mock/KubernetesMockServer.java @@ -20,6 +20,7 @@ import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; +import io.fabric8.kubernetes.client.http.TlsVersion; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.mockwebserver.Context; import io.fabric8.mockwebserver.DefaultMockServer; @@ -31,9 +32,6 @@ import java.util.Map; import java.util.Queue; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; -import static okhttp3.TlsVersion.TLS_1_2; - @Deprecated // The class has moved under mvn:io.fabric8:kubernetes-server-mock in package: io.fabric8.client.server.mock public class KubernetesMockServer extends DefaultMockServer { @@ -65,6 +63,7 @@ public void destroy() { shutdown(); } + @Override public void onStart() { expect().get().withPath("/").andReturn(200, new RootPathsBuilder().addToPaths(getRootPaths()).build()).always(); } @@ -74,13 +73,18 @@ public String[] getRootPaths() { } public NamespacedKubernetesClient createClient() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .withNamespace("test") - .build(); - return new DefaultKubernetesClient(createHttpClientForMockServer(config), config); + Config config = getMockConfiguration(); + return new DefaultKubernetesClient(config); + } + + protected Config getMockConfiguration() { + return new ConfigBuilder() + .withMasterUrl(url("/")) + .withTrustCerts(true) + .withTlsVersions(TlsVersion.TLS_1_2) + .withNamespace("test") + .withHttp2Disable(true) + .build(); } diff --git a/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecExample.java b/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecExample.java index 7c89b349dbe..94f36302510 100644 --- a/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecExample.java +++ b/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecExample.java @@ -19,7 +19,6 @@ import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.ExecListener; import io.fabric8.kubernetes.client.dsl.ExecWatch; -import okhttp3.Response; /** * This is an example of entering a pod to execute a command. @@ -61,12 +60,12 @@ private static ExecWatch newExecWatch(KubernetesClient client, String namespace, private static class SimpleListener implements ExecListener { @Override - public void onOpen(Response response) { + public void onOpen() { System.out.println("The shell will remain open for 10 seconds."); } @Override - public void onFailure(Throwable t, Response response) { + public void onFailure(Throwable t, Response failureResponse) { System.err.println("shell barfed"); } diff --git a/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecExampleWithTerminalSize.java b/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecExampleWithTerminalSize.java index d03dfea95f5..e76ba1f5339 100644 --- a/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecExampleWithTerminalSize.java +++ b/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecExampleWithTerminalSize.java @@ -19,7 +19,6 @@ import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.ExecListener; import io.fabric8.kubernetes.client.dsl.ExecWatch; -import okhttp3.Response; @SuppressWarnings("java:S106") public class ExecExampleWithTerminalSize { @@ -67,12 +66,12 @@ private static ExecWatch newExecWatch(KubernetesClient client, String namespace, private static class SimpleListener implements ExecListener { @Override - public void onOpen(Response response) { + public void onOpen() { System.out.println("The shell will remain open for 10 seconds."); } @Override - public void onFailure(Throwable t, Response response) { + public void onFailure(Throwable t, Response failureResponse) { System.err.println("shell barfed"); } diff --git a/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecLoopExample.java b/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecLoopExample.java index 0f3198c1f7d..b855895a01f 100644 --- a/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecLoopExample.java +++ b/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecLoopExample.java @@ -20,7 +20,6 @@ import io.fabric8.kubernetes.client.dsl.ExecListener; import io.fabric8.kubernetes.client.dsl.ExecWatch; import io.fabric8.kubernetes.client.utils.InputStreamPumper; -import okhttp3.Response; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; @@ -56,11 +55,12 @@ public static void main(String[] args) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); watch = client.pods().inNamespace(namespace).withName(podName).redirectingOutput().usingListener(new ExecListener() { @Override - public void onOpen(Response response) { + public void onOpen() { + System.out.println("Open"); } @Override - public void onFailure(Throwable t, Response response) { + public void onFailure(Throwable t, Response failureResponse) { latch.countDown(); } diff --git a/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecuteCommandOnPodExample.java b/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecuteCommandOnPodExample.java index 9329d953237..7d2dcdc7a45 100644 --- a/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecuteCommandOnPodExample.java +++ b/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/ExecuteCommandOnPodExample.java @@ -22,10 +22,7 @@ import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.ExecListener; import io.fabric8.kubernetes.client.dsl.ExecWatch; -import io.fabric8.kubernetes.client.utils.HttpClientUtils; import lombok.SneakyThrows; -import okhttp3.OkHttpClient; -import okhttp3.Response; import java.io.ByteArrayOutputStream; import java.util.Arrays; @@ -35,19 +32,15 @@ @SuppressWarnings("java:S106") public class ExecuteCommandOnPodExample implements AutoCloseable { - private final OkHttpClient okHttpClient; private final KubernetesClient client; public ExecuteCommandOnPodExample() { Config config = new ConfigBuilder().build(); - this.okHttpClient = HttpClientUtils.createHttpClient(config); - this.client = new DefaultKubernetesClient(okHttpClient, config); + this.client = new DefaultKubernetesClient(config); } @Override public void close() { - okHttpClient.dispatcher().executorService().shutdown(); - okHttpClient.connectionPool().evictAll(); client.close(); } @@ -86,13 +79,13 @@ public SimpleListener(CompletableFuture data, ByteArrayOutputStream baos } @Override - public void onOpen(Response response) { - System.out.println("Reading data... " + response.message()); + public void onOpen() { + System.out.println("Reading data... "); } @Override - public void onFailure(Throwable t, Response response) { - System.err.println(t.getMessage() + " " + response.message()); + public void onFailure(Throwable t, Response failureResponse) { + System.err.println(t.getMessage()); data.completeExceptionally(t); } diff --git a/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/kubectl/equivalents/PodExecEquivalent.java b/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/kubectl/equivalents/PodExecEquivalent.java index e091846713a..9dcc2253e17 100644 --- a/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/kubectl/equivalents/PodExecEquivalent.java +++ b/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/kubectl/equivalents/PodExecEquivalent.java @@ -19,7 +19,6 @@ import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.ExecListener; import io.fabric8.kubernetes.client.dsl.ExecWatch; -import okhttp3.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,12 +59,12 @@ public static void main(String[] args) { private static class MyPodExecListener implements ExecListener { @Override - public void onOpen(Response response) { + public void onOpen() { logger.info("Shell was opened"); } @Override - public void onFailure(Throwable throwable, Response response) { + public void onFailure(Throwable t, Response failureResponse) { logger.info("Some error encountered"); execLatch.countDown(); } diff --git a/kubernetes-itests/src/test/java/io/fabric8/kubernetes/PodIT.java b/kubernetes-itests/src/test/java/io/fabric8/kubernetes/PodIT.java index e6da2bac22d..aa09e66a289 100644 --- a/kubernetes-itests/src/test/java/io/fabric8/kubernetes/PodIT.java +++ b/kubernetes-itests/src/test/java/io/fabric8/kubernetes/PodIT.java @@ -31,7 +31,6 @@ import io.fabric8.kubernetes.client.dsl.ExecWatch; import io.fabric8.kubernetes.client.dsl.PodResource; import io.fabric8.kubernetes.client.internal.readiness.Readiness; -import okhttp3.Response; import org.arquillian.cube.kubernetes.api.Session; import org.arquillian.cube.kubernetes.impl.requirement.RequiresKubernetes; import org.arquillian.cube.requirement.ArquillianConditionalRunner; @@ -196,12 +195,12 @@ public void exec() throws InterruptedException { ExecWatch execWatch = client.pods().inNamespace(session.getNamespace()).withName(pod1.getMetadata().getName()) .writingOutput(out).withTTY().usingListener(new ExecListener() { @Override - public void onOpen(Response response) { + public void onOpen() { logger.info("Shell was opened"); } @Override - public void onFailure(Throwable throwable, Response response) { + public void onFailure(Throwable t, Response failureResponse) { logger.info("Shell barfed"); execLatch.countDown(); } diff --git a/kubernetes-server-mock/src/main/java/io/fabric8/kubernetes/client/server/mock/KubernetesCrudDispatcher.java b/kubernetes-server-mock/src/main/java/io/fabric8/kubernetes/client/server/mock/KubernetesCrudDispatcher.java index cb1fae2b9c3..5ee6cad5608 100644 --- a/kubernetes-server-mock/src/main/java/io/fabric8/kubernetes/client/server/mock/KubernetesCrudDispatcher.java +++ b/kubernetes-server-mock/src/main/java/io/fabric8/kubernetes/client/server/mock/KubernetesCrudDispatcher.java @@ -28,6 +28,7 @@ import io.fabric8.kubernetes.client.Watcher.Action; import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext; import io.fabric8.kubernetes.client.dsl.base.OperationSupport; +import io.fabric8.kubernetes.client.okhttp.OkHttpClientImpl; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.kubernetes.client.utils.Utils; @@ -188,15 +189,15 @@ public MockResponse handlePatch(RecordedRequest request) { MediaType mergeType; if (contentType == null) { - mergeType = OperationSupport.JSON_PATCH; + mergeType = OkHttpClientImpl.JSON_PATCH; } else { MediaType mediaType = MediaType.parse(contentType); String subtype = mediaType.subtype(); - if (subtype.equals(OperationSupport.JSON_PATCH.subtype())) { - mergeType = OperationSupport.JSON_PATCH; - } else if (subtype.equals(OperationSupport.JSON_MERGE_PATCH.subtype())) { - mergeType = OperationSupport.JSON_MERGE_PATCH; + if (subtype.equals(OkHttpClientImpl.JSON_PATCH.subtype())) { + mergeType = OkHttpClientImpl.JSON_PATCH; + } else if (subtype.equals(OkHttpClientImpl.JSON_MERGE_PATCH.subtype())) { + mergeType = OkHttpClientImpl.JSON_MERGE_PATCH; } else { response.setResponseCode(HttpURLConnection.HTTP_UNSUPPORTED_TYPE); return response; @@ -204,7 +205,7 @@ public MockResponse handlePatch(RecordedRequest request) { } JsonNode updated; - if (mergeType == OperationSupport.JSON_PATCH) { + if (mergeType == OkHttpClientImpl.JSON_PATCH) { updated = JsonPatch.apply(patch, source); } else { ObjectReader objectReader = context.getMapper().readerForUpdating(source); diff --git a/kubernetes-server-mock/src/main/java/io/fabric8/kubernetes/client/server/mock/KubernetesMockServer.java b/kubernetes-server-mock/src/main/java/io/fabric8/kubernetes/client/server/mock/KubernetesMockServer.java index fc432099701..e86da8cad20 100644 --- a/kubernetes-server-mock/src/main/java/io/fabric8/kubernetes/client/server/mock/KubernetesMockServer.java +++ b/kubernetes-server-mock/src/main/java/io/fabric8/kubernetes/client/server/mock/KubernetesMockServer.java @@ -20,6 +20,7 @@ import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; +import io.fabric8.kubernetes.client.http.TlsVersion; import io.fabric8.kubernetes.client.VersionInfo; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.mockwebserver.Context; @@ -35,9 +36,6 @@ import java.util.Map; import java.util.Queue; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; -import static okhttp3.TlsVersion.TLS_1_2; - public class KubernetesMockServer extends DefaultMockServer { private static final Context context = new Context(Serialization.jsonMapper()); @@ -96,9 +94,10 @@ public String[] getRootPaths() { public NamespacedKubernetesClient createClient() { Config config = getMockConfiguration(); - return new DefaultKubernetesClient(createHttpClientForMockServer(config), config); + return new DefaultKubernetesClient(config); } + /** * Removes all recorded expectations. */ @@ -110,8 +109,9 @@ protected Config getMockConfiguration() { return new ConfigBuilder(Config.empty()) .withMasterUrl(url("/")) .withTrustCerts(true) - .withTlsVersions(TLS_1_2) + .withTlsVersions(TlsVersion.TLS_1_2) .withNamespace("test") + .withHttp2Disable(true) .build(); } } diff --git a/kubernetes-server-mock/src/test/java/io/fabric8/kubernetes/client/server/mock/MasterProtocolTest.java b/kubernetes-server-mock/src/test/java/io/fabric8/kubernetes/client/server/mock/MasterProtocolTest.java index ee5cb21dfe1..491b3f907ec 100644 --- a/kubernetes-server-mock/src/test/java/io/fabric8/kubernetes/client/server/mock/MasterProtocolTest.java +++ b/kubernetes-server-mock/src/test/java/io/fabric8/kubernetes/client/server/mock/MasterProtocolTest.java @@ -18,14 +18,12 @@ import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; - +import io.fabric8.kubernetes.client.http.TlsVersion; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Locale; -import static okhttp3.TlsVersion.TLS_1_2; - class MasterProtocolTest { @Test @@ -37,7 +35,7 @@ void testWithSSL() { int port = sslServer.getPort(); Config config = new ConfigBuilder() .withMasterUrl(host + ":" +port) - .withTlsVersions(TLS_1_2) + .withTlsVersions(TlsVersion.TLS_1_2) .withTrustCerts(true) .build(); assertTrue(config.getMasterUrl().toLowerCase(Locale.ROOT).startsWith(Config.HTTPS_PROTOCOL_PREFIX)); diff --git a/kubernetes-tests/src/test/java/io/fabric8/kubernetes/client/mock/PodTest.java b/kubernetes-tests/src/test/java/io/fabric8/kubernetes/client/mock/PodTest.java index 13463903b8a..23fa7576f14 100644 --- a/kubernetes-tests/src/test/java/io/fabric8/kubernetes/client/mock/PodTest.java +++ b/kubernetes-tests/src/test/java/io/fabric8/kubernetes/client/mock/PodTest.java @@ -41,7 +41,6 @@ import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import io.fabric8.kubernetes.client.server.mock.OutputStreamMessage; import io.fabric8.kubernetes.client.utils.Utils; -import okhttp3.Response; import okio.ByteString; import org.junit.Assert; import org.junit.jupiter.api.Assertions; @@ -327,12 +326,9 @@ void testExec() throws InterruptedException { final CountDownLatch execLatch = new CountDownLatch(1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ExecWatch watch = client.pods().withName("pod1").writingOutput(baos).usingListener(new ExecListener() { - @Override - public void onOpen(Response response) { - } @Override - public void onFailure(Throwable t , Response response) { + public void onFailure(Throwable t, Response failureResponse) { execLatch.countDown(); } diff --git a/kubernetes-tests/src/test/java/io/fabric8/openshift/client/server/mock/AdaptTest.java b/kubernetes-tests/src/test/java/io/fabric8/openshift/client/server/mock/AdaptTest.java index 478657a8d18..c177b319538 100644 --- a/kubernetes-tests/src/test/java/io/fabric8/openshift/client/server/mock/AdaptTest.java +++ b/kubernetes-tests/src/test/java/io/fabric8/openshift/client/server/mock/AdaptTest.java @@ -24,7 +24,6 @@ import io.fabric8.mockwebserver.utils.ResponseProvider; import io.fabric8.openshift.client.OpenShiftClient; import okhttp3.Headers; -import okhttp3.OkHttpClient; import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.Test; @@ -53,8 +52,8 @@ void testSharedClient() { .build()).once(); OpenShiftClient oclient = client.adapt(OpenShiftClient.class); - assertNotNull(client.adapt(OkHttpClient.class)); - assertNotNull(oclient.adapt(OkHttpClient.class)); + assertNotNull(client.getHttpClient()); + assertNotNull(oclient.getHttpClient()); } @Test diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/BaseOpenShiftClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/BaseOpenShiftClient.java new file mode 100644 index 00000000000..15ce7f0eddc --- /dev/null +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/BaseOpenShiftClient.java @@ -0,0 +1,37 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.fabric8.openshift.client; + +import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; + +public class BaseOpenShiftClient extends BaseClient implements OpenshiftClientContext { + + public BaseOpenShiftClient() { + + } + + public BaseOpenShiftClient(ClientContext clientContext) { + super(clientContext); + } + + @Override + public OpenShiftConfig getConfiguration() { + return OpenShiftConfig.wrap(super.getConfiguration()); + } + +} diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/DefaultOpenShiftClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/DefaultOpenShiftClient.java index 3d4d38a0ccf..a07b8ee505c 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/DefaultOpenShiftClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/DefaultOpenShiftClient.java @@ -22,11 +22,13 @@ import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.api.model.RootPaths; import io.fabric8.kubernetes.client.BaseKubernetesClient; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ExtensionsAPIGroupClient; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.RequestConfig; +import io.fabric8.kubernetes.client.SimpleClientContext; import io.fabric8.kubernetes.client.VersionInfo; import io.fabric8.kubernetes.client.WithRequestCallable; import io.fabric8.kubernetes.client.dsl.CreateOrDeleteable; @@ -46,6 +48,8 @@ import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.internal.core.v1.ComponentStatusOperationsImpl; import io.fabric8.kubernetes.client.extended.leaderelection.LeaderElectorBuilder; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.okhttp.OkHttpClientImpl; import io.fabric8.kubernetes.client.utils.HttpClientUtils; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.openshift.api.model.BrokerTemplateInstance; @@ -186,7 +190,7 @@ * Class for Default Openshift Client implementing KubernetesClient interface. * It is thread safe. */ -public class DefaultOpenShiftClient extends BaseKubernetesClient implements NamespacedOpenShiftClient { +public class DefaultOpenShiftClient extends BaseKubernetesClient implements NamespacedOpenShiftClient, OpenshiftClientContext { public static final String OPENSHIFT_VERSION_ENDPOINT = "version/openshift"; @@ -208,10 +212,23 @@ public DefaultOpenShiftClient(final OpenShiftConfig config) { this(HttpClientUtils.createHttpClient(config), config); } + /** + * @deprecated use {@link DefaultOpenShiftClient#DefaultOpenShiftClient(HttpClient, OpenShiftConfig)} instead. + * use {@link OkHttpClientImpl#OkHttpClientImpl(OkHttpClient)} to wrap the client. + */ + @Deprecated public DefaultOpenShiftClient(OkHttpClient httpClient, OpenShiftConfig config) { - super(httpClient, config); + this(new OkHttpClientImpl(httpClient), config); + } + + public DefaultOpenShiftClient(HttpClient httpClient, OpenShiftConfig config) { + this(new SimpleClientContext(config, httpClient)); + } + + public DefaultOpenShiftClient(ClientContext clientContext) { + super(clientContext); try { - this.openShiftUrl = new URL(config.getOpenShiftUrl()); + this.openShiftUrl = new URL(getConfiguration().getOpenShiftUrl()); } catch (MalformedURLException e) { throw new KubernetesClientException("Could not create client", e); } @@ -262,93 +279,93 @@ public OpenShiftOperatorHubAPIGroupDSL operatorHub() { @Override public MixedOperation> componentstatuses() { - return new ComponentStatusOperationsImpl(httpClient, getConfiguration()); + return new ComponentStatusOperationsImpl(this); } @Override public ParameterNamespaceListVisitFromServerGetDeleteRecreateWaitApplicable load(InputStream is) { - return new OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(httpClient, getConfiguration(), is); + return new OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(this, is); } @Override public NamespaceListVisitFromServerGetDeleteRecreateWaitApplicable resourceList(KubernetesResourceList item) { - return new OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(httpClient, getConfiguration(), item); + return new OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(this, item); } @Override public ParameterNamespaceListVisitFromServerGetDeleteRecreateWaitApplicable resourceList(String s) { - return new OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(httpClient, getConfiguration(), s); + return new OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(this, s); } @Override public MixedOperation> builds() { - return new BuildOperationsImpl(httpClient, getConfiguration()); + return new BuildOperationsImpl(this); } @Override public MixedOperation> buildConfigs() { - return new BuildConfigOperationsImpl(httpClient, getConfiguration()); + return new BuildConfigOperationsImpl(this); } @Override public MixedOperation> credentialsRequests() { - return OpenShiftHandlers.getOperation(CredentialsRequest.class, CredentialsRequestList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(CredentialsRequest.class, CredentialsRequestList.class, this); } @Override public MixedOperation> deploymentConfigs() { - return new DeploymentConfigOperationsImpl(httpClient, getConfiguration()); + return new DeploymentConfigOperationsImpl(this); } @Override public MixedOperation> groups() { - return new GroupOperationsImpl(httpClient, getConfiguration()); + return new GroupOperationsImpl(this); } @Override public NonNamespaceOperation> helmChartRepositories() { - return OpenShiftHandlers.getOperation(HelmChartRepository.class, HelmChartRepositoryList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(HelmChartRepository.class, HelmChartRepositoryList.class, this); } @Override public NonNamespaceOperation> images() { - return OpenShiftHandlers.getOperation(Image.class, ImageList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(Image.class, ImageList.class, this); } @Override public MixedOperation> imageTags() { - return OpenShiftHandlers.getOperation(ImageTag.class, ImageTagList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(ImageTag.class, ImageTagList.class, this); } @Override public MixedOperation> imageStreams() { - return OpenShiftHandlers.getOperation(ImageStream.class, ImageStreamList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(ImageStream.class, ImageStreamList.class, this); } @Override public MixedOperation> imageStreamTags() { - return OpenShiftHandlers.getOperation(ImageStreamTag.class, ImageStreamTagList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(ImageStreamTag.class, ImageStreamTagList.class, this); } @Override public NamespacedInOutCreateable imageStreamImports() { - return Handlers.getNamespacedHasMetadataCreateOnlyOperation(ImageStreamImport.class, httpClient, getConfiguration()); + return Handlers.getNamespacedHasMetadataCreateOnlyOperation(ImageStreamImport.class, this); } @Override public NamespacedInOutCreateable imageStreamMappings() { - return Handlers.getNamespacedHasMetadataCreateOnlyOperation(ImageStreamMapping.class, httpClient, getConfiguration()); + return Handlers.getNamespacedHasMetadataCreateOnlyOperation(ImageStreamMapping.class, this); } @Override public Namespaceable>> imageStreamImages() { - HasMetadataOperation> operation = Handlers.getNonListingOperation(ImageStreamImage.class, httpClient, getConfiguration()); + HasMetadataOperation> operation = Handlers.getNonListingOperation(ImageStreamImage.class, this); return operation::inNamespace; } @Override public NameableCreateOrDeleteable imageSignatures() { - HasMetadataOperation> operation = Handlers.getNonListingOperation(ImageSignature.class, httpClient, getConfiguration()); + HasMetadataOperation> operation = Handlers.getNonListingOperation(ImageSignature.class, this); return new NameableCreateOrDeleteable() { @Override @@ -375,57 +392,57 @@ public CreateOrDeleteable withName(String name) { @Override public NonNamespaceOperation> imageRegistryOperatorConfigs() { - return OpenShiftHandlers.getOperation(io.fabric8.openshift.api.model.miscellaneous.imageregistry.operator.v1.Config.class, ConfigList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(io.fabric8.openshift.api.model.miscellaneous.imageregistry.operator.v1.Config.class, ConfigList.class, this); } @Override public MixedOperation> networkAttachmentDefinitions() { - return new NetworkAttachmentDefinitionOperationsImpl(httpClient, getConfiguration()); + return new NetworkAttachmentDefinitionOperationsImpl(this); } @Override public NonNamespaceOperation> oAuthAccessTokens() { - return new OAuthAccessTokenOperationsImpl(httpClient, getConfiguration()); + return new OAuthAccessTokenOperationsImpl(this); } @Override public NonNamespaceOperation> oAuthAuthorizeTokens() { - return new OAuthAuthorizeTokenOperationsImpl(httpClient, getConfiguration()); + return new OAuthAuthorizeTokenOperationsImpl(this); } @Override public NonNamespaceOperation> oAuthClients() { - return new OAuthClientOperationsImpl(httpClient, getConfiguration()); + return new OAuthClientOperationsImpl(this); } @Override public NamespacedInOutCreateable podSecurityPolicyReviews() { - return OpenShiftHandlers.getCreateOnlyResourceOperation(PodSecurityPolicyReview.class, PodSecurityPolicyReview.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getCreateOnlyResourceOperation(PodSecurityPolicyReview.class, PodSecurityPolicyReview.class, this); } @Override public NonNamespaceOperation> oAuthClientAuthorizations() { - return OpenShiftHandlers.getOperation(OAuthClientAuthorization.class, OAuthClientAuthorizationList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(OAuthClientAuthorization.class, OAuthClientAuthorizationList.class, this); } @Override public MixedOperation> operatorPKIs() { - return OpenShiftHandlers.getOperation(OperatorPKI.class, OperatorPKIList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(OperatorPKI.class, OperatorPKIList.class, this); } @Override public NamespacedInOutCreateable podSecurityPolicySelfSubjectReviews() { - return OpenShiftHandlers.getCreateOnlyResourceOperation(PodSecurityPolicySelfSubjectReview.class, PodSecurityPolicySelfSubjectReview.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getCreateOnlyResourceOperation(PodSecurityPolicySelfSubjectReview.class, PodSecurityPolicySelfSubjectReview.class, this); } @Override public NamespacedInOutCreateable podSecurityPolicySubjectReviews() { - return OpenShiftHandlers.getCreateOnlyResourceOperation(PodSecurityPolicySubjectReview.class, PodSecurityPolicySubjectReview.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getCreateOnlyResourceOperation(PodSecurityPolicySubjectReview.class, PodSecurityPolicySubjectReview.class, this); } @Override public ProjectOperation projects() { - return new ProjectOperationsImpl(httpClient, getConfiguration()); + return new ProjectOperationsImpl(this); } @Override @@ -435,42 +452,42 @@ public OpenShiftQuotaAPIGroupDSL quotas() { @Override public NonNamespaceOperation> rangeAllocations() { - return OpenShiftHandlers.getOperation(RangeAllocation.class, RangeAllocationList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(RangeAllocation.class, RangeAllocationList.class, this); } @Override public NonNamespaceOperation> securityContextConstraints() { - return new SecurityContextConstraintsOperationsImpl(httpClient, getConfiguration()); + return new SecurityContextConstraintsOperationsImpl(this); } @Override public ProjectRequestOperation projectrequests() { - return new ProjectRequestsOperationImpl(httpClient, getConfiguration()); + return new ProjectRequestsOperationImpl(this); } @Override public MixedOperation> roles() { - return new RoleOperationsImpl(httpClient, getConfiguration()); + return new RoleOperationsImpl(this); } @Override public MixedOperation> roleBindings() { - return new RoleBindingOperationsImpl(httpClient, getConfiguration()); + return new RoleBindingOperationsImpl(this); } @Override public MixedOperation> routes() { - return OpenShiftHandlers.getOperation(Route.class, RouteList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(Route.class, RouteList.class, this); } @Override public ParameterMixedOperation> templates() { - return new TemplateOperationsImpl(httpClient, getConfiguration()); + return new TemplateOperationsImpl(this); } @Override public MixedOperation> templateInstances() { - return OpenShiftHandlers.getOperation(TemplateInstance.class, TemplateInstanceList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(TemplateInstance.class, TemplateInstanceList.class, this); } @Override @@ -480,22 +497,22 @@ public OpenShiftTunedAPIGroupDSL tuned() { @Override public NonNamespaceOperation> brokerTemplateInstances() { - return OpenShiftHandlers.getOperation(BrokerTemplateInstance.class, BrokerTemplateInstanceList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(BrokerTemplateInstance.class, BrokerTemplateInstanceList.class, this); } @Override public MixedOperation> users() { - return new UserOperationsImpl(httpClient, getConfiguration()); + return new UserOperationsImpl(this); } @Override public MixedOperation> clusterRoleBindings() { - return new ClusterRoleBindingOperationsImpl(httpClient, getConfiguration()); + return new ClusterRoleBindingOperationsImpl(this); } @Override public MixedOperation> roleBindingRestrictions() { - return OpenShiftHandlers.getOperation(RoleBindingRestriction.class, RoleBindingRestrictionList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(RoleBindingRestriction.class, RoleBindingRestrictionList.class, this); } @Override @@ -503,7 +520,7 @@ public NamespacedOpenShiftClient inNamespace(String namespace) { OpenShiftConfig updated = new OpenShiftConfigBuilder(getConfiguration()) .withNamespace(namespace) .build(); - return new DefaultOpenShiftClient(httpClient, updated); + return new DefaultOpenShiftClient(newState(updated)); } @Override @@ -583,57 +600,57 @@ public OpenShiftMachineAPIGroupDSL machine() { @Override public NonNamespaceOperation> netNamespaces() { - return OpenShiftHandlers.getOperation(NetNamespace.class, NetNamespaceList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(NetNamespace.class, NetNamespaceList.class, this); } @Override public NonNamespaceOperation> clusterNetworks() { - return OpenShiftHandlers.getOperation(ClusterNetwork.class, ClusterNetworkList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(ClusterNetwork.class, ClusterNetworkList.class, this); } @Override public MixedOperation> egressNetworkPolicies() { - return OpenShiftHandlers.getOperation(EgressNetworkPolicy.class, EgressNetworkPolicyList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(EgressNetworkPolicy.class, EgressNetworkPolicyList.class, this); } @Override public NonNamespaceOperation> hostSubnets() { - return OpenShiftHandlers.getOperation(HostSubnet.class, HostSubnetList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(HostSubnet.class, HostSubnetList.class, this); } @Override public MixedOperation> bareMetalHosts() { - return OpenShiftHandlers.getOperation(BareMetalHost.class, BareMetalHostList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(BareMetalHost.class, BareMetalHostList.class, this); } @Override public InOutCreateable subjectAccessReviews() { - return OpenShiftHandlers.getCreateOnlyResourceOperation(SubjectAccessReview.class, SubjectAccessReviewResponse.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getCreateOnlyResourceOperation(SubjectAccessReview.class, SubjectAccessReviewResponse.class, this); } @Override public InOutCreateable resourceAccessReviews() { - return OpenShiftHandlers.getCreateOnlyResourceOperation(ResourceAccessReview.class, ResourceAccessReviewResponse.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getCreateOnlyResourceOperation(ResourceAccessReview.class, ResourceAccessReviewResponse.class, this); } @Override public NamespacedInOutCreateable localSubjectAccessReviews() { - return OpenShiftHandlers.getCreateOnlyResourceOperation(LocalSubjectAccessReview.class, SubjectAccessReviewResponse.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getCreateOnlyResourceOperation(LocalSubjectAccessReview.class, SubjectAccessReviewResponse.class, this); } @Override public NamespacedInOutCreateable localResourceAccessReviews() { - return OpenShiftHandlers.getCreateOnlyResourceOperation(LocalResourceAccessReview.class, ResourceAccessReviewResponse.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getCreateOnlyResourceOperation(LocalResourceAccessReview.class, ResourceAccessReviewResponse.class, this); } @Override public NamespacedInOutCreateable selfSubjectRulesReviews() { - return OpenShiftHandlers.getCreateOnlyResourceOperation(SelfSubjectRulesReview.class, SelfSubjectRulesReview.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getCreateOnlyResourceOperation(SelfSubjectRulesReview.class, SelfSubjectRulesReview.class, this); } @Override public NamespacedInOutCreateable subjectRulesReviews() { - return OpenShiftHandlers.getCreateOnlyResourceOperation(SubjectRulesReview.class, SubjectRulesReview.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getCreateOnlyResourceOperation(SubjectRulesReview.class, SubjectRulesReview.class, this); } @Override @@ -643,7 +660,7 @@ public OpenShiftStorageVersionMigratorApiGroupDSL kubeStorageVersionMigrator() { @Override public NonNamespaceOperation> clusterRoles() { - return OpenShiftHandlers.getOperation(ClusterRole.class, ClusterRoleList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(ClusterRole.class, ClusterRoleList.class, this); } /** @@ -666,17 +683,17 @@ public User currentUser() { @Override public NonNamespaceOperation> identities() { - return OpenShiftHandlers.getOperation(Identity.class, IdentityList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(Identity.class, IdentityList.class, this); } @Override public InOutCreateable userIdentityMappings() { - return Handlers.getNonListingOperation(UserIdentityMapping.class, httpClient, getConfiguration()); + return Handlers.getNonListingOperation(UserIdentityMapping.class, this); } @Override public NonNamespaceOperation> userOAuthAccessTokens() { - return OpenShiftHandlers.getOperation(UserOAuthAccessToken.class, UserOAuthAccessTokenList.class, httpClient, getConfiguration()); + return OpenShiftHandlers.getOperation(UserOAuthAccessToken.class, UserOAuthAccessTokenList.class, this); } @Override @@ -702,8 +719,10 @@ public boolean supportsOpenShiftAPIGroup(String apiGroup) { } @Override - protected OkHttpClient adaptOkHttpClient(OkHttpClient okHttpClient) { - return OpenshiftAdapterSupport.adaptOkHttpClient(okHttpClient, getConfiguration()); + protected void adaptState() { + OpenShiftConfig wrapped = OpenShiftConfig.wrap(config); + this.config = wrapped; + this.httpClient = OpenshiftAdapterSupport.adaptHttpClient(httpClient, wrapped); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftClusterAutoscalingAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftClusterAutoscalingAPIGroupClient.java index 4d2752fa51c..ef23be4d3d0 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftClusterAutoscalingAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftClusterAutoscalingAPIGroupClient.java @@ -16,19 +16,18 @@ package io.fabric8.openshift.client; import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.openshift.client.dsl.OpenShiftClusterAutoscalingAPIGroupDSL; import io.fabric8.openshift.client.dsl.V1ClusterAutoscalingAPIGroupDSL; import io.fabric8.openshift.client.dsl.V1beta1ClusterAutoscalingAPIGroupDSL; -import okhttp3.OkHttpClient; public class OpenShiftClusterAutoscalingAPIGroupClient extends BaseClient implements OpenShiftClusterAutoscalingAPIGroupDSL { public OpenShiftClusterAutoscalingAPIGroupClient() { super(); } - public OpenShiftClusterAutoscalingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftClusterAutoscalingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java index 9fa04a1ea04..095312417ef 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftClusterAutoscalingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,7 +31,7 @@ public Class getExtensionType() { @Override protected OpenShiftClusterAutoscalingAPIGroupClient newInstance(Client client) { - return new OpenShiftClusterAutoscalingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftClusterAutoscalingAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfig.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfig.java index 8ab34b96329..bfcd8e3678f 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfig.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfig.java @@ -20,13 +20,13 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.OAuthTokenProvider; +import io.fabric8.kubernetes.client.http.TlsVersion; import io.fabric8.kubernetes.client.internal.readiness.Readiness; import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.kubernetes.client.utils.Utils; import io.fabric8.openshift.client.internal.readiness.OpenShiftReadiness; import io.sundr.builder.annotations.Buildable; import io.sundr.builder.annotations.BuildableReference; -import okhttp3.TlsVersion; import java.net.MalformedURLException; import java.net.URL; diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfigAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfigAPIGroupClient.java index 962dcd61090..bf8c3fa07b7 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfigAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfigAPIGroupClient.java @@ -16,8 +16,8 @@ package io.fabric8.openshift.client; import io.fabric8.kubernetes.client.BaseClient; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.openshift.api.model.APIServer; @@ -50,84 +50,84 @@ import io.fabric8.openshift.api.model.SchedulerList; import io.fabric8.openshift.client.dsl.OpenShiftConfigAPIGroupDSL; import io.fabric8.openshift.client.dsl.internal.config.DNSOperationsImpl; -import okhttp3.OkHttpClient; -public class OpenShiftConfigAPIGroupClient extends BaseClient implements OpenShiftConfigAPIGroupDSL { +public class OpenShiftConfigAPIGroupClient extends BaseOpenShiftClient implements OpenShiftConfigAPIGroupDSL { public OpenShiftConfigAPIGroupClient() { super(); } - public OpenShiftConfigAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftConfigAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public NonNamespaceOperation> apiServers() { - return OpenShiftHandlers.getOperation(APIServer.class, APIServerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(APIServer.class, APIServerList.class, this); } @Override public NonNamespaceOperation> authentications() { - return OpenShiftHandlers.getOperation(Authentication.class, AuthenticationList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Authentication.class, AuthenticationList.class, this); } @Override public NonNamespaceOperation> clusterOperators() { - return OpenShiftHandlers.getOperation(ClusterOperator.class, ClusterOperatorList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ClusterOperator.class, ClusterOperatorList.class, this); } @Override public NonNamespaceOperation> consoles() { - return OpenShiftHandlers.getOperation(Console.class, ConsoleList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Console.class, ConsoleList.class, this); } @Override public NonNamespaceOperation> clusterVersions() { - return OpenShiftHandlers.getOperation(ClusterVersion.class, ClusterVersionList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ClusterVersion.class, ClusterVersionList.class, this); } @Override public NonNamespaceOperation> dnses() { - return new DNSOperationsImpl(httpClient, OpenShiftConfig.wrap(getConfiguration())); + return new DNSOperationsImpl(this); } @Override public NonNamespaceOperation> featureGates() { - return OpenShiftHandlers.getOperation(FeatureGate.class, FeatureGateList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(FeatureGate.class, FeatureGateList.class, this); } @Override public NonNamespaceOperation> infrastructures() { - return OpenShiftHandlers.getOperation(Infrastructure.class, InfrastructureList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Infrastructure.class, InfrastructureList.class, this); } @Override public NonNamespaceOperation> ingresses() { - return OpenShiftHandlers.getOperation(Ingress.class, IngressList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Ingress.class, IngressList.class, this); } @Override public NonNamespaceOperation> networks() { - return OpenShiftHandlers.getOperation(Network.class, NetworkList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Network.class, NetworkList.class, this); } @Override public NonNamespaceOperation> oAuths() { - return OpenShiftHandlers.getOperation(OAuth.class, OAuthList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(OAuth.class, OAuthList.class, this); } @Override public NonNamespaceOperation> operatorHubs() { - return OpenShiftHandlers.getOperation(OperatorHub.class, OperatorHubList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(OperatorHub.class, OperatorHubList.class, this); } @Override public NonNamespaceOperation> proxies() { - return OpenShiftHandlers.getOperation(Proxy.class, ProxyList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Proxy.class, ProxyList.class, this); } @Override public NonNamespaceOperation> schedulers() { - return OpenShiftHandlers.getOperation(Scheduler.class, SchedulerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Scheduler.class, SchedulerList.class, this); } + } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfigAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfigAPIGroupExtensionAdapter.java index 53aab3fd76b..d45bb38dac0 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfigAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConfigAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftConfigAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,7 +31,7 @@ public Class getExtensionType() { @Override protected OpenShiftConfigAPIGroupClient newInstance(Client client) { - return new OpenShiftConfigAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftConfigAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConsoleAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConsoleAPIGroupClient.java index 4cdedc0fbb5..5340f5e1b3e 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConsoleAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConsoleAPIGroupClient.java @@ -15,9 +15,7 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.Handlers; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.openshift.api.model.console.v1.ConsoleCLIDownload; @@ -35,49 +33,49 @@ import io.fabric8.openshift.api.model.console.v1alpha1.ConsolePlugin; import io.fabric8.openshift.api.model.console.v1alpha1.ConsolePluginList; import io.fabric8.openshift.client.dsl.OpenShiftConsoleAPIGroupDSL; -import okhttp3.OkHttpClient; -public class OpenShiftConsoleAPIGroupClient extends BaseClient implements OpenShiftConsoleAPIGroupDSL { +public class OpenShiftConsoleAPIGroupClient extends BaseOpenShiftClient implements OpenShiftConsoleAPIGroupDSL { public OpenShiftConsoleAPIGroupClient() { super(); } - public OpenShiftConsoleAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftConsoleAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public NonNamespaceOperation> consoleCLIDownloads() { - return OpenShiftHandlers.getOperation(ConsoleCLIDownload.class, ConsoleCLIDownloadList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ConsoleCLIDownload.class, ConsoleCLIDownloadList.class, this); } @Override public NonNamespaceOperation> consoleExternalLogLinks() { - return OpenShiftHandlers.getOperation(ConsoleExternalLogLink.class, ConsoleExternalLogLinkList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ConsoleExternalLogLink.class, ConsoleExternalLogLinkList.class, this); } @Override public NonNamespaceOperation> consoleLinks() { - return OpenShiftHandlers.getOperation(ConsoleLink.class, ConsoleLinkList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ConsoleLink.class, ConsoleLinkList.class, this); } @Override public NonNamespaceOperation> consoleNotifications() { - return OpenShiftHandlers.getOperation(ConsoleNotification.class, ConsoleNotificationList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ConsoleNotification.class, ConsoleNotificationList.class, this); } @Override public NonNamespaceOperation> consoleYAMLSamples() { - return OpenShiftHandlers.getOperation(ConsoleYAMLSample.class, ConsoleYAMLSampleList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ConsoleYAMLSample.class, ConsoleYAMLSampleList.class, this); } @Override public NonNamespaceOperation> consoleQuickStarts() { - return OpenShiftHandlers.getOperation(ConsoleQuickStart.class, ConsoleQuickStartList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ConsoleQuickStart.class, ConsoleQuickStartList.class, this); } @Override public NonNamespaceOperation> consolePlugins() { - return OpenShiftHandlers.getOperation(ConsolePlugin.class, ConsolePluginList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ConsolePlugin.class, ConsolePluginList.class, this); } + } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConsoleAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConsoleAPIGroupExtensionAdapter.java index 9c8ad5a4cb8..c5107882f91 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConsoleAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftConsoleAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftConsoleAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,7 +31,7 @@ public Class getExtensionType() { @Override protected OpenShiftConsoleAPIGroupClient newInstance(Client client) { - return new OpenShiftConsoleAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftConsoleAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftHandlers.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftHandlers.java index 385189a0230..2702b7bb94a 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftHandlers.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftHandlers.java @@ -24,9 +24,9 @@ import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation; import io.fabric8.kubernetes.client.dsl.base.ResourceDefinitionContext; import io.fabric8.kubernetes.client.dsl.internal.CreateOnlyResourceOperationsImpl; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.http.HttpClient; -import java.util.function.BiFunction; +import java.util.function.Function; public final class OpenShiftHandlers { @@ -35,18 +35,29 @@ private OpenShiftHandlers() { } public static , R extends Resource> void register( - Class type, BiFunction> operationConstructor) { - Handlers.register(type, (o, c) -> operationConstructor.apply(o, OpenShiftConfig.wrap(c))); + Class type, Function> operationConstructor) { + Handlers.register(type, c -> operationConstructor.apply(new OpenshiftClientContext() { + + @Override + public HttpClient getHttpClient() { + return c.getHttpClient(); + } + + @Override + public OpenShiftConfig getConfiguration() { + return OpenShiftConfig.wrap(c.getConfiguration()); + } + })); } public static , R extends Resource> HasMetadataOperation getOperation( - Class type, Class listType, OkHttpClient client, OpenShiftConfig config) { - return Handlers.getOperation(type, listType, client, config); + Class type, Class listType, OpenshiftClientContext clientContext) { + return Handlers.getOperation(type, listType, clientContext); } public static CreateOnlyResourceOperationsImpl getCreateOnlyResourceOperation( - Class inputType, Class outputType, OkHttpClient client, OpenShiftConfig config) { - return new CreateOnlyResourceOperationsImpl<>(client, config, ResourceDefinitionContext.fromResourceType(inputType), inputType, outputType); + Class inputType, Class outputType, OpenshiftClientContext clientContext) { + return new CreateOnlyResourceOperationsImpl<>(clientContext, ResourceDefinitionContext.fromResourceType(inputType), inputType, outputType); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineAPIGroupClient.java index b00ad1760f5..68f6e3d1ff6 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineAPIGroupClient.java @@ -15,8 +15,7 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.openshift.api.model.machine.v1beta1.Machine; @@ -26,29 +25,28 @@ import io.fabric8.openshift.api.model.machine.v1beta1.MachineSet; import io.fabric8.openshift.api.model.machine.v1beta1.MachineSetList; import io.fabric8.openshift.client.dsl.OpenShiftMachineAPIGroupDSL; -import okhttp3.OkHttpClient; -public class OpenShiftMachineAPIGroupClient extends BaseClient implements OpenShiftMachineAPIGroupDSL { +public class OpenShiftMachineAPIGroupClient extends BaseOpenShiftClient implements OpenShiftMachineAPIGroupDSL { public OpenShiftMachineAPIGroupClient() { super(); } - public OpenShiftMachineAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftMachineAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> machines() { - return OpenShiftHandlers.getOperation(Machine.class, MachineList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Machine.class, MachineList.class, this); } @Override public MixedOperation> machineSets() { - return OpenShiftHandlers.getOperation(MachineSet.class, MachineSetList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(MachineSet.class, MachineSetList.class, this); } @Override public MixedOperation> machineHealthChecks() { - return OpenShiftHandlers.getOperation(MachineHealthCheck.class, MachineHealthCheckList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(MachineHealthCheck.class, MachineHealthCheckList.class, this); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineAPIGroupExtensionAdapter.java index 1d49e7d0e81..51295b180f4 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftMachineAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected OpenShiftMachineAPIGroupClient newInstance(Client client) { - return new OpenShiftMachineAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftMachineAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineConfigurationAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineConfigurationAPIGroupClient.java index a9c566939c1..b0f0b4d83c4 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineConfigurationAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineConfigurationAPIGroupClient.java @@ -15,8 +15,7 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.openshift.api.model.machineconfig.v1.ContainerRuntimeConfig; @@ -30,40 +29,39 @@ import io.fabric8.openshift.api.model.machineconfig.v1.MachineConfigPool; import io.fabric8.openshift.api.model.machineconfig.v1.MachineConfigPoolList; import io.fabric8.openshift.client.dsl.MachineConfigurationAPIGroupDSL; -import okhttp3.OkHttpClient; -public class OpenShiftMachineConfigurationAPIGroupClient extends BaseClient implements MachineConfigurationAPIGroupDSL { +public class OpenShiftMachineConfigurationAPIGroupClient extends BaseOpenShiftClient implements MachineConfigurationAPIGroupDSL { public OpenShiftMachineConfigurationAPIGroupClient() { super(); } - public OpenShiftMachineConfigurationAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftMachineConfigurationAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public NonNamespaceOperation> containerRuntimeConfigs() { - return OpenShiftHandlers.getOperation(ContainerRuntimeConfig.class, ContainerRuntimeConfigList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ContainerRuntimeConfig.class, ContainerRuntimeConfigList.class, this); } @Override public NonNamespaceOperation> controllerConfigs() { - return OpenShiftHandlers.getOperation(ControllerConfig.class, ControllerConfigList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ControllerConfig.class, ControllerConfigList.class, this); } @Override public NonNamespaceOperation> kubeletConfigs() { - return OpenShiftHandlers.getOperation(KubeletConfig.class, KubeletConfigList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(KubeletConfig.class, KubeletConfigList.class, this); } @Override public NonNamespaceOperation> machineConfigPools() { - return OpenShiftHandlers.getOperation(MachineConfigPool.class, MachineConfigPoolList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(MachineConfigPool.class, MachineConfigPoolList.class, this); } @Override public NonNamespaceOperation> machineConfigs() { - return OpenShiftHandlers.getOperation(MachineConfig.class, MachineConfigList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(MachineConfig.class, MachineConfigList.class, this); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineConfigurationAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineConfigurationAPIGroupExtensionAdapter.java index 445cf849c99..b7e266d3a34 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineConfigurationAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMachineConfigurationAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftMachineConfigurationAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,7 +31,7 @@ public Class getExtensionType() { @Override protected OpenShiftMachineConfigurationAPIGroupClient newInstance(Client client) { - return new OpenShiftMachineConfigurationAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftMachineConfigurationAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMonitoringAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMonitoringAPIGroupClient.java index b61b571aed4..a8594362407 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMonitoringAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMonitoringAPIGroupClient.java @@ -15,8 +15,7 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.openshift.api.model.monitoring.v1.Alertmanager; @@ -36,54 +35,53 @@ import io.fabric8.openshift.api.model.monitoring.v1alpha1.AlertmanagerConfig; import io.fabric8.openshift.api.model.monitoring.v1alpha1.AlertmanagerConfigList; import io.fabric8.openshift.client.dsl.OpenShiftMonitoringAPIGroupDSL; -import okhttp3.OkHttpClient; -public class OpenShiftMonitoringAPIGroupClient extends BaseClient implements OpenShiftMonitoringAPIGroupDSL { +public class OpenShiftMonitoringAPIGroupClient extends BaseOpenShiftClient implements OpenShiftMonitoringAPIGroupDSL { public OpenShiftMonitoringAPIGroupClient() { super(); } - public OpenShiftMonitoringAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftMonitoringAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> alertmanagerConfigs() { - return OpenShiftHandlers.getOperation(AlertmanagerConfig.class, AlertmanagerConfigList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(AlertmanagerConfig.class, AlertmanagerConfigList.class, this); } @Override public MixedOperation> prometheuses() { - return OpenShiftHandlers.getOperation(Prometheus.class, PrometheusList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Prometheus.class, PrometheusList.class, this); } @Override public MixedOperation> podMonitors() { - return OpenShiftHandlers.getOperation(PodMonitor.class, PodMonitorList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(PodMonitor.class, PodMonitorList.class, this); } @Override public MixedOperation> probes() { - return OpenShiftHandlers.getOperation(Probe.class, ProbeList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Probe.class, ProbeList.class, this); } @Override public MixedOperation> alertmanagers() { - return OpenShiftHandlers.getOperation(Alertmanager.class, AlertmanagerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Alertmanager.class, AlertmanagerList.class, this); } @Override public MixedOperation> prometheusRules() { - return OpenShiftHandlers.getOperation(PrometheusRule.class, PrometheusRuleList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(PrometheusRule.class, PrometheusRuleList.class, this); } @Override public MixedOperation> serviceMonitors() { - return OpenShiftHandlers.getOperation(ServiceMonitor.class, ServiceMonitorList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ServiceMonitor.class, ServiceMonitorList.class, this); } @Override public MixedOperation> thanosRulers() { - return OpenShiftHandlers.getOperation(ThanosRuler.class, ThanosRulerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ThanosRuler.class, ThanosRulerList.class, this); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMonitoringAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMonitoringAPIGroupExtensionAdapter.java index ebc9e0172df..83d1398eabb 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMonitoringAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftMonitoringAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftMonitoringAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,7 +31,7 @@ public Class getExtensionType() { @Override protected OpenShiftMonitoringAPIGroupClient newInstance(Client client) { - return new OpenShiftMonitoringAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftMonitoringAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorAPIGroupClient.java index a0ef7d1f078..d847706496f 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorAPIGroupClient.java @@ -15,8 +15,7 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; @@ -68,134 +67,133 @@ import io.fabric8.openshift.api.model.operator.v1alpha1.ImageContentSourcePolicy; import io.fabric8.openshift.api.model.operator.v1alpha1.ImageContentSourcePolicyList; import io.fabric8.openshift.client.dsl.OpenShiftOperatorAPIGroupDSL; -import okhttp3.OkHttpClient; -public class OpenShiftOperatorAPIGroupClient extends BaseClient implements OpenShiftOperatorAPIGroupDSL { +public class OpenShiftOperatorAPIGroupClient extends BaseOpenShiftClient implements OpenShiftOperatorAPIGroupDSL { public OpenShiftOperatorAPIGroupClient() { super(); } - public OpenShiftOperatorAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftOperatorAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public NonNamespaceOperation> etcds() { - return OpenShiftHandlers.getOperation(Etcd.class, EtcdList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Etcd.class, EtcdList.class, this); } @Override public NonNamespaceOperation> kubeStorageVersionMigrators() { - return OpenShiftHandlers.getOperation(KubeStorageVersionMigrator.class, KubeStorageVersionMigratorList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(KubeStorageVersionMigrator.class, KubeStorageVersionMigratorList.class, this); } @Override public NonNamespaceOperation> kubeControllerManagers() { - return OpenShiftHandlers.getOperation(KubeControllerManager.class, KubeControllerManagerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(KubeControllerManager.class, KubeControllerManagerList.class, this); } @Override public NonNamespaceOperation> csiSnapshotControllers() { - return OpenShiftHandlers.getOperation(CSISnapshotController.class, CSISnapshotControllerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(CSISnapshotController.class, CSISnapshotControllerList.class, this); } @Override public NonNamespaceOperation> networks() { - return OpenShiftHandlers.getOperation(Network.class, NetworkList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Network.class, NetworkList.class, this); } @Override public NonNamespaceOperation> kubeSchedulers() { - return OpenShiftHandlers.getOperation(KubeScheduler.class, KubeSchedulerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(KubeScheduler.class, KubeSchedulerList.class, this); } @Override public NonNamespaceOperation> consoles() { - return OpenShiftHandlers.getOperation(Console.class, ConsoleList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Console.class, ConsoleList.class, this); } @Override public NonNamespaceOperation> serviceCatalogControllerManagers() { - return OpenShiftHandlers.getOperation(ServiceCatalogControllerManager.class, ServiceCatalogControllerManagerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ServiceCatalogControllerManager.class, ServiceCatalogControllerManagerList.class, this); } @Override public NonNamespaceOperation> serviceCAs() { - return OpenShiftHandlers.getOperation(ServiceCA.class, ServiceCAList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ServiceCA.class, ServiceCAList.class, this); } @Override public NonNamespaceOperation> imageContentSourcePolicies() { - return OpenShiftHandlers.getOperation(ImageContentSourcePolicy.class, ImageContentSourcePolicyList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ImageContentSourcePolicy.class, ImageContentSourcePolicyList.class, this); } @Override public NonNamespaceOperation> dnses() { - return OpenShiftHandlers.getOperation(DNS.class, DNSList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(DNS.class, DNSList.class, this); } @Override public MixedOperation> dnsRecords() { - return OpenShiftHandlers.getOperation(DNSRecord.class, DNSRecordList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(DNSRecord.class, DNSRecordList.class, this); } @Override public NonNamespaceOperation> openShiftControllerManagers() { - return OpenShiftHandlers.getOperation(OpenShiftControllerManager.class, OpenShiftControllerManagerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(OpenShiftControllerManager.class, OpenShiftControllerManagerList.class, this); } @Override public NonNamespaceOperation> openShiftAPIServers() { - return OpenShiftHandlers.getOperation(OpenShiftAPIServer.class, OpenShiftAPIServerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(OpenShiftAPIServer.class, OpenShiftAPIServerList.class, this); } @Override public NonNamespaceOperation> kubeAPIServers() { - return OpenShiftHandlers.getOperation(KubeAPIServer.class, KubeAPIServerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(KubeAPIServer.class, KubeAPIServerList.class, this); } @Override public MixedOperation> ingressControllers() { - return OpenShiftHandlers.getOperation(IngressController.class, IngressControllerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(IngressController.class, IngressControllerList.class, this); } @Override public NonNamespaceOperation> imagePruners() { - return OpenShiftHandlers.getOperation(ImagePruner.class, ImagePrunerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ImagePruner.class, ImagePrunerList.class, this); } @Override public MixedOperation> podNetworkConnectivityChecks() { - return OpenShiftHandlers.getOperation(PodNetworkConnectivityCheck.class, PodNetworkConnectivityCheckList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(PodNetworkConnectivityCheck.class, PodNetworkConnectivityCheckList.class, this); } @Override public NonNamespaceOperation> serviceCatalogAPIServers() { - return OpenShiftHandlers.getOperation(ServiceCatalogAPIServer.class, ServiceCatalogAPIServerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ServiceCatalogAPIServer.class, ServiceCatalogAPIServerList.class, this); } @Override public NonNamespaceOperation> storages() { - return OpenShiftHandlers.getOperation(Storage.class, StorageList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Storage.class, StorageList.class, this); } @Override public NonNamespaceOperation> authentications() { - return OpenShiftHandlers.getOperation(Authentication.class, AuthenticationList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Authentication.class, AuthenticationList.class, this); } @Override public NonNamespaceOperation> cloudCredentials() { - return OpenShiftHandlers.getOperation(CloudCredential.class, CloudCredentialList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(CloudCredential.class, CloudCredentialList.class, this); } @Override public NonNamespaceOperation> clusterCSIDrivers() { - return OpenShiftHandlers.getOperation(ClusterCSIDriver.class, ClusterCSIDriverList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ClusterCSIDriver.class, ClusterCSIDriverList.class, this); } @Override public NonNamespaceOperation> configs() { - return OpenShiftHandlers.getOperation(io.fabric8.openshift.api.model.operator.v1.Config.class, ConfigList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(io.fabric8.openshift.api.model.operator.v1.Config.class, ConfigList.class, this); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorAPIGroupExtensionAdapter.java index 133287c4d47..ab6a8b99d78 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftOperatorAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,7 +31,7 @@ public Class getExtensionType() { @Override protected OpenShiftOperatorAPIGroupClient newInstance(Client client) { - return new OpenShiftOperatorAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftOperatorAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorHubAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorHubAPIGroupClient.java index 2b728e21c60..3977dde5dc1 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorHubAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorHubAPIGroupClient.java @@ -15,8 +15,7 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; @@ -37,54 +36,53 @@ import io.fabric8.openshift.api.model.operatorhub.v1alpha1.Subscription; import io.fabric8.openshift.api.model.operatorhub.v1alpha1.SubscriptionList; import io.fabric8.openshift.client.dsl.OpenShiftOperatorHubAPIGroupDSL; -import okhttp3.OkHttpClient; -public class OpenShiftOperatorHubAPIGroupClient extends BaseClient implements OpenShiftOperatorHubAPIGroupDSL { +public class OpenShiftOperatorHubAPIGroupClient extends BaseOpenShiftClient implements OpenShiftOperatorHubAPIGroupDSL { public OpenShiftOperatorHubAPIGroupClient() { super(); } - public OpenShiftOperatorHubAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftOperatorHubAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> catalogSources() { - return OpenShiftHandlers.getOperation(CatalogSource.class, CatalogSourceList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(CatalogSource.class, CatalogSourceList.class, this); } @Override public MixedOperation> operatorGroups() { - return OpenShiftHandlers.getOperation(OperatorGroup.class, OperatorGroupList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(OperatorGroup.class, OperatorGroupList.class, this); } @Override public MixedOperation> subscriptions() { - return OpenShiftHandlers.getOperation(Subscription.class, SubscriptionList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Subscription.class, SubscriptionList.class, this); } @Override public MixedOperation> installPlans() { - return OpenShiftHandlers.getOperation(InstallPlan.class, InstallPlanList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(InstallPlan.class, InstallPlanList.class, this); } @Override public MixedOperation> clusterServiceVersions() { - return OpenShiftHandlers.getOperation(ClusterServiceVersion.class, ClusterServiceVersionList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ClusterServiceVersion.class, ClusterServiceVersionList.class, this); } @Override public MixedOperation> packageManifests() { - return OpenShiftHandlers.getOperation(PackageManifest.class, PackageManifestList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(PackageManifest.class, PackageManifestList.class, this); } @Override public MixedOperation> operatorConditions() { - return OpenShiftHandlers.getOperation(OperatorCondition.class, OperatorConditionList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(OperatorCondition.class, OperatorConditionList.class, this); } @Override public NonNamespaceOperation> operators() { - return OpenShiftHandlers.getOperation(Operator.class, OperatorList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Operator.class, OperatorList.class, this); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorHubAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorHubAPIGroupExtensionAdapter.java index 5e0a4d7f1e7..883fae1431e 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorHubAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftOperatorHubAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftOperatorHubAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected OpenShiftOperatorHubAPIGroupClient newInstance(Client client) { - return new OpenShiftOperatorHubAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftOperatorHubAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftQuotaAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftQuotaAPIGroupClient.java index 1af5e537d93..d0e2b6b6f0c 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftQuotaAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftQuotaAPIGroupClient.java @@ -15,8 +15,7 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.openshift.api.model.AppliedClusterResourceQuota; @@ -24,24 +23,23 @@ import io.fabric8.openshift.api.model.ClusterResourceQuota; import io.fabric8.openshift.api.model.ClusterResourceQuotaList; import io.fabric8.openshift.client.dsl.OpenShiftQuotaAPIGroupDSL; -import okhttp3.OkHttpClient; -public class OpenShiftQuotaAPIGroupClient extends BaseClient implements OpenShiftQuotaAPIGroupDSL { +public class OpenShiftQuotaAPIGroupClient extends BaseOpenShiftClient implements OpenShiftQuotaAPIGroupDSL { public OpenShiftQuotaAPIGroupClient() { super(); } - public OpenShiftQuotaAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftQuotaAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> appliedClusterResourceQuotas() { - return OpenShiftHandlers.getOperation(AppliedClusterResourceQuota.class, AppliedClusterResourceQuotaList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(AppliedClusterResourceQuota.class, AppliedClusterResourceQuotaList.class, this); } @Override public MixedOperation> clusterResourceQuotas() { - return OpenShiftHandlers.getOperation(ClusterResourceQuota.class, ClusterResourceQuotaList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ClusterResourceQuota.class, ClusterResourceQuotaList.class, this); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftQuotaAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftQuotaAPIGroupExtensionAdapter.java index c87aa8a3ba9..0040475749e 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftQuotaAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftQuotaAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftQuotaAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,7 +31,7 @@ public Class getExtensionType() { @Override protected OpenShiftQuotaAPIGroupClient newInstance(Client client) { - return new OpenShiftQuotaAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftQuotaAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftStorageVersionMigratorApiGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftStorageVersionMigratorApiGroupClient.java index 5b2669be785..f8a7e9cd78f 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftStorageVersionMigratorApiGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftStorageVersionMigratorApiGroupClient.java @@ -15,8 +15,7 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.openshift.api.model.storageversionmigrator.v1alpha1.StorageState; @@ -24,24 +23,23 @@ import io.fabric8.openshift.api.model.storageversionmigrator.v1alpha1.StorageVersionMigration; import io.fabric8.openshift.api.model.storageversionmigrator.v1alpha1.StorageVersionMigrationList; import io.fabric8.openshift.client.dsl.OpenShiftStorageVersionMigratorApiGroupDSL; -import okhttp3.OkHttpClient; -public class OpenShiftStorageVersionMigratorApiGroupClient extends BaseClient implements OpenShiftStorageVersionMigratorApiGroupDSL { +public class OpenShiftStorageVersionMigratorApiGroupClient extends BaseOpenShiftClient implements OpenShiftStorageVersionMigratorApiGroupDSL { public OpenShiftStorageVersionMigratorApiGroupClient() { super(); } - public OpenShiftStorageVersionMigratorApiGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftStorageVersionMigratorApiGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public NonNamespaceOperation> storageStates() { - return OpenShiftHandlers.getOperation(StorageState.class, StorageStateList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(StorageState.class, StorageStateList.class, this); } @Override public NonNamespaceOperation> storageVersionMigrations() { - return OpenShiftHandlers.getOperation(StorageVersionMigration.class, StorageVersionMigrationList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(StorageVersionMigration.class, StorageVersionMigrationList.class, this); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftStorageVersionMigratorApiGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftStorageVersionMigratorApiGroupExtensionAdapter.java index 0c77fefdff6..73e1d4dbdd3 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftStorageVersionMigratorApiGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftStorageVersionMigratorApiGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftStorageVersionMigratorApiGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected OpenShiftStorageVersionMigratorApiGroupClient newInstance(Client client) { - return new OpenShiftStorageVersionMigratorApiGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftStorageVersionMigratorApiGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftTunedAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftTunedAPIGroupClient.java index b10c72dd4c7..b9182c26ee8 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftTunedAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftTunedAPIGroupClient.java @@ -15,8 +15,7 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.openshift.api.model.tuned.v1.Profile; @@ -24,24 +23,23 @@ import io.fabric8.openshift.api.model.tuned.v1.Tuned; import io.fabric8.openshift.api.model.tuned.v1.TunedList; import io.fabric8.openshift.client.dsl.OpenShiftTunedAPIGroupDSL; -import okhttp3.OkHttpClient; -public class OpenShiftTunedAPIGroupClient extends BaseClient implements OpenShiftTunedAPIGroupDSL { +public class OpenShiftTunedAPIGroupClient extends BaseOpenShiftClient implements OpenShiftTunedAPIGroupDSL { public OpenShiftTunedAPIGroupClient() { super(); } - public OpenShiftTunedAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftTunedAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> tuneds() { - return OpenShiftHandlers.getOperation(Tuned.class, TunedList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Tuned.class, TunedList.class, this); } @Override public MixedOperation> profiles() { - return OpenShiftHandlers.getOperation(Profile.class, ProfileList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(Profile.class, ProfileList.class, this); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftTunedAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftTunedAPIGroupExtensionAdapter.java index 91c1c761d2a..413484994f3 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftTunedAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftTunedAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftTunedAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,7 +31,7 @@ public Class getExtensionType() { @Override protected OpenShiftTunedAPIGroupClient newInstance(Client client) { - return new OpenShiftTunedAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftTunedAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftWhereaboutsAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftWhereaboutsAPIGroupClient.java index 630509e295b..d2d5e72488b 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftWhereaboutsAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftWhereaboutsAPIGroupClient.java @@ -15,8 +15,7 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.openshift.api.model.whereabouts.v1alpha1.IPPool; @@ -24,24 +23,23 @@ import io.fabric8.openshift.api.model.whereabouts.v1alpha1.OverlappingRangeIPReservation; import io.fabric8.openshift.api.model.whereabouts.v1alpha1.OverlappingRangeIPReservationList; import io.fabric8.openshift.client.dsl.OpenShiftWhereaboutsAPIGroupDSL; -import okhttp3.OkHttpClient; -public class OpenShiftWhereaboutsAPIGroupClient extends BaseClient implements OpenShiftWhereaboutsAPIGroupDSL { +public class OpenShiftWhereaboutsAPIGroupClient extends BaseOpenShiftClient implements OpenShiftWhereaboutsAPIGroupDSL { public OpenShiftWhereaboutsAPIGroupClient() { super(); } - public OpenShiftWhereaboutsAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public OpenShiftWhereaboutsAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> ippools() { - return OpenShiftHandlers.getOperation(IPPool.class, IPPoolList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(IPPool.class, IPPoolList.class, this); } @Override public MixedOperation> overlappingRangeIpReservations() { - return OpenShiftHandlers.getOperation(OverlappingRangeIPReservation.class, OverlappingRangeIPReservationList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(OverlappingRangeIPReservation.class, OverlappingRangeIPReservationList.class, this); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftWhereaboutsAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftWhereaboutsAPIGroupExtensionAdapter.java index f8163ff9139..bfa6dd6047a 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftWhereaboutsAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenShiftWhereaboutsAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class OpenShiftWhereaboutsAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,7 +31,7 @@ public Class getExtensionType() { @Override protected OpenShiftWhereaboutsAPIGroupClient newInstance(Client client) { - return new OpenShiftWhereaboutsAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new OpenShiftWhereaboutsAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenshiftAdapterSupport.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenshiftAdapterSupport.java index 1bc305a921e..71973189dc0 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/OpenshiftAdapterSupport.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenshiftAdapterSupport.java @@ -20,11 +20,10 @@ import io.fabric8.kubernetes.client.BaseClient; import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.KubernetesClientException; -import io.fabric8.kubernetes.client.utils.BackwardsCompatibilityInterceptor; -import io.fabric8.kubernetes.client.utils.ImpersonatorInterceptor; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.utils.HttpClientUtils; +import io.fabric8.kubernetes.client.utils.TokenRefreshInterceptor; import io.fabric8.openshift.client.internal.OpenShiftOAuthInterceptor; -import okhttp3.Authenticator; -import okhttp3.OkHttpClient; import java.net.URI; import java.util.Map; @@ -36,14 +35,14 @@ public class OpenshiftAdapterSupport { public Boolean isAdaptable(Client client) { OpenShiftConfig config = OpenShiftConfig.wrap(client.getConfiguration()); - return hasCustomOpenShiftUrl(config) || isOpenShiftAPIGroups(client.adapt(OkHttpClient.class), config); + return hasCustomOpenShiftUrl(config) || isOpenShiftAPIGroups(client.getHttpClient(), config); } public DefaultOpenShiftClient adapt(Client client) { if (!isAdaptable(client)) { throw new OpenShiftNotAvailableException("OpenShift is not available. Root paths at: " + client.getMasterUrl() + " do not include oapi."); } - return new DefaultOpenShiftClient(client.adapt(OkHttpClient.class), OpenShiftConfig.wrap(client.getConfiguration())); + return new DefaultOpenShiftClient(client); } /** @@ -52,14 +51,14 @@ public DefaultOpenShiftClient adapt(Client client) { * @param config {@link OpenShiftConfig} OpenShift Configuration * @return True if oapi is found in the root paths. */ - public static boolean isOpenShiftAPIGroups(OkHttpClient client, OpenShiftConfig config) { + public static boolean isOpenShiftAPIGroups(HttpClient client, OpenShiftConfig config) { if (config.isDisableApiGroupCheck()) { return true; } String url = config.getMasterUrl(); return API_GROUPS_ENABLED_PER_URL.computeIfAbsent(url, k -> { - APIGroupList apiGroups = new BaseClient(adaptOkHttpClient(client, config), config).getApiGroups(); + APIGroupList apiGroups = new BaseClient(adaptHttpClient(client, config), config).getApiGroups(); if (apiGroups == null) { return false; } @@ -88,18 +87,15 @@ static boolean hasCustomOpenShiftUrl(OpenShiftConfig config) { /** * Creates a new OkHttpClient from the provided one with OpenShift specific interceptors and configurations. * - * @param okHttpClient the client to adapt. + * @param httpClient the client to adapt. * @param config the OpenShift configuration. * @return an adapted OkHttpClient instance */ - public static OkHttpClient adaptOkHttpClient(OkHttpClient okHttpClient, OpenShiftConfig config) { - OkHttpClient.Builder builder = okHttpClient != null ? - okHttpClient.newBuilder().authenticator(Authenticator.NONE) : - new OkHttpClient.Builder().authenticator(Authenticator.NONE); - builder.interceptors().clear(); - return builder.addInterceptor(new OpenShiftOAuthInterceptor(okHttpClient, config)) - .addInterceptor(new ImpersonatorInterceptor(config)) - .addInterceptor(new BackwardsCompatibilityInterceptor()) - .build(); + public static HttpClient adaptHttpClient(HttpClient httpClient, OpenShiftConfig config) { + if (httpClient == null) { + httpClient = HttpClientUtils.createHttpClient(config); + } + HttpClient.Builder builder = httpClient.newBuilder().authenticatorNone(); + return builder.addOrReplaceInterceptor(TokenRefreshInterceptor.NAME, new OpenShiftOAuthInterceptor(httpClient, config)).build(); } } diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/MockOkhttpClientUtils.java b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenshiftClientContext.java similarity index 74% rename from kubernetes-client/src/test/java/io/fabric8/kubernetes/client/MockOkhttpClientUtils.java rename to openshift-client/src/main/java/io/fabric8/openshift/client/OpenshiftClientContext.java index 60a069385aa..1381d3774a4 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/MockOkhttpClientUtils.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/OpenshiftClientContext.java @@ -13,7 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package io.fabric8.kubernetes.client; -public class MockOkhttpClientUtils { +package io.fabric8.openshift.client; + +import io.fabric8.kubernetes.client.ClientContext; + +public interface OpenshiftClientContext extends ClientContext { + + @Override + OpenShiftConfig getConfiguration(); + } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/V1OpenShiftClusterAutoscalingAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/V1OpenShiftClusterAutoscalingAPIGroupClient.java index 580b28a1eb5..ec2144edc02 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/V1OpenShiftClusterAutoscalingAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/V1OpenShiftClusterAutoscalingAPIGroupClient.java @@ -15,27 +15,24 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.Handlers; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.openshift.api.model.clusterautoscaling.v1.ClusterAutoscaler; import io.fabric8.openshift.api.model.clusterautoscaling.v1.ClusterAutoscalerList; import io.fabric8.openshift.client.dsl.V1ClusterAutoscalingAPIGroupDSL; -import okhttp3.OkHttpClient; -public class V1OpenShiftClusterAutoscalingAPIGroupClient extends BaseClient implements V1ClusterAutoscalingAPIGroupDSL { +public class V1OpenShiftClusterAutoscalingAPIGroupClient extends BaseOpenShiftClient implements V1ClusterAutoscalingAPIGroupDSL { public V1OpenShiftClusterAutoscalingAPIGroupClient() { super(); } - public V1OpenShiftClusterAutoscalingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1OpenShiftClusterAutoscalingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public NonNamespaceOperation> clusterAutoscalers() { - return OpenShiftHandlers.getOperation(ClusterAutoscaler.class, ClusterAutoscalerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(ClusterAutoscaler.class, ClusterAutoscalerList.class, this); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/V1OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/V1OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java index 00932507f72..5c3d130bbb3 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/V1OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/V1OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1OpenShiftClusterAutoscalingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType() { @Override protected V1OpenShiftClusterAutoscalingAPIGroupClient newInstance(Client client) { - return new V1OpenShiftClusterAutoscalingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1OpenShiftClusterAutoscalingAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/V1beta1OpenShiftClusterAutoscalingAPIGroupClient.java b/openshift-client/src/main/java/io/fabric8/openshift/client/V1beta1OpenShiftClusterAutoscalingAPIGroupClient.java index bf89edfb306..97cdb150350 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/V1beta1OpenShiftClusterAutoscalingAPIGroupClient.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/V1beta1OpenShiftClusterAutoscalingAPIGroupClient.java @@ -15,27 +15,24 @@ */ package io.fabric8.openshift.client; -import io.fabric8.kubernetes.client.BaseClient; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.Handlers; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.openshift.api.model.clusterautoscaling.v1beta1.MachineAutoscaler; import io.fabric8.openshift.api.model.clusterautoscaling.v1beta1.MachineAutoscalerList; import io.fabric8.openshift.client.dsl.V1beta1ClusterAutoscalingAPIGroupDSL; -import okhttp3.OkHttpClient; -public class V1beta1OpenShiftClusterAutoscalingAPIGroupClient extends BaseClient implements V1beta1ClusterAutoscalingAPIGroupDSL { +public class V1beta1OpenShiftClusterAutoscalingAPIGroupClient extends BaseOpenShiftClient implements V1beta1ClusterAutoscalingAPIGroupDSL { public V1beta1OpenShiftClusterAutoscalingAPIGroupClient() { super(); } - public V1beta1OpenShiftClusterAutoscalingAPIGroupClient(OkHttpClient httpClient, final Config config) { - super(httpClient, config); + public V1beta1OpenShiftClusterAutoscalingAPIGroupClient(ClientContext clientContext) { + super(clientContext); } @Override public MixedOperation> machineAutoscalers() { - return OpenShiftHandlers.getOperation(MachineAutoscaler.class, MachineAutoscalerList.class, httpClient, OpenShiftConfig.wrap(getConfiguration())); + return OpenShiftHandlers.getOperation(MachineAutoscaler.class, MachineAutoscalerList.class, this); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/V1beta1OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java b/openshift-client/src/main/java/io/fabric8/openshift/client/V1beta1OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java index cb2ba9048e6..f440e589f28 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/V1beta1OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/V1beta1OpenShiftClusterAutoscalingAPIGroupExtensionAdapter.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.client.APIGroupExtensionAdapter; import io.fabric8.kubernetes.client.Client; -import okhttp3.OkHttpClient; public class V1beta1OpenShiftClusterAutoscalingAPIGroupExtensionAdapter extends APIGroupExtensionAdapter { @Override @@ -32,6 +31,6 @@ public Class getExtensionType( @Override protected V1beta1OpenShiftClusterAutoscalingAPIGroupClient newInstance(Client client) { - return new V1beta1OpenShiftClusterAutoscalingAPIGroupClient(client.adapt(OkHttpClient.class), client.getConfiguration()); + return new V1beta1OpenShiftClusterAutoscalingAPIGroupClient(client); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/ProjectRequestsOperationImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/ProjectRequestsOperationImpl.java index f4c8235dbf9..7ad7b072c03 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/ProjectRequestsOperationImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/ProjectRequestsOperationImpl.java @@ -21,26 +21,25 @@ import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.base.OperationContext; import io.fabric8.kubernetes.client.dsl.base.OperationSupport; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; +import io.fabric8.kubernetes.client.utils.URLUtils.URLBuilder; import io.fabric8.kubernetes.client.utils.Utils; import io.fabric8.openshift.api.model.ProjectRequest; import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.ProjectRequestOperation; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; -import java.util.concurrent.ExecutionException; import static io.fabric8.openshift.client.OpenShiftAPIGroups.PROJECT; // TODO: Check why this class does not extend OpenshiftOperation, then the getRoot method can be removed public class ProjectRequestsOperationImpl extends OperationSupport implements ProjectRequestOperation { - public ProjectRequestsOperationImpl(OkHttpClient client, OpenShiftConfig config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public ProjectRequestsOperationImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public ProjectRequestsOperationImpl(OperationContext context) { @@ -89,7 +88,7 @@ public ProjectRequest create(ProjectRequest... resources) { } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(ie); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(e); } @@ -103,16 +102,7 @@ public ProjectRequest create(ProjectRequest resource) { @Override public Status list() { - try { - URL requestUrl = getNamespacedUrl(); - Request.Builder requestBuilder = new Request.Builder().get().url(requestUrl); - return handleResponse(requestBuilder, Status.class); - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - throw KubernetesClientException.launderThrowable(ie); - } catch (ExecutionException | IOException e) { - throw KubernetesClientException.launderThrowable(e); - } + return list(new ListOptions()); } @Override @@ -123,7 +113,7 @@ public Status list(Integer limitVal, String continueVal) { @Override public Status list(ListOptions listOptions) { try { - HttpUrl.Builder urlBuilder = HttpUrl.get(getNamespacedUrl().toString()).newBuilder(); + URLBuilder urlBuilder = new URLBuilder(getNamespacedUrl().toString()); if(listOptions.getLimit() != null) { urlBuilder.addQueryParameter("limit", listOptions.getLimit().toString()); } @@ -150,12 +140,11 @@ public Status list(ListOptions listOptions) { if (listOptions.getAllowWatchBookmarks() != null) { urlBuilder.addQueryParameter("allowWatchBookmarks", listOptions.getAllowWatchBookmarks().toString()); } - Request.Builder requestBuilder = new Request.Builder().get().url(urlBuilder.build()); - return handleResponse(requestBuilder, Status.class); + return handleGet(urlBuilder.build(), Status.class); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(ie); - } catch (ExecutionException | IOException e) { + } catch (IOException e) { throw KubernetesClientException.launderThrowable(e); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/apps/DeploymentConfigOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/apps/DeploymentConfigOperationsImpl.java index 5bc6dbd2124..0d5cdbc397f 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/apps/DeploymentConfigOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/apps/DeploymentConfigOperationsImpl.java @@ -17,7 +17,6 @@ import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.autoscaling.v1.Scale; -import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.KubernetesClientTimeoutException; import io.fabric8.kubernetes.client.dsl.LogWatch; @@ -25,26 +24,24 @@ import io.fabric8.kubernetes.client.dsl.PodResource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; import io.fabric8.kubernetes.client.dsl.base.PatchContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.LogWatchCallback; import io.fabric8.kubernetes.client.dsl.internal.RollingOperationContext; import io.fabric8.kubernetes.client.utils.PodOperationUtil; import io.fabric8.kubernetes.client.utils.URLUtils; +import io.fabric8.kubernetes.client.utils.URLUtils.URLBuilder; import io.fabric8.openshift.api.model.DeploymentConfig; import io.fabric8.openshift.api.model.DeploymentConfigList; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.DeployableScalableResource; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; import java.io.OutputStream; import java.io.Reader; import java.net.MalformedURLException; +import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -64,8 +61,8 @@ public class DeploymentConfigOperationsImpl extends OpenShiftOperation T doGetLog(Boolean isPretty, Class type) { try { - Request.Builder requestBuilder = new Request.Builder().get().url(getResourceLogUrl(isPretty, false)); - Request request = requestBuilder.build(); - Response response = client.newCall(request).execute(); - ResponseBody body = response.body(); - assertResponseCode(request, response); - return body; + URL url = getResourceLogUrl(isPretty, false); + return handleRawGet(url, type); } catch (Throwable t) { throw KubernetesClientException.launderThrowable(forOperationType("doGetLog"), t); } @@ -229,7 +218,7 @@ private ResponseBody doGetLog(Boolean isPretty) { */ @Override public Reader getLogReader() { - return doGetLog(false).charStream(); + return doGetLog(false, Reader.class); } @Override @@ -242,19 +231,16 @@ public LogWatch watchLog(OutputStream out) { try { // In case of DeploymentConfig we directly get logs at DeploymentConfig Url, but we need to wait for Pods waitUntilDeploymentConfigPodBecomesReady(fromServer().get()); - Request request = new Request.Builder().url(getResourceLogUrl(false, true)).get().build(); - final LogWatchCallback callback = new LogWatchCallback(out); - OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build(); - clone.newCall(request).enqueue(callback); - callback.waitUntilReady(); - return callback; + URL url = getResourceLogUrl(false, true); + final LogWatchCallback callback = new LogWatchCallback(this.config, out); + return callback.callAndWait(this.httpClient, url); } catch (Throwable t) { throw KubernetesClientException.launderThrowable(forOperationType("watchLog"), t); } } - private HttpUrl getResourceLogUrl(Boolean withPrettyOutput, Boolean follow) throws MalformedURLException { - HttpUrl.Builder requestUrlBuilder = HttpUrl.get(URLUtils.join(getResourceUrl().toString(), "log")).newBuilder(); + private URL getResourceLogUrl(Boolean withPrettyOutput, Boolean follow) throws MalformedURLException { + URLBuilder requestUrlBuilder = new URLBuilder(URLUtils.join(getResourceUrl().toString(), "log")); if (Boolean.TRUE.equals(withPrettyOutput)) { requestUrlBuilder.addQueryParameter("pretty", withPrettyOutput.toString()); } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/authorization/ClusterRoleBindingOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/authorization/ClusterRoleBindingOperationsImpl.java index 381ba6664cb..dca6b7aa447 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/authorization/ClusterRoleBindingOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/authorization/ClusterRoleBindingOperationsImpl.java @@ -18,19 +18,19 @@ import io.fabric8.kubernetes.api.builder.VisitableBuilder; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.openshift.api.model.ClusterRoleBinding; import io.fabric8.openshift.api.model.ClusterRoleBindingBuilder; import io.fabric8.openshift.api.model.ClusterRoleBindingList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.OkHttpClient; import static io.fabric8.openshift.client.OpenShiftAPIGroups.AUTHORIZATION; public class ClusterRoleBindingOperationsImpl extends OpenShiftOperation> { - public ClusterRoleBindingOperationsImpl(OkHttpClient client, OpenShiftConfig config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public ClusterRoleBindingOperationsImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public ClusterRoleBindingOperationsImpl(OperationContext context) { diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/authorization/RoleBindingOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/authorization/RoleBindingOperationsImpl.java index 59c965f8e0d..61065acf8f9 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/authorization/RoleBindingOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/authorization/RoleBindingOperationsImpl.java @@ -21,16 +21,15 @@ import io.fabric8.kubernetes.api.model.ObjectReferenceBuilder; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.openshift.api.model.RoleBinding; import io.fabric8.openshift.api.model.RoleBindingBuilder; import io.fabric8.openshift.api.model.RoleBindingList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.OkHttpClient; import java.io.IOException; import java.util.List; -import java.util.concurrent.ExecutionException; import java.util.function.Supplier; import static io.fabric8.openshift.client.OpenShiftAPIGroups.AUTHORIZATION; @@ -41,8 +40,8 @@ public class RoleBindingOperationsImpl extends OpenShiftOperation> { - public RoleOperationsImpl(OkHttpClient client, OpenShiftConfig config) { - this((new OperationContext()).withOkhttpClient(client).withConfig(config)); + public RoleOperationsImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public RoleOperationsImpl(OperationContext context) { diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/build/BuildConfigOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/build/BuildConfigOperationsImpl.java index 928ae3469c7..73231c3c880 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/build/BuildConfigOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/build/BuildConfigOperationsImpl.java @@ -18,13 +18,15 @@ import io.fabric8.kubernetes.api.builder.VisitableBuilder; import io.fabric8.kubernetes.api.model.Event; import io.fabric8.kubernetes.api.model.EventList; -import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.Handlers; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.Triggerable; import io.fabric8.kubernetes.client.dsl.Typeable; import io.fabric8.kubernetes.client.dsl.base.OperationContext; import io.fabric8.kubernetes.client.dsl.base.OperationSupport; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.kubernetes.client.utils.Utils; @@ -34,7 +36,7 @@ import io.fabric8.openshift.api.model.BuildConfigList; import io.fabric8.openshift.api.model.BuildRequest; import io.fabric8.openshift.api.model.WebHookTrigger; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.BuildConfigOperation; import io.fabric8.openshift.client.dsl.BuildConfigResource; import io.fabric8.openshift.client.dsl.InputStreamable; @@ -47,17 +49,9 @@ import io.fabric8.openshift.client.dsl.buildconfig.MessageAsFileTimeoutInputStreamable; import io.fabric8.openshift.client.dsl.internal.BuildConfigOperationContext; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okio.BufferedSink; -import okio.Okio; -import okio.Source; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -91,8 +85,8 @@ public class BuildConfigOperationsImpl extends OpenShiftOperation withType(String triggerType) { @Override public Build fromInputStream(final InputStream inputStream) { - return fromInputStream(inputStream, -1L); + return submitToApiServer(inputStream, -1L); } @Override @@ -176,16 +168,12 @@ public Build fromFile(final File file) { // Use a length to prevent chunked encoding with OkHttp, which in turn // doesn't work with 'Expect: 100-continue' negotiation with the OpenShift API server logger.debug("Uploading archive file \"{}\" as binary input for the build ...", file.getAbsolutePath()); - return fromInputStream(is, file.length()); + return submitToApiServer(is, file.length()); } catch (IOException e) { throw KubernetesClientException.launderThrowable(e); } } - private Build fromInputStream(final InputStream inputStream, final long contentLength) { - return submitToApiServerWithRequestBody(new ArchiveFileInputStreamRequestBody(client, config, inputStream, contentLength, name, namespace)); - } - private String getQueryParameters() throws MalformedURLException { StringBuilder sb = new StringBuilder(); sb.append(URLUtils.join(getResourceUrl().toString(), "instantiatebinary")); @@ -277,79 +265,42 @@ public Typeable> withSecret(String secret) { return new BuildConfigBuilder(item); } - protected Build submitToApiServerWithRequestBody(RequestBody requestBody) { + protected Build submitToApiServer(InputStream inputStream, long contentLength) { try { - OkHttpClient newClient = client.newBuilder() + HttpClient newClient = this.httpClient.newBuilder() .readTimeout(timeout, timeoutUnit) .writeTimeout(timeout, timeoutUnit) .build(); - Request.Builder requestBuilder = - new Request.Builder().post(requestBody) - .header("Expect", "100-continue") - .url(getQueryParameters()); + HttpRequest.Builder requestBuilder = + this.httpClient.newHttpRequestBuilder().post("application/octet-stream", inputStream, contentLength) + .expectContinue() + .uri(getQueryParameters()); return handleResponse(newClient, requestBuilder, Build.class); - } catch (Exception e) { + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(e); + } catch (Throwable e) { + // TODO: better determine which exception this should occur on + // otherwise we need to have the httpclient api open up to the notion + // of a RequestBody/BodyPublisher + logger.error("Failed to upload archive file for the build: {}", name); + logger.error("Please check cluster events via `oc get events` to see what could have possibly gone wrong"); + throw new KubernetesClientException("Can't instantiate binary build, due to error reading/writing stream. " + + "Can be caused if the output stream was closed by the server." + + "See if something's wrong in recent events in Cluster = " + getRecentEvents(), e); } } - public static class ArchiveFileInputStreamRequestBody extends RequestBody { - private long contentLength; - private InputStream inputStream; - private OkHttpClient okHttpClient; - private Config clientConfig; - private String name; - private String namespace; - public ArchiveFileInputStreamRequestBody(OkHttpClient client, Config config, InputStream inputStream, long contentLength, String name, String namespace) { - this.contentLength = contentLength; - this.inputStream = inputStream; - this.okHttpClient = client; - this.clientConfig = config; - this.name = name; - this.namespace = namespace; - } - - @Override - public MediaType contentType() { - return MediaType.parse("application/octet-stream"); - } - - @Override - public long contentLength() throws IOException { - return contentLength; - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - try { - writeToSink(sink); - } catch (IOException e) { - logger.error("Failed to upload archive file for the build: {}", name); - logger.error("Please check cluster events via `oc get events` to see what could have possibly gone wrong"); - throw KubernetesClientException.launderThrowable("Can't instantiate binary build, due to error reading/writing stream. " - + "Can be caused if the output stream was closed by the server." + - "See if something's wrong in recent events in Cluster = " + getRecentEvents(), e); - } - } - - public void writeToSink(BufferedSink sink) throws IOException { - try (final BufferedInputStream bis = new BufferedInputStream(inputStream); - final Source source = Okio.source(bis)) { - sink.writeAll(source); - } - } - - protected String getRecentEvents() { - StringBuilder eventsAsStrBuilder = new StringBuilder(); - List recentEventList = Handlers.getOperation(Event.class, EventList.class, okHttpClient, clientConfig).inNamespace(namespace).list().getItems(); - KubernetesResourceUtil.sortEventListBasedOnTimestamp(recentEventList); - for (int i = 0; i < 10 && i < recentEventList.size(); i++) { - Event event = recentEventList.get(i); - eventsAsStrBuilder.append(event.getReason()).append(" ") - .append(event.getMetadata().getName()).append(" ") - .append(event.getMessage()).append("\n"); - } - return eventsAsStrBuilder.toString(); + protected String getRecentEvents() { + StringBuilder eventsAsStrBuilder = new StringBuilder(); + List recentEventList = Handlers.getOperation(Event.class, EventList.class, context).inNamespace(namespace).list().getItems(); + KubernetesResourceUtil.sortEventListBasedOnTimestamp(recentEventList); + for (int i = 0; i < 10 && i < recentEventList.size(); i++) { + Event event = recentEventList.get(i); + eventsAsStrBuilder.append(event.getReason()).append(" ") + .append(event.getMetadata().getName()).append(" ") + .append(event.getMessage()).append("\n"); } + return eventsAsStrBuilder.toString(); } } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/build/BuildOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/build/BuildOperationsImpl.java index 56ef3a162ba..9c1473f2775 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/build/BuildOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/build/BuildOperationsImpl.java @@ -26,6 +26,7 @@ import io.fabric8.kubernetes.client.dsl.TailPrettyLoggable; import io.fabric8.kubernetes.client.dsl.TimeTailPrettyLoggable; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.LogWatchCallback; import io.fabric8.kubernetes.client.internal.PatchUtils; import io.fabric8.kubernetes.client.utils.PodOperationUtil; @@ -33,15 +34,11 @@ import io.fabric8.openshift.api.model.Build; import io.fabric8.openshift.api.model.BuildBuilder; import io.fabric8.openshift.api.model.BuildList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.BuildResource; import io.fabric8.openshift.client.dsl.internal.BuildOperationContext; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; import io.fabric8.openshift.client.internal.patchmixins.BuildMixIn; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; import java.io.IOException; import java.io.OutputStream; @@ -50,7 +47,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.TimeUnit; import static io.fabric8.openshift.client.OpenShiftAPIGroups.BUILD; @@ -71,8 +67,8 @@ public class BuildOperationsImpl extends OpenShiftOperation T doGetLog(Class type){ try { URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters())); - Request.Builder requestBuilder = new Request.Builder().get().url(url); - Request request = requestBuilder.build(); - Response response = client.newCall(request).execute(); - ResponseBody body = response.body(); - assertResponseCode(request, response); - return body; + return handleRawGet(url, type); } catch (IOException t) { throw KubernetesClientException.launderThrowable(forOperationType("doGetLog"), t); } @@ -141,11 +132,7 @@ protected ResponseBody doGetLog(){ @Override public String getLog() { - try(ResponseBody body = doGetLog()) { - return doGetLog().string(); - } catch (IOException e) { - throw KubernetesClientException.launderThrowable(forOperationType("getLog"), e); - } + return doGetLog(String.class); } @Override @@ -159,7 +146,7 @@ public String getLog(Boolean isPretty) { */ @Override public Reader getLogReader(){ - return doGetLog().charStream(); + return doGetLog(Reader.class); } @Override @@ -173,12 +160,8 @@ public LogWatch watchLog(OutputStream out) { // In case of Build we directly get logs at Build Url, but we need to wait for Pods waitUntilBuildPodBecomesReady(fromServer().get()); URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters() + "&follow=true")); - Request request = new Request.Builder().url(url).get().build(); - final LogWatchCallback callback = new LogWatchCallback(out); - OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build(); - clone.newCall(request).enqueue(callback); - callback.waitUntilReady(); - return callback; + final LogWatchCallback callback = new LogWatchCallback(this.config, out); + return callback.callAndWait(this.httpClient, url); } catch (IOException t) { throw KubernetesClientException.launderThrowable(forOperationType("watchLog"), t); } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/config/DNSOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/config/DNSOperationsImpl.java index 586193102e6..06f28736019 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/config/DNSOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/config/DNSOperationsImpl.java @@ -18,17 +18,17 @@ import io.fabric8.kubernetes.api.builder.VisitableBuilder; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.openshift.api.model.DNS; import io.fabric8.openshift.api.model.DNSBuilder; import io.fabric8.openshift.api.model.DNSList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.OkHttpClient; public class DNSOperationsImpl extends OpenShiftOperation> { - public DNSOperationsImpl(OkHttpClient client, OpenShiftConfig config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public DNSOperationsImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public DNSOperationsImpl(OperationContext context) { diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/core/NetworkAttachmentDefinitionOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/core/NetworkAttachmentDefinitionOperationsImpl.java index bc618723d67..d17a7739df4 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/core/NetworkAttachmentDefinitionOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/core/NetworkAttachmentDefinitionOperationsImpl.java @@ -18,17 +18,17 @@ import io.fabric8.kubernetes.api.builder.Visitor; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.openshift.api.model.miscellaneous.cncf.cni.v1.NetworkAttachmentDefinition; import io.fabric8.openshift.api.model.miscellaneous.cncf.cni.v1.NetworkAttachmentDefinitionBuilder; import io.fabric8.openshift.api.model.miscellaneous.cncf.cni.v1.NetworkAttachmentDefinitionList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.OkHttpClient; public class NetworkAttachmentDefinitionOperationsImpl extends OpenShiftOperation> { - public NetworkAttachmentDefinitionOperationsImpl(OkHttpClient client, OpenShiftConfig config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)); + public NetworkAttachmentDefinitionOperationsImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public NetworkAttachmentDefinitionOperationsImpl(OperationContext context) { diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/core/TemplateOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/core/TemplateOperationsImpl.java index 211655c747f..189cb7cf145 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/core/TemplateOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/core/TemplateOperationsImpl.java @@ -25,6 +25,9 @@ import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpRequest.Builder; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.kubernetes.client.utils.Utils; @@ -32,14 +35,11 @@ import io.fabric8.openshift.api.model.Template; import io.fabric8.openshift.api.model.TemplateBuilder; import io.fabric8.openshift.api.model.TemplateList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.ParameterValue; import io.fabric8.openshift.client.dsl.TemplateOperation; import io.fabric8.openshift.client.dsl.TemplateResource; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -56,7 +56,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.ExecutionException; import static io.fabric8.openshift.client.OpenShiftAPIGroups.TEMPLATE; @@ -71,8 +70,8 @@ public class TemplateOperationsImpl private final Map parameters; - public TemplateOperationsImpl(OkHttpClient client, OpenShiftConfig config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config), null); + public TemplateOperationsImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext), null); } public TemplateOperationsImpl(OperationContext context, Map parameters) { @@ -119,8 +118,7 @@ public KubernetesList process(Map valuesMap) { } } - RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(t)); - Request.Builder requestBuilder = new Request.Builder().post(body).url(getProcessUrl()); + HttpRequest.Builder requestBuilder = this.httpClient.newHttpRequestBuilder().post(JSON, JSON_MAPPER.writeValueAsString(t)).url(getProcessUrl()); t = handleResponse(requestBuilder); KubernetesList l = new KubernetesList(); l.setItems(t.getObjects()); @@ -279,12 +277,13 @@ public TemplateResource load(InputStream is) { } @Override - protected Template handleGet(URL resourceUrl) throws InterruptedException, ExecutionException, IOException { + protected Template handleGet(URL resourceUrl) throws InterruptedException, IOException { return super.handleGet(resourceUrl, getType(), this.parameters); } @Override - protected T handleResponse(Request.Builder requestBuilder, Class type) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { + protected T handleResponse(Builder requestBuilder, Class type) + throws InterruptedException, IOException { return handleResponse(requestBuilder, type, parameters); } diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthAccessTokenOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthAccessTokenOperationsImpl.java index bda9f68225c..5ed5734b141 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthAccessTokenOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthAccessTokenOperationsImpl.java @@ -17,19 +17,19 @@ import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; -import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.OkHttpClient; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.openshift.api.model.OAuthAccessToken; import io.fabric8.openshift.api.model.OAuthAccessTokenList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; +import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; import static io.fabric8.openshift.client.OpenShiftAPIGroups.OAUTH; public class OAuthAccessTokenOperationsImpl extends OpenShiftOperation> { - public OAuthAccessTokenOperationsImpl(OkHttpClient client, OpenShiftConfig config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public OAuthAccessTokenOperationsImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public OAuthAccessTokenOperationsImpl(OperationContext context) { diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthAuthorizeTokenOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthAuthorizeTokenOperationsImpl.java index 0ee5c4b65b3..a45680870a2 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthAuthorizeTokenOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthAuthorizeTokenOperationsImpl.java @@ -18,20 +18,20 @@ import io.fabric8.kubernetes.api.builder.VisitableBuilder; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.openshift.api.model.OAuthAuthorizeToken; import io.fabric8.openshift.api.model.OAuthAuthorizeTokenBuilder; import io.fabric8.openshift.api.model.OAuthAuthorizeTokenList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.OkHttpClient; import static io.fabric8.openshift.client.OpenShiftAPIGroups.OAUTH; public class OAuthAuthorizeTokenOperationsImpl extends OpenShiftOperation> { - public OAuthAuthorizeTokenOperationsImpl(OkHttpClient client, OpenShiftConfig config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public OAuthAuthorizeTokenOperationsImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public OAuthAuthorizeTokenOperationsImpl(OperationContext context) { diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthClientOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthClientOperationsImpl.java index d53ace7d6a8..10ee7d8fef5 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthClientOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/oauth/OAuthClientOperationsImpl.java @@ -18,20 +18,20 @@ import io.fabric8.kubernetes.api.builder.VisitableBuilder; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.openshift.api.model.OAuthClient; import io.fabric8.openshift.api.model.OAuthClientBuilder; import io.fabric8.openshift.api.model.OAuthClientList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.OkHttpClient; import static io.fabric8.openshift.client.OpenShiftAPIGroups.OAUTH; public class OAuthClientOperationsImpl extends OpenShiftOperation> { - public OAuthClientOperationsImpl(OkHttpClient client, OpenShiftConfig config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public OAuthClientOperationsImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public OAuthClientOperationsImpl(OperationContext context) { diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/project/ProjectOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/project/ProjectOperationsImpl.java index 062a9d33803..bc9a54c3661 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/project/ProjectOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/project/ProjectOperationsImpl.java @@ -21,15 +21,15 @@ import io.fabric8.kubernetes.api.model.rbac.RoleBindingBuilder; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.kubernetes.client.dsl.internal.NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl; import io.fabric8.kubernetes.client.dsl.internal.NamespaceVisitOperationContext; import io.fabric8.openshift.api.model.Project; import io.fabric8.openshift.api.model.ProjectBuilder; import io.fabric8.openshift.api.model.ProjectList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.ProjectOperation; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.OkHttpClient; import java.util.ArrayList; import java.util.List; @@ -45,8 +45,8 @@ public class ProjectOperationsImpl extends OpenShiftOperation> { - public SecurityContextConstraintsOperationsImpl(OkHttpClient client, OpenShiftConfig config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public SecurityContextConstraintsOperationsImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public SecurityContextConstraintsOperationsImpl(OperationContext context) { diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/user/GroupOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/user/GroupOperationsImpl.java index a086f2feb34..930b7d354e2 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/user/GroupOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/user/GroupOperationsImpl.java @@ -18,19 +18,19 @@ import io.fabric8.kubernetes.api.builder.VisitableBuilder; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.openshift.api.model.Group; import io.fabric8.openshift.api.model.GroupBuilder; import io.fabric8.openshift.api.model.GroupList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.OkHttpClient; import static io.fabric8.openshift.client.OpenShiftAPIGroups.USER; public class GroupOperationsImpl extends OpenShiftOperation> { - public GroupOperationsImpl(OkHttpClient client, OpenShiftConfig config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public GroupOperationsImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public GroupOperationsImpl(OperationContext context) { diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/user/UserOperationsImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/user/UserOperationsImpl.java index 748263056de..174e2f90c27 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/user/UserOperationsImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/user/UserOperationsImpl.java @@ -18,19 +18,19 @@ import io.fabric8.kubernetes.api.builder.VisitableBuilder; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.dsl.base.OperationContext; +import io.fabric8.kubernetes.client.dsl.internal.HasMetadataOperationsImpl; import io.fabric8.openshift.api.model.User; import io.fabric8.openshift.api.model.UserBuilder; import io.fabric8.openshift.api.model.UserList; -import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenshiftClientContext; import io.fabric8.openshift.client.dsl.internal.OpenShiftOperation; -import okhttp3.OkHttpClient; import static io.fabric8.openshift.client.OpenShiftAPIGroups.USER; public class UserOperationsImpl extends OpenShiftOperation> { - public UserOperationsImpl(OkHttpClient client, OpenShiftConfig config) { - this(new OperationContext().withOkhttpClient(client).withConfig(config)); + public UserOperationsImpl(OpenshiftClientContext clientContext) { + this(HasMetadataOperationsImpl.defaultContext(clientContext)); } public UserOperationsImpl(OperationContext context) { diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/internal/OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java b/openshift-client/src/main/java/io/fabric8/openshift/client/internal/OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java index 25cbd8985eb..f0fdd4e1d55 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/internal/OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/internal/OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java @@ -19,7 +19,7 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesList; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; -import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ClientContext; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.base.OperationContext; import io.fabric8.kubernetes.client.dsl.internal.NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl; @@ -27,7 +27,6 @@ import io.fabric8.kubernetes.client.utils.Utils; import io.fabric8.openshift.api.model.Parameter; import io.fabric8.openshift.api.model.Template; -import okhttp3.OkHttpClient; import java.io.IOException; import java.util.ArrayList; @@ -36,9 +35,8 @@ public class OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl extends NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl { - public OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(OkHttpClient client, - Config config, Object item) { - super(client, config, item); + public OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(ClientContext clientContext, Object item) { + super(clientContext, item); } public OpenShiftNamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(OperationContext context, NamespaceVisitOperationContext namespaceVisitOperationContext) { diff --git a/openshift-client/src/main/java/io/fabric8/openshift/client/internal/OpenShiftOAuthInterceptor.java b/openshift-client/src/main/java/io/fabric8/openshift/client/internal/OpenShiftOAuthInterceptor.java index 41b0fadfa1b..70a59b7bce8 100644 --- a/openshift-client/src/main/java/io/fabric8/openshift/client/internal/OpenShiftOAuthInterceptor.java +++ b/openshift-client/src/main/java/io/fabric8/openshift/client/internal/OpenShiftOAuthInterceptor.java @@ -20,7 +20,15 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.authorization.v1.SelfSubjectAccessReview; import io.fabric8.kubernetes.client.KubernetesClientException; +import io.fabric8.kubernetes.client.http.BasicBuilder; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpHeaders; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.http.Interceptor; +import io.fabric8.kubernetes.client.utils.HttpClientUtils; import io.fabric8.kubernetes.client.utils.Serialization; +import io.fabric8.kubernetes.client.utils.TokenRefreshInterceptor; import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.kubernetes.client.utils.Utils; import io.fabric8.openshift.api.model.LocalResourceAccessReview; @@ -30,17 +38,12 @@ import io.fabric8.openshift.api.model.SubjectAccessReview; import io.fabric8.openshift.api.model.SubjectRulesReview; import io.fabric8.openshift.client.OpenShiftConfig; -import okhttp3.Credentials; -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; @@ -66,35 +69,33 @@ public class OpenShiftOAuthInterceptor implements Interceptor { HasMetadata.getPlural(SelfSubjectAccessReview.class) ))); - private final OkHttpClient client; + private final HttpClient client; private final OpenShiftConfig config; private final AtomicReference oauthToken = new AtomicReference<>(); - public OpenShiftOAuthInterceptor(OkHttpClient client, OpenShiftConfig config) { + public OpenShiftOAuthInterceptor(HttpClient client, OpenShiftConfig config) { this.client = client; this.config = config; } @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - - //Build new request - Request.Builder builder = request.newBuilder(); - + public void before(BasicBuilder builder, HttpHeaders headers) { String token = oauthToken.get(); // avoid overwriting basic auth token with stale bearer token - if (Utils.isNotNullOrEmpty(token) && Utils.isNullOrEmpty(request.header(AUTHORIZATION))) { + if (Utils.isNotNullOrEmpty(token) && (headers.headers(AUTHORIZATION).isEmpty() || Utils.isNullOrEmpty(headers.headers(AUTHORIZATION).get(0)))) { setAuthHeader(builder, token); } + } + + @Override + public boolean afterFailure(BasicBuilder builder, HttpResponse response) { + if (shouldProceed(response.request(), response)) { + return false; + } - request = builder.build(); - Response response = chain.proceed(request); + String token = oauthToken.get(); - //If response is Forbidden or Unauthorized, try to obtain a token via authorize() or via config. - if (isResponseSuccessful(request, response)) { - return response; - } else if (Utils.isNotNullOrEmpty(config.getUsername()) && Utils.isNotNullOrEmpty(config.getPassword())) { + if (Utils.isNotNullOrEmpty(config.getUsername()) && Utils.isNotNullOrEmpty(config.getPassword())) { synchronized (client) { // current token (if exists) is borked, don't resend oauthToken.set(null); @@ -108,53 +109,47 @@ public Response intercept(Chain chain) throws IOException { oauthToken.set(token); } - //If token was obtained, then retry request using the obtained token. if (Utils.isNotNullOrEmpty(token)) { - // Close the previous response to prevent leaked connections. - response.body().close(); - setAuthHeader(builder, token); - request = builder.build(); - return chain.proceed(request); //repeat request with new token - } else { - return response; + return true; } + + return false; } - private void setAuthHeader(Request.Builder builder, String token) { + private void setAuthHeader(BasicBuilder builder, String token) { if (token != null) { - builder.header(AUTHORIZATION, String.format("Bearer %s", token)); + builder.setHeader(AUTHORIZATION, String.format("Bearer %s", token)); } } private String authorize() { try { - OkHttpClient.Builder builder = client.newBuilder(); - builder.interceptors().remove(this); - OkHttpClient clone = builder.build(); + HttpClient.Builder builder = client.newBuilder(); + builder.addOrReplaceInterceptor(TokenRefreshInterceptor.NAME, null); + HttpClient clone = builder.build(); URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZATION_SERVER_PATH)); - Response response = clone.newCall(new Request.Builder().get().url(url).build()).execute(); + HttpResponse response = clone.send(clone.newHttpRequestBuilder().url(url).build(), String.class); if (!response.isSuccessful() || response.body() == null) { throw new KubernetesClientException("Unexpected response (" + response.code() + " " + response.message() + ")"); } - String body = response.body().string(); + String body = response.body(); JsonNode jsonResponse = Serialization.jsonMapper().readTree(body); String authorizationServer = jsonResponse.get("authorization_endpoint").asText(); - response.close(); url = new URL(authorizationServer + AUTHORIZE_QUERY); - String credential = Credentials.basic(config.getUsername(), config.getPassword()); - response = clone.newCall(new Request.Builder().get().url(url).header(AUTHORIZATION, credential).build()).execute(); + String credential = HttpClientUtils.basicCredentials(config.getUsername(), config.getPassword()); + response = clone.send(client.newHttpRequestBuilder().url(url).setHeader(AUTHORIZATION, credential).build(), String.class); + + response = response.previousResponse().isPresent() ? response.previousResponse().get() : response; - response.close(); - response = response.priorResponse() != null ? response.priorResponse() : response; - response = response.networkResponse() != null ? response.networkResponse() : response; - String token = response.header(LOCATION); + List location = response.headers(LOCATION); + String token = !location.isEmpty() ? location.get(0) : null; if (token == null || token.isEmpty()) { throw new KubernetesClientException("Unexpected response (" + response.code() + " " + response.message() + "), to the authorization request. Missing header:[" + LOCATION + "]!"); } @@ -166,8 +161,8 @@ private String authorize() { } } - private boolean isResponseSuccessful(Request request, Response response) { - String url = request.url().toString(); + private boolean shouldProceed(HttpRequest request, HttpResponse response) { + String url = request.uri().toString(); String method = request.method(); // always retry in case of authorization endpoints; since they also return 200 when no // authorization header is provided diff --git a/openshift-client/src/test/java/io/fabric8/openshift/client/dsl/AdaptTest.java b/openshift-client/src/test/java/io/fabric8/openshift/client/dsl/AdaptTest.java index 9d11678a880..06c8d0e5a63 100644 --- a/openshift-client/src/test/java/io/fabric8/openshift/client/dsl/AdaptTest.java +++ b/openshift-client/src/test/java/io/fabric8/openshift/client/dsl/AdaptTest.java @@ -18,7 +18,6 @@ import io.fabric8.openshift.client.DefaultOpenShiftClient; import io.fabric8.openshift.client.OpenShiftClient; import io.fabric8.openshift.client.OpenShiftConfigBuilder; -import okhttp3.OkHttpClient; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -26,16 +25,6 @@ class AdaptTest { - @Test - void testAdaptToHttpClient() { - // Given - OpenShiftClient client = new DefaultOpenShiftClient(); - - // When + Then - assertTrue(client.isAdaptable(OkHttpClient.class)); - assertNotNull(client.adapt(OkHttpClient.class)); - } - @Test void testAdaptDisabledCheck() { // Given diff --git a/openshift-client/src/test/java/io/fabric8/openshift/client/dsl/internal/build/ArchiveFileInputStreamRequestBodyTest.java b/openshift-client/src/test/java/io/fabric8/openshift/client/dsl/internal/build/ArchiveFileInputStreamRequestBodyTest.java deleted file mode 100644 index 76f59a681b1..00000000000 --- a/openshift-client/src/test/java/io/fabric8/openshift/client/dsl/internal/build/ArchiveFileInputStreamRequestBodyTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (C) 2015 Red Hat, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.fabric8.openshift.client.dsl.internal.build; - -import io.fabric8.kubernetes.client.KubernetesClientException; -import io.fabric8.openshift.client.OpenShiftConfig; -import io.fabric8.openshift.client.OpenShiftConfigBuilder; -import io.fabric8.openshift.client.dsl.internal.build.BuildConfigOperationsImpl; -import okhttp3.OkHttpClient; -import okio.BufferedSink; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.Mockito; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doCallRealMethod; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -class ArchiveFileInputStreamRequestBodyTest { - @Mock - OkHttpClient okHttpClient; - - @Mock - OpenShiftConfig config; - - @Mock - BufferedSink bufferedSink; - - @BeforeEach - public void setUp() { - this.okHttpClient = Mockito.mock(OkHttpClient.class, Mockito.RETURNS_DEEP_STUBS); - this.config = new OpenShiftConfigBuilder().withMasterUrl("https://localhost:8443/").build(); - this.bufferedSink = Mockito.mock(BufferedSink.class, Mockito.RETURNS_DEEP_STUBS); - } - - @Test - void testWriteToThrowsExceptionShouldAddEvents() throws IOException { - // Given - File tempFile = File.createTempFile("test-", ".war"); - String eventMessage = "FailedScheduling demo-1-7zkjd.1619493da51f6b6f some error"; - BuildConfigOperationsImpl.ArchiveFileInputStreamRequestBody body = new BuildConfigOperationsImpl.ArchiveFileInputStreamRequestBody(okHttpClient, config, new FileInputStream(tempFile), 50L, "test-bc", "ns1"); - body = spy(body); - doThrow(IOException.class).when(body).writeToSink(any()); - doReturn(eventMessage).when(body).getRecentEvents(); - doCallRealMethod().when(body).writeTo(any()); - - // When - BuildConfigOperationsImpl.ArchiveFileInputStreamRequestBody finalBody = body; - KubernetesClientException exception = assertThrows(KubernetesClientException.class, - () -> finalBody.writeTo(bufferedSink)); - - // Then - assertTrue(exception.getMessage().contains(eventMessage)); - } - - @Test - void testWriteToShouldCompleteSuccessfully() throws IOException { - // Given - BuildConfigOperationsImpl.ArchiveFileInputStreamRequestBody body = mock(BuildConfigOperationsImpl.ArchiveFileInputStreamRequestBody.class, Mockito.RETURNS_DEEP_STUBS); - doNothing().when(body).writeToSink(any()); - - // When - body.writeTo(bufferedSink); - - // Then - verify(body, times(0)).getRecentEvents(); - } -} diff --git a/openshift-client/src/test/java/io/fabric8/openshift/client/dsl/internal/build/BuildConfigOperationsImplTest.java b/openshift-client/src/test/java/io/fabric8/openshift/client/dsl/internal/build/BuildConfigOperationsImplTest.java new file mode 100644 index 00000000000..82250324268 --- /dev/null +++ b/openshift-client/src/test/java/io/fabric8/openshift/client/dsl/internal/build/BuildConfigOperationsImplTest.java @@ -0,0 +1,132 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.fabric8.openshift.client.dsl.internal.build; + +import io.fabric8.kubernetes.client.KubernetesClientException; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.openshift.client.OpenShiftConfig; +import io.fabric8.openshift.client.OpenShiftConfigBuilder; +import io.fabric8.openshift.client.OpenshiftClientContext; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.Mockito; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +class BuildConfigOperationsImplTest { + @Mock + HttpClient httpClient; + + @Mock + OpenShiftConfig config; + + @BeforeEach + public void setUp() { + this.httpClient = Mockito.mock(HttpClient.class, Mockito.RETURNS_DEEP_STUBS); + + HttpRequest response = Mockito.mock(HttpRequest.class, Mockito.CALLS_REAL_METHODS); + when(response.method()).thenReturn("POST"); + when(response.uri()).thenReturn(URI.create("https://localhost:8443/")); + + when(this.httpClient.newBuilder() + .readTimeout(anyLong(), any()) + .writeTimeout(anyLong(), any()) + .build()).thenReturn(httpClient); + when(this.httpClient.newHttpRequestBuilder() + .post(any(), any(), anyLong()) + .header(any(), any()) + .uri(any(String.class)) + .build()).thenReturn(response); + + this.config = new OpenShiftConfigBuilder().withMasterUrl("https://localhost:8443/").build(); + } + + @Test + void testWriteToThrowsExceptionShouldAddEvents() throws IOException { + // Given + String eventMessage = "FailedScheduling demo-1-7zkjd.1619493da51f6b6f some error"; + + BuildConfigOperationsImpl impl = new BuildConfigOperationsImpl(new OpenshiftClientContext() { + + @Override + public HttpClient getHttpClient() { + return httpClient; + } + + @Override + public OpenShiftConfig getConfiguration() { + return config; + } + }) { + @Override + protected String getRecentEvents() { + return eventMessage; + }; + }; + + // When + ByteArrayInputStream inputStream = new ByteArrayInputStream(new byte[0]); + KubernetesClientException exception = assertThrows(KubernetesClientException.class, + () -> impl.submitToApiServer(inputStream, 0)); + + // Then + assertTrue(exception.getMessage().contains(eventMessage)); + } + + @Test + void testWriteShouldCompleteSuccessfully() throws IOException { + // Given + BuildConfigOperationsImpl impl = new BuildConfigOperationsImpl(new OpenshiftClientContext() { + + @Override + public HttpClient getHttpClient() { + return httpClient; + } + + @Override + public OpenShiftConfig getConfiguration() { + return config; + } + }) { + @Override + protected String getRecentEvents() { + throw new AssertionError(); + }; + }; + + HttpResponse response = Mockito.mock(HttpResponse.class, Mockito.CALLS_REAL_METHODS); + when(response.code()).thenReturn(200); + when(response.body()).thenReturn(new ByteArrayInputStream(new byte[0])); + + when(httpClient.send(any(), eq(InputStream.class))).thenReturn(response); + impl.submitToApiServer(new ByteArrayInputStream(new byte[0]), 0); + + Mockito.verify(response, Mockito.times(1)).body(); + } +} diff --git a/openshift-client/src/test/java/io/fabric8/openshift/client/server/mock/OpenShiftMockServer.java b/openshift-client/src/test/java/io/fabric8/openshift/client/server/mock/OpenShiftMockServer.java index 38618c05c8c..420fc26e787 100644 --- a/openshift-client/src/test/java/io/fabric8/openshift/client/server/mock/OpenShiftMockServer.java +++ b/openshift-client/src/test/java/io/fabric8/openshift/client/server/mock/OpenShiftMockServer.java @@ -17,15 +17,11 @@ package io.fabric8.openshift.client.server.mock; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.server.mock.KubernetesMockServer; import io.fabric8.openshift.client.DefaultOpenShiftClient; import io.fabric8.openshift.client.NamespacedOpenShiftClient; import io.fabric8.openshift.client.OpenShiftConfig; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; -import static okhttp3.TlsVersion.TLS_1_2; - @Deprecated // The class has moved under mvn:io.fabric8:openshift-server-mock in package: io.fabric8.openshift.client.server.mock public class OpenShiftMockServer extends KubernetesMockServer { @@ -44,14 +40,9 @@ public String[] getRootPaths() { } public NamespacedOpenShiftClient createOpenShiftClient() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); + Config config = getMockConfiguration(); OpenShiftConfig openShiftConfig = new OpenShiftConfig(config); openShiftConfig.setDisableApiGroupCheck(true); - return new DefaultOpenShiftClient(createHttpClientForMockServer(config), openShiftConfig); + return new DefaultOpenShiftClient(openShiftConfig); } } diff --git a/openshift-client/src/test/java/io/fabric8/openshift/server/mock/OpenShiftMockServer.java b/openshift-client/src/test/java/io/fabric8/openshift/server/mock/OpenShiftMockServer.java index 821a9327e43..7cf05c2470b 100644 --- a/openshift-client/src/test/java/io/fabric8/openshift/server/mock/OpenShiftMockServer.java +++ b/openshift-client/src/test/java/io/fabric8/openshift/server/mock/OpenShiftMockServer.java @@ -17,15 +17,11 @@ package io.fabric8.openshift.server.mock; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.server.mock.KubernetesMockServer; import io.fabric8.openshift.client.DefaultOpenShiftClient; import io.fabric8.openshift.client.NamespacedOpenShiftClient; import io.fabric8.openshift.client.OpenShiftConfig; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; -import static okhttp3.TlsVersion.TLS_1_2; - @Deprecated // The class has moved under mvn:io.fabric8:openshift-server-mock in package: io.fabric8.openshift.client.server.mock public class OpenShiftMockServer extends KubernetesMockServer { @@ -44,12 +40,7 @@ public String[] getRootPaths() { } public NamespacedOpenShiftClient createOpenShiftClient() { - Config config = new ConfigBuilder() - .withMasterUrl(url("/")) - .withNamespace("test") - .withTrustCerts(true) - .withTlsVersions(TLS_1_2) - .build(); - return new DefaultOpenShiftClient(createHttpClientForMockServer(config), new OpenShiftConfig(config)); + Config config = getMockConfiguration(); + return new DefaultOpenShiftClient(new OpenShiftConfig(config)); } } diff --git a/openshift-server-mock/src/main/java/io/fabric8/openshift/client/server/mock/OpenShiftMockServer.java b/openshift-server-mock/src/main/java/io/fabric8/openshift/client/server/mock/OpenShiftMockServer.java index b3b145252c8..b9604d7e6be 100644 --- a/openshift-server-mock/src/main/java/io/fabric8/openshift/client/server/mock/OpenShiftMockServer.java +++ b/openshift-server-mock/src/main/java/io/fabric8/openshift/client/server/mock/OpenShiftMockServer.java @@ -29,8 +29,6 @@ import java.util.Map; import java.util.Queue; -import static io.fabric8.kubernetes.client.utils.HttpClientUtils.createHttpClientForMockServer; - public class OpenShiftMockServer extends KubernetesMockServer { private boolean disableApiGroupCheck = true; @@ -54,7 +52,7 @@ public String[] getRootPaths() { public NamespacedOpenShiftClient createOpenShiftClient() { OpenShiftConfig config = OpenShiftConfig.wrap(getMockConfiguration()); config.setDisableApiGroupCheck(disableApiGroupCheck); - return new DefaultOpenShiftClient(createHttpClientForMockServer(config), config); + return new DefaultOpenShiftClient(config); } public boolean isDisableApiGroupCheck() {