io.fabric8.kubernetes.client.utils.URLUtils Java Examples

The following examples show how to use io.fabric8.kubernetes.client.utils.URLUtils. 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: OpenShiftConfig.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Buildable(builderPackage = "io.fabric8.kubernetes.api.builder", editableEnabled = false, refs = {@BuildableReference(Config.class)})
public OpenShiftConfig(String openShiftUrl, String oapiVersion, String masterUrl, String apiVersion, String namespace, Boolean trustCerts, Boolean disableHostnameVerification, String caCertFile, String caCertData, String clientCertFile, String clientCertData, String clientKeyFile, String clientKeyData, String clientKeyAlgo, String clientKeyPassphrase, String username, String password, String oauthToken, int watchReconnectInterval, int watchReconnectLimit, int connectionTimeout, int requestTimeout, long rollingTimeout, long scaleTimeout, int loggingInterval, Integer maxConcurrentRequestsPerHost, String httpProxy, String httpsProxy, String[] noProxy, Map<Integer, String> errorMessages, String userAgent, TlsVersion[] tlsVersions, long buildTimeout, long websocketTimeout, long websocketPingInterval, String proxyUsername, String proxyPassword, String trustStoreFile, String trustStorePassphrase, String keyStoreFile, String keyStorePassphrase, String impersonateUsername, String[] impersonateGroups, Map<String, List<String>> impersonateExtras, boolean openshiftApiGroupsEnabled, boolean disableApiGroupCheck) {
  super(masterUrl, apiVersion, namespace, trustCerts, disableHostnameVerification, caCertFile, caCertData, clientCertFile, clientCertData, clientKeyFile, clientKeyData, clientKeyAlgo, clientKeyPassphrase, username, password, oauthToken, watchReconnectInterval, watchReconnectLimit, connectionTimeout, requestTimeout, rollingTimeout, scaleTimeout, loggingInterval, maxConcurrentRequestsPerHost, httpProxy, httpsProxy, noProxy, errorMessages, userAgent, tlsVersions, websocketTimeout, websocketPingInterval, proxyUsername, proxyPassword, trustStoreFile, trustStorePassphrase, keyStoreFile, keyStorePassphrase, impersonateUsername, impersonateGroups, impersonateExtras);
  this.oapiVersion = oapiVersion;
  this.openShiftUrl = openShiftUrl;
  this.buildTimeout = buildTimeout;
  this.openshiftApiGroupsEnabled = openshiftApiGroupsEnabled;
  this.disableApiGroupCheck = openshiftApiGroupsEnabled ? false : disableApiGroupCheck;

  if (this.openShiftUrl == null || this.openShiftUrl.isEmpty()) {
    this.openShiftUrl = URLUtils.join(getMasterUrl(), "oapi", this.oapiVersion);
  }
  if (!this.openShiftUrl.endsWith("/")) {
    this.openShiftUrl = this.openShiftUrl + "/";
  }
}
 
Example #2
Source File: OpenshiftAdapterSupport.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
/**
 * Check if OpenShift API Groups are available
 * @param httpClient   The httpClient.
 * @param masterUrl    The master url.
 * @return             True if the new <code>/apis/*.openshift.io/</code> APIs are found in the root paths.
 */
static boolean isOpenShiftAPIGroups(OkHttpClient httpClient, String masterUrl) {
  try {
    Request.Builder requestBuilder = new Request.Builder()
      .get()
      .url(URLUtils.join(masterUrl, APIS));
    Response response = httpClient.newCall(requestBuilder.build()).execute();
    APIGroupList apiGroupList = Serialization.unmarshal(response.body().string(), APIGroupList.class);

    for (APIGroup apiGroup : apiGroupList.getGroups()) {
      if (apiGroup.getName().endsWith("openshift.io")) {
        return true;
      }
    }
  } catch(Exception e) {
    KubernetesClientException.launderThrowable(e);
  }
  return false;
}
 
Example #3
Source File: OpenshiftAdapterSupport.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
/**
 * Check if OpenShift API Groups are available
 * @param client   The client.
 * @return         True if the new <code>/apis/*.openshift.io/</code> APIs are found in the root paths.
 */
static boolean isOpenShiftAPIGroups(Client client) {
  URL masterUrl = client.getMasterUrl();

  OkHttpClient httpClient = ((BaseClient)client).getHttpClient();
  try {
    Request.Builder requestBuilder = new Request.Builder()
      .get()
      .url(URLUtils.join(masterUrl.toString(), APIS));
    Response response = httpClient.newCall(requestBuilder.build()).execute();
    APIGroupList apiGroupList = Serialization.unmarshal(response.body().string(), APIGroupList.class);

    for (APIGroup apiGroup : apiGroupList.getGroups()) {
      if (apiGroup.getName().endsWith("openshift.io")) {
        return true;
      }
    }
  } catch(Exception e) {
    KubernetesClientException.launderThrowable(e);
  }
  return false;
}
 
Example #4
Source File: PodUpload.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static URL buildCommandUrl(String command, PodOperationContext context, OperationSupport operationSupport)
  throws UnsupportedEncodingException, MalformedURLException {

  final StringBuilder commandBuilder = new StringBuilder();
  commandBuilder.append("exec?");
  commandBuilder.append("command=sh&command=-c");
  commandBuilder.append("&command=");
  commandBuilder.append(URLUtils.encodeToUTF(command));
  if (context.getContainerId() != null && !context.getContainerId().isEmpty()) {
    commandBuilder.append("&container=").append(context.getContainerId());
  }
  commandBuilder.append("&stdin=true");
  commandBuilder.append("&stderr=true");
  return new URL(
    URLUtils.join(operationSupport.getResourceUrl().toString(), commandBuilder.toString()));
}
 
Example #5
Source File: ServiceOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private String getUrlHelper(String portName) {
  ServiceLoader<ServiceToURLProvider> urlProvider = ServiceLoader.load(ServiceToURLProvider.class, Thread.currentThread().getContextClassLoader());
  Iterator<ServiceToURLProvider> iterator = urlProvider.iterator();
  List<ServiceToURLProvider> servicesList = new ArrayList<>();

  while(iterator.hasNext()) {
    servicesList.add(iterator.next());
  }

  // Sort all loaded implementations according to priority
  Collections.sort(servicesList, new ServiceToUrlSortComparator());
  for(ServiceToURLProvider serviceToURLProvider : servicesList) {
    String url = serviceToURLProvider.getURL(getMandatory(), portName, namespace, new DefaultKubernetesClient(client, getConfig()));
    if(url != null && URLUtils.isValidURL(url)) {
      return url;
    }
  }

  return null;
}
 
Example #6
Source File: ZipkinMinimalKubernetesTest.java    From kubernetes-zipkin with Apache License 2.0 5 votes vote down vote up
@Test
@RunAsClient
public void testConnectionToZipkinQuery() throws Exception {
    String url = URLUtils.join(KubernetesHelper.getServiceURL(service), "/api/v1/services");
    OkHttpClient httpClient = new OkHttpClient();
    try {
        Request request = new Request.Builder().get().url(url).build();
        Response response = httpClient.newCall(request).execute();
        Assert.assertNotNull(response);
        Assert.assertEquals(200, response.code());
    } finally {
        close(httpClient);
    }
}
 
Example #7
Source File: OpenShiftConfig.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private static String getDefaultOpenShiftUrl(Config config) {
  String openshiftUrl = Utils.getSystemPropertyOrEnvVar(OPENSHIFT_URL_SYSTEM_PROPERTY);
  if (openshiftUrl != null) {
    // The OPENSHIFT_URL environment variable may be set to the root url (i.e. without the '/oapi/version' path) in some configurations
    if (isRootURL(openshiftUrl)) {
      openshiftUrl = URLUtils.join(openshiftUrl, "oapi", getDefaultOapiVersion(config));
    }
    return openshiftUrl;
  } else {
    return URLUtils.join(config.getMasterUrl(), "oapi", getDefaultOapiVersion(config));
  }
}
 
Example #8
Source File: BuildOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public LogWatch watchLog(OutputStream out) {
  try {
    URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters() + "&follow=true"));
    Request request = new Request.Builder().url(url).get().build();
    final LogWatchCallback callback = new LogWatchCallback(out);
    OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build();
    clone.newCall(request).enqueue(callback);
    callback.waitUntilReady();
    return callback;
  } catch (Throwable t) {
    throw KubernetesClientException.launderThrowable(forOperationType("watchLog"), t);
  }
}
 
Example #9
Source File: BuildOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
protected ResponseBody doGetLog(){
  try {
    URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters()));
    Request.Builder requestBuilder = new Request.Builder().get().url(url);
    Request request = requestBuilder.build();
    Response response = client.newCall(request).execute();
    ResponseBody body = response.body();
    assertResponseCode(request, response);
    return body;
  } catch (Throwable t) {
    throw KubernetesClientException.launderThrowable(forOperationType("doGetLog"), t);
  }
}
 
Example #10
Source File: BuildConfigOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private String getQueryParameters() throws MalformedURLException {
  StringBuilder sb = new StringBuilder();
  sb.append(URLUtils.join(getResourceUrl().toString(), "instantiatebinary"));
  if (Utils.isNullOrEmpty(message)) {
    sb.append("?commit=");
  } else {
    sb.append("?commit=").append(message);
  }

  if (!Utils.isNullOrEmpty(authorName)) {
    sb.append("&revision.authorName=").append(authorName);
  }

  if (!Utils.isNullOrEmpty(authorEmail)) {
    sb.append("&revision.authorEmail=").append(authorEmail);
  }

  if (!Utils.isNullOrEmpty(committerName)) {
    sb.append("&revision.committerName=").append(committerName);
  }

  if (!Utils.isNullOrEmpty(committerEmail)) {
    sb.append("&revision.committerEmail=").append(committerEmail);
  }

  if (!Utils.isNullOrEmpty(commit)) {
    sb.append("&revision.commit=").append(commit);
  }

  if (!Utils.isNullOrEmpty(asFile)) {
    sb.append("&asFile=").append(asFile);
  }
  return sb.toString();
}
 
Example #11
Source File: BuildConfigOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Build instantiate(BuildRequest request) {
  try {
    updateApiVersion(request);
    URL instantiationUrl = new URL(URLUtils.join(getResourceUrl().toString(), "instantiate"));
    RequestBody requestBody = RequestBody.create(JSON, BaseOperation.JSON_MAPPER.writer().writeValueAsString(request));
    Request.Builder requestBuilder = new Request.Builder().post(requestBody).url(instantiationUrl);
    return handleResponse(requestBuilder, Build.class);
  } catch (Exception e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example #12
Source File: PodMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public PodMetricsList metrics(String namespace) {
  try {
    String resourceUrl = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL,
      "namespaces", namespace, "pods");
    return handleMetric(resourceUrl, PodMetricsList.class);
  } catch(Exception e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example #13
Source File: PodMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public PodMetricsList metrics() {
  try {
    String resourceUrl = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL, "pods");
    return handleMetric(resourceUrl, PodMetricsList.class);
  } catch(Exception e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example #14
Source File: PodMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public PodMetrics metrics(String namespace, String podName) {
  try {
    Utils.checkNotNull(namespace, "Namespace not provided");
    Utils.checkNotNull(podName, "Name not provided");

    String resourceUrl = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL,
      "namespaces", namespace, "pods", podName);
    return handleMetric(resourceUrl, PodMetrics.class);
  } catch(Exception e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example #15
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private void handleEvict(URL podUrl, String namespace, String name) throws ExecutionException, InterruptedException, IOException {
  Eviction eviction = new EvictionBuilder()
    .withNewMetadata()
    .withName(name)
    .withNamespace(namespace)
    .endMetadata()
    .withDeleteOptions(new DeleteOptions())
    .build();

  RequestBody requestBody = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(eviction));

  URL requestUrl = new URL(URLUtils.join(podUrl.toString(), "eviction"));
  Request.Builder requestBuilder = new Request.Builder().post(requestBody).url(requestUrl);
  handleResponse(requestBuilder, null, Collections.<String, String>emptyMap());
}
 
Example #16
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public LogWatch watchLog(OutputStream out) {
  try {
    URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters() + "&follow=true"));
    Request request = new Request.Builder().url(url).get().build();
    final LogWatchCallback callback = new LogWatchCallback(out);
    OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build();
    clone.newCall(request).enqueue(callback);
    callback.waitUntilReady();
    return callback;
  } catch (Throwable t) {
    throw KubernetesClientException.launderThrowable(forOperationType("watchLog"), t);
  }
}
 
Example #17
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
protected ResponseBody doGetLog(){
  try {
    URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters()));
    Request.Builder requestBuilder = new Request.Builder().get().url(url);
    Request request = requestBuilder.build();
    Response response = client.newCall(request).execute();
    ResponseBody body = response.body();
    assertResponseCode(request, response);
    return body;
  } catch (Throwable t) {
    throw KubernetesClientException.launderThrowable(forOperationType("doGetLog"), t);
  }
}
 
Example #18
Source File: NodeMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public NodeMetricsList metrics(Map<String, Object> labelsMap) {
	try {
     HttpUrl.Builder httpUrlBuilder = HttpUrl.get(URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL)).newBuilder();

     StringBuilder sb = new StringBuilder();
		for(Map.Entry<String, Object> entry : labelsMap.entrySet()) {
			sb.append(entry.getKey()).append("=").append(entry.getValue().toString()).append(",");
		}
     httpUrlBuilder.addQueryParameter("labelSelector", sb.toString().substring(0, sb.toString().length() - 1));
		return handleMetric(httpUrlBuilder.build().toString(), NodeMetricsList.class);
	} catch(Exception e) {
		throw KubernetesClientException.launderThrowable(e);
	}
}
 
Example #19
Source File: NodeMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public NodeMetrics metrics(String nodeName) {
	try {
		String resourceUrl = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL, nodeName);
		return handleMetric(resourceUrl, NodeMetrics.class);
	} catch(Exception e) {
		throw KubernetesClientException.launderThrowable(e);
	}
}
 
Example #20
Source File: NodeMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public NodeMetricsList metrics() {
	try {
		String resourceUrl = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL);
		return handleMetric(resourceUrl, NodeMetricsList.class);
	} catch(Exception e) {
		throw KubernetesClientException.launderThrowable(e);
	}
}
 
Example #21
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public URL getRootUrl() {
  try {
    if (!Utils.isNullOrEmpty(apiGroupName)) {
      return new URL(URLUtils.join(config.getMasterUrl().toString(), "apis", apiGroupName, apiGroupVersion));
    }
    return new URL(URLUtils.join(config.getMasterUrl().toString(), "api", apiGroupVersion));
  } catch (MalformedURLException e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example #22
Source File: BaseOperationTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testListOptions() throws MalformedURLException {
  // Given
  URL url = new URL("https://172.17.0.2:8443/api/v1/namespaces/default/pods");
  final BaseOperation<Pod, PodList, DoneablePod, Resource<Pod, DoneablePod>> operation = new BaseOperation<>(new OperationContext());

  // When and Then
  assertEquals(URLUtils.join(url.toString(), "?limit=5"),
    operation.fetchListUrl(url, new ListOptionsBuilder()
      .withLimit(5L)
      .build()).toString());
  assertEquals(URLUtils.join(url.toString(), "?limit=5&continue=eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ"),
    operation.fetchListUrl(url, new ListOptionsBuilder()
      .withLimit(5L)
      .withContinue("eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ")
      .build()).toString());
  assertEquals(URLUtils.join(url.toString(), "?limit=5&continue=eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ&fieldSelector=status.phase%3DRunning"),
    operation.fetchListUrl(url, new ListOptionsBuilder()
      .withLimit(5L)
      .withContinue("eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ")
      .withFieldSelector("status.phase=Running")
      .build()).toString());
  assertEquals(URLUtils.join(url.toString(), "?limit=5&continue=eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ&resourceVersion=210448&fieldSelector=status.phase%3DRunning"),
    operation.fetchListUrl(url, new ListOptionsBuilder()
      .withLimit(5L)
      .withContinue("eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ")
      .withFieldSelector("status.phase=Running")
      .withResourceVersion("210448")
      .build()).toString());
  assertEquals(URLUtils.join(url.toString(), "?limit=5&continue=eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ&resourceVersion=210448&labelSelector=%21node-role.kubernetes.io%2Fmaster"),
    operation.fetchListUrl(url, new ListOptionsBuilder()
      .withLimit(5L)
      .withContinue("eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ")
      .withLabelSelector("!node-role.kubernetes.io/master")
      .withResourceVersion("210448")
      .build()).toString());
  assertEquals(URLUtils.join(url.toString(), "?limit=5&continue=eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ&resourceVersion=210448&labelSelector=%21node-role.kubernetes.io%2Fmaster&timeoutSeconds=10"),
    operation.fetchListUrl(url, new ListOptionsBuilder()
      .withLimit(5L)
      .withContinue("eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ")
      .withLabelSelector("!node-role.kubernetes.io/master")
      .withResourceVersion("210448")
      .withTimeoutSeconds(10L)
      .build()).toString());
  assertEquals(URLUtils.join(url.toString(), "?limit=5&continue=eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ&resourceVersion=210448&labelSelector=%21node-role.kubernetes.io%2Fmaster&timeoutSeconds=10&allowWatchBookmarks=true"),
    operation.fetchListUrl(url, new ListOptionsBuilder()
      .withLimit(5L)
      .withContinue("eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ")
      .withLabelSelector("!node-role.kubernetes.io/master")
      .withResourceVersion("210448")
      .withTimeoutSeconds(10L)
      .withAllowWatchBookmarks(true)
      .build()).toString());
  assertEquals(URLUtils.join(url.toString(), "?limit=5&continue=eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ&resourceVersion=210448&labelSelector=%21node-role.kubernetes.io%2Fmaster&timeoutSeconds=10&allowWatchBookmarks=true&watch=true"),
    operation.fetchListUrl(url, new ListOptionsBuilder()
      .withLimit(5L)
      .withContinue("eyJ2IjoibWV0YS5rOHMuaW8vdjEiLCJydiI6MjE0NDUzLCJzdGFydCI6ImV0Y2QtbWluaWt1YmVcdTAwMDAifQ")
      .withLabelSelector("!node-role.kubernetes.io/master")
      .withResourceVersion("210448")
      .withTimeoutSeconds(10L)
      .withAllowWatchBookmarks(true)
      .withWatch(true)
      .build()).toString());
  assertEquals(URLUtils.join(url.toString(), "?resourceVersion=210448"), operation.fetchListUrl(url, new ListOptionsBuilder()
    .withResourceVersion("210448")
    .build()).toString());
  assertEquals(URLUtils.join(url.toString(), "?timeoutSeconds=10"), operation.fetchListUrl(url, new ListOptionsBuilder()
    .withTimeoutSeconds(10L)
    .build()).toString());
  assertEquals(URLUtils.join(url.toString(), "?watch=true"), operation.fetchListUrl(url, new ListOptionsBuilder()
    .withWatch(true)
    .build()).toString());
}
 
Example #23
Source File: ClusterOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private Response handleVersionGet(String versionEndpointToBeUsed) throws IOException {
  Request.Builder requestBuilder = new Request.Builder()
    .get()
    .url(URLUtils.join(config.getMasterUrl(), versionEndpointToBeUsed));
  return client.newCall(requestBuilder.build()).execute();
}
 
Example #24
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public URL getResourceUrl() throws MalformedURLException {
  if (name == null) {
    return getNamespacedUrl();
  }
  return new URL(URLUtils.join(getNamespacedUrl().toString(), name));
}
 
Example #25
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public URL getResourceUrl(String namespace, String name) throws MalformedURLException {
  if (name == null) {
    return getNamespacedUrl(namespace);
  }
  return new URL(URLUtils.join(getNamespacedUrl(namespace).toString(), name));
}
 
Example #26
Source File: OpenShiftClientFactory.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected Interceptor buildKubernetesInterceptor(Config config) {
  final String oauthToken;
  if (Utils.isNotNullOrEmpty(config.getUsername())
      && Utils.isNotNullOrEmpty(config.getPassword())) {
    synchronized (getHttpClient()) {
      try {
        OkHttpClient.Builder builder = getHttpClient().newBuilder();
        builder.interceptors().clear();
        OkHttpClient clone = builder.build();

        String credential = Credentials.basic(config.getUsername(), config.getPassword());
        URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZE_PATH));
        Response response =
            clone
                .newCall(
                    new Request.Builder()
                        .get()
                        .url(url)
                        .header(AUTHORIZATION, credential)
                        .build())
                .execute();

        // False positive warn: according to javadocs response.body() returns non-null value
        // if called after Call.execute()
        response.body().close();
        response = response.priorResponse() != null ? response.priorResponse() : response;
        response = response.networkResponse() != null ? response.networkResponse() : response;
        String token = response.header(LOCATION);
        if (token == null || token.isEmpty()) {
          throw new KubernetesClientException(
              "Unexpected response ("
                  + response.code()
                  + " "
                  + response.message()
                  + "), to the authorization request. Missing header:["
                  + LOCATION
                  + "]!");
        }
        token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length());
        token = token.substring(0, token.indexOf(AFTER_TOKEN));
        oauthToken = token;
      } catch (Exception e) {
        throw KubernetesClientException.launderThrowable(e);
      }
    }
  } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) {
    oauthToken = config.getOauthToken();
  } else {
    oauthToken = null;
  }

  return chain -> {
    Request request = chain.request();
    if (isNotNullOrEmpty(oauthToken)) {
      Request authReq =
          chain.request().newBuilder().addHeader("Authorization", "Bearer " + oauthToken).build();
      return chain.proceed(authReq);
    }
    return chain.proceed(request);
  };
}
 
Example #27
Source File: CustomResourceCondition.java    From dekorate with Apache License 2.0 4 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
 Optional<OnCustomResourcePresentCondition> annotation = context.getElement().map(e -> e.getAnnotation(OnCustomResourcePresentCondition.class));
 if (!annotation.isPresent()) {
  return ConditionEvaluationResult.enabled("Condition not found!");
 }
 OnCustomResourcePresentCondition condition = annotation.get();
  try {
    String apiVersion = condition.apiVersion();
    String kind = condition.kind();
    String plural = Strings.isNotNullOrEmpty(condition.plural()) ? condition.plural() : Pluralize.FUNCTION.apply(kind).toLowerCase();
    String name = condition.name();
    String namespace = condition.namespace();

    KubernetesClient client = getKubernetesClient(context);
    Config config = client.getConfiguration();
    OkHttpClient http = client.adapt(OkHttpClient.class);

    List<String> parts = new ArrayList<>();
    parts.add(config.getMasterUrl());
    parts.add("apis");
    parts.add(apiVersion);

    if (Strings.isNotNullOrEmpty(namespace)) {
      parts.add("namespaces");
      parts.add(namespace);
    }

    parts.add(plural);
    if (Strings.isNotNullOrEmpty(name)) {
      parts.add(name);
    }
    parts.add(plural);
    String requestUrl = URLUtils.join(parts.stream().toArray(s->new String[s]));
    Request request = new Request.Builder().get().url(requestUrl).build();
    Response response = http.newCall(request).execute();

    if (!response.isSuccessful()) {
      return ConditionEvaluationResult.disabled("Could not lookup custom resource.");
    }


    //TODO: Add support for cases where name() is empty. In this case the result will be a list.
    //We need to check if empty.
    return ConditionEvaluationResult.enabled("Found resource with apiVersion:" + apiVersion + " kind:" + kind + " namespace: " + (Strings.isNullOrEmpty(namespace) ? "any" : namespace) + " name: " + (Strings.isNullOrEmpty(name) ? "any" : name));

  } catch (Throwable t) {
    return ConditionEvaluationResult.disabled("Could not lookup for service.");
  }
}
 
Example #28
Source File: ManagedOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Activate
public void activate(Map<String, Object> properties) {
  final OpenShiftConfigBuilder builder = new OpenShiftConfigBuilder();

  if (properties.containsKey(KUBERNETES_MASTER_SYSTEM_PROPERTY)) {
    builder.withMasterUrl((String) properties.get(KUBERNETES_MASTER_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_API_VERSION_SYSTEM_PROPERTY)) {
    builder.withApiVersion((String) properties.get(KUBERNETES_API_VERSION_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_NAMESPACE_SYSTEM_PROPERTY)) {
    builder.withNamespace((String) properties.get(KUBERNETES_NAMESPACE_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_CA_CERTIFICATE_FILE_SYSTEM_PROPERTY)) {
    builder.withCaCertFile((String) properties.get(KUBERNETES_CA_CERTIFICATE_FILE_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_CA_CERTIFICATE_DATA_SYSTEM_PROPERTY)) {
    builder.withCaCertData((String) properties.get(KUBERNETES_CA_CERTIFICATE_DATA_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_CLIENT_CERTIFICATE_FILE_SYSTEM_PROPERTY)) {
    builder.withClientCertFile((String) properties.get(KUBERNETES_CLIENT_CERTIFICATE_FILE_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_CLIENT_CERTIFICATE_DATA_SYSTEM_PROPERTY)) {
    builder.withClientCertData((String) properties.get(KUBERNETES_CLIENT_CERTIFICATE_DATA_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_CLIENT_KEY_FILE_SYSTEM_PROPERTY)) {
    builder.withClientKeyFile((String) properties.get(KUBERNETES_CLIENT_KEY_FILE_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_CLIENT_KEY_DATA_SYSTEM_PROPERTY)) {
    builder.withClientKeyData((String) properties.get(KUBERNETES_CLIENT_KEY_DATA_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_CLIENT_KEY_ALGO_SYSTEM_PROPERTY)) {
    builder.withClientKeyAlgo((String) properties.get(KUBERNETES_CLIENT_KEY_ALGO_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_CLIENT_KEY_PASSPHRASE_SYSTEM_PROPERTY)) {
    builder.withClientKeyPassphrase((String) properties.get(KUBERNETES_CLIENT_KEY_PASSPHRASE_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_AUTH_BASIC_USERNAME_SYSTEM_PROPERTY)) {
    builder.withUsername((String) properties.get(KUBERNETES_AUTH_BASIC_USERNAME_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_AUTH_BASIC_PASSWORD_SYSTEM_PROPERTY)) {
    builder.withPassword((String) properties.get(KUBERNETES_AUTH_BASIC_PASSWORD_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_OAUTH_TOKEN_SYSTEM_PROPERTY)) {
    builder.withOauthToken((String) properties.get(KUBERNETES_OAUTH_TOKEN_SYSTEM_PROPERTY));
  }
  if (properties.containsKey(KUBERNETES_WATCH_RECONNECT_INTERVAL_SYSTEM_PROPERTY)) {
    builder.withWatchReconnectInterval(Integer.parseInt((String) properties.get(KUBERNETES_WATCH_RECONNECT_INTERVAL_SYSTEM_PROPERTY)));
  }
  if (properties.containsKey(KUBERNETES_WATCH_RECONNECT_LIMIT_SYSTEM_PROPERTY)) {
    builder.withWatchReconnectLimit(Integer.parseInt((String) properties.get(KUBERNETES_WATCH_RECONNECT_LIMIT_SYSTEM_PROPERTY)));
  }
  if (properties.containsKey(KUBERNETES_REQUEST_TIMEOUT_SYSTEM_PROPERTY)) {
    builder.withRequestTimeout(Integer.parseInt((String) properties.get(KUBERNETES_REQUEST_TIMEOUT_SYSTEM_PROPERTY)));
  }
  if (properties.containsKey(KUBERNETES_HTTP_PROXY)) {
    builder.withHttpProxy((String) properties.get(KUBERNETES_HTTP_PROXY));
  }
  if (properties.containsKey(KUBERNETES_HTTPS_PROXY)) {
    builder.withHttpsProxy((String) properties.get(KUBERNETES_HTTPS_PROXY));
  }
  if (properties.containsKey(KUBERNETES_NO_PROXY)) {
    String noProxyProperty = (String) properties.get(KUBERNETES_NO_PROXY);
    builder.withNoProxy(noProxyProperty.split(","));
  }
  if (properties.containsKey(OPENSHIFT_URL_SYSTEM_PROPERTY)) {
    builder.withOpenShiftUrl((String) properties.get(OPENSHIFT_URL_SYSTEM_PROPERTY));
  } else {
    builder.withOpenShiftUrl(URLUtils.join(builder.getMasterUrl(), "oapi", builder.getOapiVersion()));
  }
  if (properties.containsKey(OPENSHIFT_BUILD_TIMEOUT_SYSTEM_PROPERTY)) {
    builder.withBuildTimeout(Integer.parseInt((String) properties.get(OPENSHIFT_BUILD_TIMEOUT_SYSTEM_PROPERTY)));
  } else {
    builder.withBuildTimeout(DEFAULT_BUILD_TIMEOUT);
  }
  if (properties.containsKey(KUBERNETES_WEBSOCKET_TIMEOUT_SYSTEM_PROPERTY)) {
    builder.withWebsocketTimeout(Long.parseLong((String) properties.get(KUBERNETES_WEBSOCKET_TIMEOUT_SYSTEM_PROPERTY)));
  }
  if (properties.containsKey(KUBERNETES_WEBSOCKET_PING_INTERVAL_SYSTEM_PROPERTY)) {
    builder.withWebsocketPingInterval(Long.parseLong((String) properties.get(KUBERNETES_WEBSOCKET_PING_INTERVAL_SYSTEM_PROPERTY)));
  }

  delegate = new DefaultOpenShiftClient(builder.build());
}