Skip to content

Commit

Permalink
Merge pull request #2683 from manusa/doc/crd-examples
Browse files Browse the repository at this point in the history
  • Loading branch information
fusesource-ci committed Dec 18, 2020
2 parents 0bf51cf + aaa509b commit 367233a
Show file tree
Hide file tree
Showing 4 changed files with 153 additions and 31 deletions.
Expand Up @@ -68,24 +68,24 @@
@Buildable(builderPackage = "io.fabric8.kubernetes.api.builder", editableEnabled = false)
public abstract class CustomResource<S, T> implements HasMetadata {
private static final Logger LOG = LoggerFactory.getLogger(CustomResource.class);

public static final String NAMESPACE_SCOPE = "Namespaced";
public static final String CLUSTER_SCOPE = "Cluster";
private ObjectMeta metadata = new ObjectMeta();

@JsonProperty("spec")
private S spec;

@JsonProperty("status")
private T status;

private final String singular;
private final String crdName;
private final String kind;
private final String apiVersion;
private final String scope;
private final String plural;

public CustomResource() {
final String version = HasMetadata.super.getApiVersion();
final Class<? extends CustomResource> clazz = getClass();
Expand All @@ -100,7 +100,7 @@ public CustomResource() {
this.plural = getPlural(clazz);
this.crdName = getCRDName(clazz);
}

@Override
public String toString() {
return "CustomResource{" +
Expand All @@ -111,38 +111,38 @@ public String toString() {
", status=" + status +
'}';
}

@Override
public String getApiVersion() {
return apiVersion;
}

@Override
public void setApiVersion(String version) {
// already set in constructor
LOG.warn("Calling CustomResource#setApiVersion doesn't do anything because the API version is computed and shouldn't be changed");
LOG.debug("Calling CustomResource#setApiVersion doesn't do anything because the API version is computed and shouldn't be changed");
}

@Override
public String getKind() {
return this.kind;
}

public void setKind(String kind) {
// already set in constructor
LOG.warn("Calling CustomResource#setKind doesn't do anything because the Kind is computed and shouldn't be changed");
LOG.debug("Calling CustomResource#setKind doesn't do anything because the Kind is computed and shouldn't be changed");
}

@Override
public ObjectMeta getMetadata() {
return metadata;
}

@Override
public void setMetadata(ObjectMeta metadata) {
this.metadata = metadata;
}

/**
* Retrieves the plural form associated with the specified CustomResource if annotated with {@link Plural} or computes a default value
* using the value returned by {@link #getSingular(Class)} as input to {@link Pluralize#toPlural(String)}.
Expand All @@ -154,12 +154,12 @@ public static String getPlural(Class<? extends CustomResource> clazz) {
final Plural fromAnnotation = clazz.getAnnotation(Plural.class);
return (fromAnnotation != null ? fromAnnotation.value().toLowerCase(Locale.ROOT) : Pluralize.toPlural(getSingular(clazz)));
}

@JsonIgnore
public String getPlural() {
return plural;
}

/**
* Retrieves the singular form associated with the specified CustomResource as defined by the {@link Singular} annotation or
* computes a default value (lower-cased version of the value returned by {@link HasMetadata#getKind(Class)}) if the annotation
Expand All @@ -172,12 +172,12 @@ public static String getSingular(Class<? extends CustomResource> clazz) {
final Singular fromAnnotation = clazz.getAnnotation(Singular.class);
return (fromAnnotation != null ? fromAnnotation.value() : HasMetadata.getKind(clazz)).toLowerCase(Locale.ROOT);
}

@JsonIgnore
public String getSingular() {
return singular;
}

/**
* Computes the name of the Custom Resource Definition (CRD) associated with the specified CustomResource.
* See https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/ for more details.
Expand All @@ -188,12 +188,12 @@ public String getSingular() {
public static String getCRDName(Class<? extends CustomResource> clazz) {
return getPlural(clazz) + "." + HasMetadata.getGroup(clazz);
}

@JsonIgnore
public String getCRDName() {
return crdName;
}

/**
* Retrieves the scope that this CustomResource targets
*
Expand All @@ -203,29 +203,29 @@ public String getCRDName() {
public String getScope() {
return scope;
}

@JsonIgnore
public String getGroup() {
return HasMetadata.getGroup(getClass());
}

@JsonIgnore
public String getVersion() {
return HasMetadata.getVersion(getClass());
}

public S getSpec() {
return spec;
}

public void setSpec(S spec) {
this.spec = spec;
}

public T getStatus() {
return status;
}

public void setStatus(T status) {
this.status = status;
}
Expand Down
Expand Up @@ -72,7 +72,7 @@ public static CustomResourceDefinitionBuilder v1beta1CRDFromCustomResourceType(C
.withNewSpec()
.withGroup(instance.getGroup())
.withVersion(version) // also set version to the first (and only) versions item
.addNewVersion().withName(version).endVersion()
.addNewVersion().withName(version).withServed(true).withStorage(true).endVersion()
.withScope(instance.getScope())
.withNewNames()
.withKind(instance.getKind())
Expand All @@ -94,7 +94,7 @@ public static io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDef
.endMetadata()
.withNewSpec()
.withGroup(instance.getGroup())
.addNewVersion().withName(instance.getVersion()).endVersion()
.addNewVersion().withName(instance.getVersion()).withServed(true).withStorage(true).endVersion()
.withScope(instance.getScope())
.withNewNames()
.withKind(instance.getKind())
Expand Down
Expand Up @@ -46,7 +46,7 @@ public class CRDExample {
private static final Logger logger = LoggerFactory.getLogger(CRDExample.class);

private static boolean logRootPaths = false;

/**
* Example of Cluster and Namespaced scoped K8S Custom Resources.
* To test Cluster scoped resource use "--cluster" as first argument.
Expand Down Expand Up @@ -112,7 +112,7 @@ public static void main(String[] args) {
System.out.println("Found CRD: " + dummyCRD.getMetadata().getSelfLink());
} else {
dummyCRD = CustomResourceDefinitionContext.v1beta1CRDFromCustomResourceType(Dummy.class).build();
client.customResourceDefinitions().create(dummyCRD);
client.apiextensions().v1beta1().customResourceDefinitions().create(dummyCRD);
System.out.println("Created CRD " + dummyCRD.getMetadata().getName());
}

Expand Down
@@ -0,0 +1,122 @@
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.kubernetes.examples;

import io.fabric8.kubernetes.api.model.Namespaced;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition;
import io.fabric8.kubernetes.api.model.apiextensions.v1.JSONSchemaPropsBuilder;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.client.CustomResourceList;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation;
import io.fabric8.kubernetes.client.dsl.Resource;
import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;

import java.io.Serializable;
import java.util.Map;

public class CustomResourceV1Example {

@SuppressWarnings("java:S106")
public static void main(String... args) {
try (KubernetesClient kc = new DefaultKubernetesClient()) {
// @formatter:off
final CustomResourceDefinition crd = CustomResourceDefinitionContext.v1CRDFromCustomResourceType(Show.class)
.editSpec().editVersion(0)
.withNewSchema().withNewOpenAPIV3Schema()
.withTitle("Shows")
.withType("object")
.addToRequired("spec")
.addToProperties("spec", new JSONSchemaPropsBuilder()
.withType("object")
.addToProperties("name", new JSONSchemaPropsBuilder().withNewType("string").build())
.addToProperties("score", new JSONSchemaPropsBuilder().withNewType("number").build())
.build())
.endOpenAPIV3Schema().endSchema()
.endVersion().endSpec().build();
// @formatter:on
kc.apiextensions().v1().customResourceDefinitions().createOrReplace(crd);
System.out.println("Created custom shows.example.com Kubernetes API");
final NonNamespaceOperation<Show, ShowList, Resource<Show>> shows =
kc.customResources(CustomResourceDefinitionContext.fromCrd(crd), Show.class, ShowList.class)
.inNamespace("default");
shows.list();
shows.createOrReplace(new Show("breaking-bad", new ShowSpec("Breaking Bad", 10)));
shows.createOrReplace(new Show("better-call-saul", new ShowSpec("Better call Saul", 8)));
shows.createOrReplace(new Show("the-wire", new ShowSpec("The Wire", 10)));
System.out.println("Added three shows");
shows.list().getItems()
.forEach(s -> System.out.printf(" - %s%n", s.getSpec().name));
final Show theWire = shows.withName("the-wire").fromServer().get();
System.out.printf("The Wire Score is: %s%n", theWire.getSpec().score);
}
}

@Group("example.com")
@Version("v1")
public static final class Show extends CustomResource<ShowSpec, Map<String, Object>> implements Namespaced {

@SuppressWarnings("unused")
public Show() {
super();
}
public Show(String metaName, ShowSpec spec) {
setMetadata(new ObjectMetaBuilder().withName(metaName).build());
setSpec(spec);
}
}

public static final class ShowList extends CustomResourceList<Show> {}

@SuppressWarnings("unused")
public static final class ShowSpec implements Serializable {

private static final long serialVersionUID = -1548881019086449848L;

private String name;
private Number score;

public ShowSpec() {
super();
}

public ShowSpec(String name, int score) {
this.name = name;
this.score = score;
}

public String getName() {
return name;
}

public Number getScore() {
return score;
}

public void setName(String name) {
this.name = name;
}

public void setScore(Number score) {
this.score = score;
}
}

}

0 comments on commit 367233a

Please sign in to comment.