Search in sources :

Example 1 with KieServerStateInfo

use of org.kie.server.api.model.KieServerStateInfo in project droolsjbpm-integration by kiegroup.

the class LoadBalancerClientTest method testMultipleConcurrentFailRequestsForLoadBalancerWithSingleServer.

@Test
public void testMultipleConcurrentFailRequestsForLoadBalancerWithSingleServer() throws Exception {
    class SendKieRequestThread extends Thread {

        CountDownLatch startLatch;

        CountDownLatch stopLatch;

        int threadNo;

        KieServicesClient kieClient;

        SendKieRequestThread(int threadNo, CountDownLatch startLatch, CountDownLatch stopLatch, KieServicesClient client) {
            this.startLatch = startLatch;
            this.stopLatch = stopLatch;
            this.threadNo = threadNo;
            this.kieClient = client;
        }

        @Override
        public void run() {
            try {
                startLatch.await();
                logger.debug("Th#" + threadNo + " Calling Kie Server ");
                // Stagger execution of threads by 20ms
                Thread.sleep(20 * threadNo);
                // Call KieServer...
                try {
                    KieServerStateInfo info = kieClient.getServerState().getResult();
                    logger.debug("response {}", info.getServerId());
                    fail("Unexpected successful request");
                } catch (NoEndpointFoundException e) {
                    // expected failed configured in "Timeout Fail followed by Success" scenario
                    logger.debug("Expected failure Endpoint timeout", e);
                }
            } catch (Exception e) {
                logger.debug("Exception while calling kie Server: " + e);
            } finally {
                logger.debug("Th#" + threadNo + " Done.");
                stopLatch.countDown();
            }
        }
    }
    // Setup a single server
    config = KieServicesFactory.newRestConfiguration(mockServerBaseUri1, null, null);
    config.setCapabilities(Arrays.asList("KieServer"));
    KieServicesClient client = KieServicesFactory.newKieServicesClient(config);
    ((AbstractKieServicesClientImpl) client).getLoadBalancer().setCheckFailedEndpoint(false);
    // Issue successful request
    ServiceResponse<KieServerStateInfo> response = client.getServerState();
    assertSuccess(response);
    Assertions.assertThat(response.getResult().getContainers()).isEmpty();
    // Setup 2 concurrent requests both failing with a timeout representing a temporary failure in server
    logger.debug("Reset mappings #1");
    wireMockServer1.resetMappings();
    wireMockServer1.stubFor(get(urlEqualTo("/state")).withHeader("Accept", equalTo("application/xml")).willReturn(aResponse().withFixedDelay(5100).withStatus(200).withHeader("Content-Type", "application/xml").withBody("<response type=\"SUCCESS\" msg=\"Kie Server state\">\n" + "  <kie-server-state-info>\n" + "    <server-id>1a</server-id>\n" + "  </kie-server-state-info>\n" + "</response>")));
    // Add a delay to background thread scanning to ensure availableEndpoints list
    // is kept empty long enough to demonstrate failing situation.
    wireMockServer1.stubFor(get(urlEqualTo("/")).willReturn(aResponse().withFixedDelay(500).withStatus(200).withHeader("Content-Type", "application/xml").withBody("<response type=\"SUCCESS\" msg=\"Kie Server info\">\n" + "  <kie-server-info>\n" + "    <version>background scan</version>\n" + "  </kie-server-info>\n" + "</response>")));
    // Kickoff first scenario
    int threadCount = 2;
    logger.debug("Starting 2 Threads");
    CountDownLatch startLatch = new CountDownLatch(1);
    CountDownLatch stopLatch = new CountDownLatch(threadCount);
    List<SendKieRequestThread> threads = new ArrayList<>();
    for (int i = 1; i <= threadCount; i++) {
        threads.add(new SendKieRequestThread(i, startLatch, stopLatch, client));
    }
    threads.forEach(SendKieRequestThread::start);
    // Threads will be waiting to proceed, so let them off.
    startLatch.countDown();
    // We expect the threads to complete within 7 seconds
    stopLatch.await(7, TimeUnit.SECONDS);
    logger.debug("\nEnd of Threads - ");
    threads.forEach(thread -> {
        try {
            thread.join();
        } catch (InterruptedException e) {
            logger.debug("Interrupted", e);
        }
    });
    // Expect to now have server:/state incorrectly retained in failedEndpoints
    List<String> availableList = ((AbstractKieServicesClientImpl) client).getLoadBalancer().getAvailableEndpoints();
    availableList.forEach(item -> logger.debug("Available Endpoint : [" + item + "]"));
    List<String> failedList = ((AbstractKieServicesClientImpl) client).getLoadBalancer().getFailedEndpoints();
    assertEquals(1, failedList.size());
    failedList.forEach(item -> logger.debug("Failed Endpoint : [" + item + "]"));
    // Now set up a subsequent request failure due to server temporarily not responding.");
    // Could have many successful requests up to this point after first failing scenario but as
    // soon as we have another timeout failure like below, server:/state gets moved to availableEndpoints.
    logger.debug("Reset mappings #2");
    wireMockServer1.resetMappings();
    wireMockServer1.stubFor(get(urlEqualTo("/state")).withHeader("Accept", equalTo("application/xml")).inScenario("Brief Timeout Fails followed by Scan Success").willReturn(aResponse().withFixedDelay(5100).withStatus(200).withHeader("Content-Type", "application/xml").withBody("<response type=\"SUCCESS\" msg=\"Kie Server state\">\n" + "  <kie-server-state-info>\n" + "    <server-id>1d</server-id>\n" + "  </kie-server-state-info>\n" + "</response>")).willSetStateTo("After Failed Req"));
    wireMockServer1.stubFor(get(urlEqualTo("/state")).inScenario("Brief Timeout Fails followed by Scan Success").whenScenarioStateIs("After Failed Req").willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/xml").withBody("<response type=\"SUCCESS\" msg=\"Kie Server state\">\n" + "  <kie-server-state-info>\n" + "    <server-id>1e</server-id>\n" + "  </kie-server-state-info>\n" + "</response>")).willSetStateTo("After success 1"));
    wireMockServer1.stubFor(get(urlEqualTo("/")).inScenario("Brief Timeout Fails followed by Scan Success").whenScenarioStateIs("After success 1").willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/xml").withBody("<response type=\"SUCCESS\" msg=\"Kie Server info\">\n" + "  <kie-server-info>\n" + "    <server-id>background scan</server-id>\n" + "  </kie-server-info>\n" + "</response>")).willSetStateTo("After success 2"));
    logger.debug(" Current wireMockServer1 stub count =" + wireMockServer1.listAllStubMappings().getMappings().size());
    try {
        response = client.getServerState();
        fail("Unexpected successful request");
    } catch (KieServerHttpRequestException e) {
        logger.debug("Expected failure Endpoint", e);
    }
    // Expect to now have server:/state incorrectly retained in availableEndpoints transferred from failedEndpoints
    availableList = ((AbstractKieServicesClientImpl) client).getLoadBalancer().getAvailableEndpoints();
    availableList.forEach(item -> logger.debug("Available Endpoint : [" + item + "]"));
    failedList = ((AbstractKieServicesClientImpl) client).getLoadBalancer().getFailedEndpoints();
    assertTrue(availableList.isEmpty());
    assertEquals(1, failedList.size());
    ((AbstractKieServicesClientImpl) client).getLoadBalancer().setCheckFailedEndpoint(true);
    ((AbstractKieServicesClientImpl) client).getLoadBalancer().checkFailedEndpoints().get(5, TimeUnit.SECONDS);
    // Set up what should be a successful request
    wireMockServer1.stubFor(get(urlEqualTo("/state")).withHeader("Accept", equalTo("application/xml")).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/xml").withBody("<response type=\"SUCCESS\" msg=\"Kie Server state\">\n" + "  <kie-server-state-info>\n" + "    <server-id>1b</server-id>\n" + "  </kie-server-state-info>\n" + "</response>")));
    // Run request and expect success request but instead a 404 HTTP status results
    // due to final request URL generated as "http://localhost:<port>/state/state"
    // based on presence of server:/state in availableEndpoints.
    response = client.getServerState();
    assertSuccess(response);
    Assertions.assertThat(response.getResult().getContainers()).isEmpty();
}
Also used : NoEndpointFoundException(org.kie.server.common.rest.NoEndpointFoundException) ArrayList(java.util.ArrayList) KieServerStateInfo(org.kie.server.api.model.KieServerStateInfo) CountDownLatch(java.util.concurrent.CountDownLatch) KieServerHttpRequestException(org.kie.server.common.rest.KieServerHttpRequestException) NoEndpointFoundException(org.kie.server.common.rest.NoEndpointFoundException) KieServicesHttpException(org.kie.server.api.exception.KieServicesHttpException) KieServerHttpRequestException(org.kie.server.common.rest.KieServerHttpRequestException) AbstractKieServicesClientImpl(org.kie.server.client.impl.AbstractKieServicesClientImpl) Test(org.junit.Test)

Example 2 with KieServerStateInfo

use of org.kie.server.api.model.KieServerStateInfo in project droolsjbpm-integration by kiegroup.

the class KieServerContainerCRUDIntegrationTest method testUpdateReleaseIdForExistingContainer.

@Test
public void testUpdateReleaseIdForExistingContainer() throws Exception {
    client.createContainer("update-releaseId", new KieContainerResource("update-releaseId", releaseId1));
    ServiceResponse<ReleaseId> reply = client.updateReleaseId("update-releaseId", releaseId2);
    KieServerAssert.assertSuccess(reply);
    Assert.assertEquals(releaseId2, reply.getResult());
    ServiceResponse<KieServerStateInfo> currentServerStateReply = client.getServerState();
    KieServerAssert.assertSuccess(currentServerStateReply);
    KieServerStateInfo currentServerState = currentServerStateReply.getResult();
    Assert.assertNotNull(currentServerState);
    Set<KieContainerResource> containers = currentServerState.getContainers();
    Assert.assertEquals(1, containers.size());
    KieContainerResource container = containers.iterator().next();
    Assert.assertNotNull(container);
    Assert.assertEquals(releaseId2, container.getReleaseId());
    Assert.assertEquals(releaseId2, container.getResolvedReleaseId());
    ServiceResponse<Void> disposeReply = client.disposeContainer("update-releaseId");
    KieServerAssert.assertSuccess(disposeReply);
}
Also used : KieServerStateInfo(org.kie.server.api.model.KieServerStateInfo) ReleaseId(org.kie.server.api.model.ReleaseId) KieContainerResource(org.kie.server.api.model.KieContainerResource) RestJmsSharedBaseIntegrationTest(org.kie.server.integrationtests.shared.basetests.RestJmsSharedBaseIntegrationTest) Test(org.junit.Test)

Example 3 with KieServerStateInfo

use of org.kie.server.api.model.KieServerStateInfo in project droolsjbpm-integration by kiegroup.

the class KieServicesClientIntegrationTest method testGetKieServerState.

@Test
public void testGetKieServerState() {
    final ExecutionServerCommand executionServerCommand = new ExecutionServerCommand();
    executionServerCommand.setClient("kieServices");
    executionServerCommand.setOperation("getServerState");
    Object response = runOnExecutionServer(executionServerCommand);
    Assertions.assertThat(response).isNotNull();
    final KieServerStateInfo kieServerStateInfo = (KieServerStateInfo) response;
    Assertions.assertThat(kieServerStateInfo.getContainers()).isNotEmpty();
}
Also used : KieServerStateInfo(org.kie.server.api.model.KieServerStateInfo) ExecutionServerCommand(org.kie.camel.container.api.ExecutionServerCommand) Test(org.junit.Test)

Example 4 with KieServerStateInfo

use of org.kie.server.api.model.KieServerStateInfo in project droolsjbpm-integration by kiegroup.

the class KieServerImpl method getInternalServerState.

public KieServerStateInfo getInternalServerState() {
    try {
        KieServerInfo kieServerInfo = getInfoInternal();
        KieServerState currentState = repository.load(KieServerEnvironment.getServerId());
        KieServerStateInfo stateInfo = new KieServerStateInfo(currentState.getControllers(), currentState.getConfiguration(), currentState.getContainers());
        stateInfo.setServerId(kieServerInfo.getServerId());
        stateInfo.setLocation(kieServerInfo.getLocation());
        return stateInfo;
    } catch (Exception e) {
        logger.error("Error when loading server state due to {}", e.getMessage(), e);
        return null;
    }
}
Also used : KieServerState(org.kie.server.services.impl.storage.KieServerState) KieServerInfo(org.kie.server.api.model.KieServerInfo) KieServerStateInfo(org.kie.server.api.model.KieServerStateInfo)

Example 5 with KieServerStateInfo

use of org.kie.server.api.model.KieServerStateInfo in project droolsjbpm-integration by kiegroup.

the class WebSocketKieServerClient method getServerState.

@Override
public ServiceResponse<KieServerStateInfo> getServerState() {
    CommandScript script = new CommandScript(Collections.singletonList((KieServerCommand) new GetServerStateCommand()));
    ServiceResponse<KieServerStateInfo> response = (ServiceResponse<KieServerStateInfo>) sendCommand(script, new WebSocketServiceResponse(true, (message) -> {
        ServiceResponsesList list = WebSocketUtils.unmarshal(message, ServiceResponsesList.class);
        return list.getResponses().get(0);
    })).getResponses().get(0);
    return response;
}
Also used : ServiceResponsesList(org.kie.server.api.model.ServiceResponsesList) GetServerStateCommand(org.kie.server.api.commands.GetServerStateCommand) WebSocketServiceResponse(org.kie.server.controller.websocket.common.handlers.WebSocketServiceResponse) ServiceResponse(org.kie.server.api.model.ServiceResponse) KieServerCommand(org.kie.server.api.model.KieServerCommand) WebSocketServiceResponse(org.kie.server.controller.websocket.common.handlers.WebSocketServiceResponse) CommandScript(org.kie.server.api.commands.CommandScript) KieServerStateInfo(org.kie.server.api.model.KieServerStateInfo)

Aggregations

KieServerStateInfo (org.kie.server.api.model.KieServerStateInfo)11 Test (org.junit.Test)6 ServiceResponse (org.kie.server.api.model.ServiceResponse)3 CommandScript (org.kie.server.api.commands.CommandScript)2 GetServerStateCommand (org.kie.server.api.commands.GetServerStateCommand)2 KieContainerResource (org.kie.server.api.model.KieContainerResource)2 KieServerCommand (org.kie.server.api.model.KieServerCommand)2 KieServerConfigItem (org.kie.server.api.model.KieServerConfigItem)2 ReleaseId (org.kie.server.api.model.ReleaseId)2 RestJmsSharedBaseIntegrationTest (org.kie.server.integrationtests.shared.basetests.RestJmsSharedBaseIntegrationTest)2 File (java.io.File)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 Consumes (javax.ws.rs.Consumes)1 POST (javax.ws.rs.POST)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 ExecutionServerCommand (org.kie.camel.container.api.ExecutionServerCommand)1 KieServicesHttpException (org.kie.server.api.exception.KieServicesHttpException)1