Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: Updated and cleaned up Kubernetes + OpenShift examples #2688

Merged
merged 1 commit into from Dec 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -25,7 +25,6 @@
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
Expand Down Expand Up @@ -415,7 +414,7 @@ public static void configFromSysPropsOrEnvVars(Config config) {
if (configuredMaxConcurrentRequests != null) {
config.setMaxConcurrentRequests(Integer.parseInt(configuredMaxConcurrentRequests));
}

String configuredMaxConcurrentReqeustsPerHost = Utils.getSystemPropertyOrEnvVar(KUBERNETES_MAX_CONCURRENT_REQUESTS_PER_HOST, String.valueOf(config.getMaxConcurrentRequestsPerHost()));
if (configuredMaxConcurrentReqeustsPerHost != null) {
config.setMaxConcurrentRequestsPerHost(Integer.parseInt(configuredMaxConcurrentReqeustsPerHost));
Expand Down Expand Up @@ -1244,9 +1243,9 @@ public Boolean getAutoConfigure() {

/**
* Returns all the {@link NamedContext}s that exist in the kube config
*
*
* @return all the contexts
*
*
* @see NamedContext
*/
public List<NamedContext> getContexts() {
Expand All @@ -1259,9 +1258,9 @@ public void setContexts(List<NamedContext> contexts) {

/**
* Returns the current context that's defined in the kube config. Returns {@code null} if there's none
*
*
* @return the current context
*
*
* @see NamedContext
*/
public NamedContext getCurrentContext() {
Expand Down
Expand Up @@ -22,13 +22,13 @@
import java.util.concurrent.ConcurrentHashMap;

/**
* Utility class to monitor alhpa/beta version usage and log.
* Utility class to monitor alpha/beta version usage and log.
*/
public final class VersionUsageUtils {

private static final Logger LOG = LoggerFactory.getLogger(VersionUsageUtils.class);

private static ConcurrentHashMap<String, Boolean> UNSTABLE_TYPES = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, Boolean> UNSTABLE_TYPES = new ConcurrentHashMap<>();

private static final boolean LOG_EACH_USAGE = false;

Expand Down
Expand Up @@ -15,35 +15,56 @@
*/
package io.fabric8.kubernetes.examples;

import io.fabric8.kubernetes.api.model.Binding;
import io.fabric8.kubernetes.api.model.BindingBuilder;
import io.fabric8.kubernetes.api.model.KubernetesResourceList;
import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.PodSpecBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.UUID;

public class BindingExample {
private static Logger logger = LoggerFactory.getLogger(WaitUntilReadyExample.class);

public static void main(String args[]) throws IOException, InterruptedException {
@SuppressWarnings("java:S106")
public static void main(String[] args) {
final String podName = "binding-example-" + UUID.randomUUID().toString();
try (final KubernetesClient client = new DefaultKubernetesClient()) {
Binding binding = new BindingBuilder()
.withNewMetadata().withName("testpod").endMetadata()
.withNewTarget().withKind("Node").withApiVersion("v1").withName("minikube").endTarget()
.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.bindings().inNamespace("default").create(binding);
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());
}
}

private static void log(String action, Object obj) {
logger.info("{}: {}", action, obj);
}

private static void log(String action) {
logger.info(action);
}
}
Expand Up @@ -22,34 +22,26 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class CRDLoadExample {
private static Logger logger = LoggerFactory.getLogger(CRDLoadExample.class);

public static void main(String args[]) throws IOException {
private static final Logger logger = LoggerFactory.getLogger(CRDLoadExample.class);

public static void main(String[] args) {
try (final KubernetesClient client = new DefaultKubernetesClient()) {
// List all Custom resources.
log("Listing all current Custom Resource Definitions :");
CustomResourceDefinitionList crdList = client.customResourceDefinitions().list();
crdList.getItems().forEach(crd -> log(crd.getMetadata().getName()));
logger.info("Listing all current Custom Resource Definitions :");
CustomResourceDefinitionList crdList = client.apiextensions().v1beta1().customResourceDefinitions().list();
crdList.getItems().forEach(crd -> logger.info(crd.getMetadata().getName()));

// Creating a custom resource from yaml
CustomResourceDefinition aCustomResourceDefinition = client.customResourceDefinitions().load(CRDLoadExample.class.getResourceAsStream("/crd.yml")).get();
log("Creating CRD...");
client.customResourceDefinitions().create(aCustomResourceDefinition);
CustomResourceDefinition aCustomResourceDefinition = client.apiextensions().v1beta1().customResourceDefinitions()
.load(CRDLoadExample.class.getResourceAsStream("/crd.yml")).get();
logger.info("Creating CRD...");
client.apiextensions().v1beta1().customResourceDefinitions().create(aCustomResourceDefinition);

log("Updated Custom Resource Definitions: ");
client.customResourceDefinitions().list().getItems().forEach(crd -> log(crd.getMetadata().getName()));
logger.info("Updated Custom Resource Definitions: ");
client.apiextensions().v1beta1().customResourceDefinitions().list().getItems().forEach(crd -> logger.info(crd.getMetadata().getName()));

}
}

private static void log(String action, Object obj) {
logger.info("{}: {}", action, obj);
}

private static void log(String action) {
logger.info(action);
}
}
Expand Up @@ -30,7 +30,7 @@
public class ConfigMapExample {
private static final Logger logger = LoggerFactory.getLogger(ConfigMapExample.class);

public static void main(String[] args) throws InterruptedException {
public static void main(String[] args) {
Config config = new ConfigBuilder().build();
KubernetesClient client = new DefaultKubernetesClient(config);

Expand All @@ -56,19 +56,10 @@ public static void main(String[] args) throws InterruptedException {
addToData("bar", "beer").
build());

log("Upserted ConfigMap at " + configMap.getMetadata().getSelfLink() + " data " + configMap.getData());
logger.info("Upserted ConfigMap at {} data {}", configMap.getMetadata().getSelfLink(), configMap.getData());

} finally {
client.close();
}
}


private static void log(String action, Object obj) {
logger.info("{}: {}", action, obj);
}

private static void log(String action) {
logger.info(action);
}
}
Expand Up @@ -22,7 +22,6 @@
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation;
import io.fabric8.kubernetes.client.dsl.PodResource;
import org.slf4j.Logger;
Expand All @@ -38,7 +37,7 @@ public class CreatePod {

public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: podJsonFileName <token> <namespace>");
logger.warn("Usage: podJsonFileName <token> <namespace>");
return;
}
String fileName = args[0];
Expand All @@ -49,7 +48,7 @@ public static void main(String[] args) {

File file = new File(fileName);
if (!file.exists() || !file.isFile()) {
System.err.println("File does not exist: " + fileName);
logger.warn("File does not exist: {}", fileName);
return;
}

Expand All @@ -65,21 +64,19 @@ public static void main(String[] args) {

List<HasMetadata> resources = client.load(new FileInputStream(fileName)).get();
if (resources.isEmpty()) {
System.err.println("No resources loaded from file: " +fileName);
logger.error("No resources loaded from file: {}", fileName);
return;
}
HasMetadata resource = resources.get(0);
if (resource instanceof Pod){
Pod pod = (Pod) resource;
System.out.println("Creating pod in namespace " + namespace);
logger.info("Creating pod in namespace {}", namespace);
NonNamespaceOperation<Pod, PodList, PodResource<Pod>> pods = client.pods().inNamespace(namespace);
Pod result = pods.create(pod);
System.out.println("Created pod " + result.getMetadata().getName());
logger.info("Created pod {}", result.getMetadata().getName());
} else {
System.err.println("Loaded resource is not a Pod! " + resource);
logger.error("Loaded resource is not a Pod! {}", resource);
}
} catch (KubernetesClientException e) {
logger.error(e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
Expand Down
Expand Up @@ -18,37 +18,32 @@
import io.fabric8.kubernetes.client.AutoAdaptableKubernetesClient;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.openshift.client.OpenShiftClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CredentialsExample {

private static final Logger logger = LoggerFactory.getLogger(CredentialsExample.class);

public static void main(String[] args) throws InterruptedException {
String master = "https://localhost:8443/";
if (args.length == 1) {
master = args[0];
}

Config config = new ConfigBuilder().withMasterUrl(master)
public static void main(String[] args) {
final ConfigBuilder configBuilder = new ConfigBuilder();
if (args.length > 0) {
configBuilder.withMasterUrl(args[0]);
}
Config config = configBuilder
.withTrustCerts(true)
.withUsername("admin")
.withPassword("admin")
.withNamespace("default")
.withUsername("developer")
.withPassword("developer")
.withNamespace("myproject")
.build();
try (final KubernetesClient client = new AutoAdaptableKubernetesClient(config)) {

log("Received pods", client.pods().list());
logger.info("Received pods {}", client.pods().list());

} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);


Throwable[] suppressed = e.getSuppressed();
if (suppressed != null) {
for (Throwable t : suppressed) {
Expand All @@ -57,12 +52,4 @@ public static void main(String[] args) throws InterruptedException {
}
}
}

private static void log(String action, Object obj) {
logger.info("{}: {}", action, obj);
}

private static void log(String action) {
logger.info(action);
}
}