-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathcloudConsole.ts
More file actions
705 lines (630 loc) · 32.2 KB
/
cloudConsole.ts
File metadata and controls
705 lines (630 loc) · 32.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TenantIdDescription } from '@azure/arm-resources-subscriptions';
import { AzureSubscriptionProvider, AzureTenant, getConfiguredAzureEnv } from '@microsoft/vscode-azext-azureauth';
import { IActionContext, IAzureQuickPickItem, IParsedError, callWithTelemetryAndErrorHandlingSync, nonNullProp, parseError } from '@microsoft/vscode-azext-utils';
import * as cp from 'child_process';
import { default as FormData } from 'form-data';
import { ReadStream } from 'fs';
import { ClientRequest } from 'http';
import { Socket } from 'net';
import * as path from 'path';
import * as semver from 'semver';
import { UrlWithStringQuery, parse } from 'url';
import { CancellationToken, EventEmitter, MessageItem, Terminal, TerminalOptions, TerminalProfile, ThemeIcon, Uri, commands, env, window, workspace } from 'vscode';
import { ext } from '../extensionVariables';
import { localize } from '../utils/localize';
import { fetchWithLogging } from '../utils/logging/nodeFetch/nodeFetch';
import { CloudShell, CloudShellInternal, CloudShellStatus, UploadOptions } from './CloudShellInternal';
import { Deferred, delay, logAttemptingToReachUrlMessage } from './cloudConsoleUtils';
import { readJSON } from './cloudShellChildProcess/readJSON';
import { Queue, Server, createServer } from './ipc';
function ensureEndingSlash(value: string): string {
return value.endsWith('/') ? value : `${value}/`;
}
function getArmEndpoint(): string {
return ensureEndingSlash(getConfiguredAzureEnv().resourceManagerEndpointUrl);
}
interface OS {
id: 'linux' | 'windows';
shellName: string;
otherOS: OS;
}
export type OSName = 'Linux' | 'Windows';
type OSes = { Linux: OS, Windows: OS };
export const OSes: OSes = {
Linux: {
id: 'linux',
shellName: localize('bash', "Bash"),
get otherOS(): OS { return OSes.Windows; },
},
Windows: {
id: 'windows',
shellName: localize('powershell', "PowerShell"),
get otherOS(): OS { return OSes.Linux; },
}
};
async function waitForConnection(this: CloudShell): Promise<boolean> {
const handleStatus = () => {
switch (this.status) {
case 'Connecting':
return new Promise<boolean>(resolve => {
const subs = this.onStatusChanged(() => {
subs.dispose();
resolve(handleStatus());
});
});
case 'Connected':
return true;
case 'Disconnected':
return false;
default:
throw new Error(`Unexpected status '${this.status}'`);
}
};
return handleStatus();
}
function getUploadFile(tokens: Promise<AccessTokens>, uris: Promise<ConsoleUris>): (this: CloudShell, filename: string, stream: ReadStream, options?: UploadOptions) => Promise<void> {
return async function (this: CloudShell, filename: string, stream: ReadStream, options: UploadOptions = {}) {
if (options.progress) {
options.progress.report({ message: localize('connectingForUpload', "Connecting to upload '{0}'...", filename) });
}
const accessTokens: AccessTokens = await tokens;
const { terminalUri } = await uris;
if (options.token && options.token.isCancellationRequested) {
throw 'canceled';
}
return new Promise<void>((resolve, reject) => {
const form = new FormData();
form.append('uploading-file', stream, {
filename,
knownLength: options.contentLength
});
const uploadUri: string = `${terminalUri}/upload`;
logAttemptingToReachUrlMessage(uploadUri);
const uri: UrlWithStringQuery = parse(uploadUri);
const req: ClientRequest = form.submit(
{
// eslint-disable-next-line @typescript-eslint/no-explicit-any
protocol: <any>uri.protocol,
hostname: uri.hostname,
port: uri.port,
path: uri.path,
headers: {
'Authorization': `Bearer ${accessTokens.resource}`
},
},
(err, res) => {
if (err) {
reject(err);
} if (res && res.statusCode && (res.statusCode < 200 || res.statusCode > 299)) {
reject(`${res.statusMessage} (${res.statusCode})`);
} else {
resolve();
}
if (res) {
res.resume(); // Consume response.
}
}
);
if (options.token) {
options.token.onCancellationRequested(() => {
reject('canceled');
req.abort();
});
}
if (options.progress) {
req.on('socket', (socket: Socket) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
options.progress!.report({
message: localize('uploading', "Uploading '{0}'...", filename),
increment: 0
});
let previous: number = 0;
socket.on('drain', () => {
const total: number = req.getHeader('Content-Length') as number;
if (total) {
const worked: number = Math.min(Math.round(100 * socket.bytesWritten / total), 100);
const increment: number = worked - previous;
if (increment) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
options.progress!.report({
message: localize('uploading', "Uploading '{0}'...", filename),
increment
});
}
previous = worked;
}
});
});
}
});
};
}
export const shells: CloudShellInternal[] = [];
export function createCloudConsole(subscriptionProvider: AzureSubscriptionProvider, osName: OSName, terminalProfileToken?: CancellationToken): CloudShellInternal {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return (callWithTelemetryAndErrorHandlingSync('azureResourceGroups.createCloudConsole', (context: IActionContext) => {
const os: OS = OSes[osName];
context.telemetry.properties.cloudShellType = os.shellName;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let liveServerQueue: Queue<any> | undefined;
const event: EventEmitter<CloudShellStatus> = new EventEmitter<CloudShellStatus>();
let deferredTerminal: Deferred<Terminal>;
let deferredTerminalProfile: Deferred<TerminalProfile>;
// let deferredSession: Deferred<AzureSession>;
let deferredTokens: Deferred<AccessTokens>;
const tokensPromise: Promise<AccessTokens> = new Promise<AccessTokens>((resolve, reject) => deferredTokens = { resolve, reject });
let deferredUris: Deferred<ConsoleUris>;
const urisPromise: Promise<ConsoleUris> = new Promise<ConsoleUris>((resolve, reject) => deferredUris = { resolve, reject });
let deferredInitialSize: Deferred<Size>;
const initialSizePromise: Promise<Size> = new Promise<Size>((resolve, reject) => deferredInitialSize = { resolve, reject });
const state: CloudShellInternal = {
status: 'Connecting',
onStatusChanged: event.event,
waitForConnection,
terminal: new Promise<Terminal>((resolve, reject) => deferredTerminal = { resolve, reject }),
terminalProfile: new Promise<TerminalProfile>((resolve, reject) => deferredTerminalProfile = { resolve, reject }),
// session: new Promise<AzureSession>((resolve, reject) => deferredSession = { resolve, reject }),
uploadFile: getUploadFile(tokensPromise, urisPromise)
};
// eslint-disable-next-line @typescript-eslint/no-empty-function
state.terminal?.catch(() => { }); // ignore
// state.session.catch(() => { }); // ignore
shells.push(state);
function updateStatus(status: CloudShellStatus) {
state.status = status;
event.fire(state.status);
if (status === 'Disconnected') {
deferredTerminal.reject(status);
deferredTerminalProfile.reject(status);
// deferredSession.reject(status);
deferredTokens.reject(status);
deferredUris.reject(status);
shells.splice(shells.indexOf(state), 1);
void commands.executeCommand('setContext', 'azureResourcesOpenCloudConsoleCount', `${shells.length}`);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(async function (): Promise<any> {
if (!workspace.isTrusted) {
updateStatus('Disconnected');
return requiresWorkspaceTrust(context);
}
void commands.executeCommand('setContext', 'azureResourcesOpenCloudConsoleCount', `${shells.length}`);
const isWindows: boolean = process.platform === 'win32';
if (isWindows) {
// See below
try {
const { stdout } = await exec('node.exe --version');
const version: string | boolean = stdout[0] === 'v' && stdout.substr(1).trim();
if (version && semver.valid(version) && !semver.gte(version, '6.0.0')) {
updateStatus('Disconnected');
return requiresNode(context);
}
} catch {
updateStatus('Disconnected');
return requiresNode(context);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const serverQueue: Queue<any> = new Queue<any>();
const server: Server = await createServer('vscode-cloud-console', async (req, res) => {
let dequeue: boolean = false;
for (const message of await readJSON(req)) {
if (message.type === 'poll') {
dequeue = true;
} else if (message.type === 'log') {
if (Array.isArray(message.args)) {
ext.outputChannel.appendLog((<string[]>message.args).join(' '));
}
} else if (message.type === 'size') {
deferredInitialSize.resolve(message.size as Size);
} else if (message.type === 'status') {
updateStatus(message.status as CloudShellStatus);
}
}
let response = [];
if (dequeue) {
try {
response = await serverQueue.dequeue(60000);
} catch {
// ignore timeout
}
}
res.write(JSON.stringify(response));
res.end();
});
serverQueue.push({ type: 'log', args: [localize('loggingIn', "Signing in...")] });
try {
if (await subscriptionProvider.signIn()) {
serverQueue.push({ type: 'log', args: [localize('loggingIn', "Signed in successful.")] });
}
} catch (e) {
serverQueue.push({ type: 'log', args: [localize('loggingIn', parseError(e).message)] });
// We used to delay for a second then exit here, but then the user can't read or copy the error message
// await delay(1000);
// serverQueue.push({ type: 'exit' });
updateStatus('Disconnected');
return;
}
const env: TerminalOptions['env'] = {
// Child process uses this ipc handle to communicate with the extension host
// eslint-disable-next-line @typescript-eslint/naming-convention
CLOUD_CONSOLE_IPC: server.ipcHandlePath
};
if (!isWindows) {
// Needed to fork a child process as a node.js process from within the application
env['ELECTRON_RUN_AS_NODE'] = '1';
env['ELECTRON_NO_ASAR'] = '1';
}
// open terminal
let cloudConsoleLauncherPath: string = path.join(ext.context.asAbsolutePath('dist'), 'cloudConsoleLauncher');
if (isWindows) {
cloudConsoleLauncherPath = cloudConsoleLauncherPath.replace(/\\/g, '\\\\');
}
const terminalOptions: TerminalOptions = {
name: localize('azureCloudShell', 'Azure Cloud Shell ({0})', os.shellName),
iconPath: new ThemeIcon('azure'),
shellPath: isWindows ? 'node.exe' : process.execPath,
shellArgs: ['-e', `require('${cloudConsoleLauncherPath}').main()`],
env,
isTransient: true
};
const cleanupCloudShell = () => {
liveServerQueue = undefined;
server.dispose();
updateStatus('Disconnected');
};
// Open the appropriate type of VS Code terminal depending on the entry point
if (terminalProfileToken) {
// Entry point: Terminal profile provider
const terminalProfileCloseSubscription = terminalProfileToken.onCancellationRequested(() => {
terminalProfileCloseSubscription.dispose();
cleanupCloudShell();
});
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
deferredTerminalProfile!.resolve(new TerminalProfile(terminalOptions));
} else {
// Entry point: Extension API
const terminal: Terminal = window.createTerminal(terminalOptions);
const terminalCloseSubscription = window.onDidCloseTerminal(t => {
if (t === terminal) {
terminalCloseSubscription.dispose();
cleanupCloudShell();
}
});
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
deferredTerminal!.resolve(terminal);
}
liveServerQueue = serverQueue;
const tenants: AzureTenant[] = [];
for (const account of await subscriptionProvider.getAccounts({ filter: false })) {
tenants.push(...await subscriptionProvider.getTenantsForAccount(account, { filter: false }));
}
let selectedTenant: TenantIdDescription | undefined = undefined;
const subscriptions = await subscriptionProvider.getAvailableSubscriptions({ filter: false });
if (tenants.length <= 1) {
serverQueue.push({ type: 'log', args: [localize('foundOneTenant', `Found 1 tenant.`)] });
// if they have only one tenant, use it
selectedTenant = tenants[0];
} else {
// If the user has multiple tenants, then we check which tenants have subscriptions.
// This also checks if this tenant is authenticated.
// If a tenant is not authenticated, users will have to use the "Sign in to Directory..." command before launching cloud shell.
const tenantsIdsWithSubs = new Set<string>();
subscriptions.forEach((sub) => {
tenantsIdsWithSubs.add(sub.tenantId);
});
const tenantsWithSubs = tenants.filter(tenant => tenantsIdsWithSubs.has(nonNullProp(tenant, 'tenantId')));
serverQueue.push({ type: 'log', args: [localize('foundTenants', `Found ${tenantsWithSubs.length} authenticated tenant${tenants.length > 1 ? 's' : ''}. Please use the "Sign in to Tenant (Directory)..." command to sign in to additional tenants.`)] });
if (tenantsWithSubs.length <= 1) {
// If they have only one tenant with subscriptions, use it. If there's no tenant with subscriptions, use the first tenant.
selectedTenant = tenantsWithSubs[0] ?? tenants[0];
} else {
const duplicates = tenantsWithSubs.filter((tenant, index, self) => self.findIndex(t => t.tenantId === tenant.tenantId) !== index);
// Multipe tenants with subscriptions, user must pick a tenant
serverQueue.push({ type: 'log', args: [localize('selectingTenant', `Selecting tenant...`)] });
const picks = tenantsWithSubs.map(tenant => {
const defaultDomainName: string | undefined = tenant.defaultDomain;
const isDuplicate = duplicates.some(dup => dup.tenantId === tenant.tenantId);
return <IAzureQuickPickItem<TenantIdDescription>>{
label: isDuplicate ? `${tenant.displayName} (${tenant.account.label})` : tenant.displayName,
description: defaultDomainName,
data: tenant,
};
}).sort((a, b) => a.label.localeCompare(b.label));
const pick = await window.showQuickPick<IAzureQuickPickItem<TenantIdDescription>>(picks, {
placeHolder: localize('selectDirectoryPlaceholder', "Select tenant"),
ignoreFocusOut: true // The terminal opens concurrently and can steal focus (https://github.com/microsoft/vscode-azure-account/issues/77).
});
if (!pick) {
context.telemetry.properties.outcome = 'noTenantPicked';
serverQueue.push({ type: 'exit' });
updateStatus('Disconnected');
return;
}
selectedTenant = pick.data;
}
}
serverQueue.push({ type: 'log', args: [localize('usingTenant', `Using "${selectedTenant.displayName}" tenant.`)] });
// get all subscriptions for the selected tenant
const subscriptionsInSelectedTenant = subscriptions.filter(sub => sub.tenantId === selectedTenant?.tenantId);
if (subscriptionsInSelectedTenant.length === 0) {
// cloud shell requires at least one subscription to work
serverQueue.push({ type: 'log', args: [localize('noSubscriptions', `Error: No subscriptions found for the selected account and tenant.`)] });
updateStatus('Disconnected');
return;
}
// get session from the first subscription for the selected tenant
const session = await subscriptionsInSelectedTenant[0].authentication.getSession();
if (!session) {
serverQueue.push({ type: 'log', args: [localize('failedToGetSession', `Failed to get session.`)] });
updateStatus('Disconnected');
return;
}
const result = await findUserSettings(session.accessToken);
if (!result) {
serverQueue.push({ type: 'log', args: [localize('setupNeeded', "Setup needed.")] });
await requiresSetUp(context);
serverQueue.push({ type: 'exit' });
updateStatus('Disconnected');
return;
}
// provision
let consoleUri: string;
const provisionTask: () => Promise<void> = async () => {
consoleUri = await provisionConsole(session.accessToken, result, OSes.Linux.id);
context.telemetry.properties.outcome = 'provisioned';
};
try {
serverQueue.push({ type: 'log', args: [localize('requestingCloudConsole', "Requesting a Cloud Shell...")] });
await provisionTask();
} catch (err) {
if (parseError(err).message === Errors.DeploymentOsTypeConflict) {
const reset = await deploymentConflict(context, os);
if (reset) {
await resetConsole(session.accessToken, getArmEndpoint());
return provisionTask();
} else {
serverQueue.push({ type: 'exit' });
updateStatus('Disconnected');
return;
}
} else {
throw err;
}
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
deferredTokens!.resolve({ resource: session.accessToken });
// Connect to terminal
const connecting: string = localize('connectingTerminal', "Connecting terminal...");
serverQueue.push({ type: 'log', args: [connecting] });
const progressTask: (i: number) => void = (i: number) => {
serverQueue.push({ type: 'log', args: [`\x1b[A${connecting}${'.'.repeat(i)}`] });
};
const initialSize: Size = await initialSizePromise;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const consoleUris: ConsoleUris = await connectTerminal(session.accessToken, consoleUri!, /* TODO: Separate Shell from OS */ osName === 'Linux' ? 'bash' : 'pwsh', initialSize, progressTask);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
deferredUris!.resolve(consoleUris);
// Connect to WebSocket
serverQueue.push({
type: 'connect',
accessToken: session.accessToken,
consoleUris
});
})().catch(err => {
const parsedError: IParsedError = parseError(err);
ext.outputChannel.appendLog(parsedError.message);
if (parsedError.stack) {
ext.outputChannel.appendLog(parsedError.stack);
}
updateStatus('Disconnected');
context.telemetry.properties.outcome = 'error';
context.telemetry.properties.message = parsedError.message;
if (liveServerQueue) {
liveServerQueue.push({ type: 'log', args: [localize('error', "Error: {0}", parsedError.message)] });
}
});
return state;
}))!;
}
async function findUserSettings(accessToken: string): Promise<UserSettings | undefined> {
const userSettings: UserSettings | undefined = await getUserSettings(accessToken);
// Valid settings will have either a storage profile (mounted) or a session type of 'Ephemeral'.
if (userSettings && (userSettings.storageProfile || userSettings.sessionType === 'Ephemeral')) {
return userSettings;
}
return undefined;
}
async function requiresSetUp(context: IActionContext) {
context.telemetry.properties.outcome = 'requiresSetUp';
const open: MessageItem = { title: localize('open', "Open") };
const message: string = localize('setUpInWeb', "First launch of Cloud Shell in a directory requires setup in the web application (https://shell.azure.com).");
const response: MessageItem | undefined = await window.showInformationMessage(message, open);
if (response === open) {
context.telemetry.properties.outcome = 'requiresSetUpOpen';
void env.openExternal(Uri.parse('https://shell.azure.com'));
} else {
context.telemetry.properties.outcome = 'requiresSetUpCancel';
}
}
async function requiresNode(context: IActionContext) {
context.telemetry.properties.outcome = 'requiresNode';
const open: MessageItem = { title: localize('open', "Open") };
const message: string = localize('requiresNode', "Opening a Cloud Shell currently requires Node.js 6 or later to be installed (https://nodejs.org).");
const response: MessageItem | undefined = await window.showInformationMessage(message, open);
if (response === open) {
context.telemetry.properties.outcome = 'requiresNodeOpen';
void env.openExternal(Uri.parse('https://nodejs.org'));
} else {
context.telemetry.properties.outcome = 'requiresNodeCancel';
}
}
async function requiresWorkspaceTrust(context: IActionContext) {
context.telemetry.properties.outcome = 'requiresWorkspaceTrust';
const ok: MessageItem = { title: localize('ok', "OK") };
const message: string = localize('cloudShellRequiresTrustedWorkspace', 'Opening a Cloud Shell only works in a trusted workspace.');
return await window.showInformationMessage(message, ok) === ok;
}
async function deploymentConflict(context: IActionContext, os: OS) {
context.telemetry.properties.outcome = 'deploymentConflict';
const ok: MessageItem = { title: localize('ok', "OK") };
const message: string = localize('deploymentConflict', "Starting a {0} session will terminate all active {1} sessions. Any running processes in active {1} sessions will be terminated.", os.shellName, os.otherOS.shellName);
const response: MessageItem | undefined = await window.showWarningMessage(message, ok);
const reset: boolean = response === ok;
context.telemetry.properties.outcome = reset ? 'deploymentConflictReset' : 'deploymentConflictCancel';
return reset;
}
export interface ExecResult {
error: Error | null;
stdout: string;
stderr: string;
}
async function exec(command: string): Promise<ExecResult> {
return new Promise<ExecResult>((resolve, reject) => {
cp.exec(command, (error, stdout, stderr) => {
(error || stderr ? reject : resolve)({ error, stdout, stderr });
});
});
}
const consoleApiVersion = '2023-02-01-preview';
export enum Errors {
DeploymentOsTypeConflict = 'DeploymentOsTypeConflict'
}
function getConsoleUri(armEndpoint: string) {
return `${armEndpoint}/providers/Microsoft.Portal/consoles/default?api-version=${consoleApiVersion}`;
}
export interface UserSettings {
preferredLocation: string;
preferredOsType: string; // The last OS chosen in the portal.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
storageProfile: any;
sessionType: 'Ephemeral' | 'Mounted';
}
export interface AccessTokens {
resource: string;
// graph: string;
keyVault?: string;
}
export interface ConsoleUris {
consoleUri: string;
terminalUri: string;
socketUri: string;
}
export interface Size {
cols: number;
rows: number;
}
export async function getUserSettings(accessToken: string): Promise<UserSettings | undefined> {
const targetUri = `${getArmEndpoint()}/providers/Microsoft.Portal/userSettings/cloudconsole?api-version=${consoleApiVersion}`;
const response = await fetch(targetUri, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
});
if (response.status < 200 || response.status > 299) {
return;
}
return (await response.json() as { properties: UserSettings }).properties;
}
export async function provisionConsole(accessToken: string, userSettings: UserSettings, osType: string): Promise<string> {
let response = await createTerminal(accessToken, userSettings, osType, true);
for (let i = 0; i < 10; i++, response = await createTerminal(accessToken, userSettings, osType, false)) {
if (response.status < 200 || response.status > 299) {
const body = await response.json() as { error?: { message?: string, code?: string }, id: string, socketUri: string };
if (response.status === 409 && response.body && body.error && body.error.code === Errors.DeploymentOsTypeConflict) {
throw new Error(Errors.DeploymentOsTypeConflict);
} else if (body && body.error && body.error.message) {
throw new Error(`${body.error.message} (${response.status})`);
} else {
throw new Error(`${response.status} ${response.headers} ${body}`);
}
}
const consoleResource = await response.json() as { properties: { provisioningState: string, uri: string } };
if (consoleResource.properties.provisioningState === 'Succeeded') {
return consoleResource.properties.uri;
} else if (consoleResource.properties.provisioningState === 'Failed') {
break;
}
}
throw new Error(`Sorry, your Cloud Shell failed to provision. Please retry later. Request correlation id: ${response.headers.get('x-ms-routing-request-id')}`);
}
async function createTerminal(accessToken: string, userSettings: UserSettings, osType: string, initial: boolean): Promise<Response> {
return fetchWithLogging(getConsoleUri(getArmEndpoint()), {
method: initial ? 'PUT' : 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`,
'x-ms-console-preferred-location': userSettings.preferredLocation
},
body: JSON.stringify(initial ? {
properties: {
osType
}
} : {}),
});
}
export async function resetConsole(accessToken: string, armEndpoint: string) {
const response = await fetchWithLogging(getConsoleUri(armEndpoint), {
method: 'DELETE',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
});
const body = await response.json() as { error?: { message?: string } };
if (response.status < 200 || response.status > 299) {
if (body && body.error && body.error.message) {
throw new Error(`${body.error.message} (${response.status})`);
} else {
throw new Error(`${response.status} ${response.headers} ${body}`);
}
}
}
export async function connectTerminal(accessToken: string, consoleUri: string, shellType: string, initialSize: Size, progress: (i: number) => void): Promise<ConsoleUris> {
for (let i = 0; i < 10; i++) {
const response = await initializeTerminal(accessToken, consoleUri, shellType, initialSize);
const body = await response.json() as { error?: { message?: string }, id: string, socketUri: string };
if (response.status < 200 || response.status > 299) {
if (response.status !== 503 && response.status !== 504 && body && body.error) {
if (body && body.error && body.error.message) {
throw new Error(`${body.error.message} (${response.status})`);
} else {
throw new Error(`${response.status} ${response.headers} ${await response.text()}`);
}
}
await delay(1000 * (i + 1));
progress(i + 1);
continue;
}
return {
consoleUri,
terminalUri: `${consoleUri}/terminals/${body.id}`,
socketUri: body.socketUri
};
}
throw new Error('Failed to connect to the terminal.');
}
async function initializeTerminal(accessToken: string, consoleUri: string, shellType: string, initialSize: Size): Promise<Response> {
const consoleUrl = new URL(consoleUri);
const response = fetchWithLogging(consoleUri + '/terminals?cols=' + initialSize.cols + '&rows=' + initialSize.rows + '&shell=' + shellType, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${accessToken}`,
'Referer': consoleUrl.protocol + "//" + consoleUrl.hostname + '/$hc' + consoleUrl.pathname + '/terminals',
},
body: JSON.stringify({}),
});
return response;
}