-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathworkspace-starter.ts
1522 lines (1390 loc) · 64.5 KB
/
workspace-starter.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) 2020 Gitpod GmbH. All rights reserved.
* Licensed under the GNU Affero General Public License (AGPL).
* See License-AGPL.txt in the project root for license information.
*/
import {
CloneTargetMode,
FileDownloadInitializer,
GitAuthMethod,
GitConfig,
GitInitializer,
PrebuildInitializer,
SnapshotInitializer,
WorkspaceInitializer,
} from "@gitpod/content-service/lib";
import { CompositeInitializer, FromBackupInitializer } from "@gitpod/content-service/lib/initializer_pb";
import {
DBUser,
DBWithTracing,
ProjectDB,
TracedUserDB,
TracedWorkspaceDB,
UserDB,
WorkspaceDB,
} from "@gitpod/gitpod-db/lib";
import {
CommitContext,
Disposable,
GitpodToken,
GitpodTokenType,
GitCheckoutInfo,
NamedWorkspaceFeatureFlag,
RefType,
SnapshotContext,
StartWorkspaceResult,
User,
UserEnvVar,
UserEnvVarValue,
WithEnvvarsContext,
WithPrebuild,
Workspace,
WorkspaceContext,
WorkspaceImageSource,
WorkspaceImageSourceDocker,
WorkspaceImageSourceReference,
WorkspaceInstance,
WorkspaceInstanceConfiguration,
WorkspaceInstanceStatus,
WorkspaceProbeContext,
Permission,
HeadlessWorkspaceEvent,
HeadlessWorkspaceEventType,
DisposableCollection,
AdditionalContentContext,
ImageConfigFile,
ProjectEnvVar,
ImageBuildLogInfo,
} from "@gitpod/gitpod-protocol";
import { IAnalyticsWriter } from "@gitpod/gitpod-protocol/lib/analytics";
import { log } from "@gitpod/gitpod-protocol/lib/util/logging";
import { TraceContext } from "@gitpod/gitpod-protocol/lib/util/tracing";
import {
BuildRegistryAuth,
BuildRegistryAuthSelective,
BuildRegistryAuthTotal,
BuildRequest,
BuildResponse,
BuildSource,
BuildSourceDockerfile,
BuildSourceReference,
BuildStatus,
ImageBuilderClientProvider,
ResolveBaseImageRequest,
ResolveWorkspaceImageRequest,
} from "@gitpod/image-builder/lib";
import { StartWorkspaceSpec, WorkspaceFeatureFlag, StartWorkspaceResponse, IDEImage } from "@gitpod/ws-manager/lib";
import { WorkspaceManagerClientProvider } from "@gitpod/ws-manager/lib/client-provider";
import {
AdmissionLevel,
EnvironmentVariable,
GitSpec,
PortSpec,
PortVisibility,
StartWorkspaceRequest,
WorkspaceMetadata,
WorkspaceType,
} from "@gitpod/ws-manager/lib/core_pb";
import * as crypto from "crypto";
import { inject, injectable } from "inversify";
import { v4 as uuidv4 } from "uuid";
import { HostContextProvider } from "../auth/host-context-provider";
import { ScopedResourceGuard } from "../auth/resource-access";
import { Config } from "../config";
import { OneTimeSecretServer } from "../one-time-secret-server";
import { AuthorizationService } from "../user/authorization-service";
import { TokenProvider } from "../user/token-provider";
import { UserService } from "../user/user-service";
import { ImageSourceProvider } from "./image-source-provider";
import { MessageBusIntegration } from "./messagebus-integration";
import * as path from "path";
import * as grpc from "@grpc/grpc-js";
import { IDEConfig, IDEConfigService } from "../ide-config";
import { EnvVarWithValue } from "@gitpod/gitpod-protocol/src/protocol";
import { WithReferrerContext } from "@gitpod/gitpod-protocol/lib/protocol";
import { IDEOption } from "@gitpod/gitpod-protocol/lib/ide-protocol";
import { Deferred } from "@gitpod/gitpod-protocol/lib/util/deferred";
import { ExtendedUser } from "@gitpod/ws-manager/lib/constraints";
import { increaseFailedInstanceStartCounter, increaseSuccessfulInstanceStartCounter } from "../prometheus-metrics";
import { ContextParser } from "./context-parser-service";
export interface StartWorkspaceOptions {
rethrow?: boolean;
forceDefaultImage?: boolean;
excludeFeatureFlags?: NamedWorkspaceFeatureFlag[];
}
const MAX_INSTANCE_START_RETRIES = 2;
const INSTANCE_START_RETRY_INTERVAL_SECONDS = 2;
@injectable()
export class WorkspaceStarter {
@inject(WorkspaceManagerClientProvider) protected readonly clientProvider: WorkspaceManagerClientProvider;
@inject(Config) protected readonly config: Config;
@inject(IDEConfigService) private readonly ideConfigService: IDEConfigService;
@inject(TracedWorkspaceDB) protected readonly workspaceDb: DBWithTracing<WorkspaceDB>;
@inject(TracedUserDB) protected readonly userDB: DBWithTracing<UserDB>;
@inject(TokenProvider) protected readonly tokenProvider: TokenProvider;
@inject(HostContextProvider) protected readonly hostContextProvider: HostContextProvider;
@inject(MessageBusIntegration) protected readonly messageBus: MessageBusIntegration;
@inject(AuthorizationService) protected readonly authService: AuthorizationService;
@inject(ImageBuilderClientProvider) protected readonly imagebuilderClientProvider: ImageBuilderClientProvider;
@inject(ImageSourceProvider) protected readonly imageSourceProvider: ImageSourceProvider;
@inject(UserService) protected readonly userService: UserService;
@inject(IAnalyticsWriter) protected readonly analytics: IAnalyticsWriter;
@inject(OneTimeSecretServer) protected readonly otsServer: OneTimeSecretServer;
@inject(ProjectDB) protected readonly projectDB: ProjectDB;
@inject(ContextParser) protected contextParser: ContextParser;
public async startWorkspace(
ctx: TraceContext,
workspace: Workspace,
user: User,
userEnvVars: UserEnvVar[],
projectEnvVars: ProjectEnvVar[],
options?: StartWorkspaceOptions,
): Promise<StartWorkspaceResult> {
const span = TraceContext.startSpan("WorkspaceStarter.startWorkspace", ctx);
span.setTag("workspaceId", workspace.id);
options = options || {};
try {
// Some workspaces do not have an image source.
// Workspaces without image source are not only legacy, but also happened due to what looks like a bug.
// Whenever a such a workspace is re-started we'll give it an image source now. This is in line with how this thing used to work.
//
// At this point any workspace that has no imageSource should have a commit context (we don't have any other contexts which don't resolve
// to a commit context prior to being started, or which don't get an imageSource).
if (!workspace.imageSource) {
const imageSource = await this.imageSourceProvider.getImageSource(
ctx,
user,
workspace.context as CommitContext,
workspace.config,
);
log.debug("Found workspace without imageSource, generated one", { imageSource });
workspace.imageSource = imageSource;
await this.workspaceDb.trace({ span }).store(workspace);
}
if (options.forceDefaultImage) {
const req = new ResolveBaseImageRequest();
req.setRef(this.config.workspaceDefaults.workspaceImage);
const allowAll = new BuildRegistryAuthTotal();
allowAll.setAllowAll(true);
const auth = new BuildRegistryAuth();
auth.setTotal(allowAll);
req.setAuth(auth);
const client = this.imagebuilderClientProvider.getDefault();
const res = await client.resolveBaseImage({ span }, req);
workspace.imageSource = <WorkspaceImageSourceReference>{
baseImageResolved: res.getRef(),
};
}
// check if there has been an instance before, i.e. if this is a restart
const pastInstances = await this.workspaceDb.trace({ span }).findInstances(workspace.id);
const mustHaveBackup = pastInstances.some(
(i) => !!i.status && !!i.status.conditions && !i.status.conditions.failed,
);
const ideConfig = await this.ideConfigService.config;
// create and store instance
let instance = await this.workspaceDb
.trace({ span })
.storeInstance(
await this.newInstance(ctx, workspace, user, options.excludeFeatureFlags || [], ideConfig),
);
span.log({ newInstance: instance.id });
const forceRebuild = !!workspace.context.forceImageBuild;
let needsImageBuild: boolean;
try {
// if we need to build the workspace image we musn't wait for actuallyStartWorkspace to return as that would block the
// frontend until the image is built.
const additionalAuth = await this.getAdditionalImageAuth(projectEnvVars);
needsImageBuild =
forceRebuild || (await this.needsImageBuild({ span }, user, workspace, instance, additionalAuth));
if (needsImageBuild) {
instance.status.conditions = {
neededImageBuild: true,
};
}
span.setTag("needsImageBuild", needsImageBuild);
} catch (err) {
// if we fail to check if the workspace needs an image build (e.g. becuase the image builder is unavailable),
// we must properly fail the workspace instance, i.e. set its status to stopped, deal with prebuilds etc.
//
// Once we've reached actuallyStartWorkspace that function will take care of failing the instance.
await this.failInstanceStart({ span }, err, workspace, instance);
throw err;
}
// If the caller requested that errors be rethrown we must await the actual workspace start to be in the exception path.
// To this end we disable the needsImageBuild behaviour if rethrow is true.
if (needsImageBuild && !options.rethrow) {
this.actuallyStartWorkspace(
{ span },
instance,
workspace,
user,
mustHaveBackup,
ideConfig,
userEnvVars,
projectEnvVars,
options.rethrow,
forceRebuild,
).catch((err) => log.error("actuallyStartWorkspace", err));
return { instanceID: instance.id };
}
return await this.actuallyStartWorkspace(
{ span },
instance,
workspace,
user,
mustHaveBackup,
ideConfig,
userEnvVars,
projectEnvVars,
options.rethrow,
forceRebuild,
);
} catch (e) {
TraceContext.setError({ span }, e);
throw e;
} finally {
span.finish();
}
}
// Note: this function does not expect to be awaited for by its caller. This means that it takes care of error handling itself.
protected async actuallyStartWorkspace(
ctx: TraceContext,
instance: WorkspaceInstance,
workspace: Workspace,
user: User,
mustHaveBackup: boolean,
ideConfig: IDEConfig,
userEnvVars: UserEnvVar[],
projectEnvVars: ProjectEnvVar[],
rethrow?: boolean,
forceRebuild?: boolean,
): Promise<StartWorkspaceResult> {
const span = TraceContext.startSpan("actuallyStartWorkspace", ctx);
try {
// build workspace image
const additionalAuth = await this.getAdditionalImageAuth(projectEnvVars);
instance = await this.buildWorkspaceImage(
{ span },
user,
workspace,
instance,
additionalAuth,
forceRebuild,
forceRebuild,
);
let type: WorkspaceType = WorkspaceType.REGULAR;
if (workspace.type === "prebuild") {
type = WorkspaceType.PREBUILD;
} else if (workspace.type === "probe") {
type = WorkspaceType.PROBE;
}
// create spec
const spec = await this.createSpec(
{ span },
user,
workspace,
instance,
mustHaveBackup,
ideConfig,
userEnvVars,
projectEnvVars,
);
// create start workspace request
const metadata = new WorkspaceMetadata();
metadata.setOwner(workspace.ownerId);
metadata.setMetaId(workspace.id);
const startRequest = new StartWorkspaceRequest();
startRequest.setId(instance.id);
startRequest.setMetadata(metadata);
startRequest.setType(type);
startRequest.setSpec(spec);
startRequest.setServicePrefix(workspace.id);
// we add additional information to the user to help with cluster selection
const euser: ExtendedUser = {
...user,
getsMoreResources: await this.userService.userGetsMoreResources(user),
};
// choose a cluster and start the instance
let resp: StartWorkspaceResponse.AsObject | undefined = undefined;
let retries = 0;
try {
for (; retries < MAX_INSTANCE_START_RETRIES; retries++) {
resp = await this.tryStartOnCluster({ span }, startRequest, euser, workspace, instance);
if (resp) {
break;
}
await new Promise((resolve) => setTimeout(resolve, INSTANCE_START_RETRY_INTERVAL_SECONDS * 1000));
}
} catch (err) {
increaseFailedInstanceStartCounter("startOnClusterFailed");
throw err;
}
if (!resp) {
increaseFailedInstanceStartCounter("clusterSelectionFailed");
throw new Error("cannot start a workspace because no workspace clusters are available");
}
increaseSuccessfulInstanceStartCounter(retries);
span.log({ resp: resp });
this.analytics.track({
userId: user.id,
event: "workspace_started",
properties: {
workspaceId: workspace.id,
instanceId: instance.id,
contextURL: workspace.contextURL,
usesPrebuild: spec.getInitializer()?.hasPrebuild(),
},
});
{
if (type === WorkspaceType.PREBUILD) {
// do not await
this.notifyOnPrebuildQueued(ctx, workspace.id).catch((err) => {
log.error("failed to notify on prebuild queued", err);
});
}
}
return { instanceID: instance.id, workspaceURL: resp.url };
} catch (err) {
TraceContext.setError({ span }, err);
await this.failInstanceStart({ span }, err, workspace, instance);
if (rethrow) {
throw err;
} else {
log.error("error starting instance", err, { instanceId: instance.id });
}
return { instanceID: instance.id };
} finally {
span.finish();
}
}
protected async tryStartOnCluster(
ctx: TraceContext,
startRequest: StartWorkspaceRequest,
euser: ExtendedUser,
workspace: Workspace,
instance: WorkspaceInstance,
): Promise<StartWorkspaceResponse.AsObject | undefined> {
let lastInstallation = "";
const clusters = await this.clientProvider.getStartClusterSets(euser, workspace, instance);
for await (let cluster of clusters) {
try {
// getStartManager will throw an exception if there's no cluster available and hence exit the loop
const { manager, installation } = cluster;
lastInstallation = installation;
instance.status.phase = "pending";
instance.region = installation;
await this.workspaceDb.trace(ctx).storeInstance(instance);
try {
await this.messageBus.notifyOnInstanceUpdate(workspace.ownerId, instance);
} catch (err) {
// if sending the notification fails that's no reason to stop the workspace creation.
// If the dashboard misses this event it will catch up at the next one.
ctx.span?.log({ "notifyOnInstanceUpdate.error": err });
log.debug("cannot send instance update - this should be mostly inconsequential", err);
}
// start that thing
log.info({ instanceId: instance.id }, "starting instance");
return (await manager.startWorkspace(ctx, startRequest)).toObject();
} catch (err: any) {
if ("code" in err && err.code !== grpc.status.OK && lastInstallation !== "") {
log.error({ instanceId: instance.id }, "cannot start workspace on cluster, might retry", err, {
cluster: lastInstallation,
});
} else {
throw err;
}
}
}
return undefined;
}
protected async getAdditionalImageAuth(projectEnvVars: ProjectEnvVar[]): Promise<Map<string, string>> {
const res = new Map<string, string>();
const imageAuth = projectEnvVars.find((e) => e.name === "GITPOD_IMAGE_AUTH");
if (!imageAuth) {
return res;
}
const imageAuthValue = (await this.projectDB.getProjectEnvironmentVariableValues([imageAuth]))[0];
(imageAuthValue.value || "")
.split(",")
.map((e) => e.trim().split(":"))
.filter((e) => e.length == 2)
.forEach((e) => res.set(e[0], e[1]));
return res;
}
protected async notifyOnPrebuildQueued(ctx: TraceContext, workspaceId: string) {
const span = TraceContext.startSpan("notifyOnPrebuildQueued", ctx);
const prebuild = await this.workspaceDb.trace({ span }).findPrebuildByWorkspaceID(workspaceId);
if (prebuild) {
const info = (await this.workspaceDb.trace({ span }).findPrebuildInfos([prebuild.id]))[0];
if (info) {
await this.messageBus.notifyOnPrebuildUpdate({ info, status: "queued" });
}
}
}
/**
* failInstanceStart properly fails a workspace instance if something goes wrong before the instance ever reaches
* workspace manager. In this case we need to make sure we also fulfil the tasks of the bridge (e.g. for prebulds).
*/
protected async failInstanceStart(
ctx: TraceContext,
err: Error,
workspace: Workspace,
instance: WorkspaceInstance,
) {
const span = TraceContext.startSpan("failInstanceStart", ctx);
try {
// We may have never actually started the workspace which means that ws-manager-bridge never set a workspace status.
// We have to set that status ourselves.
instance.status.phase = "stopped";
instance.stoppingTime = new Date().toISOString();
instance.stoppedTime = new Date().toISOString();
instance.status.conditions.failed = err.toString();
instance.status.message = `Workspace cannot be started: ${err}`;
await this.workspaceDb.trace({ span }).storeInstance(instance);
await this.messageBus.notifyOnInstanceUpdate(workspace.ownerId, instance);
// If we just attempted to start a workspace for a prebuild - and that failed, we have to fail the prebuild itself.
if (workspace.type === "prebuild") {
const prebuild = await this.workspaceDb.trace({ span }).findPrebuildByWorkspaceID(workspace.id);
if (prebuild && prebuild.state !== "failed") {
prebuild.state = "failed";
prebuild.error = err.toString();
await this.workspaceDb.trace({ span }).storePrebuiltWorkspace(prebuild);
await this.messageBus.notifyHeadlessUpdate({ span }, workspace.ownerId, workspace.id, <
HeadlessWorkspaceEvent
>{
type: HeadlessWorkspaceEventType.Failed,
// TODO: `workspaceID: workspace.id` not needed here? (found in ee/src/prebuilds/prebuild-queue-maintainer.ts and ee/src/bridge.ts)
});
}
}
} catch (err) {
TraceContext.setError({ span }, err);
log.error(
{ workspaceId: workspace.id, instanceId: instance.id, userId: workspace.ownerId },
"cannot properly fail workspace instance during start",
err,
);
}
}
/**
* Creates a new instance for a given workspace and its owner
*
* @param workspace the workspace to create an instance for
*/
protected async newInstance(
ctx: TraceContext,
workspace: Workspace,
user: User,
excludeFeatureFlags: NamedWorkspaceFeatureFlag[],
ideConfig: IDEConfig,
): Promise<WorkspaceInstance> {
// TODO(cw): once we allow changing the IDE in the workspace config (i.e. .gitpod.yml), we must
// give that value precedence over the default choice.
const configuration: WorkspaceInstanceConfiguration = {
ideImage: ideConfig.ideOptions.options[ideConfig.ideOptions.defaultIde].image,
supervisorImage: ideConfig.supervisorImage,
};
const ideChoice = user.additionalData?.ideSettings?.defaultIde;
if (!!ideChoice) {
const mappedImage = ideConfig.ideOptions.options[ideChoice];
if (!!mappedImage && mappedImage.image) {
configuration.ideImage = mappedImage.image;
} else if (this.authService.hasPermission(user, "ide-settings")) {
// if the IDE choice isn't one of the preconfiured choices, we assume its the image name.
// For now, this feature requires special permissions.
configuration.ideImage = ideChoice;
}
}
const useLatest = !!user.additionalData?.ideSettings?.useLatestVersion;
const referrerIde = this.resolveReferrerIDE(workspace, user, ideConfig);
if (referrerIde) {
configuration.desktopIdeImage = useLatest
? referrerIde.option.latestImage ?? referrerIde.option.image
: referrerIde.option.image;
if (!user.additionalData?.ideSettings) {
// A user does not have IDE settings configured yet configure it with a referrer ide as default.
const additionalData = user?.additionalData || {};
const settings = additionalData.ideSettings || {};
settings.useDesktopIde = true;
settings.defaultDesktopIde = referrerIde.id;
additionalData.ideSettings = settings;
user.additionalData = additionalData;
this.userDB
.trace(ctx)
.updateUserPartial(user)
.catch((e) => {
log.error({ userId: user.id }, "cannot configure default desktop ide", e);
});
}
} else {
const useDesktopIdeChoice = user.additionalData?.ideSettings?.useDesktopIde || false;
if (useDesktopIdeChoice) {
const desktopIdeChoice = user.additionalData?.ideSettings?.defaultDesktopIde;
if (!!desktopIdeChoice) {
const mappedImage = ideConfig.ideOptions.options[desktopIdeChoice];
if (!!mappedImage && mappedImage.image) {
configuration.desktopIdeImage = useLatest
? mappedImage.latestImage ?? mappedImage.image
: mappedImage.image;
} else if (this.authService.hasPermission(user, "ide-settings")) {
// if the IDE choice isn't one of the preconfiured choices, we assume its the image name.
// For now, this feature requires special permissions.
configuration.desktopIdeImage = desktopIdeChoice;
}
}
}
}
let featureFlags: NamedWorkspaceFeatureFlag[] = workspace.config._featureFlags || [];
featureFlags = featureFlags.concat(this.config.workspaceDefaults.defaultFeatureFlags);
if (user.featureFlags && user.featureFlags.permanentWSFeatureFlags) {
featureFlags = featureFlags.concat(featureFlags, user.featureFlags.permanentWSFeatureFlags);
}
// if the user has feature preview enabled, we need to add the respective feature flags.
// Beware: all feature flags we add here are not workspace-persistent feature flags, e.g. no full-workspace backup.
if (!!user.additionalData?.featurePreview) {
featureFlags = featureFlags.concat(
this.config.workspaceDefaults.previewFeatureFlags.filter((f) => !featureFlags.includes(f)),
);
}
featureFlags = featureFlags.filter((f) => !excludeFeatureFlags.includes(f));
if (!!featureFlags) {
// only set feature flags if there actually are any. Otherwise we waste the
// few bytes of JSON in the database for no good reason.
configuration.featureFlags = featureFlags;
}
const now = new Date().toISOString();
const instance: WorkspaceInstance = {
id: uuidv4(),
workspaceId: workspace.id,
creationTime: now,
ideUrl: "", // Initially empty, filled during starting process
region: this.config.installationShortname, // Shortname set to bridge can cleanup workspaces stuck preparing
workspaceImage: "", // Initially empty, filled during starting process
status: {
conditions: {},
phase: "unknown",
},
configuration,
};
if (WithReferrerContext.is(workspace.context)) {
this.analytics.track({
userId: user.id,
event: "ide_referrer",
properties: {
workspaceId: workspace.id,
instanceId: instance.id,
referrer: workspace.context.referrer,
referrerIde: workspace.context.referrerIde,
},
});
}
return instance;
}
protected resolveReferrerIDE(
workspace: Workspace,
user: User,
ideConfig: IDEConfig,
): { id: string; option: IDEOption } | undefined {
if (!WithReferrerContext.is(workspace.context)) {
return undefined;
}
const referrer = ideConfig.ideOptions.clients?.[workspace.context.referrer];
if (!referrer) {
return undefined;
}
const providedIde = workspace.context.referrerIde;
const providedOption = providedIde && ideConfig.ideOptions.options[providedIde];
if (providedOption && referrer.desktopIDEs?.some((ide) => ide === providedIde)) {
return { id: providedIde, option: providedOption };
}
const defaultDesktopIde = user.additionalData?.ideSettings?.defaultDesktopIde;
const userOption = defaultDesktopIde && ideConfig.ideOptions.options[defaultDesktopIde];
if (userOption && referrer.desktopIDEs?.some((ide) => ide === defaultDesktopIde)) {
return { id: defaultDesktopIde, option: userOption };
}
const defaultIde = referrer.defaultDesktopIDE;
const defaultOption = defaultIde && ideConfig.ideOptions.options[defaultIde];
if (defaultOption) {
return { id: defaultIde, option: defaultOption };
}
return undefined;
}
protected async prepareBuildRequest(
ctx: TraceContext,
workspace: Workspace,
imgsrc: WorkspaceImageSource,
user: User,
additionalAuth: Map<string, string>,
ignoreBaseImageresolvedAndRebuildBase: boolean = false,
): Promise<{ src: BuildSource; auth: BuildRegistryAuth; disposable?: Disposable }> {
const span = TraceContext.startSpan("prepareBuildRequest", ctx);
try {
// if our workspace ever had its base image built, we do not want to build it again. In this case we use a build source reference
// and dismiss the original image source.
if (workspace.baseImageNameResolved && !ignoreBaseImageresolvedAndRebuildBase) {
span.setTag("hasBaseImageNameResolved", true);
span.log({ baseImageNameResolved: workspace.baseImageNameResolved });
const ref = new BuildSourceReference();
ref.setRef(workspace.baseImageNameResolved);
const src = new BuildSource();
src.setRef(ref);
// It doesn't matter what registries the user has access to at this point.
// All they need access to is the base image repository, as we're building the Gitpod layer only.
const nauth = new BuildRegistryAuthSelective();
nauth.setAllowBaserep(true);
// The base image is not neccesarily stored on the Gitpod registry, but might also come
// from a private whitelisted registry also. Hence allowBaserep is not enough, and we also
// need to explicitly allow all whitelisted registry when resolving the base image.
nauth.setAnyOfList(this.config.defaultBaseImageRegistryWhitelist);
const auth = new BuildRegistryAuth();
auth.setSelective(nauth);
return { src, auth };
}
const auth = new BuildRegistryAuth();
const userHasRegistryAccess = this.authService.hasPermission(user, Permission.REGISTRY_ACCESS);
if (userHasRegistryAccess) {
const totalAuth = new BuildRegistryAuthTotal();
totalAuth.setAllowAll(userHasRegistryAccess);
auth.setTotal(totalAuth);
} else {
const selectiveAuth = new BuildRegistryAuthSelective();
selectiveAuth.setAnyOfList(this.config.defaultBaseImageRegistryWhitelist);
auth.setSelective(selectiveAuth);
}
additionalAuth.forEach((val, key) => auth.getAdditionalMap().set(key, val));
if (WorkspaceImageSourceDocker.is(imgsrc)) {
let source: WorkspaceInitializer;
const disp = new DisposableCollection();
let checkoutLocation =
(CommitContext.is(workspace.context) && workspace.context.checkoutLocation) || ".";
if (
!AdditionalContentContext.hasDockerConfig(workspace.context, workspace.config) &&
imgsrc.dockerFileSource
) {
// TODO(se): we cannot change this initializer structure now because it is part of how baserefs are computed in image-builder.
// Image builds should however just use the initialization if the workspace they are running for (i.e. the one from above).
const { initializer, disposable } = await this.createCommitInitializer(
{ span },
workspace,
{
...imgsrc.dockerFileSource,
checkoutLocation: ".",
title: "irrelevant",
ref: undefined,
},
user,
);
disp.push(disposable);
let git: GitInitializer;
if (initializer instanceof CompositeInitializer) {
// we use the first git initializer for image builds only
git = initializer.getInitializerList()[0].getGit()!;
} else {
git = initializer;
}
git.setCloneTaget(imgsrc.dockerFileSource.revision);
git.setTargetMode(CloneTargetMode.REMOTE_COMMIT);
source = new WorkspaceInitializer();
source.setGit(git);
} else {
const { initializer, disposable } = await this.createInitializer(
{ span },
workspace,
workspace.context,
user,
false,
);
source = initializer;
disp.push(disposable);
}
const context = (workspace.config.image as ImageConfigFile).context;
const contextPath = !!context ? path.join(checkoutLocation, context) : checkoutLocation;
const dockerFilePath = path.join(checkoutLocation, imgsrc.dockerFilePath);
const file = new BuildSourceDockerfile();
file.setContextPath(contextPath);
file.setDockerfilePath(dockerFilePath);
file.setSource(source);
file.setDockerfileVersion(imgsrc.dockerFileHash);
const src = new BuildSource();
src.setFile(file);
return { src, auth, disposable: disp };
}
if (WorkspaceImageSourceReference.is(imgsrc)) {
const ref = new BuildSourceReference();
ref.setRef(imgsrc.baseImageResolved);
const src = new BuildSource();
src.setRef(ref);
return { src, auth };
}
throw new Error("unknown workspace image source");
} catch (e) {
TraceContext.setError({ span }, e);
throw e;
} finally {
span.finish();
}
}
protected async needsImageBuild(
ctx: TraceContext,
user: User,
workspace: Workspace,
instance: WorkspaceInstance,
additionalAuth: Map<string, string>,
): Promise<boolean> {
const span = TraceContext.startSpan("needsImageBuild", ctx);
try {
const client = this.imagebuilderClientProvider.getDefault();
const { src, auth, disposable } = await this.prepareBuildRequest(
{ span },
workspace,
workspace.imageSource!,
user,
additionalAuth,
);
const req = new ResolveWorkspaceImageRequest();
req.setSource(src);
req.setAuth(auth);
const result = await client.resolveWorkspaceImage({ span }, req);
if (!!disposable) {
disposable.dispose();
}
return result.getStatus() != BuildStatus.DONE_SUCCESS;
} catch (err) {
TraceContext.setError({ span }, err);
throw err;
} finally {
span.finish();
}
}
protected async buildWorkspaceImage(
ctx: TraceContext,
user: User,
workspace: Workspace,
instance: WorkspaceInstance,
additionalAuth: Map<string, string>,
ignoreBaseImageresolvedAndRebuildBase: boolean = false,
forceRebuild: boolean = false,
): Promise<WorkspaceInstance> {
const span = TraceContext.startSpan("buildWorkspaceImage", ctx);
try {
// Start build...
const client = this.imagebuilderClientProvider.getDefault();
const { src, auth, disposable } = await this.prepareBuildRequest(
{ span },
workspace,
workspace.imageSource!,
user,
additionalAuth,
ignoreBaseImageresolvedAndRebuildBase || forceRebuild,
);
const req = new BuildRequest();
req.setSource(src);
req.setAuth(auth);
req.setForceRebuild(forceRebuild);
// Make sure we persist logInfo as soon as we retrieve it
const imageBuildLogInfo = new Deferred<ImageBuildLogInfo>();
imageBuildLogInfo.promise
.then(async (logInfo) => {
const imageBuildInfo = {
...(instance.imageBuildInfo || {}),
log: logInfo,
};
instance.imageBuildInfo = imageBuildInfo; // make sure we're not overriding ourselves again
await this.workspaceDb
.trace({ span })
.updateInstancePartial(instance.id, { imageBuildInfo })
.catch((err) => log.error("error writing image build log info to the DB", err));
})
.catch((err) => log.warn("image build: never received log info"));
const result = await client.build({ span }, req, imageBuildLogInfo);
// Update the workspace now that we know what the name of the workspace image will be (which doubles as buildID)
workspace.imageNameResolved = result.ref;
span.log({ ref: workspace.imageNameResolved });
await this.workspaceDb.trace({ span }).store(workspace);
// Update workspace instance to tell the world we're building an image
const workspaceImage = result.ref;
const status: WorkspaceInstanceStatus = result.actuallyNeedsBuild
? { ...instance.status, phase: "preparing" }
: instance.status;
instance = await this.workspaceDb
.trace({ span })
.updateInstancePartial(instance.id, { workspaceImage, status });
await this.messageBus.notifyOnInstanceUpdate(workspace.ownerId, instance);
let buildResult: BuildResponse;
try {
// ...and wait for the build to finish
buildResult = await result.buildPromise;
if (buildResult.getStatus() == BuildStatus.DONE_FAILURE) {
throw new Error(buildResult.getMessage());
}
} catch (err) {
if (
err &&
err.message &&
err.message.includes("base image does not exist") &&
!ignoreBaseImageresolvedAndRebuildBase
) {
// we've attempted to add the base layer for a workspace whoose base image has gone missing.
// Ignore the previously built (now missing) base image and force a rebuild.
return this.buildWorkspaceImage(ctx, user, workspace, instance, additionalAuth, true, forceRebuild);
} else {
throw err;
}
} finally {
// clean any created one time secrets, so they don't hang around unnecessarily
if (!!disposable) {
disposable.dispose();
}
}
// We have just found out how our base image is called - remember that.
// Note: it's intentional that we overwrite existing baseImageNameResolved values here so that one by one the refs here become absolute (i.e. digested form).
// This prevents the "rebuilds" for old workspaces.
if (!!buildResult.getBaseRef() && buildResult.getBaseRef() != workspace.baseImageNameResolved) {
span.log({ oldBaseRef: workspace.baseImageNameResolved, newBaseRef: buildResult.getBaseRef() });
workspace.baseImageNameResolved = buildResult.getBaseRef();
await this.workspaceDb.trace({ span }).store(workspace);
}
return instance;
} catch (err) {
// Notify error
let message = "Error building image!";
if (err && err.message) {
message = err.message;
}
instance = await this.workspaceDb.trace({ span }).updateInstancePartial(instance.id, {
status: { ...instance.status, phase: "preparing", conditions: { failed: message }, message },
});
await this.messageBus.notifyOnInstanceUpdate(workspace.ownerId, instance);
TraceContext.setError({ span }, err);
const looksLikeUserError = (msg: string): boolean => {
return msg.startsWith("build failed:");
};
if (looksLikeUserError(message)) {
log.debug(
{ instanceId: instance.id, userId: user.id, workspaceId: workspace.id },
`workspace image build failed: ${message}`,
);
} else {
log.warn(
{ instanceId: instance.id, userId: user.id, workspaceId: workspace.id },
`workspace image build failed: ${message}`,
);
}
this.analytics.track({
userId: user.id,
event: "imagebuild-failed",
properties: { workspaceId: workspace.id, instanceId: instance.id, contextURL: workspace.contextURL },
});
throw err;
} finally {
span.finish();
}
}
protected async createSpec(
traceCtx: TraceContext,
user: User,
workspace: Workspace,
instance: WorkspaceInstance,
mustHaveBackup: boolean,
ideConfig: IDEConfig,
userEnvVars: UserEnvVarValue[],
projectEnvVars: ProjectEnvVar[],
): Promise<StartWorkspaceSpec> {
const context = workspace.context;
let allEnvVars: EnvVarWithValue[] = [];
if (userEnvVars.length > 0) {
if (CommitContext.is(context)) {
// this is a commit context, thus we can filter the env vars
allEnvVars = allEnvVars.concat(
UserEnvVar.filter(userEnvVars, context.repository.owner, context.repository.name),
);
} else {
allEnvVars = allEnvVars.concat(userEnvVars);
}
}
if (projectEnvVars.length > 0) {
// Instead of using an access guard for Project environment variables, we let Project owners decide whether
// a variable should be:
// - exposed in all workspaces (even for non-Project members when the repository is public), or
// - censored from all workspaces (even for Project members)
let availablePrjEnvVars = projectEnvVars;
if (workspace.type !== "prebuild") {