io.fabric8.openshift.api.model.Project Java Examples

The following examples show how to use io.fabric8.openshift.api.model.Project. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HandlersTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void checkHandlers() {
  checkHandler(new BuildConfig(), new BuildConfigHandler());
  checkHandler(new Build(), new BuildHandler());
  checkHandler(new DeploymentConfig(), new DeploymentConfigHandler());
  checkHandler(new Group(), new GroupHandler());
  checkHandler(new Identity(), new IdentityHandler());
  checkHandler(new Image(), new ImageHandler());
  checkHandler(new ImageStream(), new ImageStreamHandler());
  checkHandler(new ImageStreamTag(), new ImageStreamTagHandler());
  checkHandler(new NetNamespace(), new NetNamespaceHandler());
  checkHandler(new OAuthAccessToken(), new OAuthAccessTokenHandler());
  checkHandler(new OAuthAuthorizeToken(), new OAuthAuthorizeTokenHandler());
  checkHandler(new OAuthClient(), new OAuthClientHandler());
  checkHandler(new Project(), new ProjectHandler());
  checkHandler(new Route(), new RouteHandler());
  checkHandler(new SecurityContextConstraints(), new SecurityContextConstraintsHandler());
  checkHandler(new User(), new UserHandler());
}
 
Example #2
Source File: ProjectEnricher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private Project convertToProject(Namespace namespace) {

        ProjectBuilder builder = new ProjectBuilder();
        builder.withMetadata(namespace.getMetadata());

        if (namespace.getSpec() != null) {
            NamespaceSpec namespaceSpec = namespace.getSpec();
            ProjectSpec projectSpec = new ProjectSpec();
            if (namespaceSpec.getFinalizers() != null) {
                projectSpec.setFinalizers(namespaceSpec.getFinalizers());
            }
            builder.withSpec(projectSpec);
        }

        if (namespace.getStatus() != null) {
            ProjectStatus status = new ProjectStatusBuilder()
                    .withPhase(namespace.getStatus().getPhase()).build();

            builder.withStatus(status);
        }

        return builder.build();
    }
 
Example #3
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
public boolean checkNamespace(String namespaceName) {
    if (StringUtils.isBlank(namespaceName)) {
        return false;
    }
    OpenShiftClient openshiftClient = getOpenShiftClient();
    if (openshiftClient != null) {
        // It is preferable to iterate on the list of projects as regular user with the 'basic-role' bound
        // are not granted permission get operation on non-existing project resource that returns 403
        // instead of 404. Only more privileged roles like 'view' or 'cluster-reader' are granted this permission.
        List<Project> projects = openshiftClient.projects().list().getItems();
        for (Project project : projects) {
            if (namespaceName.equals(project.getMetadata().getName())) {
                return true;
            }
        }
        return false;
    }
    else {
        return kubernetesClient.namespaces().withName(namespaceName).get() != null;
    }
}
 
Example #4
Source File: ProjectTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() {
 server.expect().withPath("/apis/project.openshift.io/v1/projects/project1").andReturn(200, new ProjectBuilder()
    .withNewMetadata().withName("project1").endMetadata()
    .build()).once();

 server.expect().withPath("/apis/project.openshift.io/v1/projects/project2").andReturn(200, new ProjectBuilder()
    .withNewMetadata().withName("project2").endMetadata()
    .build()).once();

  OpenShiftClient client = server.getOpenshiftClient();

  Project project = client.projects().withName("project1").get();
  assertNotNull(project);
  assertEquals("project1", project.getMetadata().getName());

  project = client.projects().withName("project2").get();
  assertNotNull(project);
  assertEquals("project2", project.getMetadata().getName());

  project = client.projects().withName("project3").get();
  assertNull(project);
}
 
Example #5
Source File: OpenShiftProjectFactory.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private Optional<Project> fetchNamespaceObject(String name) throws InfrastructureException {
  try {
    Project project = clientFactory.createOC().projects().withName(name).get();
    return Optional.ofNullable(project);
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      // 403 means that the project does not exist
      // or a user really is not permitted to access it which is Che Server misconfiguration
      return Optional.empty();
    } else {
      throw new InfrastructureException(
          format("Error while trying to fetch the project '%s'. Cause: %s", name, e.getMessage()),
          e);
    }
  }
}
 
Example #6
Source File: OpenShiftProjectFactory.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private KubernetesNamespaceMeta asNamespaceMeta(io.fabric8.openshift.api.model.Project project) {
  Map<String, String> attributes = new HashMap<>(4);
  ObjectMeta metadata = project.getMetadata();
  Map<String, String> annotations = metadata.getAnnotations();
  String displayName = annotations.get(Constants.PROJECT_DISPLAY_NAME_ANNOTATION);
  if (displayName != null) {
    attributes.put(Constants.PROJECT_DISPLAY_NAME_ATTRIBUTE, displayName);
  }
  String description = annotations.get(Constants.PROJECT_DESCRIPTION_ANNOTATION);
  if (description != null) {
    attributes.put(Constants.PROJECT_DESCRIPTION_ATTRIBUTE, description);
  }

  if (project.getStatus() != null && project.getStatus().getPhase() != null) {
    attributes.put(PHASE_ATTRIBUTE, project.getStatus().getPhase());
  }
  return new KubernetesNamespaceMetaImpl(metadata.getName(), attributes);
}
 
Example #7
Source File: OpenShiftProject.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Prepare a project for using.
 *
 * <p>Preparing includes creating if needed and waiting for default service account.
 *
 * @param canCreate defines what to do when the project is not found. The project is created when
 *     {@code true}, otherwise an exception is thrown.
 * @throws InfrastructureException if any exception occurs during project preparation or if the
 *     project doesn't exist and {@code canCreate} is {@code false}.
 */
void prepare(boolean canCreate) throws InfrastructureException {
  String workspaceId = getWorkspaceId();
  String projectName = getName();

  KubernetesClient kubeClient = clientFactory.create(workspaceId);
  OpenShiftClient osClient = clientFactory.createOC(workspaceId);

  Project project = get(projectName, osClient);

  if (project == null) {
    if (!canCreate) {
      throw new InfrastructureException(
          format(
              "Creating the namespace '%s' is not allowed, yet" + " it was not found.",
              projectName));
    }

    create(projectName, osClient);
    waitDefaultServiceAccount(projectName, kubeClient);
  }
}
 
Example #8
Source File: OpenShiftProjectFactoryTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private Project createProject(String name, String displayName, String description, String phase) {
  Map<String, String> annotations = new HashMap<>();
  if (displayName != null) {
    annotations.put(PROJECT_DISPLAY_NAME_ANNOTATION, displayName);
  }
  if (description != null) {
    annotations.put(PROJECT_DESCRIPTION_ANNOTATION, description);
  }

  return new ProjectBuilder()
      .withNewMetadata()
      .withName(name)
      .withAnnotations(annotations)
      .endMetadata()
      .withNewStatus()
      .withNewPhase(phase)
      .endStatus()
      .build();
}
 
Example #9
Source File: OpenShiftProjectFactoryTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
  lenient().when(clientFactory.createOC()).thenReturn(osClient);
  lenient().when(osClient.projects()).thenReturn(projectOperation);

  lenient()
      .when(workspaceManager.getWorkspace(any()))
      .thenReturn(WorkspaceImpl.builder().setId("1").setAttributes(emptyMap()).build());

  lenient().when(projectOperation.withName(any())).thenReturn(projectResource);
  lenient().when(projectResource.get()).thenReturn(mock(Project.class));

  lenient()
      .when(userManager.getById(USER_ID))
      .thenReturn(new UserImpl(USER_ID, "[email protected]", USER_NAME));
}
 
Example #10
Source File: OpenShiftProject.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isProjectManaged(OpenShiftClient client) throws InfrastructureException {
  try {
    Project namespace = client.projects().withName(getName()).get();
    return namespace.getMetadata().getLabels() != null
        && "true".equals(namespace.getMetadata().getLabels().get(MANAGED_NAMESPACE_LABEL));
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      throw new InfrastructureException(
          format(
              "Could not access the project %s when trying to determine if it is managed "
                  + "for workspace %s",
              getName(), getWorkspaceId()),
          e);
    } else if (e.getCode() == 404) {
      // we don't want to block whatever work the caller is doing on the namespace. The caller
      // will fail anyway if the project doesn't exist.
      return true;
    }

    throw new InternalInfrastructureException(
        format(
            "Failed to determine whether the project"
                + " %s is managed. OpenShift client said: %s",
            getName(), e.getMessage()),
        e);
  }
}
 
Example #11
Source File: ProjectOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public ProjectOperationsImpl(OperationContext context) {
  super(context.withApiGroupName(PROJECT)
    .withPlural("projects"));
  this.type = Project.class;
  this.listType = ProjectList.class;
  this.doneableType = DoneableProject.class;
}
 
Example #12
Source File: OpenShiftProjectFactoryTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void prepareListedProjects(List<Project> projects) throws Exception {
  @SuppressWarnings("unchecked")
  ProjectList projectList = mock(ProjectList.class);
  when(projectOperation.list()).thenReturn(projectList);

  when(projectList.getItems()).thenReturn(projects);
}
 
Example #13
Source File: OpenShiftProjectFactoryTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void throwOnTryToGetProjectByName(String name, KubernetesClientException e)
    throws Exception {
  @SuppressWarnings("unchecked")
  Resource<Project, DoneableProject> getProjectByNameOperation = mock(Resource.class);
  when(projectOperation.withName(name)).thenReturn(getProjectByNameOperation);

  when(getProjectByNameOperation.get()).thenThrow(e);
}
 
Example #14
Source File: OpenShiftProjectFactoryTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void prepareNamespaceToBeFoundByName(String name, Project project) throws Exception {
  @SuppressWarnings("unchecked")
  Resource<Project, DoneableProject> getProjectByNameOperation = mock(Resource.class);
  when(projectOperation.withName(name)).thenReturn(getProjectByNameOperation);

  when(getProjectByNameOperation.get()).thenReturn(project);
}
 
Example #15
Source File: OpenShiftProject.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Project get(String projectName, OpenShiftClient client) throws InfrastructureException {
  try {
    return client.projects().withName(projectName).get();
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      // project is foreign or doesn't exist
      return null;
    } else {
      throw new KubernetesInfrastructureException(e);
    }
  }
}
 
Example #16
Source File: OpenShiftProject.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void update(Project project, OpenShiftClient client) throws InfrastructureException {
  try {
    client.projects().createOrReplace(project);
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      LOG.error(
          "Unable to update new Kubernetes project due to lack of permissions."
              + "When using workspace namespace placeholders, service account with lenient permissions (cluster-admin) must be used.");
    }
    throw new KubernetesInfrastructureException(e);
  }
}
 
Example #17
Source File: DefaultNamespaceEnricher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method will create a default Namespace or Project if a namespace property is
 * specified in the xml resourceConfig or as a parameter to a mojo.
 * @param platformMode platform mode whether it's Kubernetes or OpenShift
 * @param builder list of kubernetes resources
 */
@Override
public void create(PlatformMode platformMode, KubernetesListBuilder builder) {

    final String name = config.getNamespace();

    if (name == null || name.isEmpty()) {
        return;
    }

    if (!KubernetesResourceUtil.checkForKind(builder, NAMESPACE_KINDS)) {
        String type = getConfig(Config.type);
        if ("project".equalsIgnoreCase(type) || "namespace".equalsIgnoreCase(type)) {
            if (platformMode == PlatformMode.kubernetes) {

                log.info("Adding a default Namespace:" + config.getNamespace());
                Namespace namespace = handlerHub.getNamespaceHandler().getNamespace(config.getNamespace());
                builder.addToNamespaceItems(namespace);
            } else {

                log.info("Adding a default Project" + config.getNamespace());
                Project project = handlerHub.getProjectHandler().getProject(config.getNamespace());
                builder.addToItems(project);
            }
        }
    }
}
 
Example #18
Source File: ProjectEnricher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void create(PlatformMode platformMode, KubernetesListBuilder builder) {
    if(platformMode == PlatformMode.openshift) {
        for(HasMetadata item : builder.buildItems()) {
            if(item instanceof Namespace) {
                Project project = convertToProject((Namespace) item);
                removeItemFromKubernetesBuilder(builder, item);
                builder.addToItems(project);
            }
        }
    }
}
 
Example #19
Source File: ProjectHandler.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
public Project getProject(String namespace) {
    return new ProjectBuilder().withMetadata(createProjectMetaData(namespace)).withNewStatus().withPhase("Active").endStatus().build();
}
 
Example #20
Source File: OpenShiftProjectTest.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
private Project prepareProject(String projectName) {
  Project project = mock(Project.class);
  Resource projectResource = prepareProjectResource(projectName);
  doReturn(project).when(projectResource).get();
  return project;
}
 
Example #21
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Creates and return a project in openshift
 * @param project
 * @return
 */
public boolean applyProject(Project project) {
    return applyProjectRequest(new ProjectRequestBuilder()
            .withDisplayName(project.getMetadata().getName())
            .withMetadata(project.getMetadata()).build());
}
 
Example #22
Source File: DefaultOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public NonNamespaceOperation<Project, ProjectList, DoneableProject, Resource<Project, DoneableProject>> projects() {
  return new ProjectOperationsImpl(httpClient, OpenShiftConfig.wrap(getConfiguration()));
}
 
Example #23
Source File: ProjectRequestHandler.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public String getKind() {
  return Project.class.getSimpleName();
}