io.fabric8.openshift.client.OpenShiftClient Java Examples

The following examples show how to use io.fabric8.openshift.client.OpenShiftClient. 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: SecurityContextConstraintsTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelete() {
 server.expect().withPath("/apis/security.openshift.io/v1/securitycontextconstraints/scc1").andReturn(200, new SecurityContextConstraintsBuilder().build()).once();
 server.expect().withPath("/apis/security.openshift.io/v1/securitycontextconstraints/scc2").andReturn(200, new SecurityContextConstraintsBuilder().build()).once();

  OpenShiftClient client = server.getOpenshiftClient();

  Boolean deleted = client.securityContextConstraints().withName("scc1").delete();
  assertNotNull(deleted);

  deleted = client.securityContextConstraints().withName("scc1").delete();
  assertFalse(deleted);

  deleted = client.securityContextConstraints().withName("scc2").delete();
  assertTrue(deleted);
}
 
Example #2
Source File: OpenshiftBuildService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private void checkOrCreateImageStream(BuildServiceConfig config, OpenShiftClient client, KubernetesListBuilder builder, String imageStreamName) {
    boolean hasImageStream = client.imageStreams().withName(imageStreamName).get() != null;
    if (hasImageStream && config.getBuildRecreateMode().isImageStream()) {
        client.imageStreams().withName(imageStreamName).delete();
        hasImageStream = false;
    }
    if (!hasImageStream) {
        log.info("Creating ImageStream %s", imageStreamName);
        builder.addToItems(new ImageStreamBuilder()
            .withNewMetadata()
                .withName(imageStreamName)
            .endMetadata()
            .withNewSpec()
                .withNewLookupPolicy()
                    .withLocal(config.isS2iImageStreamLookupPolicyLocal())
                .endLookupPolicy()
            .endSpec()
            .build()
        );
    } else {
        log.info("Adding to ImageStream %s", imageStreamName);
    }
}
 
Example #3
Source File: BuildConfigTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public void testBinaryBuildWithTimeout() {
 server.expect().post().delay(200).withPath("/apis/build.openshift.io/v1/namespaces/ns1/buildconfigs/bc2/instantiatebinary?commit=")
    .andReturn(201, new BuildBuilder()
    .withNewMetadata().withName("bc2").endMetadata().build()).once();

  OpenShiftClient client = server.getOpenshiftClient();
  InputStream dummy = new ByteArrayInputStream("".getBytes() );

  try {
    client.buildConfigs().inNamespace("ns1").withName("bc2").instantiateBinary()
      .withTimeout(100, TimeUnit.MILLISECONDS)
      .fromInputStream(dummy);
  } catch (KubernetesClientException e) {
    assertEquals(SocketTimeoutException.class, e.getCause().getClass());
    return;
  }
  fail("Expected exception");
}
 
Example #4
Source File: OpenShiftVersionExample.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static void main(String args[]) {
  String master = "https://localhost:8443/";
  if (args.length == 1) {
    master = args[0];
  }

  Config config = new ConfigBuilder().withMasterUrl(master).build();

  try(final OpenShiftClient client = new DefaultOpenShiftClient(config)) {
    VersionInfo versionInfo = client.getVersion();

    log("Version details of this OpenShift cluster :-");
    log("Major        : ", versionInfo.getMajor());
    log("Minor        : ", versionInfo.getMinor());
    log("GitVersion   : ", versionInfo.getGitVersion());
    log("BuildDate    : ", versionInfo.getBuildDate());
    log("GitTreeState : ", versionInfo.getGitTreeState());
    log("Platform     : ", versionInfo.getPlatform());
    log("GitVersion   : ", versionInfo.getGitVersion());
    log("GoVersion    : ", versionInfo.getGoVersion());
    log("GitCommit    : ", versionInfo.getGitCommit());
  }
}
 
Example #5
Source File: OpenshiftBuildService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private Build startBuild(OpenShiftClient client, File dockerTar, String buildName) {
    log.info("Starting Build %s", buildName);
    try {
        return client.buildConfigs().withName(buildName)
                .instantiateBinary()
                .fromFile(dockerTar);
    } catch (KubernetesClientException exp) {
        Status status = exp.getStatus();
        if (status != null) {
            log.error("OpenShift Error: [%d %s] [%s] %s", status.getCode(), status.getStatus(), status.getReason(), status.getMessage());
        }
        if (exp.getCause() instanceof IOException && exp.getCause().getMessage().contains("Stream Closed")) {
            log.error("Build for %s failed: %s", buildName, exp.getCause().getMessage());
            logBuildFailedDetails(client, buildName);
        }
        throw exp;
    }
}
 
Example #6
Source File: OpenShiftProject.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Deletes the project. Deleting a non-existent projects is not an error as is not an attempt to
 * delete a project that is already being deleted.
 *
 * @throws InfrastructureException if any unexpected exception occurs during project deletion
 */
void delete() throws InfrastructureException {
  String workspaceId = getWorkspaceId();
  String projectName = getName();

  OpenShiftClient osClient = clientFactory.createOC(workspaceId);

  try {
    delete(projectName, osClient);
  } catch (KubernetesClientException e) {
    if (e.getCode() == 403) {
      throw new InfrastructureException(
          format(
              "Could not access the project %s when deleting it for workspace %s",
              projectName, workspaceId),
          e);
    }

    throw new KubernetesInfrastructureException(e);
  }
}
 
Example #7
Source File: ImageStreamService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private void createOrUpdateImageStreamTag(OpenShiftClient client, ImageName image, ImageStream is) {
    String namespace = client.getNamespace();
    String tagSha = findTagSha(client, image.getSimpleName(), client.getNamespace());
    String name = image.getSimpleName() + "@" + tagSha;

    TagReference tag = extractTag(is);
    ObjectReference from = extractFrom(tag);

    if (!Objects.equals(image.getTag(), tag.getName())) {
        tag.setName(image.getTag());
    }
    if (!Objects.equals("ImageStreamImage", from.getKind())) {
        from.setKind("ImageStreamImage");
    }
    if (!Objects.equals(namespace, from.getNamespace())) {
        from.setNamespace(namespace);
    }
    if (!Objects.equals(name, from.getName())) {
        from.setName(name);
    }
}
 
Example #8
Source File: PatchService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private static EntityPatcher<BuildConfig> bcPatcher() {
    return (KubernetesClient client, String namespace, BuildConfig newObj, BuildConfig oldObj) -> {
        if (UserConfigurationCompare.configEqual(newObj, oldObj)) {
            return oldObj;
        }
        OpenShiftClient openShiftClient = OpenshiftHelper.asOpenShiftClient(client);
        if (openShiftClient == null) {
            throw new IllegalArgumentException("BuildConfig can only be patched when connected to an OpenShift cluster");
        }
        DoneableBuildConfig entity =
            openShiftClient.buildConfigs()
                  .inNamespace(namespace)
                  .withName(oldObj.getMetadata().getName())
                  .edit();

        if (!UserConfigurationCompare.configEqual(newObj.getMetadata(), oldObj.getMetadata())) {
            entity.withMetadata(newObj.getMetadata());
        }

        if(!UserConfigurationCompare.configEqual(newObj.getSpec(), oldObj.getSpec())) {
                entity.withSpec(newObj.getSpec());
        }
        return entity.done();
    };
}
 
Example #9
Source File: AdaptTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSharedClient() {
  server.expect().withPath("/apis").andReturn(200, new APIGroupListBuilder()
    .addNewGroup()
    .withApiVersion("v1")
    .withName("autoscaling.k8s.io")
    .endGroup()
    .addNewGroup()
    .withApiVersion("v1")
    .withName("security.openshift.io")
    .endGroup()
    .build()).once();

  KubernetesClient client = server.getClient();
  OpenShiftClient oclient = client.adapt(OpenShiftClient.class);
  assertNotNull(client.adapt(OkHttpClient.class));
  assertNotNull(oclient.adapt(OkHttpClient.class));
}
 
Example #10
Source File: DeploymentConfigTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeployingLatestHandlesMissingLatestVersion() {
  server.expect().withPath("/apis/apps.openshift.io/v1/namespaces/test/deploymentconfigs/dc1")
    .andReturn(200, new DeploymentConfigBuilder().withNewMetadata().withName("dc1").endMetadata()
      .withNewStatus().endStatus().build())
    .always();

  server.expect().patch().withPath("/apis/apps.openshift.io/v1/namespaces/test/deploymentconfigs/dc1")
    .andReturn(200, new DeploymentConfigBuilder().withNewMetadata().withName("dc1").endMetadata()
      .withNewStatus().withLatestVersion(1L).endStatus().build())
    .once();

  OpenShiftClient client = server.getOpenshiftClient();

  DeploymentConfig deploymentConfig = client.deploymentConfigs().withName("dc1").deployLatest();
  assertNotNull(deploymentConfig);
  assertEquals(new Long(1), deploymentConfig.getStatus().getLatestVersion());
}
 
Example #11
Source File: OAuthClientTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() {
 server.expect().withPath("/apis/oauth.openshift.io/v1/oauthclients/client1").andReturn(200, new OAuthClientBuilder()
    .withNewMetadata().withName("client1").endMetadata()
    .build()).once();

 server.expect().withPath("/apis/oauth.openshift.io/v1/oauthclients/client2").andReturn(200, new OAuthClientBuilder()
    .withNewMetadata().withName("client2").endMetadata()
    .build()).once();

  OpenShiftClient client = server.getOpenshiftClient();

  OAuthClient oauthclient = client.oAuthClients().withName("client1").get();
  assertNotNull(oauthclient);
  assertEquals("client1", oauthclient.getMetadata().getName());

  oauthclient = client.oAuthClients().withName("client2").get();
  assertNotNull(oauthclient);
  assertEquals("client2", oauthclient.getMetadata().getName());

  oauthclient = client.oAuthClients().withName("client3").get();
  assertNull(oauthclient);
}
 
Example #12
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 #13
Source File: OpenshiftBuildServiceTest.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSuccessfulSecondBuild() throws Exception {
    retryInMockServer(() -> {
        BuildServiceConfig config = defaultConfig.build();
        // @formatter:on
        new Expectations() {{
            jKubeServiceHub.getBuildServiceConfig(); result = config;
        }};
        // @formatter:off
        WebServerEventCollector<OpenShiftMockServer> collector = createMockServer(config, true, 50, true, true);
        OpenShiftMockServer mockServer = collector.getMockServer();

        OpenShiftClient client = mockServer.createOpenShiftClient();
        OpenshiftBuildService service = new OpenshiftBuildService(client, logger, jKubeServiceHub);
        service.build(image);

        assertTrue(mockServer.getRequestCount() > 8);
        collector.assertEventsRecordedInOrder("build-config-check", "patch-build-config", "pushed");
        collector.assertEventsNotRecorded("new-build-config");
    });
}
 
Example #14
Source File: NewProjectExamples.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
  String master = "https://localhost:8443/";
  if (args.length == 1) {
    master = args[0];
  }

  Config config = new ConfigBuilder().withMasterUrl(master).build();

  try (OpenShiftClient client = new DefaultOpenShiftClient(config)) {
    ProjectRequest request = null;
    try {
      request = client.projectrequests().createNew().withNewMetadata().withName("thisisatest").endMetadata().withDescription("Jimmi").withDisplayName("Jimmi").done();
    } finally {
      if (request != null) {
        client.projects().withName(request.getMetadata().getName()).delete();
      }
    }
  }
}
 
Example #15
Source File: ApplyStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 6 votes vote down vote up
private List<HasMetadata> loadImageStreams() throws IOException, InterruptedException {
    if (kubernetes.isAdaptable(OpenShiftClient.class)) {
        FilePath child = workspace.child("target");
        if (child.exists() && child.isDirectory()) {
            List<FilePath> paths = child.list();
            if (paths != null) {
                for (FilePath path : paths) {
                    String name = path.getName();
                    if (path.exists() && !path.isDirectory() && name.endsWith("-is.yml")) {
                        try (InputStream is = path.read()) {
                            listener.getLogger().println("Loading OpenShift ImageStreams file: " + name);
                            KubernetesResource dto = KubernetesHelper.loadYaml(is, KubernetesResource.class);
                            return KubernetesHelper.toItemList(dto);
                        }
                    }
                }
            }
        }
    }
    return Collections.emptyList();
}
 
Example #16
Source File: K8sManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the client for deploying custom resources
 *
 * @param client , openshift client
 * @param crd    , CustomResourceDefinition
 * @return , Custom resource client
 */
private NonNamespaceOperation<APICustomResourceDefinition, APICustomResourceDefinitionList,
        DoneableAPICustomResourceDefinition, Resource<APICustomResourceDefinition,
        DoneableAPICustomResourceDefinition>> getCRDClient(OpenShiftClient client, CustomResourceDefinition crd) {

    NonNamespaceOperation<APICustomResourceDefinition, APICustomResourceDefinitionList,
            DoneableAPICustomResourceDefinition, Resource<APICustomResourceDefinition,
            DoneableAPICustomResourceDefinition>> crdClient = client
            .customResources(crd, APICustomResourceDefinition.class, APICustomResourceDefinitionList.class,
                    DoneableAPICustomResourceDefinition.class);

    crdClient = ((MixedOperation<APICustomResourceDefinition, APICustomResourceDefinitionList,
            DoneableAPICustomResourceDefinition, Resource<APICustomResourceDefinition,
            DoneableAPICustomResourceDefinition>>) crdClient).inNamespace(client.getNamespace());

    return crdClient;
}
 
Example #17
Source File: TeiidOpenShiftClient.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private RouteStatus getRoute(String openShiftName, ProtocolType protocolType) {
    String namespace = ApplicationProperties.getNamespace();
    OpenShiftClient client = openshiftClient();
    RouteStatus theRoute = null;
    debug(openShiftName, "Getting route of type " + protocolType.id() + " for Service");

    Route route = client.routes().inNamespace(namespace).withName(openShiftName + StringConstants.HYPHEN + protocolType.id()).get();

    if (route != null) {
        ObjectMeta metadata = route.getMetadata();
        String name = metadata.getName();
        RouteSpec spec = route.getSpec();
        String target = spec.getTo().getName();

        theRoute = new RouteStatus(name, protocolType);
        theRoute.setHost(spec.getHost());
        theRoute.setPath(spec.getPath());
        theRoute.setPort(spec.getPort().getTargetPort().getStrVal());
        theRoute.setTarget(target);
        theRoute.setSecure(spec.getTls() != null);
    }
    return theRoute;
}
 
Example #18
Source File: DeploymentConfigTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() {
 server.expect().withPath("/apis/apps.openshift.io/v1/namespaces/test/deploymentconfigs/dc1").andReturn(200, new DeploymentConfigBuilder()
    .withNewMetadata().withName("dc1").endMetadata()
    .build()).once();

 server.expect().withPath("/apis/apps.openshift.io/v1/namespaces/ns1/deploymentconfigs/dc2").andReturn(200, new DeploymentConfigBuilder()
    .withNewMetadata().withName("dc2").endMetadata()
    .build()).once();

  OpenShiftClient client = server.getOpenshiftClient();

  DeploymentConfig buildConfig = client.deploymentConfigs().withName("dc1").get();
  assertNotNull(buildConfig);
  assertEquals("dc1", buildConfig.getMetadata().getName());

  buildConfig = client.deploymentConfigs().withName("dc2").get();
  assertNull(buildConfig);

  buildConfig = client.deploymentConfigs().inNamespace("ns1").withName("dc2").get();
  assertNotNull(buildConfig);
  assertEquals("dc2", buildConfig.getMetadata().getName());
}
 
Example #19
Source File: OpenshiftRoleTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() {
 server.expect().withPath("/apis/authorization.openshift.io/v1/namespaces/test/roles/role1").andReturn(200, new RoleBuilder()
    .withNewMetadata().withName("role1").endMetadata()
    .build()).once();

 server.expect().withPath("/apis/authorization.openshift.io/v1/namespaces/ns1/roles/role2").andReturn(200, new RoleBuilder()
    .withNewMetadata().withName("role2").endMetadata()
    .build()).once();

  OpenShiftClient client = server.getOpenshiftClient();

  Role role = client.roles().withName("role1").get();
  assertNotNull(role);
  assertEquals("role1", role.getMetadata().getName());

  role = client.roles().withName("role2").get();
  assertNull(role);

  role = client.roles().inNamespace("ns1").withName("role2").get();
  assertNotNull(role);
  assertEquals("role2", role.getMetadata().getName());
}
 
Example #20
Source File: OpenShiftStopWorkspaceRoleProvisioner.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
public void provision(String projectName) throws InfrastructureException {
  if (stopWorkspaceRoleEnabled && installationLocation != null) {
    OpenShiftClient osClient = clientFactory.createOC();
    String stopWorkspacesRoleName = "workspace-stop";
    if (osClient.roles().inNamespace(projectName).withName(stopWorkspacesRoleName).get()
        == null) {
      osClient
          .roles()
          .inNamespace(projectName)
          .createOrReplace(createStopWorkspacesRole(stopWorkspacesRoleName));
    }
    osClient
        .roleBindings()
        .inNamespace(projectName)
        .createOrReplace(createStopWorkspacesRoleBinding(projectName));
  } else {
    LOG.warn(
        "Stop workspace Role and RoleBinding will not be provisioned to the '{}' namespace. 'che.workspace.stop.role.enabled' property is set to '{}'",
        installationLocation,
        stopWorkspaceRoleEnabled);
  }
}
 
Example #21
Source File: TemplateTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateWithHandler() {
  Template template = new TemplateBuilder()
    .editOrNewMetadata()
    .withName("tmpl3")
    .withNamespace("test")
    .endMetadata()
    .build();

  server.expect().withPath("/apis/template.openshift.io/v1/namespaces/test/templates").andReturn(200, template).once();
  server.expect().withPath("/apis/template.openshift.io/v1/namespaces/test/templates/tmpl3").andReturn(404, new StatusBuilder().withCode(404).build()).once();

  OpenShiftClient client = server.getOpenshiftClient();

  Template created = client.resource(template).createOrReplace();
  assertNotNull(created);
}
 
Example #22
Source File: DeploymentConfigTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeployingLatest() {
	server.expect().withPath("/apis/apps.openshift.io/v1/namespaces/test/deploymentconfigs/dc1")
			.andReturn(200, new DeploymentConfigBuilder().withNewMetadata().withName("dc1").endMetadata()
					.withNewStatus().withLatestVersion(1L).endStatus().build())
			.always();

	server.expect().patch().withPath("/apis/apps.openshift.io/v1/namespaces/test/deploymentconfigs/dc1")
			.andReturn(200, new DeploymentConfigBuilder().withNewMetadata().withName("dc1").endMetadata()
					.withNewStatus().withLatestVersion(2L).endStatus().build())
			.once();

	OpenShiftClient client = server.getOpenshiftClient();

	DeploymentConfig deploymentConfig = client.deploymentConfigs().withName("dc1").deployLatest();
	assertNotNull(deploymentConfig);
	assertEquals(new Long(2), deploymentConfig.getStatus().getLatestVersion());
}
 
Example #23
Source File: ListBuildConfigs.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  try {
    OpenShiftClient client = new DefaultOpenShiftClient();
    if (!client.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.BUILD)) {
      System.out.println("WARNING this cluster does not support the API Group " + OpenShiftAPIGroups.BUILD);
      return;
    }
    BuildConfigList list = client.buildConfigs().list();
    if (list == null) {
      System.out.println("ERROR no list returned!");
      return;
    }
    List<BuildConfig> items = list.getItems();
    for (BuildConfig item : items) {
      System.out.println("BuildConfig " + item.getMetadata().getName() + " has version: " + item.getApiVersion());
    }
  } catch (KubernetesClientException e) {
    System.out.println("Failed: " + e);
    e.printStackTrace();
  }
}
 
Example #24
Source File: GroupTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() {
 server.expect().withPath("/apis/user.openshift.io/v1/groups/group1").andReturn(200, new GroupBuilder()
    .withNewMetadata().withName("group1").endMetadata()
    .build()).once();

 server.expect().withPath("/apis/user.openshift.io/v1/groups/Group2").andReturn(200, new GroupBuilder()
    .withNewMetadata().withName("Group2").endMetadata()
    .build()).once();

  OpenShiftClient client = server.getOpenshiftClient();

  Group group = client.groups().withName("group1").get();
  assertNotNull(group);
  assertEquals("group1", group.getMetadata().getName());

  group = client.groups().withName("Group2").get();
  assertNotNull(group);
  assertEquals("Group2", group.getMetadata().getName());

  group = client.groups().withName("Group3").get();
  assertNull(group);
}
 
Example #25
Source File: LoginExample.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

    try (DefaultKubernetesClient kubernetesClient = new DefaultKubernetesClient(new ConfigBuilder()
      .withMasterUrl("cluster_url")
      .withUsername("my_username")
      .withPassword("my_password")
      .build())) {

      final OpenShiftClient openShiftClient = kubernetesClient.adapt(OpenShiftClient.class);
      logger.info(openShiftClient.projects().list().toString());
    }
  }
 
Example #26
Source File: OpenShift.java    From enmasse with Apache License 2.0 5 votes vote down vote up
@Override
public Endpoint getKeycloakEndpoint() {
    OpenShiftClient openShift = client.adapt(OpenShiftClient.class);
    Route route = openShift.routes().inNamespace(infraNamespace).withName("keycloak").get();
    Endpoint endpoint = new Endpoint(route.getSpec().getHost(), 443);
    log.info("Testing endpoint : " + endpoint);
    if (TestUtils.resolvable(endpoint)) {
        return endpoint;
    } else {
        log.info("Endpoint didn't resolve, falling back to service endpoint");
        return getEndpoint("standard-authservice", infraNamespace, "https");
    }
}
 
Example #27
Source File: OpenShiftWorkspaceServiceAccount.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Make sure that workspace service account exists and has `view` and `exec` role bindings, as
 * well as create workspace-view and exec roles in namespace scope
 *
 * <p>Do NOT make any changes to the service account if it already exists in the namespace to
 * preserve its configuration done by someone else.
 *
 * @throws InfrastructureException when any exception occurred
 */
void prepare() throws InfrastructureException {
  OpenShiftClient osClient = clientFactory.createOC(workspaceId);

  if (osClient.serviceAccounts().inNamespace(projectName).withName(serviceAccountName).get()
      == null) {
    createWorkspaceServiceAccount(osClient);
  } else {
    return;
  }

  String execRoleName = "exec";
  if (osClient.roles().inNamespace(projectName).withName(execRoleName).get() == null) {
    createExecRole(osClient, execRoleName);
  }

  String viewRoleName = "workspace-view";
  if (osClient.roles().inNamespace(projectName).withName(viewRoleName).get() == null) {
    createViewRole(osClient, viewRoleName);
  }

  osClient.roleBindings().inNamespace(projectName).createOrReplace(createExecRoleBinding());
  osClient.roleBindings().inNamespace(projectName).createOrReplace(createViewRoleBinding());

  // If the user specified an additional cluster role for the workspace,
  // create a role binding for it too
  if (!isNullOrEmpty(this.clusterRoleName)) {
    if (osClient.rbac().clusterRoles().withName(this.clusterRoleName).get() != null) {
      osClient
          .roleBindings()
          .inNamespace(projectName)
          .createOrReplace(createCustomRoleBinding(this.clusterRoleName));
    } else {
      LOG.warn(
          "Unable to find the cluster role {}. Skip creating custom role binding.",
          this.clusterRoleName);
    }
  }
}
 
Example #28
Source File: DeploymentConfigOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
protected void mocker(OpenShiftClient mockClient, MixedOperation op) {
    /*ExtensionsAPIGroupDSL mockExt = mock(ExtensionsAPIGroupDSL.class);
    when(mockExt.deployments()).thenReturn(op);
    when(mockClient.extensions()).thenReturn(mockExt);*/
    when(mockClient.deploymentConfigs()).thenReturn(op);
}
 
Example #29
Source File: OpenshiftBuildService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private boolean updateSecret(OpenShiftClient client, String pullSecretName, Map<String, String> data) {
    if (!Objects.equals(data, client.secrets().withName(pullSecretName).get().getData())) {
        client.secrets().withName(pullSecretName).edit()
                .editMetadata()
                .withName(pullSecretName)
                .endMetadata()
                .withData(data)
                .withType("kubernetes.io/dockerconfigjson")
                .done();
        log.info("Updating Secret %s", pullSecretName);
    } else {
        log.info("Using Secret %s", pullSecretName);
    }
    return true;
}
 
Example #30
Source File: TemplateTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testList() {
  server.expect().withPath("/apis/template.openshift.io/v1/namespaces/test/templates").andReturn(200, new TemplateListBuilder().build()).once();
  server.expect().withPath("/apis/template.openshift.io/v1/namespaces/ns1/templates").andReturn(200, new TemplateListBuilder()
    .addNewItem().and()
    .addNewItem().and().build()).once();
  server.expect().withPath("/apis").andReturn(200, new APIGroupListBuilder()
    .addNewGroup()
    .withApiVersion("v1")
    .withName("autoscaling.k8s.io")
    .endGroup()
    .addNewGroup()
    .withApiVersion("v1")
    .withName("security.openshift.io")
    .endGroup()
    .build()).always();

  server.expect().withPath("/apis/template.openshift.io/v1/templates").andReturn(200, new TemplateListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .addNewItem()
    .and().build()).once();

  OpenShiftClient client = server.getOpenshiftClient();

  TemplateList templateList = client.templates().list();
  assertNotNull(templateList);
  assertEquals(0, templateList.getItems().size());

  templateList = client.templates().inNamespace("ns1").list();
  assertNotNull(templateList);
  assertEquals(2, templateList.getItems().size());

  templateList = client.templates().inAnyNamespace().list();
  assertNotNull(templateList);
  assertEquals(3, templateList.getItems().size());
}