io.fabric8.openshift.client.DefaultOpenShiftClient Java Examples

The following examples show how to use io.fabric8.openshift.client.DefaultOpenShiftClient. 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: OpenshiftBuildServiceTest.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSuccessfulBuild() throws Exception {
    retryInMockServer(() -> {
        BuildServiceConfig config = defaultConfig.build();
        // @formatter:off
        new Expectations() {{
            jKubeServiceHub.getBuildServiceConfig(); result = config;
        }};
        // @formatter:on
        WebServerEventCollector<OpenShiftMockServer> collector = createMockServer(config, true, 50, false, false);
        OpenShiftMockServer mockServer = collector.getMockServer();

        DefaultOpenShiftClient client = (DefaultOpenShiftClient) mockServer.createOpenShiftClient();
        LOG.info("Current write timeout is : {}", client.getHttpClient().writeTimeoutMillis());
        LOG.info("Current read timeout is : {}", client.getHttpClient().readTimeoutMillis());
        LOG.info("Retry on failure : {}", client.getHttpClient().retryOnConnectionFailure());
        OpenshiftBuildService service = new OpenshiftBuildService(client, logger, jKubeServiceHub);
        service.build(image);

        // we should Foadd a better way to assert that a certain call has been made
        assertTrue(mockServer.getRequestCount() > 8);
        collector.assertEventsRecordedInOrder("build-config-check", "new-build-config", "pushed");
        assertEquals("{\"apiVersion\":\"build.openshift.io/v1\",\"kind\":\"BuildConfig\",\"metadata\":{\"name\":\"myapp-s2i-suffix2\"},\"spec\":{\"output\":{\"to\":{\"kind\":\"ImageStreamTag\",\"name\":\"myapp:latest\"}},\"source\":{\"type\":\"Binary\"},\"strategy\":{\"sourceStrategy\":{\"forcePull\":false,\"from\":{\"kind\":\"DockerImage\",\"name\":\"myapp\"}},\"type\":\"Source\"}}}", collector.getBodies().get(1));
        collector.assertEventsNotRecorded("patch-build-config");
    });
}
 
Example #2
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 #3
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 #4
Source File: WatchBuildConfigs.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();
    String namespace = client.getNamespace();
    System.out.println("Watching BuildConfigs in namespace " + namespace);
    try (Watch watchable = client.buildConfigs().inNamespace(namespace).watch(new Watcher<BuildConfig>() {
      @Override
      public void eventReceived(Action action, BuildConfig resource) {
        System.out.println(">> Action: " + action + " on BuildConfig " + resource.getMetadata().getName() + " with version: " + resource.getApiVersion());
      }

      @Override
      public void onClose(KubernetesClientException cause) {
        System.out.println("Watch Closed: " + cause);
        if (cause != null) {
          cause.printStackTrace();
        }
      }
    })) {
      System.out.println("Created watchable " + watchable);
    }
  } catch (KubernetesClientException e) {
    System.out.println("Failed: " + e);
    e.printStackTrace();
  }
}
 
Example #5
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 #6
Source File: OpenshiftAPIService.java    From openshift-elasticsearch-plugin with Apache License 2.0 6 votes vote down vote up
public String userName(final String token) {
    Response response = null;
    try (DefaultOpenShiftClient client = factory.buildClient(token)) {
        Request okRequest = new Request.Builder()
                .url(client.getMasterUrl() + "apis/user.openshift.io/v1/users/~")
                .header("Authorization", "Bearer " + token)
                .header(ACCEPT, APPLICATION_JSON)
                .build();
        response = client.getHttpClient().newCall(okRequest).execute();
        final String body = response.body().string();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response: code '{}' {}", response.code(), body);
        }
        if(response.code() != RestStatus.OK.getStatus()) {
            throw new ElasticsearchSecurityException("Unable to determine username from the token provided", RestStatus.fromCode(response.code()));
        }
        return JsonPath.read(body,"$.metadata.name");
    } catch (IOException e) {
        LOGGER.error("Error retrieving username from token", e);
        throw new ElasticsearchException(e);
    }        
}
 
Example #7
Source File: OpenShift.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public OpenShift(Environment environment) {
    super(environment, () -> {
        Config config = new ConfigBuilder().withMasterUrl(environment.getApiUrl())
                .withOauthToken(environment.getApiToken())
                .build();
        OkHttpClient httpClient = HttpClientUtils.createHttpClient(config);
        // Workaround https://github.com/square/okhttp/issues/3146
        httpClient = httpClient.newBuilder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .connectTimeout(environment.getKubernetesApiConnectTimeout())
                .writeTimeout(environment.getKubernetesApiWriteTimeout())
                .readTimeout(environment.getKubernetesApiReadTimeout())
                .build();
        return new DefaultOpenShiftClient(httpClient, new OpenShiftConfig(config));
    });
}
 
Example #8
Source File: ListImageStreams.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.IMAGE)) {
      System.out.println("WARNING this cluster does not support the API Group " + OpenShiftAPIGroups.IMAGE);
      return;
    }
    ImageStreamList list = client.imageStreams().list();
    if (list == null) {
      System.out.println("ERROR no list returned!");
      return;
    }
    List<ImageStream> items = list.getItems();
    for (ImageStream item : items) {
      System.out.println("ImageStream " + item.getMetadata().getName() + " has version: " + item.getApiVersion());
    }
    System.out.println("Found " + items.size() + " ImageStream(s)");
  } catch (KubernetesClientException e) {
    System.out.println("Failed: " + e);
    e.printStackTrace();
  }
}
 
Example #9
Source File: HistoryServerOperator.java    From spark-operator with Apache License 2.0 6 votes vote down vote up
@Override
protected void onAdd(SparkHistoryServer hs) {
    log.info("Spark history server added");

    KubernetesResourceList list = deployer.getResourceList(hs, namespace, isOpenshift);
    if (isOpenshift && hs.getExpose() && !osClient) {

        // we will create openshift specific resource (Route)
        this.client = new DefaultOpenShiftClient();
        osClient = true;
    }
    client.resourceList(list).inNamespace(namespace).createOrReplace();
    cache.put(hs.getName(), list);
    updateStatus(hs, "ready");
    put(hs);
}
 
Example #10
Source File: LogScrapingRecoveryErrorDetector.java    From narayana-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
public void startDetection() {
    if (this.client == null && this.logWatch == null && this.executorService == null) {
        // Printing the START_MESSAGE to limit log scraping
        LOG.info("Log-scraping recovery error detector started: {}", START_MESSAGE);
        this.watchClosed = false;
        this.errorMessageFound = false;
        this.startMessageFound = false;
        this.stopMessageFound = false;

        this.client = new DefaultOpenShiftClient();

        this.logWatch = this.client.pods().withName(this.podName).watchLog();

        this.executorService = Executors.newSingleThreadExecutor();
        this.startLogScraping();
    }
}
 
Example #11
Source File: OperatorAutoConfiguration.java    From java-operator-sdk with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public KubernetesClient kubernetesClient(OperatorProperties operatorProperties) {
    ConfigBuilder config = new ConfigBuilder();
    config.withTrustCerts(operatorProperties.isTrustSelfSignedCertificates());
    if (StringUtils.isNotBlank(operatorProperties.getUsername())) {
        config.withUsername(operatorProperties.getUsername());
    }
    if (StringUtils.isNotBlank(operatorProperties.getPassword())) {
        config.withUsername(operatorProperties.getPassword());
    }
    if (StringUtils.isNotBlank(operatorProperties.getMasterUrl())) {
        config.withMasterUrl(operatorProperties.getMasterUrl());
    }
    KubernetesClient k8sClient = operatorProperties.isOpenshift() ? new DefaultOpenShiftClient(config.build()) : new DefaultKubernetesClient(config.build());
    return k8sClient;
}
 
Example #12
Source File: OpenshiftBuildServiceTest.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSuccessfulBuildSecret() throws Exception {
    retryInMockServer(() -> {
        BuildServiceConfig config = defaultConfigSecret.build();
        // @formatter:on
        new Expectations() {{
            jKubeServiceHub.getBuildServiceConfig(); result = config;
        }};
        // @formatter:off
        WebServerEventCollector<OpenShiftMockServer> collector = createMockServer(config, true, 50, false, false);
        OpenShiftMockServer mockServer = collector.getMockServer();

        DefaultOpenShiftClient client = (DefaultOpenShiftClient) mockServer.createOpenShiftClient();
        LOG.info("Current write timeout is : {}", client.getHttpClient().writeTimeoutMillis());
        LOG.info("Current read timeout is : {}", client.getHttpClient().readTimeoutMillis());
        LOG.info("Retry on failure : {}", client.getHttpClient().retryOnConnectionFailure());
        OpenshiftBuildService service = new OpenshiftBuildService(client, logger, jKubeServiceHub);
        service.build(image);

        // we should Foadd a better way to assert that a certain call has been made
        assertTrue(mockServer.getRequestCount() > 8);
        collector.assertEventsRecordedInOrder("build-config-check", "new-build-config", "pushed");
        collector.assertEventsNotRecorded("patch-build-config");
    });
}
 
Example #13
Source File: AdaptTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void testAdaptDSLs() {
  // Given
  OpenShiftClient client = new DefaultOpenShiftClient();

  assertNotNull(client.v1());
  assertNotNull(client.apps());
  assertNotNull(client.autoscaling());
  assertNotNull(client.batch());
  assertNotNull(client.buildConfigs());
  assertNotNull(client.builds());
  assertNotNull(client.clusterRoleBindings());
  assertNotNull(client.deploymentConfigs());
  assertNotNull(client.extensions());
  assertNotNull(client.groups());
  assertNotNull(client.imageStreams());
  assertNotNull(client.imageStreamTags());
  assertNotNull(client.network());
  assertNotNull(client.oAuthAccessTokens());
  assertNotNull(client.oAuthAuthorizeTokens());
  assertNotNull(client.oAuthClients());
  assertNotNull(client.projectrequests());
  assertNotNull(client.projects());
  assertNotNull(client.pods());
  assertNotNull(client.rbac());
  assertNotNull(client.roleBindings());
  assertNotNull(client.settings());
  assertNotNull(client.storage());
  assertNotNull(client.templates());
  assertNotNull(client.users());
}
 
Example #14
Source File: AdaptTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void testAdaptToHttpClient() {
  // Given
  OpenShiftClient client = new DefaultOpenShiftClient();

  // When + Then
  assertTrue(client.isAdaptable(OkHttpClient.class));
  assertNotNull(client.adapt(OkHttpClient.class));
}
 
Example #15
Source File: ImageStreamTagExample.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {

    String namespace = "myproject";
    String master = "CLUSTER_URL";
    Config config = new ConfigBuilder().withMasterUrl(master).build();
    OpenShiftClient client = new DefaultOpenShiftClient(config);

    try {

      ImageStreamTag istag = new ImageStreamTagBuilder().withNewMetadata().withName("bar1:1.0.12").endMetadata()
        .withNewTag().withNewFrom().withKind("DockerImage").withName("openshift/wildfly-81-centos7:latest").endFrom().endTag()
        .build();

      log("Created istag", client.imageStreamTags().inNamespace(namespace).create(istag));
      
      Thread.sleep(30000);

    }finally {

      log("ImageStreamTags are :");
      log(client.imageStreamTags().inNamespace(namespace).withName("bar1:1.0.12").get().toString());

      log("ImageStreamTags using list are :");
      log(client.imageStreamTags().list().getItems().get(0).toString());
      log("Deleted istag",client.imageStreamTags().withName("bar1:1.0.12").delete());
      client.close();
    }
  }
 
Example #16
Source File: SecurityContextConstraintExample.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {

        try (OpenShiftClient client = new DefaultOpenShiftClient()) {

          SecurityContextConstraints scc = new SecurityContextConstraintsBuilder()
            .withNewMetadata().withName("scc").endMetadata()
            .withAllowPrivilegedContainer(true)
            .withNewRunAsUser()
            .withType("RunAsAny")
            .endRunAsUser()
            .withNewSeLinuxContext()
            .withType("RunAsAny")
            .endSeLinuxContext()
            .withNewFsGroup()
            .withType("RunAsAny")
            .endFsGroup()
            .withNewSupplementalGroups()
            .withType("RunAsAny")
            .endSupplementalGroups()
            .addToUsers("admin")
            .addToGroups("admin-group")
            .build();

          log("Created SecurityContextConstraints", client.securityContextConstraints().create(scc));

          client.close();

        } catch (KubernetesClientException e) {
          logger.error(e.getMessage(), e);
        }
    }
 
Example #17
Source File: ListDeploymentConfigs.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  try {
    OpenShiftClient client = new DefaultOpenShiftClient();
    if (!client.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.APPS)) {
      System.out.println("WARNING this cluster does not support the API Group " + OpenShiftAPIGroups.APPS);
      return;
    }
    DeploymentConfigList list = client.deploymentConfigs().list();
    if (list == null) {
      System.out.println("ERROR no list returned!");
      return;
    }
    List<DeploymentConfig> items = list.getItems();
    for (DeploymentConfig item : items) {
      System.out.println("DeploymentConfig " + item.getMetadata().getName() + " has version: " + item.getApiVersion());
    }

    if (items.size() > 0) {
      // lets check .get() too
      DeploymentConfig deploymentConfig = items.get(0);
      String name = deploymentConfig.getMetadata().getName();
      deploymentConfig = client.deploymentConfigs().withName(name).get();
      assertNotNull("No DeploymentConfig found for name " + name, deploymentConfig);
      System.out.println("get() DeploymentConfig " + name + " has version: " + deploymentConfig.getApiVersion());
    }
  } catch (KubernetesClientException e) {
    System.out.println("Failed: " + e);
    e.printStackTrace();
  }
}
 
Example #18
Source File: OpenShiftMockServer.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public NamespacedOpenShiftClient createOpenShiftClient() {
  Config config = new ConfigBuilder()
    .withMasterUrl(url("/"))
    .withNamespace("test")
    .withTrustCerts(true)
    .withTlsVersions(TLS_1_0)
    .build();
  return new DefaultOpenShiftClient(createHttpClientForMockServer(config), new OpenShiftConfig(config));
}
 
Example #19
Source File: OpenShiftMockServer.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public NamespacedOpenShiftClient createOpenShiftClient() {
  Config config = new ConfigBuilder()
    .withMasterUrl(url("/"))
    .withNamespace("test")
    .withTrustCerts(true)
    .withTlsVersions(TLS_1_0)
    .build();
  return new DefaultOpenShiftClient(createHttpClientForMockServer(config), new OpenShiftConfig(config));
}
 
Example #20
Source File: OpenShiftMockServer.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public NamespacedOpenShiftClient createOpenShiftClient() {
  OpenShiftConfig config = new OpenShiftConfigBuilder()
    .withMasterUrl(url("/"))
    .withNamespace("test")
    .withTrustCerts(true)
    .withTlsVersions(TLS_1_0)
    .withDisableApiGroupCheck(disableApiGroupCheck)
    .build();
  return new DefaultOpenShiftClient(createHttpClientForMockServer(config), config);
}
 
Example #21
Source File: K8sManager.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the API from all the clusters it had been deployed
 *
 * @param apiId                   API Identifier
 * @param containerMgtInfoDetails Clusters which the API has published
 */
@Override
public void deleteAPI(APIIdentifier apiId, JSONObject containerMgtInfoDetails) {

    String apiName = apiId.getApiName();

    JSONObject propreties = (JSONObject) containerMgtInfoDetails.get(PROPERTIES);

    if (propreties.get(MASTER_URL) != null &&
            propreties.get(SATOKEN) != null &&
            propreties.get(NAMESPACE) != null) {
        Config config = new ConfigBuilder()
                .withMasterUrl(propreties.get(MASTER_URL).toString().replace("\\", ""))
                .withOauthToken(propreties.get(SATOKEN).toString())
                .withNamespace(propreties.get(NAMESPACE).toString())
                .withClientKeyPassphrase(System.getProperty(CLIENT_KEY_PASSPHRASE)).build();

        OpenShiftClient client = new DefaultOpenShiftClient(config);
        CustomResourceDefinition apiCRD = client.customResourceDefinitions().withName(API_CRD_NAME).get();

        NonNamespaceOperation<APICustomResourceDefinition, APICustomResourceDefinitionList,
                DoneableAPICustomResourceDefinition, Resource<APICustomResourceDefinition,
                DoneableAPICustomResourceDefinition>> crdClient = getCRDClient(client, apiCRD);

        crdClient.withName(apiName.toLowerCase()).cascading(true).delete();

        log.info("Successfully deleted the [API] " + apiName);
    } else {
        log.error("Error occurred while deleting API from Kubernetes cluster");
    }

}
 
Example #22
Source File: K8sManager.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the openshift client( This supprots both the Openshift and Kubernetes)
 */
private void setClient() {

    if (masterURL != null && saToken != null && namespace != null) {
        Config config = new ConfigBuilder().withMasterUrl(masterURL).withOauthToken(saToken).withNamespace(namespace)
                //Get keystore password to connect with local clusters
                .withClientKeyPassphrase(System.getProperty(CLIENT_KEY_PASSPHRASE)).build();

        this.openShiftClient = new DefaultOpenShiftClient(config);
    } else {
        log.error("Failed to make the connection to the cluster");
    }

}
 
Example #23
Source File: OpenshiftAPIServiceTest.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalSubjectAccessReviewForNonResourceURL() throws IOException{
    OkHttpClient okClient = mock(OkHttpClient.class);
    DefaultOpenShiftClient client = mock(DefaultOpenShiftClient.class);
    OpenShiftClientFactory factory = mock(OpenShiftClientFactory.class);
    Call call = mock(Call.class);
    when(factory.buildClient(anyString())).thenReturn(client);
    when(client.getHttpClient()).thenReturn(okClient);
    when(client.getMasterUrl()).thenReturn(new URL("https://localhost:8443/"));
    
    Response response = new Response.Builder()
            .request(new Request.Builder().url("https://localhost:8443").build())
            .code(201)
            .protocol(Protocol.HTTP_1_1)
            .message("")
            .body(ResponseBody.create(MediaType.parse("application/json;utf-8"), "{\"allowed\":true}"))
            .build();
    
    RequestAnswer answer = new RequestAnswer(call);
    when(okClient.newCall(any(Request.class))).thenAnswer(answer);
    when(call.execute()).thenReturn(response);
    
    service = new OpenshiftAPIService(factory );
    
    assertTrue(service.localSubjectAccessReview("sometoken", "openshift-logging", "get", "/metrics", null, ArrayUtils.EMPTY_STRING_ARRAY));
    Buffer buffer = new Buffer();
    answer.getRequest().body().writeTo(buffer);
    assertEquals("https://localhost:8443/apis/authorization.openshift.io/v1/subjectaccessreviews",answer.getRequest().url().toString());
    String exp = "{\"kind\":\"SubjectAccessReview\","
            + "\"apiVersion\":\"authorization.openshift.io/v1\",\"verb\":\"get\",\"scopes\":[],"
            + "\"isNonResourceURL\":true,\"path\":\"/metrics\"}";
    assertEquals(exp, new String(buffer.readByteArray()));
}
 
Example #24
Source File: OpenshiftAPIServiceTest.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalSubjectAccessReviewWhenNotNonResourceURL() throws IOException{
    OkHttpClient okClient = mock(OkHttpClient.class);
    DefaultOpenShiftClient client = mock(DefaultOpenShiftClient.class);
    OpenShiftClientFactory factory = mock(OpenShiftClientFactory.class);
    Call call = mock(Call.class);
    when(factory.buildClient(anyString())).thenReturn(client);
    when(client.getHttpClient()).thenReturn(okClient);
    when(client.getMasterUrl()).thenReturn(new URL("https://localhost:8443/"));
    
    Response response = new Response.Builder()
        .request(new Request.Builder().url("https://localhost:8443").build())
        .code(201)
        .protocol(Protocol.HTTP_1_1)
        .message("")
        .body(ResponseBody.create(MediaType.parse("application/json;utf-8"), "{\"allowed\":true}"))
        .build();

    RequestAnswer answer = new RequestAnswer(call);
    when(okClient.newCall(any(Request.class))).thenAnswer(answer);
    when(call.execute()).thenReturn(response);
    
    service = new OpenshiftAPIService(factory );
    
    assertTrue(service.localSubjectAccessReview("sometoken", "openshift-logging", "get", "pod/metrics", null, ArrayUtils.EMPTY_STRING_ARRAY));
    Buffer buffer = new Buffer();
    assertEquals("https://localhost:8443/apis/authorization.openshift.io/v1/subjectaccessreviews",answer.getRequest().url().toString());
    answer.getRequest().body().writeTo(buffer);
    String exp = "{\"kind\":\"SubjectAccessReview\","
            + "\"apiVersion\":\"authorization.openshift.io/v1\",\"verb\":\"get\",\"scopes\":[],\"resourceAPIGroup\":null,"
            + "\"resource\":\"pod/metrics\",\"namespace\":\"openshift-logging\"}";
    assertEquals(exp, new String(buffer.readByteArray()));
}
 
Example #25
Source File: OpenshiftAPIService.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Execute a LocalSubectAccessReview
 * 
 * @param token             a token to check
 * @param project           the namespace to check against
 * @param verb              the verb (e.g. view)
 * @param resource          the resource (e.g. pods/log)
 * @param resourceAPIGroup  the group of the resource being checked
 * @param scopes            the scopes:
 *                            null  - use token scopes
 *                            empty - remove scopes
 *                            list  - an array of scopes
 *                            
 * @return  true if the SAR is satisfied
 */
public boolean localSubjectAccessReview(final String token, 
        final String project, final String verb, final String resource, final String resourceAPIGroup, final String [] scopes) {
    try (DefaultOpenShiftClient client = factory.buildClient(token)) {
        XContentBuilder payload = XContentFactory.jsonBuilder()
            .startObject()
                .field("kind","SubjectAccessReview")
                .field("apiVersion","authorization.openshift.io/v1")
                .field("verb", verb)
                .array("scopes", scopes);
        if(resource.startsWith("/")) {
            payload.field("isNonResourceURL", Boolean.TRUE)
                .field("path", resource);
        } else {
            payload.field("resourceAPIGroup", resourceAPIGroup)
                .field("resource", resource)
                .field("namespace", project);
        }
        payload.endObject();
        Request request = new Request.Builder()
                .url(String.format("%sapis/authorization.openshift.io/v1/subjectaccessreviews", client.getMasterUrl(), project))
                .header("Authorization", "Bearer " + token)
                .header(CONTENT_TYPE, APPLICATION_JSON)
                .header(ACCEPT, APPLICATION_JSON)
                .post(RequestBody.create(MediaType.parse(APPLICATION_JSON), payload.string()))
                .build();
        log(request);
        Response response = client.getHttpClient().newCall(request).execute();
        final String body = IOUtils.toString(response.body().byteStream());
        log(response, body);
        if(response.code() != RestStatus.CREATED.getStatus()) {
            throw new ElasticsearchSecurityException("Unable to determine user's operations role", RestStatus.fromCode(response.code()));
        }
        return JsonPath.read(body, "$.allowed");
    } catch (IOException e) {
        LOGGER.error("Error determining user's role", e);
    }
    return false;
}
 
Example #26
Source File: OpenshiftBuildServiceTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testSuccessfulBuildNoS2iSuffix() throws Exception {
    retryInMockServer(() -> {
        BuildServiceConfig config = defaultConfig
                .s2iBuildNameSuffix(null)
                .build();
        // @formatter:on
        new Expectations() {{
            jKubeServiceHub.getBuildServiceConfig(); result = config;
        }};
        WebServerEventCollector<OpenShiftMockServer> collector = createMockServer(
            config, true, 50, false, false);
        OpenShiftMockServer mockServer = collector.getMockServer();

        DefaultOpenShiftClient client = (DefaultOpenShiftClient) mockServer.createOpenShiftClient();
        LOG.info("Current write timeout is : {}", client.getHttpClient().writeTimeoutMillis());
        LOG.info("Current read timeout is : {}", client.getHttpClient().readTimeoutMillis());
        LOG.info("Retry on failure : {}", client.getHttpClient().retryOnConnectionFailure());
        OpenshiftBuildService service = new OpenshiftBuildService(client, logger, jKubeServiceHub);
        service.build(image);

        // we should Foadd a better way to assert that a certain call has been made
        assertTrue(mockServer.getRequestCount() > 8);
        collector.assertEventsRecordedInOrder("build-config-check", "new-build-config", "pushed");
        assertEquals("{\"apiVersion\":\"build.openshift.io/v1\",\"kind\":\"BuildConfig\",\"metadata\":{\"name\":\"myapp-s2i\"},\"spec\":{\"output\":{\"to\":{\"kind\":\"ImageStreamTag\",\"name\":\"myapp:latest\"}},\"source\":{\"type\":\"Binary\"},\"strategy\":{\"sourceStrategy\":{\"forcePull\":false,\"from\":{\"kind\":\"DockerImage\",\"name\":\"myapp\"}},\"type\":\"Source\"}}}", collector.getBodies().get(1));
        collector.assertEventsNotRecorded("patch-build-config");
    });
}
 
Example #27
Source File: OpenshiftBuildServiceTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDockerBuild() throws Exception {
    retryInMockServer(() -> {
        BuildServiceConfig dockerConfig = BuildServiceConfig.builder()
                .buildDirectory(baseDir)
                .buildRecreateMode(BuildRecreateMode.none)
                .s2iBuildNameSuffix("-docker")
                .openshiftBuildStrategy(OpenShiftBuildStrategy.docker).build();
        // @formatter:on
        new Expectations() {{
            jKubeServiceHub.getBuildServiceConfig(); result = dockerConfig;
        }};
        // @formatter:off
        WebServerEventCollector<OpenShiftMockServer> collector = createMockServer(dockerConfig, true, 50,
                false, false);
        OpenShiftMockServer mockServer = collector.getMockServer();

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

        assertTrue(mockServer.getRequestCount() > 8);
        collector.assertEventsRecordedInOrder("build-config-check", "new-build-config", "pushed");
        assertEquals("{\"apiVersion\":\"build.openshift.io/v1\",\"kind\":\"BuildConfig\",\"metadata\":{\"name\":\"myapp-docker\"},\"spec\":{\"output\":{\"to\":{\"kind\":\"ImageStreamTag\",\"name\":\"myapp:latest\"}},\"source\":{\"type\":\"Binary\"},\"strategy\":{\"dockerStrategy\":{\"from\":{\"kind\":\"DockerImage\",\"name\":\"myapp\"},\"noCache\":false},\"type\":\"Docker\"}}}", collector.getBodies().get(1));
        collector.assertEventsNotRecorded("patch-build-config");
    });
}
 
Example #28
Source File: OpenshiftBuildServiceTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDockerBuildNoS2iSuffix() throws Exception {
    retryInMockServer(() -> {
        final BuildServiceConfig dockerConfig = BuildServiceConfig.builder()
                .buildDirectory(baseDir)
                .buildRecreateMode(BuildRecreateMode.none)
                .openshiftBuildStrategy(OpenShiftBuildStrategy.docker)
                .build();
        // @formatter:on
        new Expectations() {{
            jKubeServiceHub.getBuildServiceConfig(); result = dockerConfig;
        }};
        // @formatter:off
        WebServerEventCollector<OpenShiftMockServer> collector = createMockServer(dockerConfig, true, 50,
                false, false);
        OpenShiftMockServer mockServer = collector.getMockServer();

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

        assertTrue(mockServer.getRequestCount() > 8);
        collector.assertEventsRecordedInOrder("build-config-check", "new-build-config", "pushed");
        assertEquals("{\"apiVersion\":\"build.openshift.io/v1\",\"kind\":\"BuildConfig\",\"metadata\":{\"name\":\"myapp\"},\"spec\":{\"output\":{\"to\":{\"kind\":\"ImageStreamTag\",\"name\":\"myapp:latest\"}},\"source\":{\"type\":\"Binary\"},\"strategy\":{\"dockerStrategy\":{\"from\":{\"kind\":\"DockerImage\",\"name\":\"myapp\"},\"noCache\":false},\"type\":\"Docker\"}}}", collector.getBodies().get(1));
        collector.assertEventsNotRecorded("patch-build-config");
    });
}
 
Example #29
Source File: KnativeMetaDataSupport.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static List<String> listResources(CustomResourceDefinition crd) {
    try (OpenShiftClient client = new DefaultOpenShiftClient()) {
        return client.customResources(crd, KnativeResource.class, KnativeResourceList.class, KnativeResourceDoneable.class)
            .inNamespace(getTargetNamespace())
            .list()
            .getItems()
            .stream()
            .map(KnativeResource::getMetadata)
            .map(ObjectMeta::getName)
            .collect(Collectors.toList());
    }
}
 
Example #30
Source File: TemplateTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLoadTemplateWithNumberParameters() throws Exception {
  OpenShiftClient client = new DefaultOpenShiftClient(new OpenShiftConfigBuilder().build());
  Map<String, String> map = new HashMap<>();
  map.put("PORT", "8080");
  KubernetesList list = client.templates().withParameters(map).load(getClass().getResourceAsStream("/template-with-number-params.yml")).processLocally(map);
  assertListIsServiceWithPort8080(list);
}