Search in sources :

Example 1 with V1LabelSelector

use of io.kubernetes.client.openapi.models.V1LabelSelector in project java by kubernetes-client.

the class DeployRolloutRestartExample method main.

public static void main(String[] args) throws IOException, ApiException {
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);
    AppsV1Api appsV1Api = new AppsV1Api(client);
    String deploymentName = "example-nginx";
    String imageName = "nginx:1.21.6";
    String namespace = "default";
    // Create an example deployment
    V1DeploymentBuilder deploymentBuilder = new V1DeploymentBuilder().withApiVersion("apps/v1").withKind("Deployment").withMetadata(new V1ObjectMeta().name(deploymentName).namespace(namespace)).withSpec(new V1DeploymentSpec().replicas(1).selector(new V1LabelSelector().putMatchLabelsItem("name", deploymentName)).template(new V1PodTemplateSpec().metadata(new V1ObjectMeta().putLabelsItem("name", deploymentName)).spec(new V1PodSpec().containers(Collections.singletonList(new V1Container().name(deploymentName).image(imageName))))));
    appsV1Api.createNamespacedDeployment(namespace, deploymentBuilder.build(), null, null, null, null);
    // Wait until example deployment is ready
    Wait.poll(Duration.ofSeconds(3), Duration.ofSeconds(60), () -> {
        try {
            System.out.println("Waiting until example deployment is ready...");
            return appsV1Api.readNamespacedDeployment(deploymentName, namespace, null).getStatus().getReadyReplicas() > 0;
        } catch (ApiException e) {
            e.printStackTrace();
            return false;
        }
    });
    System.out.println("Created example deployment!");
    // Trigger a rollout restart of the example deployment
    V1Deployment runningDeployment = appsV1Api.readNamespacedDeployment(deploymentName, namespace, null);
    // Explicitly set "restartedAt" annotation with current date/time to trigger rollout when patch
    // is applied
    runningDeployment.getSpec().getTemplate().getMetadata().putAnnotationsItem("kubectl.kubernetes.io/restartedAt", LocalDateTime.now().toString());
    try {
        String deploymentJson = client.getJSON().serialize(runningDeployment);
        PatchUtils.patch(V1Deployment.class, () -> appsV1Api.patchNamespacedDeploymentCall(deploymentName, namespace, new V1Patch(deploymentJson), null, null, "kubectl-rollout", null, null, null), V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH, client);
        // Wait until deployment has stabilized after rollout restart
        Wait.poll(Duration.ofSeconds(3), Duration.ofSeconds(60), () -> {
            try {
                System.out.println("Waiting until example deployment restarted successfully...");
                return appsV1Api.readNamespacedDeployment(deploymentName, namespace, null).getStatus().getReadyReplicas() > 0;
            } catch (ApiException e) {
                e.printStackTrace();
                return false;
            }
        });
        System.out.println("Example deployment restarted successfully!");
    } catch (ApiException e) {
        e.printStackTrace();
    }
}
Also used : V1Deployment(io.kubernetes.client.openapi.models.V1Deployment) AppsV1Api(io.kubernetes.client.openapi.apis.AppsV1Api) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) V1Patch(io.kubernetes.client.custom.V1Patch) V1DeploymentSpec(io.kubernetes.client.openapi.models.V1DeploymentSpec) V1DeploymentBuilder(io.kubernetes.client.openapi.models.V1DeploymentBuilder) ApiClient(io.kubernetes.client.openapi.ApiClient) V1Container(io.kubernetes.client.openapi.models.V1Container) V1PodTemplateSpec(io.kubernetes.client.openapi.models.V1PodTemplateSpec) V1LabelSelector(io.kubernetes.client.openapi.models.V1LabelSelector) V1PodSpec(io.kubernetes.client.openapi.models.V1PodSpec) ApiException(io.kubernetes.client.openapi.ApiException)

Example 2 with V1LabelSelector

use of io.kubernetes.client.openapi.models.V1LabelSelector in project java by kubernetes-client.

the class LabelSelectorTest method parseWithLabelsShouldWork.

@Test
public void parseWithLabelsShouldWork() throws IllegalArgumentException {
    HashMap<String, String> labels = new HashMap<String, String>() {

        {
            put("app1", "foo");
            put("app2", "bar");
        }
    };
    V1LabelSelector v1LabelSelector = new V1LabelSelector().matchLabels(labels);
    LabelSelector labelSelector = LabelSelector.parse(v1LabelSelector);
    HashMap<String, String> testSelector = new HashMap<String, String>() {

        {
            put("app1", "foo");
            put("app2", "bar");
        }
    };
    Assert.assertTrue(labelSelector.test(testSelector));
    testSelector.remove("app1");
    Assert.assertFalse(labelSelector.test(testSelector));
}
Also used : HashMap(java.util.HashMap) V1LabelSelector(io.kubernetes.client.openapi.models.V1LabelSelector) V1LabelSelector(io.kubernetes.client.openapi.models.V1LabelSelector) Test(org.junit.Test)

Example 3 with V1LabelSelector

use of io.kubernetes.client.openapi.models.V1LabelSelector in project java by kubernetes-client.

the class LabelSelectorTest method parseWithLabelsAndExpressionsShouldWork.

@Test
public void parseWithLabelsAndExpressionsShouldWork() throws IllegalArgumentException {
    HashMap<String, String> labels = new HashMap<String, String>() {

        {
            put("app1", "foo");
            put("app2", "bar");
        }
    };
    List<V1LabelSelectorRequirement> exprs = new LinkedList<V1LabelSelectorRequirement>() {

        {
            add(new V1LabelSelectorRequirement().key("key1").values(new LinkedList<String>() {

                {
                    add("value1");
                    add("value2");
                }
            }).operator(LabelSelector.LABEL_SELECTOR_OP_IN));
            add(new V1LabelSelectorRequirement().key("key2").values(new LinkedList<String>() {

                {
                    add("value3");
                    add("value4");
                }
            }).operator(LabelSelector.LABEL_SELECTOR_OP_NOT_IN));
            add(new V1LabelSelectorRequirement().key("key3").operator(LabelSelector.LABEL_SELECTOR_OP_EXISTS));
            add(new V1LabelSelectorRequirement().key("key4").operator(LabelSelector.LABEL_SELECTOR_OP_DOES_NOT_EXIST));
        }
    };
    V1LabelSelector v1LabelSelector = new V1LabelSelector().matchExpressions(exprs).matchLabels(labels);
    LabelSelector labelSelector = LabelSelector.parse(v1LabelSelector);
    HashMap<String, String> testSelector = new HashMap<String, String>() {

        {
            put("app1", "foo");
            put("app2", "bar");
            put("key1", "value1");
            put("key2", "value5");
            put("key3", "");
        }
    };
    Assert.assertTrue(labelSelector.test(testSelector));
}
Also used : HashMap(java.util.HashMap) V1LabelSelectorRequirement(io.kubernetes.client.openapi.models.V1LabelSelectorRequirement) V1LabelSelector(io.kubernetes.client.openapi.models.V1LabelSelector) V1LabelSelector(io.kubernetes.client.openapi.models.V1LabelSelector) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 4 with V1LabelSelector

use of io.kubernetes.client.openapi.models.V1LabelSelector in project twister2 by DSC-SPIDAL.

the class JobMasterRequestObject method createStatefulSetObject.

/**
 * create StatefulSet object for a job
 */
public static V1StatefulSet createStatefulSetObject() {
    if (config == null) {
        LOG.severe("JobMasterRequestObject.init method has not been called.");
        return null;
    }
    V1StatefulSet statefulSet = new V1StatefulSet();
    String statefulSetName = KubernetesUtils.createJobMasterStatefulSetName(jobID);
    // set labels for the jm stateful set
    HashMap<String, String> labels = KubernetesUtils.createJobLabels(jobID);
    // job master statefulset
    labels.put("t2-mss", jobID);
    // construct metadata and set for jobID setting
    V1ObjectMeta meta = new V1ObjectMeta();
    meta.setName(statefulSetName);
    meta.setLabels(labels);
    statefulSet.setMetadata(meta);
    // construct JobSpec and set
    V1StatefulSetSpec setSpec = new V1StatefulSetSpec();
    setSpec.serviceName(KubernetesUtils.createJobMasterServiceName(jobID));
    setSpec.setReplicas(1);
    // add selector for the job
    V1LabelSelector selector = new V1LabelSelector();
    selector.putMatchLabelsItem("t2-mp", jobID);
    setSpec.setSelector(selector);
    // construct the pod template
    V1PodTemplateSpec template = constructPodTemplate();
    setSpec.setTemplate(template);
    statefulSet.setSpec(setSpec);
    return statefulSet;
}
Also used : V1StatefulSet(io.kubernetes.client.openapi.models.V1StatefulSet) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) V1StatefulSetSpec(io.kubernetes.client.openapi.models.V1StatefulSetSpec) IntOrString(io.kubernetes.client.custom.IntOrString) V1PodTemplateSpec(io.kubernetes.client.openapi.models.V1PodTemplateSpec) V1LabelSelector(io.kubernetes.client.openapi.models.V1LabelSelector)

Example 5 with V1LabelSelector

use of io.kubernetes.client.openapi.models.V1LabelSelector in project heron by twitter.

the class V1Controller method createStatefulSet.

/**
 * Creates and configures the <code>StatefulSet</code> which the topology's <code>executor</code>s will run in.
 * @param containerResource Passed down to configure the <code>executor</code> resource limits.
 * @param numberOfInstances Used to configure the execution command and ports for the <code>executor</code>.
 * @param isExecutor Flag used to configure components specific to <code>executor</code> and <code>manager</code>.
 * @return A fully configured <code>StatefulSet</code> for the topology's <code>executors</code>.
 */
private V1StatefulSet createStatefulSet(Resource containerResource, int numberOfInstances, boolean isExecutor) {
    final String topologyName = getTopologyName();
    final Config runtimeConfiguration = getRuntimeConfiguration();
    final List<V1Volume> volumes = new LinkedList<>();
    final List<V1VolumeMount> volumeMounts = new LinkedList<>();
    // Collect Persistent Volume Claim configurations from the CLI.
    final Map<String, Map<KubernetesConstants.VolumeConfigKeys, String>> configsPVC = KubernetesContext.getVolumeClaimTemplates(getConfiguration(), isExecutor);
    // Collect all Volume configurations from the CLI and generate Volumes and Volume Mounts.
    createVolumeAndMountsPersistentVolumeClaimCLI(configsPVC, volumes, volumeMounts);
    createVolumeAndMountsHostPathCLI(KubernetesContext.getVolumeHostPath(getConfiguration(), isExecutor), volumes, volumeMounts);
    createVolumeAndMountsEmptyDirCLI(KubernetesContext.getVolumeEmptyDir(getConfiguration(), isExecutor), volumes, volumeMounts);
    createVolumeAndMountsNFSCLI(KubernetesContext.getVolumeNFS(getConfiguration(), isExecutor), volumes, volumeMounts);
    final V1StatefulSet statefulSet = new V1StatefulSet();
    // Setup StatefulSet's metadata.
    final V1ObjectMeta objectMeta = new V1ObjectMeta().name(getStatefulSetName(isExecutor)).labels(getPodLabels(topologyName));
    statefulSet.setMetadata(objectMeta);
    // Create the StatefulSet Spec.
    // Reduce replica count by one for Executors and set to one for Manager.
    final int replicasCount = isExecutor ? Runtime.numContainers(runtimeConfiguration).intValue() - 1 : 1;
    final V1StatefulSetSpec statefulSetSpec = new V1StatefulSetSpec().serviceName(topologyName).replicas(replicasCount);
    // Parallel pod management tells the StatefulSet controller to launch or terminate
    // all Pods in parallel, and not to wait for Pods to become Running and Ready or completely
    // terminated prior to launching or terminating another Pod.
    statefulSetSpec.setPodManagementPolicy("Parallel");
    // Add selector match labels "app=heron" and "topology=topology-name"
    // so we know which pods to manage.
    final V1LabelSelector selector = new V1LabelSelector().matchLabels(getPodMatchLabels(topologyName));
    statefulSetSpec.setSelector(selector);
    // Create a Pod Template.
    final V1PodTemplateSpec podTemplateSpec = loadPodFromTemplate(isExecutor);
    // Set up Pod Metadata.
    final V1ObjectMeta templateMetaData = new V1ObjectMeta().labels(getPodLabels(topologyName));
    Map<String, String> annotations = new HashMap<>();
    annotations.putAll(getPodAnnotations());
    annotations.putAll(getPrometheusAnnotations());
    templateMetaData.setAnnotations(annotations);
    podTemplateSpec.setMetadata(templateMetaData);
    configurePodSpec(podTemplateSpec, containerResource, numberOfInstances, isExecutor, volumes, volumeMounts);
    statefulSetSpec.setTemplate(podTemplateSpec);
    statefulSet.setSpec(statefulSetSpec);
    statefulSetSpec.setVolumeClaimTemplates(createPersistentVolumeClaims(configsPVC));
    return statefulSet;
}
Also used : HashMap(java.util.HashMap) Config(org.apache.heron.spi.common.Config) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) LinkedList(java.util.LinkedList) V1VolumeMount(io.kubernetes.client.openapi.models.V1VolumeMount) V1Volume(io.kubernetes.client.openapi.models.V1Volume) V1StatefulSet(io.kubernetes.client.openapi.models.V1StatefulSet) V1StatefulSetSpec(io.kubernetes.client.openapi.models.V1StatefulSetSpec) V1PodTemplateSpec(io.kubernetes.client.openapi.models.V1PodTemplateSpec) V1LabelSelector(io.kubernetes.client.openapi.models.V1LabelSelector) Map(java.util.Map) HashMap(java.util.HashMap) V1ConfigMap(io.kubernetes.client.openapi.models.V1ConfigMap)

Aggregations

V1LabelSelector (io.kubernetes.client.openapi.models.V1LabelSelector)9 V1LabelSelectorRequirement (io.kubernetes.client.openapi.models.V1LabelSelectorRequirement)4 V1ObjectMeta (io.kubernetes.client.openapi.models.V1ObjectMeta)4 V1PodTemplateSpec (io.kubernetes.client.openapi.models.V1PodTemplateSpec)4 HashMap (java.util.HashMap)4 LinkedList (java.util.LinkedList)4 Test (org.junit.Test)4 V1StatefulSet (io.kubernetes.client.openapi.models.V1StatefulSet)3 V1StatefulSetSpec (io.kubernetes.client.openapi.models.V1StatefulSetSpec)3 IntOrString (io.kubernetes.client.custom.IntOrString)1 V1Patch (io.kubernetes.client.custom.V1Patch)1 ApiClient (io.kubernetes.client.openapi.ApiClient)1 ApiException (io.kubernetes.client.openapi.ApiException)1 AppsV1Api (io.kubernetes.client.openapi.apis.AppsV1Api)1 V1ConfigMap (io.kubernetes.client.openapi.models.V1ConfigMap)1 V1Container (io.kubernetes.client.openapi.models.V1Container)1 V1Deployment (io.kubernetes.client.openapi.models.V1Deployment)1 V1DeploymentBuilder (io.kubernetes.client.openapi.models.V1DeploymentBuilder)1 V1DeploymentSpec (io.kubernetes.client.openapi.models.V1DeploymentSpec)1 V1PodAffinity (io.kubernetes.client.openapi.models.V1PodAffinity)1