-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
workspace-starter.ts
1921 lines (1758 loc) · 81.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,
TeamDB,
TracedUserDB,
TracedWorkspaceDB,
UserDB,
WorkspaceDB,
} from "@gitpod/gitpod-db/lib";
import { BlockedRepositoryDB } from "@gitpod/gitpod-db/lib/blocked-repository-db";
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,
IDESettings,
} 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,
VolumeSnapshotInfo,
StopWorkspacePolicy,
StopWorkspaceRequest,
} 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, IDEOptions } 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 {
FailedInstanceStartReason,
increaseFailedInstanceStartCounter,
increaseSuccessfulInstanceStartCounter,
} from "../prometheus-metrics";
import { ContextParser } from "./context-parser-service";
import { IDEService } from "../ide-service";
import { WorkspaceClusterImagebuilderClientProvider } from "./workspace-cluster-imagebuilder-client-provider";
import { getExperimentsClientForBackend } from "@gitpod/gitpod-protocol/lib/experiments/configcat-server";
import { WorkspaceClasses, WorkspaceClassesConfig } from "./workspace-classes";
import { EntitlementService } from "../billing/entitlement-service";
import { BillingModes } from "../../ee/src/billing/billing-mode";
import { AttributionId } from "@gitpod/gitpod-protocol/lib/attribution";
import { BillingMode } from "@gitpod/gitpod-protocol/lib/billing-mode";
import { LogContext } from "@gitpod/gitpod-protocol/lib/util/logging";
export interface StartWorkspaceOptions {
rethrow?: boolean;
forceDefaultImage?: boolean;
excludeFeatureFlags?: NamedWorkspaceFeatureFlag[];
pvcEnabledForPrebuilds?: boolean;
}
const MAX_INSTANCE_START_RETRIES = 2;
const INSTANCE_START_RETRY_INTERVAL_SECONDS = 2;
// TODO(ak) move to IDE service
export const migrationIDESettings = (user: User) => {
if (!user?.additionalData?.ideSettings || user.additionalData.ideSettings.settingVersion === "2.0") {
return;
}
const newIDESettings: IDESettings = {
settingVersion: "2.0",
};
const ideSettings = user.additionalData.ideSettings;
if (ideSettings.useDesktopIde) {
if (ideSettings.defaultDesktopIde === "code-desktop") {
newIDESettings.defaultIde = "code-desktop";
} else if (ideSettings.defaultDesktopIde === "code-desktop-insiders") {
newIDESettings.defaultIde = "code-desktop";
newIDESettings.useLatestVersion = true;
} else {
newIDESettings.defaultIde = ideSettings.defaultDesktopIde;
newIDESettings.useLatestVersion = ideSettings.useLatestVersion;
}
} else {
const useLatest = ideSettings.defaultIde === "code-latest";
newIDESettings.defaultIde = "code";
newIDESettings.useLatestVersion = useLatest;
}
return newIDESettings;
};
// TODO(ak) move to IDE service
export const chooseIDE = (
ideChoice: string,
ideOptions: IDEOptions,
useLatest: boolean,
hasIdeSettingPerm: boolean,
) => {
const defaultIDEOption = ideOptions.options[ideOptions.defaultIde];
const defaultIdeImage = useLatest ? defaultIDEOption.latestImage ?? defaultIDEOption.image : defaultIDEOption.image;
const data: { desktopIdeImage?: string; desktopIdePluginImage?: string; ideImage: string } = {
ideImage: defaultIdeImage,
};
const chooseOption = ideOptions.options[ideChoice] ?? defaultIDEOption;
const isDesktopIde = chooseOption.type === "desktop";
if (isDesktopIde) {
data.desktopIdeImage = useLatest ? chooseOption?.latestImage ?? chooseOption?.image : chooseOption?.image;
data.desktopIdePluginImage = useLatest
? chooseOption?.pluginLatestImage ?? chooseOption?.pluginImage
: chooseOption?.pluginImage;
if (hasIdeSettingPerm) {
data.desktopIdeImage = data.desktopIdeImage || ideChoice;
}
} else {
data.ideImage = useLatest ? chooseOption?.latestImage ?? chooseOption?.image : chooseOption?.image;
if (hasIdeSettingPerm) {
data.ideImage = data.ideImage || ideChoice;
}
}
if (!data.ideImage) {
data.ideImage = defaultIdeImage;
// throw new Error("cannot choose correct browser ide");
}
return data;
};
export async function getWorkspaceClassForInstance(
ctx: TraceContext,
workspace: Workspace,
previousInstance: WorkspaceInstance | undefined,
user: User,
entitlementService: EntitlementService,
config: WorkspaceClassesConfig,
workspaceDb: DBWithTracing<WorkspaceDB>,
): Promise<string> {
const span = TraceContext.startSpan("getWorkspaceClassForInstance", ctx);
try {
let workspaceClass = "";
if (!previousInstance?.workspaceClass) {
if (workspace.type == "regular") {
const prebuildClass = await WorkspaceClasses.getFromPrebuild(ctx, workspace, workspaceDb.trace(ctx));
if (prebuildClass) {
const userClass = await WorkspaceClasses.getConfiguredOrUpgradeFromLegacy(
user,
config,
entitlementService,
);
workspaceClass = WorkspaceClasses.selectClassForRegular(prebuildClass, userClass, config);
} else if (user.additionalData?.workspaceClasses?.regular) {
workspaceClass = user.additionalData?.workspaceClasses?.regular;
}
}
if (workspace.type == "prebuild") {
if (user.additionalData?.workspaceClasses?.prebuild) {
workspaceClass = user.additionalData?.workspaceClasses?.prebuild;
}
}
if (!workspaceClass) {
workspaceClass = WorkspaceClasses.getDefaultId(config);
if (await entitlementService.userGetsMoreResources(user)) {
workspaceClass = WorkspaceClasses.getMoreResourcesIdOrDefault(config);
}
}
} else {
workspaceClass = WorkspaceClasses.getPreviousOrDefault(config, previousInstance.workspaceClass);
}
return workspaceClass;
} finally {
span.finish();
}
}
class StartInstanceError extends Error {
constructor(public readonly reason: FailedInstanceStartReason, public readonly cause: Error) {
super("Starting workspace instance failed: " + cause.message);
}
}
@injectable()
export class WorkspaceStarter {
@inject(WorkspaceManagerClientProvider) protected readonly clientProvider: WorkspaceManagerClientProvider;
@inject(Config) protected readonly config: Config;
@inject(IDEConfigService) private readonly ideConfigService: IDEConfigService;
@inject(IDEService) private readonly ideService: IDEService;
@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(WorkspaceClusterImagebuilderClientProvider)
protected readonly wsClusterImageBuilderClientProvider: 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;
@inject(BlockedRepositoryDB) protected readonly blockedRepositoryDB: BlockedRepositoryDB;
@inject(TeamDB) protected readonly teamDB: TeamDB;
@inject(EntitlementService) protected readonly entitlementService: EntitlementService;
@inject(BillingModes) protected readonly billingModes: BillingModes;
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);
if (workspace.projectId && workspace.type === "regular") {
/* tslint:disable-next-line */
/** no await */ this.projectDB.updateProjectUsage(workspace.projectId, {
lastWorkspaceStart: new Date().toISOString(),
});
}
options = options || {};
let instanceId: string | undefined = undefined;
try {
await this.checkBlockedRepository(user, workspace.contextURL);
// 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 = await this.getImageBuilderClient(user, workspace, undefined);
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 hasValidBackup = pastInstances.some(
(i) => !!i.status && !!i.status.conditions && !i.status.conditions.failed,
);
let lastValidWorkspaceInstance: WorkspaceInstance | undefined;
if (hasValidBackup) {
lastValidWorkspaceInstance = pastInstances.reduce((previousValue, currentValue) =>
currentValue.creationTime > previousValue.creationTime ? currentValue : previousValue,
);
}
const ideConfig = await this.ideConfigService.config;
// create and store instance
let instance = await this.workspaceDb
.trace({ span })
.storeInstance(
await this.newInstance(
ctx,
workspace,
lastValidWorkspaceInstance,
user,
options.excludeFeatureFlags || [],
ideConfig,
options.pvcEnabledForPrebuilds || false,
),
);
span.log({ newInstance: instance.id });
instanceId = 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,
lastValidWorkspaceInstance?.id ?? "",
ideConfig,
userEnvVars,
projectEnvVars,
options.rethrow,
forceRebuild,
).catch((err) => log.error("actuallyStartWorkspace", err));
return { instanceID: instance.id };
}
return await this.actuallyStartWorkspace(
{ span },
instance,
workspace,
user,
lastValidWorkspaceInstance?.id ?? "",
ideConfig,
userEnvVars,
projectEnvVars,
options.rethrow,
forceRebuild,
);
} catch (e) {
this.logAndTraceStartWorkspaceError({ span }, { userId: user.id, instanceId }, e);
throw e;
} finally {
span.finish();
}
}
public async stopWorkspaceInstance(
ctx: TraceContext,
instanceId: string,
instanceRegion: string,
reason: string,
policy?: StopWorkspacePolicy,
): Promise<void> {
ctx.span?.setTag("stopWorkspaceReason", reason);
log.info({ instanceId }, "Stopping workspace instance", { reason });
const req = new StopWorkspaceRequest();
req.setId(instanceId);
req.setPolicy(policy || StopWorkspacePolicy.NORMALLY);
const client = await this.clientProvider.get(instanceRegion);
await client.stopWorkspace(ctx, req);
}
protected async checkBlockedRepository(user: User, contextURL: string) {
const blockedRepository = await this.blockedRepositoryDB.findBlockedRepositoryByURL(contextURL);
if (!blockedRepository) return;
if (blockedRepository.blockUser) {
try {
await this.userService.blockUser(user.id, true);
log.info({ userId: user.id }, "Blocked user.", { contextURL });
} catch (error) {
log.error({ userId: user.id }, "Failed to block user.", error, { contextURL });
}
}
throw new Error(`${contextURL} is blocklisted on Gitpod.`);
}
// 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,
lastValidWorkspaceInstanceId: string,
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,
lastValidWorkspaceInstanceId,
ideConfig,
userEnvVars,
projectEnvVars,
);
// create start workspace request
const metadata = await this.createMetadata(workspace);
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,
};
// 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) {
await this.failInstanceStart({ span }, err, workspace, instance);
throw new StartInstanceError("startOnClusterFailed", err);
}
if (!resp) {
const err = new Error("cannot start a workspace because no workspace clusters are available");
await this.failInstanceStart({ span }, err, workspace, instance);
throw new StartInstanceError("clusterSelectionFailed", err);
}
increaseSuccessfulInstanceStartCounter(retries);
span.log({ resp: resp });
this.analytics.track({
userId: user.id,
event: "workspace_started",
properties: {
workspaceId: workspace.id,
instanceId: instance.id,
projectId: workspace.projectId,
contextURL: workspace.contextURL,
type: workspace.type,
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) {
if (rethrow) {
throw err;
} else {
this.logAndTraceStartWorkspaceError({ span }, { userId: user.id, instanceId: instance.id }, err);
}
return { instanceID: instance.id };
} finally {
span.finish();
}
}
protected logAndTraceStartWorkspaceError(ctx: TraceContext, logCtx: LogContext, err: any) {
TraceContext.setError(ctx, err);
let reason: FailedInstanceStartReason | undefined = undefined;
if (err instanceof StartInstanceError) {
reason = err.reason;
increaseFailedInstanceStartCounter(reason);
}
log.error(logCtx, "error starting instance", err, {
failedInstanceStartReason: reason,
});
ctx.span?.setTag("failedInstanceStartReason", reason);
}
protected async createMetadata(workspace: Workspace): Promise<WorkspaceMetadata> {
let metadata = new WorkspaceMetadata();
metadata.setOwner(workspace.ownerId);
metadata.setMetaId(workspace.id);
if (workspace.projectId) {
metadata.setProject(workspace.projectId);
let project = await this.projectDB.findProjectById(workspace.projectId);
if (project && project.teamId) {
metadata.setTeam(project.teamId);
}
}
return metadata;
}
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);
try {
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" });
}
}
} catch (e) {
TraceContext.setError({ span }, e);
throw e;
} finally {
span.finish();
}
}
/**
* 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,
);
} finally {
span.finish();
}
}
/**
* 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,
previousInstance: WorkspaceInstance | undefined,
user: User,
excludeFeatureFlags: NamedWorkspaceFeatureFlag[],
ideConfig: IDEConfig,
pvcEnabledForPrebuilds: boolean,
): Promise<WorkspaceInstance> {
const span = TraceContext.startSpan("newInstance", ctx);
//#endregion IDE resolution TODO(ak) move to IDE service
// TODO: Compatible with ide-config not deployed, need revert after ide-config deployed
delete ideConfig.ideOptions.options["code-latest"];
delete ideConfig.ideOptions.options["code-desktop-insiders"];
try {
const migrated = migrationIDESettings(user);
if (user.additionalData?.ideSettings && migrated) {
user.additionalData.ideSettings = migrated;
}
const ideChoice = user.additionalData?.ideSettings?.defaultIde;
const useLatest = !!user.additionalData?.ideSettings?.useLatestVersion;
// 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,
ideConfig: {
// We only check user setting because if code(insider) but desktopIde has no latestImage
// it still need to notice user that this workspace is using latest IDE
useLatest: user.additionalData?.ideSettings?.useLatestVersion,
},
};
if (!!ideChoice) {
const choose = chooseIDE(
ideChoice,
ideConfig.ideOptions,
useLatest,
this.authService.hasPermission(user, "ide-settings"),
);
configuration.ideImage = choose.ideImage;
configuration.desktopIdeImage = choose.desktopIdeImage;
configuration.desktopIdePluginImage = choose.desktopIdePluginImage;
}
const referrerIde = this.resolveReferrerIDE(workspace, user, ideConfig);
if (referrerIde) {
configuration.desktopIdeImage = useLatest
? referrerIde.option.latestImage ?? referrerIde.option.image
: referrerIde.option.image;
configuration.desktopIdePluginImage = useLatest
? referrerIde.option.pluginLatestImage ?? referrerIde.option.pluginImage
: referrerIde.option.pluginImage;
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.settingVersion = "2.0";
settings.defaultIde = 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);
});
}
}
//#endregion
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)),
);
}
if (await getExperimentsClientForBackend().getValueAsync("protected_secrets", false, { user })) {
// We roll out the protected secrets feature using a ConfigCat feature flag, to ensure
// a smooth, gradual roll out without breaking users.
featureFlags = featureFlags.concat(["protected_secrets"]);
}
featureFlags = featureFlags.filter((f) => !excludeFeatureFlags.includes(f));
if (workspace.type === "prebuild") {
if (pvcEnabledForPrebuilds === true) {
featureFlags = featureFlags.concat(["persistent_volume_claim"]);
} else {
// If PVC is disabled for prebuilds, we need to remove the PVC feature flag.
// This is necessary to ensure if user has PVC enabled on their account, that they
// will not hijack prebuild with PVC and make everyone who use this prebuild to auto enroll into PVC feature.
featureFlags = featureFlags.filter((f) => f !== "persistent_volume_claim");
}
}
let workspaceClass = "";
const userTeams = await this.teamDB.findTeamsByUser(user.id);
let classesEnabled = await getExperimentsClientForBackend().getValueAsync("workspace_classes", false, {
user: user,
teams: userTeams,
});
const usageAttributionId = await this.userService.getWorkspaceUsageAttributionId(user, workspace.projectId);
const billingMode = await this.billingModes.getBillingMode(usageAttributionId, new Date());
if (classesEnabled || BillingMode.canSetWorkspaceClass(billingMode)) {
// this is either the first time we start the workspace or the workspace was started
// before workspace classes and does not have a class yet
workspaceClass = await getWorkspaceClassForInstance(
ctx,
workspace,
previousInstance,
user,
this.entitlementService,
this.config.workspaceClasses,
this.workspaceDb,
);
if (featureFlags.includes("persistent_volume_claim")) {
if (workspaceClass === "g1-standard" || workspaceClass === "g1-large") {
workspaceClass = workspaceClass + "-pvc";
}
}
featureFlags = featureFlags.concat(["workspace_class_limiting"]);
} else {
// todo: remove this once pvc has been rolled out
const prebuildClass = await WorkspaceClasses.getFromPrebuild(
ctx,
workspace,
this.workspaceDb.trace(ctx),
);
if (prebuildClass?.endsWith("-pvc")) {
workspaceClass = prebuildClass;
// ####
} else {
workspaceClass = "default";
if (await this.entitlementService.userGetsMoreResources(user)) {
workspaceClass = "gitpodio-internal-xl";
}
}
}
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: {
version: 0,
conditions: {},
phase: "preparing",
},
configuration,
usageAttributionId: usageAttributionId && AttributionId.render(usageAttributionId),
workspaceClass,
};
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;
} finally {
span.finish();
}
}
// TODO(ak) move to IDE service
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);