diff --git a/pom.xml b/pom.xml index fd4711f..8aa852e 100644 --- a/pom.xml +++ b/pom.xml @@ -41,7 +41,7 @@ 3.5 2.6.1 1.11 - v1.5 + v1.7 4.9 0.7.0 2.1.4 diff --git a/src/main/java/io/fabric8/che/starter/client/CheRestEndpoints.java b/src/main/java/io/fabric8/che/starter/client/CheRestEndpoints.java index 6374747..72a9236 100644 --- a/src/main/java/io/fabric8/che/starter/client/CheRestEndpoints.java +++ b/src/main/java/io/fabric8/che/starter/client/CheRestEndpoints.java @@ -22,8 +22,7 @@ public enum CheRestEndpoints { STOP_WORKSPACE ("/api/workspace/{id}/runtime"), LIST_STACKS ("/api/stack?maxItems=1000"), DELETE_PROJECT ("/project/{id}"), - SET_OAUTH_TOKEN_V1 ("/wsmaster/api/oauth/token?oauth_provider={provider}"), - SET_OAUTH_TOKEN_V2 ("/wsmaster/api/token/github"), + SET_OAUTH_TOKEN ("/wsmaster/api/token/github"), GET_PREFERENCES ("/wsmaster/api/preferences"), UPDATE_PREFERENCES ("/wsmaster/api/preferences"); diff --git a/src/main/java/io/fabric8/che/starter/client/CheServerClient.java b/src/main/java/io/fabric8/che/starter/client/CheServerClient.java deleted file mode 100644 index 40a2405..0000000 --- a/src/main/java/io/fabric8/che/starter/client/CheServerClient.java +++ /dev/null @@ -1,114 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.client; - -import java.util.concurrent.TimeUnit; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Component; - -import io.fabric8.che.starter.exception.MultiTenantMigrationException; -import io.fabric8.che.starter.exception.RouteNotFoundException; -import io.fabric8.che.starter.model.server.CheServerInfo; -import io.fabric8.che.starter.multi.tenant.MigrationConfigMap; -import io.fabric8.che.starter.multi.tenant.MigrationPod; -import io.fabric8.che.starter.multi.tenant.MultiTenantToggle; -import io.fabric8.che.starter.multi.tenant.TenantUpdater; -import io.fabric8.che.starter.openshift.CheDeploymentConfig; -import io.fabric8.che.starter.openshift.CheServerRouteChecker; -import io.fabric8.che.starter.util.CheServerHelper; -import io.fabric8.openshift.client.OpenShiftClient; - -@Component -public class CheServerClient { - - @Autowired - private CheDeploymentConfig cheDeploymentConfig; - - @Autowired - private MultiTenantToggle toggle; - - @Autowired - private CheServerRouteChecker cheServerRouteChecker; - - @Autowired - private TenantUpdater tenanUpdater; - - @Autowired - MigrationConfigMap migrationCongigMap; - - @Autowired - MigrationPod migrationPod; - - public CheServerInfo getCheServerInfo(OpenShiftClient client, String namespace, String requestURL, - String keycloakToken) throws MultiTenantMigrationException { - if (toggle.isMultiTenant(keycloakToken)) { - return getCheServerInfoForMultiTenant(client, namespace, requestURL, keycloakToken); - } else { - return getCheServerInfoForSingleTenant(client, namespace, requestURL, keycloakToken); - } - } - - @Async - public void startCheServer(OpenShiftClient client, String namespace, String keycloakToken) - throws RouteNotFoundException { - if (toggle.isMultiTenant(keycloakToken)) { - return; // che-starter is not supposed to start multi-tenant che-server - } - cheDeploymentConfig.deployCheIfSuspended(client, namespace); - } - - private CheServerInfo getCheServerInfoForSingleTenant(OpenShiftClient client, String namespace, String requestURL, - String keycloakToken) { - boolean isCheServerReadyToHandleRequests; - boolean isDeploymentAvailable = cheDeploymentConfig.isDeploymentAvailable(client, namespace); - - if (isDeploymentAvailable) { - isCheServerReadyToHandleRequests = cheServerRouteChecker.isRouteAccessible(client, namespace, keycloakToken); - } else { - isCheServerReadyToHandleRequests = false; - } - - CheServerInfo info = CheServerHelper.generateCheServerInfo(isCheServerReadyToHandleRequests, requestURL, false); - return info; - } - - private CheServerInfo getCheServerInfoForMultiTenant(OpenShiftClient client, String namespace, String requestURL, - String keycloakToken) { - if (cheDeploymentConfig.deploymentExists(client, namespace) && !migrationCongigMap.exists(client, namespace)) { - // user is supposed to be multi-tenant but still has single-tenant che-server in *-che namespace, - // and does not have 'migration' cm, so update tenant must be called - tenanUpdater.update(keycloakToken); - // wait 10 seconds to be sure that 'migration' cm would be created - indication that migration has started - try { - TimeUnit.SECONDS.sleep(10); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - // migration has just started - return CheServerHelper.generateCheServerInfo(false, requestURL, true); - } else if (migrationPod.exists(client, namespace) - && (!migrationPod.isReady(client, namespace) || migrationPod.isRunning(client, namespace))) { - // migration is in progress - return CheServerHelper.generateCheServerInfo(false, requestURL, true); - } else if (migrationPod.isTerminated(client, namespace)) { - // migration has been already done - return CheServerHelper.generateCheServerInfo(true, requestURL, true); - } else { - // Should only happen if migration pod have been removed manually - return CheServerHelper.generateCheServerInfo(true, requestURL, true); - } - } - -} diff --git a/src/main/java/io/fabric8/che/starter/client/ProjectClient.java b/src/main/java/io/fabric8/che/starter/client/ProjectClient.java index 9de24d0..f12d924 100644 --- a/src/main/java/io/fabric8/che/starter/client/ProjectClient.java +++ b/src/main/java/io/fabric8/che/starter/client/ProjectClient.java @@ -17,6 +17,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; @@ -30,53 +31,54 @@ public class ProjectClient { private static final Logger LOG = LoggerFactory.getLogger(ProjectClient.class); + @Value("${MULTI_TENANT_CHE_SERVER_URL:https://che.prod-preview.openshift.io}") + private String multiTenantCheServerURL; + @Autowired private WorkspaceClient workspaceClient; - /** - * Delete a project from workspace. Workspace must be running to delete a - * project. - * - * @param cheServerURL - * @param workspaceName - * @param projectName - */ - public void deleteProject(String cheServerURL, Workspace workspace, String projectName, String keycloakToken) { - String wsAgentUrl = getWsAgentUrl(workspace); - - String deleteProjectURL = CheRestEndpoints.DELETE_PROJECT.generateUrl(wsAgentUrl, projectName); - LOG.info("Deleting project {}", projectName); - RestTemplate template = new KeycloakRestTemplate(keycloakToken); - template.delete(deleteProjectURL); - } - @Async - public void deleteAllProjectsAndWorkspace(String cheServerURL, String workspaceName, String masterUrl, String namespace, String openShiftToken, - String keycloakToken) throws WorkspaceNotFound { - Workspace runningWorkspace = workspaceClient.getStartedWorkspace(cheServerURL, keycloakToken); + public void deleteAllProjectsAndWorkspace(String workspaceName, String keycloakToken) throws WorkspaceNotFound { + Workspace runningWorkspace = workspaceClient.getStartedWorkspace(keycloakToken); - Workspace workspaceToDelete = workspaceClient.startWorkspace(cheServerURL, workspaceName, masterUrl, namespace, openShiftToken, keycloakToken); - workspaceClient.waitUntilWorkspaceIsRunning(cheServerURL, workspaceToDelete, keycloakToken); - workspaceToDelete = workspaceClient.getWorkspaceById(cheServerURL, workspaceToDelete.getId(), keycloakToken); + Workspace workspaceToDelete = workspaceClient.startWorkspace(workspaceName, keycloakToken); + workspaceClient.waitUntilWorkspaceIsRunning(workspaceToDelete, keycloakToken); + workspaceToDelete = workspaceClient.getWorkspaceById(workspaceToDelete.getId(), keycloakToken); List projectsToDelete = workspaceToDelete.getConfig().getProjects(); if (projectsToDelete != null && !projectsToDelete.isEmpty()) { for (Project project : projectsToDelete) { - deleteProject(cheServerURL, workspaceToDelete, project.getName(), keycloakToken); + deleteProject(workspaceToDelete, project.getName(), keycloakToken); } } - workspaceClient.stopWorkspace(cheServerURL, workspaceToDelete, keycloakToken); - workspaceClient.waitUntilWorkspaceIsStopped(masterUrl, namespace, openShiftToken, cheServerURL, workspaceToDelete, keycloakToken); - - workspaceClient.deleteWorkspace(cheServerURL, workspaceToDelete.getId(), keycloakToken); + workspaceClient.stopWorkspace(workspaceToDelete, keycloakToken); + workspaceClient.waitUntilWorkspaceIsStopped(workspaceToDelete, keycloakToken); + workspaceClient.deleteWorkspace(workspaceToDelete.getId(), keycloakToken); if (runningWorkspace != null && !runningWorkspace.getConfig().getName().equals(workspaceName)) { - workspaceClient.startWorkspace(cheServerURL, runningWorkspace.getConfig().getName(), masterUrl, namespace, openShiftToken, keycloakToken); + workspaceClient.startWorkspace(runningWorkspace.getConfig().getName(), keycloakToken); } } + /** + * Delete a project from workspace. Workspace must be running to delete a + * project. + * + * @param workspaceName + * @param projectName + * @param keycloakToken + */ + public void deleteProject(Workspace workspace, String projectName, String keycloakToken) { + String wsAgentUrl = getWsAgentUrl(workspace); + + String deleteProjectURL = CheRestEndpoints.DELETE_PROJECT.generateUrl(wsAgentUrl, projectName); + LOG.info("Deleting project {}", projectName); + RestTemplate template = new KeycloakRestTemplate(keycloakToken); + template.delete(deleteProjectURL); + } + private String getWsAgentUrl(final Workspace workspace) { return workspace.getRuntime().getDevMachine().getRuntime().getServers().get("4401/tcp").getUrl(); } diff --git a/src/main/java/io/fabric8/che/starter/client/StackClient.java b/src/main/java/io/fabric8/che/starter/client/StackClient.java index 37ea397..694a783 100644 --- a/src/main/java/io/fabric8/che/starter/client/StackClient.java +++ b/src/main/java/io/fabric8/che/starter/client/StackClient.java @@ -15,6 +15,7 @@ import java.util.List; import java.util.NoSuchElementException; +import org.springframework.beans.factory.annotation.Value; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; @@ -29,8 +30,11 @@ @Component public class StackClient { - public List listStacks(String cheServerUrl, String keycloakToken) { - String url = CheRestEndpoints.LIST_STACKS.generateUrl(cheServerUrl); + @Value("${MULTI_TENANT_CHE_SERVER_URL:https://che.prod-preview.openshift.io}") + private String multiTenantCheServerURL; + + public List listStacks(String keycloakToken) { + String url = CheRestEndpoints.LIST_STACKS.generateUrl(multiTenantCheServerURL); RestTemplate template = new KeycloakRestTemplate(keycloakToken); @@ -44,14 +48,13 @@ public List listStacks(String cheServerUrl, String keycloakToken) { * Gets image for specified stack ID. Throws StackNotFoundException if there is no such stack * on the Che server. * - * @param cheServerUrl URL of Che server * @param stackId stack ID * @param keycloakToken Keycloak token * @return image name for stack * @throws StackNotFoundException if no image name exists for such stack ID or call to Che server was not successful */ - public Stack getStack(String cheServerUrl, String stackId, String keycloakToken) throws StackNotFoundException { - List stacks = listStacks(cheServerUrl, keycloakToken); + public Stack getStack(String stackId, String keycloakToken) throws StackNotFoundException { + List stacks = listStacks(keycloakToken); if (stacks != null && !stacks.isEmpty()) { try { Stack stack = stacks.stream().filter(s -> stackId.equals(s.getId())).findFirst().get(); diff --git a/src/main/java/io/fabric8/che/starter/client/WorkspaceClient.java b/src/main/java/io/fabric8/che/starter/client/WorkspaceClient.java index b179e13..ebeb74b 100644 --- a/src/main/java/io/fabric8/che/starter/client/WorkspaceClient.java +++ b/src/main/java/io/fabric8/che/starter/client/WorkspaceClient.java @@ -39,7 +39,6 @@ import io.fabric8.che.starter.model.workspace.WorkspaceConfig; import io.fabric8.che.starter.model.workspace.WorkspaceState; import io.fabric8.che.starter.model.workspace.WorkspaceStatus; -import io.fabric8.che.starter.openshift.OpenShiftClientWrapper; import io.fabric8.che.starter.util.ProjectHelper; import io.fabric8.che.starter.util.WorkspaceHelper; @@ -47,6 +46,9 @@ public class WorkspaceClient { private static final Logger LOG = LoggerFactory.getLogger(WorkspaceClient.class); + @Value("${MULTI_TENANT_CHE_SERVER_URL:https://che.prod-preview.openshift.io}") + private String multiTenantCheServerURL; + @Value("${che.workspace.start.timeout}") private long workspaceStartTimeout; @@ -60,19 +62,10 @@ public class WorkspaceClient { private StackClient stackClient; @Autowired - ProjectHelper projectHelper; - - @Autowired - OpenShiftClientWrapper openshiftClientWrapper; - - @Value("${che.openshift.start.timeout}") - private String startTimeout; + private ProjectHelper projectHelper; - @Value("${che.openshift.deploymentconfig}") - private String deploymentConfigName; - - public void waitUntilWorkspaceIsRunning(String cheServerURL, Workspace workspace, String keycloakToken) { - WorkspaceStatus status = getWorkspaceStatus(cheServerURL, workspace.getId(), keycloakToken); + public void waitUntilWorkspaceIsRunning(Workspace workspace, String keycloakToken) { + WorkspaceStatus status = getWorkspaceStatus(workspace.getId(), keycloakToken); long currentTime = System.currentTimeMillis(); while (!WorkspaceState.RUNNING.toString().equals(status.getWorkspaceStatus()) && System.currentTimeMillis() < (currentTime + workspaceStartTimeout)) { @@ -83,25 +76,20 @@ public void waitUntilWorkspaceIsRunning(String cheServerURL, Workspace workspace LOG.error("Error while polling for workspace status", e); break; } - status = getWorkspaceStatus(cheServerURL, workspace.getId(), keycloakToken); + status = getWorkspaceStatus(workspace.getId(), keycloakToken); } LOG.info("Workspace '{}' is running", workspace.getConfig().getName()); } /** - * This method blocks execution until the specified workspace has been stopped and its resources + * Blocks execution until the specified workspace has been stopped and its resources * made available again. * - * @param masterUrl The master URL for the OpenShift API - * @param namespace The OpenShift namespace - * @param openShiftToken The OpenShift token - * @param cheServerURL Che server URL * @param workspace The workspace to stop * @param keycloakToken The KeyCloak token */ - public void waitUntilWorkspaceIsStopped(String masterUrl, String namespace, String openShiftToken, - String cheServerURL, Workspace workspace, String keycloakToken) { - WorkspaceStatus status = getWorkspaceStatus(cheServerURL, workspace.getId(), keycloakToken); + public void waitUntilWorkspaceIsStopped(Workspace workspace, String keycloakToken) { + WorkspaceStatus status = getWorkspaceStatus(workspace.getId(), keycloakToken); long currentTime = System.currentTimeMillis(); // Poll the Che server until it returns a status of 'STOPPED' for the workspace @@ -114,12 +102,12 @@ public void waitUntilWorkspaceIsStopped(String masterUrl, String namespace, Stri LOG.error("Error while polling for workspace status", e); break; } - status = getWorkspaceStatus(cheServerURL, workspace.getId(), keycloakToken); + status = getWorkspaceStatus(workspace.getId(), keycloakToken); } } - public List listWorkspaces(String cheServerUrl, String keycloakToken) { - String url = CheRestEndpoints.LIST_WORKSPACES.generateUrl(cheServerUrl); + public List listWorkspaces(String keycloakToken) { + String url = CheRestEndpoints.LIST_WORKSPACES.generateUrl(multiTenantCheServerURL); RestTemplate template = new KeycloakRestTemplate(keycloakToken); ResponseEntity> response = template.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference>() { @@ -128,15 +116,14 @@ public List listWorkspaces(String cheServerUrl, String keycloakToken) return response.getBody(); } - public List listWorkspacesPerRepository(String cheServerUrl, String repository, String keycloakToken) { - List workspaces = listWorkspaces(cheServerUrl, keycloakToken); + public List listWorkspacesPerRepository(String repository, String keycloakToken) { + List workspaces = listWorkspaces(keycloakToken); return workspaceHelper.filterByRepository(workspaces, repository); } /** * Create workspace on the Che server with given URL. * - * @param cheServerUrl * @param keycloakToken * @param name * @param stackId @@ -147,10 +134,10 @@ public List listWorkspacesPerRepository(String cheServerUrl, String r * @throws IOException * @throws URISyntaxException */ - public Workspace createWorkspace(String cheServerURL, String keycloakToken, String stackId, String repo, + public Workspace createWorkspace(String keycloakToken, String stackId, String repo, String branch, String description) throws StackNotFoundException, IOException, URISyntaxException { - String url = CheRestEndpoints.CREATE_WORKSPACE.generateUrl(cheServerURL); - WorkspaceConfig wsConfig = stackClient.getStack(cheServerURL, stackId, keycloakToken).getWorkspaceConfig(); + String url = CheRestEndpoints.CREATE_WORKSPACE.generateUrl(multiTenantCheServerURL); + WorkspaceConfig wsConfig = stackClient.getStack(stackId, keycloakToken).getWorkspaceConfig(); String projectName = projectHelper.getProjectNameFromGitRepository(repo); String projectType = stackClient.getProjectTypeByStackId(stackId); @@ -178,8 +165,8 @@ public Workspace createWorkspace(String cheServerURL, String keycloakToken, Stri return workspace; } - public Workspace getWorkspaceById(String cheServerURL, String workspaceId, String keycloakToken) { - String url = CheRestEndpoints.GET_WORKSPACE_BY_ID.generateUrl(cheServerURL, workspaceId); + public Workspace getWorkspaceById(String workspaceId, String keycloakToken) { + String url = CheRestEndpoints.GET_WORKSPACE_BY_ID.generateUrl(multiTenantCheServerURL, workspaceId); RestTemplate template = new KeycloakRestTemplate(keycloakToken); HttpHeaders headers = new HttpHeaders(); @@ -190,10 +177,10 @@ public Workspace getWorkspaceById(String cheServerURL, String workspaceId, Strin } public Workspace getWorkspaceByName(String cheServerURL, String workspaceName, String keycloakToken) throws WorkspaceNotFound { - List workspaces = listWorkspaces(cheServerURL, keycloakToken); + List workspaces = listWorkspaces( keycloakToken); for (Workspace workspace : workspaces) { if (workspace.getConfig().getName().equals(workspaceName)) { - return getWorkspaceById(cheServerURL, workspace.getId(), keycloakToken); + return getWorkspaceById(workspace.getId(), keycloakToken); } } throw new WorkspaceNotFound("Workspace '" + workspaceName + "' was not found"); @@ -201,29 +188,18 @@ public Workspace getWorkspaceByName(String cheServerURL, String workspaceName, S /** Deletes a workspace. Workspace must be stopped before invoking its deletion. * - * @param cheServerURL Che server URL * @param workspaceId workspace ID + * @param keycloakToken keycloak token * @throws WorkspaceNotFound if workspace does not exists */ - public void deleteWorkspace(String cheServerURL, String workspaceId, String keycloakToken) throws WorkspaceNotFound { - String url = CheRestEndpoints.DELETE_WORKSPACE.generateUrl(cheServerURL, workspaceId); + public void deleteWorkspace(String workspaceId, String keycloakToken) throws WorkspaceNotFound { + String url = CheRestEndpoints.DELETE_WORKSPACE.generateUrl(multiTenantCheServerURL, workspaceId); RestTemplate template = new KeycloakRestTemplate(keycloakToken); template.delete(url); } - /** - * Starts and gets a workspace by its name. - * - * @param cheServerURL - * Che server URL - * @param workspaceName - * name of workspace to start - * @return started workspace - * @throws WorkspaceNotFound - */ - public Workspace startWorkspace(String cheServerURL, String workspaceName, String masterUrl, String namespace, - String openShiftToken, String keycloakToken) throws WorkspaceNotFound { - List workspaces = listWorkspaces(cheServerURL, keycloakToken); + public Workspace startWorkspace(String workspaceName, String keycloakToken) throws WorkspaceNotFound { + List workspaces = listWorkspaces(keycloakToken); boolean alreadyStarted = false; Workspace workspaceToStart = null; @@ -236,8 +212,8 @@ public Workspace startWorkspace(String cheServerURL, String workspaceName, Strin alreadyStarted = true; } } else if (!WorkspaceState.STOPPED.toString().equals(workspace.getStatus())) { - stopWorkspace(cheServerURL, workspace, keycloakToken); - waitUntilWorkspaceIsStopped(masterUrl, namespace, openShiftToken, cheServerURL, workspace, keycloakToken); + stopWorkspace(workspace, keycloakToken); + waitUntilWorkspaceIsStopped(workspace, keycloakToken); } } @@ -246,7 +222,7 @@ public Workspace startWorkspace(String cheServerURL, String workspaceName, Strin } if (!alreadyStarted) { - String url = CheRestEndpoints.START_WORKSPACE.generateUrl(cheServerURL, workspaceToStart.getId()); + String url = CheRestEndpoints.START_WORKSPACE.generateUrl(multiTenantCheServerURL, workspaceToStart.getId()); RestTemplate template = new KeycloakRestTemplate(keycloakToken); template.postForLocation(url, null); } @@ -254,21 +230,12 @@ public Workspace startWorkspace(String cheServerURL, String workspaceName, Strin } @Async - public Workspace startWorkspaceAsync(String cheServerURL, String workspaceName, String masterUrl, String namespace, - String openShiftToken, String keycloakToken) throws WorkspaceNotFound { - return startWorkspace(cheServerURL, workspaceName, masterUrl, namespace, openShiftToken, keycloakToken); + public Workspace startWorkspaceAsync(String workspaceName, String keycloakToken) throws WorkspaceNotFound { + return startWorkspace(workspaceName, keycloakToken); } - /** - * Gets started/starting workspace. - * - * @param cheServerUrl - * url of che server - * @return started workspace or null if there is no running/starting - * workspace - */ - public Workspace getStartedWorkspace(String cheServerURL, String keycloakToken) { - List workspaces = listWorkspaces(cheServerURL, keycloakToken); + public Workspace getStartedWorkspace(String keycloakToken) { + List workspaces = listWorkspaces(keycloakToken); for (Workspace workspace : workspaces) { if (WorkspaceState.RUNNING.toString().equals(workspace.getStatus()) @@ -279,17 +246,8 @@ public Workspace getStartedWorkspace(String cheServerURL, String keycloakToken) return null; } - /** - * Gets workspace status - * - * @param cheServerURL - * Che server URL - * @param workspaceId - * workspace ID - * @return workspace status - */ - public WorkspaceStatus getWorkspaceStatus(String cheServerURL, String workspaceId, String keycloakToken) { - String url = CheRestEndpoints.CHECK_WORKSPACE.generateUrl(cheServerURL, workspaceId); + public WorkspaceStatus getWorkspaceStatus(String workspaceId, String keycloakToken) { + String url = CheRestEndpoints.CHECK_WORKSPACE.generateUrl(multiTenantCheServerURL, workspaceId); RestTemplate template = new KeycloakRestTemplate(keycloakToken); HttpHeaders headers = new HttpHeaders(); @@ -300,12 +258,9 @@ public WorkspaceStatus getWorkspaceStatus(String cheServerURL, String workspaceI return status.getBody(); } - /** - * Stops a running workspace. - */ - public void stopWorkspace(String cheServerURL, Workspace workspace, String keycloakToken) { + public void stopWorkspace(Workspace workspace, String keycloakToken) { LOG.info("Stopping workspace {}", workspace.getId()); - String url = CheRestEndpoints.STOP_WORKSPACE.generateUrl(cheServerURL, workspace.getId()); + String url = CheRestEndpoints.STOP_WORKSPACE.generateUrl(multiTenantCheServerURL, workspace.getId()); RestTemplate template = new KeycloakRestTemplate(keycloakToken); template.delete(url); } diff --git a/src/main/java/io/fabric8/che/starter/client/WorkspacePreferencesClient.java b/src/main/java/io/fabric8/che/starter/client/WorkspacePreferencesClient.java index f989ac1..e761898 100644 --- a/src/main/java/io/fabric8/che/starter/client/WorkspacePreferencesClient.java +++ b/src/main/java/io/fabric8/che/starter/client/WorkspacePreferencesClient.java @@ -16,6 +16,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -33,31 +34,34 @@ public class WorkspacePreferencesClient { private static final Logger LOG = LoggerFactory.getLogger(WorkspacePreferencesClient.class); + @Value("${MULTI_TENANT_CHE_SERVER_URL:https://che.prod-preview.openshift.io}") + private String multiTenantCheServerURL; + @Autowired - GitHubClient client; + GitHubClient gitHubClient; - public void setCommitterInfo(final String cheServerUrl, final String gitHubToken, final String keycloakToken) { - GitHubUserInfo userInfo = client.getUserInfo(gitHubToken); + public void setCommitterInfo(final String gitHubToken, final String keycloakToken) { + GitHubUserInfo userInfo = gitHubClient.getUserInfo(gitHubToken); WorkspacePreferences preferences = getPreferences(userInfo); - setCommitterInfo(cheServerUrl, keycloakToken, preferences); + setCommitterInfo(keycloakToken, preferences); } - public void setCommitterInfo(final String cheServerUrl, final String keycloakToken, final WorkspacePreferences preferences) { + public void setCommitterInfo(final String keycloakToken, final WorkspacePreferences preferences) { RestTemplate template = new KeycloakRestTemplate(keycloakToken); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity entity = new HttpEntity(preferences, headers); - template.exchange(CheRestEndpoints.UPDATE_PREFERENCES.generateUrl(cheServerUrl), HttpMethod.PUT, entity, String.class); + template.exchange(CheRestEndpoints.UPDATE_PREFERENCES.generateUrl(multiTenantCheServerURL), HttpMethod.PUT, entity, String.class); } - public WorkspacePreferences getCommitterInfo(final String cheServerUrl, final String keycloakToken) { + public WorkspacePreferences getCommitterInfo(final String keycloakToken) { RestTemplate template = new KeycloakRestTemplate(keycloakToken); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity entity = new HttpEntity(headers); ResponseEntity response = template.exchange( - CheRestEndpoints.GET_PREFERENCES.generateUrl(cheServerUrl), HttpMethod.GET, entity, + CheRestEndpoints.GET_PREFERENCES.generateUrl(multiTenantCheServerURL), HttpMethod.GET, entity, WorkspacePreferences.class); return response.getBody(); } diff --git a/src/main/java/io/fabric8/che/starter/client/github/GitHubClient.java b/src/main/java/io/fabric8/che/starter/client/github/GitHubClient.java index 966b60e..bf0a2f1 100644 --- a/src/main/java/io/fabric8/che/starter/client/github/GitHubClient.java +++ b/src/main/java/io/fabric8/che/starter/client/github/GitHubClient.java @@ -39,6 +39,9 @@ public class GitHubClient { private static final Logger LOG = LoggerFactory.getLogger(GitHubClient.class); + @Value("${MULTI_TENANT_CHE_SERVER_URL:https://che.prod-preview.openshift.io}") + private String multiTenantCheServerURL; + @Value("${GITHUB_USER_URL:https://api.github.com/user}") private String GITHUB_USER_URL; @@ -52,9 +55,9 @@ public class GitHubClient { * @throws IOException * @throws GitHubOAthTokenException */ - public void setGitHubOAuthToken(final String cheServerURL, final String gitHubToken, final String keycloakToken) + public void setGitHubOAuthToken(final String gitHubToken, final String keycloakToken) throws IOException, GitHubOAthTokenException { - String url = cheServerURL + CheRestEndpoints.SET_OAUTH_TOKEN_V1.getEndpoint().replace("{provider}", "github"); + String url = CheRestEndpoints.SET_OAUTH_TOKEN.generateUrl(multiTenantCheServerURL); Token token = new Token(); token.setToken(gitHubToken); @@ -66,13 +69,9 @@ public void setGitHubOAuthToken(final String cheServerURL, final String gitHubTo try { template.postForLocation(url, entity); + LOG.debug("GitHub OAuth token has been successfully set via '{}'", url); } catch (Exception e) { - LOG.info("Trying new version of API - Unable to set GitHub OAuth token via '{}'", url); - try { - setGitHubOAuthTokenVersion2(cheServerURL, template, entity); - } catch (Exception ex) { - throw new GitHubOAthTokenException("Error setting GitHub OAuth token", ex); - } + throw new GitHubOAthTokenException("Error setting GitHub OAuth token", e); } } @@ -102,10 +101,4 @@ public GitHubEmail getPrimaryEmail(final String gitHubToken) { return primary; } - private void setGitHubOAuthTokenVersion2(String cheServerURL, RestTemplate template, HttpEntity entity) { - String url = cheServerURL + CheRestEndpoints.SET_OAUTH_TOKEN_V2.getEndpoint(); - template.postForLocation(url, entity); - LOG.info("GitHub OAuth token has been successfully set via '{}'", url); - } - } diff --git a/src/main/java/io/fabric8/che/starter/client/keycloak/KeycloakClient.java b/src/main/java/io/fabric8/che/starter/client/github/GitHubTokenProvider.java similarity index 70% rename from src/main/java/io/fabric8/che/starter/client/keycloak/KeycloakClient.java rename to src/main/java/io/fabric8/che/starter/client/github/GitHubTokenProvider.java index f1a35ed..47d4322 100644 --- a/src/main/java/io/fabric8/che/starter/client/keycloak/KeycloakClient.java +++ b/src/main/java/io/fabric8/che/starter/client/github/GitHubTokenProvider.java @@ -10,11 +10,10 @@ * http://www.eclipse.org/legal/epl-v10.html * #L% */ -package io.fabric8.che.starter.client.keycloak; +package io.fabric8.che.starter.client.github; import java.io.IOException; -import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -27,33 +26,17 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.fabric8.che.starter.client.keycloak.KeycloakRestTemplate; import io.fabric8.che.starter.exception.KeycloakException; @Component -public class KeycloakClient { - private static final Logger LOG = LoggerFactory.getLogger(KeycloakClient.class); +public class GitHubTokenProvider { + private static final Logger LOG = LoggerFactory.getLogger(GitHubTokenProvider.class); private static final String ACCESS_TOKEN = "access_token"; - @Value("${OSO_ADMIN_TOKEN:#{null}}") - private String openShiftAdminToken; - - @Value("${OPENSHIFT_TOKEN_URL:https://sso.prod-preview.openshift.io/auth/realms/fabric8/broker/openshift-v3/token}") - private String openShiftTokenUrl; - @Value("${GITHUB_TOKEN_URL:https://auth.prod-preview.openshift.io/api/token?for=https://github.com}") private String gitHubTokenUrl; - public String getOpenShiftToken(String keycloakToken) throws JsonProcessingException, IOException, KeycloakException { - if (StringUtils.isNotBlank(openShiftAdminToken)) { - LOG.info("Using OpenShift admin token"); - return openShiftAdminToken; - } - LOG.info("OpenShift token url - {}", openShiftTokenUrl); - // {"access_token":"token","expires_in":86400,"scope":"user:full","token_type":"Bearer"} - String token = getAccessToken(openShiftTokenUrl, keycloakToken); - return token; - } - public String getGitHubToken(String keycloakToken) throws KeycloakException, JsonProcessingException, IOException { LOG.info("GitHub token url - {}", gitHubTokenUrl); // {"access_token":"token","scope":"admin:repo_hook,gist,read:org,repo,user","token_type":"bearer"} diff --git a/src/main/java/io/fabric8/che/starter/controller/CheServerController.java b/src/main/java/io/fabric8/che/starter/controller/CheServerController.java index 58609a2..a30dd90 100644 --- a/src/main/java/io/fabric8/che/starter/controller/CheServerController.java +++ b/src/main/java/io/fabric8/che/starter/controller/CheServerController.java @@ -15,7 +15,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; @@ -23,14 +22,9 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import io.fabric8.che.starter.client.CheServerClient; -import io.fabric8.che.starter.client.keycloak.KeycloakClient; import io.fabric8.che.starter.client.keycloak.KeycloakTokenValidator; -import io.fabric8.che.starter.exception.MultiTenantMigrationException; -import io.fabric8.che.starter.exception.RouteNotFoundException; import io.fabric8.che.starter.model.server.CheServerInfo; -import io.fabric8.che.starter.openshift.OpenShiftClientWrapper; -import io.fabric8.openshift.client.OpenShiftClient; +import io.fabric8.che.starter.util.CheServerHelper; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -38,68 +32,31 @@ @RestController public class CheServerController { - @Autowired - OpenShiftClientWrapper openShiftClientWrapper; - - @Autowired - KeycloakClient keycloakClient; - - @Autowired - CheServerClient cheServerClient; - @ApiOperation(value = "Get Che server info") @GetMapping("/server") public CheServerInfo getCheServerInfo(@RequestParam String masterUrl, @RequestParam String namespace, @ApiParam(value = "Keycloak token", required = true) @RequestHeader("Authorization") String keycloakToken, HttpServletRequest request) throws Exception { - KeycloakTokenValidator.validate(keycloakToken); - String openShiftToken = keycloakClient.getOpenShiftToken(keycloakToken); - OpenShiftClient openShiftClient = openShiftClientWrapper.get(masterUrl, openShiftToken); - String requestURL = request.getRequestURL().toString(); - return cheServerClient.getCheServerInfo(openShiftClient, namespace, requestURL, keycloakToken); - } - - @ApiOperation(value = "Get Che server info") - @GetMapping("/server/oso") - public CheServerInfo getCheServerInfoOnOpenShift(@RequestParam String masterUrl, @RequestParam String namespace, - @ApiParam(value = "OpenShift token", required = true) @RequestHeader("Authorization") String openShiftToken, HttpServletRequest request) throws Exception { - - OpenShiftClient openShiftClient = openShiftClientWrapper.get(masterUrl, openShiftToken); - String requestURL = request.getRequestURL().toString(); - return cheServerClient.getCheServerInfo(openShiftClient, namespace, requestURL, null); + return getCheServerInfo(request); + } + /* + * Deprecated since che-starter is not supposed to start multi-tenant che server which never idles + */ + @Deprecated @ApiOperation(value = "Start Che Server") @PatchMapping("/server") public CheServerInfo startCheServer(@RequestParam String masterUrl, @RequestParam String namespace, @ApiParam(value = "Keycloak token", required = true) @RequestHeader("Authorization") String keycloakToken, HttpServletResponse response, HttpServletRequest request) throws Exception { KeycloakTokenValidator.validate(keycloakToken); - String openShiftToken = keycloakClient.getOpenShiftToken(keycloakToken); - CheServerInfo info = startServer(masterUrl, openShiftToken, keycloakToken, namespace, response, request); - return info; + return getCheServerInfo(request); } - @ApiOperation(value = "Start Che Server") - @PatchMapping("/server/oso") - public CheServerInfo startCheServerOnOpenShift(@RequestParam String masterUrl, @RequestParam String namespace, - @ApiParam(value = "OpenShift token", required = true) @RequestHeader("Authorization") String openShiftToken, HttpServletResponse response, HttpServletRequest request) throws Exception { - - CheServerInfo info = startServer(masterUrl, openShiftToken, null, namespace, response, request); - return info; - } - - private CheServerInfo startServer(String masterUrl, String openShiftToken, String keycloakToken, String namespace, HttpServletResponse response, - HttpServletRequest request) throws RouteNotFoundException, MultiTenantMigrationException { - OpenShiftClient openShiftClient = openShiftClientWrapper.get(masterUrl, openShiftToken); + private CheServerInfo getCheServerInfo(HttpServletRequest request) { String requestURL = request.getRequestURL().toString(); - - CheServerInfo cheServerInfo = cheServerClient.getCheServerInfo(openShiftClient, namespace, requestURL, keycloakToken); - if (!cheServerInfo.isRunning()) { - cheServerClient.startCheServer(openShiftClient, namespace, keycloakToken); - response.setStatus(HttpServletResponse.SC_ACCEPTED); - } - return cheServerInfo; + return CheServerHelper.generateCheServerInfo(true, requestURL, true); } } diff --git a/src/main/java/io/fabric8/che/starter/controller/StackController.java b/src/main/java/io/fabric8/che/starter/controller/StackController.java index ce87635..bce2122 100644 --- a/src/main/java/io/fabric8/che/starter/controller/StackController.java +++ b/src/main/java/io/fabric8/che/starter/controller/StackController.java @@ -15,8 +15,6 @@ import java.io.IOException; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; @@ -27,51 +25,26 @@ import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.che.starter.client.StackClient; -import io.fabric8.che.starter.client.keycloak.KeycloakClient; import io.fabric8.che.starter.client.keycloak.KeycloakTokenValidator; import io.fabric8.che.starter.exception.KeycloakException; -import io.fabric8.che.starter.exception.RouteNotFoundException; import io.fabric8.che.starter.model.stack.Stack; -import io.fabric8.che.starter.openshift.OpenShiftClientWrapper; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @CrossOrigin @RestController public class StackController { - private static final Logger LOG = LoggerFactory.getLogger(StackController.class); - @Autowired private StackClient stackClient; - @Autowired - private OpenShiftClientWrapper openShiftClientWrapper; - - @Autowired - KeycloakClient keycloakClient; - @ApiOperation(value = "List the available stacks") @GetMapping("/stack") - public List list(@RequestParam String masterUrl, @RequestParam String namespace, @ApiParam(value = "Keycloak token", required = true) @RequestHeader("Authorization") String keycloakToken) - throws RouteNotFoundException, JsonProcessingException, IOException, KeycloakException { + public List list(@RequestParam String masterUrl, @RequestParam String namespace, + @ApiParam(value = "Keycloak token", required = true) @RequestHeader("Authorization") String keycloakToken) + throws JsonProcessingException, IOException, KeycloakException { + KeycloakTokenValidator.validate(keycloakToken); - String openShiftToken = keycloakClient.getOpenShiftToken(keycloakToken); - return getStacks(masterUrl, namespace, openShiftToken, keycloakToken); - } - - @ApiOperation(value = "List the available stacks") - @GetMapping("/stack/oso") - public List listOnOpenShift(@RequestParam String masterUrl, @RequestParam String namespace, @ApiParam(value = "OpenShift token", required = true) @RequestHeader("Authorization") String openShiftToken) - throws RouteNotFoundException, JsonProcessingException, IOException { - return getStacks(masterUrl, namespace, openShiftToken, null); - } - - private List getStacks(String masterUrl, String namespace, String openShiftToken, String keycloakToken) throws RouteNotFoundException { - LOG.info("Getting stacks from masterUrl {}", masterUrl); - LOG.info("Getting stacks from namespace {}", namespace); - - String cheServerUrl = openShiftClientWrapper.getCheServerUrl(masterUrl, namespace, openShiftToken, keycloakToken); - return stackClient.listStacks(cheServerUrl, keycloakToken); + return stackClient.listStacks(keycloakToken); } } diff --git a/src/main/java/io/fabric8/che/starter/controller/WorkspaceController.java b/src/main/java/io/fabric8/che/starter/controller/WorkspaceController.java index d6d1cc7..5a9fccd 100644 --- a/src/main/java/io/fabric8/che/starter/controller/WorkspaceController.java +++ b/src/main/java/io/fabric8/che/starter/controller/WorkspaceController.java @@ -40,17 +40,14 @@ import io.fabric8.che.starter.client.WorkspaceClient; import io.fabric8.che.starter.client.WorkspacePreferencesClient; import io.fabric8.che.starter.client.github.GitHubClient; -import io.fabric8.che.starter.client.keycloak.KeycloakClient; +import io.fabric8.che.starter.client.github.GitHubTokenProvider; import io.fabric8.che.starter.client.keycloak.KeycloakTokenValidator; import io.fabric8.che.starter.exception.GitHubOAthTokenException; import io.fabric8.che.starter.exception.KeycloakException; -import io.fabric8.che.starter.exception.ProjectCreationException; -import io.fabric8.che.starter.exception.RouteNotFoundException; import io.fabric8.che.starter.exception.StackNotFoundException; import io.fabric8.che.starter.exception.WorkspaceNotFound; import io.fabric8.che.starter.model.request.WorkspaceCreateParams; import io.fabric8.che.starter.model.workspace.Workspace; -import io.fabric8.che.starter.openshift.OpenShiftClientWrapper; import io.fabric8.che.starter.util.WorkspaceHelper; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -60,9 +57,6 @@ public class WorkspaceController { private static final Logger LOG = LoggerFactory.getLogger(WorkspaceController.class); - @Autowired - OpenShiftClientWrapper openShiftClientWrapper; - @Autowired WorkspaceClient workspaceClient; @@ -70,7 +64,7 @@ public class WorkspaceController { ProjectClient projectClient; @Autowired - KeycloakClient keycloakClient; + GitHubTokenProvider keycloakClient; @Autowired GitHubClient tokenClient; @@ -87,23 +81,11 @@ public List list(@RequestParam String masterUrl, @RequestParam String @RequestParam(required = false) String repository, @ApiParam(value = "Keycloak token", required = true) @RequestHeader("Authorization") String keycloakToken, HttpServletRequest request) - throws RouteNotFoundException, JsonProcessingException, IOException, KeycloakException { + throws JsonProcessingException, IOException, KeycloakException { KeycloakTokenValidator.validate(keycloakToken); - String openShiftToken = keycloakClient.getOpenShiftToken(keycloakToken); String requestURL = request.getRequestURL().toString(); - return listWorkspaces(masterUrl, namespace, openShiftToken, repository, requestURL, keycloakToken); - } - - @ApiOperation(value = "List workspaces per git repository. If repository parameter is not specified return all workspaces") - @GetMapping("/workspace/oso") - public List listOnOpenShift(@RequestParam String masterUrl, @RequestParam String namespace, - @RequestParam(required = false) String repository, - @ApiParam(value = "OpenShift token", required = true) @RequestHeader("Authorization") String openShiftToken, - HttpServletRequest request) throws RouteNotFoundException, JsonProcessingException, IOException { - - String requestURL = request.getRequestURL().toString(); - return listWorkspaces(masterUrl, namespace, openShiftToken, repository, requestURL, null); + return listWorkspaces(repository, requestURL, keycloakToken); } @ApiOperation(value = "Create and start a new workspace. Stop all other workspaces (only one workspace can be running at a time)") @@ -111,24 +93,12 @@ public List listOnOpenShift(@RequestParam String masterUrl, @RequestP public Workspace create(@RequestParam String masterUrl, @RequestParam String namespace, @RequestBody WorkspaceCreateParams params, @ApiParam(value = "Keycloak token", required = true) @RequestHeader("Authorization") String keycloakToken) - throws IOException, URISyntaxException, RouteNotFoundException, StackNotFoundException, - GitHubOAthTokenException, ProjectCreationException, KeycloakException, WorkspaceNotFound { + throws IOException, URISyntaxException, StackNotFoundException, + GitHubOAthTokenException, KeycloakException, WorkspaceNotFound { KeycloakTokenValidator.validate(keycloakToken); - String openShiftToken = keycloakClient.getOpenShiftToken(keycloakToken); String gitHubOAuthToken = keycloakClient.getGitHubToken(keycloakToken); - return createWorkspace(masterUrl, namespace, openShiftToken, gitHubOAuthToken, keycloakToken, params); - } - - @ApiOperation(value = "Create and start a new workspace. Stop all other workspaces (only one workspace can be running at a time)") - @PostMapping("/workspace/oso") - public Workspace createOnOpenShift(@RequestParam String masterUrl, @RequestParam String namespace, - @RequestBody WorkspaceCreateParams params, - @ApiParam(value = "OpenShift token", required = true) @RequestHeader("Authorization") String openShiftToken) - throws IOException, URISyntaxException, RouteNotFoundException, StackNotFoundException, - GitHubOAthTokenException, ProjectCreationException, WorkspaceNotFound { - - return createWorkspace(masterUrl, namespace, openShiftToken, null, null, params); + return createWorkspace(gitHubOAuthToken, keycloakToken, params); } @ApiOperation(value = "Start an existing workspace. Stop all other workspaces (only one workspace can be running at a time)") @@ -136,52 +106,25 @@ public Workspace createOnOpenShift(@RequestParam String masterUrl, @RequestParam public Workspace startExisting(@PathVariable String name, @RequestParam String masterUrl, @RequestParam String namespace, @ApiParam(value = "Keycloak token", required = true) @RequestHeader("Authorization") String keycloakToken) - throws IOException, URISyntaxException, RouteNotFoundException, StackNotFoundException, - GitHubOAthTokenException, ProjectCreationException, KeycloakException, WorkspaceNotFound { + throws IOException, URISyntaxException, StackNotFoundException, + GitHubOAthTokenException, KeycloakException, WorkspaceNotFound { KeycloakTokenValidator.validate(keycloakToken); - - String openShiftToken = keycloakClient.getOpenShiftToken(keycloakToken); String gitHubToken = keycloakClient.getGitHubToken(keycloakToken); - String cheServerURL = openShiftClientWrapper.getCheServerUrl(masterUrl, namespace, openShiftToken, keycloakToken); - - Workspace workspace = workspaceClient.startWorkspace(cheServerURL, name, masterUrl, namespace, openShiftToken, keycloakToken); - setGitHubOAthTokenAndCommitterInfo(cheServerURL, gitHubToken, keycloakToken); + Workspace workspace = workspaceClient.startWorkspace(name, keycloakToken); + setGitHubOAthTokenAndCommitterInfo(gitHubToken, keycloakToken); return workspace; } - @ApiOperation(value = "Start an existing workspace. Stop all other workspaces (only one workspace can be running at a time)") - @PatchMapping("/workspace/oso/{name}") - public Workspace startExistingOnOpenShift(@PathVariable String name, @RequestParam String masterUrl, - @RequestParam String namespace, - @ApiParam(value = "OpenShift token", required = true) @RequestHeader("Authorization") String openShiftToken) - throws IOException, URISyntaxException, RouteNotFoundException, StackNotFoundException, - GitHubOAthTokenException, ProjectCreationException, WorkspaceNotFound { - - String cheServerURL = openShiftClientWrapper.getCheServerUrl(masterUrl, namespace, openShiftToken, null); - return workspaceClient.startWorkspace(cheServerURL, name, masterUrl, namespace, openShiftToken, null); - } - @ApiOperation(value = "Delete an existing workspace") @DeleteMapping("/workspace/{name}") public void deleteExistingWorkspace(@PathVariable String name, @RequestParam String masterUrl, @RequestParam String namespace, @ApiParam(value = "Keycloak token", required = true) @RequestHeader("Authorization") String keycloakToken) - throws JsonProcessingException, IOException, KeycloakException, RouteNotFoundException, WorkspaceNotFound { + throws JsonProcessingException, IOException, KeycloakException, WorkspaceNotFound { KeycloakTokenValidator.validate(keycloakToken); - String openShiftToken = keycloakClient.getOpenShiftToken(keycloakToken); - deleteWorkspace(masterUrl, namespace, openShiftToken, name, keycloakToken); - } - - @ApiOperation(value = "Delete an existing workspace") - @DeleteMapping("/workspace/oso/{name}") - public void deleteExistingWorkspaceOnOpenShift(@PathVariable String name, @RequestParam String masterUrl, - @RequestParam String namespace, - @ApiParam(value = "OpenShift token", required = true) @RequestHeader("Authorization") String openShiftToken) - throws JsonProcessingException, IOException, KeycloakException, RouteNotFoundException, WorkspaceNotFound { - - deleteWorkspace(masterUrl, namespace, openShiftToken, name, null); + deleteWorkspace(name, keycloakToken); } /** @@ -190,103 +133,68 @@ public void deleteExistingWorkspaceOnOpenShift(@PathVariable String name, @Reque * running, during this process it is stopped and after successful deletion * it gets started again. * - * @param masterURL - * master URL - * @param namespace - * namespace - * @param openShiftToken - * OpenShift token * @param workspaceName - * workspace name - * @throws RouteNotFoundException + * @param keycloakToken * @throws WorkspaceNotFound */ - public void deleteWorkspace(String masterUrl, String namespace, String openShiftToken, String workspaceName, String keycloakToken) - throws RouteNotFoundException, WorkspaceNotFound { - String cheServerURL = openShiftClientWrapper.getCheServerUrl(masterUrl, namespace, openShiftToken, keycloakToken); - - projectClient.deleteAllProjectsAndWorkspace(cheServerURL, workspaceName, masterUrl, namespace, openShiftToken, keycloakToken); + public void deleteWorkspace(String workspaceName, String keycloakToken) throws WorkspaceNotFound { + projectClient.deleteAllProjectsAndWorkspace(workspaceName, keycloakToken); } /** * Create workspace from specified params. * - * @param masterUrl - * @param namespace - * @param openShiftToken * @param gitHubOAuthToken * @param keycloakToken * @param params * @return create Workspace * @throws WorkspaceNotFound */ - public Workspace createWorkspace(String masterUrl, String namespace, String openShiftToken, - String gitHubOAuthToken, String keycloakToken, WorkspaceCreateParams params) - throws RouteNotFoundException, URISyntaxException, IOException, StackNotFoundException, - GitHubOAthTokenException, ProjectCreationException, WorkspaceNotFound { - - String cheServerURL = openShiftClientWrapper.getCheServerUrl(masterUrl, namespace, openShiftToken, keycloakToken); - Workspace workspace = createWorkspaceFromParams(cheServerURL, keycloakToken, gitHubOAuthToken, params); + public Workspace createWorkspace(String gitHubOAuthToken, String keycloakToken, WorkspaceCreateParams params) + throws URISyntaxException, IOException, StackNotFoundException, + GitHubOAthTokenException, WorkspaceNotFound { + Workspace workspace = createWorkspaceFromParams(gitHubOAuthToken, keycloakToken, params); String workspaceName = workspace.getConfig().getName(); - workspaceClient.startWorkspaceAsync(cheServerURL, workspaceName, masterUrl, namespace, openShiftToken, keycloakToken); - + workspaceClient.startWorkspaceAsync(workspaceName, keycloakToken); return workspace; } /** - * Creates a new workspace from params. - * - * @param cheServerURL - * che server URL - * @param keycloakToken - * keycloak token to authenticate against Che server - * @param params - * workspace create params - * @throws IOException - * @throws StackNotFoundException - * @throws GitHubOAthTokenException - * - * @return created workspace - * @throws URISyntaxException + * Creates a new workspace from params */ - private Workspace createWorkspaceFromParams(String cheServerURL, String keycloakToken, String gitHubToken, - WorkspaceCreateParams params) throws StackNotFoundException, IOException, GitHubOAthTokenException, URISyntaxException { - - Workspace workspace = workspaceClient.createWorkspace(cheServerURL, keycloakToken, params.getStackId(), - params.getRepo(), params.getBranch(), params.getDescription()); - setGitHubOAthTokenAndCommitterInfo(cheServerURL, gitHubToken, keycloakToken); + private Workspace createWorkspaceFromParams(String gitHubToken, String keycloakToken, WorkspaceCreateParams params) throws StackNotFoundException, IOException, GitHubOAthTokenException, URISyntaxException { + Workspace workspace = workspaceClient.createWorkspace(keycloakToken, params.getStackId(), params.getRepo(), params.getBranch(), params.getDescription()); + setGitHubOAthTokenAndCommitterInfo(gitHubToken, keycloakToken); return workspace; } - private void setGitHubOAthTokenAndCommitterInfo(String cheServerURL, String gitHubToken, String keycloakToken) + private void setGitHubOAthTokenAndCommitterInfo(String gitHubToken, String keycloakToken) throws IOException, GitHubOAthTokenException { if (!StringUtils.isBlank(gitHubToken)) { - tokenClient.setGitHubOAuthToken(cheServerURL, gitHubToken, keycloakToken); + tokenClient.setGitHubOAuthToken(gitHubToken, keycloakToken); try { - workspacePreferencesClient.setCommitterInfo(cheServerURL, gitHubToken, keycloakToken); + workspacePreferencesClient.setCommitterInfo(gitHubToken, keycloakToken); } catch (Exception e) { LOG.warn("Unable to set committer info in Che Git preferences"); } } } - public List listWorkspaces(final String masterURL, final String namespace, final String openShiftToken, - final String repository, final String requestUrl, final String keycloakToken) throws RouteNotFoundException { - String cheServerURL = openShiftClientWrapper.getCheServerUrl(masterURL, namespace, openShiftToken, keycloakToken); + public List listWorkspaces(final String repository, final String requestUrl, final String keycloakToken) { List workspaces; try { if (!StringUtils.isBlank(repository)) { LOG.info("Fetching workspaces for repositoriy: {}", repository); - workspaces = workspaceClient.listWorkspacesPerRepository(cheServerURL, repository, keycloakToken); + workspaces = workspaceClient.listWorkspacesPerRepository(repository, keycloakToken); } else { - workspaces = workspaceClient.listWorkspaces(cheServerURL, keycloakToken); + workspaces = workspaceClient.listWorkspaces(keycloakToken); } workspaceHelper.addWorkspaceStartLink(workspaces, requestUrl); } catch (RestClientException e) { throw new RestClientException( - "Error while getting the list of workspaces against che server route: " + cheServerURL, e); + "Error while getting the list of workspaces", e); } return workspaces; } diff --git a/src/main/java/io/fabric8/che/starter/exception/GlobalExceptionHandler.java b/src/main/java/io/fabric8/che/starter/exception/GlobalExceptionHandler.java index b77ed3f..3ba338b 100644 --- a/src/main/java/io/fabric8/che/starter/exception/GlobalExceptionHandler.java +++ b/src/main/java/io/fabric8/che/starter/exception/GlobalExceptionHandler.java @@ -39,12 +39,6 @@ public String handleHostException(UnknownHostException e) { return e.getMessage(); } - @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Route not found") - @ExceptionHandler(RouteNotFoundException.class) - public String handleRouteNotFoundException(RouteNotFoundException e) { - return e.getMessage(); - } - @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Stack not found") @ExceptionHandler(StackNotFoundException.class) public String handleStackNotFoundException(StackNotFoundException e) { @@ -81,21 +75,10 @@ public String handleGitHubOAthTokenException(GitHubOAthTokenException e) { return e.getMessage(); } - @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Error occurred while creating project") - @ExceptionHandler(ProjectCreationException.class) - public String handleProjectCreationException(ProjectCreationException e) { - return e.getMessage(); - } - @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Workspace not found") @ExceptionHandler(WorkspaceNotFound.class) public String handleWorkspaceNotFoundException(WorkspaceNotFound e) { return e.getMessage(); } - @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Migration to multi-tenant Che server has failed") - @ExceptionHandler(MultiTenantMigrationException.class) - public String handleMultiTenantMigrationException(WorkspaceNotFound e) { - return e.getMessage(); - } } diff --git a/src/main/java/io/fabric8/che/starter/exception/MultiTenantMigrationException.java b/src/main/java/io/fabric8/che/starter/exception/MultiTenantMigrationException.java deleted file mode 100644 index 9ee7634..0000000 --- a/src/main/java/io/fabric8/che/starter/exception/MultiTenantMigrationException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.exception; - -public class MultiTenantMigrationException extends Exception { - private static final long serialVersionUID = 1L; - - public MultiTenantMigrationException() { - } - - public MultiTenantMigrationException(String message) { - super(message); - } - - public MultiTenantMigrationException(Throwable cause) { - super(cause); - } - - public MultiTenantMigrationException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/src/main/java/io/fabric8/che/starter/exception/ProjectCreationException.java b/src/main/java/io/fabric8/che/starter/exception/ProjectCreationException.java deleted file mode 100644 index d3b9c22..0000000 --- a/src/main/java/io/fabric8/che/starter/exception/ProjectCreationException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.exception; - -public class ProjectCreationException extends Exception { - private static final long serialVersionUID = 1L; - - public ProjectCreationException() { - } - - public ProjectCreationException(String message) { - super(message); - } - - public ProjectCreationException(Throwable cause) { - super(cause); - } - - public ProjectCreationException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/src/main/java/io/fabric8/che/starter/exception/RouteNotFoundException.java b/src/main/java/io/fabric8/che/starter/exception/RouteNotFoundException.java deleted file mode 100644 index 3539e40..0000000 --- a/src/main/java/io/fabric8/che/starter/exception/RouteNotFoundException.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.exception; - -public class RouteNotFoundException extends Exception { - private static final long serialVersionUID = 1L; - - public RouteNotFoundException() { - } - - public RouteNotFoundException(String message) { - super(message); - } - - public RouteNotFoundException(Throwable cause) { - super(cause); - } - - public RouteNotFoundException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/src/main/java/io/fabric8/che/starter/multi/tenant/MigrationConfigMap.java b/src/main/java/io/fabric8/che/starter/multi/tenant/MigrationConfigMap.java deleted file mode 100644 index c5cbf82..0000000 --- a/src/main/java/io/fabric8/che/starter/multi/tenant/MigrationConfigMap.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.multi.tenant; - -import org.springframework.stereotype.Component; - -import io.fabric8.che.starter.exception.MultiTenantMigrationException; -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.fabric8.openshift.client.OpenShiftClient; - -@Component -public class MigrationConfigMap { - private static final String REQUEST_ID = "request-id"; - private static final String MIGRATION_CONFIG_MAP_NAME = "migration"; - - public boolean exists(final OpenShiftClient client, final String namespace) { - return getConfigMap(client, namespace) != null; - } - - public String getRequestId(final OpenShiftClient client, final String namespace) throws MultiTenantMigrationException { - ConfigMap cm = getConfigMap(client, namespace); - if (cm == null) { - throw new MultiTenantMigrationException(MIGRATION_CONFIG_MAP_NAME + " config map does not exist"); - } - return cm.getData().get(REQUEST_ID); - } - - private ConfigMap getConfigMap(final OpenShiftClient client, final String namespace) { - return client.configMaps().inNamespace(namespace).withName(MIGRATION_CONFIG_MAP_NAME).get(); - } -} diff --git a/src/main/java/io/fabric8/che/starter/multi/tenant/MigrationPod.java b/src/main/java/io/fabric8/che/starter/multi/tenant/MigrationPod.java deleted file mode 100644 index 06fd4f8..0000000 --- a/src/main/java/io/fabric8/che/starter/multi/tenant/MigrationPod.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.multi.tenant; - -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import io.fabric8.che.starter.exception.MultiTenantMigrationException; -import io.fabric8.kubernetes.api.model.ContainerStateRunning; -import io.fabric8.kubernetes.api.model.ContainerStateTerminated; -import io.fabric8.kubernetes.api.model.Pod; -import io.fabric8.openshift.client.OpenShiftClient; - -@Component -public class MigrationPod { - private static final Logger LOG = LoggerFactory.getLogger(MigrationPod.class); - private static final String MIGRATION_POD_LABEL = "migration"; - private static final String REQUEST_ID_ANNOTATION = "request-id"; - - @Autowired - MigrationConfigMap migrationCongigMap; - - public boolean exists(final OpenShiftClient client, final String namespace) { - Pod pod = getPod(client, namespace); - return (pod != null); - } - - public boolean isReady(final OpenShiftClient client, final String namespace) { - Pod pod = getPod(client, namespace); - if (pod != null) { - return pod.getStatus().getContainerStatuses().get(0).getReady(); - } - return false; - } - - public boolean isRunning(final OpenShiftClient client, final String namespace) { - Pod pod = getPod(client, namespace); - if (pod != null) { - ContainerStateRunning running = pod.getStatus().getContainerStatuses().get(0).getState().getRunning(); - return (running != null); - } - return false; - } - - public boolean isTerminated(final OpenShiftClient client, final String namespace) { - Pod pod = getPod(client, namespace); - if (pod != null) { - ContainerStateTerminated terminated = pod.getStatus().getContainerStatuses().get(0).getState().getTerminated(); - return (terminated != null); - } - return false; - } - - private Pod getPod(OpenShiftClient client, String namespace) { - try { - Pod migrationPod = null; - String requestId = migrationCongigMap.getRequestId(client, namespace); - List pods = client.pods().inNamespace(namespace).withLabel(MIGRATION_POD_LABEL).list().getItems(); - for (Pod pod : pods) { - String requestIdAnnotaion = pod.getMetadata().getAnnotations().get(REQUEST_ID_ANNOTATION); - if (requestId.equals(requestIdAnnotaion)) { - migrationPod = pod; - break; - } - } - return migrationPod; - } catch (MultiTenantMigrationException e) { - LOG.debug("Migration ConfigMap does not exist: {}", e.getMessage()); - return null; - } catch (Exception e) { - LOG.error("Exception occured during workspaces migration to multi-tenant Che server: {}", e); - return null; - } - } - -} diff --git a/src/main/java/io/fabric8/che/starter/multi/tenant/MultiTenantToggle.java b/src/main/java/io/fabric8/che/starter/multi/tenant/MultiTenantToggle.java deleted file mode 100644 index dee8af1..0000000 --- a/src/main/java/io/fabric8/che/starter/multi/tenant/MultiTenantToggle.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.multi.tenant; - -import java.io.IOException; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import com.fasterxml.jackson.core.JsonProcessingException; - -import io.fabric8.che.starter.client.keycloak.KeycloakTokenParser; -import no.finn.unleash.DefaultUnleash; -import no.finn.unleash.Unleash; -import no.finn.unleash.UnleashContext; -import no.finn.unleash.util.UnleashConfig; - -@Component -public class MultiTenantToggle { - private static final Logger LOG = LoggerFactory.getLogger(MultiTenantToggle.class); - - private static final String APP_NAME = "che-starter"; - private static final String FEATURE_NAME = "deploy.che-multi-tenant"; - - @Value("${HOSTNAME:che-starter-host}") - private String hostname; - - @Value("${TOGGLE_URL:http://f8toggles/api}") - private String unleashAPI; - - @Autowired - KeycloakTokenParser keycloakTokenParser; - - private Unleash unleash; - - @PostConstruct - public void initUnleash() { - UnleashConfig config = UnleashConfig.builder() - .appName(APP_NAME) - .instanceId(hostname) - .unleashAPI(unleashAPI) - .build(); - - this.unleash = new DefaultUnleash(config); - } - - public boolean isMultiTenant(final String keycloakToken) { - if (StringUtils.isBlank(keycloakToken)) { - return false; - } - try { - UnleashContext context = getContext(keycloakToken); - return unleash.isEnabled(FEATURE_NAME, context); - } catch (Throwable e) { - LOG.error("Unable to get UnleashContext from the Keycloak token", e); - return false; - } - } - - private UnleashContext getContext(final String keycloakToken) throws JsonProcessingException, IOException { - String identityId = keycloakTokenParser.getIdentityId(keycloakToken); - String sessionState = keycloakTokenParser.getSessionState(keycloakToken); - LOG.info("Identity ID: {}", identityId); - LOG.info("Session State: {}", sessionState); - return UnleashContext.builder().userId(identityId).sessionId(sessionState).build(); - } - -} diff --git a/src/main/java/io/fabric8/che/starter/multi/tenant/TenantUpdater.java b/src/main/java/io/fabric8/che/starter/multi/tenant/TenantUpdater.java deleted file mode 100644 index ea4f71f..0000000 --- a/src/main/java/io/fabric8/che/starter/multi/tenant/TenantUpdater.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.multi.tenant; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; - -import io.fabric8.che.starter.client.keycloak.KeycloakRestTemplate; - -@Component -public class TenantUpdater { - private static final Logger LOG = LoggerFactory.getLogger(TenantUpdater.class); - - @Value("${UPDATE_TENANT_ENDPOINT:https://api.openshift.io/api/user/services}") - private String updateTenantEndpoint; - - @Async - public void update(final String keycloakToken) { - RestTemplate template = new KeycloakRestTemplate(keycloakToken); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - template.setRequestFactory(requestFactory); - ResponseEntity response = template.exchange(updateTenantEndpoint, HttpMethod.PATCH, null, String.class); - LOG.info("User tenant has been updated. Status code {}", response.getStatusCode()); - } - -} diff --git a/src/main/java/io/fabric8/che/starter/openshift/CheDeploymentConfig.java b/src/main/java/io/fabric8/che/starter/openshift/CheDeploymentConfig.java deleted file mode 100644 index a4193a2..0000000 --- a/src/main/java/io/fabric8/che/starter/openshift/CheDeploymentConfig.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.openshift; - -import java.util.List; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.fabric8.che.starter.exception.RouteNotFoundException; -import io.fabric8.openshift.api.model.DeploymentCondition; -import io.fabric8.openshift.api.model.DeploymentConfig; -import io.fabric8.openshift.api.model.DoneableDeploymentConfig; -import io.fabric8.openshift.client.OpenShiftClient; -import io.fabric8.openshift.client.dsl.ClientDeployableScalableResource; - -@Component -public final class CheDeploymentConfig { - - @Autowired - private CheServerRouteChecker cheServerRouteChecker; - - @Value("${che.openshift.deploymentconfig}") - private String deploymentConfigName; - - @Value("${che.openshift.start.timeout}") - private String startTimeout; - - public void deployCheIfSuspended(OpenShiftClient client, String namespace) throws RouteNotFoundException { - final ClientDeployableScalableResource deploymentConfig = getDeploymentConfig(client, namespace); - if (!isDeploymentAvailable(client, namespace)) { - deploymentConfig.scale(1, false); - waitUntilDeploymentConfigIsAvailable(client, namespace); - cheServerRouteChecker.waitUntilRouteIsAccessible(client, namespace, null); - waitHAProxyConfigChange(); - } - } - - public boolean deploymentExists(OpenShiftClient client, String namespace) { - DeploymentConfig dc = getDeploymentConfig(client, namespace).get(); - return (dc != null); - } - - public boolean isDeploymentAvailable(OpenShiftClient client, String namespace) { - DeploymentConfig deploymentConfig = getDeploymentConfig(client, namespace).get(); - if (deploymentConfig == null) { - return false; - } - List conditions = deploymentConfig.getStatus().getConditions(); - if (!conditions.isEmpty()) { - for (DeploymentCondition condition : conditions) { - if (condition.getType().equals("Available") && condition.getStatus().equals("True")) { - return true; - } - } - } - return false; - } - - private ClientDeployableScalableResource getDeploymentConfig( - OpenShiftClient client, String namespace) { - return client.deploymentConfigs().inNamespace(namespace).withName(deploymentConfigName); - } - - private void waitUntilDeploymentConfigIsAvailable(final OpenShiftClient client, String namespace) { - final BlockingQueue queue = new ArrayBlockingQueue(1); - - final Runnable readinessPoller = new Runnable() { - public void run() { - try { - if (isDeploymentAvailable(client, namespace)) { - queue.put(true); - return; - } else { - queue.put(false); - return; - } - } catch (Throwable t) { - try { - if (queue.isEmpty()) { - queue.put(false); - } - return; - } catch (InterruptedException e) { - } - } - } - }; - - ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - ScheduledFuture poller = executor.scheduleWithFixedDelay(readinessPoller, 0, 500, TimeUnit.MILLISECONDS); - executor.schedule(new Runnable() { - - @Override - public void run() { - poller.cancel(true); - } - }, Integer.valueOf(startTimeout), TimeUnit.MILLISECONDS); - - try { - while (!waitUntilReady(queue)) { - } - } finally { - if (!poller.isDone()) { - poller.cancel(true); - } - executor.shutdown(); - } - } - - private boolean waitUntilReady(BlockingQueue queue) { - try { - Object obj = queue.poll(2, TimeUnit.SECONDS); - if (obj == null) { - return true; - } - if (obj instanceof Boolean) { - return (Boolean) obj; - } - return false; - } catch (InterruptedException ex) { - return true; - } - } - - /** - * 503 Service Unavailable is returned when che-server is idled and - * che-starter performs request against it. This might be coupled with the - * fact that HAProxy configuration needs to be changed and reloaded on - * OpenShift, which may take some time. This method is a hack - waiting 60 - * seconds after che-server deployment is available before continuing - * request execution - * - * @see issue - * @see demo of the problem - */ - private void waitHAProxyConfigChange() { - try { - TimeUnit.SECONDS.sleep(60); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } -} diff --git a/src/main/java/io/fabric8/che/starter/openshift/CheServerRoute.java b/src/main/java/io/fabric8/che/starter/openshift/CheServerRoute.java deleted file mode 100644 index 7962635..0000000 --- a/src/main/java/io/fabric8/che/starter/openshift/CheServerRoute.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.openshift; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.fabric8.che.starter.exception.RouteNotFoundException; -import io.fabric8.openshift.api.model.Route; -import io.fabric8.openshift.api.model.TLSConfig; -import io.fabric8.openshift.client.OpenShiftClient; - -@Component -public final class CheServerRoute { - private static final Logger LOG = LoggerFactory.getLogger(CheServerRoute.class); - private final String HTTP = "http"; - private final String HTTPS = "https"; - - @Value("${che.openshift.route}") - private String cheRoute; - - @Value("${che-host.openshift.route}") - private String cheHostRoute; - - public String getUrl(final OpenShiftClient client, final String namespace) throws RouteNotFoundException { - Route route = getRouteByName(client, namespace, cheRoute); - if (route == null) { - LOG.warn("Route '" + cheRoute + "' not found. Trying to get '" + cheHostRoute + "' route"); - route = getRouteByName(client, namespace, cheHostRoute); - } - if (route != null) { - String host = route.getSpec().getHost(); - String protocol = getProtocol(route); - LOG.info("Host '{}' has been found", host); - LOG.info("Route protocol '{}'", protocol); - return protocol + "://" + host; - } - throw new RouteNotFoundException( - "Routes '" + cheRoute + "'/'" + cheHostRoute + "' not found in '" + namespace + "' namespace"); - } - - private Route getRouteByName(final OpenShiftClient client, final String namespace, final String routeName) { - return client.routes().inNamespace(namespace).withName(routeName).get(); - } - - private String getProtocol(final Route route) { - TLSConfig tls = route.getSpec().getTls(); - return (tls != null) ? HTTPS : HTTP; - } - -} diff --git a/src/main/java/io/fabric8/che/starter/openshift/CheServerRouteChecker.java b/src/main/java/io/fabric8/che/starter/openshift/CheServerRouteChecker.java deleted file mode 100644 index 63dfb7e..0000000 --- a/src/main/java/io/fabric8/che/starter/openshift/CheServerRouteChecker.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.openshift; - -import java.net.HttpURLConnection; -import java.net.URL; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.fabric8.che.starter.client.CheRestEndpoints; -import io.fabric8.che.starter.exception.RouteNotFoundException; -import io.fabric8.openshift.client.OpenShiftClient; - -@Component -public class CheServerRouteChecker { - private static final Logger LOG = LoggerFactory.getLogger(CheServerRouteChecker.class); - - @Autowired - private CheServerRoute route; - - @Value("${che.openshift.start.timeout}") - private String startTimeout; - - /** - * @see The endpoints value always be delayed - * - * @param client - * @param namespace - * @throws RouteNotFoundException - */ - public void waitUntilRouteIsAccessible(final OpenShiftClient client, final String namespace, final String keycloakToken) throws RouteNotFoundException { - long start = System.currentTimeMillis(); - long end = start + Long.valueOf(startTimeout); - while (System.currentTimeMillis() < end) { - if (isRouteAccessible(client, namespace, keycloakToken)) { - break; - } - } - } - - public boolean isRouteAccessible(final OpenShiftClient client, final String namespace, final String keycloakToken) { - try { - String routeURL = route.getUrl(client, namespace); - String listWorkspacesURL = CheRestEndpoints.LIST_WORKSPACES.generateUrl(routeURL); - URL url = new URL(listWorkspacesURL); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - if (StringUtils.isNotBlank(keycloakToken)) { - connection.setRequestProperty("Authorization", keycloakToken); - } - int statusCode = connection.getResponseCode(); - boolean isRouteAccessible = isValid(statusCode); - LOG.info("Che server endpoint '{}' is accessible: {}", listWorkspacesURL, isRouteAccessible); - return isRouteAccessible; - } catch (Exception e) { - return false; - } - } - - private boolean isValid(int statusCode) { - return (200 == statusCode || 403 == statusCode || 302 == statusCode); - } - -} diff --git a/src/main/java/io/fabric8/che/starter/openshift/OpenShiftClientWrapper.java b/src/main/java/io/fabric8/che/starter/openshift/OpenShiftClientWrapper.java deleted file mode 100644 index 5d2cce5..0000000 --- a/src/main/java/io/fabric8/che/starter/openshift/OpenShiftClientWrapper.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.openshift; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.fabric8.che.starter.exception.RouteNotFoundException; -import io.fabric8.che.starter.multi.tenant.MultiTenantToggle; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.ConfigBuilder; -import io.fabric8.openshift.client.DefaultOpenShiftClient; -import io.fabric8.openshift.client.OpenShiftClient; - -@Component -public class OpenShiftClientWrapper { - private static final Logger LOG = LoggerFactory.getLogger(OpenShiftClientWrapper.class); - - @Autowired - private CheServerRoute route; - - @Autowired - private CheDeploymentConfig dc; - - @Autowired - private MultiTenantToggle toggle; - - @Value("${KUBERNETES_CERTS_CA_FILE:#{null}}") - private String caCertFile; - - @Value("${FABRIC8_PLATFORM_DEV_MODE:false}") - private boolean fabric8PlatformDevMode; - - @Value("${MULTI_TENANT_CHE_SERVER_URL:https://che.prod-preview.openshift.io}") - private String multiTenantCheServerURL; - - /** - * Gets OpenShift client. When using, you are responsible for closing it. - * - * @param masterUrl URL of OpenShift master - * @param username user name of OpenShift user - * @param password user's password - * @return OpenShift client - */ - public OpenShiftClient get(String masterUrl, String username, String password) { - Config config = new ConfigBuilder().withMasterUrl(masterUrl).withUsername(username).withPassword(password).build(); - return new DefaultOpenShiftClient(config); - } - - /** - * Gets OpenShift client. When using, you are responsible for closing it. - * @param masterUrl URL of OpenShift master - * @param token authorization token - * @return OpenShift client - */ - public OpenShiftClient get(String masterUrl, String token) { - if (fabric8PlatformDevMode) { - LOG.info("Using default OpenShift Client for 'fabric8-platform' deployment on minishift"); - return new DefaultOpenShiftClient(); - } - - LOG.info("Certificate file: {}", caCertFile); - Config config = (StringUtils.isBlank(caCertFile)) - ? new ConfigBuilder().withMasterUrl(masterUrl).withOauthToken(token).build() - : new ConfigBuilder().withMasterUrl(masterUrl).withOauthToken(token).withCaCertFile(caCertFile).build(); - return new DefaultOpenShiftClient(config); - } - - /** - * Gets URL of Che server running in user's namespace on OpenShift. - * - * @param masterUrl URL of OpenShift master - * @param namespace user's namespace - * @param osoToken authorization token - * @return URL of Che server - * @throws RouteNotFoundException - */ - public String getCheServerUrl(String masterUrl, String namespace, String osoToken, String keycloakToken) throws RouteNotFoundException { - if (toggle.isMultiTenant(keycloakToken)) { - return multiTenantCheServerURL; - } - try (OpenShiftClient openShiftClient = this.get(masterUrl, osoToken)) { - dc.deployCheIfSuspended(openShiftClient, namespace); - String routeURL = route.getUrl(openShiftClient, namespace); - LOG.info("Che server route URL {}", routeURL); - return routeURL; - } - } - -} diff --git a/src/main/java/io/fabric8/che/starter/template/CheServerTemplate.java b/src/main/java/io/fabric8/che/starter/template/CheServerTemplate.java deleted file mode 100644 index 86d27ea..0000000 --- a/src/main/java/io/fabric8/che/starter/template/CheServerTemplate.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.template; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; - -import javax.annotation.PostConstruct; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import io.fabric8.che.starter.util.Reader; - -@Component -public class CheServerTemplate { - private static final Logger LOG = LoggerFactory.getLogger(CheServerTemplate.class); - - private String template; - - @PostConstruct - public void init() throws IOException { - template = Reader.read(new URL(templateUrl)); - LOG.info("Che Server Template initialized"); - } - - @Value("${che.server.template.url}") - private String templateUrl; - - public String get() throws MalformedURLException, IOException { - return template; - } -} diff --git a/src/main/java/io/fabric8/che/starter/util/Reader.java b/src/main/java/io/fabric8/che/starter/util/Reader.java deleted file mode 100644 index 59292c7..0000000 --- a/src/main/java/io/fabric8/che/starter/util/Reader.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.Scanner; -import java.util.stream.Collectors; - -public final class Reader { - - private Reader() { - } - - public static String read(InputStream input) throws IOException { - try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) { - return buffer.lines().collect(Collectors.joining("\n")); - } - } - - public static String read(URL url) throws IOException { - try (Scanner skanner = new Scanner(url.openStream(), "UTF-8")) { - return skanner.useDelimiter("\\A").next(); - } - } - -} diff --git a/src/main/resources/application-local.properties b/src/main/resources/application-local.properties index 6afb17a..c1610d6 100644 --- a/src/main/resources/application-local.properties +++ b/src/main/resources/application-local.properties @@ -13,4 +13,3 @@ include.error.stack.trace = true logging.level.org.springframework.web = INFO server.port = 10000 -che.server.url = http://che.192.168.42.20.xip.io diff --git a/src/main/resources/application-test.properties b/src/main/resources/application-test.properties index 679f5f0..81ff0c7 100644 --- a/src/main/resources/application-test.properties +++ b/src/main/resources/application-test.properties @@ -10,5 +10,4 @@ # http://www.eclipse.org/legal/epl-v10.html # #L% ### -che.server.url=https://che-ibuziuk-che.d800.free-int.openshiftapps.com -che.server.template.url=http://central.maven.org/maven2/io/fabric8/tenant/packages/fabric8-tenant-che/2.0.35/fabric8-tenant-che-2.0.35-openshift.json +MULTI_TENANT_CHE_SERVER_URL=https://che-ibuziuk-che.1b7d.free-stg.openshiftapps.com diff --git a/src/test/java/io/fabric8/che/starter/client/CheRestEndpointTest.java b/src/test/java/io/fabric8/che/starter/client/CheRestEndpointTest.java index d3306a7..09a5dc5 100644 --- a/src/test/java/io/fabric8/che/starter/client/CheRestEndpointTest.java +++ b/src/test/java/io/fabric8/che/starter/client/CheRestEndpointTest.java @@ -19,17 +19,17 @@ import static org.junit.Assert.assertEquals; public class CheRestEndpointTest extends TestConfig { - private static final String WORKSPACE_ID = "quwieuqoweuqo"; + private static final String WORKSPACE_ID = "test_workspace_id"; - @Value("${che.server.url}") - String cheServerUrl; + @Value("${MULTI_TENANT_CHE_SERVER_URL}") + private String multiTenantCheServerURL; @Test public void generateUrlsFromEndpoints() { - String createWorkspceUrl = CheRestEndpoints.CREATE_WORKSPACE.generateUrl(cheServerUrl); - assertEquals(createWorkspceUrl, cheServerUrl + "/api/workspace"); - String deleteWorkspaceUrl = CheRestEndpoints.DELETE_WORKSPACE.generateUrl(cheServerUrl, WORKSPACE_ID); - assertEquals(deleteWorkspaceUrl, cheServerUrl + "/api/workspace/" + WORKSPACE_ID); + String createWorkspceUrl = CheRestEndpoints.CREATE_WORKSPACE.generateUrl(multiTenantCheServerURL); + assertEquals(createWorkspceUrl, multiTenantCheServerURL + "/api/workspace"); + String deleteWorkspaceUrl = CheRestEndpoints.DELETE_WORKSPACE.generateUrl(multiTenantCheServerURL, WORKSPACE_ID); + assertEquals(deleteWorkspaceUrl, multiTenantCheServerURL + "/api/workspace/" + WORKSPACE_ID); } } diff --git a/src/test/java/io/fabric8/che/starter/client/StackClientTest.java b/src/test/java/io/fabric8/che/starter/client/StackClientTest.java index c8b7efd..cc16ba2 100644 --- a/src/test/java/io/fabric8/che/starter/client/StackClientTest.java +++ b/src/test/java/io/fabric8/che/starter/client/StackClientTest.java @@ -22,7 +22,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import io.fabric8.che.starter.TestConfig; import io.fabric8.che.starter.exception.StackNotFoundException; @@ -39,22 +38,19 @@ public class StackClientTest extends TestConfig { private static final String NON_EXISTING_STACK_ID = "non-existing-stack-id"; private static final String KEYCLOAK_TOKEN = null; - @Value("${che.server.url}") - String cheServerUrl; - @Autowired private StackClient client; @Test public void listStacks() { - List stacks = client.listStacks(cheServerUrl, KEYCLOAK_TOKEN); + List stacks = client.listStacks(KEYCLOAK_TOKEN); LOG.info("Number of stacks: {}", stacks.size()); assertTrue(!stacks.isEmpty()); } @Test public void vertxStackExists() { - List stacks = client.listStacks(cheServerUrl, KEYCLOAK_TOKEN); + List stacks = client.listStacks(KEYCLOAK_TOKEN); Stack stack = stacks.stream().filter(s -> VERTX_STACK_ID.equals(s.getId())).findFirst().get(); assertNotNull(VERTX_STACK_ID + " not Found", stack); LOG.info("vertx stack is found: {}", stack.getId()); @@ -63,31 +59,31 @@ public void vertxStackExists() { @Test public void getVertxStack() throws StackNotFoundException { - Stack vertx = client.getStack(cheServerUrl, VERTX_STACK_ID, KEYCLOAK_TOKEN); + Stack vertx = client.getStack(VERTX_STACK_ID, KEYCLOAK_TOKEN); LOG.info("'vert.x' stack is found: {}", vertx); } @Test public void getJavaCentosStack() throws StackNotFoundException { - Stack javaCentos = client.getStack(cheServerUrl, JAVA_CENTOS_STACK_ID, KEYCLOAK_TOKEN); + Stack javaCentos = client.getStack(JAVA_CENTOS_STACK_ID, KEYCLOAK_TOKEN); LOG.info("'java-centos' stack is found: {}", javaCentos); } @Test public void getSpringBootStack() throws StackNotFoundException { - Stack springBoot = client.getStack(cheServerUrl, SPRING_BOOT_STACK_ID, KEYCLOAK_TOKEN); + Stack springBoot = client.getStack(SPRING_BOOT_STACK_ID, KEYCLOAK_TOKEN); LOG.info("'spring-boot' stack is found: {}", springBoot); } @Test public void getWildflySwarmStack() throws StackNotFoundException { - Stack wildflySwarm = client.getStack(cheServerUrl, WILDFLY_SWARM_STACK_ID, KEYCLOAK_TOKEN); + Stack wildflySwarm = client.getStack(WILDFLY_SWARM_STACK_ID, KEYCLOAK_TOKEN); LOG.info("'wildfly-swarm' stack is found: {}", wildflySwarm); } @Test public void getNodeJsStack() throws StackNotFoundException { - Stack nodeJs = client.getStack(cheServerUrl, NODE_JS_STACK_ID, KEYCLOAK_TOKEN); + Stack nodeJs = client.getStack(NODE_JS_STACK_ID, KEYCLOAK_TOKEN); LOG.info("'nodejs4' stack is found: {}", nodeJs); } @@ -105,7 +101,7 @@ public void getProjectTypeForNonExistingStack() { @Test(expected = StackNotFoundException.class) public void getNonExistingStackImage() throws StackNotFoundException { - client.getStack(cheServerUrl, NON_EXISTING_STACK_ID, KEYCLOAK_TOKEN); + client.getStack(NON_EXISTING_STACK_ID, KEYCLOAK_TOKEN); } } diff --git a/src/test/java/io/fabric8/che/starter/client/WorkspaceClientTest.java b/src/test/java/io/fabric8/che/starter/client/WorkspaceClientTest.java index 2d2f993..a07ce44 100644 --- a/src/test/java/io/fabric8/che/starter/client/WorkspaceClientTest.java +++ b/src/test/java/io/fabric8/che/starter/client/WorkspaceClientTest.java @@ -22,7 +22,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import io.fabric8.che.starter.TestConfig; import io.fabric8.che.starter.exception.StackNotFoundException; @@ -36,19 +35,13 @@ public class WorkspaceClientTest extends TestConfig { private static final String STACK_ID = "java-centos"; private static final String DESCRIPTION = GITHUB_REPO + "#" + BRANCH + "#" + "WI1345"; private static final String KEYCLOAK_TOKEN = null; - private static final String MASTER_URL = ""; - private static final String NAMESPACE = ""; - private static final String OPENSHIFT_TOKEN = null; - - @Value("${che.server.url}") - String cheServerURL; @Autowired private WorkspaceClient client; @Test public void listWorkspaces() { - List workspaces = this.client.listWorkspaces(cheServerURL, KEYCLOAK_TOKEN); + List workspaces = this.client.listWorkspaces(KEYCLOAK_TOKEN); LOG.info("Number of workspaces: {}", workspaces.size()); workspaces.forEach(w -> LOG.info("workspace ID: {}", w.getId())); } @@ -56,25 +49,25 @@ public void listWorkspaces() { @Test @Ignore("Ignored due to issue with running a workspace on remote OS test instance") public void createAndDeleteWorkspace() throws IOException, StackNotFoundException, WorkspaceNotFound, URISyntaxException { - Workspace workspace = client.createWorkspace(cheServerURL, null, STACK_ID, GITHUB_REPO, BRANCH, DESCRIPTION); - client.waitUntilWorkspaceIsRunning(cheServerURL, workspace, KEYCLOAK_TOKEN); + Workspace workspace = client.createWorkspace(KEYCLOAK_TOKEN, STACK_ID, GITHUB_REPO, BRANCH, DESCRIPTION); + client.waitUntilWorkspaceIsRunning(workspace, KEYCLOAK_TOKEN); - client.stopWorkspace(cheServerURL, workspace, KEYCLOAK_TOKEN); - client.waitUntilWorkspaceIsStopped(MASTER_URL, NAMESPACE, OPENSHIFT_TOKEN, cheServerURL, workspace, KEYCLOAK_TOKEN); + client.stopWorkspace(workspace, KEYCLOAK_TOKEN); + client.waitUntilWorkspaceIsStopped(workspace, KEYCLOAK_TOKEN); - client.deleteWorkspace(cheServerURL, workspace.getId(), KEYCLOAK_TOKEN); + client.deleteWorkspace(workspace.getId(), KEYCLOAK_TOKEN); } @Test public void stopWorskpace() { - List workspaces = client.listWorkspaces(cheServerURL, KEYCLOAK_TOKEN); + List workspaces = client.listWorkspaces(KEYCLOAK_TOKEN); if (!workspaces.isEmpty()) { List runningWorkspaces = workspaces.stream().filter(w -> w.getStatus().equals("RUNNING")) .collect(Collectors.toList()); if (!runningWorkspaces.isEmpty()) { - client.stopWorkspace(cheServerURL, runningWorkspaces.get(0), KEYCLOAK_TOKEN); - client.waitUntilWorkspaceIsStopped(MASTER_URL, NAMESPACE, OPENSHIFT_TOKEN, cheServerURL, runningWorkspaces.get(0), KEYCLOAK_TOKEN); + client.stopWorkspace(runningWorkspaces.get(0), KEYCLOAK_TOKEN); + client.waitUntilWorkspaceIsStopped(runningWorkspaces.get(0), KEYCLOAK_TOKEN); } } } diff --git a/src/test/java/io/fabric8/che/starter/client/WorkspacePreferencesClientTest.java b/src/test/java/io/fabric8/che/starter/client/WorkspacePreferencesClientTest.java index 92477f6..3735c8d 100644 --- a/src/test/java/io/fabric8/che/starter/client/WorkspacePreferencesClientTest.java +++ b/src/test/java/io/fabric8/che/starter/client/WorkspacePreferencesClientTest.java @@ -20,7 +20,6 @@ import org.apache.commons.lang3.RandomStringUtils; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import io.fabric8.che.starter.TestConfig; import io.fabric8.che.starter.model.WorkspacePreferences; @@ -35,9 +34,6 @@ public class WorkspacePreferencesClientTest extends TestConfig { private String committerEmail; private GitHubUserInfo gitHubUserInfo; - @Value("${che.server.url}") - String cheServerUrl; - @Autowired WorkspacePreferencesClient client; @@ -53,7 +49,7 @@ public void init() { @Test public void setCommitterInfo() throws Exception { - client.setCommitterInfo(cheServerUrl, KEYCLOAK_TOKEN, getTestPreferences()); + client.setCommitterInfo(KEYCLOAK_TOKEN, getTestPreferences()); checkCommitterInfoSetCorrectly(); } @@ -70,7 +66,7 @@ public void getCommitterInfoWhenNameIsBlank() { } private void checkCommitterInfoSetCorrectly() { - WorkspacePreferences committerInfo = client.getCommitterInfo(cheServerUrl, KEYCLOAK_TOKEN); + WorkspacePreferences committerInfo = client.getCommitterInfo(KEYCLOAK_TOKEN); assertNotNull(committerInfo); assertEquals(committerInfo.getCommiterName(), committerName); diff --git a/src/test/java/io/fabric8/che/starter/client/github/GitHubTokenClientTest.java b/src/test/java/io/fabric8/che/starter/client/github/GitHubTokenClientTest.java index 5be3989..c08aeeb 100644 --- a/src/test/java/io/fabric8/che/starter/client/github/GitHubTokenClientTest.java +++ b/src/test/java/io/fabric8/che/starter/client/github/GitHubTokenClientTest.java @@ -19,10 +19,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import io.fabric8.che.starter.TestConfig; -import io.fabric8.che.starter.client.github.GitHubClient; import io.fabric8.che.starter.exception.GitHubOAthTokenException; import io.fabric8.che.starter.model.github.GitHubEmail; import io.fabric8.che.starter.model.github.GitHubUserInfo; @@ -32,15 +30,12 @@ public class GitHubTokenClientTest extends TestConfig { private static final String GIT_HUB_TOKEN = "dummy_token"; private static final String KEYCLOAK_TOKEN = null; - @Value("${che.server.url}") - String cheServerURL; - @Autowired private GitHubClient client; @Test public void setGitHubToken() throws GitHubOAthTokenException, IOException { - client.setGitHubOAuthToken(cheServerURL, GIT_HUB_TOKEN, KEYCLOAK_TOKEN); + client.setGitHubOAuthToken(GIT_HUB_TOKEN, KEYCLOAK_TOKEN); } @Ignore("Valid GitHub token must be provided") diff --git a/src/test/java/io/fabric8/che/starter/client/keycloak/KeycloakTest.java b/src/test/java/io/fabric8/che/starter/client/github/GitHubTokenProviderTest.java similarity index 64% rename from src/test/java/io/fabric8/che/starter/client/keycloak/KeycloakTest.java rename to src/test/java/io/fabric8/che/starter/client/github/GitHubTokenProviderTest.java index 4f93aa6..7d594c6 100644 --- a/src/test/java/io/fabric8/che/starter/client/keycloak/KeycloakTest.java +++ b/src/test/java/io/fabric8/che/starter/client/github/GitHubTokenProviderTest.java @@ -10,7 +10,7 @@ * http://www.eclipse.org/legal/epl-v10.html * #L% */ -package io.fabric8.che.starter.client.keycloak; +package io.fabric8.che.starter.client.github; import java.io.IOException; @@ -23,26 +23,21 @@ import com.fasterxml.jackson.core.JsonProcessingException; import io.fabric8.che.starter.TestConfig; +import io.fabric8.che.starter.client.github.GitHubTokenProvider; import io.fabric8.che.starter.exception.KeycloakException; @Ignore("Valid keycloak token must be provided") -public class KeycloakTest extends TestConfig { - private static final Logger LOG = LoggerFactory.getLogger(KeycloakTest.class); +public class GitHubTokenProviderTest extends TestConfig { + private static final Logger LOG = LoggerFactory.getLogger(GitHubTokenProviderTest.class); private static final String KEYCLOAK_TOKEN = "Bearer "; @Autowired - KeycloakClient keycloakClient; + GitHubTokenProvider gitHubTokenProvider; @Test public void getGitHubToken() throws KeycloakException, JsonProcessingException, IOException { - String gitHubToken = keycloakClient.getGitHubToken(KEYCLOAK_TOKEN); + String gitHubToken = gitHubTokenProvider.getGitHubToken(KEYCLOAK_TOKEN); LOG.info("GitHub Token: {}", gitHubToken); } - @Test - public void getOpenShiftToken() throws JsonProcessingException, IOException, KeycloakException { - String openShiftToken = keycloakClient.getOpenShiftToken(KEYCLOAK_TOKEN); - LOG.info("OpenShift Token: {}", openShiftToken); - } - } diff --git a/src/test/java/io/fabric8/che/starter/controller/StackControllerTest.java b/src/test/java/io/fabric8/che/starter/controller/StackControllerTest.java index 1d207c1..88c3d4e 100644 --- a/src/test/java/io/fabric8/che/starter/controller/StackControllerTest.java +++ b/src/test/java/io/fabric8/che/starter/controller/StackControllerTest.java @@ -34,10 +34,10 @@ @RunWith(SpringRunner.class) @AutoConfigureMockMvc @SpringBootTest(properties = { "OPENSHIFT_TOKEN_URL=http://localhost:33333/keycloak/token/openshift", - "GITHUB_TOKEN_URL=http://localhost:33333/keycloak/token/github" }) + "GITHUB_TOKEN_URL=http://localhost:33333/keycloak/token/github", + "MULTI_TENANT_CHE_SERVER_URL=http://localhost:33333"}) public class StackControllerTest extends TestBase { - private static final String STACK_OSO_ENDPOINT = "/stack/oso"; private static final String STACK_ENDPOINT = "/stack"; @Autowired @@ -53,31 +53,6 @@ public static void destroy() throws Exception { VertxServer.getInstance().stopVertxServer(); } - @Test - public void testGetStacksOSO() throws Exception { - mockMvc.perform(get(STACK_OSO_ENDPOINT).header("Authorization", OPENSHIFT_TOKEN) - .param("masterUrl", VERTX_SERVER).param("namespace", NAMESPACE)).andExpect(status().is2xxSuccessful()) - .andExpect(jsonPath("$[1].id", is("java-default"))).andExpect(jsonPath("$[0].id", is("vert.x"))); - } - - @Test - public void testGetStacksOSOWithWrongToken() throws Exception { - mockMvc.perform(get(STACK_OSO_ENDPOINT).header("Authorization", "badtoken").param("masterUrl", VERTX_SERVER) - .param("namespace", NAMESPACE)).andExpect(status().is(401)); - } - - @Test - public void testGetStacksOSOWithWrongNamespace() throws Exception { - mockMvc.perform(get(STACK_OSO_ENDPOINT).header("Authorization", OPENSHIFT_TOKEN) - .param("masterUrl", VERTX_SERVER).param("namespace", "noexisting")).andExpect(status().is(401)); - } - - @Test - public void testGetStacksOSOWithWrongMasterURL() throws Exception { - mockMvc.perform(get(STACK_OSO_ENDPOINT).header("Authorization", OPENSHIFT_TOKEN) - .param("masterUrl", "http://i.do.not.exist").param("namespace", NAMESPACE)).andExpect(status().is(401)); - } - @Test public void testGetStacks() throws Exception { mockMvc.perform(get(STACK_ENDPOINT).header("Authorization", KEYCLOAK_TOKEN).param("masterUrl", VERTX_SERVER) @@ -91,15 +66,23 @@ public void testGetStacksWithWrongToken() throws Exception { .param("namespace", NAMESPACE)).andExpect(status().is(400)); } + /* + * Deprecated - namespace is not required anymore for multi-tenant che server + */ + @Deprecated @Test public void testGetStacksWithWrongNamespace() throws Exception { mockMvc.perform(get(STACK_ENDPOINT).header("Authorization", KEYCLOAK_TOKEN).param("masterUrl", VERTX_SERVER) - .param("namespace", "noexisting")).andExpect(status().is(401)); + .param("namespace", "noexisting")).andExpect(status().is(200)); } + /* + * Deprecated - masterURL is not required anymore for multi-tenant che server + */ + @Deprecated @Test public void testGetStacksWithWrongMasterURL() throws Exception { mockMvc.perform(get(STACK_ENDPOINT).header("Authorization", KEYCLOAK_TOKEN) - .param("masterUrl", "http://i.do.not.exist").param("namespace", NAMESPACE)).andExpect(status().is(401)); + .param("masterUrl", "http://i.do.not.exist").param("namespace", NAMESPACE)).andExpect(status().is(200)); } } diff --git a/src/test/java/io/fabric8/che/starter/controller/WorkspaceControllerTest.java b/src/test/java/io/fabric8/che/starter/controller/WorkspaceControllerTest.java index 189253f..3c7aa1a 100644 --- a/src/test/java/io/fabric8/che/starter/controller/WorkspaceControllerTest.java +++ b/src/test/java/io/fabric8/che/starter/controller/WorkspaceControllerTest.java @@ -37,11 +37,11 @@ @AutoConfigureMockMvc @SpringBootTest(properties = { "OPENSHIFT_TOKEN_URL=http://localhost:33333/keycloak/token/openshift", "GITHUB_TOKEN_URL=http://localhost:33333/keycloak/token/github", - "GITHUB_USER_URL=http://localhost:33333/github/user"}) + "GITHUB_USER_URL=http://localhost:33333/github/user", + "MULTI_TENANT_CHE_SERVER_URL=http://localhost:33333"}) public class WorkspaceControllerTest extends TestBase { private static final String WORKSPACE_ENDPOINT = "/workspace"; - private static final String WORKSPACE_OSO_ENDPOINT = "/workspace/oso"; @Autowired private MockMvc mockMvc; @@ -63,48 +63,30 @@ public void getWorkspacesTest() throws Exception { .andExpect(status().is2xxSuccessful()).andExpect(jsonPath("$[0].status", is("RUNNING"))); } - @Test - public void getWorkspacesOSOTest() throws Exception { - mockMvc.perform(get(WORKSPACE_OSO_ENDPOINT).header("Authorization", OPENSHIFT_TOKEN) - .param("masterUrl", VERTX_SERVER).param("namespace", NAMESPACE)) - .andExpect(jsonPath("$[0].id", is("chevertxwsid13"))).andExpect(status().is2xxSuccessful()) - .andExpect(jsonPath("$[0].status", is("RUNNING"))); - } - @Test public void getWorkspaceWithWrongTokenTest() throws Exception { mockMvc.perform(get(WORKSPACE_ENDPOINT).header("Authorization", "wrongkeycloaktoken") .param("masterUrl", VERTX_SERVER).param("namespace", NAMESPACE)).andExpect(status().is(400)); } - @Test - public void getWorkspaceOSOWithWrongTokenTest() throws Exception { - mockMvc.perform(get(WORKSPACE_OSO_ENDPOINT).header("Authorization", "wrongopenshifttoken") - .param("masterUrl", VERTX_SERVER).param("namespace", NAMESPACE)).andExpect(status().is(401)); - } - + /* + * Deprecated - namespace is not required anymore for multi-tenant che server + */ + @Deprecated @Test public void getWorkspacesWithWrongNamespaceTest() throws Exception { mockMvc.perform(get(WORKSPACE_ENDPOINT).header("Authorization", KEYCLOAK_TOKEN).param("masterUrl", VERTX_SERVER) - .param("namespace", "noexisting")).andExpect(status().is(401)); - } - - @Test - public void getWorkspacesOSOWithWrongNamespaceTest() throws Exception { - mockMvc.perform(get(WORKSPACE_OSO_ENDPOINT).header("Authorization", OPENSHIFT_TOKEN) - .param("masterUrl", VERTX_SERVER).param("namespace", "noexisting")).andExpect(status().is(401)); + .param("namespace", "noexisting")).andExpect(status().is(200)); } + /* + * Deprecated - masterURL is not required anymore for multi-tenant che server + */ + @Deprecated @Test public void getWorkspacesWithWrongMasterURLTest() throws Exception { mockMvc.perform(get(WORKSPACE_ENDPOINT).header("Authorization", KEYCLOAK_TOKEN) - .param("masterUrl", "http://i.do.not.exist").param("namespace", NAMESPACE)).andExpect(status().is(401)); - } - - @Test - public void getWorkspacesOSOWithWrongMasterURLTest() throws Exception { - mockMvc.perform(get(WORKSPACE_OSO_ENDPOINT).header("Authorization", OPENSHIFT_TOKEN) - .param("masterUrl", "http://i.do.not.exist").param("namespace", NAMESPACE)).andExpect(status().is(401)); + .param("masterUrl", "http://i.do.not.exist").param("namespace", NAMESPACE)).andExpect(status().is(200)); } @Test @@ -115,14 +97,6 @@ public void createWorkspaceTest() throws Exception { .andExpect(status().is2xxSuccessful()).andExpect(jsonPath("$.config.name", is(WORKSPACE_NAME))); } - @Test - public void createWorkspaceOSOTest() throws Exception { - mockMvc.perform(post(WORKSPACE_OSO_ENDPOINT).header("Authorization", OPENSHIFT_TOKEN) - .header("Content-Type", "application/json").param("masterUrl", VERTX_SERVER) - .param("namespace", NAMESPACE).content(getCreateWorkspaceRequestBody(initWorkspaceCreateParams()))) - .andExpect(status().is2xxSuccessful()).andExpect(jsonPath("$.config.name", is(WORKSPACE_NAME))); - } - @Test public void createWorkspaceWithWrongTokenTest() throws Exception { mockMvc.perform(post(WORKSPACE_ENDPOINT).header("Authorization", "wrongkeycloakttoken") @@ -131,44 +105,28 @@ public void createWorkspaceWithWrongTokenTest() throws Exception { .andExpect(status().is(400)); } - @Test - public void createWorkspaceOSOWithWrongTokenTest() throws Exception { - mockMvc.perform(post(WORKSPACE_OSO_ENDPOINT).header("Authorization", "wrongopenshifttoken") - .header("Content-Type", "application/json").param("masterUrl", VERTX_SERVER) - .param("namespace", NAMESPACE).content(getCreateWorkspaceRequestBody(initWorkspaceCreateParams()))) - .andExpect(status().is(401)); - } - + /* + * Deprecated - namespace is not required anymore for multi-tenant che server + */ + @Deprecated @Test public void createWorkspaceWithWrongNamespaceTest() throws Exception { mockMvc.perform(post(WORKSPACE_ENDPOINT).header("Authorization", KEYCLOAK_TOKEN) .header("Content-Type", "application/json").param("masterUrl", VERTX_SERVER) .param("namespace", "idonotexists").content(getCreateWorkspaceRequestBody(initWorkspaceCreateParams()))) - .andExpect(status().is(401)); - } - - @Test - public void createWorkspaceOSOWithWrongNamespaceTest() throws Exception { - mockMvc.perform(post(WORKSPACE_OSO_ENDPOINT).header("Authorization", OPENSHIFT_TOKEN) - .header("Content-Type", "application/json").param("masterUrl", VERTX_SERVER) - .param("namespace", "idonotexists").content(getCreateWorkspaceRequestBody(initWorkspaceCreateParams()))) - .andExpect(status().is(401)); + .andExpect(status().is(200)); } + /* + * Deprecated - masterURL is not required anymore for multi-tenant che server + */ + @Deprecated @Test public void createWorkspaceWithWrongMasterURLTest() throws Exception { mockMvc.perform(post(WORKSPACE_ENDPOINT).header("Authorization", KEYCLOAK_TOKEN) .header("Content-Type", "application/json").param("masterUrl", "http://i.do.not.exist") .param("namespace", NAMESPACE).content(getCreateWorkspaceRequestBody(initWorkspaceCreateParams()))) - .andExpect(status().is(401)); - } - - @Test - public void createWorkspaceOSOWithWrongMasterURLTest() throws Exception { - mockMvc.perform(post(WORKSPACE_OSO_ENDPOINT).header("Authorization", OPENSHIFT_TOKEN) - .header("Content-Type", "application/json").param("masterUrl", "http://i.do.not.exist") - .param("namespace", NAMESPACE).content(getCreateWorkspaceRequestBody(initWorkspaceCreateParams()))) - .andExpect(status().is(401)); + .andExpect(status().is(200)); } @Test @@ -181,16 +139,6 @@ public void createWorkspaceWithWrongRepoParamTest() throws Exception { .andExpect(status().is(400)); } - @Test - public void createWorkspaceOSOWithWrongRepoParamTest() throws Exception { - WorkspaceCreateParams workspaceParams = initWorkspaceCreateParams(); - workspaceParams.setRepo("incorrecturl"); - mockMvc.perform(post(WORKSPACE_OSO_ENDPOINT).header("Authorization", OPENSHIFT_TOKEN) - .header("Content-Type", "application/json").param("masterUrl", VERTX_SERVER) - .param("namespace", NAMESPACE).content(getCreateWorkspaceRequestBody(workspaceParams))) - .andExpect(status().is(400)); - } - @Test public void createWorkspaceWithNonexistingStackParamTest() throws Exception { WorkspaceCreateParams workspaceParams = initWorkspaceCreateParams(); @@ -204,16 +152,4 @@ public void createWorkspaceWithNonexistingStackParamTest() throws Exception { .andExpect(status().is(404)); } - @Test - public void createWorkspaceOSOWithNonexistingStackParamTest() throws Exception { - WorkspaceCreateParams workspaceParams = initWorkspaceCreateParams(); - workspaceParams.setStackId("nada"); - // Need to also modify description, which is ID of a workspace to avoid - // getting already existing WS - workspaceParams.setDescription("https://github.com/mlabuda/vertx-with-che.git#master#WI0"); - mockMvc.perform(post(WORKSPACE_OSO_ENDPOINT).header("Authorization", OPENSHIFT_TOKEN) - .header("Content-Type", "application/json").param("masterUrl", VERTX_SERVER) - .param("namespace", NAMESPACE).content(getCreateWorkspaceRequestBody(workspaceParams))) - .andExpect(status().is(404)); - } } diff --git a/src/test/java/io/fabric8/che/starter/multi/tenant/TenantUpdaterTest.java b/src/test/java/io/fabric8/che/starter/multi/tenant/TenantUpdaterTest.java deleted file mode 100644 index 7798456..0000000 --- a/src/test/java/io/fabric8/che/starter/multi/tenant/TenantUpdaterTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ - -package io.fabric8.che.starter.multi.tenant; - -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import io.fabric8.che.starter.TestConfig; - -@Ignore("Valid keycloak token must be provided") -public class TenantUpdaterTest extends TestConfig { - private static final String KEYCLOAK_TOKEN = "Bearer "; - - @Autowired - private TenantUpdater tenanUpdater; - - @Test - public void updateTenantTest() { - tenanUpdater.update(KEYCLOAK_TOKEN); - } - -} diff --git a/src/test/java/io/fabric8/che/starter/openshift/OpenShiftTest.java b/src/test/java/io/fabric8/che/starter/openshift/OpenShiftTest.java deleted file mode 100644 index 350b249..0000000 --- a/src/test/java/io/fabric8/che/starter/openshift/OpenShiftTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.openshift; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.Resource; - -import io.fabric8.che.starter.TestConfig; -import io.fabric8.che.starter.template.CheServerTemplate; -import io.fabric8.kubernetes.api.model.KubernetesList; -import io.fabric8.kubernetes.api.model.Pod; -import io.fabric8.openshift.api.model.DoneableTemplate; -import io.fabric8.openshift.api.model.Parameter; -import io.fabric8.openshift.api.model.ProjectRequest; -import io.fabric8.openshift.api.model.Route; -import io.fabric8.openshift.api.model.Template; -import io.fabric8.openshift.client.OpenShiftClient; -import io.fabric8.openshift.client.ParameterValue; -import io.fabric8.openshift.client.dsl.ClientTemplateResource; - -@Ignore("Test is run against local minishift cluster and requires additional setup") -public class OpenShiftTest extends TestConfig { - private static final Logger LOG = LoggerFactory.getLogger(OpenShiftTest.class); - private static final String CHE_OPENSHIFT_ENDPOINT = "CHE_OPENSHIFT_ENDPOINT"; - - @Autowired - private CheServerTemplate template; - - @Autowired - private OpenShiftClientWrapper client; - - @Value(value = "classpath:templates/che_server_template.json") - private Resource cheServerTemplate; - - @Value("${che.server.template.url}") - private String templateUrl; - - @Value("${che.openshift.endpoint}") - private String endpoint; - - @Value("${che.openshift.project}") - private String project; - - @Value("${che.openshift.username}") - private String username; - - @Value("${che.openshift.password}") - private String password; - - @Test - public void createCheServer() throws Exception { - OpenShiftClient openShiftClient = null; - try { - openShiftClient = client.get(endpoint, username, password); - - ProjectRequest projectRequest = createTestProject(openShiftClient); - LOG.info("Number of projects: {}", getNumberOfProjects(openShiftClient)); - - LOG.info("Test project has been deleted: {}", deleteTestProject(openShiftClient, projectRequest)); - LOG.info("Number of projects: {}", getNumberOfProjects(openShiftClient)); - - // Controller controller = new Controller(client); - // controller.applyJson(template.get()); - - Template template = loadTemplate(openShiftClient); - - List parameters = template.getParameters(); - LOG.info("Number of template parameters: {}", parameters.size()); - - List pvs = new ArrayList<>(); - for (Parameter parameter : parameters) { - String name = parameter.getName(); - String value = parameter.getValue(); - LOG.info("Template Parameter Name: {}", name); - LOG.info("Template Parameter Value: {}", value); - if (CHE_OPENSHIFT_ENDPOINT.equals(name) && value.isEmpty()) { - value = endpoint; - } - pvs.add(new ParameterValue(name, value)); - } - - KubernetesList list = processTemplate(openShiftClient, pvs); - createResources(openShiftClient, list); - - Pod pod = openShiftClient.pods().inNamespace(project).withName("che-host").get(); - - Route route = openShiftClient.routes().inNamespace(project).withName("che-host").get(); - - LOG.info("Pods: {}", getNumberOfPods(openShiftClient)); - } finally { - if (openShiftClient != null) { - openShiftClient.close(); - } - } - } - - private int getNumberOfProjects(OpenShiftClient client) { - return client.projects().list().getItems().size(); - } - - private int getNumberOfTemplates(OpenShiftClient client) { - return client.templates().inNamespace(project).list().getItems().size(); - } - - private int getNumberOfPods(OpenShiftClient client) { - return client.pods().inNamespace(project).list().getItems().size(); - } - - private ProjectRequest createTestProject(OpenShiftClient client) { - return client.projectrequests().createNew().withNewMetadata().withName("test-project").endMetadata() - .withDescription("Test Project").withDisplayName("Test Project").done(); - } - - private KubernetesList processTemplate(OpenShiftClient client, List parameterValues) - throws IOException { - ClientTemplateResource templateHandle = client.templates() - .load(cheServerTemplate.getInputStream()); - return templateHandle.process(parameterValues.toArray(new ParameterValue[parameterValues.size()])); - } - - private boolean deleteTestProject(OpenShiftClient client, ProjectRequest projectRequest) { - return client.projects().withName(projectRequest.getMetadata().getName()).delete(); - } - - private Template loadTemplate(OpenShiftClient client) throws IOException { - return client.templates().load(cheServerTemplate.getInputStream()).get(); - } - - private KubernetesList createResources(OpenShiftClient client, KubernetesList list) { - return client.lists().inNamespace(project).create(list); - } - -} diff --git a/src/test/java/io/fabric8/che/starter/openshift/RouteTest.java b/src/test/java/io/fabric8/che/starter/openshift/RouteTest.java deleted file mode 100644 index 1fef325..0000000 --- a/src/test/java/io/fabric8/che/starter/openshift/RouteTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.openshift; - -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; - -import io.fabric8.che.starter.TestConfig; -import io.fabric8.che.starter.exception.RouteNotFoundException; -import io.fabric8.openshift.client.OpenShiftClient; - -@Ignore("Test is run against local minishift cluster and requires additional setup") -public class RouteTest extends TestConfig { - - @Autowired - CheServerRoute route; - - @Autowired - OpenShiftClientWrapper client; - - @Value("${che.openshift.username}") - private String username; - - @Value("${che.openshift.password}") - private String password; - - @Value("${che.openshift.endpoint}") - private String endpoint; - - @Value("${che.openshift.namespace}") - private String namespace; - - @Test - public void testRouteURL() throws RouteNotFoundException { - OpenShiftClient openShiftClient = null; - try { - openShiftClient = client.get(endpoint, username, password); - route.getUrl(openShiftClient, namespace); - openShiftClient.close(); - } finally { - if (openShiftClient != null) { - openShiftClient.close(); - } - } - } - -} diff --git a/src/test/java/io/fabric8/che/starter/template/CheServerTemplateTest.java b/src/test/java/io/fabric8/che/starter/template/CheServerTemplateTest.java deleted file mode 100644 index 8001da4..0000000 --- a/src/test/java/io/fabric8/che/starter/template/CheServerTemplateTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * #%L - * che-starter - * %% - * Copyright (C) 2017 Red Hat, Inc. - * %% - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * #L% - */ -package io.fabric8.che.starter.template; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.net.MalformedURLException; - -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.JsonNodeType; - -import io.fabric8.che.starter.TestConfig; - -public class CheServerTemplateTest extends TestConfig { - - @Autowired - CheServerTemplate template; - - @Test - public void processTemplate() throws MalformedURLException, IOException { - String json = template.get(); - assertTrue(!StringUtils.isEmpty(json)); - ObjectMapper mapper = new ObjectMapper(); - JsonNode node = mapper.readTree(json); - assertTrue(node.getNodeType() == JsonNodeType.OBJECT); - } - -}