use of org.jboss.pnc.spi.builddriver.DebugData in project pnc by project-ncl.
the class DefaultBuildExecutionSession method getBuildResult.
private BuildResult getBuildResult() {
EnvironmentDriverResult environmentDriverResult = null;
DebugData debugData = getRunningEnvironment() != null ? getRunningEnvironment().getDebugData() : null;
if (debugData != null && debugData.isDebugEnabled()) {
environmentDriverResult = new EnvironmentDriverResult(CompletionStatus.SUCCESS, "", Optional.of(debugData.getSshCredentials()));
}
CompletionStatus completionStatus = CompletionStatus.SUCCESS;
if (executorException == null) {
if (failedReasonStatus != null) {
switch(failedReasonStatus) {
case BUILD_ENV_SETUP_COMPLETE_WITH_ERROR:
case SYSTEM_ERROR:
completionStatus = CompletionStatus.SYSTEM_ERROR;
break;
case COLLECTING_RESULTS_FROM_REPOSITORY_MANAGER_COMPLETED_WITH_ERROR:
case BUILD_COMPLETED_WITH_ERROR:
completionStatus = CompletionStatus.FAILED;
break;
case CANCELLED:
completionStatus = CompletionStatus.CANCELLED;
break;
case DONE_WITH_ERRORS:
executorException = new ExecutorException("DONE_WITH_ERRORS cannot be set as failed reason.");
break;
}
}
}
ProcessException processException = null;
if (executorException != null) {
processException = new ProcessException(executorException);
completionStatus = CompletionStatus.SYSTEM_ERROR;
}
log.debug("Returning result of task {}.", getId());
return new BuildResult(completionStatus, Optional.ofNullable(processException), "", Optional.ofNullable(buildExecutionConfiguration), Optional.ofNullable(buildDriverResult), Optional.ofNullable(repositoryManagerResult), Optional.ofNullable(environmentDriverResult), Optional.empty());
}
use of org.jboss.pnc.spi.builddriver.DebugData in project pnc by project-ncl.
the class DefaultBuildExecutor method startBuilding.
@Override
public BuildExecutionSession startBuilding(BuildExecutionConfiguration buildExecutionConfiguration, Consumer<BuildExecutionStatusChangedEvent> onBuildExecutionStatusChangedEvent, String accessToken) throws ExecutorException {
DefaultBuildExecutionSession buildExecutionSession = new DefaultBuildExecutionSession(buildExecutionConfiguration, onBuildExecutionStatusChangedEvent);
String executionConfigurationId = buildExecutionConfiguration.getId();
DefaultBuildExecutionSession existing = runningExecutions.putIfAbsent(executionConfigurationId, buildExecutionSession);
if (existing != null) {
throw new AlreadyRunningException("Build execution with id: " + executionConfigurationId + " is already running.");
}
buildExecutionSession.setStartTime(new Date());
userLog.info("Starting build execution...");
buildExecutionSession.setStatus(BuildExecutionStatus.NEW);
buildExecutionSession.setAccessToken(accessToken);
DebugData debugData = new DebugData(buildExecutionConfiguration.isPodKeptOnFailure());
CompletableFuture.supplyAsync(() -> configureRepository(buildExecutionSession), executor).thenComposeAsync(repositoryConfiguration -> setUpEnvironment(buildExecutionSession, repositoryConfiguration, debugData), executor).thenComposeAsync(nul -> runTheBuild(buildExecutionSession), executor).thenApplyAsync(completedBuild -> {
buildExecutionSession.setCancelHook(null);
return optionallyEnableSsh(buildExecutionSession, completedBuild);
}, executor).thenApplyAsync(completedBuild -> retrieveBuildDriverResults(buildExecutionSession, completedBuild), executor).thenApplyAsync(nul -> retrieveRepositoryManagerResults(buildExecutionSession), executor).handleAsync((nul, e) -> {
// make sure there are no references left
buildExecutionSession.setCancelHook(null);
return completeExecution(buildExecutionSession, e);
}, executor);
// TODO re-connect running instances in case of crash
return buildExecutionSession;
}
use of org.jboss.pnc.spi.builddriver.DebugData 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);
}
use of org.jboss.pnc.spi.builddriver.DebugData 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);
}
use of org.jboss.pnc.spi.builddriver.DebugData in project pnc by project-ncl.
the class DestroyableEnvironmentMock method build.
public static DestroyableEnvironment build() {
RepositorySession repositorySession = new RepositorySessionMock();
Path workingDir = Paths.get("/root");
return RunningEnvironment.createInstance("1", 8080, "localhost", "build/agent/url", "internal,build/agent/url", repositorySession, workingDir, () -> {
}, new DebugData(false));
}
Aggregations