java icon indicating copy to clipboard operation
java copied to clipboard

I want to use JDK to call the rollback function of deploy, but after checking the source code, I failed. I want to implement the k8s command as an example kubectl rollout history deployment example-nginx --revision=2 -n nss

Open dengyichao opened this issue 9 months ago • 4 comments
trafficstars

Hello, I have written a large number of test cases on my end, but none of them were able to successfully roll back using Kubernetes Java JDK. I hope that experts can provide help. Below is my test case code and environment K8s version is: 1.21 Example of Writing: ` @Test public void rollbackDeploymentTest() { ApiClient apiClient = kubeClient.getApiClient(null); Configuration.setDefaultApiClient(apiClient); AppsV1Api appsV1Api = new AppsV1Api(apiClient);

    String deploymentName = "example-nginx";
    String namespace = "xxx-test";
    String revision = "4";

    try {
        //  Deployment
        V1Deployment deployment = appsV1Api.readNamespacedDeployment(deploymentName, namespace).execute();

        if (deployment == null) {
            System.err.println("not Deployment:" + deploymentName);
        }

        // Update Annotation, trigger rollback
        deployment.getMetadata().getAnnotations().put("deployment.kubernetes.io/revision", revision);

        // Update Deployment
        appsV1Api.replaceNamespacedDeployment(deploymentName, namespace, deployment);
        System.out.println("Rollback successful!");
    } catch (ApiException e) {
        // 打印详细错误日志
        System.err.println(" Deployment : " + e.getResponseBody());
        e.printStackTrace();
    }
}

@Test
public void test(){
    ApiClient apiClient = kubeClient.getApiClient(null);
    Configuration.setDefaultApiClient(apiClient);
    AppsV1Api appsV1Api = new AppsV1Api(apiClient);

    String deploymentName = "example-nginx";
    String namespace = "xxx-test";
    String revision = "3";

    Map<String, Object> patch = new HashMap<>();
    Map<String, Object> spec = new HashMap<>();
    Map<String, Object> rollbackTo = new HashMap<>();
    rollbackTo.put("revision", revision);
    spec.put("rollbackTo", rollbackTo);
    patch.put("spec", spec);


    String jsonPatch = JsonUtils.toJson(patch);

    try {
        V1Patch v1Patch = new V1Patch(jsonPatch);
        // Use merge patch+json format
        appsV1Api.patchNamespacedDeployment(deploymentName, namespace, v1Patch);
        PatchUtils.patch(V1Deployment.class, () -> appsV1Api.patchNamespacedDeployment(deploymentName, namespace, v1Patch).fieldManager("kubectl-rollout").buildCall(null), V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH, apiClient);

    } catch (ApiException e) {
        e.printStackTrace();
    }
}`

dengyichao avatar Feb 13 '25 08:02 dengyichao