use of io.fabric8.kubernetes.client.KubernetesClientBuilder in project kubernetes-client by fabric8io.
the class BindingExample method main.
@SuppressWarnings("java:S106")
public static void main(String[] args) {
final String podName = "binding-example-" + UUID.randomUUID();
try (final KubernetesClient client = new KubernetesClientBuilder().build()) {
final String namespace;
if (client.getConfiguration().getNamespace() != null) {
namespace = client.getConfiguration().getNamespace();
} else if (client.getNamespace() != null) {
namespace = client.getNamespace();
} else {
namespace = client.namespaces().list().getItems().stream().findFirst().orElseThrow(() -> new IllegalStateException("No namespace available")).getMetadata().getName();
}
client.pods().inNamespace(namespace).create(new PodBuilder().withMetadata(new ObjectMetaBuilder().withName(podName).build()).withSpec(new PodSpecBuilder().withSchedulerName("random-scheduler-name-which-does-not-exist").addNewContainer().withName(podName).withImage("nginx:latest").endContainer().build()).build());
final Node firstNode = client.nodes().list().getItems().stream().findFirst().orElseThrow(() -> new IllegalStateException("No nodes available"));
client.bindings().inNamespace(namespace).create(new BindingBuilder().withNewMetadata().withName(podName).endMetadata().withNewTarget().withKind(firstNode.getKind()).withApiVersion(firstNode.getApiVersion()).withName(firstNode.getMetadata().getName()).endTarget().build());
System.out.printf("Successfully bound Pod %s to Node %s%n", podName, firstNode.getMetadata().getName());
}
}
use of io.fabric8.kubernetes.client.KubernetesClientBuilder in project kubernetes-client by fabric8io.
the class CRDExample method main.
/**
* Example of Cluster and Namespaced scoped K8S Custom Resources.
* To test Cluster scoped resource use "--cluster" as first argument.
* To test Namespaced resource provide namespace as first argument (namespace must exists in K8S).
*
* @param args Either "--cluster" or namespace name.
*/
public static void main(String[] args) {
boolean resourceNamespaced = true;
String namespace = null;
if (args.length > 0) {
if ("--cluster".equals(args[0])) {
resourceNamespaced = false;
} else {
namespace = args[0];
}
}
try (final KubernetesClient client = new KubernetesClientBuilder().build()) {
if (resourceNamespaced) {
if (namespace == null) {
namespace = client.getNamespace();
}
if (namespace == null) {
System.err.println("No namespace specified and no default defined!");
return;
}
System.out.println("Using namespace: " + namespace);
} else {
System.out.println("Creating cluster scoped resource");
}
if (LOG_ROOT_PATHS) {
RootPaths rootPaths = client.rootPaths();
if (rootPaths != null) {
List<String> paths = rootPaths.getPaths();
if (paths != null) {
System.out.println("Supported API Paths:");
for (String path : paths) {
System.out.println(" " + path);
}
System.out.println();
}
}
}
CustomResourceDefinitionList crds = client.apiextensions().v1().customResourceDefinitions().list();
List<CustomResourceDefinition> crdsItems = crds.getItems();
System.out.println("Found " + crdsItems.size() + " CRD(s)");
CustomResourceDefinition dummyCRD = null;
final String dummyCRDName = CustomResource.getCRDName(Dummy.class);
for (CustomResourceDefinition crd : crdsItems) {
ObjectMeta metadata = crd.getMetadata();
if (metadata != null) {
String name = metadata.getName();
System.out.println(" " + name + " => " + metadata.getSelfLink());
if (dummyCRDName.equals(name)) {
dummyCRD = crd;
}
}
}
if (dummyCRD != null) {
System.out.println("Found CRD: " + dummyCRD.getMetadata().getSelfLink());
} else {
dummyCRD = CustomResourceDefinitionContext.v1CRDFromCustomResourceType(Dummy.class).editSpec().editVersion(0).withNewSchema().withNewOpenAPIV3Schema().withTitle("dummy").withType("object").addToRequired("spec").addToProperties("spec", new JSONSchemaPropsBuilder().withType("object").addToProperties("foo", new JSONSchemaPropsBuilder().withType("string").build()).addToProperties("bar", new JSONSchemaPropsBuilder().withType("string").build()).build()).endOpenAPIV3Schema().endSchema().endVersion().endSpec().build();
client.apiextensions().v1().customResourceDefinitions().create(dummyCRD);
System.out.println("Created CRD " + dummyCRD.getMetadata().getName());
}
// wait a beat for the endpoints to be ready
Thread.sleep(5000);
// lets create a client for the CRD
NonNamespaceOperation<Dummy, DummyList, Resource<Dummy>> dummyClient = client.resources(Dummy.class, DummyList.class);
if (resourceNamespaced) {
dummyClient = ((MixedOperation<Dummy, DummyList, Resource<Dummy>>) dummyClient).inNamespace(namespace);
}
CustomResourceList<Dummy> dummyList = dummyClient.list();
List<Dummy> items = dummyList.getItems();
System.out.println(" found " + items.size() + " dummies");
for (Dummy item : items) {
System.out.println(" " + item);
}
Dummy dummy = new Dummy();
ObjectMeta metadata = new ObjectMeta();
metadata.setName("foo");
dummy.setMetadata(metadata);
DummySpec dummySpec = new DummySpec();
Date now = new Date();
dummySpec.setBar("beer: " + now);
dummySpec.setFoo("cheese: " + now);
dummy.setSpec(dummySpec);
Dummy created = dummyClient.createOrReplace(dummy);
System.out.println("Upserted " + dummy);
created.getSpec().setBar("otherBar");
dummyClient.createOrReplace(created);
System.out.println("Watching for changes to Dummies");
dummyClient.withResourceVersion(created.getMetadata().getResourceVersion()).watch(new Watcher<Dummy>() {
@Override
public void eventReceived(Action action, Dummy resource) {
System.out.println("==> " + action + " for " + resource);
if (resource.getSpec() == null) {
logger.error("No Spec for resource {}", resource);
}
}
@Override
public void onClose(WatcherException cause) {
}
});
System.in.read();
} catch (KubernetesClientException e) {
logger.error(e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
use of io.fabric8.kubernetes.client.KubernetesClientBuilder in project kubernetes-client by fabric8io.
the class UploadDirectoryToPod method main.
public static void main(String[] args) {
try (KubernetesClient k8s = new KubernetesClientBuilder().build()) {
File fileToUpload = new File("/tmp/test-dir-src");
// <- Namespace of Pod
k8s.pods().inNamespace("default").withName(// <- Name of Pod
"my-pod").dir(// <- Path of directory inside Pod
"/tmp/test-dir").upload(// <- Local Path of directory
fileToUpload.toPath());
}
}
use of io.fabric8.kubernetes.client.KubernetesClientBuilder in project kubernetes-client by fabric8io.
the class BuildConfigExamples method main.
@SuppressWarnings("java:S106")
public static void main(String[] args) throws InterruptedException {
try (KubernetesClient kubernetesClient = new KubernetesClientBuilder().build()) {
final OpenShiftClient client = kubernetesClient.adapt(OpenShiftClient.class);
final String namespace;
if (client.getNamespace() != null) {
namespace = client.getNamespace();
logger.info("Using configured namespace: {}", namespace);
} else {
final Namespace ns = client.namespaces().create(new NamespaceBuilder().withNewMetadata().withName(NAMESPACE).addToLabels("this", "rocks").endMetadata().build());
namespace = ns.getMetadata().getName();
logger.info("Created namespace: {}", namespace);
}
client.serviceAccounts().inNamespace(namespace).create(new ServiceAccountBuilder().withNewMetadata().withName("fabric8").endMetadata().build());
final ImageStream is = client.imageStreams().inNamespace(namespace).create(new ImageStreamBuilder().withNewMetadata().withName("example-camel-cdi").endMetadata().withNewSpec().addNewTag().withName("latest").endTag().withDockerImageRepository("fabric8/example-camel-cdi").endSpec().withNewStatus().withDockerImageRepository("").endStatus().build());
logger.info("Created image stream: {}", is.getMetadata().getName());
final String buildConfigName = "custom-build-config";
final BuildConfig buildConfig = client.buildConfigs().inNamespace(namespace).create(new BuildConfigBuilder().withNewMetadata().withName(buildConfigName).endMetadata().withNewSpec().withServiceAccount("fabric8").withNewSource().withType("Git").withNewGit().withUri("https://github.com/fabric8io/example-camel-cdi.git").endGit().endSource().withNewResources().addToLimits("mykey", new Quantity("10")).addToRequests("mykey", new Quantity("10")).endResources().withNewStrategy().withType("Source").withNewSourceStrategy().withNewFrom().withName("java-sti:latest").withKind("DockerImage").endFrom().endSourceStrategy().endStrategy().withNewOutput().withNewTo().withKind("DockerImage").withName("example-camel-cdi:latest").endTo().endOutput().addNewTrigger().withType("GitHub").withNewGithub().withSecret("secret101").endGithub().endTrigger().endSpec().build());
logger.info("Created Build Config: {}", buildConfig.getMetadata().getName());
final Build build = client.buildConfigs().inNamespace(namespace).withName("custom-build-config").instantiate(new BuildRequestBuilder().withNewMetadata().withName(buildConfigName).endMetadata().build());
logger.info("Instantiated Build: {}", build.getMetadata().getName());
client.buildConfigs().inNamespace(namespace).withName(buildConfigName).withSecret("secret101").withType("github").trigger(new WebHookTriggerBuilder().withSecret("secret101").build());
logger.info("Triggered Build Config: {}", buildConfigName);
Thread.sleep(6000);
logger.info("Builds:");
for (Build b : client.builds().inNamespace(namespace).list().getItems()) {
logger.info("\t\t\t{}", b.getMetadata().getName());
logger.info("\t\t\t\t\t Log:");
client.builds().inNamespace(namespace).withName(b.getMetadata().getName()).watchLog(System.out);
}
logger.info("Done");
}
}
use of io.fabric8.kubernetes.client.KubernetesClientBuilder in project kubernetes-client by fabric8io.
the class ListBuildConfigs method main.
public static void main(String[] args) {
try (OpenShiftClient client = new KubernetesClientBuilder().build().adapt(OpenShiftClient.class)) {
if (!client.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.BUILD)) {
logger.warn("This cluster does not support the API Group {}", OpenShiftAPIGroups.BUILD);
return;
}
BuildConfigList list = client.buildConfigs().list();
if (list == null) {
logger.error("No list returned!");
return;
}
List<BuildConfig> items = list.getItems();
for (BuildConfig item : items) {
logger.info("BuildConfig {} has version: {}", item.getMetadata().getName(), item.getApiVersion());
}
} catch (KubernetesClientException e) {
logger.error("Failed: {}", e.getMessage(), e);
}
}
Aggregations