001/*
002 * VM-Operator
003 * Copyright (C) 2024 Michael N. Lipp
004 * 
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
017 */
018
019package org.jdrupes.vmoperator.common;
020
021import io.kubernetes.client.Discovery.APIResource;
022import io.kubernetes.client.custom.V1Patch;
023import io.kubernetes.client.openapi.ApiException;
024import io.kubernetes.client.openapi.models.V1Deployment;
025import io.kubernetes.client.openapi.models.V1DeploymentList;
026import java.util.List;
027import java.util.Optional;
028
029/**
030 * A stub for pods (v1).
031 */
032@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
033public class K8sV1DeploymentStub
034        extends K8sGenericStub<V1Deployment, V1DeploymentList> {
035
036    /** The deployment's context. */
037    public static final APIResource CONTEXT = new APIResource("apps",
038        List.of("v1"), "v1", "Pod", true, "deployments", "deployment");
039
040    /**
041     * Instantiates a new stub.
042     *
043     * @param client the client
044     * @param namespace the namespace
045     * @param name the name
046     */
047    protected K8sV1DeploymentStub(K8sClient client, String namespace,
048            String name) {
049        super(V1Deployment.class, V1DeploymentList.class, client,
050            CONTEXT, namespace, name);
051    }
052
053    /**
054     * Scales the deployment.
055     *
056     * @param replicas the replicas
057     * @return the new model or empty if not successful
058     * @throws ApiException the API exception
059     */
060    public Optional<V1Deployment> scale(int replicas) throws ApiException {
061        return patch(V1Patch.PATCH_FORMAT_JSON_PATCH,
062            new V1Patch("[{\"op\": \"replace\", \"path\": \"/spec/replicas"
063                + "\", \"value\": " + replicas + "}]"),
064            client.defaultPatchOptions());
065    }
066
067    /**
068     * Gets the stub for the given namespace and name.
069     *
070     * @param client the client
071     * @param namespace the namespace
072     * @param name the name
073     * @return the deployment stub
074     */
075    public static K8sV1DeploymentStub get(K8sClient client, String namespace,
076            String name) {
077        return new K8sV1DeploymentStub(client, namespace, name);
078    }
079}