forked from Farbfox/hetzner-cloud-deploy-server-action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.js
336 lines (302 loc) · 8.6 KB
/
lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// @format
const core = require("@actions/core");
const fetch = require("cross-fetch");
const isPortReachable = require("is-port-reachable");
const { periodicExecution, TimeoutError } = require("periodic-execution");
const process = require("process");
const config = require("./config.js");
// TODO: Move within each function
const options = {
server: {
name: core.getInput("server-name"),
location: core.getInput("server-location"),
type: core.getInput("server-type"),
},
image: {
name: core.getInput("image-identifier"),
label: core.getInput("image-label"),
type: core.getInput("image-type"),
},
sshKeyName: core.getInput("ssh-key-name"),
hcloudToken: core.getInput("hcloud-token"),
timeout: core.getInput("startup-timeout"),
};
async function deploy() {
let imageId;
let res;
try {
if (options.image.type === "snapshot") {
imageId = await getImageId(options.image.name);
}
imageIdentifier = imageId || options.image.name;
core.info(`debug imageIdentifier: "${imageIdentifier}"`);
res = await fetch(`${config.API}/servers`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${options.hcloudToken}`,
"User-Agent": config.USER_AGENT,
},
body: JSON.stringify({
name: options.server.name,
image: imageIdentifier,
location: options.server.location,
server_type: options.server.type,
ssh_keys: [options.sshKeyName],
}),
});
} catch (err) {
core.setFailed(err.message);
}
if (res.status === 201) {
core.info("Hetzner Cloud Server deployment successful");
const body = await res.json();
// NOTE: We set the SERVER_ID optimistically as we definitely want to still
// delete the server if our periodic request fails.
const ipv4 = body.server.public_net.ipv4.ip;
core.exportVariable("SERVER_ID", body.server.id);
core.exportVariable("SERVER_IPV4", ipv4);
const fn = () => {
core.debug(
`Trying to connect to server on default port "${config.DEFAULT_PORT}"`
);
return isPortReachable(config.DEFAULT_PORT, {
host: ipv4,
});
};
let online;
try {
online = await periodicExecution(fn, true, options.timeout);
} catch (err) {
core.error(err.toString());
if (err instanceof TimeoutError) {
online = false;
} else {
throw err;
}
}
if (online) {
return res;
} else {
core.setFailed(
`Waited ${options.timeout}ms for server to come online, but it never came online. Value: "${online}"`
);
}
} else {
core.setFailed(
`When sending the request to Hetzner's API, an error occurred "${res.statusText}"`
);
}
}
async function clean() {
const deleteServer = core.getInput("delete-server") === "true";
if (!deleteServer) {
core.warning("Aborted post cleaning procedure with delete-server: false");
return;
}
let res;
const URI = `${config.API}/servers/${process.env.SERVER_ID}`;
try {
res = await fetch(URI, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${options.hcloudToken}`,
"User-Agent": config.USER_AGENT,
},
});
} catch (err) {
core.setFailed(err.message);
}
if (res.status === 200) {
core.info("Hetzner Cloud Server deleted in clean up routine");
return res;
} else {
core.setFailed(
`When sending the request to Hetzner's API, an error occurred "${res.statusText}"`
);
return;
}
}
function getAssignmentProgress(floatingIPId, actionId) {
return async () => {
const URI = `${config.API}/floating_ips/${floatingIPId}/actions/${actionId}`;
let res;
try {
res = await fetch(URI, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${options.hcloudToken}`,
"User-Agent": config.USER_AGENT,
},
});
} catch (err) {
core.setFailed(err.message);
}
if (res.status === 200) {
const body = await res.json();
return body.action.status;
} else {
core.setFailed(
`When trying to check on the ip's assignment progress, an error occurred: ${res.status}`
);
return;
}
};
}
async function getImageId(name) {
let imageId = null;
let res;
let URI;
if (!options.image.label || options.image.label.length === 0) {
URI = `${config.API}/images?type=${options.image.type}&sort=created:desc`;
} else {
URI = `${config.API}/images?type=${options.image.type}&label_selector=${options.image.label}&sort=created:desc`;
}
try {
res = await fetch(URI, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${options.hcloudToken}`,
"User-Agent": config.USER_AGENT,
},
});
} catch (err) {
core.setFailed(err.message);
}
if (res.status === 200) {
const body = await res.json();
core.info(`getImageId image count: "${body.images.length}"`);
core.info(`getImageId image name: "${name}"`);
core.info(`getImageId image type: "${options.image.type}"`);
body.images.every((element) => {
if (
element &&
element.description === name &&
element.type === options.image.type
) {
imageId = element.id;
core.info(`getImageId imageId: "${imageId}"`);
return false;
}
return true;
});
core.exportVariable("IMAGE_ID", imageId);
return imageId;
}
return;
}
async function getFloatingIP(id) {
const URI = `${config.API}/floating_ips/${id}`;
try {
res = await fetch(URI, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${options.hcloudToken}`,
"User-Agent": config.USER_AGENT,
},
});
} catch (err) {
core.setFailed(err.message);
}
if (res.status === 200) {
const body = await res.json();
return body.floating_ip.ip;
} else {
core.setFailed(
`When trying to get a floating ip, an error occurred ${res.status}`
);
return;
}
}
async function assignIP() {
const floatingIPId = core.getInput("floating-ip-id");
if (!floatingIPId) {
core.warning(
"No value for floating-ip-id input was found. Hence skipping this step."
);
return;
}
const parsedIPId = parseInt(floatingIPId, 10);
if (isNaN(parsedIPId)) {
core.setFailed(
`Not assigning server a floating-ip-id as it asn't parseable as an integer. Unparsed value: ${floatingIPId}`
);
return;
}
let res;
const URI = `${config.API}/floating_ips/${parsedIPId}/actions/assign`;
let { SERVER_ID } = process.env;
SERVER_ID = parseInt(SERVER_ID, 10);
try {
res = await fetch(URI, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${options.hcloudToken}`,
"User-Agent": config.USER_AGENT,
},
body: JSON.stringify({ server: SERVER_ID }),
});
} catch (err) {
core.setFailed(err.message);
}
if (res.status === 201) {
const body = await res.json();
core.info(
`Successfully created assignment action for IP "${parsedIPId}" and SERVER_ID "${SERVER_ID}"`
);
const expectedStatus = "success";
const assignmentTimeout = parseInt(
core.getInput("floating-ip-assignment-timeout"),
10
);
core.info(
`Attempting to get the status of the assignment process with expected status: "${expectedStatus}" and timeout: "${assignmentTimeout}"`
);
let _status;
try {
_status = await periodicExecution(
getAssignmentProgress(parsedIPId, body.action.id),
expectedStatus,
assignmentTimeout
);
} catch (err) {
core.error(err.toString());
if (err instanceof TimeoutError) {
_status = "timeout";
} else {
throw err;
}
}
if (_status === "success") {
const floatingIP = await getFloatingIP(parsedIPId);
core.exportVariable("SERVER_FLOATING_IPV4", floatingIP);
core.info(
`Floating IP with ID "${parsedIPId}" was assigned to server with id: "${SERVER_ID}"`
);
return;
} else {
core.setFailed(
`An error happened while trying to get the IP's assignment progress. Status: "${_status}"`
);
return;
}
} else {
core.setFailed(
`When assigning a floating ip to the server an error occurred "${res.statusText}"`
);
return;
}
}
module.exports = {
deploy,
clean,
assignIP,
getAssignmentProgress,
getImageId,
getFloatingIP
};