Search in sources :

Example 1 with RunningEnvironment

use of org.jboss.pnc.spi.environment.RunningEnvironment in project pnc by project-ncl.

the class DefaultBuildExecutor method runTheBuild.

private CompletableFuture<CompletedBuild> runTheBuild(DefaultBuildExecutionSession buildExecutionSession) {
    CompletableFuture<CompletedBuild> waitToCompleteFuture = new CompletableFuture<>();
    if (buildExecutionSession.isCanceled()) {
        waitToCompleteFuture.complete(null);
        return waitToCompleteFuture;
    }
    ProcessStageUtils.logProcessStageBegin(BuildExecutionStatus.BUILD_SETTING_UP.toString(), "Running the build ...");
    buildExecutionSession.setStatus(BuildExecutionStatus.BUILD_SETTING_UP);
    RunningEnvironment runningEnvironment = buildExecutionSession.getRunningEnvironment();
    try {
        Consumer<CompletedBuild> onComplete = value -> {
            ProcessStageUtils.logProcessStageEnd(BuildExecutionStatus.BUILD_SETTING_UP.toString(), "Build completed.");
            waitToCompleteFuture.complete(value);
        };
        Consumer<Throwable> onError = (e) -> {
            ProcessStageUtils.logProcessStageEnd(BuildExecutionStatus.BUILD_SETTING_UP.toString(), "Build failed.");
            waitToCompleteFuture.completeExceptionally(new BuildProcessException(e, runningEnvironment));
        };
        String buildAgentUrl = runningEnvironment.getBuildAgentUrl();
        String liveLogWebSocketUrl = "ws" + StringUtils.addEndingSlash(buildAgentUrl).replaceAll("http(s?):", ":") + "socket/text/ro";
        log.debug("Setting live log websocket url: {}", liveLogWebSocketUrl);
        buildExecutionSession.setLiveLogsUri(Optional.of(new URI(liveLogWebSocketUrl)));
        BuildDriver buildDriver = buildDriverFactory.getBuildDriver();
        RunningBuild runningBuild = buildDriver.startProjectBuild(buildExecutionSession, runningEnvironment, onComplete, onError);
        buildExecutionSession.setCancelHook(runningBuild::cancel);
        buildExecutionSession.setStatus(BuildExecutionStatus.BUILD_WAITING);
    } catch (Throwable e) {
        throw new BuildProcessException(e, runningEnvironment);
    }
    return waitToCompleteFuture;
}
Also used : CompletedBuild(org.jboss.pnc.spi.builddriver.CompletedBuild) RunningBuild(org.jboss.pnc.spi.builddriver.RunningBuild) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) RepositoryManagerFactory(org.jboss.pnc.executor.servicefactories.RepositoryManagerFactory) StringUtils(org.jboss.pnc.common.util.StringUtils) PreDestroy(javax.annotation.PreDestroy) RepositoryManager(org.jboss.pnc.spi.repositorymanager.RepositoryManager) KeycloakServiceClient(org.jboss.pnc.auth.KeycloakServiceClient) DestroyableEnvironment(org.jboss.pnc.spi.environment.DestroyableEnvironment) BuildExecutionConfiguration(org.jboss.pnc.spi.executor.BuildExecutionConfiguration) URI(java.net.URI) EnvironmentDriver(org.jboss.pnc.spi.environment.EnvironmentDriver) BuildDriverFactory(org.jboss.pnc.executor.servicefactories.BuildDriverFactory) RepositoryManagerException(org.jboss.pnc.spi.repositorymanager.RepositoryManagerException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CompletedBuild(org.jboss.pnc.spi.builddriver.CompletedBuild) BuildStatus(org.jboss.pnc.enums.BuildStatus) BuildDriverResult(org.jboss.pnc.spi.builddriver.BuildDriverResult) PncConfigProvider(org.jboss.pnc.common.json.moduleprovider.PncConfigProvider) RunningEnvironment(org.jboss.pnc.spi.environment.RunningEnvironment) RepositorySession(org.jboss.pnc.spi.repositorymanager.model.RepositorySession) BuildExecution(org.jboss.pnc.spi.repositorymanager.BuildExecution) MDCExecutors(org.jboss.pnc.common.concurrent.MDCExecutors) DebugData(org.jboss.pnc.spi.builddriver.DebugData) Optional(java.util.Optional) ApplicationScoped(javax.enterprise.context.ApplicationScoped) SystemConfig(org.jboss.pnc.common.json.moduleconfig.SystemConfig) NamedThreadFactory(org.jboss.pnc.common.concurrent.NamedThreadFactory) BuildDriver(org.jboss.pnc.spi.builddriver.BuildDriver) BuildProcessException(org.jboss.pnc.executor.exceptions.BuildProcessException) CompletableFuture(java.util.concurrent.CompletableFuture) ConcurrentMap(java.util.concurrent.ConcurrentMap) Inject(javax.inject.Inject) ConfigurationParseException(org.jboss.pnc.common.json.ConfigurationParseException) RepositoryType(org.jboss.pnc.enums.RepositoryType) BuildExecutionStatusChangedEvent(org.jboss.pnc.spi.events.BuildExecutionStatusChangedEvent) ExecutorException(org.jboss.pnc.spi.executor.exceptions.ExecutorException) BuildType(org.jboss.pnc.enums.BuildType) ExecutorService(java.util.concurrent.ExecutorService) Logger(org.slf4j.Logger) Configuration(org.jboss.pnc.common.Configuration) ProcessStageUtils(org.jboss.pnc.common.util.ProcessStageUtils) BuildExecutor(org.jboss.pnc.spi.executor.BuildExecutor) Consumer(java.util.function.Consumer) StartedEnvironment(org.jboss.pnc.spi.environment.StartedEnvironment) AlreadyRunningException(org.jboss.pnc.spi.executor.exceptions.AlreadyRunningException) RepositoryManagerResult(org.jboss.pnc.spi.repositorymanager.RepositoryManagerResult) BuildExecutionStatus(org.jboss.pnc.enums.BuildExecutionStatus) EnvironmentDriverFactory(org.jboss.pnc.executor.servicefactories.EnvironmentDriverFactory) BuildExecutionSession(org.jboss.pnc.spi.executor.BuildExecutionSession) RunningBuild(org.jboss.pnc.spi.builddriver.RunningBuild) URI(java.net.URI) RunningEnvironment(org.jboss.pnc.spi.environment.RunningEnvironment) BuildProcessException(org.jboss.pnc.executor.exceptions.BuildProcessException) BuildDriver(org.jboss.pnc.spi.builddriver.BuildDriver) CompletableFuture(java.util.concurrent.CompletableFuture)

Example 2 with RunningEnvironment

use of org.jboss.pnc.spi.environment.RunningEnvironment in project pnc by project-ncl.

the class DefaultBuildExecutor method completeExecution.

private Void completeExecution(DefaultBuildExecutionSession buildExecutionSession, Throwable e) {
    String buildExecutionId = buildExecutionSession.getId();
    try {
        // Ends when the result is stored by the Orchestrator
        ProcessStageUtils.logProcessStageBegin("FINALIZING_BUILD", "Finalizing build ...");
        if (e != null) {
            log.debug("Finalizing FAILED execution. Exception: ", e);
        } else {
            log.debug("Finalizing SUCCESS execution.");
        }
        buildExecutionSession.setStatus(BuildExecutionStatus.FINALIZING_EXECUTION);
        if (buildExecutionSession.getStartTime() == null) {
            buildExecutionSession.setException(new ExecutorException("Missing start time."));
        }
        if (e != null) {
            stopRunningEnvironment(e);
        } else {
            try {
                destroyEnvironment(buildExecutionSession);
            } catch (BuildProcessException destroyException) {
                e = destroyException;
            }
        }
        if (e != null) {
            buildExecutionSession.setException(new ExecutorException(e));
        }
        if (buildExecutionSession.getEndTime() != null) {
            buildExecutionSession.setException(new ExecutorException("End time already set."));
        } else {
            buildExecutionSession.setEndTime(new Date());
        }
        // check if any of previous statuses indicated "failed" state
        if (buildExecutionSession.isCanceled()) {
            buildExecutionSession.setStatus(BuildExecutionStatus.CANCELLED);
            userLog.info("Build execution completed (canceled).");
        } else if (buildExecutionSession.hasFailed()) {
            buildExecutionSession.setStatus(BuildExecutionStatus.DONE_WITH_ERRORS);
            userLog.warn("Build execution completed with errors.");
        } else {
            buildExecutionSession.setStatus(BuildExecutionStatus.DONE);
            userLog.info("Build execution completed successfully.");
        }
        log.debug("Removing buildExecutionTask [" + buildExecutionId + "] from list of running tasks.");
        runningExecutions.remove(buildExecutionId);
        userLog.info("Build execution completed.");
    } catch (Throwable t) {
        userLog.error("Unable to complete execution!", t);
        String executorException = "Unable to recover, see system log for the details.";
        if (t.getMessage() != null) {
            executorException += " " + t.getMessage();
        }
        buildExecutionSession.setException(new ExecutorException(executorException));
        buildExecutionSession.setEndTime(new Date());
        buildExecutionSession.setStatus(BuildExecutionStatus.SYSTEM_ERROR);
        runningExecutions.remove(buildExecutionId);
    } finally {
        RunningEnvironment runningEnvironment = buildExecutionSession.getRunningEnvironment();
        if (runningEnvironment == null) {
            log.warn("Could not close Maven repository session [" + buildExecutionId + "]. Running environment was not set!");
        } else {
            RepositorySession repositorySession = runningEnvironment.getRepositorySession();
            if (repositorySession == null) {
                log.warn("Could not close Maven repository session [" + buildExecutionId + "]. Repository session was not set!");
            } else {
                log.debug("Closing Maven repository session [" + buildExecutionId + "].");
                repositorySession.close();
            }
        }
    }
    return null;
}
Also used : ExecutorException(org.jboss.pnc.spi.executor.exceptions.ExecutorException) RepositorySession(org.jboss.pnc.spi.repositorymanager.model.RepositorySession) Date(java.util.Date) RunningEnvironment(org.jboss.pnc.spi.environment.RunningEnvironment) BuildProcessException(org.jboss.pnc.executor.exceptions.BuildProcessException)

Example 3 with RunningEnvironment

use of org.jboss.pnc.spi.environment.RunningEnvironment in project pnc by project-ncl.

the class OpenshiftStartedEnvironment method monitorInitialization.

/**
 * retries is decremented in retryPod in case of pod failing to start
 *
 * @param onComplete
 * @param onError
 * @param retries
 */
private void monitorInitialization(Consumer<RunningEnvironment> onComplete, Consumer<Exception> onError, int retries) {
    cancelHook = () -> onComplete.accept(null);
    CompletableFuture<Void> podFuture = creatingPod.thenComposeAsync(nul -> {
        CancellableCompletableFuture<Void> monitor = pollingMonitor.monitor(this::isPodRunning, pollingMonitorCheckInterval, pollingMonitorTimeout, TimeUnit.SECONDS);
        addFuture(monitor);
        return monitor;
    }, executor);
    CompletableFuture<Void> serviceFuture = creatingService.thenComposeAsync(nul -> {
        CancellableCompletableFuture<Void> monitor = pollingMonitor.monitor(this::isServiceRunning, pollingMonitorCheckInterval, pollingMonitorTimeout, TimeUnit.SECONDS);
        addFuture(monitor);
        return monitor;
    }, executor);
    CompletableFuture<Void> routeFuture;
    if (creatingRoute.isPresent()) {
        routeFuture = creatingRoute.get().thenComposeAsync(nul -> {
            CancellableCompletableFuture<Void> monitor = pollingMonitor.monitor(this::isRouteRunning, pollingMonitorCheckInterval, pollingMonitorTimeout, TimeUnit.SECONDS);
            addFuture(monitor);
            return monitor;
        }, executor);
    } else {
        routeFuture = CompletableFuture.completedFuture(null);
    }
    CompletableFuture<Void> openshiftDefinitionsError = new CompletableFuture<>();
    openshiftDefinitions.exceptionally(t -> {
        openshiftDefinitionsError.completeExceptionally(t);
        return null;
    });
    CancellableCompletableFuture<Void> isBuildAgentUpFuture = pollingMonitor.monitor(this::isInternalServletAvailable, pollingMonitorCheckInterval, pollingMonitorTimeout, TimeUnit.SECONDS);
    addFuture(isBuildAgentUpFuture);
    CompletableFuture<RunningEnvironment> runningEnvironmentFuture = CompletableFutureUtils.allOfOrException(podFuture, serviceFuture, routeFuture).thenComposeAsync(nul -> isBuildAgentUpFuture, executor).thenApplyAsync(nul -> RunningEnvironment.createInstance(pod.getMetadata().getName(), Integer.parseInt(environmentConfiguration.getContainerPort()), route.getSpec().getHost(), getPublicEndpointUrl(), getInternalEndpointUrl(), repositorySession, Paths.get(environmentConfiguration.getWorkingDirectory()), this::destroyEnvironment, debugData), executor);
    CompletableFuture.anyOf(runningEnvironmentFuture, openshiftDefinitionsError).handleAsync((runningEnvironment, throwable) -> {
        if (throwable != null) {
            logger.info("Error while trying to create an OpenShift environment... ", throwable);
            cancelAndClearMonitors();
            // no more retries, execute the onError consumer
            if (retries == 0) {
                logger.info("No more retries left, giving up!");
                onError.accept(new Exception(getPrettierErrorMessageFromThrowable(throwable, true), throwable));
            } else {
                PodFailedStartException podFailedStartExc = null;
                if (throwable instanceof PodFailedStartException) {
                    podFailedStartExc = (PodFailedStartException) throwable;
                } else if (throwable.getCause() instanceof PodFailedStartException) {
                    podFailedStartExc = (PodFailedStartException) throwable.getCause();
                }
                if (podFailedStartExc != null && !Arrays.asList(POD_RETRYABLE_STATUSES).contains(podFailedStartExc.getPodStatus())) {
                    logger.info("The detected pod error status '{}' is not considered among the ones to be retried, giving up!", podFailedStartExc.getPodStatus());
                    // the status is not to be retried
                    onError.accept(new Exception(getPrettierErrorMessageFromThrowable(throwable, false), throwable));
                } else {
                    if (!cancelRequested) {
                        logger.warn("Creating build environment failed with error '{}'! Retrying ({} retries left)...", throwable, retries);
                        retryEnvironment(onComplete, onError, retries);
                    } else {
                        logger.info("Build was cancelled, not retrying environment!");
                    }
                }
            }
        } else {
            logger.info("Environment successfully initialized. Pod [{}]; Service [{}].", pod.getMetadata().getName(), service.getMetadata().getName());
            // openshiftDefinitionsError
            onComplete.accept((RunningEnvironment) runningEnvironment);
        // completes only with error
        }
        gaugeMetric.ifPresent(g -> g.incrementMetric(METRICS_POD_STARTED_SUCCESS_KEY));
        return null;
    }, executor);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ConcurrentSet(org.jboss.util.collection.ConcurrentSet) Arrays(java.util.Arrays) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) GaugeMetric(org.jboss.pnc.pncmetrics.GaugeMetric) DefaultOpenShiftClient(io.fabric8.openshift.client.DefaultOpenShiftClient) MDCUtils(org.jboss.pnc.common.logging.MDCUtils) StringUtils(org.jboss.pnc.common.util.StringUtils) Route(io.fabric8.openshift.api.model.Route) OpenshiftBuildAgentConfig(org.jboss.pnc.common.json.moduleconfig.OpenshiftBuildAgentConfig) Map(java.util.Map) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) BuildConfigurationParameterKeys(org.jboss.pnc.api.constants.BuildConfigurationParameterKeys) OpenshiftEnvironmentDriverModuleConfig(org.jboss.pnc.common.json.moduleconfig.OpenshiftEnvironmentDriverModuleConfig) JsonStringEncoder(com.fasterxml.jackson.core.io.JsonStringEncoder) MetricsConfiguration(org.jboss.pnc.pncmetrics.MetricsConfiguration) Instant(java.time.Instant) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Config(io.fabric8.kubernetes.client.Config) RunningEnvironment(org.jboss.pnc.spi.environment.RunningEnvironment) RepositorySession(org.jboss.pnc.spi.repositorymanager.model.RepositorySession) DebugData(org.jboss.pnc.spi.builddriver.DebugData) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) MixedOperation(io.fabric8.kubernetes.client.dsl.MixedOperation) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) RandomUtils(org.jboss.pnc.common.util.RandomUtils) Service(io.fabric8.kubernetes.api.model.Service) ExecutorService(java.util.concurrent.ExecutorService) RandomStringUtils(org.apache.commons.lang.RandomStringUtils) StringPropertyReplacer(org.jboss.util.StringPropertyReplacer) Logger(org.slf4j.Logger) Properties(java.util.Properties) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Pod(io.fabric8.kubernetes.api.model.Pod) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PodFailedStartException(org.jboss.pnc.environment.openshift.exceptions.PodFailedStartException) IOException(java.io.IOException) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) PollingMonitor(org.jboss.pnc.common.monitor.PollingMonitor) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CancellableCompletableFuture(org.jboss.pnc.common.monitor.CancellableCompletableFuture) KubernetesResource(io.fabric8.kubernetes.api.model.KubernetesResource) StartedEnvironment(org.jboss.pnc.spi.environment.StartedEnvironment) Paths(java.nio.file.Paths) CompletableFutureUtils(org.jboss.pnc.common.util.CompletableFutureUtils) ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder) CompletableFuture(java.util.concurrent.CompletableFuture) CancellableCompletableFuture(org.jboss.pnc.common.monitor.CancellableCompletableFuture) CancellableCompletableFuture(org.jboss.pnc.common.monitor.CancellableCompletableFuture) PodFailedStartException(org.jboss.pnc.environment.openshift.exceptions.PodFailedStartException) RunningEnvironment(org.jboss.pnc.spi.environment.RunningEnvironment) TimeoutException(java.util.concurrent.TimeoutException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PodFailedStartException(org.jboss.pnc.environment.openshift.exceptions.PodFailedStartException) IOException(java.io.IOException)

Example 4 with RunningEnvironment

use of org.jboss.pnc.spi.environment.RunningEnvironment in project pnc by project-ncl.

the class OpenshiftEnvironmentDriverRemoteTest method createAndDestroyEnvironment.

@Test
public void createAndDestroyEnvironment() throws EnvironmentDriverException, InterruptedException {
    final Semaphore mutex = new Semaphore(0);
    ObjectWrapper<Throwable> exceptionWrapper = new ObjectWrapper<>();
    String dummyImageId = "abcd1234";
    String dummyRepoUrl = "test.repo.url/repo";
    // Create container
    final StartedEnvironment startedEnv = environmentDriver.startEnvironment(dummyImageId, dummyRepoUrl, SystemImageType.DOCKER_IMAGE, DUMMY_REPOSITORY_CONFIGURATION, new DebugData(false), "put-access-token-here", false, Collections.emptyMap());
    Consumer<RunningEnvironment> onEnvironmentStarted = (runningEnvironment) -> {
        boolean containerDestroyed = false;
        try {
            assertThatContainerIsRunning(runningEnvironment);
            // Destroy container
            destroyEnvironment(runningEnvironment);
            containerDestroyed = true;
            assertThatContainerIsNotRunning(runningEnvironment);
            mutex.release();
        } catch (Throwable e) {
            exceptionWrapper.set(e);
        } finally {
            if (!containerDestroyed) {
                destroyEnvironmentWithReport(runningEnvironment);
            }
        }
        mutex.release();
    };
    Consumer<Exception> onError = (e) -> {
        try {
            logger.info("Trying to destroy environment due to an error:", e);
            startedEnv.destroyEnvironment();
            mutex.release();
        } catch (EnvironmentDriverException e1) {
            logger.error("Environment LEAK! The running environment was not destroyed. ID: " + startedEnv.getId(), e1);
        }
        fail("Failed to init builder. " + e.getMessage());
    };
    startedEnv.monitorInitialization(onEnvironmentStarted, onError);
    boolean completed = mutex.tryAcquire(TEST_EXECUTION_TIMEOUT, TimeUnit.SECONDS);
    Throwable exception = exceptionWrapper.get();
    if (exception != null) {
        logger.error("", exception);
        fail(exception.getMessage());
    }
    assertTrue("timeout reached, test has not complete.", completed);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) SystemImageType(org.jboss.pnc.enums.SystemImageType) RepositoryType(org.jboss.pnc.enums.RepositoryType) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) EnvironmentDriver(org.jboss.pnc.spi.environment.EnvironmentDriver) OpenshiftEnvironmentDriverModuleConfig(org.jboss.pnc.common.json.moduleconfig.OpenshiftEnvironmentDriverModuleConfig) RepositoryManagerException(org.jboss.pnc.spi.repositorymanager.RepositoryManagerException) Semaphore(java.util.concurrent.Semaphore) MethodHandles(java.lang.invoke.MethodHandles) Assert.assertTrue(org.junit.Assert.assertTrue) DebugTest(org.jboss.pnc.test.category.DebugTest) Test(org.junit.Test) IOException(java.io.IOException) Category(org.junit.experimental.categories.Category) PollingMonitor(org.jboss.pnc.common.monitor.PollingMonitor) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ObjectWrapper(org.jboss.pnc.common.util.ObjectWrapper) RepositoryConnectionInfo(org.jboss.pnc.spi.repositorymanager.model.RepositoryConnectionInfo) Mockito(org.mockito.Mockito) RunningEnvironment(org.jboss.pnc.spi.environment.RunningEnvironment) StartedEnvironment(org.jboss.pnc.spi.environment.StartedEnvironment) RepositorySession(org.jboss.pnc.spi.repositorymanager.model.RepositorySession) DebugData(org.jboss.pnc.spi.builddriver.DebugData) RepositoryManagerResult(org.jboss.pnc.spi.repositorymanager.RepositoryManagerResult) Assert.assertFalse(org.junit.Assert.assertFalse) EnvironmentDriverException(org.jboss.pnc.spi.environment.exception.EnvironmentDriverException) SystemConfig(org.jboss.pnc.common.json.moduleconfig.SystemConfig) Collections(java.util.Collections) DebugData(org.jboss.pnc.spi.builddriver.DebugData) Semaphore(java.util.concurrent.Semaphore) StartedEnvironment(org.jboss.pnc.spi.environment.StartedEnvironment) RunningEnvironment(org.jboss.pnc.spi.environment.RunningEnvironment) RepositoryManagerException(org.jboss.pnc.spi.repositorymanager.RepositoryManagerException) IOException(java.io.IOException) EnvironmentDriverException(org.jboss.pnc.spi.environment.exception.EnvironmentDriverException) EnvironmentDriverException(org.jboss.pnc.spi.environment.exception.EnvironmentDriverException) ObjectWrapper(org.jboss.pnc.common.util.ObjectWrapper) DebugTest(org.jboss.pnc.test.category.DebugTest) Test(org.junit.Test)

Example 5 with RunningEnvironment

use of org.jboss.pnc.spi.environment.RunningEnvironment in project pnc by project-ncl.

the class LivenessProbeTest method shouldFailTheBuildWhenAgentIsNotResponding.

@Test
public void shouldFailTheBuildWhenAgentIsNotResponding() throws InterruptedException, BuildDriverException {
    TermdBuildDriverModuleConfig buildDriverModuleConfig = mock(TermdBuildDriverModuleConfig.class);
    doReturn(200L).when(buildDriverModuleConfig).getLivenessProbeFrequencyMillis();
    doReturn(500L).when(buildDriverModuleConfig).getLivenessFailTimeoutMillis();
    ClientMockFactory buildAgentClientMockFactory = new ClientMockFactory();
    TermdBuildDriver driver = new TermdBuildDriver(systemConfig, buildDriverModuleConfig, buildAgentClientMockFactory);
    BuildExecutionSession buildExecution = mock(BuildExecutionSession.class);
    BuildExecutionConfiguration buildExecutionConfiguration = mock(BuildExecutionConfiguration.class);
    doReturn(buildExecutionConfiguration).when(buildExecution).getBuildExecutionConfiguration();
    RunningEnvironment runningEnvironment = mock(RunningEnvironment.class);
    doReturn(Paths.get("")).when(runningEnvironment).getWorkingDirectory();
    doReturn(new DebugData(false)).when(runningEnvironment).getDebugData();
    doReturn("http://localhost/").when(runningEnvironment).getInternalBuildAgentUrl();
    doReturn(runningEnvironment).when(buildExecution).getRunningEnvironment();
    BlockingQueue<Throwable> result = new ArrayBlockingQueue(1);
    Consumer<CompletedBuild> onComplete = (completedBuild) -> Assert.fail("Build should complete with error.");
    Consumer<Throwable> onError = (throwable) -> {
        try {
            result.put(throwable);
        } catch (InterruptedException e) {
            Assert.fail("Error in the test. Unable to add the result to queue.");
        }
    };
    // when
    RunningBuild runningBuild = driver.startProjectBuild(buildExecution, runningEnvironment, onComplete, onError);
    // then
    Throwable throwable = result.poll(1, TimeUnit.SECONDS);
    Assert.assertNotNull("It should complete with an exception.", throwable);
    Assert.assertEquals("Build Agent has gone away.", throwable.getMessage());
}
Also used : BuildExecutionSession(org.jboss.pnc.spi.executor.BuildExecutionSession) CompletedBuild(org.jboss.pnc.spi.builddriver.CompletedBuild) Logger(org.slf4j.Logger) BuildDriverException(org.jboss.pnc.spi.builddriver.exception.BuildDriverException) RunningBuild(org.jboss.pnc.spi.builddriver.RunningBuild) LoggerFactory(org.slf4j.LoggerFactory) CompletedBuild(org.jboss.pnc.spi.builddriver.CompletedBuild) Test(org.junit.Test) BlockingQueue(java.util.concurrent.BlockingQueue) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) RunningEnvironment(org.jboss.pnc.spi.environment.RunningEnvironment) Paths(java.nio.file.Paths) DebugData(org.jboss.pnc.spi.builddriver.DebugData) TermdBuildDriverModuleConfig(org.jboss.pnc.common.json.moduleconfig.TermdBuildDriverModuleConfig) BuildExecutionConfiguration(org.jboss.pnc.spi.executor.BuildExecutionConfiguration) SystemConfig(org.jboss.pnc.common.json.moduleconfig.SystemConfig) Assert(org.junit.Assert) BuildExecutionSession(org.jboss.pnc.spi.executor.BuildExecutionSession) Mockito.doReturn(org.mockito.Mockito.doReturn) Mockito.mock(org.mockito.Mockito.mock) BuildExecutionConfiguration(org.jboss.pnc.spi.executor.BuildExecutionConfiguration) DebugData(org.jboss.pnc.spi.builddriver.DebugData) RunningBuild(org.jboss.pnc.spi.builddriver.RunningBuild) RunningEnvironment(org.jboss.pnc.spi.environment.RunningEnvironment) TermdBuildDriverModuleConfig(org.jboss.pnc.common.json.moduleconfig.TermdBuildDriverModuleConfig) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Test(org.junit.Test)

Aggregations

RunningEnvironment (org.jboss.pnc.spi.environment.RunningEnvironment)12 Consumer (java.util.function.Consumer)6 CompletedBuild (org.jboss.pnc.spi.builddriver.CompletedBuild)6 DebugData (org.jboss.pnc.spi.builddriver.DebugData)6 RepositorySession (org.jboss.pnc.spi.repositorymanager.model.RepositorySession)6 LoggerFactory (org.slf4j.LoggerFactory)6 TimeUnit (java.util.concurrent.TimeUnit)5 SystemConfig (org.jboss.pnc.common.json.moduleconfig.SystemConfig)5 BuildDriverException (org.jboss.pnc.spi.builddriver.exception.BuildDriverException)5 Logger (org.slf4j.Logger)5 Paths (java.nio.file.Paths)4 BuildProcessException (org.jboss.pnc.executor.exceptions.BuildProcessException)4 RunningBuild (org.jboss.pnc.spi.builddriver.RunningBuild)4 BuildExecutionSession (org.jboss.pnc.spi.executor.BuildExecutionSession)4 Optional (java.util.Optional)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 ExecutorService (java.util.concurrent.ExecutorService)3 TermdBuildDriverModuleConfig (org.jboss.pnc.common.json.moduleconfig.TermdBuildDriverModuleConfig)3 BuildStatus (org.jboss.pnc.enums.BuildStatus)3 StartedEnvironment (org.jboss.pnc.spi.environment.StartedEnvironment)3