) t -> null);
138 | }
139 |
140 | public static BasicSSHUserPrivateKey assertSshKey(String credentialsId) {
141 | final BasicSSHUserPrivateKey privateKey = CredentialsMatchers.firstOrNull(
142 | CredentialsProvider.lookupCredentialsInItemGroup(BasicSSHUserPrivateKey.class, Jenkins.get(), ACL.SYSTEM2,
143 | Collections.emptyList()),
144 | CredentialsMatchers.withId(credentialsId));
145 |
146 | Preconditions.checkState(privateKey != null,
147 | "No SSH credentials found with ID '%s'", credentialsId);
148 |
149 | return privateKey;
150 | }
151 |
152 | public static String getStringOrDefault(String value, String defValue) {
153 | if(Strings.isNullOrEmpty(value)) {
154 | return defValue;
155 | }
156 | return value;
157 | }
158 |
159 | @RequiredArgsConstructor
160 | public static class LogAdapter {
161 | private static final SimpleFormatter FORMATTER = new SimpleFormatter();
162 | @Getter
163 | private final PrintStream stream;
164 | private final Logger logger;
165 |
166 | public void info(String message) {
167 | logger.info(message);
168 | final LogRecord rec = new LogRecord(Level.INFO, message);
169 | rec.setLoggerName(logger.getName());
170 | stream.println(FORMATTER.format(rec));
171 | }
172 |
173 | public void error(String message, Throwable cause) {
174 | logger.error(message, cause);
175 | final LogRecord rec = new LogRecord(Level.SEVERE, message + " Cause: " + cause);
176 | rec.setLoggerName(logger.getName());
177 | rec.setThrown(cause);
178 | stream.println(FORMATTER.format(rec));
179 | }
180 | }
181 |
182 | /**
183 | * Check if idle server can be shut down.
184 | *
185 | * According to Hetzner billing policy,
186 | * you are billed for every hour of existence of server, so it makes sense to keep server running as long as next hour did
187 | * not start yet.
188 | *
189 | * @param createdStr RFC3339-formatted instant when server was created. See ServerDetail#getCreated().
190 | * @param currentTime current time. Kept as argument to allow unit-testing.
191 | * @return true if server should be shut down, false otherwise.
192 | * Note: we keep small time buffer for corner cases like clock skew or Jenkins's queue manager overload, which could
193 | * lead to unnecessary 1-hour over-billing.
194 | */
195 | public static boolean canShutdownServer(@NonNull String createdStr, LocalDateTime currentTime) {
196 | final LocalDateTime created = LocalDateTime.from(DateTimeFormatter.ISO_DATE_TIME.parse(createdStr))
197 | .atOffset(ZoneOffset.UTC).toLocalDateTime();
198 | long diff = Duration.between(created, currentTime.atOffset(ZoneOffset.UTC).toLocalDateTime()).toMinutes() % 60;
199 | return (60 - SHUTDOWN_TIME_BUFFER) <= diff;
200 | }
201 |
202 | /**
203 | * Get all nodes that are {@link HetznerServerAgent}.
204 | *
205 | * @return list of all {@link HetznerServerAgent} nodes
206 | */
207 | public static List getHetznerAgents() {
208 | return Jenkins.get().getNodes()
209 | .stream()
210 | .filter(HetznerServerAgent.class::isInstance)
211 | .map(HetznerServerAgent.class::cast)
212 | .collect(Collectors.toList());
213 | }
214 |
215 | public static boolean isValidLabelValue(String value) {
216 | if (Strings.isNullOrEmpty(value)) {
217 | return false;
218 | }
219 | return LABEL_VALUE_RE.matcher(value).matches();
220 | }
221 | }
222 |
--------------------------------------------------------------------------------
/src/main/java/cloud/dnation/jenkins/plugins/hetzner/launcher/HetznerServerComputerLauncher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 https://dnation.cloud
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package cloud.dnation.jenkins.plugins.hetzner.launcher;
17 |
18 | import cloud.dnation.hetznerclient.ServerDetail;
19 | import cloud.dnation.jenkins.plugins.hetzner.Helper;
20 | import cloud.dnation.jenkins.plugins.hetzner.HetznerConstants;
21 | import cloud.dnation.jenkins.plugins.hetzner.HetznerServerAgent;
22 | import cloud.dnation.jenkins.plugins.hetzner.HetznerServerComputer;
23 | import com.cloudbees.jenkins.plugins.sshcredentials.SSHAuthenticator;
24 | import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey;
25 | import com.google.common.base.Preconditions;
26 | import com.google.common.util.concurrent.Uninterruptibles;
27 | import com.trilead.ssh2.Connection;
28 | import com.trilead.ssh2.SCPClient;
29 | import com.trilead.ssh2.ServerHostKeyVerifier;
30 | import com.trilead.ssh2.Session;
31 | import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
32 | import hudson.AbortException;
33 | import hudson.Util;
34 | import hudson.model.TaskListener;
35 | import hudson.remoting.Channel;
36 | import hudson.slaves.ComputerLauncher;
37 | import hudson.slaves.SlaveComputer;
38 | import jenkins.model.Jenkins;
39 | import lombok.RequiredArgsConstructor;
40 | import lombok.extern.slf4j.Slf4j;
41 |
42 | import java.io.IOException;
43 | import java.nio.charset.StandardCharsets;
44 | import java.util.concurrent.TimeUnit;
45 | import java.util.concurrent.atomic.AtomicBoolean;
46 |
47 | import static cloud.dnation.jenkins.plugins.hetzner.Helper.assertSshKey;
48 | import static cloud.dnation.jenkins.plugins.hetzner.Helper.getStringOrDefault;
49 | import static cloud.dnation.jenkins.plugins.hetzner.HetznerConstants.DEFAULT_REMOTE_FS;
50 | import static hudson.plugins.sshslaves.SSHLauncher.AGENT_JAR;
51 |
52 | @RequiredArgsConstructor
53 | @Slf4j
54 | public class HetznerServerComputerLauncher extends ComputerLauncher {
55 | private static final String AGENT_SCRIPT = ".agent.start.sh";
56 | private final AtomicBoolean terminated = new AtomicBoolean(false);
57 | private final AbstractHetznerSshConnector connector;
58 |
59 | private static String getRemoteFs(HetznerServerAgent agent) {
60 | final String res = getStringOrDefault(agent.getRemoteFS(), DEFAULT_REMOTE_FS);
61 | //trim trailing slash
62 | if (res.endsWith("/")) {
63 | return res.substring(0, res.length() - 1);
64 | }
65 | return res;
66 | }
67 |
68 | private void copyAgent(Connection connection,
69 | HetznerServerComputer computer,
70 | Helper.LogAdapter logger,
71 | String remoteFs) throws IOException {
72 | final byte[] agentBlob = Jenkins.get().getJnlpJars(AGENT_JAR).readFully();
73 | final String remoteAgentPath = remoteFs + "/" + AGENT_JAR;
74 | final byte[] launchScriptContent = ("#!/bin/sh" + '\n' + getAgentCommand(computer, remoteFs) + '\n')
75 | .getBytes(StandardCharsets.UTF_8);
76 | final String launchScriptPath = remoteFs + "/" + AGENT_SCRIPT;
77 | final SCPClient scp = connection.createSCPClient();
78 | logger.info("Copying agent JAR - " + agentBlob.length + " bytes into " + remoteAgentPath);
79 | scp.put(agentBlob, AGENT_JAR, remoteFs, "0644");
80 | logger.info("Copying agent script - " + launchScriptContent.length + " bytes into " + launchScriptPath);
81 | scp.put(launchScriptContent, AGENT_SCRIPT, remoteFs, "0755");
82 | }
83 |
84 | @Override
85 | @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF")
86 | public void launch(final SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException {
87 | if (!(computer instanceof HetznerServerComputer hcomputer)) {
88 | throw new AbortException("Incompatible computer : " + computer);
89 | }
90 | if (connector.getConnectionMethod() == null) {
91 | connector.setConnectionMethod(HetznerConstants.DEFAULT_CONNECTION_METHOD);
92 | }
93 | if (connector.getSshPort() == 0) {
94 | connector.setSshPort(22);
95 | }
96 | final Helper.LogAdapter logger = new Helper.LogAdapter(listener.getLogger(), log);
97 | final HetznerServerAgent node = hcomputer.getNode();
98 | Preconditions.checkState(node != null && node.getServerInstance() != null,
99 | "Missing node or server instance data in computer %s", computer.getName());
100 | final String remoteFs = getRemoteFs(node);
101 | final Connection connection = setupConnection(node, logger, listener);
102 | copyAgent(connection, hcomputer, logger, remoteFs);
103 | launchAgent(connection, hcomputer, logger, listener, remoteFs);
104 | }
105 |
106 | @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE",
107 | justification = "NULLnes of node is checked in launch method")
108 | private String getAgentCommand(HetznerServerComputer computer, String remoteFs) {
109 | final String jvmOpts = Util.fixNull(computer.getNode().getTemplate().getJvmOpts());
110 | return "java " + jvmOpts + " -jar " + remoteFs + "/remoting.jar -workDir " + remoteFs;
111 | }
112 |
113 | private void launchAgent(Connection connection,
114 | HetznerServerComputer computer,
115 | Helper.LogAdapter logger,
116 | TaskListener listener,
117 | String remoteFs
118 | )
119 | throws IOException, InterruptedException {
120 | final HetznerServerAgent node = computer.getNode();
121 | final Session session = connection.openSession();
122 | final String scriptCmd = "/bin/sh " + remoteFs + "/" + AGENT_SCRIPT;
123 | final String launchCmd;
124 | final String username = connector.getUsernameOverride();
125 | if (username != null) {
126 | final String credentialsId = node.getTemplate().getConnector().getSshCredentialsId();
127 | final BasicSSHUserPrivateKey privateKey = assertSshKey(credentialsId);
128 | launchCmd = "sudo -n -u " + privateKey.getUsername() + " " + scriptCmd;
129 | } else {
130 | launchCmd = scriptCmd;
131 | }
132 |
133 | logger.info("Launching agent using '" + launchCmd + "'");
134 | session.execCommand(launchCmd);
135 | computer.setChannel(session.getStdout(), session.getStdin(), listener, new Channel.Listener() {
136 | @Override
137 | public void onClosed(Channel channel, IOException cause) {
138 | session.close();
139 | connection.close();
140 | }
141 | });
142 | }
143 |
144 | private Connection setupConnection(HetznerServerAgent node,
145 | Helper.LogAdapter logger,
146 | TaskListener taskListener) throws InterruptedException, AbortException {
147 | int retries = 10;
148 | while (!terminated.get() && retries-- > 0) {
149 | final ServerDetail serverDetail = node.getServerInstance().getServerDetail();
150 | final String ipv4 = connector.getConnectionMethod().getAddress(serverDetail);
151 | final int port = connector.getSshPort();
152 | final Connection conn = new Connection(ipv4, port);
153 | try {
154 | conn.connect(AllowAnyServerHostKeyVerifier.INSTANCE,
155 | 30_000, 10_000);
156 | logger.info("Connected to " + node.getNodeName() + " via " + ipv4 + ":" + port);
157 | final String credentialsId = node.getTemplate().getConnector().getSshCredentialsId();
158 | final BasicSSHUserPrivateKey privateKey = assertSshKey(credentialsId);
159 | final String username = Util.fixNull(node.getTemplate().getConnector().getUsernameOverride(),
160 | privateKey.getUsername());
161 |
162 | logger.info("Authenticating using username '" + username + "'");
163 |
164 | final SSHAuthenticator authenticator = SSHAuthenticator
165 | .newInstance(conn, privateKey, username);
166 |
167 | if (authenticator.authenticate(taskListener) && conn.isAuthenticationComplete()) {
168 | logger.info("Authentication succeeded");
169 | return conn;
170 | } else {
171 | throw new AbortException("Authentication failed");
172 | }
173 | } catch (IOException e) {
174 | logger.error("Connection to " + ipv4 + " failed. Will wait 10 seconds before retry", e);
175 | Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
176 | }
177 | }
178 | throw new AbortException("Failed to launch agent");
179 | }
180 |
181 | public void signalTermination() {
182 | terminated.set(true);
183 | }
184 |
185 | //TODO: is there a way to verify hostkey of newly created server?
186 | //its is usually generated by cloud-init
187 | private static class AllowAnyServerHostKeyVerifier implements ServerHostKeyVerifier {
188 | static final AllowAnyServerHostKeyVerifier INSTANCE = new AllowAnyServerHostKeyVerifier();
189 |
190 | @Override
191 | public boolean verifyServerHostKey(String hostname, int port,
192 | String serverHostKeyAlgorithm,
193 | byte[] serverHostKey) throws Exception {
194 | return true;
195 | }
196 | }
197 | }
198 |
--------------------------------------------------------------------------------
/src/main/java/cloud/dnation/jenkins/plugins/hetzner/HetznerCloud.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 https://dnation.cloud
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package cloud.dnation.jenkins.plugins.hetzner;
17 |
18 | import com.cloudbees.plugins.credentials.CredentialsMatchers;
19 | import com.cloudbees.plugins.credentials.CredentialsProvider;
20 | import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
21 | import com.google.common.primitives.Ints;
22 | import edu.umd.cs.findbugs.annotations.NonNull;
23 | import hudson.Extension;
24 | import hudson.model.Computer;
25 | import hudson.model.Descriptor;
26 | import hudson.model.Item;
27 | import hudson.model.Label;
28 | import hudson.model.Node;
29 | import hudson.security.ACL;
30 | import hudson.slaves.AbstractCloudImpl;
31 | import hudson.slaves.Cloud;
32 | import hudson.slaves.NodeProvisioner.PlannedNode;
33 | import hudson.util.FormValidation;
34 | import hudson.util.ListBoxModel;
35 | import java.util.Objects;
36 | import jenkins.model.Jenkins;
37 | import lombok.Getter;
38 | import lombok.SneakyThrows;
39 | import lombok.extern.slf4j.Slf4j;
40 | import org.apache.commons.lang.RandomStringUtils;
41 | import org.jenkinsci.plugins.cloudstats.ProvisioningActivity;
42 | import org.jenkinsci.plugins.cloudstats.TrackedPlannedNode;
43 | import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl;
44 | import org.kohsuke.accmod.Restricted;
45 | import org.kohsuke.accmod.restrictions.NoExternalUse;
46 | import org.kohsuke.stapler.AncestorInPath;
47 | import org.kohsuke.stapler.DataBoundConstructor;
48 | import org.kohsuke.stapler.DataBoundSetter;
49 | import org.kohsuke.stapler.QueryParameter;
50 | import org.kohsuke.stapler.interceptor.RequirePOST;
51 |
52 | import java.io.IOException;
53 | import java.util.ArrayList;
54 | import java.util.Collection;
55 | import java.util.Collections;
56 | import java.util.List;
57 | import java.util.Locale;
58 | import java.util.stream.Collectors;
59 |
60 | @Slf4j
61 | public class HetznerCloud extends AbstractCloudImpl {
62 | @Getter
63 | private final String credentialsId;
64 | @Getter
65 | private List serverTemplates;
66 | @Getter
67 | private transient HetznerCloudResourceManager resourceManager;
68 |
69 | @DataBoundConstructor
70 | public HetznerCloud(String name, String credentialsId, String instanceCapStr,
71 | List serverTemplates) {
72 | super(name, instanceCapStr);
73 | this.credentialsId = credentialsId;
74 | this.serverTemplates = serverTemplates;
75 | readResolve();
76 | }
77 |
78 | /**
79 | * Pick random template from provided list.
80 | *
81 | * @param matchingTemplates List of all matching templates.
82 | * @return picked template
83 | */
84 | private static HetznerServerTemplate pickTemplate(List matchingTemplates) {
85 | if (matchingTemplates.size() == 1) {
86 | return matchingTemplates.get(0);
87 | }
88 | final List shuffled = new ArrayList<>(matchingTemplates);
89 | Collections.shuffle(shuffled);
90 | return shuffled.get(0);
91 | }
92 |
93 | @DataBoundSetter
94 | public void setServerTemplates(List serverTemplates) {
95 | this.serverTemplates = Objects.requireNonNullElse(serverTemplates, Collections.emptyList());
96 | readResolve();
97 | }
98 |
99 | protected Object readResolve() {
100 | resourceManager = HetznerCloudResourceManager.create(credentialsId);
101 | if (serverTemplates == null) {
102 | setServerTemplates(Collections.emptyList());
103 | }
104 | for (HetznerServerTemplate template : serverTemplates) {
105 | template.setCloud(this);
106 | template.readResolve();
107 | }
108 | return this;
109 | }
110 |
111 | @SneakyThrows
112 | private int runningNodeCount() {
113 | return Ints.checkedCast(resourceManager.fetchAllServers(name)
114 | .stream()
115 | .filter(sd -> HetznerConstants.RUNNABLE_STATE_SET.contains(sd.getStatus()))
116 | .count());
117 | }
118 |
119 | @Override
120 | public Collection provision(CloudState state, int excessWorkload) {
121 | log.debug("provision(cloud={},label={},excessWorkload={})", name, state.getLabel(), excessWorkload);
122 | final List plannedNodes = new ArrayList<>();
123 | final Label label = state.getLabel();
124 | final List matchingTemplates = getTemplates(label);
125 | final Jenkins jenkinsInstance = Jenkins.get();
126 | try {
127 | while (excessWorkload > 0) {
128 | if (jenkinsInstance.isQuietingDown() || jenkinsInstance.isTerminating()) {
129 | log.warn("Jenkins is going down, no new nodes will be provisioned");
130 | break;
131 | }
132 | int running = runningNodeCount();
133 | int instanceCap = getInstanceCap();
134 | int available = instanceCap - running;
135 | final HetznerServerTemplate template = pickTemplate(matchingTemplates);
136 | log.info("Creating new agent with {} executors, have {} running VMs", template.getNumExecutors(), running);
137 | if (available <= 0) {
138 | log.warn("Cloud capacity reached ({}). Has {} VMs running, but want {} more executors",
139 | instanceCap, running , excessWorkload);
140 | break;
141 | } else {
142 | final String serverName = template.generateNodeName();
143 | final ProvisioningActivity.Id provisioningId = new ProvisioningActivity.Id(name, template.getName(),
144 | serverName);
145 | final HetznerServerAgent agent = template.createAgent(provisioningId, serverName);
146 | agent.setMode(template.getMode());
147 | plannedNodes.add(new TrackedPlannedNode(
148 | provisioningId,
149 | agent.getNumExecutors(),
150 | Computer.threadPoolForRemoting.submit(new NodeCallable(agent, this)
151 | )
152 | )
153 | );
154 | excessWorkload -= agent.getNumExecutors();
155 | }
156 | }
157 |
158 | } catch (IOException | Descriptor.FormException e) {
159 | log.error("Unable to provision node", e);
160 | }
161 | return plannedNodes;
162 | }
163 |
164 | @Override
165 | public boolean canProvision(CloudState state) {
166 | return !getTemplates(state.getLabel()).isEmpty();
167 | }
168 |
169 | private List getTemplates(Label label) {
170 | return serverTemplates.stream().filter(t -> {
171 | //no labels has been provided in template
172 | if (t.getLabels().isEmpty()) {
173 | return Node.Mode.NORMAL.equals(t.getMode());
174 | } else {
175 | if (Node.Mode.NORMAL.equals(t.getMode())) {
176 | return label == null || label.matches(t.getLabels());
177 | } else {
178 | return label != null && label.matches(t.getLabels());
179 | }
180 | }
181 | })
182 | .collect(Collectors.toList());
183 | }
184 |
185 | @SuppressWarnings("unused")
186 | @Extension
187 | public static class DescriptorImpl extends Descriptor {
188 | @Override
189 | @NonNull
190 | public String getDisplayName() {
191 | return Messages.plugin_displayName();
192 | }
193 |
194 | @Restricted(NoExternalUse.class)
195 | @RequirePOST
196 | public FormValidation doVerifyConfiguration(@QueryParameter String credentialsId) {
197 | Jenkins.get().checkPermission(Jenkins.ADMINISTER);
198 | final ConfigurationValidator.ValidationResult result = ConfigurationValidator.validateCloudConfig(credentialsId);
199 | if (result.isSuccess()) {
200 | return FormValidation.ok(Messages.cloudConfigPassed());
201 | } else {
202 | return FormValidation.error(result.getMessage());
203 | }
204 | }
205 |
206 | @Restricted(NoExternalUse.class)
207 | @RequirePOST
208 | public FormValidation doCheckCloudName(@QueryParameter String name) {
209 | if (Helper.isValidLabelValue(name)) {
210 | return FormValidation.ok();
211 | }
212 | return FormValidation.error("Cloud name is not a valid label value: %s", name);
213 | }
214 |
215 | @Restricted(NoExternalUse.class)
216 | @RequirePOST
217 | public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item owner) {
218 | final StandardListBoxModel result = new StandardListBoxModel();
219 | if (owner == null) {
220 | if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
221 | return result;
222 | }
223 | } else {
224 | if (!owner.hasPermission(Item.EXTENDED_READ)
225 | && !owner.hasPermission(CredentialsProvider.USE_ITEM)) {
226 | return result;
227 | }
228 | }
229 | return new StandardListBoxModel()
230 | .includeEmptyValue()
231 | .includeMatchingAs(ACL.SYSTEM2, owner, StringCredentialsImpl.class,
232 | Collections.emptyList(), CredentialsMatchers.always());
233 | }
234 | }
235 | }
236 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/src/main/java/cloud/dnation/jenkins/plugins/hetzner/HetznerServerTemplate.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 https://dnation.cloud
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package cloud.dnation.jenkins.plugins.hetzner;
17 |
18 | import cloud.dnation.jenkins.plugins.hetzner.connect.AbstractConnectivity;
19 | import cloud.dnation.jenkins.plugins.hetzner.launcher.AbstractHetznerSshConnector;
20 | import cloud.dnation.jenkins.plugins.hetzner.primaryip.AbstractPrimaryIpStrategy;
21 | import cloud.dnation.jenkins.plugins.hetzner.shutdown.AbstractShutdownPolicy;
22 | import com.google.common.base.Strings;
23 | import edu.umd.cs.findbugs.annotations.NonNull;
24 | import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
25 | import hudson.Extension;
26 | import hudson.Util;
27 | import hudson.model.AbstractDescribableImpl;
28 | import hudson.model.Descriptor;
29 | import hudson.model.Label;
30 | import hudson.model.Node.Mode;
31 | import hudson.model.labels.LabelAtom;
32 | import hudson.util.FormValidation;
33 | import jenkins.model.Jenkins;
34 | import lombok.AccessLevel;
35 | import lombok.Getter;
36 | import lombok.Setter;
37 | import lombok.ToString;
38 | import lombok.extern.slf4j.Slf4j;
39 | import org.apache.commons.lang.RandomStringUtils;
40 | import org.jenkinsci.plugins.cloudstats.ProvisioningActivity;
41 | import org.kohsuke.accmod.Restricted;
42 | import org.kohsuke.accmod.restrictions.NoExternalUse;
43 | import org.kohsuke.stapler.DataBoundConstructor;
44 | import org.kohsuke.stapler.DataBoundSetter;
45 | import org.kohsuke.stapler.QueryParameter;
46 | import org.kohsuke.stapler.interceptor.RequirePOST;
47 |
48 | import java.io.IOException;
49 | import java.util.Locale;
50 | import java.util.Set;
51 | import java.util.regex.Pattern;
52 |
53 | import static cloud.dnation.jenkins.plugins.hetzner.ConfigurationValidator.doCheckNonEmpty;
54 | import static cloud.dnation.jenkins.plugins.hetzner.ConfigurationValidator.doCheckPositiveInt;
55 | import static cloud.dnation.jenkins.plugins.hetzner.ConfigurationValidator.verifyFirewall;
56 | import static cloud.dnation.jenkins.plugins.hetzner.ConfigurationValidator.verifyImage;
57 | import static cloud.dnation.jenkins.plugins.hetzner.ConfigurationValidator.verifyLocation;
58 | import static cloud.dnation.jenkins.plugins.hetzner.ConfigurationValidator.verifyNetwork;
59 | import static cloud.dnation.jenkins.plugins.hetzner.ConfigurationValidator.verifyPlacementGroup;
60 | import static cloud.dnation.jenkins.plugins.hetzner.ConfigurationValidator.verifyPrefix;
61 | import static cloud.dnation.jenkins.plugins.hetzner.ConfigurationValidator.verifyServerType;
62 | import static cloud.dnation.jenkins.plugins.hetzner.ConfigurationValidator.verifyVolumes;
63 | import static cloud.dnation.jenkins.plugins.hetzner.Helper.getStringOrDefault;
64 | import static cloud.dnation.jenkins.plugins.hetzner.HetznerConstants.DEFAULT_REMOTE_FS;
65 |
66 | @ToString
67 | @Slf4j
68 | public class HetznerServerTemplate extends AbstractDescribableImpl {
69 | private static final Pattern PREFIX_RE = Pattern.compile("^[a-z][\\w_-]+$");
70 | @Getter
71 | private final String name;
72 |
73 | @Getter
74 | private final String labelStr;
75 |
76 | @Getter
77 | private final String image;
78 |
79 | @Getter
80 | private final String location;
81 |
82 | @Getter
83 | private final String serverType;
84 |
85 | @Getter
86 | private transient Set labels;
87 |
88 | @Setter(AccessLevel.PACKAGE)
89 | @Getter(AccessLevel.PACKAGE)
90 | @NonNull
91 | private transient HetznerCloud cloud;
92 |
93 | @Setter(onMethod = @__({@DataBoundSetter}))
94 | @Getter
95 | private AbstractHetznerSshConnector connector;
96 |
97 | @Setter(onMethod = @__({@DataBoundSetter}))
98 | @Getter
99 | private String remoteFs;
100 |
101 | @Setter(onMethod = @__({@DataBoundSetter}))
102 | @Getter
103 | private String placementGroup;
104 |
105 | @Setter(onMethod = @__({@DataBoundSetter}))
106 | @Getter
107 | private String userData;
108 |
109 | @Setter(onMethod = @__({@DataBoundSetter}))
110 | @Getter
111 | private String jvmOpts;
112 |
113 | @Getter
114 | @Setter(onMethod = @__({@DataBoundSetter}))
115 | private int numExecutors;
116 |
117 | @Getter
118 | @Setter(onMethod = @__({@DataBoundSetter}))
119 | private int bootDeadline;
120 |
121 | @Getter
122 | @Setter(onMethod = @__({@DataBoundSetter}))
123 | private String network;
124 |
125 | @Getter
126 | @Setter(onMethod = @__({@DataBoundSetter}))
127 | private String firewall;
128 |
129 | @Getter
130 | @Setter(onMethod = @__({@DataBoundSetter}))
131 | private String prefix;
132 |
133 | @Getter
134 | @Setter(onMethod = @__({@DataBoundSetter}))
135 | private Mode mode = Mode.EXCLUSIVE;
136 |
137 | @Getter
138 | @Setter(onMethod = @__({@DataBoundSetter}))
139 | private AbstractShutdownPolicy shutdownPolicy;
140 |
141 | @Getter
142 | @Setter(onMethod = @__({@DataBoundSetter}))
143 | private AbstractPrimaryIpStrategy primaryIp;
144 |
145 | @Getter
146 | @Setter(onMethod = @__({@DataBoundSetter}))
147 | private AbstractConnectivity connectivity;
148 |
149 | @Getter
150 | @Setter(onMethod = @__({@DataBoundSetter}))
151 | private boolean automountVolumes;
152 |
153 | @Getter
154 | @Setter(onMethod = @__({@DataBoundSetter}))
155 | private String volumeIds;
156 |
157 | @DataBoundConstructor
158 | @SuppressFBWarnings("NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR")
159 | public HetznerServerTemplate(String name, String labelStr, String image,
160 | String location, String serverType) {
161 | this.name = name;
162 | this.labelStr = Util.fixNull(labelStr);
163 | this.image = image;
164 | this.location = location;
165 | this.serverType = serverType;
166 | readResolve();
167 | }
168 |
169 | protected Object readResolve() {
170 | Jenkins.get().checkPermission(Jenkins.ADMINISTER);
171 | labels = Label.parse(labelStr);
172 | if (Strings.isNullOrEmpty(location)) {
173 | throw new IllegalArgumentException("Location must be specified");
174 | }
175 | if (numExecutors == 0) {
176 | setNumExecutors(HetznerConstants.DEFAULT_NUM_EXECUTORS);
177 | }
178 | if (bootDeadline == 0) {
179 | setBootDeadline(HetznerConstants.DEFAULT_BOOT_DEADLINE);
180 | }
181 | if (shutdownPolicy == null) {
182 | shutdownPolicy = HetznerConstants.DEFAULT_SHUTDOWN_POLICY;
183 | }
184 | if (primaryIp == null) {
185 | primaryIp = HetznerConstants.DEFAULT_PRIMARY_IP_STRATEGY;
186 | }
187 | if (connectivity == null ) {
188 | connectivity = HetznerConstants.DEFAULT_CONNECTIVITY;
189 | }
190 | if (placementGroup == null) {
191 | placementGroup = "";
192 | }
193 | if (userData == null) {
194 | userData = "";
195 | }
196 | if (volumeIds == null) {
197 | volumeIds = "";
198 | }
199 | if (prefix == null) {
200 | prefix = "";
201 | }
202 | prefix = prefix.toLowerCase(Locale.ROOT);
203 | return this;
204 | }
205 |
206 | boolean isPrefixValid() {
207 | return checkPrefixValue(prefix);
208 | }
209 |
210 | static boolean checkPrefixValue(String prefixStr) {
211 | return PREFIX_RE.matcher(prefixStr).matches();
212 | }
213 |
214 | String generateNodeName() {
215 | final String prefixStr = isPrefixValid() ? prefix : "hcloud";
216 | return prefixStr + "-" + RandomStringUtils.randomAlphanumeric(16)
217 | .toLowerCase(Locale.ROOT);
218 | }
219 |
220 | /**
221 | * Create new {@link HetznerServerAgent}.
222 | *
223 | * @param provisioningId ID to track activity of provisioning
224 | * @param nodeName name of server
225 | * @return new agent instance
226 | */
227 | HetznerServerAgent createAgent(ProvisioningActivity.Id provisioningId, String nodeName)
228 | throws IOException, Descriptor.FormException {
229 | return new HetznerServerAgent(
230 | provisioningId,
231 | nodeName,
232 | getStringOrDefault(remoteFs, DEFAULT_REMOTE_FS),
233 | connector.createLauncher(),
234 | cloud,
235 | this
236 | );
237 | }
238 |
239 | @SuppressWarnings("unused")
240 | @Extension
241 | public static final class DescriptorImpl extends Descriptor {
242 | @Override
243 | @NonNull
244 | public String getDisplayName() {
245 | return Messages.serverTemplate_displayName();
246 | }
247 |
248 |
249 | @Restricted(NoExternalUse.class)
250 | @RequirePOST
251 | public FormValidation doVerifyPrefix(@QueryParameter String prefix) {
252 | return verifyPrefix(prefix);
253 | }
254 |
255 | @Restricted(NoExternalUse.class)
256 | @RequirePOST
257 | public FormValidation doVerifyLocation(@QueryParameter String location,
258 | @QueryParameter String credentialsId) {
259 | return verifyLocation(location, credentialsId).toFormValidation();
260 | }
261 |
262 | @Restricted(NoExternalUse.class)
263 | @RequirePOST
264 | public FormValidation doVerifyImage(@QueryParameter String image,
265 | @QueryParameter String credentialsId) {
266 | return verifyImage(image, credentialsId).toFormValidation();
267 | }
268 |
269 | @Restricted(NoExternalUse.class)
270 | @RequirePOST
271 | public FormValidation doVerifyNetwork(@QueryParameter String network,
272 | @QueryParameter String credentialsId) {
273 | return verifyNetwork(network, credentialsId).toFormValidation();
274 | }
275 |
276 | @Restricted(NoExternalUse.class)
277 | @RequirePOST
278 | public FormValidation doVerifyFirewall(@QueryParameter String firewall,
279 | @QueryParameter String credentialsId) {
280 | return verifyFirewall(firewall, credentialsId).toFormValidation();
281 | }
282 |
283 | @Restricted(NoExternalUse.class)
284 | @RequirePOST
285 | public FormValidation doVerifyPlacementGroup(@QueryParameter String placementGroup,
286 | @QueryParameter String credentialsId) {
287 | return verifyPlacementGroup(placementGroup, credentialsId).toFormValidation();
288 | }
289 |
290 | @Restricted(NoExternalUse.class)
291 | @RequirePOST
292 | public FormValidation doVerifyServerType(@QueryParameter String serverType,
293 | @QueryParameter String credentialsId) {
294 | return verifyServerType(serverType, credentialsId).toFormValidation();
295 | }
296 |
297 | @Restricted(NoExternalUse.class)
298 | @RequirePOST
299 | public FormValidation doVerifyVolumes(@QueryParameter String volumeIds,
300 | @QueryParameter String credentialsId) {
301 | return verifyVolumes(volumeIds, credentialsId).toFormValidation();
302 | }
303 |
304 | @Restricted(NoExternalUse.class)
305 | @RequirePOST
306 | public FormValidation doCheckImage(@QueryParameter String image) {
307 | return doCheckNonEmpty(image, "Image");
308 | }
309 |
310 | @Restricted(NoExternalUse.class)
311 | @RequirePOST
312 | public FormValidation doCheckLabelStr(@QueryParameter String labelStr, @QueryParameter Mode mode) {
313 | if (Strings.isNullOrEmpty(labelStr) && Mode.EXCLUSIVE == mode) {
314 | return FormValidation.warning("You may want to assign labels to this node;"
315 | + " it's marked to only run jobs that are exclusively tied to itself or a label.");
316 | }
317 | return FormValidation.ok();
318 | }
319 |
320 | @Restricted(NoExternalUse.class)
321 | @RequirePOST
322 | public FormValidation doCheckServerType(@QueryParameter String serverType) {
323 | return doCheckNonEmpty(serverType, "Server type");
324 | }
325 |
326 | @Restricted(NoExternalUse.class)
327 | @RequirePOST
328 | public FormValidation doCheckLocation(@QueryParameter String location) {
329 | return doCheckNonEmpty(location, "Location");
330 | }
331 |
332 | @Restricted(NoExternalUse.class)
333 | @RequirePOST
334 | public FormValidation doCheckName(@QueryParameter String name) {
335 | return doCheckNonEmpty(name, "Name");
336 | }
337 |
338 | @Restricted(NoExternalUse.class)
339 | @RequirePOST
340 | public FormValidation doCheckNumExecutors(@QueryParameter String numExecutors) {
341 | return doCheckPositiveInt(numExecutors, "Number of executors");
342 | }
343 |
344 | @Restricted(NoExternalUse.class)
345 | @RequirePOST
346 | public FormValidation doCheckBootDeadline(@QueryParameter String bootDeadline) {
347 | return doCheckPositiveInt(bootDeadline, "Boot deadline");
348 | }
349 | }
350 | }
351 |
--------------------------------------------------------------------------------