Search in sources :

Example 6 with HttpRequest

use of io.fabric8.kubernetes.client.http.HttpRequest in project kubernetes-client by fabric8io.

the class LogWatchCallback method callAndWait.

public LogWatchCallback callAndWait(HttpClient client, URL url) {
    HttpRequest request = client.newHttpRequestBuilder().url(url).build();
    HttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build();
    CompletableFuture<HttpResponse<InputStream>> 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;
}
Also used : HttpRequest(io.fabric8.kubernetes.client.http.HttpRequest) PipedInputStream(java.io.PipedInputStream) InputStream(java.io.InputStream) HttpClient(io.fabric8.kubernetes.client.http.HttpClient) HttpResponse(io.fabric8.kubernetes.client.http.HttpResponse)

Example 7 with HttpRequest

use of io.fabric8.kubernetes.client.http.HttpRequest in project kubernetes-client by fabric8io.

the class BuildConfigOperationsImplTest method setUp.

@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();
}
Also used : HttpRequest(io.fabric8.kubernetes.client.http.HttpRequest) HttpClient(io.fabric8.kubernetes.client.http.HttpClient) OpenShiftConfigBuilder(io.fabric8.openshift.client.OpenShiftConfigBuilder) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 8 with HttpRequest

use of io.fabric8.kubernetes.client.http.HttpRequest in project kas-fleetshard by bf2fc6cc711aee1a0c2a.

the class OMB method deployWorkers.

/**
 * Deploy workers to run producers and consumers.
 *
 * @param workers The number of workers to deploy.
 * @return List of worker hostnames.
 */
public List<String> deployWorkers(int workers) throws Exception {
    LOGGER.info("Deploying {} workers, container memory: {}, cpu: {}", workers, workerContainerMemory, workerCpu);
    // we are now on java 11 which defaults to https://www.eclipse.org/openj9/docs/xxusecontainersupport/ and -XX:+PreferContainerQuotaForCPUCount
    String jvmOpts = String.format("-XX:+ExitOnOutOfMemoryError");
    List<Future<Void>> futures = new ArrayList<>();
    List<Node> nodes = ombCluster.getWorkerNodes();
    ExecutorService executorService = Executors.newFixedThreadPool(N_THREADS);
    try {
        for (int i = 0; i < workers; i++) {
            String name = String.format("worker-%d", i);
            final int nodeIdx = i % nodes.size();
            futures.add(executorService.submit(() -> {
                workerNames.add(name);
                createWorker(jvmOpts, name, this.useSingleNode ? nodes.get(0) : nodes.get(nodeIdx));
                return null;
            }));
        }
    } finally {
        executorService.shutdown();
        awaitAllFutures(futures);
    }
    LOGGER.info("Collecting hosts");
    TreeMap<Integer, String> sortedHostnames = new TreeMap<>();
    ombCluster.kubeClient().client().adapt(OpenShiftClient.class).routes().inNamespace(Constants.OMB_NAMESPACE).withLabel("app", "worker").list().getItems().forEach(r -> {
        String host = r.getSpec().getHost();
        if (host == null || host.isEmpty()) {
            throw new IllegalStateException("Host node not defined");
        }
        sortedHostnames.put(workerNames.indexOf(r.getMetadata().getLabels().get("app.kubernetes.io/name")), String.format("http://%s", host));
    });
    List<String> hostnames = new ArrayList<>(sortedHostnames.values());
    LOGGER.info("Waiting for worker pods to run");
    // Wait until workers are running
    List<Pod> pods = ombCluster.kubeClient().client().pods().inNamespace(Constants.OMB_NAMESPACE).withLabel("app", "worker").list().getItems();
    while (pods.size() != workers) {
        pods = ombCluster.kubeClient().client().pods().inNamespace(Constants.OMB_NAMESPACE).withLabel("app", "worker").list().getItems();
        LOGGER.info("Found {} pods, expecting {}", pods.size(), workers);
        Thread.sleep(5000);
    }
    CompletableFuture<?>[] ready = new CompletableFuture<?>[pods.size()];
    for (int i = 0; i < pods.size(); i++) {
        Pod pod = pods.get(i);
        ready[i] = TestUtils.asyncWaitFor("pod ready", 1_000, 600_000, () -> ombCluster.kubeClient().client().pods().inNamespace(Constants.OMB_NAMESPACE).withName(pod.getMetadata().getName()).isReady());
    }
    CompletableFuture.allOf(ready).get();
    HttpClient client = HttpClient.newHttpClient();
    List<URI> notReady = hostnames.stream().map(u -> u + "/counters-stats").map(URI::create).collect(Collectors.toList());
    do {
        Iterator<URI> itr = notReady.iterator();
        LOGGER.info("Awaiting {} OMB endpoint(s) to become ready.", notReady.size());
        while (itr.hasNext()) {
            HttpRequest request = HttpRequest.newBuilder().uri(itr.next()).timeout(Duration.ofSeconds(10)).GET().build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                itr.remove();
            }
        }
        Thread.sleep(1000);
    } while (!notReady.isEmpty());
    LOGGER.info("Deployed {} workers: {}", workers, hostnames);
    return hostnames;
}
Also used : HttpRequest(java.net.http.HttpRequest) Pod(io.fabric8.kubernetes.api.model.Pod) Node(io.fabric8.kubernetes.api.model.Node) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) IntOrString(io.fabric8.kubernetes.api.model.IntOrString) TreeMap(java.util.TreeMap) URI(java.net.URI) CompletableFuture(java.util.concurrent.CompletableFuture) HttpClient(java.net.http.HttpClient) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) CompletableFuture(java.util.concurrent.CompletableFuture)

Example 9 with HttpRequest

use of io.fabric8.kubernetes.client.http.HttpRequest in project cryostat by cryostatio.

the class OpenShiftAuthManagerTest method shouldReturnLogoutRedirectUrl.

@Test
void shouldReturnLogoutRedirectUrl() throws Exception {
    Mockito.when(fs.readFile(Paths.get(Config.KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH))).thenReturn(new BufferedReader(new StringReader(SERVICE_ACCOUNT_TOKEN)));
    Resource<OAuthAccessToken> token = Mockito.mock(Resource.class);
    NonNamespaceOperation<OAuthAccessToken, OAuthAccessTokenList, Resource<OAuthAccessToken>> tokens = Mockito.mock(NonNamespaceOperation.class);
    Mockito.when(client.oAuthAccessTokens()).thenReturn(tokens);
    Mockito.when(tokens.withName(Mockito.anyString())).thenReturn(token);
    Mockito.when(token.delete()).thenReturn(true);
    HttpRequest<Buffer> req = Mockito.mock(HttpRequest.class);
    HttpResponse<Buffer> resp = Mockito.mock(HttpResponse.class);
    Mockito.when(webClient.get(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString())).thenReturn(req);
    Mockito.when(req.putHeader(Mockito.anyString(), Mockito.anyString())).thenReturn(req);
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock args) throws Throwable {
            AsyncResult<HttpResponse<Buffer>> asyncResult = Mockito.mock(AsyncResult.class);
            Mockito.when(asyncResult.result()).thenReturn(resp);
            Mockito.when(resp.bodyAsJsonObject()).thenReturn(OAUTH_METADATA);
            ((Handler<AsyncResult<HttpResponse<Buffer>>>) args.getArgument(0)).handle(asyncResult);
            return null;
        }
    }).when(req).send(Mockito.any());
    String logoutRedirectUrl = mgr.logout(() -> "Bearer myToken").get();
    MatcherAssert.assertThat(logoutRedirectUrl, Matchers.equalTo(EXPECTED_LOGOUT_REDIRECT_URL));
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Resource(io.fabric8.kubernetes.client.dsl.Resource) OAuthAccessTokenList(io.fabric8.openshift.api.model.OAuthAccessTokenList) InvocationOnMock(org.mockito.invocation.InvocationOnMock) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) OAuthAccessToken(io.fabric8.openshift.api.model.OAuthAccessToken) AsyncResult(io.vertx.core.AsyncResult) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 10 with HttpRequest

use of io.fabric8.kubernetes.client.http.HttpRequest in project fabric8 by jboss-fuse.

the class JolokiaFabricConnector method connect.

/**
 * connects to a fabric
 */
public void connect() {
    if (this.j4p != null || this.fabricServiceFacade != null) {
        disconnect();
    }
    this.j4p = J4pClient.url(this.url).user(this.userName).password(this.password).build();
    /* This needs further investigation...
        DefaultHttpClient httpClient = (DefaultHttpClient) j4p.getHttpClient();
        httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
            @Override
            public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
                return true;
            }
        });
        */
    this.fabricServiceFacade = new FabricServiceFacade(this);
    this.fabricMBeanFacade = new FabricMBean(this);
}
Also used : FabricMBean(io.fabric8.jolokia.facade.mbeans.FabricMBean) FabricServiceFacade(io.fabric8.jolokia.facade.facades.FabricServiceFacade)

Aggregations

HttpRequest (io.fabric8.kubernetes.client.http.HttpRequest)12 InputStream (java.io.InputStream)7 HttpClient (io.fabric8.kubernetes.client.http.HttpClient)5 IOException (java.io.IOException)5 HttpResponse (io.fabric8.kubernetes.client.http.HttpResponse)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 Pod (io.fabric8.kubernetes.api.model.Pod)2 URI (java.net.URI)2 FabricServiceFacade (io.fabric8.jolokia.facade.facades.FabricServiceFacade)1 FabricMBean (io.fabric8.jolokia.facade.mbeans.FabricMBean)1 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)1 IntOrString (io.fabric8.kubernetes.api.model.IntOrString)1 Node (io.fabric8.kubernetes.api.model.Node)1 PodBuilder (io.fabric8.kubernetes.api.model.PodBuilder)1 AdmissionReview (io.fabric8.kubernetes.api.model.admission.v1.AdmissionReview)1 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)1 Resource (io.fabric8.kubernetes.client.dsl.Resource)1 Builder (io.fabric8.kubernetes.client.http.HttpRequest.Builder)1 Interceptor (io.fabric8.kubernetes.client.http.Interceptor)1 WebSocket (io.fabric8.kubernetes.client.http.WebSocket)1