-
Notifications
You must be signed in to change notification settings - Fork 206
/
containerFeaturesConfiguration.ts
1040 lines (877 loc) · 36.3 KB
/
containerFeaturesConfiguration.ts
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as jsonc from 'jsonc-parser';
import * as path from 'path';
import * as URL from 'url';
import * as tar from 'tar';
import { DevContainerConfig, DevContainerFeature, VSCodeCustomizations } from './configuration';
import { mkdirpLocal, readLocalFile, rmLocal, writeLocalFile, cpDirectoryLocal, isLocalFile } from '../spec-utils/pfs';
import { Log, LogLevel } from '../spec-utils/log';
import { request } from '../spec-utils/httpRequest';
import { computeFeatureInstallationOrder } from './containerFeaturesOrder';
import { fetchOCIFeature, getOCIFeatureSet, OCIFeatureRef, fetchOCIFeatureManifestIfExistsFromUserIdentifier, OCIManifest } from './containerFeaturesOCI';
// v1
const V1_ASSET_NAME = 'devcontainer-features.tgz';
export const V1_DEVCONTAINER_FEATURES_FILE_NAME = 'devcontainer-features.json';
// v2
export const DEVCONTAINER_FEATURE_FILE_NAME = 'devcontainer-feature.json';
export interface Feature {
id: string;
version?: string;
name: string;
description?: string;
cachePath?: string;
internalVersion?: string; // set programmatically
consecutiveId?: string;
documentationURL?: string;
licenseURL?: string;
options?: Record<string, FeatureOption>;
buildArg?: string; // old properties for temporary compatibility
containerEnv?: Record<string, string>;
mounts?: Mount[];
init?: boolean;
privileged?: boolean;
capAdd?: string[];
securityOpt?: string[];
entrypoint?: string;
installAfter?: string[];
include?: string[];
exclude?: string[];
value: boolean | string | Record<string, boolean | string | undefined>; // set programmatically
included: boolean; // set programmatically
customizations?: VSCodeCustomizations;
installsAfter?: string[];
}
export type FeatureOption = {
type: 'boolean';
default?: boolean;
description?: string;
} | {
type: 'string';
enum?: string[];
default?: string;
description?: string;
} | {
type: 'string';
proposals?: string[];
default?: string;
description?: string;
};
export interface Mount {
type: 'bind' | 'volume';
source: string;
target: string;
external?: boolean;
}
export type SourceInformation = LocalCacheSourceInformation | GithubSourceInformation | DirectTarballSourceInformation | FilePathSourceInformation | OCISourceInformation;
interface BaseSourceInformation {
type: string;
userFeatureId: string; // Dictates how a supporting tool will locate and download a given feature. See https://github.com/devcontainers/spec/blob/main/proposals/devcontainer-features.md#referencing-a-feature
userFeatureIdWithoutVersion?: string;
}
export interface LocalCacheSourceInformation extends BaseSourceInformation {
type: 'local-cache';
}
export interface OCISourceInformation extends BaseSourceInformation {
type: 'oci';
featureRef: OCIFeatureRef;
manifest: OCIManifest;
userFeatureIdWithoutVersion: string;
}
export interface DirectTarballSourceInformation extends BaseSourceInformation {
type: 'direct-tarball';
tarballUri: string;
}
export interface FilePathSourceInformation extends BaseSourceInformation {
type: 'file-path';
resolvedFilePath: string; // Resolved, absolute file path
}
// deprecated
export interface GithubSourceInformation extends BaseSourceInformation {
type: 'github-repo';
apiUri: string;
unauthenticatedUri: string;
owner: string;
repo: string;
isLatest: boolean; // 'true' indicates user didn't supply a version tag, thus we implicitly pull latest.
tag?: string;
ref?: string;
sha?: string;
userFeatureIdWithoutVersion: string;
}
export interface GithubSourceInformationInput {
owner: string;
repo: string;
ref?: string;
sha?: string;
tag?: string;
}
export interface FeatureSet {
features: Feature[];
internalVersion?: string;
sourceInformation: SourceInformation;
}
export interface FeaturesConfig {
featureSets: FeatureSet[];
dstFolder?: string; // set programatically
}
export interface GitHubApiReleaseInfo {
assets: GithubApiReleaseAsset[];
name: string;
tag_name: string;
}
export interface GithubApiReleaseAsset {
url: string;
name: string;
content_type: string;
size: number;
download_count: number;
updated_at: string;
}
// Supports the `node` layer by collapsing all the individual features into a single `features` array.
// Regardless of their origin.
// Information is lost, but for the node layer we need not care about which set a given feature came from.
export interface CollapsedFeaturesConfig {
allFeatures: Feature[];
}
export function collapseFeaturesConfig(original: FeaturesConfig): CollapsedFeaturesConfig {
const collapsed = {
allFeatures: original.featureSets
.map(fSet => fSet.features)
.flat()
};
return collapsed;
}
export const multiStageBuildExploration = false;
// Counter to ensure that no two folders are the same even if we are executing the same feature multiple times.
let counter = 1;
function getCounter() {
return counter++;
}
const isTsnode = path.basename(process.argv[0]) === 'ts-node' || process.argv.indexOf('ts-node/register') !== -1;
export function getContainerFeaturesFolder(_extensionPath: string | { distFolder: string }) {
if (isTsnode) {
return path.join(require.resolve('vscode-dev-containers/package.json'), '..', 'container-features');
}
const distFolder = typeof _extensionPath === 'string' ? path.join(_extensionPath, 'dist') : _extensionPath.distFolder;
return path.join(distFolder, 'node_modules', 'vscode-dev-containers', 'container-features');
}
// Take a SourceInformation and condense it down into a single string
// Useful for calculating a unique build folder name for a given featureSet.
export function getSourceInfoString(srcInfo: SourceInformation): string {
const { type } = srcInfo;
switch (type) {
case 'local-cache':
return 'local-cache-' + getCounter();
case 'direct-tarball':
return srcInfo.tarballUri + getCounter();
case 'github-repo':
return `github-${srcInfo.owner}-${srcInfo.repo}-${srcInfo.isLatest ? 'latest' : srcInfo.tag}-${getCounter()}`;
case 'file-path':
return srcInfo.resolvedFilePath + '-' + getCounter();
case 'oci':
return `oci-${srcInfo.featureRef.resource}-${getCounter()}`;
}
}
// TODO: Move to node layer.
export function getContainerFeaturesBaseDockerFile() {
return `
#{featureBuildStages}
#{nonBuildKitFeatureContentFallback}
FROM $_DEV_CONTAINERS_BASE_IMAGE AS dev_containers_target_stage
USER root
COPY --from=dev_containers_feature_content_source {contentSourceRootPath} /tmp/build-features/
#{featureLayer}
#{copyFeatureBuildStages}
#{containerEnv}
ARG _DEV_CONTAINERS_IMAGE_USER=root
USER $_DEV_CONTAINERS_IMAGE_USER
`;
}
export function getFeatureLayers(featuresConfig: FeaturesConfig) {
let result = '';
// Features version 1
const folders = (featuresConfig.featureSets || []).filter(y => y.internalVersion !== '2').map(x => x.features[0].consecutiveId);
folders.forEach(folder => {
result += `RUN cd /tmp/build-features/${folder} \\
&& chmod +x ./install.sh \\
&& ./install.sh
`;
});
// Features version 2
featuresConfig.featureSets.filter(y => y.internalVersion === '2').forEach(featureSet => {
featureSet.features.forEach(feature => {
result += generateContainerEnvs(feature);
result += `
RUN cd /tmp/build-features/${feature.consecutiveId} \\
&& set -a \\
&& . ./devcontainer-features.env \\
&& set +a \\
&& chmod +x ./install.sh \\
&& ./install.sh
`;
});
});
return result;
}
// Features version two export their environment variables as part of the Dockerfile to make them available to subsequent features.
export function generateContainerEnvs(feature: Feature) {
let result = '';
if (!feature.containerEnv) {
return result;
}
let keys = Object.keys(feature.containerEnv);
result = keys.map(k => `ENV ${k}=${feature.containerEnv![k]}`).join('\n');
return result;
}
const allowedFeatureIdRegex = new RegExp('^[a-zA-Z0-9_-]*$');
// Parses a declared feature in user's devcontainer file into
// a usable URI to download remote features.
// RETURNS
// {
// "id", <----- The ID of the feature in the feature set.
// sourceInformation <----- Source information (is this locally cached, a GitHub remote feature, etc..), including tarballUri if applicable.
// }
//
const cleanupIterationFetchAndMerge = async (tempTarballPath: string, output: Log) => {
// Non-fatal, will just get overwritten if we don't do the cleaned up.
try {
await rmLocal(tempTarballPath, { force: true });
} catch (e) {
output.write(`Didn't remove temporary tarball from disk with caught exception: ${e?.Message} `, LogLevel.Trace);
}
};
function getRequestHeaders(sourceInformation: SourceInformation, env: NodeJS.ProcessEnv, output: Log) {
let headers: { 'user-agent': string; 'Authorization'?: string; 'Accept'?: string } = {
'user-agent': 'devcontainer'
};
const isGitHubUri = (srcInfo: DirectTarballSourceInformation) => {
const uri = srcInfo.tarballUri;
return uri.startsWith('https://github.com') || uri.startsWith('https://api.github.com');
};
if (sourceInformation.type === 'github-repo' || (sourceInformation.type === 'direct-tarball' && isGitHubUri(sourceInformation))) {
const githubToken = env['GITHUB_TOKEN'];
if (githubToken) {
output.write('Using environment GITHUB_TOKEN.');
headers.Authorization = `Bearer ${githubToken}`;
} else {
output.write('No environment GITHUB_TOKEN available.');
}
}
return headers;
}
async function askGitHubApiForTarballUri(sourceInformation: GithubSourceInformation, feature: Feature, headers: { 'user-agent': string; 'Authorization'?: string; 'Accept'?: string }, output: Log) {
const options = {
type: 'GET',
url: sourceInformation.apiUri,
headers
};
const apiInfo: GitHubApiReleaseInfo = JSON.parse(((await request(options, output)).toString()));
if (apiInfo) {
const asset =
apiInfo.assets.find(a => a.name === `${feature.id}.tgz`) // v2
|| apiInfo.assets.find(a => a.name === V1_ASSET_NAME) // v1
|| undefined;
if (asset && asset.url) {
output.write(`Found url to fetch release artifact '${asset.name}'. Asset of size ${asset.size} has been downloaded ${asset.download_count} times and was last updated at ${asset.updated_at}`);
return asset.url;
} else {
output.write('Unable to fetch release artifact URI from GitHub API', LogLevel.Error);
return undefined;
}
}
return undefined;
}
export async function loadFeaturesJson(jsonBuffer: Buffer, filePath: string, output: Log): Promise<FeatureSet | undefined> {
if (jsonBuffer.length === 0) {
output.write('Parsed featureSet is empty.', LogLevel.Error);
return undefined;
}
const featureSet: FeatureSet = jsonc.parse(jsonBuffer.toString());
if (!featureSet?.features || featureSet.features.length === 0) {
output.write('Parsed featureSet contains no features.', LogLevel.Error);
return undefined;
}
output.write(`Loaded ${filePath}, which declares ${featureSet.features.length} features and ${(!!featureSet.sourceInformation) ? 'contains' : 'does not contain'} explicit source info.`,
LogLevel.Trace);
return updateFromOldProperties(featureSet);
}
export async function loadV1FeaturesJsonFromDisk(pathToDirectory: string, output: Log): Promise<FeatureSet | undefined> {
const filePath = path.join(pathToDirectory, V1_DEVCONTAINER_FEATURES_FILE_NAME);
const jsonBuffer: Buffer = await readLocalFile(filePath);
return loadFeaturesJson(jsonBuffer, filePath, output);
}
function updateFromOldProperties<T extends { features: (Feature & { extensions?: string[]; settings?: object; customizations?: VSCodeCustomizations })[] }>(original: T): T {
// https://github.com/microsoft/dev-container-spec/issues/1
if (!original.features.find(f => f.extensions || f.settings)) {
return original;
}
return {
...original,
features: original.features.map(f => {
if (!(f.extensions || f.settings)) {
return f;
}
const copy = { ...f };
const customizations = copy.customizations || (copy.customizations = {});
const vscode = customizations.vscode || (customizations.vscode = {});
if (copy.extensions) {
vscode.extensions = (vscode.extensions || []).concat(copy.extensions);
delete copy.extensions;
}
if (copy.settings) {
vscode.settings = {
...copy.settings,
...(vscode.settings || {}),
};
delete copy.settings;
}
return copy;
}),
};
}
// Generate a base featuresConfig object with the set of locally-cached features,
// as well as downloading and merging in remote feature definitions.
export async function generateFeaturesConfig(params: { extensionPath: string; cwd: string; output: Log; env: NodeJS.ProcessEnv; skipFeatureAutoMapping: boolean }, dstFolder: string, config: DevContainerConfig, getLocalFeaturesFolder: (d: string) => string) {
const { output } = params;
const workspaceRoot = params.cwd;
output.write(`workspace root: ${workspaceRoot}`, LogLevel.Trace);
const userFeatures = featuresToArray(config);
if (!userFeatures) {
return undefined;
}
// Create the featuresConfig object.
// Initialize the featureSets object, and stash the dstFolder on the object for use later.
let featuresConfig: FeaturesConfig = {
featureSets: [],
dstFolder
};
// load local cache of features;
// TODO: Update so that cached features are always version 2
const localFeaturesFolder = getLocalFeaturesFolder(params.extensionPath);
const locallyCachedFeatureSet = await loadV1FeaturesJsonFromDisk(localFeaturesFolder, output); // TODO: Pass dist folder instead to also work with the devcontainer.json support package.
if (!locallyCachedFeatureSet) {
output.write('Failed to load locally cached features', LogLevel.Error);
return undefined;
}
// Read features and get the type.
output.write('--- Processing User Features ----', LogLevel.Trace);
featuresConfig = await processUserFeatures(params.output, config, workspaceRoot, params.env, userFeatures, featuresConfig, params.skipFeatureAutoMapping);
output.write(JSON.stringify(featuresConfig, null, 4), LogLevel.Trace);
const ociCacheDir = await prepareOCICache(dstFolder);
// Fetch features, stage into the appropriate build folder, and read the feature's devcontainer-feature.json
output.write('--- Fetching User Features ----', LogLevel.Trace);
await fetchFeatures(params, featuresConfig, locallyCachedFeatureSet, dstFolder, localFeaturesFolder, ociCacheDir);
const orderedFeatures = computeFeatureInstallationOrder(config, featuresConfig.featureSets);
output.write('--- Computed order ----', LogLevel.Trace);
for (const feature of orderedFeatures) {
output.write(`${feature.sourceInformation.userFeatureId}`, LogLevel.Trace);
}
featuresConfig.featureSets = orderedFeatures;
return featuresConfig;
}
async function prepareOCICache(dstFolder: string) {
const ociCacheDir = path.join(dstFolder, 'ociCache');
await mkdirpLocal(ociCacheDir);
return ociCacheDir;
}
function featuresToArray(config: DevContainerConfig): DevContainerFeature[] | undefined {
if (!config.features) {
return undefined;
}
const userFeatures: DevContainerFeature[] = [];
for (const userFeatureKey of Object.keys(config.features)) {
const userFeatureValue = config.features[userFeatureKey];
const feature: DevContainerFeature = {
id: userFeatureKey,
options: userFeatureValue
};
userFeatures.push(feature);
}
return userFeatures;
}
// Process features contained in devcontainer.json
// Creates one feature set per feature to aid in support of the previous structure.
async function processUserFeatures(output: Log, config: DevContainerConfig, workspaceRoot: string, env: NodeJS.ProcessEnv, userFeatures: DevContainerFeature[], featuresConfig: FeaturesConfig, skipFeatureAutoMapping: boolean): Promise<FeaturesConfig> {
for (const userFeature of userFeatures) {
const newFeatureSet = await processFeatureIdentifier(output, config.configFilePath.path, workspaceRoot, env, userFeature, skipFeatureAutoMapping);
if (!newFeatureSet) {
throw new Error(`Failed to process feature ${userFeature.id}`);
}
featuresConfig.featureSets.push(newFeatureSet);
}
return featuresConfig;
}
export async function getFeatureIdType(output: Log, env: NodeJS.ProcessEnv, userFeatureId: string) {
// See the specification for valid feature identifiers:
// > https://github.com/devcontainers/spec/blob/main/proposals/devcontainer-features.md#referencing-a-feature
//
// Additionally, we support the following deprecated syntaxes for backwards compatibility:
// (0) A 'local feature' packaged with the CLI.
// Syntax: <feature>
//
// (1) A feature backed by a GitHub Release
// Syntax: <repoOwner>/<repoName>/<featureId>[@version]
// DEPRECATED: This is a legacy feature-set ID
if (!userFeatureId.includes('/') && !userFeatureId.includes('\\')) {
return { type: 'local-cache', manifest: undefined };
}
// Direct tarball reference
if (userFeatureId.startsWith('https://')) {
return { type: 'direct-tarball', manifest: undefined };
}
// Local feature on disk
// !! NOTE: The ability for paths outside the project file tree will soon be removed.
if (userFeatureId.startsWith('./') || userFeatureId.startsWith('../') || userFeatureId.startsWith('/')) {
return { type: 'file-path', manifest: undefined };
}
// version identifier for a github release feature.
// DEPRECATED: This is a legacy feature-set ID
if (userFeatureId.includes('@')) {
return { type: 'github-repo', manifest: undefined };
}
const manifest = await fetchOCIFeatureManifestIfExistsFromUserIdentifier(output, env, userFeatureId);
if (manifest) {
return { type: 'oci', manifest: manifest };
} else {
// DEPRECATED: This is a legacy feature-set ID
output.write('(!) WARNING: Falling back to deprecated GitHub Release syntax. See https://github.com/devcontainers/spec/blob/main/proposals/devcontainer-features.md#referencing-a-feature for updated specification.', LogLevel.Warning);
return { type: 'github-repo', manifest: undefined };
}
}
export function getBackwardCompatibleFeatureId(id: string) {
const migratedfeatures = ['aws-cli', 'azure-cli', 'desktop-lite', 'docker-in-docker', 'docker-from-docker', 'dotnet', 'git', 'git-lfs', 'github-cli', 'java', 'kubectl-helm-minikube', 'node', 'powershell', 'python', 'ruby', 'rust', 'sshd', 'terraform'];
const renamedFeatures = new Map();
renamedFeatures.set('golang', 'go');
renamedFeatures.set('common', 'common-utils');
// TODO: Add warning log messages only when auto-mapping is ready to be put in Remote-Containers STABLE version.
// const deprecatedFeatures = ['fish', 'gradle', 'homebrew', 'jupyterlab', 'maven'];
const newFeaturePath = 'ghcr.io/devcontainers/features';
// Note: Pin the versionBackwardComp to '1' to avoid breaking changes.
const versionBackwardComp = '1';
// Mapping feature references (old shorthand syntax) from "microsoft/vscode-dev-containers" to "ghcr.io/devcontainers/features"
if (migratedfeatures.includes(id)) {
return `${newFeaturePath}/${id}:${versionBackwardComp}`;
}
// Mapping feature references (renamed old shorthand syntax) from "microsoft/vscode-dev-containers" to "ghcr.io/devcontainers/features"
if (renamedFeatures.get(id) !== undefined) {
return `${newFeaturePath}/${renamedFeatures.get(id)}:${versionBackwardComp}`;
}
// if (deprecatedFeatures.includes(id)) {
// output.write(`(!) WARNING: Falling back to deprecated '${id}' feature.`, LogLevel.Warning);
// }
// Deprecated and all other features references (eg. fish, ghcr.io/devcontainers/features/go, ghcr.io/owner/repo/id etc)
return id;
}
// Strictly processes the user provided feature identifier to determine sourceInformation type.
// Returns a featureSet per feature.
export async function processFeatureIdentifier(output: Log, configPath: string, _workspaceRoot: string, env: NodeJS.ProcessEnv, userFeature: DevContainerFeature, skipFeatureAutoMapping?: boolean): Promise<FeatureSet | undefined> {
output.write(`* Processing feature: ${userFeature.id}`);
// id referenced by the user before the automapping from old shorthand syntax to "ghcr.io/devcontainers/features"
const originalUserFeatureId = userFeature.id;
// Adding backward compatibility
if (!skipFeatureAutoMapping) {
userFeature.id = getBackwardCompatibleFeatureId(userFeature.id);
}
const { type, manifest } = await getFeatureIdType(output, env, userFeature.id);
// cached feature
// Resolves deprecated features (fish, maven, gradle, homebrew, jupyterlab)
if (type === 'local-cache') {
output.write(`Cached feature found.`);
let feat: Feature = {
id: userFeature.id,
name: userFeature.id,
value: userFeature.options,
included: true,
};
let newFeaturesSet: FeatureSet = {
sourceInformation: {
type: 'local-cache',
userFeatureId: originalUserFeatureId
},
features: [feat],
};
return newFeaturesSet;
}
// remote tar file
if (type === 'direct-tarball') {
output.write(`Remote tar file found.`);
const tarballUri = new URL.URL(userFeature.id);
const fullPath = tarballUri.pathname;
const tarballName = fullPath.substring(fullPath.lastIndexOf('/') + 1);
output.write(`tarballName = ${tarballName}`, LogLevel.Trace);
const regex = new RegExp('devcontainer-feature-(.*).tgz');
const matches = regex.exec(tarballName);
if (!matches || matches.length !== 2) {
output.write(`Expected tarball name to follow 'devcontainer-feature-<feature-id>.tgz' format. Received '${tarballName}'`, LogLevel.Error);
return undefined;
}
const id = matches[1];
if (id === '' || !allowedFeatureIdRegex.test(id)) {
output.write(`Parse error. Specify a feature id with alphanumeric, dash, or underscore characters. Received ${id}.`, LogLevel.Error);
return undefined;
}
let feat: Feature = {
id: id,
name: userFeature.id,
value: userFeature.options,
included: true,
};
let newFeaturesSet: FeatureSet = {
sourceInformation: {
type: 'direct-tarball',
tarballUri: tarballUri.toString(),
userFeatureId: originalUserFeatureId
},
features: [feat],
};
return newFeaturesSet;
}
// Spec: https://containers.dev/implementors/features-distribution/#addendum-locally-referenced
if (type === 'file-path') {
output.write(`Local disk feature.`);
const id = path.basename(userFeature.id);
// Fail on Absolute paths.
if (path.isAbsolute(userFeature.id)) {
output.write('An Absolute path to a local feature is not allowed.', LogLevel.Error);
return undefined;
}
// Local-path features are expected to be a sub-folder of the '$WORKSPACE_ROOT/.devcontainer' folder.
const featureFolderPath = path.join(path.dirname(configPath), userFeature.id);
// Ensure we aren't escaping .devcontainer folder
const parent = path.join(_workspaceRoot, '.devcontainer');
const child = featureFolderPath;
const relative = path.relative(parent, child);
output.write(`${parent} -> ${child}: Relative Distance = '${relative}'`, LogLevel.Trace);
if (relative.indexOf('..') !== -1) {
output.write(`Local file path parse error. Resolved path must be a child of the .devcontainer/ folder. Parsed: ${featureFolderPath}`, LogLevel.Error);
return undefined;
}
output.write(`Resolved: ${userFeature.id} -> ${featureFolderPath}`, LogLevel.Trace);
// -- All parsing and validation steps complete at this point.
output.write(`Parsed feature id: ${id}`, LogLevel.Trace);
let feat: Feature = {
id,
name: userFeature.id,
value: userFeature.options,
included: true,
};
let newFeaturesSet: FeatureSet = {
sourceInformation: {
type: 'file-path',
resolvedFilePath: featureFolderPath,
userFeatureId: originalUserFeatureId
},
features: [feat],
};
return newFeaturesSet;
}
// (6) Oci Identifier
if (type === 'oci' && manifest) {
let newFeaturesSet: FeatureSet = getOCIFeatureSet(output, userFeature.id, userFeature.options, manifest, originalUserFeatureId);
return newFeaturesSet;
}
output.write(`Github feature.`);
// Github repository source.
let version = 'latest';
let splitOnAt = userFeature.id.split('@');
if (splitOnAt.length > 2) {
output.write(`Parse error. Use the '@' symbol only to designate a version tag.`, LogLevel.Error);
return undefined;
}
if (splitOnAt.length === 2) {
output.write(`[${userFeature.id}] has version ${splitOnAt[1]}`, LogLevel.Trace);
version = splitOnAt[1];
}
// Remaining info must be in the first part of the split.
const featureBlob = splitOnAt[0];
const splitOnSlash = featureBlob.split('/');
// We expect all GitHub/registry features to follow the triple slash pattern at this point
// eg: <publisher>/<feature-set>/<feature>
if (splitOnSlash.length !== 3 || splitOnSlash.some(x => x === '') || !allowedFeatureIdRegex.test(splitOnSlash[2])) {
output.write(`Invalid parse for GitHub Release feature: Follow format '<publisher>/<feature-set>/<feature>, or republish feature to OCI registry.'`, LogLevel.Error);
return undefined;
}
const owner = splitOnSlash[0];
const repo = splitOnSlash[1];
const id = splitOnSlash[2];
let feat: Feature = {
id: id,
name: userFeature.id,
value: userFeature.options,
included: true,
};
const userFeatureIdWithoutVersion = originalUserFeatureId.split('@')[0];
if (version === 'latest') {
let newFeaturesSet: FeatureSet = {
sourceInformation: {
type: 'github-repo',
apiUri: `https://api.github.com/repos/${owner}/${repo}/releases/latest`,
unauthenticatedUri: `https://github.com/${owner}/${repo}/releases/latest/download`, // v1/v2 implementations append name of relevant asset
owner,
repo,
isLatest: true,
userFeatureId: originalUserFeatureId,
userFeatureIdWithoutVersion
},
features: [feat],
};
return newFeaturesSet;
} else {
// We must have a tag, return a tarball URI for the tagged version.
let newFeaturesSet: FeatureSet = {
sourceInformation: {
type: 'github-repo',
apiUri: `https://api.github.com/repos/${owner}/${repo}/releases/tags/${version}`,
unauthenticatedUri: `https://github.com/${owner}/${repo}/releases/download/${version}`, // v1/v2 implementations append name of relevant asset
owner,
repo,
tag: version,
isLatest: false,
userFeatureId: originalUserFeatureId,
userFeatureIdWithoutVersion
},
features: [feat],
};
return newFeaturesSet;
}
// TODO: Handle invalid source types better by refactoring this function.
// throw new Error(`Unsupported feature source type: ${type}`);
}
async function fetchFeatures(params: { extensionPath: string; cwd: string; output: Log; env: NodeJS.ProcessEnv }, featuresConfig: FeaturesConfig, localFeatures: FeatureSet, dstFolder: string, localFeaturesFolder: string, ociCacheDir: string) {
for (const featureSet of featuresConfig.featureSets) {
try {
if (!featureSet || !featureSet.features || !featureSet.sourceInformation) {
continue;
}
if (!localFeatures) {
continue;
}
const { output } = params;
const feature = featureSet.features[0];
const consecutiveId = feature.id + '_' + getCounter();
// Calculate some predictable caching paths.
const featCachePath = path.join(dstFolder, consecutiveId);
const sourceInfoType = featureSet.sourceInformation?.type;
feature.cachePath = featCachePath;
feature.consecutiveId = consecutiveId;
const featureDebugId = `${feature.consecutiveId}_${sourceInfoType}`;
output.write(`* Fetching feature: ${featureDebugId}`);
if (sourceInfoType === 'oci') {
output.write(`Fetching from OCI`, LogLevel.Trace);
await mkdirpLocal(featCachePath);
const success = await fetchOCIFeature(output, params.env, featureSet, ociCacheDir, featCachePath);
if (!success) {
const err = `Could not download OCI feature: ${featureSet.sourceInformation.featureRef.id}`;
throw new Error(err);
}
if (!(await applyFeatureConfigToFeature(output, featureSet, feature, featCachePath))) {
const err = `Failed to parse feature '${featureDebugId}'. Please check your devcontainer.json 'features' attribute.`;
throw new Error(err);
}
continue;
}
if (sourceInfoType === 'local-cache') {
// create copy of the local features to set the environment variables for them.
await mkdirpLocal(featCachePath);
await cpDirectoryLocal(localFeaturesFolder, featCachePath);
if (!(await applyFeatureConfigToFeature(output, featureSet, feature, featCachePath))) {
const err = `Failed to parse feature '${featureDebugId}'. Please check your devcontainer.json 'features' attribute.`;
throw new Error(err);
}
continue;
}
if (sourceInfoType === 'file-path') {
output.write(`Detected local file path`, LogLevel.Trace);
await mkdirpLocal(featCachePath);
const executionPath = featureSet.sourceInformation.resolvedFilePath;
await cpDirectoryLocal(executionPath, featCachePath);
if (!(await applyFeatureConfigToFeature(output, featureSet, feature, featCachePath))) {
const err = `Failed to parse feature '${featureDebugId}'. Please check your devcontainer.json 'features' attribute.`;
throw new Error(err);
}
continue;
}
output.write(`Detected tarball`, LogLevel.Trace);
const headers = getRequestHeaders(featureSet.sourceInformation, params.env, output);
// Ordered list of tarballUris to attempt to fetch from.
let tarballUris: string[] = [];
if (sourceInfoType === 'github-repo') {
output.write('Determining tarball URI for provided github repo.', LogLevel.Trace);
if (headers.Authorization && headers.Authorization !== '') {
output.write('GITHUB_TOKEN available. Attempting to fetch via GH API.', LogLevel.Info);
const authenticatedGithubTarballUri = await askGitHubApiForTarballUri(featureSet.sourceInformation, feature, headers, output);
if (authenticatedGithubTarballUri) {
tarballUris.push(authenticatedGithubTarballUri);
} else {
output.write('Failed to generate autenticated tarball URI for provided feature, despite a GitHub token present', LogLevel.Warning);
}
headers.Accept = 'Accept: application/octet-stream';
}
// Always add the unauthenticated URIs as fallback options.
output.write('Appending unauthenticated URIs for v2 and then v1', LogLevel.Trace);
tarballUris.push(`${featureSet.sourceInformation.unauthenticatedUri}/${feature.id}.tgz`);
tarballUris.push(`${featureSet.sourceInformation.unauthenticatedUri}/${V1_ASSET_NAME}`);
} else {
// We have a plain ol' tarball URI, since we aren't in the github-repo case.
tarballUris.push(featureSet.sourceInformation.tarballUri);
}
// Attempt to fetch from 'tarballUris' in order, until one succeeds.
let didSucceed: boolean = false;
for (const tarballUri of tarballUris) {
didSucceed = await fetchContentsAtTarballUri(tarballUri, featCachePath, headers, dstFolder, output);
if (didSucceed) {
output.write(`Succeeded fetching ${tarballUri}`, LogLevel.Trace);
if (!(await applyFeatureConfigToFeature(output, featureSet, feature, featCachePath))) {
const err = `Failed to parse feature '${featureDebugId}'. Please check your devcontainer.json 'features' attribute.`;
throw new Error(err);
}
break;
}
}
if (!didSucceed) {
const msg = `(!) Failed to fetch tarball for ${featureDebugId} after attempting ${tarballUris.length} possibilities.`;
throw new Error(msg);
}
}
catch (e) {
params.output.write(`(!) ERR: Failed to fetch feature: ${e?.message ?? ''} `, LogLevel.Error);
throw e;
}
}
}
async function fetchContentsAtTarballUri(tarballUri: string, featCachePath: string, headers: { 'user-agent': string; 'Authorization'?: string; 'Accept'?: string }, dstFolder: string, output: Log): Promise<boolean> {
const tempTarballPath = path.join(dstFolder, 'temp.tgz');
try {
const options = {
type: 'GET',
url: tarballUri,
headers
};
output.write(`Fetching tarball at ${options.url}`);
output.write(`Headers: ${JSON.stringify(options)}`, LogLevel.Trace);
const tarball = await request(options, output);
if (!tarball || tarball.length === 0) {
output.write(`Did not receive a response from tarball download URI: ${tarballUri}`, LogLevel.Trace);
return false;
}
// Filter what gets emitted from the tar.extract().
const filter = (file: string, _: tar.FileStat) => {
// Don't include .dotfiles or the archive itself.
if (file.startsWith('./.') || file === `./${V1_ASSET_NAME}` || file === './.') {
return false;
}
return true;
};
output.write(`Preparing to unarchive received tgz from ${tempTarballPath} -> ${featCachePath}.`, LogLevel.Trace);
// Create the directory to cache this feature-set in.
await mkdirpLocal(featCachePath);
await writeLocalFile(tempTarballPath, tarball);
await tar.x(
{
file: tempTarballPath,
cwd: featCachePath,
filter
}
);
await cleanupIterationFetchAndMerge(tempTarballPath, output);
return true;
} catch (e) {
output.write(`Caught failure when fetching from URI '${tarballUri}': ${e}`, LogLevel.Trace);
await cleanupIterationFetchAndMerge(tempTarballPath, output);
return false;
}
}
// Reads the feature's 'devcontainer-feature.json` and applies any attributes to the in-memory Feature object.
// NOTE:
// Implements the latest ('internalVersion' = '2') parsing logic,
// Falls back to earlier implementation(s) if requirements not present.
// Returns a boolean indicating whether the feature was successfully parsed.
async function applyFeatureConfigToFeature(output: Log, featureSet: FeatureSet, feature: Feature, featCachePath: string): Promise<boolean> {
const innerJsonPath = path.join(featCachePath, DEVCONTAINER_FEATURE_FILE_NAME);
if (!(await isLocalFile(innerJsonPath))) {
output.write(`Feature ${feature.id} is not a 'v2' feature. Attempting fallback to 'v1' implementation.`, LogLevel.Trace);
output.write(`For v2, expected devcontainer-feature.json at ${innerJsonPath}`, LogLevel.Trace);
return await parseDevContainerFeature_v1Impl(output, featureSet, feature, featCachePath);
}
featureSet.internalVersion = '2';
feature.cachePath = featCachePath;
const jsonString: Buffer = await readLocalFile(innerJsonPath);
const featureJson = jsonc.parse(jsonString.toString());
feature = {
...featureJson,
...feature
};
featureSet.features[0] = updateFromOldProperties({ features: [feature] }).features[0];
return true;
}
async function parseDevContainerFeature_v1Impl(output: Log, featureSet: FeatureSet, feature: Feature, featCachePath: string): Promise<boolean> {
const pathToV1DevContainerFeatureJson = path.join(featCachePath, V1_DEVCONTAINER_FEATURES_FILE_NAME);
if (!(await isLocalFile(pathToV1DevContainerFeatureJson))) {
output.write(`Failed to find ${V1_DEVCONTAINER_FEATURES_FILE_NAME} metadata file (v1)`, LogLevel.Error);
return false;
}
featureSet.internalVersion = '1';
feature.cachePath = featCachePath;
const jsonString: Buffer = await readLocalFile(pathToV1DevContainerFeatureJson);
const featureJson: FeatureSet = jsonc.parse(jsonString.toString());
const seekedFeature = featureJson?.features.find(f => f.id === feature.id);
if (!seekedFeature) {
output.write(`Failed to find feature '${feature.id}' in provided v1 metadata file`, LogLevel.Error);
return false;
}
feature = {
...seekedFeature,
...feature
};
featureSet.features[0] = updateFromOldProperties({ features: [feature] }).features[0];
return true;
}
export function getFeatureMainProperty(feature: Feature) {
return feature.options?.version ? 'version' : undefined;
}
export function getFeatureMainValue(feature: Feature) {
const defaultProperty = getFeatureMainProperty(feature);
if (!defaultProperty) {
return !!feature.value;
}