|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | +package org.netbeans.modules.cloud.oracle.assets; |
| 20 | + |
| 21 | +import io.fabric8.kubernetes.api.model.PodTemplateSpec; |
| 22 | +import io.fabric8.kubernetes.api.model.PodTemplateSpecBuilder; |
| 23 | +import io.fabric8.kubernetes.api.model.Secret; |
| 24 | +import io.fabric8.kubernetes.api.model.SecretList; |
| 25 | +import io.fabric8.kubernetes.api.model.ServiceAccount; |
| 26 | +import io.fabric8.kubernetes.api.model.ServiceAccountBuilder; |
| 27 | +import io.fabric8.kubernetes.api.model.ServiceAccountList; |
| 28 | +import java.util.Arrays; |
| 29 | +import java.util.Collections; |
| 30 | +import java.util.HashSet; |
| 31 | +import java.util.List; |
| 32 | +import java.util.Set; |
| 33 | +import java.util.concurrent.CompletableFuture; |
| 34 | +import org.netbeans.spi.lsp.CommandProvider; |
| 35 | +import org.openide.util.lookup.ServiceProvider; |
| 36 | +import io.fabric8.kubernetes.api.model.batch.v1.CronJobList; |
| 37 | +import io.fabric8.kubernetes.api.model.batch.v1.CronJob; |
| 38 | +import io.fabric8.kubernetes.api.model.batch.v1.CronJobBuilder; |
| 39 | +import io.fabric8.kubernetes.api.model.batch.v1.JobBuilder; |
| 40 | +import io.fabric8.kubernetes.api.model.rbac.ClusterRole; |
| 41 | +import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding; |
| 42 | +import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBindingBuilder; |
| 43 | +import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBindingList; |
| 44 | +import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBuilder; |
| 45 | +import io.fabric8.kubernetes.api.model.rbac.ClusterRoleList; |
| 46 | +import io.fabric8.kubernetes.client.KubernetesClient; |
| 47 | +import java.util.Calendar; |
| 48 | +import java.util.UUID; |
| 49 | +import java.util.concurrent.Executors; |
| 50 | +import java.util.concurrent.ScheduledExecutorService; |
| 51 | +import java.util.concurrent.ScheduledFuture; |
| 52 | +import java.util.concurrent.TimeUnit; |
| 53 | +import java.util.concurrent.TimeoutException; |
| 54 | +import java.util.function.Supplier; |
| 55 | +import org.netbeans.modules.cloud.oracle.NotificationUtils; |
| 56 | +import org.netbeans.modules.cloud.oracle.compute.ClusterItem; |
| 57 | +import org.openide.util.NbBundle; |
| 58 | + |
| 59 | +/** |
| 60 | + * |
| 61 | + * @author Dusan Petrovic |
| 62 | + */ |
| 63 | +@NbBundle.Messages({ |
| 64 | + "CronJobCreationError=Error while creating secret rotation CronJob" |
| 65 | +}) |
| 66 | +@ServiceProvider(service = CommandProvider.class) |
| 67 | +public class CreateSecretRotationCronJobCommand implements CommandProvider { |
| 68 | + |
| 69 | + private static final String COMMAND_CREATE_CRONJOB = "nbls.cloud.assets.cluster.cronjob.create"; //NOI18N |
| 70 | + private static final String SECRET_NAME = "docker-bearer-vscode-generated-ocirsecret"; //NOI18N |
| 71 | + private static final String CRONJOB_NAME = "secret-rotation-cronjob"; //NOI18N |
| 72 | + private static final String CLUSTER_ROLE_BINDING_NAME = "secret-manager-binding"; //NOI18N |
| 73 | + private static final String CLUSTER_ROLE_NAME = "secret-manager"; //NOI18N |
| 74 | + private static final String SERVICE_ACCOUNT_NAME = "create-secret-svc-account"; //NOI18N |
| 75 | + private static final String BASE_IMAGE = "ghcr.io/oracle/oci-cli:latest"; //NOI18N |
| 76 | + private static final String CONTAINER_NAME = "create-secret"; //NOI18N |
| 77 | + private static final int WAITING_TIMEOUT = 60; |
| 78 | + |
| 79 | + private static final Set COMMANDS = new HashSet<>(Arrays.asList( |
| 80 | + COMMAND_CREATE_CRONJOB |
| 81 | + )); |
| 82 | + |
| 83 | + private ClusterItem cluster; |
| 84 | + |
| 85 | + @Override |
| 86 | + public Set<String> getCommands() { |
| 87 | + return Collections.unmodifiableSet(COMMANDS); |
| 88 | + } |
| 89 | + |
| 90 | + @Override |
| 91 | + public CompletableFuture<Object> runCommand(String command, List<Object> arguments) { |
| 92 | + return createSecretRotationCronJob(); |
| 93 | + } |
| 94 | + |
| 95 | + public CompletableFuture<Object> createSecretRotationCronJob() { |
| 96 | + CompletableFuture completableFuture = new CompletableFuture(); |
| 97 | + this.cluster = CloudAssets.getDefault().getItem(ClusterItem.class); |
| 98 | + KubernetesUtils.runWithClient(cluster, client -> { |
| 99 | + try { |
| 100 | + ServiceAccount serviceAccount = createServiceAccountIfNotExist(client); |
| 101 | + createClusterRoleIfNotExist(client); |
| 102 | + createClusterRoleBindingIfNotExist(client); |
| 103 | + createCronJobIfNotExist(client, serviceAccount); |
| 104 | + completableFuture.complete(null); |
| 105 | + } catch(Exception ex) { |
| 106 | + completableFuture.completeExceptionally(ex); |
| 107 | + NotificationUtils.showErrorMessage(Bundle.CronJobCreationError()); |
| 108 | + } |
| 109 | + }); |
| 110 | + return completableFuture; |
| 111 | + } |
| 112 | + |
| 113 | + private void createCronJobIfNotExist(KubernetesClient client, ServiceAccount serviceAccount) { |
| 114 | + CronJobList existingCronJobs = client.batch().v1().cronjobs().inNamespace(cluster.getNamespace()).list(); |
| 115 | + CronJob cronJob = (CronJob) KubernetesUtils.findResource(client, existingCronJobs, CRONJOB_NAME); |
| 116 | + if (cronJob != null) { |
| 117 | + if (!secretExist(client)) { |
| 118 | + invokeCronJob(client, cronJob); |
| 119 | + } |
| 120 | + return; |
| 121 | + } |
| 122 | + cronJob = new CronJobBuilder() |
| 123 | + .withNewMetadata() |
| 124 | + .withName(CRONJOB_NAME) |
| 125 | + .withNamespace(cluster.getNamespace()) |
| 126 | + .endMetadata() |
| 127 | + .withNewSpec() |
| 128 | + .withSchedule(getCronExpression()) |
| 129 | + .withNewJobTemplate() |
| 130 | + .withNewSpec() |
| 131 | + .withBackoffLimit(0) |
| 132 | + .withTemplate(cronJobPodTemplate(serviceAccount)) |
| 133 | + .endSpec() |
| 134 | + .endJobTemplate() |
| 135 | + .endSpec() |
| 136 | + .build(); |
| 137 | + |
| 138 | + client.batch().v1() |
| 139 | + .cronjobs() |
| 140 | + .inNamespace(cluster.getNamespace()) |
| 141 | + .resource(cronJob) |
| 142 | + .create(); |
| 143 | + |
| 144 | + invokeCronJob(client, cronJob); |
| 145 | + } |
| 146 | + |
| 147 | + private boolean secretExist(KubernetesClient client) { |
| 148 | + SecretList existingSecrets = client.secrets().inNamespace(cluster.getNamespace()).list(); |
| 149 | + Secret secret = (Secret) KubernetesUtils.findResource(client, existingSecrets, SECRET_NAME); |
| 150 | + return secret != null; |
| 151 | + } |
| 152 | + |
| 153 | + private void invokeCronJob(KubernetesClient client, CronJob cronJob) { |
| 154 | + client.batch().v1() |
| 155 | + .jobs() |
| 156 | + .inNamespace(cluster.getNamespace()) |
| 157 | + .resource(new JobBuilder() |
| 158 | + .withNewMetadata() |
| 159 | + .withName("cronjob-invocation-" + UUID.randomUUID()) //NOI18N |
| 160 | + .endMetadata() |
| 161 | + .withSpec(cronJob.getSpec().getJobTemplate().getSpec()) |
| 162 | + .build()) |
| 163 | + .create(); |
| 164 | + |
| 165 | + waitForConditionWithTimeout(() -> { |
| 166 | + return secretExist(client); |
| 167 | + }, WAITING_TIMEOUT).join(); |
| 168 | + } |
| 169 | + |
| 170 | + private CompletableFuture<Void> waitForConditionWithTimeout(Supplier<Boolean> condition, long timeout) { |
| 171 | + CompletableFuture<Void> future = new CompletableFuture<>(); |
| 172 | + |
| 173 | + ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); |
| 174 | + |
| 175 | + ScheduledFuture<?> checkTask = executor.scheduleAtFixedRate(() -> { |
| 176 | + if (condition.get()) { |
| 177 | + future.complete(null); |
| 178 | + } |
| 179 | + }, 0, 5, TimeUnit.SECONDS); |
| 180 | + |
| 181 | + executor.schedule(() -> { |
| 182 | + if (!future.isDone()) { |
| 183 | + future.completeExceptionally(new TimeoutException("Condition was not met within the timeout.")); //NOI18N |
| 184 | + } |
| 185 | + checkTask.cancel(true); |
| 186 | + executor.shutdown(); |
| 187 | + }, timeout, TimeUnit.SECONDS); |
| 188 | + |
| 189 | + return future; |
| 190 | + } |
| 191 | + |
| 192 | + private String getCronExpression() { |
| 193 | + Calendar calendar = Calendar.getInstance(); |
| 194 | + int currentMinute = calendar.get(Calendar.MINUTE); |
| 195 | + return currentMinute + " * * * *"; |
| 196 | + } |
| 197 | + |
| 198 | + private PodTemplateSpec cronJobPodTemplate(ServiceAccount serviceAccount) { |
| 199 | + return new PodTemplateSpecBuilder() |
| 200 | + .withNewSpec() |
| 201 | + .withHostNetwork(Boolean.TRUE) |
| 202 | + .addNewContainer() |
| 203 | + .withName(CONTAINER_NAME) |
| 204 | + .withImage(BASE_IMAGE) |
| 205 | + .addNewEnv() |
| 206 | + .withName("OCI_CLI_AUTH") //NOI18N |
| 207 | + .withValue("instance_principal") //NOI18N |
| 208 | + .endEnv() |
| 209 | + .withCommand("/bin/bash", "-c", createSecretCommand()) //NOI18N |
| 210 | + .endContainer() |
| 211 | + .withRestartPolicy("Never") //NOI18N |
| 212 | + .withServiceAccountName(serviceAccount.getMetadata().getName()) |
| 213 | + .endSpec() |
| 214 | + .build(); |
| 215 | + } |
| 216 | + |
| 217 | + private ServiceAccount createServiceAccountIfNotExist(KubernetesClient client) { |
| 218 | + ServiceAccountList existingServiceAccounts = client.serviceAccounts().inNamespace(cluster.getNamespace()).list(); |
| 219 | + ServiceAccount serviceAccount = (ServiceAccount) KubernetesUtils.findResource(client, existingServiceAccounts, SERVICE_ACCOUNT_NAME); |
| 220 | + if (serviceAccount != null) { |
| 221 | + return serviceAccount; |
| 222 | + } |
| 223 | + serviceAccount = new ServiceAccountBuilder() |
| 224 | + .withNewMetadata() |
| 225 | + .withName(SERVICE_ACCOUNT_NAME) |
| 226 | + .endMetadata() |
| 227 | + .build(); |
| 228 | + |
| 229 | + return client.serviceAccounts() |
| 230 | + .inNamespace(cluster.getNamespace()) |
| 231 | + .resource(serviceAccount) |
| 232 | + .create(); |
| 233 | + } |
| 234 | + |
| 235 | + private void createClusterRoleIfNotExist(KubernetesClient client) { |
| 236 | + ClusterRoleList existingClusterRole = client.rbac().clusterRoles().list(); |
| 237 | + ClusterRole clusterRole = (ClusterRole) KubernetesUtils.findResource(client, existingClusterRole, CLUSTER_ROLE_NAME); |
| 238 | + if (clusterRole != null) { |
| 239 | + return; |
| 240 | + } |
| 241 | + clusterRole = new ClusterRoleBuilder() |
| 242 | + .withNewMetadata() |
| 243 | + .withName(CLUSTER_ROLE_NAME) |
| 244 | + .endMetadata() |
| 245 | + .addNewRule() |
| 246 | + .withApiGroups("") |
| 247 | + .withResources("secrets") //NOI18N |
| 248 | + .withVerbs("create", "get", "patch", "delete") //NOI18N |
| 249 | + .endRule() |
| 250 | + .build(); |
| 251 | + |
| 252 | + client.rbac().clusterRoles() |
| 253 | + .resource(clusterRole) |
| 254 | + .create(); |
| 255 | + } |
| 256 | + |
| 257 | + private void createClusterRoleBindingIfNotExist(KubernetesClient client) { |
| 258 | + ClusterRoleBindingList existingClusterRoleBinding = client.rbac().clusterRoleBindings().list(); |
| 259 | + ClusterRoleBinding clusterRoleBinding = (ClusterRoleBinding) KubernetesUtils.findResource(client, existingClusterRoleBinding, CLUSTER_ROLE_BINDING_NAME); |
| 260 | + if (clusterRoleBinding != null) { |
| 261 | + return; |
| 262 | + } |
| 263 | + clusterRoleBinding = new ClusterRoleBindingBuilder() |
| 264 | + .withNewMetadata() |
| 265 | + .withName(CLUSTER_ROLE_BINDING_NAME) |
| 266 | + .endMetadata() |
| 267 | + .addNewSubject() |
| 268 | + .withName(SERVICE_ACCOUNT_NAME) |
| 269 | + .withKind("ServiceAccount") //NOI18N |
| 270 | + .withNamespace(cluster.getNamespace()) |
| 271 | + .endSubject() |
| 272 | + .withNewRoleRef() |
| 273 | + .withKind("ClusterRole") //NOI18N |
| 274 | + .withName(CLUSTER_ROLE_NAME) |
| 275 | + .withApiGroup("rbac.authorization.k8s.io") //NOI18N |
| 276 | + .endRoleRef() |
| 277 | + .build(); |
| 278 | + |
| 279 | + client.rbac().clusterRoleBindings() |
| 280 | + .resource(clusterRoleBinding) |
| 281 | + .create(); |
| 282 | + } |
| 283 | + |
| 284 | + private String createSecretCommand() { |
| 285 | + String repoEndpoint = cluster.getRegionCode() + ".ocir.io"; //NOI18N |
| 286 | + return |
| 287 | + "KUBECTL_VERSION=\"v1.27.4\"\n" + //NOI18N |
| 288 | + "case \"$(uname -m)\" in\n" + //NOI18N |
| 289 | + " x86_64) ARCHITECTURE=\"amd64\" ;;\n" + //NOI18N |
| 290 | + " aarch64) ARCHITECTURE=\"arm64\" ;;\n" + //NOI18N |
| 291 | + " *) ARCHITECTURE=\"Unknown architecture\" ;;\n" + //NOI18N |
| 292 | + "esac\n" + //NOI18N |
| 293 | + "KUBECTL_URL=\"https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/${ARCHITECTURE}/kubectl\"\n" + //NOI18N |
| 294 | + "mkdir -p /tmp/bin\n" + //NOI18N |
| 295 | + "curl -LO \"${KUBECTL_URL}\"\n" + //NOI18N |
| 296 | + "chmod +x ./kubectl\n" + //NOI18N |
| 297 | + "mv ./kubectl /tmp/bin/kubectl\n" + //NOI18N |
| 298 | + "export PATH=$PATH:/tmp/bin\n" + //NOI18N |
| 299 | + "TOKEN=$(oci raw-request --http-method GET --target-uri https://" + repoEndpoint + "/20180419/docker/token | jq -r '.data.token')\n" + //NOI18N |
| 300 | + "kubectl create secret --save-config --dry-run=client docker-registry " + SECRET_NAME + " --docker-server=" + repoEndpoint + " --docker-username=BEARER_TOKEN --docker-password=\"$TOKEN\" -o yaml | kubectl apply -f - "; //NOI18N |
| 301 | + } |
| 302 | + |
| 303 | +} |
0 commit comments