{{ message }}
forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmachine.mjs
More file actions
executable file
·1642 lines (1468 loc) · 50.7 KB
/
Copy pathmachine.mjs
File metadata and controls
executable file
·1642 lines (1468 loc) · 50.7 KB
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { chmodSync, existsSync, mkdtempSync, readdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, extname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { inspect, parseArgs } from "node:util";
import { azure } from "./azure.mjs";
import { docker } from "./docker.mjs";
import { tart } from "./tart.mjs";
import {
$,
copyFile,
curlSafe,
escapePowershell,
getBootstrapVersion,
getBuildNumber,
getGithubApiUrl,
getGithubUrl,
getSecret,
getUsernameForDistro,
homedir,
isCI,
isMacOS,
isWindows,
mkdir,
mkdtemp,
parseArch,
parseOs,
readFile,
rm,
setupUserData,
sha256,
spawn,
spawnSafe,
spawnSsh,
spawnSshSafe,
spawnSyncSafe,
startGroup,
waitForPort,
which,
writeFile,
} from "./utils.mjs";
const aws = {
get name() {
return "aws";
},
/**
* @param {string[]} args
* @param {import("./utils.mjs").SpawnOptions} [options]
* @returns {Promise<unknown>}
*/
async spawn(args, options = {}) {
const aws = which("aws", { required: true });
let env;
if (isCI) {
env = {
AWS_ACCESS_KEY_ID: getSecret("EC2_ACCESS_KEY_ID", { required: true }),
AWS_SECRET_ACCESS_KEY: getSecret("EC2_SECRET_ACCESS_KEY", { required: true }),
AWS_REGION: getSecret("EC2_REGION", { required: false }) || "us-east-1",
};
}
const { stdout } = await spawnSafe($`${aws} ${args} --output json`, { env, ...options });
try {
return JSON.parse(stdout);
} catch {
return;
}
},
/**
* @param {Record<string, string | undefined>} [options]
* @returns {string[]}
*/
getFilters(options = {}) {
return Object.entries(options)
.filter(([_, value]) => typeof value !== "undefined")
.map(([key, value]) => `Name=${key},Values=${value}`);
},
/**
* @param {Record<string, string | undefined>} [options]
* @returns {string[]}
*/
getFlags(options = {}) {
return Object.entries(options)
.filter(([_, value]) => typeof value !== "undefined")
.map(([key, value]) => `--${key}=${value}`);
},
/**
* @typedef AwsInstance
* @property {string} InstanceId
* @property {string} ImageId
* @property {string} InstanceType
* @property {string} [PublicIpAddress]
* @property {string} [PlatformDetails]
* @property {string} [Architecture]
* @property {object} [Placement]
* @property {string} [Placement.AvailabilityZone]
* @property {string} LaunchTime
*/
/**
* @param {Record<string, string | undefined>} [options]
* @returns {Promise<AwsInstance[]>}
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instances.html
*/
async describeInstances(options) {
const filters = aws.getFilters(options);
const { Reservations } = await aws.spawn($`ec2 describe-instances --filters ${filters}`);
return Reservations.flatMap(({ Instances }) => Instances).sort((a, b) => (a.LaunchTime < b.LaunchTime ? 1 : -1));
},
/**
* @param {Record<string, string | undefined>} [options]
* @returns {Promise<AwsInstance[]>}
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/run-instances.html
*/
async runInstances(options) {
for (let i = 0; i < 3; i++) {
const flags = aws.getFlags(options);
const result = await aws.spawn($`ec2 run-instances ${flags}`, {
throwOnError: error => {
if (options["instance-market-options"] && /InsufficientInstanceCapacity/i.test(inspect(error))) {
delete options["instance-market-options"];
const instanceType = options["instance-type"] || "default";
console.warn(`There is not enough capacity for ${instanceType} spot instances, retrying with on-demand...`);
return false;
}
return true;
},
});
if (result) {
const { Instances } = result;
if (Instances.length) {
return Instances.sort((a, b) => (a.LaunchTime < b.LaunchTime ? 1 : -1));
}
}
await new Promise(resolve => setTimeout(resolve, i * Math.random() * 15_000));
}
throw new Error(`Failed to run instances: ${inspect(instanceOptions)}`);
},
/**
* @param {...string} instanceIds
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/stop-instances.html
*/
async stopInstances(...instanceIds) {
await aws.spawn($`ec2 stop-instances --no-hibernate --force --instance-ids ${instanceIds}`);
},
/**
* @param {...string} instanceIds
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/terminate-instances.html
*/
async terminateInstances(...instanceIds) {
await aws.spawn($`ec2 terminate-instances --instance-ids ${instanceIds}`, {
throwOnError: error => !/InvalidInstanceID\.NotFound/i.test(inspect(error)),
});
},
/**
* @param {"instance-running" | "instance-stopped" | "instance-terminated"} action
* @param {...string} instanceIds
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/wait.html
*/
async waitInstances(action, ...instanceIds) {
await aws.spawn($`ec2 wait ${action} --instance-ids ${instanceIds}`, {
retryOnError: error => /max attempts exceeded/i.test(inspect(error)),
});
},
/**
* @param {string} instanceId
* @param {string} privateKeyPath
* @param {object} [passwordOptions]
* @param {boolean} [passwordOptions.wait]
* @returns {Promise<string | undefined>}
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-password-data.html
*/
async getPasswordData(instanceId, privateKeyPath, passwordOptions = {}) {
const attempts = passwordOptions.wait ? 15 : 1;
for (let i = 0; i < attempts; i++) {
const { PasswordData } = await aws.spawn($`ec2 get-password-data --instance-id ${instanceId}`);
if (PasswordData) {
return decryptPassword(PasswordData, privateKeyPath);
}
await new Promise(resolve => setTimeout(resolve, 60000 * i));
}
throw new Error(`Failed to get password data for instance: ${instanceId}`);
},
/**
* @typedef AwsImage
* @property {string} ImageId
* @property {string} Name
* @property {string} State
* @property {string} CreationDate
*/
/**
* @param {Record<string, string | undefined>} [options]
* @returns {Promise<AwsImage[]>}
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-images.html
*/
async describeImages(options = {}) {
const { ["owner-alias"]: owners, ...filterOptions } = options;
const filters = aws.getFilters(filterOptions);
if (owners) {
filters.push(`--owners=${owners}`);
}
const { Images } = await aws.spawn($`ec2 describe-images --filters ${filters}`);
return Images.sort((a, b) => (a.CreationDate < b.CreationDate ? 1 : -1));
},
/**
* @param {Record<string, string | undefined>} [options]
* @returns {Promise<string>}
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-image.html
*/
async createImage(options) {
const flags = aws.getFlags(options);
/** @type {string | undefined} */
let existingImageId;
/** @type {AwsImage | undefined} */
const image = await aws.spawn($`ec2 create-image ${flags}`, {
throwOnError: error => {
const match = /already in use by AMI (ami-[a-z0-9]+)/i.exec(inspect(error));
if (!match) {
return true;
}
const [, imageId] = match;
existingImageId = imageId;
return false;
},
});
if (!existingImageId) {
const { ImageId } = image;
return ImageId;
}
await aws.spawn($`ec2 deregister-image --image-id ${existingImageId}`);
const { ImageId } = await aws.spawn($`ec2 create-image ${flags}`);
return ImageId;
},
/**
* @param {Record<string, string | undefined>} options
* @returns {Promise<string>}
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/copy-image.html
*/
async copyImage(options) {
const flags = aws.getFlags(options);
const { ImageId } = await aws.spawn($`ec2 copy-image ${flags}`);
return ImageId;
},
/**
* @param {"image-available"} action
* @param {...string} imageIds
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/wait/image-available.html
*/
async waitImage(action, ...imageIds) {
await aws.spawn($`ec2 wait ${action} --image-ids ${imageIds}`, {
retryOnError: error => /max attempts exceeded/i.test(inspect(error)),
});
},
/**
* @typedef {Object} AwsKeyPair
* @property {string} KeyPairId
* @property {string} KeyName
* @property {string} KeyFingerprint
* @property {string} [PublicKeyMaterial]
*/
/**
* @param {string[]} [names]
* @returns {Promise<AwsKeyPair[]>}
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-key-pairs.html
*/
async describeKeyPairs(names) {
const command = names
? $`ec2 describe-key-pairs --include-public-key --key-names ${names}`
: $`ec2 describe-key-pairs --include-public-key`;
const { KeyPairs } = await aws.spawn(command);
return KeyPairs;
},
/**
* @param {string | Buffer} publicKey
* @param {string} [name]
* @returns {Promise<AwsKeyPair>}
* @link https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/import-key-pair.html
*/
async importKeyPair(publicKey, name) {
const keyName = name || `key-pair-${sha256(publicKey)}`;
const publicKeyBase64 = Buffer.from(publicKey).toString("base64");
/** @type {AwsKeyPair | undefined} */
const keyPair = await aws.spawn(
$`ec2 import-key-pair --key-name ${keyName} --public-key-material ${publicKeyBase64}`,
{
throwOnError: error => !/InvalidKeyPair\.Duplicate/i.test(inspect(error)),
},
);
if (keyPair) {
return keyPair;
}
const keyPairs = await aws.describeKeyPairs(keyName);
if (keyPairs.length) {
return keyPairs[0];
}
throw new Error(`Failed to import key pair: ${keyName}`);
},
/**
* @param {AwsImage | string} imageOrImageId
* @returns {Promise<AwsImage>}
*/
async getAvailableImage(imageOrImageId) {
let imageId = imageOrImageId;
if (typeof imageOrImageId === "object") {
const { ImageId, State } = imageOrImageId;
if (State === "available") {
return imageOrImageId;
}
imageId = ImageId;
}
await aws.waitImage("image-available", imageId);
const [availableImage] = await aws.describeImages({
"state": "available",
"image-id": imageId,
});
if (!availableImage) {
throw new Error(`Failed to find available image: ${imageId}`);
}
return availableImage;
},
/**
* @param {MachineOptions} options
* @returns {Promise<AwsImage>}
*/
async getBaseImage(options) {
const { os, arch, distro, release } = options;
let name, owner;
if (os === "linux") {
if (!distro || distro === "debian") {
owner = "amazon";
name = `debian-${release || "*"}-${arch === "aarch64" ? "arm64" : "amd64"}-*`;
} else if (distro === "ubuntu") {
owner = "099720109477";
name = `ubuntu/images/hvm-ssd*/ubuntu-*-${release || "*"}-${arch === "aarch64" ? "arm64" : "amd64"}-server-*`;
} else if (distro === "amazonlinux") {
owner = "amazon";
if (release === "1" && arch === "x64") {
name = `amzn-ami-2018.03.*`;
} else if (release === "2") {
name = `amzn2-ami-hvm-*-${arch === "aarch64" ? "arm64" : "x86_64"}-gp2`;
} else {
name = `al${release || "*"}-ami-*-${arch === "aarch64" ? "arm64" : "x86_64"}`;
}
} else if (distro === "alpine") {
owner = "538276064493";
name = `alpine-${release || "*"}.*-${arch === "aarch64" ? "aarch64" : "x86_64"}-uefi-cloudinit-*`;
} else if (distro === "centos") {
owner = "aws-marketplace";
name = `CentOS-Stream-ec2-${release || "*"}-*.${arch === "aarch64" ? "aarch64" : "x86_64"}-*`;
}
} else if (os === "windows") {
if (!distro || distro === "server") {
owner = "amazon";
name = `Windows_Server-${release || "*"}-English-Full-Base-*`;
}
}
if (!name) {
throw new Error(`Unsupported platform: ${inspect(options)}`);
}
const baseImages = await aws.describeImages({
"state": "available",
"owner-alias": owner,
"name": name,
});
// console.table(baseImages.map(v => v.Name));
if (!baseImages.length) {
throw new Error(`No base image found: ${inspect(options)}`);
}
const [baseImage] = baseImages;
return aws.getAvailableImage(baseImage);
},
/**
* @param {MachineOptions} options
* @returns {Promise<Machine>}
*/
async createMachine(options) {
const { os, arch, imageId, instanceType, tags, sshKeys, preemptible } = options;
/** @type {AwsImage} */
let image;
if (imageId) {
image = await aws.getAvailableImage(imageId);
} else {
image = await aws.getBaseImage(options);
}
const { ImageId, Name, RootDeviceName, BlockDeviceMappings } = image;
// console.table({ os, arch, instanceType, Name, ImageId });
const blockDeviceMappings = BlockDeviceMappings.map(device => {
const { DeviceName } = device;
if (DeviceName === RootDeviceName) {
return {
...device,
Ebs: {
VolumeSize: getDiskSize(options),
},
};
}
return device;
});
const username = getUsernameForDistro(Name);
// Only include minimal cloud-init for SSH access
let userData = getUserData({ ...options, username });
if (os === "windows") {
userData = `<powershell>${userData}</powershell><powershellArguments>-ExecutionPolicy Unrestricted -NoProfile -NonInteractive</powershellArguments><persist>true</persist>`;
}
let tagSpecification = [];
if (tags) {
tagSpecification = ["instance", "volume"].map(resourceType => {
return {
ResourceType: resourceType,
Tags: Object.entries(tags).map(([Key, Value]) => ({ Key, Value: String(Value) })),
};
});
}
/** @type {string | undefined} */
let keyName, keyPath;
if (os === "windows") {
const sshKey = sshKeys.find(({ privatePath }) => existsSync(privatePath));
if (sshKey) {
const { publicKey, privatePath } = sshKey;
const { KeyName } = await aws.importKeyPair(publicKey);
keyName = KeyName;
keyPath = privatePath;
}
}
let marketOptions;
if (preemptible) {
marketOptions = JSON.stringify({
MarketType: "spot",
SpotOptions: {
InstanceInterruptionBehavior: "terminate",
SpotInstanceType: "one-time",
},
});
}
// Attach IAM instance profile for CI builds to enable S3 build cache access
let iamInstanceProfile;
if (options.ci) {
iamInstanceProfile = JSON.stringify({ Name: "buildkite-build-agent" });
}
const [instance] = await aws.runInstances({
["image-id"]: ImageId,
["instance-type"]: instanceType || (arch === "aarch64" ? "t4g.large" : "t3.large"),
["user-data"]: userData,
["block-device-mappings"]: JSON.stringify(blockDeviceMappings),
["metadata-options"]: JSON.stringify({
"HttpTokens": "optional",
"HttpEndpoint": "enabled",
"HttpProtocolIpv6": "enabled",
"InstanceMetadataTags": "enabled",
}),
["tag-specifications"]: JSON.stringify(tagSpecification),
["key-name"]: keyName,
["instance-market-options"]: marketOptions,
["iam-instance-profile"]: iamInstanceProfile,
});
const machine = aws.toMachine(instance, { ...options, username, keyPath });
await setupUserData(machine, options);
return machine;
},
/**
* @param {AwsInstance} instance
* @param {MachineOptions} [options]
* @returns {Machine}
*/
toMachine(instance, options = {}) {
let { InstanceId, ImageId, InstanceType, Placement, PublicIpAddress } = instance;
const connect = async () => {
if (!PublicIpAddress) {
await aws.waitInstances("instance-running", InstanceId);
const [{ PublicIpAddress: IpAddress }] = await aws.describeInstances({
["instance-id"]: InstanceId,
});
PublicIpAddress = IpAddress;
}
const { username, sshKeys } = options;
const identityPaths = sshKeys
?.filter(({ privatePath }) => existsSync(privatePath))
?.map(({ privatePath }) => privatePath);
return { hostname: PublicIpAddress, username, identityPaths };
};
const waitForSsh = async () => {
const connectOptions = await connect();
const { hostname, username, identityPaths } = connectOptions;
// Try to connect until it succeeds
for (let i = 0; i < 30; i++) {
try {
await spawnSshSafe({
hostname,
username,
identityPaths,
command: ["true"],
});
return;
} catch (error) {
if (i === 29) {
throw error;
}
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
};
const spawn = async (command, options) => {
const connectOptions = await connect();
return spawnSsh({ ...connectOptions, command }, options);
};
const spawnSafe = async (command, options) => {
const connectOptions = await connect();
return spawnSshSafe({ ...connectOptions, command }, options);
};
const rdp = async () => {
const { keyPath } = options;
const { hostname, username } = await connect();
const password = await aws.getPasswordData(InstanceId, keyPath, { wait: true });
return { hostname, username, password };
};
const attach = async () => {
const connectOptions = await connect();
await spawnSshSafe({ ...connectOptions });
};
const upload = async (source, destination) => {
const connectOptions = await connect();
await spawnScp({ ...connectOptions, source, destination });
};
const snapshot = async name => {
await aws.stopInstances(InstanceId);
await aws.waitInstances("instance-stopped", InstanceId);
const imageId = await aws.createImage({
["instance-id"]: InstanceId,
["name"]: name || `${InstanceId}-snapshot-${Date.now()}`,
});
await aws.waitImage("image-available", imageId);
return imageId;
};
const terminate = async () => {
await aws.terminateInstances(InstanceId);
};
return {
cloud: "aws",
id: InstanceId,
imageId: ImageId,
instanceType: InstanceType,
region: Placement?.AvailabilityZone,
get publicIp() {
return PublicIpAddress;
},
spawn,
spawnSafe,
upload,
attach,
rdp,
snapshot,
waitForSsh,
close: terminate,
[Symbol.asyncDispose]: terminate,
};
},
};
/**
* @typedef CloudInit
* @property {string} [distro]
* @property {SshKey[]} [sshKeys]
* @property {string} [username]
* @property {string} [password]
* @property {Os} [os]
*/
/**
* @param {CloudInit} cloudInit
* @returns {string}
*/
export function getUserData(cloudInit) {
const { os, userData } = cloudInit;
// For Windows, use PowerShell script
if (os === "windows") {
return getWindowsStartupScript(cloudInit);
}
// For Linux, just set up SSH access
return getCloudInit(cloudInit);
}
/**
* @param {CloudInit} cloudInit
* @returns {string}
*/
function getCloudInit(cloudInit) {
const username = cloudInit["username"] || "root";
const password = cloudInit["password"] || crypto.randomUUID();
const authorizedKeys = cloudInit["sshKeys"]?.map(({ publicKey }) => publicKey) || [];
let sftpPath = "/usr/lib/openssh/sftp-server";
let shell = "/bin/bash";
switch (cloudInit["distro"]) {
case "alpine":
sftpPath = "/usr/lib/ssh/sftp-server";
break;
case "amazonlinux":
case "rhel":
case "centos":
sftpPath = "/usr/libexec/openssh/sftp-server";
break;
}
switch (cloudInit["os"]) {
case "linux":
case "windows":
// handled above
break;
default:
throw new Error(`Unsupported os: ${cloudInit["os"]}`);
}
let users;
if (username === "root") {
users = [`root:${password}`];
} else {
users = [`root:${password}`, `${username}:${password}`];
}
// https://cloudinit.readthedocs.io/en/stable/
return `#cloud-config
users:
- name: ${username}
sudo: ALL=(ALL) NOPASSWD:ALL
shell: ${shell}
ssh_authorized_keys:
${authorizedKeys.map(key => ` - ${key}`).join("\n")}
write_files:
- path: /etc/ssh/sshd_config
permissions: '0644'
owner: root:root
content: |
Port 22
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
SyslogFacility AUTHPRIV
PermitRootLogin yes
AuthorizedKeysFile %h/.ssh/authorized_keys
PasswordAuthentication no
ChallengeResponseAuthentication no
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
UsePAM yes
X11Forwarding yes
PrintMotd no
AcceptEnv LANG LC_*
Subsystem sftp ${sftpPath}
`;
}
/**
* @param {CloudInit} cloudInit
* @returns {string}
*/
function getWindowsStartupScript(cloudInit) {
const { sshKeys } = cloudInit;
const authorizedKeys = sshKeys.map(({ publicKey }) => publicKey);
return `
$ErrorActionPreference = "Stop"
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force
function Install-Ssh {
$sshdService = Get-Service -Name sshd -ErrorAction SilentlyContinue
if (-not $sshdService) {
$buildNumber = Get-WmiObject Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber
if ($buildNumber -lt 17763) {
Write-Output "Installing OpenSSH server through Github..."
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri "https://github.com/PowerShell/Win32-OpenSSH/releases/download/v9.8.0.0p1-Preview/OpenSSH-Win64.zip" -OutFile "$env:TEMP\\OpenSSH.zip"
Expand-Archive -Path "$env:TEMP\\OpenSSH.zip" -DestinationPath "$env:TEMP\\OpenSSH" -Force
Get-ChildItem -Path "$env:TEMP\\OpenSSH\\OpenSSH-Win64" -Recurse | Move-Item -Destination "$env:ProgramFiles\\OpenSSH" -Force
& "$env:ProgramFiles\\OpenSSH\\install-sshd.ps1"
} else {
Write-Output "Installing OpenSSH server through Windows Update..."
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
}
}
Write-Output "Enabling OpenSSH server..."
Set-Service -Name sshd -StartupType Automatic
Start-Service sshd
$pwshPath = Get-Command pwsh -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Path
if (-not $pwshPath) {
$pwshPath = Get-Command powershell -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Path
}
if ($pwshPath) {
Write-Output "Setting default shell to $pwshPath..."
New-ItemProperty -Path "HKLM:\\SOFTWARE\\OpenSSH" -Name DefaultShell -Value $pwshPath -PropertyType String -Force
}
$firewallRule = Get-NetFirewallRule -Name "OpenSSH-Server" -ErrorAction SilentlyContinue
if (-not $firewallRule) {
Write-Output "Configuring firewall..."
New-NetFirewallRule -Profile Any -Name 'OpenSSH-Server' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
}
$sshPath = "C:\\ProgramData\\ssh"
if (-not (Test-Path $sshPath)) {
Write-Output "Creating SSH directory..."
New-Item -Path $sshPath -ItemType Directory
}
$authorizedKeysPath = Join-Path $sshPath "administrators_authorized_keys"
$authorizedKeys = @(${authorizedKeys.map(key => `"${escapePowershell(key)}"`).join("\n")})
if (-not (Test-Path $authorizedKeysPath) -or (Get-Content $authorizedKeysPath) -ne $authorizedKeys) {
Write-Output "Adding SSH keys..."
Set-Content -Path $authorizedKeysPath -Value $authorizedKeys
}
$sshdConfigPath = Join-Path $sshPath "sshd_config"
$sshdConfig = @"
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile $authorizedKeysPath
Subsystem sftp sftp-server.exe
"@
if (-not (Test-Path $sshdConfigPath) -or (Get-Content $sshdConfigPath) -ne $sshdConfig) {
Write-Output "Writing SSH configuration..."
Set-Content -Path $sshdConfigPath -Value $sshdConfig
}
Write-Output "Restarting SSH server..."
Restart-Service sshd
}
Install-Ssh
`;
}
/**
* @param {MachineOptions} options
* @returns {number}
*/
export function getDiskSize(options) {
const { os, diskSizeGb } = options;
if (diskSizeGb) {
return diskSizeGb;
}
// After Visual Studio and dependencies are installed,
// there is ~50GB of used disk space.
if (os === "windows") {
return 60;
}
return 40;
}
/**
* @typedef SshKey
* @property {string} [privatePath]
* @property {string} [publicPath]
* @property {string} publicKey
*/
/**
* @returns {SshKey}
*/
function createSshKey() {
const sshKeyGen = which("ssh-keygen", { required: true });
const sshAdd = which("ssh-add", { required: true });
const sshPath = join(homedir(), ".ssh");
mkdir(sshPath);
const filename = `id_rsa_${crypto.randomUUID()}`;
const privatePath = join(sshPath, filename);
const publicPath = join(sshPath, `${filename}.pub`);
spawnSyncSafe([sshKeyGen, "-t", "rsa", "-b", "4096", "-f", privatePath, "-N", ""], { stdio: "inherit" });
if (!existsSync(privatePath) || !existsSync(publicPath)) {
throw new Error(`Failed to generate SSH key: ${privatePath} / ${publicPath}`);
}
if (isWindows) {
spawnSyncSafe([sshAdd, privatePath], { stdio: "inherit" });
} else {
const sshAgent = which("ssh-agent");
if (sshAgent) {
spawnSyncSafe(["sh", "-c", `eval $(${sshAgent} -s) && ${sshAdd} ${privatePath}`], { stdio: "inherit" });
}
}
return {
privatePath,
publicPath,
get publicKey() {
return readFile(publicPath, { cache: true });
},
};
}
/**
* @returns {SshKey[]}
*/
function getSshKeys() {
const homePath = homedir();
const sshPath = join(homePath, ".ssh");
/** @type {SshKey[]} */
const sshKeys = [];
if (existsSync(sshPath)) {
const sshFiles = readdirSync(sshPath, { withFileTypes: true, encoding: "utf-8" });
const publicPaths = sshFiles
.filter(entry => entry.isFile() && entry.name.endsWith(".pub"))
.map(({ name }) => join(sshPath, name));
sshKeys.push(
...publicPaths.map(publicPath => ({
publicPath,
privatePath: publicPath.replace(/\.pub$/, ""),
get publicKey() {
return readFile(publicPath, { cache: true }).trim();
},
})),
);
}
if (!sshKeys.length) {
sshKeys.push(createSshKey());
}
return sshKeys;
}
/**
* @param {string} username
* @returns {Promise<SshKey[]>}
*/
async function getGithubUserSshKeys(username) {
const url = new URL(`${username}.keys`, getGithubUrl());
const publicKeys = await curlSafe(url);
return publicKeys
.split("\n")
.filter(key => key.length)
.map(key => ({ publicKey: `${key} github@${username}` }));
}
/**
* @param {string} organization
* @returns {Promise<SshKey[]>}
*/
async function getGithubOrgSshKeys(organization) {
const url = new URL(`orgs/${encodeURIComponent(organization)}/members`, getGithubApiUrl());
const members = await curlSafe(url, { json: true });
/** @type {SshKey[][]} */
const sshKeys = await Promise.all(
members.filter(({ type, login }) => type === "User" && login).map(({ login }) => getGithubUserSshKeys(login)),
);
return sshKeys.flat();
}
/**
* @typedef SshOptions
* @property {string} hostname
* @property {number} [port]
* @property {string} [username]
* @property {string} [password]
* @property {string[]} [command]
* @property {string[]} [identityPaths]
* @property {number} [retries]
*/
/**
* @typedef ScpOptions
* @property {string} hostname
* @property {string} source
* @property {string} destination
* @property {string[]} [identityPaths]
* @property {string} [port]
* @property {string} [username]
* @property {number} [retries]
*/
/**
* @param {ScpOptions} options
* @returns {Promise<void>}
*/
async function spawnScp(options) {
const { hostname, port, username, identityPaths, password, source, destination, retries = 3 } = options;
await waitForPort({ hostname, port: port || 22 });
const command = ["scp", "-o", "StrictHostKeyChecking=no"];
command.push("-O"); // use SCP instead of SFTP
if (!password) {
command.push("-o", "BatchMode=yes");
}
if (port) {
command.push("-P", port);
}
if (password) {
const sshPass = which("sshpass", { required: true });
command.unshift(sshPass, "-p", password);
} else if (identityPaths) {
command.push(...identityPaths.flatMap(path => ["-i", path]));
}
command.push(resolve(source));
if (username) {
command.push(`${username}@${hostname}:${destination}`);
} else {
command.push(`${hostname}:${destination}`);
}
let cause;
for (let i = 0; i < retries; i++) {
const result = await spawn(command, { stdio: "inherit" });
const { exitCode, stderr } = result;
if (exitCode === 0) {
return;
}
cause = stderr.trim() || undefined;
if (/(bad configuration option)|(no such file or directory)/i.test(stderr)) {
break;
}
await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
}
throw new Error(`SCP failed: ${source} -> ${username}@${hostname}:${destination}`, { cause });
}
/**
* @param {string} passwordData
* @param {string} privateKeyPath
You can’t perform that action at this time.
