-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathworkspace-starter.ts
2116 lines (1945 loc) · 90.3 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 {
DBWithTracing,
ProjectDB,
RedisPublisher,
TeamDB,
TracedUserDB,
TracedWorkspaceDB,
UserDB,
WorkspaceDB,
} from "@gitpod/gitpod-db/lib";
import { BlockedRepositoryDB } from "@gitpod/gitpod-db/lib/blocked-repository-db";
import {
AdditionalContentContext,
BillingTier,
CommitContext,
Disposable,
DisposableCollection,
EnvVar,
GitCheckoutInfo,
GitpodServer,
GitpodToken,
GitpodTokenType,
HeadlessWorkspaceEventType,
IDESettings,
ImageBuildLogInfo,
ImageConfigFile,
NamedWorkspaceFeatureFlag,
Permission,
Project,
RefType,
SnapshotContext,
StartWorkspaceResult,
TaskConfig,
User,
WithPrebuild,
WithReferrerContext,
Workspace,
WorkspaceContext,
WorkspaceImageSource,
WorkspaceImageSourceDocker,
WorkspaceImageSourceReference,
WorkspaceInstance,
WorkspaceInstanceConfiguration,
WorkspaceInstancePhase,
WorkspaceInstanceStatus,
WorkspaceTimeoutDuration,
} from "@gitpod/gitpod-protocol";
import { IAnalyticsWriter, TrackMessage } from "@gitpod/gitpod-protocol/lib/analytics";
import { AttributionId } from "@gitpod/gitpod-protocol/lib/attribution";
import { Deferred } from "@gitpod/gitpod-protocol/lib/util/deferred";
import { LogContext, log } from "@gitpod/gitpod-protocol/lib/util/logging";
import { TraceContext } from "@gitpod/gitpod-protocol/lib/util/tracing";
import { WorkspaceRegion } from "@gitpod/gitpod-protocol/lib/workspace-cluster";
import * as IdeServiceApi from "@gitpod/ide-service-api/lib/ide.pb";
import {
BuildRegistryAuth,
BuildRegistryAuthSelective,
BuildRegistryAuthTotal,
BuildRequest,
BuildResponse,
BuildSource,
BuildSourceDockerfile,
BuildSourceReference,
BuildStatus,
ImageBuilderClientProvider,
ResolveBaseImageRequest,
} from "@gitpod/image-builder/lib";
import {
IDEImage,
PromisifiedWorkspaceManagerClient,
StartWorkspaceResponse,
StartWorkspaceSpec,
WorkspaceFeatureFlag,
} from "@gitpod/ws-manager/lib";
import { WorkspaceManagerClientProvider } from "@gitpod/ws-manager/lib/client-provider";
import {
AdmissionLevel,
EnvironmentVariable,
GitSpec,
PortSpec,
PortVisibility,
StartWorkspaceRequest,
WorkspaceMetadata,
WorkspaceType,
PortProtocol,
StopWorkspacePolicy,
StopWorkspaceRequest,
DescribeWorkspaceRequest,
} from "@gitpod/ws-manager/lib/core_pb";
import * as grpc from "@grpc/grpc-js";
import * as crypto from "crypto";
import { inject, injectable } from "inversify";
import * as path from "path";
import { v4 as uuidv4 } from "uuid";
import { HostContextProvider } from "../auth/host-context-provider";
import { ScopedResourceGuard } from "../auth/resource-access";
import { EntitlementService } from "../billing/entitlement-service";
import { Config } from "../config";
import { ExtendedIDESettings, IDEService } from "../ide-service";
import { OneTimeSecretServer } from "../one-time-secret-server";
import {
FailedInstanceStartReason,
increaseFailedInstanceStartCounter,
increaseImageBuildsCompletedTotal,
increaseImageBuildsStartedTotal,
increaseSuccessfulInstanceStartCounter,
} from "../prometheus-metrics";
import { RedisMutex } from "../redis/mutex";
import { AuthorizationService } from "../user/authorization-service";
import { TokenProvider } from "../user/token-provider";
import { UserAuthentication } from "../user/user-authentication";
import { ImageSourceProvider } from "./image-source-provider";
import { WorkspaceClassesConfig } from "./workspace-classes";
import { SYSTEM_USER, SYSTEM_USER_ID } from "../authorization/authorizer";
import { EnvVarService, ResolvedEnvVars } from "../user/env-var-service";
import { RedlockAbortSignal } from "redlock";
import { ConfigProvider } from "./config-provider";
import { isGrpcError } from "@gitpod/gitpod-protocol/lib/util/grpc";
import { getExperimentsClientForBackend } from "@gitpod/gitpod-protocol/lib/experiments/configcat-server";
import { ctxIsAborted, runWithRequestContext, runWithSubjectId } from "../util/request-context";
import { SubjectId } from "../auth/subject-id";
import { ApplicationError, ErrorCodes } from "@gitpod/gitpod-protocol/lib/messaging/error";
import { IDESettingsVersion } from "@gitpod/gitpod-protocol/lib/ide-protocol";
import { getFeatureFlagEnableExperimentalJBTB } from "../util/featureflags";
import { OrganizationService } from "../orgs/organization-service";
import { ProjectsService } from "../projects/projects-service";
import { ImageFileRevisionMissing } from "../repohost";
export interface StartWorkspaceOptions extends Omit<GitpodServer.StartWorkspaceOptions, "ideSettings"> {
excludeFeatureFlags?: NamedWorkspaceFeatureFlag[];
ideSettings?: ExtendedIDESettings;
}
const MAX_INSTANCE_START_RETRIES = 2;
const INSTANCE_START_RETRY_INTERVAL_SECONDS = 2;
/** [mins] */
const SCM_TOKEN_LIFETIME_MINS = 30;
export async function getWorkspaceClassForInstance(
ctx: TraceContext,
workspace: Pick<Workspace, "type">,
previousInstance: Pick<WorkspaceInstance, "workspaceClass"> | undefined,
project: Project | undefined,
workspaceClassOverride: string | undefined,
config: WorkspaceClassesConfig,
): Promise<string> {
const span = TraceContext.startSpan("getWorkspaceClassForInstance", ctx);
try {
let workspaceClass: string | undefined;
if (workspaceClassOverride) {
workspaceClass = workspaceClassOverride;
}
if (!workspaceClass && previousInstance) {
workspaceClass = previousInstance.workspaceClass;
}
if (!workspaceClass) {
switch (workspace.type) {
case "prebuild":
if (project) {
const prebuildSettings = Project.getPrebuildSettings(project);
workspaceClass = prebuildSettings.workspaceClass;
}
break;
case "regular":
workspaceClass = project?.settings?.workspaceClasses?.regular;
break;
}
}
if (!workspaceClass) {
workspaceClass = config.find((c) => !!c.isDefault)?.id;
}
return workspaceClass!;
} finally {
span.finish();
}
}
class StartInstanceError extends Error {
constructor(public readonly reason: FailedInstanceStartReason, public readonly cause: any) {
super("Starting workspace instance failed: " + cause.message);
}
}
export function isResourceExhaustedError(err: any): boolean {
return "code" in err && err.code === grpc.status.RESOURCE_EXHAUSTED;
}
export function isClusterMaintenanceError(err: any): boolean {
return (
"code" in err &&
err.code == grpc.status.FAILED_PRECONDITION &&
"details" in err &&
err.details == "under maintenance"
);
}
@injectable()
export class WorkspaceStarter {
static readonly STARTING_PHASES: WorkspaceInstancePhase[] = ["preparing", "building", "pending"];
constructor(
@inject(WorkspaceManagerClientProvider) private readonly clientProvider: WorkspaceManagerClientProvider,
@inject(Config) private readonly config: Config,
@inject(ConfigProvider) private readonly configProvider: ConfigProvider,
@inject(IDEService) private readonly ideService: IDEService,
@inject(TracedWorkspaceDB) private readonly workspaceDb: DBWithTracing<WorkspaceDB>,
@inject(TracedUserDB) private readonly userDB: DBWithTracing<UserDB>,
@inject(TokenProvider) private readonly tokenProvider: TokenProvider,
@inject(HostContextProvider) private readonly hostContextProvider: HostContextProvider,
@inject(AuthorizationService) private readonly authService: AuthorizationService,
@inject(ImageBuilderClientProvider) private readonly imagebuilderClientProvider: ImageBuilderClientProvider,
@inject(ImageSourceProvider) private readonly imageSourceProvider: ImageSourceProvider,
@inject(UserAuthentication) private readonly userService: UserAuthentication,
@inject(IAnalyticsWriter) private readonly analytics: IAnalyticsWriter,
@inject(OneTimeSecretServer) private readonly otsServer: OneTimeSecretServer,
@inject(ProjectDB) private readonly projectDB: ProjectDB,
@inject(TeamDB) private readonly orgDB: TeamDB,
@inject(BlockedRepositoryDB) private readonly blockedRepositoryDB: BlockedRepositoryDB,
@inject(EntitlementService) private readonly entitlementService: EntitlementService,
@inject(RedisMutex) private readonly redisMutex: RedisMutex,
@inject(RedisPublisher) private readonly publisher: RedisPublisher,
@inject(EnvVarService) private readonly envVarService: EnvVarService,
@inject(OrganizationService) private readonly orgService: OrganizationService,
@inject(ProjectsService) private readonly projectService: ProjectsService,
) {}
public async startWorkspace(
ctx: TraceContext,
workspace: Workspace,
user: User,
project: Project | undefined,
options: StartWorkspaceOptions,
): Promise<StartWorkspaceResult> {
const span = TraceContext.startSpan("WorkspaceStarter.startWorkspace", ctx);
span.setTag("workspaceId", workspace.id);
if (workspace.projectId && workspace.type === "regular") {
this.projectDB
.updateProjectUsage(workspace.projectId, {
lastWorkspaceStart: new Date().toISOString(),
})
.catch((err) => log.error("cannot update project usage", err));
}
let instanceId: string | undefined = undefined;
try {
await this.checkStartPermission(user, workspace, project);
await this.checkBlockedRepository(user, workspace);
// 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,
);
if (
WorkspaceImageSourceDocker.is(imageSource) &&
imageSource.dockerFileHash === ImageFileRevisionMissing
) {
const revision = (workspace.context as CommitContext).revision;
// we let the workspace create here and let it fail to build the image
imageSource.dockerFileHash = revision;
if (imageSource.dockerFileSource) {
imageSource.dockerFileSource.revision = revision;
}
}
log.debug("Found workspace without imageSource, generated one", { imageSource });
workspace.imageSource = imageSource;
await this.workspaceDb.trace({ span }).store(workspace);
}
if (options.forceDefaultImage) {
const res = await this.resolveBaseImage(
{ span },
user,
this.config.workspaceDefaults.workspaceImage,
workspace,
undefined,
options.region,
);
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);
let lastValidWorkspaceInstance: WorkspaceInstance | undefined;
// Sorted from latest to oldest
for (const i of pastInstances.sort((a, b) => (a.creationTime > b.creationTime ? -1 : 1))) {
// We're trying to figure out whether there was a successful backup or not, and if yes for which instance
if (!!i.status.conditions && !i.status.conditions.failed) {
lastValidWorkspaceInstance = i;
break;
}
}
let ideSettings = options.ideSettings;
// if no explicit ideSettings are passed, we use the one from the last workspace instance
if (lastValidWorkspaceInstance) {
const ideConfig = lastValidWorkspaceInstance.configuration?.ideConfig;
if (ideConfig?.ide) {
const enableExperimentalJBTB = await getFeatureFlagEnableExperimentalJBTB(user.id);
const preferToolbox = !enableExperimentalJBTB
? false
: ideSettings?.preferToolbox ??
user.additionalData?.ideSettings?.preferToolbox ??
ideConfig.preferToolbox ??
false;
ideSettings = {
...ideSettings,
defaultIde: ideConfig.ide,
useLatestVersion:
ideSettings?.useLatestVersion ??
user.additionalData?.ideSettings?.useLatestVersion ??
!!ideConfig.useLatest,
preferToolbox,
};
}
}
const fromBackup = !!lastValidWorkspaceInstance?.id;
const ideConfig = await this.resolveIDEConfiguration(ctx, workspace, user, ideSettings);
// create an instance
let instance = await this.newInstance(
ctx,
workspace,
lastValidWorkspaceInstance,
user,
project,
options.excludeFeatureFlags || [],
ideConfig,
fromBackup,
options.region,
options.workspaceClass,
);
// we run the actual creation of a new instance in a distributed lock, to make sure we always only start one instance per workspace.
await this.redisMutex.using(["workspace-start-" + workspace.id], 2000, async () => {
const runningInstance = await this.workspaceDb.trace({ span }).findRunningInstance(workspace.id);
if (runningInstance) {
throw new Error(`Workspace ${workspace.id} is already running`);
}
instance = await this.workspaceDb.trace({ span }).storeInstance(instance);
});
span.log({ newInstance: instance.id });
instanceId = instance.id;
// start the instance
await this.reconcileWorkspaceStart({ span }, instance.id, user, workspace);
return { instanceID: instance.id };
} catch (e) {
this.logAndTraceStartWorkspaceError({ span }, { userId: user.id, instanceId }, e);
throw e;
} finally {
span.finish();
}
}
public async reconcileWorkspaceStart(_ctx: TraceContext, instanceId: string, user: User, workspace: Workspace) {
const ctx = TraceContext.childContext("reconcileWorkspaceStart", _ctx);
const doReconcileWorkspaceStart = async (abortSignal: RedlockAbortSignal) => {
await runWithRequestContext(
{
requestKind: "workspace-start",
requestMethod: "reconcileWorkspaceStart",
signal: abortSignal,
subjectId: SubjectId.fromUserId(user.id),
},
async () => {
try {
// Fetch a fresh instance to check it's phase
const instance = await this.workspaceDb.trace({}).findInstanceById(instanceId);
if (!instance) {
ctx.span.finish();
throw new Error("cannot find workspace for instance");
}
if (!WorkspaceStarter.STARTING_PHASES.includes(instance.status.phase)) {
log.debug(
{ instanceId, workspaceId: instance.workspaceId, userId: user.id },
"can't start workspace instance in this phase",
{ phase: instance.status.phase },
);
return;
}
const envVars = await this.envVarService.resolveEnvVariables(
user.id,
workspace.organizationId,
workspace.projectId,
workspace.type,
workspace.context,
workspace.config,
);
await this.actuallyStartWorkspace(ctx, instance, workspace, user, envVars);
} catch (err) {
this.logAndTraceStartWorkspaceError(
ctx,
{ userId: user.id, workspaceId: workspace.id, instanceId },
err,
);
} finally {
ctx.span.finish();
}
},
);
};
// We try to acquire a mutex here, which we intend to hold until the workspace start request is sent to ws-manager.
// In case this container dies for whatever reason, the mutex is eventually released, and the instance can be picked up
// by another server process (cmp. WorkspaceStartController).
this.redisMutex
.using(
["workspace-instance-start-" + instanceId],
5000, // After 5s without extension the lock is released
doReconcileWorkspaceStart,
{ retryCount: 4, retryDelay: 500 }, // We wait at most 2s until we give up, and conclude that someone else is already starting this instance
)
.catch((err) => {
if (!RedisMutex.isLockedError(err)) {
log.warn({ instanceId }, "unexpected error during workspace instance start", err);
}
});
}
private async resolveIDEConfiguration(
ctx: TraceContext,
workspace: Workspace,
user: User,
userSelectedIdeSettings?: ExtendedIDESettings,
) {
const span = TraceContext.startSpan("resolveIDEConfiguration", ctx);
try {
const migrated = this.ideService.migrateSettings(user);
if (user.additionalData?.ideSettings && migrated) {
user.additionalData.ideSettings = migrated;
}
const resp = await this.ideService.resolveWorkspaceConfig(workspace, user, userSelectedIdeSettings);
if (!user.additionalData?.ideSettings && WithReferrerContext.is(workspace.context)) {
// 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 = IDESettingsVersion;
settings.defaultIde = workspace.context.referrerIde;
additionalData.ideSettings = settings;
user.additionalData = additionalData;
this.userDB
.trace(ctx)
.updateUserPartial(user)
.catch((e: Error) => {
log.error({ userId: user.id }, "cannot configure default desktop ide", e);
});
}
return resp;
} finally {
span.finish();
}
}
public async stopWorkspaceInstance(
ctx: TraceContext,
instanceId: string,
instanceRegion: string,
reason: string,
policy?: StopWorkspacePolicy,
): Promise<void> {
const span = TraceContext.startSpan("stopWorkspaceInstance", ctx);
span.setTag("stopWorkspaceReason", reason);
log.info({ instanceId }, "Stopping workspace instance", { reason });
const req = new StopWorkspaceRequest();
req.setId(instanceId);
req.setPolicy(policy || StopWorkspacePolicy.NORMALLY);
let client: PromisifiedWorkspaceManagerClient | undefined;
try {
client = await this.clientProvider.get(instanceRegion);
} catch (err) {
log.error({ instanceId }, "cannot stop workspace instance", err);
// we want to stop a workspace but the region doesn't exist. So we can assume it doesn't run anymore and there will never be updates coming to bridge.
// let's mark this workspace as stopped if it is not already stopped.
const workspace = await this.workspaceDb.trace(ctx).findByInstanceId(instanceId);
const instance = await this.workspaceDb.trace(ctx).findInstanceById(instanceId);
if (workspace && instance && instance?.status.phase !== "stopped") {
log.error(
{ instanceId },
"Workspace instance is still running although the region doesn't exist anymore. Marking workspace as stopped.",
);
const updated = await this.workspaceDb.trace(ctx).updateInstancePartial(instanceId, {
status: {
phase: "stopped",
message: "Manually marked stopped, because workspace region does not exist anymore.",
},
stoppedTime: new Date().toISOString(),
});
await this.userDB.trace({ span }).deleteGitpodTokensNamedLike(workspace.ownerId, `${instance.id}-%`);
await this.publisher.publishInstanceUpdate({
instanceID: updated.id,
ownerID: workspace.ownerId,
workspaceID: workspace.id,
});
}
return;
}
await client.stopWorkspace(ctx, req);
}
private async checkBlockedRepository(user: User, { contextURL, organizationId }: Workspace) {
const blockedRepository = await this.blockedRepositoryDB.findBlockedRepositoryByURL(contextURL);
if (!blockedRepository) return;
if (blockedRepository.blockUser) {
try {
await runWithSubjectId(SYSTEM_USER, async () =>
this.userService.blockUser(SYSTEM_USER_ID, user.id, true),
);
log.info({ userId: user.id }, "Blocked user.", { contextURL });
} catch (error) {
log.error({ userId: user.id }, "Failed to block user.", error, { contextURL });
}
}
if (blockedRepository.blockFreeUsage) {
const tier = await this.entitlementService.getBillingTier(user.id, organizationId);
if (tier === "free") {
throw new ApplicationError(
ErrorCodes.PRECONDITION_FAILED,
`${contextURL} requires a paid plan on Gitpod.`,
);
}
}
if (!blockedRepository.blockFreeUsage) {
throw new ApplicationError(ErrorCodes.PRECONDITION_FAILED, `${contextURL} is blocklisted on Gitpod.`);
}
}
private async checkStartPermission(user: User, workspace: Workspace, project?: Project) {
// explicit project
if (project) {
return;
}
const { organizationId, contextURL } = workspace;
const membership = await this.orgDB.findTeamMembership(user.id, organizationId);
if (!membership) {
return;
}
// check if user's role is restricted from starting arbitrary repositories
const organizationSettings = await this.orgService.getSettings(user.id, organizationId);
if (!organizationSettings?.roleRestrictions?.[membership.role]?.includes("start_arbitrary_repositories")) {
return;
}
// implicit project (existing on the same clone URL). We skip the permission check so that collaborators are not stuck
const projects = await this.projectService.findProjectsByCloneUrl(user.id, contextURL, organizationId, true);
if (projects.length === 0) {
throw new ApplicationError(
ErrorCodes.PRECONDITION_FAILED,
"Unable to start workspace: This repository has not been imported. Your role is restricted to using only imported repositories for workspace creation. Please contact your organization owner to import this repository or modify permissions.",
);
}
}
// Note: this function does not expect to be awaited for by its caller. This means that it takes care of error handling itself.
private async actuallyStartWorkspace(
ctx: TraceContext,
instance: WorkspaceInstance,
workspace: Workspace,
user: User,
envVars: ResolvedEnvVars,
): Promise<void> {
const span = TraceContext.startSpan("actuallyStartWorkspace", ctx);
const region = instance.configuration.regionPreference;
span.setTag("region_preference", region);
const logCtx: LogContext = {
instanceId: instance.id,
userId: user.id,
organizationId: workspace.organizationId,
workspaceId: workspace.id,
};
const forceRebuild = !!workspace.context.forceImageBuild;
log.info(logCtx, "Attempting to start workspace", {
forceRebuild: forceRebuild,
});
// choose a cluster and start the instance
let resp: StartWorkspaceResponse.AsObject | undefined = undefined;
let startRequest: StartWorkspaceRequest;
let retries = 0;
let failReason: FailedInstanceStartReason = "other";
try {
if (instance.status.phase === "pending") {
// due to the reconciliation loop we might have already started the workspace, especially in the "pending" phase
const workspaceAlreadyExists = await this.existsWithWsManager(ctx, instance);
if (workspaceAlreadyExists) {
log.debug(
{ instanceId: instance.id, workspaceId: instance.workspaceId },
"workspace already exists, not starting again",
{ phase: instance.status.phase },
);
return;
}
}
// build workspace image
const additionalAuth = await this.getAdditionalImageAuth(envVars);
instance = await this.buildWorkspaceImage(
{ span },
user,
workspace,
instance,
additionalAuth,
forceRebuild,
forceRebuild,
region,
);
// create spec
const spec = await this.createSpec({ span }, user, workspace, instance, envVars);
// create start workspace request
const metadata = await this.createMetadata(workspace);
startRequest = new StartWorkspaceRequest();
startRequest.setId(instance.id);
startRequest.setMetadata(metadata);
startRequest.setType(workspace.type === "prebuild" ? WorkspaceType.PREBUILD : WorkspaceType.REGULAR);
startRequest.setSpec(spec);
startRequest.setServicePrefix(workspace.id);
// try to start the workspace on a cluster
failReason = "startOnClusterFailed";
for (; retries < MAX_INSTANCE_START_RETRIES; retries++) {
if (ctxIsAborted()) {
return;
}
resp = await this.tryStartOnCluster({ span }, startRequest, user, workspace, instance, region);
if (resp) {
break;
}
await new Promise((resolve) => setTimeout(resolve, INSTANCE_START_RETRY_INTERVAL_SECONDS * 1000));
}
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);
const trackProperties: TrackMessage["properties"] = {
workspaceId: workspace.id,
instanceId: instance.id,
projectId: workspace.projectId,
contextURL: workspace.contextURL,
type: workspace.type,
class: instance.workspaceClass,
ideConfig: instance.configuration?.ideConfig,
usesPrebuild: startRequest.getSpec()?.getInitializer()?.hasPrebuild(),
};
if (workspace.projectId && trackProperties.usesPrebuild && workspace.type === "regular") {
const project = await this.projectDB.findProjectById(workspace.projectId);
trackProperties.prebuildTriggerStrategy =
project?.settings?.prebuilds?.triggerStrategy ?? "webhook-based";
}
// update analytics
this.analytics.track({
userId: user.id,
event: "workspace_started",
properties: trackProperties,
timestamp: new Date(instance.creationTime),
});
} catch (err) {
if (isGrpcError(err) && err.code === grpc.status.ALREADY_EXISTS) {
// This might happen because of timing: When we did the "workspaceAlreadyExists" check above, the DB state was not updated yet.
// But when calling ws-manager to start the workspace, it was already present.
//
// By returning we skip the current cycle and wait for the next run of the workspace-start-controller.
// This gives ws-manager(-bridge) some time to emit(/digest) updates.
log.info(logCtx, "workspace already exists, waiting for ws-manager to push new state", err);
return;
}
if (isGrpcError(err) && err.code === grpc.status.UNAVAILABLE) {
// fall-through: we don't want to fail but retry/wait for future updates to resolve this
log.warn(logCtx, "cannot start workspace instance due to temporary error", err);
return;
}
if (ScmStartError.isScmStartError(err)) {
// user does not have access to SCM
await this.failInstanceStart({ span }, err, workspace, instance);
err = new StartInstanceError("scmAccessFailed", err);
}
if (!(err instanceof StartInstanceError)) {
// Serves as a catch-all for those cases that we have failed to map before
if (isResourceExhaustedError(err)) {
failReason = "resourceExhausted";
}
if (isClusterMaintenanceError(err)) {
failReason = "workspaceClusterMaintenance";
err = new Error(
"We're in the middle of an update. We'll be back to normal soon. Please try again in a few minutes.",
);
}
await this.failInstanceStart({ span }, err, workspace, instance);
err = new StartInstanceError(failReason, err);
}
this.logAndTraceStartWorkspaceError({ span }, logCtx, err);
} finally {
if (ctxIsAborted()) {
ctx.span?.setTag("aborted", true);
}
span.finish();
}
}
private 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);
}
private async createMetadata(workspace: Workspace): Promise<WorkspaceMetadata> {
const metadata = new WorkspaceMetadata();
metadata.setOwner(workspace.ownerId);
metadata.setMetaId(workspace.id);
if (workspace.projectId) {
metadata.setProject(workspace.projectId);
metadata.setTeam(workspace.organizationId);
}
return metadata;
}
private async tryStartOnCluster(
ctx: TraceContext,
startRequest: StartWorkspaceRequest,
user: User,
workspace: Workspace,
instance: WorkspaceInstance,
region?: WorkspaceRegion,
): Promise<StartWorkspaceResponse.AsObject | undefined> {
const constrainOnWorkspaceClassSupport = await isWorkspaceClassDiscoveryEnabled(user);
let lastInstallation = "";
const clusters = await this.clientProvider.getStartClusterSets(
user,
workspace,
instance,
region,
constrainOnWorkspaceClassSupport,
);
for await (const cluster of clusters) {
if (ctxIsAborted()) {
return;
}
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.publisher.publishInstanceUpdate({
instanceID: instance.id,
ownerID: workspace.ownerId,
workspaceID: workspace.id,
});
} 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 (isResourceExhaustedError(err)) {
throw err;
} else if (isClusterMaintenanceError(err)) {
throw err;
} else if (isGrpcError(err) && err.code === grpc.status.ALREADY_EXISTS) {
throw err;
} else 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;
}
private async getAdditionalImageAuth(envVars: ResolvedEnvVars): Promise<Map<string, string>> {
const res = new Map<string, string>();
const imageAuth = envVars.workspace.find((e) => e.name === EnvVar.GITPOD_IMAGE_AUTH_ENV_VAR_NAME);
if (!imageAuth) {
return res;
}
(imageAuth.value || "")
.split(",")
.map((e) => e.trim().split(":"))
.filter((e) => e.length == 2)
.forEach((e) => res.set(e[0], e[1]));
return res;
}
/**
* 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 prebuilds).
*/
private async failInstanceStart(ctx: TraceContext, err: any, workspace: Workspace, instance: WorkspaceInstance) {
if (ctxIsAborted()) {
return;
}
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";
const now = new Date().toISOString();
instance.stoppingTime = now;
instance.stoppedTime = now;
instance.status.conditions.failed = err.toString();
instance.status.message = `Workspace cannot be started: ${err}`;
await this.workspaceDb.trace({ span }).storeInstance(instance);
await this.publisher.publishInstanceUpdate({
instanceID: instance.id,
ownerID: workspace.ownerId,
workspaceID: workspace.id,
});
// If we just attempted to start a workspace for a prebuild - and that failed, we have to fail the prebuild itself.
await this.failPrebuildWorkspace({ span }, err, workspace);
} 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();
}
}
private async failPrebuildWorkspace(ctx: TraceContext, err: any, workspace: Workspace) {
const span = TraceContext.startSpan("failInstanceStart", ctx);
try {
if (workspace.type === "prebuild") {
const prebuild = await this.workspaceDb.trace({ span }).findPrebuildByWorkspaceID(workspace.id);
if (prebuild && prebuild.state !== "failed" && prebuild.projectId) {
prebuild.state = "failed";
prebuild.error = err.toString();
await this.workspaceDb.trace({ span }).storePrebuiltWorkspace(prebuild);
await this.publisher.publishHeadlessUpdate({
type: HeadlessWorkspaceEventType.Failed,
workspaceID: workspace.id,
});
await this.publisher.publishPrebuildUpdate({
status: "failed",
prebuildID: prebuild.id,
projectID: prebuild.projectId,
workspaceID: workspace.id,
organizationID: workspace.organizationId,
});
}
}
} catch (err) {
TraceContext.setError({ span }, err);
throw err;
} finally {
span.finish();
}
}
/**
* Creates a new instance for a given workspace and its owner
*
* @param workspace the workspace to create an instance for
*/
private async newInstance(
ctx: TraceContext,
workspace: Workspace,
previousInstance: WorkspaceInstance | undefined,
user: User,
project: Project | undefined,
excludeFeatureFlags: NamedWorkspaceFeatureFlag[],
ideConfig: IdeServiceApi.ResolveWorkspaceConfigResponse,
fromBackup: boolean,
regionPreference: WorkspaceRegion | undefined,
workspaceClassOverride?: string,
): Promise<WorkspaceInstance> {
const span = TraceContext.startSpan("newInstance", ctx);
try {
let ideTasks: TaskConfig[] = [];
try {
if (ideConfig.tasks && ideConfig.tasks.trim() !== "") {
ideTasks = JSON.parse(ideConfig.tasks);
}
} catch (e) {
log.info({ workspaceId: workspace.id }, "failed parse tasks from ide config:", e, {
tasks: ideConfig.tasks,
});
}
const configuration: WorkspaceInstanceConfiguration = {
ideImage: ideConfig.webImage,
ideImageLayers: ideConfig.ideImageLayers,
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,
},
ideSetup: {
envvars: ideConfig.envvars,
tasks: ideTasks,
},
regionPreference,
fromBackup,
};
if (ideConfig.ideSettings && ideConfig.ideSettings.trim() !== "") {
try {
const enableExperimentalJBTB = await getFeatureFlagEnableExperimentalJBTB(user.id);
const ideSettings: IDESettings = JSON.parse(ideConfig.ideSettings);
configuration.ideConfig!.ide = ideSettings.defaultIde;
configuration.ideConfig!.useLatest = !!ideSettings.useLatestVersion;
configuration.ideConfig!.preferToolbox = !enableExperimentalJBTB
? false
: ideSettings.preferToolbox ?? false;
} catch (error) {
log.error({ userId: user.id, workspaceId: workspace.id }, "cannot parse ideSettings", error);
}
}
const billingTier = await this.entitlementService.getBillingTier(user.id, workspace.organizationId);
let featureFlags: NamedWorkspaceFeatureFlag[] = workspace.config._featureFlags || [];
featureFlags = featureFlags.concat(this.config.workspaceDefaults.defaultFeatureFlags);
if (user.featureFlags && user.featureFlags.permanentWSFeatureFlags) {
// Workspace-persisted feature flags are inherited from and controlled by workspace.config._featureFlags
// Make sure we do not overide them, here.
const nonWorkspacePersistentFeatureFlags = user.featureFlags.permanentWSFeatureFlags.filter(
(ff) => !NamedWorkspaceFeatureFlag.isWorkspacePersisted(ff),
);
featureFlags = featureFlags.concat(featureFlags, nonWorkspacePersistentFeatureFlags);
}