|
| 1 | +package dev.lsegal.jenkins.codebuilder; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.Arrays; |
| 6 | +import java.util.Collection; |
| 7 | +import java.util.Collections; |
| 8 | +import java.util.List; |
| 9 | +import java.util.concurrent.Future; |
| 10 | + |
| 11 | +import javax.annotation.CheckForNull; |
| 12 | +import javax.annotation.Nonnull; |
| 13 | +import javax.annotation.Nullable; |
| 14 | + |
| 15 | +import com.amazonaws.ClientConfiguration; |
| 16 | +import com.amazonaws.SdkClientException; |
| 17 | +import com.amazonaws.regions.DefaultAwsRegionProviderChain; |
| 18 | +import com.amazonaws.regions.Region; |
| 19 | +import com.amazonaws.regions.RegionUtils; |
| 20 | +import com.amazonaws.services.codebuild.AWSCodeBuild; |
| 21 | +import com.amazonaws.services.codebuild.AWSCodeBuildClientBuilder; |
| 22 | +import com.amazonaws.services.codebuild.model.ListProjectsRequest; |
| 23 | +import com.amazonaws.services.codebuild.model.ListProjectsResult; |
| 24 | +import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsHelper; |
| 25 | +import com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials; |
| 26 | + |
| 27 | +import org.apache.commons.lang.RandomStringUtils; |
| 28 | +import org.apache.commons.lang.StringUtils; |
| 29 | +import org.kohsuke.stapler.DataBoundConstructor; |
| 30 | +import org.kohsuke.stapler.DataBoundSetter; |
| 31 | +import org.kohsuke.stapler.QueryParameter; |
| 32 | +import org.slf4j.Logger; |
| 33 | +import org.slf4j.LoggerFactory; |
| 34 | + |
| 35 | +import hudson.Extension; |
| 36 | +import hudson.ProxyConfiguration; |
| 37 | +import hudson.model.Computer; |
| 38 | +import hudson.model.Descriptor; |
| 39 | +import hudson.model.Label; |
| 40 | +import hudson.model.Node; |
| 41 | +import hudson.model.labels.LabelAtom; |
| 42 | +import hudson.slaves.Cloud; |
| 43 | +import hudson.slaves.NodeProvisioner; |
| 44 | +import hudson.slaves.NodeProvisioner.PlannedNode; |
| 45 | +import hudson.util.ListBoxModel; |
| 46 | +import jenkins.model.Jenkins; |
| 47 | +import jenkins.model.JenkinsLocationConfiguration; |
| 48 | + |
| 49 | +public class CodeBuilderCloud extends Cloud { |
| 50 | + private static final Logger LOGGER = LoggerFactory.getLogger(CodeBuilderCloud.class); |
| 51 | + private static final String DEFAULT_JNLP_IMAGE = "lsegal/jnlp-docker-agent:latest"; |
| 52 | + private static final int DEFAULT_AGENT_TIMEOUT = 120; |
| 53 | + private static final String DEFAULT_COMPUTE_TYPE = "BUILD_GENERAL1_SMALL"; |
| 54 | + |
| 55 | + static { |
| 56 | + clearAllNodes(); |
| 57 | + } |
| 58 | + |
| 59 | + @Nonnull |
| 60 | + private final String projectName; |
| 61 | + |
| 62 | + @Nonnull |
| 63 | + private final String credentialsId; |
| 64 | + |
| 65 | + @Nonnull |
| 66 | + private final String region; |
| 67 | + |
| 68 | + private String label; |
| 69 | + private String computeType; |
| 70 | + private String jenkinsUrl; |
| 71 | + private String jnlpImage; |
| 72 | + private int agentTimeout; |
| 73 | + |
| 74 | + private transient AWSCodeBuild client; |
| 75 | + |
| 76 | + @DataBoundConstructor |
| 77 | + public CodeBuilderCloud(String name, @Nonnull String projectName, @Nullable String credentialsId, |
| 78 | + @Nonnull String region) throws InterruptedException { |
| 79 | + super("codebuilder_" + Jenkins.get().clouds.size()); |
| 80 | + |
| 81 | + this.projectName = projectName; |
| 82 | + this.credentialsId = credentialsId; |
| 83 | + if (StringUtils.isBlank(region)) { |
| 84 | + this.region = getDefaultRegion(); |
| 85 | + } else { |
| 86 | + this.region = region; |
| 87 | + } |
| 88 | + |
| 89 | + LOGGER.info("[CodeBuilder]: Initializing Cloud: {}", this); |
| 90 | + } |
| 91 | + |
| 92 | + /** |
| 93 | + * Clear all CodeBuilder nodes on boot-up because these cannot be permanent. |
| 94 | + */ |
| 95 | + private static void clearAllNodes() { |
| 96 | + List<Node> nodes = Jenkins.get().getNodes(); |
| 97 | + if (nodes.size() == 0) { |
| 98 | + return; |
| 99 | + } |
| 100 | + |
| 101 | + LOGGER.info("[CodeBuilder]: Clearing all previous CodeBuilder nodes..."); |
| 102 | + for (final Node n : nodes) { |
| 103 | + if (n instanceof CodeBuilderAgent) { |
| 104 | + try { |
| 105 | + ((CodeBuilderAgent) n).terminate(); |
| 106 | + } catch (InterruptedException | IOException e) { |
| 107 | + LOGGER.error("[CodeBuilder]: Failed to terminate agent '{}'", n.getDisplayName(), e); |
| 108 | + } |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + @Override |
| 114 | + public String toString() { |
| 115 | + return String.format("%s<%s>", name, projectName); |
| 116 | + } |
| 117 | + |
| 118 | + @Nonnull |
| 119 | + public String getProjectName() { |
| 120 | + return projectName; |
| 121 | + } |
| 122 | + |
| 123 | + @Nonnull |
| 124 | + public String getRegion() { |
| 125 | + return region; |
| 126 | + } |
| 127 | + |
| 128 | + @Nonnull |
| 129 | + public String getLabel() { |
| 130 | + return StringUtils.isBlank(label) ? "" : label; |
| 131 | + } |
| 132 | + |
| 133 | + @DataBoundSetter |
| 134 | + public void setLabel(String label) { |
| 135 | + this.label = label; |
| 136 | + } |
| 137 | + |
| 138 | + @Nonnull |
| 139 | + public String getJenkinsUrl() { |
| 140 | + if (StringUtils.isNotBlank(jenkinsUrl)) { |
| 141 | + return jenkinsUrl; |
| 142 | + } else { |
| 143 | + JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get(); |
| 144 | + if (config != null) { |
| 145 | + return config.getUrl(); |
| 146 | + } |
| 147 | + } |
| 148 | + return "unknown"; |
| 149 | + } |
| 150 | + |
| 151 | + @DataBoundSetter |
| 152 | + public void setJenkinsUrl(String jenkinsUrl) { |
| 153 | + JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get(); |
| 154 | + if (config != null && config.getUrl() == jenkinsUrl) { |
| 155 | + return; |
| 156 | + } |
| 157 | + this.jenkinsUrl = jenkinsUrl; |
| 158 | + } |
| 159 | + |
| 160 | + @Nonnull |
| 161 | + public String getJnlpImage() { |
| 162 | + return StringUtils.isBlank(jnlpImage) ? DEFAULT_JNLP_IMAGE : jnlpImage; |
| 163 | + } |
| 164 | + |
| 165 | + @DataBoundSetter |
| 166 | + public void setJnlpImage(String jnlpImage) { |
| 167 | + this.jnlpImage = jnlpImage; |
| 168 | + } |
| 169 | + |
| 170 | + @Nonnull |
| 171 | + public int getAgentTimeout() { |
| 172 | + return agentTimeout == 0 ? DEFAULT_AGENT_TIMEOUT : agentTimeout; |
| 173 | + } |
| 174 | + |
| 175 | + @DataBoundSetter |
| 176 | + public void setAgentTimeout(int agentTimeout) { |
| 177 | + this.agentTimeout = agentTimeout; |
| 178 | + } |
| 179 | + |
| 180 | + @Nonnull |
| 181 | + public String getComputeType() { |
| 182 | + return StringUtils.isBlank(computeType) ? DEFAULT_COMPUTE_TYPE : computeType; |
| 183 | + } |
| 184 | + |
| 185 | + @DataBoundSetter |
| 186 | + public void setComputeType(String computeType) { |
| 187 | + this.computeType = computeType; |
| 188 | + } |
| 189 | + |
| 190 | + @CheckForNull |
| 191 | + private static AmazonWebServicesCredentials getCredentials(@Nullable String credentialsId) { |
| 192 | + return AWSCredentialsHelper.getCredentials(credentialsId, Jenkins.get()); |
| 193 | + } |
| 194 | + |
| 195 | + private static AWSCodeBuild buildClient(String credentialsId, String region) { |
| 196 | + ProxyConfiguration proxy = Jenkins.get().proxy; |
| 197 | + ClientConfiguration clientConfiguration = new ClientConfiguration(); |
| 198 | + |
| 199 | + if (proxy != null) { |
| 200 | + clientConfiguration.setProxyHost(proxy.name); |
| 201 | + clientConfiguration.setProxyPort(proxy.port); |
| 202 | + clientConfiguration.setProxyUsername(proxy.getUserName()); |
| 203 | + clientConfiguration.setProxyPassword(proxy.getPassword()); |
| 204 | + } |
| 205 | + |
| 206 | + AWSCodeBuildClientBuilder builder = AWSCodeBuildClientBuilder.standard() |
| 207 | + .withClientConfiguration(clientConfiguration).withRegion(region); |
| 208 | + |
| 209 | + AmazonWebServicesCredentials credentials = getCredentials(credentialsId); |
| 210 | + if (credentials != null) { |
| 211 | + String awsAccessKeyId = credentials.getCredentials().getAWSAccessKeyId(); |
| 212 | + String obfuscatedAccessKeyId = StringUtils.left(awsAccessKeyId, 4) |
| 213 | + + StringUtils.repeat("*", awsAccessKeyId.length() - 8) + StringUtils.right(awsAccessKeyId, 4); |
| 214 | + LOGGER.debug("[CodeBuilder]: Using credentials: {}", obfuscatedAccessKeyId); |
| 215 | + builder.withCredentials(credentials); |
| 216 | + } |
| 217 | + LOGGER.debug("[CodeBuilder]: Selected Region: {}", region); |
| 218 | + |
| 219 | + return builder.build(); |
| 220 | + } |
| 221 | + |
| 222 | + public synchronized AWSCodeBuild getClient() { |
| 223 | + if (this.client == null) { |
| 224 | + this.client = CodeBuilderCloud.buildClient(credentialsId, region); |
| 225 | + } |
| 226 | + return this.client; |
| 227 | + } |
| 228 | + |
| 229 | + private transient long lastProvisionTime = 0; |
| 230 | + |
| 231 | + @Override |
| 232 | + public synchronized Collection<PlannedNode> provision(Label label, int excessWorkload) { |
| 233 | + List<NodeProvisioner.PlannedNode> list = new ArrayList<NodeProvisioner.PlannedNode>(); |
| 234 | + |
| 235 | + // guard against non-matching labels |
| 236 | + if (label != null && !label.matches(Arrays.asList(new LabelAtom(getLabel())))) { |
| 237 | + return list; |
| 238 | + } |
| 239 | + |
| 240 | + // guard against double-provisioning with a 500ms cooldown clock |
| 241 | + long timeDiff = System.currentTimeMillis() - lastProvisionTime; |
| 242 | + if (timeDiff < 500) { |
| 243 | + LOGGER.info("[CodeBuilder]: Provision of {} skipped, still on cooldown ({}ms of 500ms)", excessWorkload, |
| 244 | + timeDiff); |
| 245 | + return list; |
| 246 | + } |
| 247 | + |
| 248 | + String labelName = label == null ? getLabel() : label.getDisplayName(); |
| 249 | + long stillProvisioning = numStillProvisioning(); |
| 250 | + long numToLaunch = Math.max(excessWorkload - stillProvisioning, 0); |
| 251 | + LOGGER.info("[CodeBuilder]: Provisioning {} nodes for label '{}' ({} already provisioning)", numToLaunch, labelName, |
| 252 | + stillProvisioning); |
| 253 | + |
| 254 | + for (int i = 0; i < numToLaunch; i++) { |
| 255 | + final String suffix = RandomStringUtils.randomAlphabetic(4); |
| 256 | + final String displayName = String.format("%s.cb-%s", projectName, suffix); |
| 257 | + final CodeBuilderCloud cloud = this; |
| 258 | + final Future<Node> nodeResolver = Computer.threadPoolForRemoting.submit(() -> { |
| 259 | + CodeBuilderLauncher launcher = new CodeBuilderLauncher(cloud); |
| 260 | + CodeBuilderAgent agent = new CodeBuilderAgent(cloud, displayName, launcher); |
| 261 | + Jenkins.get().addNode(agent); |
| 262 | + return agent; |
| 263 | + }); |
| 264 | + list.add(new NodeProvisioner.PlannedNode(displayName, nodeResolver, 1)); |
| 265 | + } |
| 266 | + |
| 267 | + lastProvisionTime = System.currentTimeMillis(); |
| 268 | + return list; |
| 269 | + } |
| 270 | + |
| 271 | + /** |
| 272 | + * Find the number of {@link CodeBuilderAgent} instances still connecting to |
| 273 | + * Jenkins host. |
| 274 | + */ |
| 275 | + private long numStillProvisioning() { |
| 276 | + return Jenkins.get().getNodes().stream().filter(CodeBuilderAgent.class::isInstance) |
| 277 | + .map(CodeBuilderAgent.class::cast).filter(a -> a.getLauncher().isLaunchSupported()).count(); |
| 278 | + } |
| 279 | + |
| 280 | + @Override |
| 281 | + public boolean canProvision(Label label) { |
| 282 | + boolean canProvision = label == null ? true : label.matches(Arrays.asList(new LabelAtom(getLabel()))); |
| 283 | + LOGGER.info("[CodeBuilder]: Check provisioning capabilities for label '{}': {}", label, canProvision); |
| 284 | + return canProvision; |
| 285 | + } |
| 286 | + |
| 287 | + private static String getDefaultRegion() { |
| 288 | + try { |
| 289 | + return new DefaultAwsRegionProviderChain().getRegion(); |
| 290 | + } catch (SdkClientException exc) { |
| 291 | + return null; |
| 292 | + } |
| 293 | + } |
| 294 | + |
| 295 | + @Extension |
| 296 | + public static class DescriptorImpl extends Descriptor<Cloud> { |
| 297 | + @Override |
| 298 | + public String getDisplayName() { |
| 299 | + return Messages.displayName(); |
| 300 | + } |
| 301 | + |
| 302 | + public String getDefaultJnlpImage() { |
| 303 | + return DEFAULT_JNLP_IMAGE; |
| 304 | + } |
| 305 | + |
| 306 | + public int getDefaultAgentTimeout() { |
| 307 | + return DEFAULT_AGENT_TIMEOUT; |
| 308 | + } |
| 309 | + |
| 310 | + public String getDefaultComputeType() { |
| 311 | + return DEFAULT_COMPUTE_TYPE; |
| 312 | + } |
| 313 | + |
| 314 | + public ListBoxModel doFillCredentialsIdItems() { |
| 315 | + return AWSCredentialsHelper.doFillCredentialsIdItems(Jenkins.get()); |
| 316 | + } |
| 317 | + |
| 318 | + public ListBoxModel doFillRegionItems() { |
| 319 | + final ListBoxModel options = new ListBoxModel(); |
| 320 | + |
| 321 | + String defaultRegion = getDefaultRegion(); |
| 322 | + if (StringUtils.isNotBlank(defaultRegion)) { |
| 323 | + options.add(defaultRegion); |
| 324 | + } |
| 325 | + |
| 326 | + for (Region r : RegionUtils.getRegionsForService(AWSCodeBuild.ENDPOINT_PREFIX)) { |
| 327 | + if (r.getName() == defaultRegion) { |
| 328 | + continue; |
| 329 | + } |
| 330 | + options.add(r.getName()); |
| 331 | + } |
| 332 | + return options; |
| 333 | + } |
| 334 | + |
| 335 | + public ListBoxModel doFillProjectNameItems(@QueryParameter String credentialsId, @QueryParameter String region) { |
| 336 | + if (StringUtils.isBlank(region)) { |
| 337 | + region = getDefaultRegion(); |
| 338 | + if (StringUtils.isBlank(region)) { |
| 339 | + return new ListBoxModel(); |
| 340 | + } |
| 341 | + } |
| 342 | + |
| 343 | + try { |
| 344 | + final List<String> projects = new ArrayList<String>(); |
| 345 | + String lastToken = null; |
| 346 | + do { |
| 347 | + ListProjectsResult result = CodeBuilderCloud.buildClient(credentialsId, region) |
| 348 | + .listProjects(new ListProjectsRequest().withNextToken(lastToken)); |
| 349 | + projects.addAll(result.getProjects()); |
| 350 | + lastToken = result.getNextToken(); |
| 351 | + } while (lastToken != null); |
| 352 | + Collections.sort(projects); |
| 353 | + final ListBoxModel options = new ListBoxModel(); |
| 354 | + for (final String arn : projects) { |
| 355 | + options.add(arn); |
| 356 | + } |
| 357 | + return options; |
| 358 | + } catch (RuntimeException e) { |
| 359 | + // missing credentials will throw an "AmazonClientException: Unable to load AWS |
| 360 | + // credentials from any provider in the chain" |
| 361 | + LOGGER.error("[CodeBuilder]: Exception listing projects (region={})", region, e); |
| 362 | + return new ListBoxModel(); |
| 363 | + } |
| 364 | + } |
| 365 | + |
| 366 | + public String getDefaultRegion() { |
| 367 | + return CodeBuilderCloud.getDefaultRegion(); |
| 368 | + } |
| 369 | + } |
| 370 | +} |
0 commit comments