|
| 1 | +package io.kubernetes.client.util.conversion; |
| 2 | + |
| 3 | +import io.kubernetes.client.openapi.models.V1Job; |
| 4 | +import io.kubernetes.client.openapi.models.V1JobSpec; |
| 5 | +import io.kubernetes.client.openapi.models.V1ObjectMeta; |
| 6 | +import io.kubernetes.client.openapi.models.V1OwnerReference; |
| 7 | +import io.kubernetes.client.openapi.models.V1beta1CronJob; |
| 8 | +import io.kubernetes.client.openapi.models.V1beta1CronJobSpec; |
| 9 | +import java.util.Arrays; |
| 10 | +import java.util.HashMap; |
| 11 | +import java.util.Map; |
| 12 | + |
| 13 | +public class Jobs { |
| 14 | + |
| 15 | + /** |
| 16 | + * Convert V1beta1CronJob object into V1Job object, based on kubectl code |
| 17 | + * https://github.com/kubernetes/kubectl/blob/master/pkg/cmd/create/create_job.go |
| 18 | + * |
| 19 | + * @param cronJob cronJob object (required) |
| 20 | + * @param jobName cronJob name |
| 21 | + * @return V1Job object |
| 22 | + */ |
| 23 | + public static V1Job cronJobToJob(V1beta1CronJob cronJob, String jobName) { |
| 24 | + |
| 25 | + Map<String, String> annotations = new HashMap<>(); |
| 26 | + Map<String, String> labels = new HashMap<>(); |
| 27 | + V1JobSpec jobSpec = null; |
| 28 | + |
| 29 | + V1beta1CronJobSpec cronJobSpec = cronJob.getSpec(); |
| 30 | + |
| 31 | + if (cronJobSpec != null && cronJobSpec.getJobTemplate() != null) { |
| 32 | + V1ObjectMeta metadata = cronJobSpec.getJobTemplate().getMetadata(); |
| 33 | + if (metadata != null) { |
| 34 | + if (metadata.getAnnotations() != null) { |
| 35 | + annotations.putAll(metadata.getAnnotations()); |
| 36 | + } |
| 37 | + if (metadata.getLabels() != null) { |
| 38 | + labels.putAll(metadata.getLabels()); |
| 39 | + } |
| 40 | + } |
| 41 | + jobSpec = cronJobSpec.getJobTemplate().getSpec(); |
| 42 | + } |
| 43 | + |
| 44 | + annotations.put("cronjob.kubernetes.io/instantiate", "manual"); |
| 45 | + |
| 46 | + V1OwnerReference v1OwnerReference = new V1OwnerReference(); |
| 47 | + v1OwnerReference.setKind("CronJob"); |
| 48 | + v1OwnerReference.setName(cronJob.getMetadata().getName()); |
| 49 | + v1OwnerReference.setBlockOwnerDeletion(true); |
| 50 | + v1OwnerReference.setController(true); |
| 51 | + v1OwnerReference.setUid(cronJob.getMetadata().getUid()); |
| 52 | + v1OwnerReference.setApiVersion("batch/v1beta1"); |
| 53 | + |
| 54 | + V1ObjectMeta jobMetadata = new V1ObjectMeta(); |
| 55 | + jobMetadata.setName(jobName != null ? jobName : cronJob.getMetadata().getName() + "-manual"); |
| 56 | + jobMetadata.setAnnotations(annotations); |
| 57 | + jobMetadata.setLabels(labels); |
| 58 | + jobMetadata.setOwnerReferences(Arrays.asList(v1OwnerReference)); |
| 59 | + |
| 60 | + V1Job job = new V1Job(); |
| 61 | + job.setKind("Job"); |
| 62 | + job.setApiVersion("batch/v1"); |
| 63 | + job.setMetadata(jobMetadata); |
| 64 | + job.setSpec(jobSpec); |
| 65 | + |
| 66 | + return job; |
| 67 | + } |
| 68 | +} |
0 commit comments