io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext Java Examples

The following examples show how to use io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext. 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: ApplyMojo.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
protected void processCustomEntities(KubernetesClient client, String namespace, List<String> customResourceDefinitions, boolean isDelete) throws Exception {
    if(customResourceDefinitions == null)
        return;

    List<CustomResourceDefinitionContext> crdContexts = KubernetesClientUtil.getCustomResourceDefinitionContext(client ,customResourceDefinitions);
    Map<File, String> fileToCrdMap = getCustomResourcesFileToNamemap();

    for(CustomResourceDefinitionContext customResourceDefinitionContext : crdContexts) {
        for(Map.Entry<File, String> entry : fileToCrdMap.entrySet()) {
            if(entry.getValue().equals(customResourceDefinitionContext.getGroup())) {
                if(isDelete) {
                    applyService.deleteCustomResource(entry.getKey(), namespace, customResourceDefinitionContext);
                } else {
                    applyService.applyCustomResource(entry.getKey(), namespace, customResourceDefinitionContext);
                }
            }
        }
    }
}
 
Example #2
Source File: RawCustomResourceOperationsImplTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp() throws IOException {
  this.mockClient = Mockito.mock(OkHttpClient.class, Mockito.RETURNS_DEEP_STUBS);
  this.config = new ConfigBuilder().withMasterUrl("https://localhost:8443/").build();
  this.customResourceDefinitionContext = new CustomResourceDefinitionContext.Builder()
    .withGroup("test.fabric8.io")
    .withName("hellos.test.fabric8.io")
    .withPlural("hellos")
    .withScope("Namespaced")
    .withVersion("v1alpha1")
    .build();

  Call mockCall = mock(Call.class);
  mockSuccessResponse = mockResponse(HttpURLConnection.HTTP_OK);
  when(mockCall.execute())
    .thenReturn(mockSuccessResponse);
  when(mockClient.newCall(any())).thenReturn(mockCall);
}
 
Example #3
Source File: KubernetesClientUtil.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
public static List<CustomResourceDefinitionContext> getCustomResourceDefinitionContext(KubernetesClient client, List<String> customResources) {
    List<CustomResourceDefinitionContext> crdContexts = new ArrayList<>();
    for(String customResource : customResources) {
        CustomResourceDefinition customResourceDefinition = client.customResourceDefinitions()
                .withName(customResource).get();
        if(customResourceDefinition != null) {
            crdContexts.add(new CustomResourceDefinitionContext.Builder()
                    .withGroup(customResourceDefinition.getSpec().getGroup())
                    .withName(customResourceDefinition.getMetadata().getName())
                    .withPlural(customResourceDefinition.getSpec().getNames().getPlural())
                    .withVersion(customResourceDefinition.getSpec().getVersion())
                    .withScope(customResourceDefinition.getSpec().getScope())
                    .build());
        }
    }
    return crdContexts;
}
 
Example #4
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
public void applyCustomResource(File customResourceFile, String namespace, CustomResourceDefinitionContext context)
    throws Exception {

    Map<String, Object> cr = KubernetesClientUtil.doReadCustomResourceFile(customResourceFile);
    Map<String, Object> objectMeta = (Map<String, Object>)cr.get("metadata");
    String name = objectMeta.get("name").toString();

    if (isRecreateMode()) {
        KubernetesClientUtil.doDeleteCustomResource(kubernetesClient, context, namespace, name);
        KubernetesClientUtil.doCreateCustomResource(kubernetesClient, context, namespace, customResourceFile);
        log.info("Created Custom Resource: " + name);
    } else {
        cr = KubernetesClientUtil.doGetCustomResource(kubernetesClient, context, namespace, name);
        if (cr == null) {
            KubernetesClientUtil.doCreateCustomResource(kubernetesClient, context, namespace, customResourceFile);
            log.info("Created Custom Resource: " + name);
        } else {
            KubernetesClientUtil.doEditCustomResource(kubernetesClient, context, namespace, name, customResourceFile);
            log.info("Updated Custom Resource: " + name);
        }
    }
}
 
Example #5
Source File: CustomResources.java    From enmasse with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a {@link CustomResourceDefinition} to a {@link CustomResourceDefinitionContext}.
 * @param definition The definition to convert.
 * @return The converted definition, or {@code null} if the input was {@code null}.
 */
public static CustomResourceDefinitionContext toContext(final CustomResourceDefinition definition) {

    if ( definition == null ) {
        return null;
    }

    return new CustomResourceDefinitionContext.Builder ()
            .withGroup(definition.getSpec().getGroup())
            .withScope(definition.getSpec().getScope())
            .withVersion(definition.getSpec().getVersion())
            .withPlural(definition.getSpec().getNames().getPlural())
            .withName(definition.getSpec().getNames().getSingular())
            .build();

}
 
Example #6
Source File: CustomResourceCrudTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void testCreateOrReplaceRaw() throws IOException {
  RawCustomResourceOperationsImpl raw = kubernetesServer.getClient().customResource(CustomResourceDefinitionContext.fromCrd(cronTabCrd));

  Map<String, Object> object = new HashMap<>();
  Map<String, Object> metadata = new HashMap<>();
  metadata.put("name", "foo");

  object.put("metadata", metadata);
  object.put("spec", "initial");

  Map<String, Object> created = raw.createOrReplace(object);

  assertEquals(object, created);

  object.put("spec", "updated");

  Map<String, Object> updated = raw.createOrReplace(object);
  assertNotEquals(created, updated);
  assertEquals(object, updated);
}
 
Example #7
Source File: PropagationPolicyTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should delete a Raw Custom Resource with PropagationPolicy=Background")
void testDeleteRawCustomResource() throws InterruptedException, IOException {
  // Given
  server.expect().delete().withPath("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos/example-hello")
    .andReturn(HttpURLConnection.HTTP_OK, "{\"metadata\":{},\"apiVersion\":\"v1\",\"kind\":\"Status\",\"details\":{\"name\":\"prometheus-example-rules\",\"group\":\"monitoring.coreos.com\",\"kind\":\"prometheusrules\",\"uid\":\"b3d085bd-6a5c-11e9-8787-525400b18c1d\"},\"status\":\"Success\"}").once();
  KubernetesClient client = server.getClient();

  // When
  Map<String, Object> result = client.customResource(new CustomResourceDefinitionContext.Builder()
    .withGroup("test.fabric8.io")
    .withName("hellos.test.fabric8.io")
    .withPlural("hellos")
    .withScope("Namespaced")
    .withVersion("v1alpha1")
    .build())
    .delete("ns1", "example-hello");

  // Then
  assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.BACKGROUND.toString(), server.getLastRequest());
}
 
Example #8
Source File: CreateIntegrationTestAction.java    From yaks with Apache License 2.0 5 votes vote down vote up
private CustomResourceDefinitionContext getIntegrationCRD() {
    return new CustomResourceDefinitionContext.Builder()
            .withName(Integration.CRD_INTEGRATION_NAME)
            .withGroup(Integration.CRD_GROUP)
            .withVersion(Integration.CRD_VERSION)
            .withPlural("integrations")
            .withScope("Namespaced")
            .build();
}
 
Example #9
Source File: DefaultKubernetesClient.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends HasMetadata, L extends KubernetesResourceList<T>, D extends Doneable<T>> MixedOperation<T, L, D, Resource<T, D>> customResources(CustomResourceDefinitionContext crdContext, Class<T> resourceType, Class<L> listClass, Class<D> doneClass) {
  return new CustomResourceOperationsImpl<>(new CustomResourceOperationContext().withOkhttpClient(httpClient).withConfig(getConfiguration())
    .withCrdContext(crdContext)
    .withType(resourceType)
    .withListType(listClass)
    .withPropagationPolicy(DEFAULT_PROPAGATION_POLICY)
    .withDoneableType(doneClass));
}
 
Example #10
Source File: CustomResourceOperationsImplTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void itFallsBackOnTypeKindIfNoKindSpecifiedInContext() throws IOException {
  assertForContext(new CustomResourceOperationContext()
    .withCrdContext(new CustomResourceDefinitionContext.Builder()
    .withGroup(crd.getSpec().getGroup())
    .withVersion(crd.getSpec().getVersion())
    .withScope(crd.getSpec().getScope())
    .withName(crd.getMetadata().getName())
    .withPlural(crd.getSpec().getNames().getPlural())
    .build())
    .withType(MyCustomResource.class)
    .withListType(MyCustomResourceList.class));
}
 
Example #11
Source File: RawCustomResourceIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Before
public void initCustomResourceDefinition() {
  currentNamespace = session.getNamespace();

  // Create a Custom Resource Definition Animals:
  CustomResourceDefinition animalCrd = client.customResourceDefinitions().load(getClass().getResourceAsStream("/test-rawcustomresource-definition.yml")).get();
  client.customResourceDefinitions().create(animalCrd);

  customResourceDefinitionContext = new CustomResourceDefinitionContext.Builder()
    .withName("animals.jungle.example.com")
    .withGroup("jungle.example.com")
    .withVersion("v1")
    .withPlural("animals")
    .withScope("Namespaced")
    .build();

  // Create a Custom Resource Definition with OpenAPIV3 validation schema
  CustomResourceDefinition aComplexCrd = client.customResourceDefinitions().load(getClass().getResourceAsStream("/kafka-crd.yml")).get();
  client.customResourceDefinitions().create(aComplexCrd);

  customResourceDefinitionContextWithOpenAPIV3Schema = new CustomResourceDefinitionContext.Builder()
    .withName("kafkas.kafka.strimzi.io")
    .withGroup("kafka.strimzi.io")
    .withPlural("kafkas")
    .withScope("Namespaced")
    .withVersion("v1beta1")
    .build();
}
 
Example #12
Source File: CustomResourceOperationContext.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public CustomResourceOperationContext(OkHttpClient client, Config config, String plural, String namespace, String name, String apiGroupName, String apiGroupVersion, boolean cascading, Object item, Map<String, String> labels, Map<String, String[]> labelsNot, Map<String, String[]> labelsIn, Map<String, String[]> labelsNotIn, Map<String, String> fields, Map<String, String[]> fieldsNot, String resourceVersion, boolean reloadingFromServer, long gracePeriodSeconds, DeletionPropagation propagationPolicy,  long watchRetryInitialBackoffMillis, double watchRetryBackoffMultiplier, CustomResourceDefinitionContext crdContext, Class type, Class listType, Class doneableType) {
  super(client, config, plural, namespace, name, apiGroupName, apiGroupVersion, cascading, item, labels, labelsNot, labelsIn, labelsNotIn, fields, fieldsNot, resourceVersion, reloadingFromServer, gracePeriodSeconds, propagationPolicy, watchRetryInitialBackoffMillis, watchRetryBackoffMultiplier);
  this.crdContext = crdContext;
  this.type = type;
  this.listType = listType;
  this.doneableType = doneableType;
}
 
Example #13
Source File: TypedCustomResourceApiTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setupCrd() {
  podSetCrd = new CustomResourceDefinitionBuilder()
    .withNewMetadata().withName("podsets.demo.k8s.io").endMetadata()
    .withNewSpec()
    .withGroup("demo.k8s.io")
    .withVersion("v1alpha1")
    .withNewNames().withKind("PodSet").withPlural("podsets").endNames()
    .withScope("Namespaced")
    .endSpec()
    .build();

  crdContext = CustomResourceDefinitionContext.fromCrd(podSetCrd);
}
 
Example #14
Source File: CustomResourceCrudTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
  KubernetesDeserializer.registerCustomKind("stable.example.com/v1", "CronTab", CronTab.class);
  cronTabCrd = kubernetesServer.getClient()
    .customResourceDefinitions()
    .load(getClass().getResourceAsStream("/crontab-crd.yml"))
    .get();
  kubernetesServer.getClient().customResourceDefinitions().create(cronTabCrd);
  crdContext = CustomResourceDefinitionContext.fromCrd(cronTabCrd);
}
 
Example #15
Source File: TypedClusterScopeCustomResourceApiTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setupCrd() {
  starCrd = new CustomResourceDefinitionBuilder()
    .withNewMetadata().withName("stars.example.crd.com").endMetadata()
    .withNewSpec()
    .withGroup("example.crd.com")
    .withVersion("v1alpha1")
    .withNewNames().withKind("Star").withPlural("stars").endNames()
    .withScope("Cluster")
    .endSpec()
    .build();

  crdContext = CustomResourceDefinitionContext.fromCrd(starCrd);
}
 
Example #16
Source File: ApplyService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public void deleteCustomResource(File customResourceFile, String namespace, CustomResourceDefinitionContext crdContext)
    throws Exception {

    Map<String, Object> customResource = KubernetesClientUtil.doReadCustomResourceFile(customResourceFile);
    Map<String, Object> objectMeta = (Map<String, Object>)customResource.get("metadata");
    String name = objectMeta.get("name").toString();
    log.info("Deleting Custom Resource " + name);
    KubernetesClientUtil.doDeleteCustomResource(kubernetesClient, crdContext, namespace, name);
}
 
Example #17
Source File: KubernetesClientUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static Map<String, Object> doGetCustomResource(KubernetesClient kubernetesClient, CustomResourceDefinitionContext crdContext, String namespace, String name) {
    try {
        if ("Namespaced".equals(crdContext.getScope())) {
            return kubernetesClient.customResource(crdContext).get(namespace, name);
        } else {
            return kubernetesClient.customResource(crdContext).get(name);
        }
    } catch (Exception exception) { // Not found exception
        return null;
    }
}
 
Example #18
Source File: KubernetesClientUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static Map<String, Object> doDeleteCustomResource(
    KubernetesClient kubernetesClient, CustomResourceDefinitionContext crdContext, String namespace, String name)
    throws IOException{

    if ("Namespaced".equals(crdContext.getScope())) {
        return kubernetesClient.customResource(crdContext).delete(namespace, name);
    } else {
        return kubernetesClient.customResource(crdContext).delete(name);
    }
}
 
Example #19
Source File: KubernetesClientUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static Map<String, Object> doEditCustomResource(KubernetesClient kubernetesClient, CustomResourceDefinitionContext crdContext, String namespace, String name, File customResourceFile) throws IOException {
    if ("Namespaced".equals(crdContext.getScope())) {
        return kubernetesClient.customResource(crdContext).edit(namespace, name, new FileInputStream(customResourceFile.getAbsolutePath()));
    } else {
        return kubernetesClient.customResource(crdContext).edit(name, doGetCustomResourceAsString(customResourceFile));
    }
}
 
Example #20
Source File: KubernetesClientUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static Map<String, Object> doCreateCustomResource(KubernetesClient kubernetesClient, CustomResourceDefinitionContext crdContext, String namespace, File customResourceFile) throws IOException {
    if ("Namespaced".equals(crdContext.getScope())) {
        return kubernetesClient.customResource(crdContext).create(namespace, new FileInputStream(customResourceFile.getAbsolutePath()));
    } else {
        return kubernetesClient.customResource(crdContext).create(new FileInputStream(customResourceFile.getAbsolutePath()));
    }
}
 
Example #21
Source File: CreateIntegrationTestAction.java    From yaks with Apache License 2.0 4 votes vote down vote up
private void createIntegration(TestContext context) {
    final Integration.Builder integrationBuilder = new Integration.Builder()
            .name(context.replaceDynamicContentInString(integrationName))
            .source(context.replaceDynamicContentInString(source));

    if (dependencies != null && !dependencies.isEmpty()) {
        integrationBuilder.dependencies(Arrays.asList(context.replaceDynamicContentInString(dependencies).split(",")));
    }

    if (traits != null && !traits.isEmpty()) {
        final Map<String, Integration.TraitConfig> traitConfigMap = new HashMap<>();
        for(String t : context.replaceDynamicContentInString(traits).split(",")){
            //traitName.key=value
            if(!validateTraitFormat(t)) {
                throw new IllegalArgumentException("Trait" + t + "does not match format traitName.key=value");
            }
            final String[] trait = t.split("\\.",2);
            final String[] traitConfig = trait[1].split("=", 2);
            if(traitConfigMap.containsKey(trait[0])) {
                traitConfigMap.get(trait[0]).add(traitConfig[0], traitConfig[1]);
            } else {
                traitConfigMap.put(trait[0],  new Integration.TraitConfig(traitConfig[0], traitConfig[1]));
            }
        }
        integrationBuilder.traits(traitConfigMap);
    }

    final Integration i = integrationBuilder.build();

    final CustomResourceDefinitionContext crdContext = getIntegrationCRD();

    try {
        Map<String, Object> result = client.customResource(crdContext).createOrReplace(CamelKHelper.namespace(), mapper.writeValueAsString(i));
        if (result.get("message") != null) {
            throw new CitrusRuntimeException(result.get("message").toString());
        }
    } catch (IOException e) {
        throw new CitrusRuntimeException("Failed to create Camel-K integration via JSON object", e);
    }

    LOG.info(String.format("Successfully created Camel-K integration '%s'", i.getMetadata().getName()));
}
 
Example #22
Source File: DefaultOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends HasMetadata, L extends KubernetesResourceList<T>, D extends Doneable<T>> MixedOperation<T, L, D, Resource<T, D>> customResources(CustomResourceDefinitionContext crdContext, Class<T> resourceType, Class<L> listClass, Class<D> doneClass) {
  return new CustomResourceOperationsImpl<>(new CustomResourceOperationContext().withOkhttpClient(httpClient).withConfig(getConfiguration()).withCrdContext(crdContext).withType(resourceType).withListType(listClass).withDoneableType(doneClass));
}
 
Example #23
Source File: ManagedOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public RawCustomResourceOperationsImpl customResource(CustomResourceDefinitionContext customResourceDefinition) {
  return delegate.customResource(customResourceDefinition);
}
 
Example #24
Source File: ManagedOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends HasMetadata, L extends KubernetesResourceList<T>, D extends Doneable<T>> MixedOperation<T, L, D, Resource<T, D>> customResources(CustomResourceDefinitionContext crdContext, Class<T> resourceType, Class<L> listClass, Class<D> doneClass) {
  return delegate.customResources(crdContext, resourceType, listClass, doneClass);
}
 
Example #25
Source File: ManagedKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public RawCustomResourceOperationsImpl customResource(CustomResourceDefinitionContext customResourceDefinition) {
  return delegate.customResource(customResourceDefinition);
}
 
Example #26
Source File: DefaultOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public RawCustomResourceOperationsImpl customResource(CustomResourceDefinitionContext customResourceDefinition) {
  return new RawCustomResourceOperationsImpl(httpClient, getConfiguration(), customResourceDefinition);
}
 
Example #27
Source File: ManagedKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends HasMetadata, L extends KubernetesResourceList<T>, D extends Doneable<T>> MixedOperation<T, L, D, Resource<T, D>> customResources(CustomResourceDefinitionContext crdContext, Class<T> resourceType, Class<L> listClass, Class<D> doneClass) {
  return delegate.customResources(crdContext, resourceType, listClass, doneClass);
}
 
Example #28
Source File: DefaultKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public RawCustomResourceOperationsImpl customResource(CustomResourceDefinitionContext customResourceDefinition) {
  return new RawCustomResourceOperationsImpl(httpClient, getConfiguration(), customResourceDefinition);
}
 
Example #29
Source File: RawCustomResourceOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public RawCustomResourceOperationsImpl(OkHttpClient client, Config config, CustomResourceDefinitionContext customResourceDefinition) {
  this.client = client;
  this.config = config;
  this.customResourceDefinition = customResourceDefinition;
  this.objectMapper = Serialization.jsonMapper();
}
 
Example #30
Source File: CustomResourceOperationContext.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public CustomResourceOperationContext withCrdContext(CustomResourceDefinitionContext crdContext) {
  return new CustomResourceOperationContext(client, config, plural, namespace, name, apiGroupName, apiGroupVersion, cascading,item, labels, labelsNot, labelsIn, labelsNotIn, fields, fieldsNot, resourceVersion, reloadingFromServer, gracePeriodSeconds, propagationPolicy, watchRetryInitialBackoffMillis, watchRetryBackoffMultiplier,  crdContext, type, listType, doneableType);
}