protected <T> String checkNamespace(T item) {
   String operationNs = getNamespace();
   String itemNs =
       item instanceof HasMetadata ? ((HasMetadata) item).getMetadata().getNamespace() : null;
   if (Utils.isNullOrEmpty(operationNs) && Utils.isNullOrEmpty(itemNs)) {
     if (!isNamespaceRequired()) {
       return null;
     } else {
       throw new KubernetesClientException(
           "Namespace not specified. But operation requires namespace.");
     }
   } else if (Utils.isNullOrEmpty(itemNs)) {
     return operationNs;
   } else if (Utils.isNullOrEmpty(operationNs)) {
     return itemNs;
   } else if (itemNs.equals(operationNs)) {
     return itemNs;
   }
   throw new KubernetesClientException(
       "Namespace mismatch. Item namespace:"
           + itemNs
           + ". Operation namespace:"
           + operationNs
           + ".");
 }
 protected <T> String checkName(T item) {
   String operationName = getName();
   String itemName =
       item instanceof HasMetadata ? ((HasMetadata) item).getMetadata().getName() : null;
   if (Utils.isNullOrEmpty(operationName) && Utils.isNullOrEmpty(itemName)) {
     return null;
   } else if (Utils.isNullOrEmpty(itemName)) {
     return operationName;
   } else if (Utils.isNullOrEmpty(operationName)) {
     return itemName;
   } else if (itemName.equals(operationName)) {
     return itemName;
   }
   throw new KubernetesClientException(
       "Name mismatch. Item name:" + itemName + ". Operation name:" + operationName + ".");
 }
Exemple #3
0
 private static Long getLongProperty(String name, Map<String, String> map, Long defaultValue) {
   if (map.containsKey(name)) {
     return Long.parseLong(map.get(name));
   } else {
     return Long.parseLong(Utils.getSystemPropertyOrEnvVar(name, String.valueOf(defaultValue)));
   }
 }
Exemple #4
0
 private static Boolean getBooleanProperty(
     String name, Map<String, String> map, Boolean defaultValue) {
   if (map.containsKey(name)) {
     return Boolean.parseBoolean(map.get(name));
   } else {
     return Utils.getSystemPropertyOrEnvVar(name, defaultValue);
   }
 }
Exemple #5
0
 private static String getStringProperty(
     String name, Map<String, String> map, String defaultValue) {
   if (map.containsKey(name)) {
     return map.get(name);
   } else {
     return Utils.getSystemPropertyOrEnvVar(name, defaultValue);
   }
 }
  @Override
  public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    // Build new request
    Request.Builder builder = request.newBuilder();
    builder.header("Accept", "application/json");

    String token = oauthToken.get();
    if (Utils.isNotNullOrEmpty(token)) {
      setAuthHeader(builder, token);
    }

    request = builder.build();
    Response response = chain.proceed(request);

    // If response is Forbidden or Unauthorized, try to obtain a token via authorize() or via
    // config.
    if (response.code() != 401 && response.code() != 403) {
      return response;
    } else if (Utils.isNotNullOrEmpty(config.getUsername())
        && Utils.isNotNullOrEmpty(config.getPassword())) {
      synchronized (client) {
        token = authorize();
        if (token != null) {
          oauthToken.set(token);
        }
      }
    } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) {
      token = config.getOauthToken();
      oauthToken.set(token);
    }

    // If token was obtain, then retry request using the obtained token.
    if (Utils.isNotNullOrEmpty(token)) {
      // Close the previous response to prevent leaked connections.
      response.body().close();

      setAuthHeader(builder, token);
      request = builder.build();
      return chain.proceed(request); // repeat request with new token
    } else {
      return response;
    }
  }
Exemple #7
0
 /**
  * Applies the kubernetes json url to the configuration.
  *
  * @param map The arquillian configuration.
  */
 private static URL getKubernetesConfigurationUrl(Map<String, String> map)
     throws MalformedURLException {
   if (map.containsKey(ENVIRONMENT_CONFIG_URL)) {
     return new URL(map.get(ENVIRONMENT_CONFIG_URL));
   } else if (map.containsKey(ENVIRONMENT_CONFIG_RESOURCE_NAME)) {
     String resourceName = map.get(ENVIRONMENT_CONFIG_RESOURCE_NAME);
     return findConfigResource(resourceName);
   } else if (Strings.isNotBlank(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, ""))) {
     return new URL(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, ""));
   } else {
     String defaultValue = "/" + DEFAULT_CONFIG_FILE_NAME;
     String resourceName =
         Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, defaultValue);
     URL answer = findConfigResource(resourceName);
     if (answer == null) {}
     return answer;
   }
 }
@Component(
    immediate = true,
    configurationPid = "io.fabric8.openshift.client",
    policy = ConfigurationPolicy.OPTIONAL)
@Service(OpenShiftClient.class)
public class ManagedOpenShiftClient extends BaseClient implements OpenShiftClient {

  @Property(name = OPENSHIFT_URL_SYTEM_PROPERTY)
  private String openshiftUrl = Utils.getSystemPropertyOrEnvVar(OPENSHIFT_URL_SYTEM_PROPERTY);

  @Property(name = KUBERNETES_OAPI_VERSION_SYSTEM_PROPERTY, value = "v1")
  private String oapiVersion =
      Utils.getSystemPropertyOrEnvVar(KUBERNETES_OAPI_VERSION_SYSTEM_PROPERTY);

  @Property(
      name = KUBERNETES_MASTER_SYSTEM_PROPERTY,
      description = "Master URL",
      value = "https://kubernetes.default.svc")
  private String masterUrl =
      Utils.getSystemPropertyOrEnvVar(
          Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, "https://kubernetes.default.svc");

  @Property(
      name = KUBERNETES_API_VERSION_SYSTEM_PROPERTY,
      description = "Api Version",
      value = "v1")
  private String apiVersion =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_API_VERSION_SYSTEM_PROPERTY, "v1");

  @Property(
      name = KUBERNETES_NAMESPACE_SYSTEM_PROPERTY,
      description = "Default namespace",
      value = "default")
  private String namespace =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_NAMESPACE_SYSTEM_PROPERTY, "default");

  @Property(
      name = KUBERNETES_CA_CERTIFICATE_FILE_SYSTEM_PROPERTY,
      description = "CA Certificate (Path to file)")
  private String caCertFile =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_CA_CERTIFICATE_FILE_SYSTEM_PROPERTY);

  @Property(
      name = KUBERNETES_CA_CERTIFICATE_DATA_SYSTEM_PROPERTY,
      description = "CA Certificate (Data)")
  private String caCertData =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_CA_CERTIFICATE_DATA_SYSTEM_PROPERTY);

  @Property(
      name = KUBERNETES_CLIENT_CERTIFICATE_FILE_SYSTEM_PROPERTY,
      description = "Client Certificate (Path to file)")
  private String clientCertFile =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_CLIENT_CERTIFICATE_FILE_SYSTEM_PROPERTY);

  @Property(
      name = KUBERNETES_CLIENT_CERTIFICATE_DATA_SYSTEM_PROPERTY,
      description = "Client Certificate (Data)")
  private String clientCertData =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_CLIENT_CERTIFICATE_DATA_SYSTEM_PROPERTY);

  @Property(
      name = KUBERNETES_CLIENT_KEY_FILE_SYSTEM_PROPERTY,
      description = "Client Key (Path to file)")
  private String clientKeyFile =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_CLIENT_KEY_FILE_SYSTEM_PROPERTY);

  @Property(name = KUBERNETES_CLIENT_KEY_DATA_SYSTEM_PROPERTY, description = "Client Key (Data)")
  private String clientKeyData =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_CLIENT_KEY_DATA_SYSTEM_PROPERTY);

  @Property(name = KUBERNETES_CLIENT_KEY_ALGO_SYSTEM_PROPERTY, description = "Client Key Algorithm")
  private String clientKeyAlgo =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_CLIENT_KEY_ALGO_SYSTEM_PROPERTY, "RSA");

  @Property(
      name = KUBERNETES_CLIENT_KEY_PASSPHRASE_SYSTEM_PROPERTY,
      description = "Client passphrase")
  private String clientKeyPassphrase =
      Utils.getSystemPropertyOrEnvVar(
          Config.KUBERNETES_CLIENT_KEY_PASSPHRASE_SYSTEM_PROPERTY, "changeit");

  @Property(name = KUBERNETES_AUTH_BASIC_USERNAME_SYSTEM_PROPERTY, description = "Username")
  private String username =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_AUTH_BASIC_USERNAME_SYSTEM_PROPERTY);

  @Property(name = KUBERNETES_AUTH_BASIC_PASSWORD_SYSTEM_PROPERTY, description = "Username")
  private String password =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_AUTH_BASIC_PASSWORD_SYSTEM_PROPERTY);

  @Property(name = KUBERNETES_OAUTH_TOKEN_SYSTEM_PROPERTY, description = "OAuth Token")
  private String oauthToken =
      Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_OAUTH_TOKEN_SYSTEM_PROPERTY);

  @Property(
      name = KUBERNETES_WATCH_RECONNECT_INTERVAL_SYSTEM_PROPERTY,
      description = "Watch reconnect interval",
      intValue = 1000)
  private int watchReconnectInterval =
      Integer.parseInt(
          Utils.getSystemPropertyOrEnvVar(
              Config.KUBERNETES_WATCH_RECONNECT_INTERVAL_SYSTEM_PROPERTY, "1000"));

  @Property(
      name = KUBERNETES_WATCH_RECONNECT_LIMIT_SYSTEM_PROPERTY,
      description = "Watch reconnect limit",
      intValue = -1)
  private int watchReconnectLimit =
      Integer.parseInt(
          Utils.getSystemPropertyOrEnvVar(
              Config.KUBERNETES_WATCH_RECONNECT_LIMIT_SYSTEM_PROPERTY, "-1"));

  @Property(
      name = KUBERNETES_REQUEST_TIMEOUT_SYSTEM_PROPERTY,
      description = "Request timeout",
      intValue = 10000)
  private int requestTimeout =
      Integer.parseInt(
          Utils.getSystemPropertyOrEnvVar(
              Config.KUBERNETES_REQUEST_TIMEOUT_SYSTEM_PROPERTY, "10000"));

  @Property(name = KUBERNETES_HTTP_PROXY, description = "HTTP Proxy")
  private String httpProxy = Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_HTTP_PROXY);

  @Property(name = KUBERNETES_HTTPS_PROXY, description = "HTTPS Proxy")
  private String httpsProxy = Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_HTTPS_PROXY);

  @Property(name = KUBERNETES_ALL_PROXY, description = "All Proxy")
  private String allProxy = Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_ALL_PROXY);

  @Property(name = KUBERNETES_NO_PROXY, description = "No Proxy")
  private String noProxy = Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_NO_PROXY);

  @Property(
      name = KUBERNETES_TRUST_CERT_SYSTEM_PROPERTY,
      description = "Kubernetes trust certifacates flag",
      boolValue = false)
  private Boolean trustCerts =
      Utils.getSystemPropertyOrEnvVar(KUBERNETES_TRUST_CERT_SYSTEM_PROPERTY, Boolean.FALSE);

  private OpenShiftClient delegate;

  @Activate
  public void activate(Map<String, Object> properties) {
    String masterUrl = (String) properties.get(KUBERNETES_MASTER_SYSTEM_PROPERTY);

    String openshiftUrl = (String) properties.get(OPENSHIFT_URL_SYTEM_PROPERTY);
    String oapiVersion = (String) properties.get(OPENSHIFT_URL_SYTEM_PROPERTY);

    String noProxyProperty = (String) properties.get(KUBERNETES_NO_PROXY);
    String[] noProxy = noProxyProperty != null ? noProxyProperty.split(",") : null;

    OpenShiftConfig config =
        new OpenShiftConfigBuilder()
            .withMasterUrl(masterUrl)
            .withApiVersion((String) properties.get(KUBERNETES_API_VERSION_SYSTEM_PROPERTY))
            .withNamespace((String) properties.get(KUBERNETES_NAMESPACE_SYSTEM_PROPERTY))
            .withCaCertFile((String) properties.get(KUBERNETES_CA_CERTIFICATE_FILE_SYSTEM_PROPERTY))
            .withCaCertData((String) properties.get(KUBERNETES_CA_CERTIFICATE_DATA_SYSTEM_PROPERTY))
            .withClientCertFile(
                (String) properties.get(KUBERNETES_CLIENT_CERTIFICATE_FILE_SYSTEM_PROPERTY))
            .withClientCertData(
                (String) properties.get(KUBERNETES_CLIENT_CERTIFICATE_DATA_SYSTEM_PROPERTY))
            .withClientKeyFile((String) properties.get(KUBERNETES_CLIENT_KEY_FILE_SYSTEM_PROPERTY))
            .withClientKeyData((String) properties.get(KUBERNETES_CLIENT_KEY_DATA_SYSTEM_PROPERTY))
            .withClientKeyAlgo((String) properties.get(KUBERNETES_CLIENT_KEY_ALGO_SYSTEM_PROPERTY))
            .withClientKeyPassphrase(
                (String) properties.get(KUBERNETES_CLIENT_KEY_PASSPHRASE_SYSTEM_PROPERTY))
            .withUsername((String) properties.get(KUBERNETES_AUTH_BASIC_USERNAME_SYSTEM_PROPERTY))
            .withPassword((String) properties.get(KUBERNETES_AUTH_BASIC_PASSWORD_SYSTEM_PROPERTY))
            .withOauthToken((String) properties.get(KUBERNETES_OAUTH_TOKEN_SYSTEM_PROPERTY))
            .withWatchReconnectInterval(
                (int) properties.get(KUBERNETES_WATCH_RECONNECT_INTERVAL_SYSTEM_PROPERTY))
            .withWatchReconnectLimit(
                (int) properties.get(KUBERNETES_WATCH_RECONNECT_LIMIT_SYSTEM_PROPERTY))
            .withRequestTimeout((int) properties.get(KUBERNETES_REQUEST_TIMEOUT_SYSTEM_PROPERTY))
            .withHttpProxy((String) properties.get(KUBERNETES_HTTP_PROXY))
            .withHttpsProxy((String) properties.get(KUBERNETES_HTTPS_PROXY))
            .withNoProxy(noProxy)
            .withOpenShiftUrl(
                (openshiftUrl != null && !openshiftUrl.isEmpty())
                    ? openshiftUrl
                    : URLUtils.join(masterUrl, "oapi", oapiVersion))
            .build();

    delegate = new DefaultOpenShiftClient(config);
  }

  @Deactivate
  public void deactivate() {
    delegate.close();
  }

  @Override
  public URL getOpenshiftUrl() {
    return delegate.getOpenshiftUrl();
  }

  @Override
  public ClientMixedOperation<Build, BuildList, DoneableBuild, ClientResource<Build, DoneableBuild>>
      builds() {
    return delegate.builds();
  }

  @Override
  public ClientMixedOperation<
          BuildConfig,
          BuildConfigList,
          DoneableBuildConfig,
          ClientBuildConfigResource<BuildConfig, DoneableBuildConfig, Void, Void>>
      buildConfigs() {
    return delegate.buildConfigs();
  }

  @Override
  public ClientMixedOperation<
          DeploymentConfig,
          DeploymentConfigList,
          DoneableDeploymentConfig,
          ClientResource<DeploymentConfig, DoneableDeploymentConfig>>
      deploymentConfigs() {
    return delegate.deploymentConfigs();
  }

  @Override
  public ClientNonNamespaceOperation<
          Group, GroupList, DoneableGroup, ClientResource<Group, DoneableGroup>>
      groups() {
    return delegate.groups();
  }

  @Override
  public ClientMixedOperation<
          ImageStream,
          ImageStreamList,
          DoneableImageStream,
          ClientResource<ImageStream, DoneableImageStream>>
      imageStreams() {
    return delegate.imageStreams();
  }

  @Override
  public ClientNonNamespaceOperation<
          OAuthAccessToken,
          OAuthAccessTokenList,
          DoneableOAuthAccessToken,
          ClientResource<OAuthAccessToken, DoneableOAuthAccessToken>>
      oAuthAccessTokens() {
    return delegate.oAuthAccessTokens();
  }

  @Override
  public ClientNonNamespaceOperation<
          OAuthAuthorizeToken,
          OAuthAuthorizeTokenList,
          DoneableOAuthAuthorizeToken,
          ClientResource<OAuthAuthorizeToken, DoneableOAuthAuthorizeToken>>
      oAuthAuthorizeTokens() {
    return delegate.oAuthAuthorizeTokens();
  }

  @Override
  public ClientNonNamespaceOperation<
          OAuthClient,
          OAuthClientList,
          DoneableOAuthClient,
          ClientResource<OAuthClient, DoneableOAuthClient>>
      oAuthClients() {
    return delegate.oAuthClients();
  }

  @Override
  public ClientMixedOperation<
          Policy, PolicyList, DoneablePolicy, ClientResource<Policy, DoneablePolicy>>
      policies() {
    return delegate.policies();
  }

  @Override
  public ClientMixedOperation<
          PolicyBinding,
          PolicyBindingList,
          DoneablePolicyBinding,
          ClientResource<PolicyBinding, DoneablePolicyBinding>>
      policyBindings() {
    return delegate.policyBindings();
  }

  @Override
  public ClientNonNamespaceOperation<
          Project, ProjectList, DoneableProject, ClientResource<Project, DoneableProject>>
      projects() {
    return delegate.projects();
  }

  @Override
  public ClientProjectRequestOperation projectrequests() {
    return delegate.projectrequests();
  }

  @Override
  public ClientMixedOperation<
          RoleBinding,
          RoleBindingList,
          DoneableRoleBinding,
          ClientResource<RoleBinding, DoneableRoleBinding>>
      roleBindings() {
    return delegate.roleBindings();
  }

  @Override
  public ClientMixedOperation<Route, RouteList, DoneableRoute, ClientResource<Route, DoneableRoute>>
      routes() {
    return delegate.routes();
  }

  @Override
  public ClientMixedOperation<
          Template,
          TemplateList,
          DoneableTemplate,
          ClientTemplateResource<Template, KubernetesList, DoneableTemplate>>
      templates() {
    return delegate.templates();
  }

  @Override
  public ClientNonNamespaceOperation<
          User, UserList, DoneableUser, ClientResource<User, DoneableUser>>
      users() {
    return delegate.users();
  }

  @Override
  public ClientSubjectAccessReviewOperation<
          CreateableSubjectAccessReview, CreateableLocalSubjectAccessReview>
      subjectAccessReviews() {
    return delegate.subjectAccessReviews();
  }

  @Override
  public ClientMixedOperation<
          Endpoints, EndpointsList, DoneableEndpoints, ClientResource<Endpoints, DoneableEndpoints>>
      endpoints() {
    return delegate.endpoints();
  }

  @Override
  public ClientMixedOperation<Event, EventList, DoneableEvent, ClientResource<Event, DoneableEvent>>
      events() {
    return delegate.events();
  }

  @Override
  public ClientNonNamespaceOperation<
          Namespace, NamespaceList, DoneableNamespace, ClientResource<Namespace, DoneableNamespace>>
      namespaces() {
    return delegate.namespaces();
  }

  @Override
  public ClientNonNamespaceOperation<
          Node, NodeList, DoneableNode, ClientResource<Node, DoneableNode>>
      nodes() {
    return delegate.nodes();
  }

  @Override
  public ClientMixedOperation<
          PersistentVolume,
          PersistentVolumeList,
          DoneablePersistentVolume,
          ClientResource<PersistentVolume, DoneablePersistentVolume>>
      persistentVolumes() {
    return delegate.persistentVolumes();
  }

  @Override
  public ClientMixedOperation<
          PersistentVolumeClaim,
          PersistentVolumeClaimList,
          DoneablePersistentVolumeClaim,
          ClientResource<PersistentVolumeClaim, DoneablePersistentVolumeClaim>>
      persistentVolumeClaims() {
    return delegate.persistentVolumeClaims();
  }

  @Override
  public ClientMixedOperation<Pod, PodList, DoneablePod, ClientPodResource<Pod, DoneablePod>>
      pods() {
    return delegate.pods();
  }

  @Override
  public ClientMixedOperation<
          ReplicationController,
          ReplicationControllerList,
          DoneableReplicationController,
          ClientRollableScallableResource<ReplicationController, DoneableReplicationController>>
      replicationControllers() {
    return delegate.replicationControllers();
  }

  @Override
  public ClientMixedOperation<
          ResourceQuota,
          ResourceQuotaList,
          DoneableResourceQuota,
          ClientResource<ResourceQuota, DoneableResourceQuota>>
      resourceQuotas() {
    return delegate.resourceQuotas();
  }

  @Override
  public ClientMixedOperation<
          Secret, SecretList, DoneableSecret, ClientResource<Secret, DoneableSecret>>
      secrets() {
    return delegate.secrets();
  }

  @Override
  public ClientMixedOperation<
          io.fabric8.kubernetes.api.model.Service,
          ServiceList,
          DoneableService,
          ClientResource<io.fabric8.kubernetes.api.model.Service, DoneableService>>
      services() {
    return delegate.services();
  }

  @Override
  public ClientMixedOperation<
          ServiceAccount,
          ServiceAccountList,
          DoneableServiceAccount,
          ClientResource<ServiceAccount, DoneableServiceAccount>>
      serviceAccounts() {
    return delegate.serviceAccounts();
  }

  @Override
  public ClientKubernetesListMixedOperation lists() {
    return delegate.lists();
  }

  @Override
  public ClientNonNamespaceOperation<
          SecurityContextConstraints,
          SecurityContextConstraintsList,
          DoneableSecurityContextConstraints,
          ClientResource<SecurityContextConstraints, DoneableSecurityContextConstraints>>
      securityContextConstraints() {
    return delegate.securityContextConstraints();
  }

  @Override
  public <C> C adapt(Class<C> type) {
    return delegate.adapt(type);
  }

  @Override
  public URL getMasterUrl() {
    return delegate.getMasterUrl();
  }

  @Override
  public String getApiVersion() {
    return delegate.getApiVersion();
  }

  @Override
  public String getNamespace() {
    return delegate.getNamespace();
  }

  @Override
  public RootPaths rootPaths() {
    return delegate.rootPaths();
  }

  @Override
  public void close() {
    delegate.close();
  }

  @Override
  public Config getConfiguration() {
    return delegate.getConfiguration();
  }

  @Override
  public OpenShiftClient inNamespace(String name) {
    return delegate.inNamespace(name);
  }

  @Override
  public OpenShiftClient inAnyNamespace() {
    return delegate.inAnyNamespace();
  }
}