-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathcli-repl.ts
1440 lines (1325 loc) · 47.1 KB
/
cli-repl.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
import {
MongoshInternalError,
MongoshRuntimeError,
MongoshWarning,
} from '@mongosh/errors';
import { redactURICredentials } from '@mongosh/history';
import i18n from '@mongosh/i18n';
import type { AutoEncryptionOptions } from '@mongosh/service-provider-core';
import { bson } from '@mongosh/service-provider-core';
import { NodeDriverServiceProvider } from '@mongosh/service-provider-node-driver';
import type { CliOptions, DevtoolsConnectOptions } from '@mongosh/arg-parser';
import { SnippetManager } from '@mongosh/snippet-manager';
import { Editor } from '@mongosh/editor';
import { redactSensitiveData } from '@mongosh/history';
import type { Analytics as SegmentAnalytics } from '@segment/analytics-node';
import askpassword from 'askpassword';
import { EventEmitter, once } from 'events';
import yaml from 'js-yaml';
import ConnectionString from 'mongodb-connection-string-url';
import semver from 'semver';
import type { Readable, Writable } from 'stream';
import { buildInfo, getGlibcVersion } from './build-info';
import type { StyleDefinition } from './clr';
import type { ShellHomePaths } from './config-directory';
import { ConfigManager, ShellHomeDirectory } from './config-directory';
import { CliReplErrors } from './error-codes';
import type { CryptLibraryPathResult } from './crypt-library-paths';
import { formatForJSONOutput } from './format-json';
import type { MongoLogWriter } from 'mongodb-log-writer';
import { MongoLogManager, mongoLogId } from 'mongodb-log-writer';
import type { MongoshNodeReplOptions, MongoshIOProvider } from './mongosh-repl';
import MongoshNodeRepl from './mongosh-repl';
import type { MongoshLoggingAndTelemetry } from '@mongosh/logging';
import { setupLoggingAndTelemetry } from '@mongosh/logging';
import {
ToggleableAnalytics,
ThrottledAnalytics,
SampledAnalytics,
} from '@mongosh/logging';
import type { MongoshBus } from '@mongosh/types';
import {
CliUserConfig,
CliUserConfigValidator,
TimingCategories,
} from '@mongosh/types';
import { promises as fs } from 'fs';
import path from 'path';
import { getOsInfo } from './get-os-info';
import { UpdateNotificationManager } from './update-notification-manager';
import { getTimingData, markTime, summariseTimingData } from './startup-timing';
import type { IdPInfo } from 'mongodb';
import type {
AgentWithInitialize,
DevtoolsProxyOptions,
} from '@mongodb-js/devtools-proxy-support';
import { useOrCreateAgent } from '@mongodb-js/devtools-proxy-support';
/**
* Connecting text key.
*/
const CONNECTING = 'cli-repl.cli-repl.connecting';
/**
* The set of options for Segment analytics support.
*/
type AnalyticsOptions = {
/** The hostname of the HTTP endpoint for Segment. */
host?: string;
/** The Segment API key. */
apiKey?: string;
/** Whether to enable telemetry even if we are running in CI. */
alwaysEnable?: boolean;
};
/**
* The set of options taken by CliRepl instances.
*/
export type CliReplOptions = {
/** The set of parsed command line flags. */
shellCliOptions: CliOptions;
/** A function for getting the shared library path for in-use encryption. */
getCryptLibraryPaths?: (bus: MongoshBus) => Promise<CryptLibraryPathResult>;
/** The stream to read user input from. */
input: Readable;
/** The stream to write shell output to. */
output: Writable;
/**
* The stream to write prompt output to when requesting data from user, like password.
* Helpful when user wants to redirect the output to a file or null device.
* If not provided, the `output` stream will be used.
*/
promptOutput?: Writable;
/** The set of home directory paths used by this shell instance. */
shellHomePaths: ShellHomePaths;
/** The ordered list of paths in which to look for a global configuration file. */
globalConfigPaths?: string[];
/** A handler for when the REPL exits, e.g. for `exit()` */
onExit: (code?: number) => never;
/** Optional analytics override options. */
analyticsOptions?: AnalyticsOptions;
} & Pick<MongoshNodeReplOptions, 'nodeReplOptions'>;
/** The set of config options that is *always* available in config files stored on the file system. */
type CliUserConfigOnDisk = Partial<CliUserConfig> &
Pick<CliUserConfig, 'enableTelemetry' | 'userId' | 'telemetryAnonymousId'>;
/**
* The REPL used from the terminal.
*
* Unlike MongoshNodeRepl, this class implements I/O interactions.
*/
export class CliRepl implements MongoshIOProvider {
mongoshRepl: MongoshNodeRepl;
bus: MongoshBus;
cliOptions: Readonly<CliOptions>;
getCryptLibraryPaths?: (bus: MongoshBus) => Promise<CryptLibraryPathResult>;
cachedCryptLibraryPath?: Promise<CryptLibraryPathResult>;
shellHomeDirectory: ShellHomeDirectory;
configDirectory: ConfigManager<CliUserConfigOnDisk>;
config: CliUserConfigOnDisk;
globalConfig: Partial<CliUserConfig> | null = null;
globalConfigPaths: string[];
logManager?: MongoLogManager;
logWriter?: MongoLogWriter;
input: Readable;
output: Writable;
promptOutput: Writable;
analyticsOptions?: AnalyticsOptions;
segmentAnalytics?: SegmentAnalytics;
toggleableAnalytics: ToggleableAnalytics = new ToggleableAnalytics();
warnedAboutInaccessibleFiles = false;
onExit: (code?: number) => Promise<never>;
closingPromise?: Promise<void>;
isContainerizedEnvironment = false;
hasOnDiskTelemetryId = false;
proxyOptions: DevtoolsProxyOptions = {
useEnvironmentVariableProxies: true,
};
agent: AgentWithInitialize | undefined;
updateNotificationManager: UpdateNotificationManager;
fetchMongoshUpdateUrlRegardlessOfCiEnvironment = false; // for testing
cachedGlibcVersion: null | string | undefined = null;
private loggingAndTelemetry: MongoshLoggingAndTelemetry | undefined;
/**
* Instantiate the new CLI Repl.
*/
constructor(options: CliReplOptions) {
this.bus = new EventEmitter();
this.cliOptions = options.shellCliOptions;
this.input = options.input;
this.output = options.output;
this.promptOutput = options.promptOutput ?? options.output;
this.analyticsOptions = options.analyticsOptions;
this.onExit = options.onExit;
const id = new bson.ObjectId().toHexString();
this.config = {
userId: id,
telemetryAnonymousId: id,
enableTelemetry: true,
};
this.getCryptLibraryPaths = options.getCryptLibraryPaths;
this.globalConfigPaths = options.globalConfigPaths ?? [];
this.shellHomeDirectory = new ShellHomeDirectory(options.shellHomePaths);
this.configDirectory = new ConfigManager<CliUserConfigOnDisk>(
this.shellHomeDirectory
)
.on('error', (err: Error) => {
this.bus.emit('mongosh:error', err, 'config');
})
.on('new-config', (config: CliUserConfigOnDisk) => {
this.hasOnDiskTelemetryId = !!(
config.userId || config.telemetryAnonymousId
);
this.setTelemetryEnabled(config.enableTelemetry);
this.bus.emit('mongosh:new-user', {
userId: config.userId,
anonymousId: config.telemetryAnonymousId,
});
})
.on('update-config', (config: CliUserConfigOnDisk) => {
this.hasOnDiskTelemetryId = !!(
config.userId || config.telemetryAnonymousId
);
this.setTelemetryEnabled(config.enableTelemetry);
this.bus.emit('mongosh:update-user', {
userId: config.userId,
anonymousId: config.telemetryAnonymousId,
});
});
this.agent = useOrCreateAgent(this.proxyOptions);
this.updateNotificationManager = new UpdateNotificationManager({
proxyOptions: this.agent,
});
// We can't really do anything meaningful if the output stream is broken or
// closed. To avoid throwing an error while writing to it, let's send it to
// the telemetry instead
this.output.on('error', (err: Error) => {
this.bus.emit('mongosh:error', err, 'io');
});
let jsContext = this.cliOptions.jsContext;
const { willEnterInteractiveMode, quiet } = CliRepl.getFileAndEvalInfo(
this.cliOptions
);
if (jsContext === 'auto' || !jsContext) {
jsContext = willEnterInteractiveMode ? 'repl' : 'plain-vm';
}
this.mongoshRepl = new MongoshNodeRepl({
...options,
shellCliOptions: { ...this.cliOptions, jsContext, quiet },
nodeReplOptions: options.nodeReplOptions ?? {
terminal: process.env.MONGOSH_FORCE_TERMINAL ? true : undefined,
},
bus: this.bus,
ioProvider: this,
});
this.setupOIDCTokenDumpListener();
}
async getIsContainerizedEnvironment() {
// Check for dockerenv file first
try {
await fs.stat('/.dockerenv');
return true;
} catch {
try {
// Check if there is any mention of docker / lxc / k8s in control groups
const cgroup = await fs.readFile('/proc/self/cgroup', 'utf8');
return /\b(docker|lxc|kubepods)\b/.test(cgroup);
} catch {
return false;
}
}
}
get forceDisableTelemetry(): boolean {
return (
this.globalConfig?.forceDisableTelemetry ||
(this.isContainerizedEnvironment && !this.mongoshRepl.isInteractive) ||
!!process.env.MONGOSH_FORCE_DISABLE_TELEMETRY_FOR_TESTING
);
}
/** Setup log writer and start logging. */
private async startLogging(): Promise<void> {
if (!this.loggingAndTelemetry) {
throw new Error('Logging and telemetry not setup');
}
this.logManager ??= new MongoLogManager({
directory:
(await this.getConfig('logLocation')) ||
this.shellHomeDirectory.localPath('.'),
retentionDays: 30,
maxLogFileCount: +(
process.env.MONGOSH_TEST_ONLY_MAX_LOG_FILE_COUNT || 100
),
onerror: (err: Error) => this.bus.emit('mongosh:error', err, 'log'),
onwarn: (err: Error, path: string) =>
this.warnAboutInaccessibleFile(err, path),
});
// Do not wait for log cleanup and log errors if MongoLogManager throws any.
void this.logManager
.cleanupOldLogFiles()
.catch((err) => {
this.bus.emit('mongosh:error', err, 'log');
})
.finally(() => {
markTime(TimingCategories.Logging, 'cleaned up log files');
});
if (!this.logWriter) {
this.logWriter ??= await this.logManager.createLogWriter();
const { quiet } = CliRepl.getFileAndEvalInfo(this.cliOptions);
if (!quiet) {
this.output.write(`Current Mongosh Log ID:\t${this.logWriter.logId}\n`);
}
markTime(TimingCategories.Logging, 'instantiated log writer');
}
this.loggingAndTelemetry.attachLogger(this.logWriter);
this.logWriter.info(
'MONGOSH',
mongoLogId(1_000_000_000),
'log',
'Starting log',
{
execPath: process.execPath,
envInfo: redactSensitiveData(this.getLoggedEnvironmentVariables()),
...(await buildInfo()),
}
);
markTime(TimingCategories.Logging, 'logged initial message');
}
/**
* Setup CLI environment: serviceProvider, ShellEvaluator, log connection
* information, external editor, and finally start the repl.
*
* @param {string} driverUri - The driver URI.
* @param {DevtoolsConnectOptions} driverOptions - The driver options.
*/
async start(
driverUri: string,
driverOptions: DevtoolsConnectOptions
): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { version }: { version: string } = require('../package.json');
await this.verifyNodeVersion();
markTime(TimingCategories.REPLInstantiation, 'verified node version');
this.isContainerizedEnvironment =
await this.getIsContainerizedEnvironment();
markTime(
TimingCategories.REPLInstantiation,
'checked containerized environment'
);
if (!this.cliOptions.nodb) {
const cs = new ConnectionString(driverUri);
const searchParams = cs.typedSearchParams<DevtoolsConnectOptions>();
if (!searchParams.get('appName')) {
searchParams.set('appName', `mongosh ${version}`);
}
if (this.isPasswordMissingURI(cs)) {
cs.password = encodeURIComponent(await this.requirePassword());
}
if (await this.isTlsKeyFilePasswordMissingURI(searchParams)) {
const keyFilePassword = encodeURIComponent(
await this.requirePassword('Enter TLS key file password')
);
searchParams.set('tlsCertificateKeyFilePassword', keyFilePassword);
}
this.ensurePasswordFieldIsPresentInAuth(driverOptions);
driverUri = cs.toString();
}
try {
await this.shellHomeDirectory.ensureExists();
} catch (err: unknown) {
this.warnAboutInaccessibleFile(err as Error);
}
markTime(TimingCategories.REPLInstantiation, 'ensured shell homedir');
let analyticsSetupError: Error | null = null;
try {
await this.setupAnalytics();
} catch (err: unknown) {
// Need to delay emitting the error on the bus so that logging is in place
// as well
analyticsSetupError = err as Error;
}
markTime(TimingCategories.Telemetry, 'created analytics instance');
this.loggingAndTelemetry = setupLoggingAndTelemetry({
bus: this.bus,
analytics: this.toggleableAnalytics,
userTraits: {
platform: process.platform,
arch: process.arch,
is_containerized: this.isContainerizedEnvironment,
...(await getOsInfo()),
},
mongoshVersion: version,
});
markTime(TimingCategories.Telemetry, 'completed telemetry setup');
if (analyticsSetupError) {
this.bus.emit('mongosh:error', analyticsSetupError, 'analytics');
}
// Read local and global configuration
try {
this.config = await this.configDirectory.generateOrReadConfig(
this.config
);
} catch (err: unknown) {
this.warnAboutInaccessibleFile(err as Error);
}
this.globalConfig = await this.loadGlobalConfigFile();
markTime(TimingCategories.UserConfigLoading, 'read global config files');
await this.setLoggingEnabled(!(await this.getConfig('disableLogging')));
// Needs to happen after loading the mongosh config file(s)
void this.fetchMongoshUpdateUrl();
if (driverOptions.autoEncryption) {
const origExtraOptions = driverOptions.autoEncryption.extraOptions ?? {};
if (origExtraOptions.cryptSharedLibPath) {
// If a CSFLE path has been specified through 'driverOptions', save it
// for later use.
this.cachedCryptLibraryPath = Promise.resolve({
cryptSharedLibPath: origExtraOptions.cryptSharedLibPath,
});
}
const extraOptions = {
...origExtraOptions,
...(await this.getCryptLibraryOptions()),
};
driverOptions.autoEncryption = {
...driverOptions.autoEncryption,
extraOptions,
};
}
if (
Object.keys(driverOptions.autoEncryption ?? {}).join(',') ===
'extraOptions'
) {
// In this case, autoEncryption opts were only specified for crypt library specs
delete driverOptions.autoEncryption;
}
driverOptions = await this.prepareOIDCOptions(driverUri, driverOptions);
markTime(TimingCategories.DriverSetup, 'prepared OIDC options');
let initialServiceProvider;
try {
initialServiceProvider = await this.connect(driverUri, driverOptions);
} catch (err) {
if (
typeof err === 'object' &&
err?.constructor.name === 'MongoDBOIDCError' &&
!String(driverOptions.oidc?.allowedFlows)?.includes('device-auth')
) {
(err as Error).message +=
'\nConsider specifying --oidcFlows=auth-code,device-auth if you are running mongosh in an environment without browser access.';
}
throw err;
}
markTime(TimingCategories.DriverSetup, 'completed SP setup');
const initialized = await this.mongoshRepl.initialize(
initialServiceProvider,
await this.getMoreRecentMongoshVersion()
);
markTime(TimingCategories.REPLInstantiation, 'initialized mongosh repl');
this.injectReplFunctions();
const {
commandLineLoadFiles,
evalScripts,
willEnterInteractiveMode,
willExecuteCommandLineScripts,
} = CliRepl.getFileAndEvalInfo(this.cliOptions);
if (
(evalScripts.length === 0 ||
this.cliOptions.shell ||
commandLineLoadFiles.length > 0) &&
this.cliOptions.json
) {
throw new MongoshRuntimeError(
'Cannot use --json without --eval or with --shell or with extra files'
);
}
let snippetManager: SnippetManager | undefined;
if (this.config.snippetIndexSourceURLs !== '') {
snippetManager = SnippetManager.create({
installdir: this.shellHomeDirectory.roamingPath('snippets'),
instanceState: this.mongoshRepl.runtimeState().instanceState,
skipInitialIndexLoad: !willEnterInteractiveMode,
proxyOptions: this.agent,
});
}
Editor.create({
input: this.input,
vscodeDir: this.shellHomeDirectory.rcPath('.vscode'),
tmpDir: this.shellHomeDirectory.localPath('editor'),
instanceState: this.mongoshRepl.runtimeState().instanceState,
loadExternalCode: this.mongoshRepl.loadExternalCode.bind(
this.mongoshRepl
),
});
markTime(TimingCategories.REPLInstantiation, 'set up editor');
if (willExecuteCommandLineScripts) {
this.mongoshRepl.setIsInteractive(willEnterInteractiveMode);
this.bus.emit('mongosh:start-session', {
isInteractive: false,
jsContext: this.mongoshRepl.jsContext(),
timings: summariseTimingData(getTimingData()),
});
this.bus.emit('mongosh:start-loading-cli-scripts', {
usesShellOption: !!this.cliOptions.shell,
});
const exitCode = await this.loadCommandLineFilesAndEval(
commandLineLoadFiles,
evalScripts
);
if (exitCode !== 0) {
await this.exit(exitCode);
return;
}
if (!this.cliOptions.shell) {
// We flush the telemetry data as part of exiting. Make sure we have
// the right config value.
this.setTelemetryEnabled(await this.getConfig('enableTelemetry'));
await this.exit(0);
return;
}
} else {
this.mongoshRepl.setIsInteractive(true);
}
if (!this.cliOptions.norc) {
/**
* We are deliberately loading snippets only after handling command line
* scripts and files:
* - Snippets are mostly supposed to make human interaction easier, less
* programmatic usage
* - Snippets can take a while to run because they're mongosh scripts
* - Programmatic users should ideally make their dependencies explicit
* and include them via load() or require() instead of relying on
* snippets, which are part of the local mongosh installation's state
* - Programmatic users who really want a dependency on a snippet can use
* snippet('load-all') to explicitly load snippets
*/
markTime(TimingCategories.SnippetLoading, 'start load snippets');
await snippetManager?.loadAllSnippets();
markTime(TimingCategories.SnippetLoading, 'done load snippets');
}
markTime(TimingCategories.ResourceFileLoading, 'loading rc files');
await this.loadRcFiles();
markTime(TimingCategories.ResourceFileLoading, 'loaded rc files');
this.verifyPlatformSupport();
// We only enable/disable here, since the rc file/command line scripts
// can disable the telemetry setting.
this.setTelemetryEnabled(await this.getConfig('enableTelemetry'));
this.bus.emit('mongosh:start-mongosh-repl', { version });
markTime(TimingCategories.REPLInstantiation, 'starting repl');
await this.mongoshRepl.startRepl(initialized);
this.bus.emit('mongosh:start-session', {
isInteractive: true,
jsContext: this.mongoshRepl.jsContext(),
timings: summariseTimingData(getTimingData()),
});
}
private static getFileAndEvalInfo(cliOptions: CliOptions): {
commandLineLoadFiles: string[];
evalScripts: string[];
willExecuteCommandLineScripts: boolean;
willEnterInteractiveMode: boolean;
quiet: boolean;
} {
const commandLineLoadFiles = cliOptions.fileNames ?? [];
const evalScripts = cliOptions.eval ?? [];
const willExecuteCommandLineScripts =
commandLineLoadFiles.length > 0 || evalScripts.length > 0;
const willEnterInteractiveMode =
!willExecuteCommandLineScripts || !!cliOptions.shell;
const quiet =
cliOptions.quiet ?? !(cliOptions.verbose ?? willEnterInteractiveMode);
return {
commandLineLoadFiles,
evalScripts,
willEnterInteractiveMode,
willExecuteCommandLineScripts,
quiet,
};
}
injectReplFunctions(): void {
const functions = {
async buildInfo() {
return await buildInfo();
},
} as const;
const { context } = this.mongoshRepl.runtimeState();
for (const [name, impl] of Object.entries(functions)) {
context[name] = (...args: Parameters<typeof impl>) => {
return Object.assign(impl(...args), {
[Symbol.for('@@mongosh.syntheticPromise')]: true,
});
};
}
}
async setupAnalytics(): Promise<void> {
if (
process.env.IS_MONGOSH_EVERGREEN_CI &&
!this.analyticsOptions?.alwaysEnable
) {
throw new Error('no analytics setup for the mongosh CI environment');
}
// build-info.json is created as a part of the release process
const apiKey =
this.analyticsOptions?.apiKey ??
(await buildInfo({ withSegmentApiKey: true })).segmentApiKey;
if (!apiKey) {
throw new Error('no analytics API key defined');
}
// 'http' is not supported in startup snapshots yet.
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { Analytics } = require('@segment/analytics-node');
this.segmentAnalytics = new Analytics({
writeKey: apiKey,
maxRetries: 0,
httpRequestTimeout: 1000,
...this.analyticsOptions,
});
this.toggleableAnalytics = new ToggleableAnalytics(
new SampledAnalytics({
target: new ThrottledAnalytics({
target: this.segmentAnalytics,
throttle: {
rate: 30,
metadataPath: this.shellHomeDirectory.paths.shellLocalDataPath,
},
}),
sampling: () =>
!!process.env.MONGOSH_ANALYTICS_SAMPLE || Math.random() <= 0.01,
})
);
}
async setLoggingEnabled(enabled: boolean): Promise<void> {
if (enabled) {
await this.startLogging();
} else {
this.loggingAndTelemetry?.detachLogger();
}
}
setTelemetryEnabled(enabled: boolean): void {
if (this.globalConfig === null) {
// This happens when the per-user config file is loaded before we have
// started loading the global config file. Keep telemetry paused in that
// case.
return;
}
if (enabled && this.hasOnDiskTelemetryId && !this.forceDisableTelemetry) {
this.toggleableAnalytics.enable();
} else {
this.toggleableAnalytics.disable();
}
}
async loadCommandLineFilesAndEval(
files: string[],
evalScripts: string[]
): Promise<number> {
let lastEvalResult: unknown;
let exitCode = 0;
try {
markTime(TimingCategories.Eval, 'start eval scripts');
for (const script of evalScripts) {
this.bus.emit('mongosh:eval-cli-script');
lastEvalResult = await this.mongoshRepl.loadExternalCode(
script,
'@(shell eval)'
);
}
markTime(TimingCategories.Eval, 'finished eval scripts');
} catch (err) {
// We have two distinct flows of control in the exception case;
// if we are running in --json mode, we treat the error as a
// special kind of output, otherwise we just pass the exception along.
// We should *probably* change this so that CliRepl.start() doesn't result
// in any user-caused exceptions, including script execution or failure to
// connect, and instead always take the --json flow, but that feels like
// it might be too big of a breaking change right now.
exitCode = 1;
if (this.cliOptions.json) {
lastEvalResult = err;
} else {
throw err;
}
}
if (lastEvalResult !== undefined) {
let formattedResult;
if (this.cliOptions.json) {
try {
formattedResult = formatForJSONOutput(
lastEvalResult,
this.cliOptions.json
);
} catch (e) {
// If formatting the result as JSON fails, instead treat the error
// itself as the output, as if the script had been e.g.
// `try { ... } catch(e) { throw EJSON.serialize(e); }`
// Do not try to format as EJSON repeatedly, if it fails then
// there's little we can do about it.
exitCode = 1;
formattedResult = formatForJSONOutput(e, this.cliOptions.json);
}
} else {
formattedResult = this.mongoshRepl.writer(lastEvalResult);
}
this.output.write(formattedResult + '\n');
}
markTime(TimingCategories.Eval, 'wrote eval output');
markTime(TimingCategories.EvalFile, 'start loading external files');
const { quiet } = CliRepl.getFileAndEvalInfo(this.cliOptions);
for (const file of files) {
if (!quiet) {
this.output.write(
`Loading file: ${this.clr(file, 'mongosh:filename')}\n`
);
}
await this.mongoshRepl.loadExternalFile(file);
}
markTime(TimingCategories.EvalFile, 'finished external files');
return exitCode;
}
/**
* Load the .mongoshrc.js file, and warn about mismatched filenames, if any.
*/
async loadRcFiles(): Promise<void> {
if (this.cliOptions.norc) {
return;
}
const legacyPath = this.shellHomeDirectory.rcPath('.mongorc.js');
const mongoshrcPath = this.shellHomeDirectory.rcPath('.mongoshrc.js');
const mongoshrcMisspelledPath =
this.shellHomeDirectory.rcPath('.mongoshrc');
let hasMongoshRc = false;
try {
await fs.stat(mongoshrcPath);
hasMongoshRc = true;
} catch {
/* file not present */
}
if (hasMongoshRc) {
try {
this.bus.emit('mongosh:mongoshrc-load');
await this.mongoshRepl.loadExternalFile(mongoshrcPath);
} catch (err: any) {
this.output.write(
this.clr('Error while running ~/.mongoshrc.js:\n', 'mongosh:warning')
);
this.output.write(this.mongoshRepl.writer(err) + '\n');
}
return;
}
if (this.cliOptions.quiet) {
return;
}
let hasLegacyRc = false;
try {
await fs.stat(legacyPath);
hasLegacyRc = true;
} catch {
/* file not present */
}
if (hasLegacyRc) {
this.bus.emit('mongosh:mongoshrc-mongorc-warn');
const msg =
'Warning: Found ~/.mongorc.js, but not ~/.mongoshrc.js. ~/.mongorc.js will not be loaded.\n' +
' You may want to copy or rename ~/.mongorc.js to ~/.mongoshrc.js.\n';
this.output.write(this.clr(msg, 'mongosh:warning'));
return;
}
let hasMisspelledFilename = false;
try {
await fs.stat(mongoshrcMisspelledPath);
hasMisspelledFilename = true;
} catch {
/* file not present */
}
if (hasMisspelledFilename) {
const msg =
'Warning: Found ~/.mongoshrc, but not ~/.mongoshrc.js. Did you forget to add .js?\n';
this.output.write(this.clr(msg, 'mongosh:warning'));
}
}
async loadGlobalConfigFile(): Promise<Partial<CliUserConfig>> {
let fileContents = '';
let filename = '';
for (filename of this.globalConfigPaths) {
try {
fileContents = await fs.readFile(filename, 'utf8');
break;
} catch (err: any) {
if (err?.code !== 'ENOENT') {
this.bus.emit('mongosh:error', err, 'config');
}
}
}
this.bus.emit('mongosh:globalconfig-load', {
filename,
found: fileContents.length > 0,
});
try {
let config: CliUserConfig;
if (fileContents.trim().startsWith('{')) {
config = bson.EJSON.parse(fileContents);
} else {
config = (yaml.load(fileContents) as any)?.mongosh ?? {};
}
for (const [key, value] of Object.entries(config) as [
keyof CliUserConfig,
any
][]) {
const validationResult = await CliUserConfigValidator.validate(
key,
value
);
if (validationResult) {
const msg = `Warning: Ignoring config option "${key}" from ${filename}: ${validationResult}\n`;
this.output.write(this.clr(msg, 'mongosh:warning'));
delete config[key];
}
}
return config;
} catch (err: any) {
this.bus.emit('mongosh:error', err, 'config');
const msg = `Warning: Could not parse global configuration file at ${filename}: ${err?.message}\n`;
this.output.write(this.clr(msg, 'mongosh:warning'));
return {};
}
}
/**
* Use when a warning about an inaccessible config file needs to be written.
*/
warnAboutInaccessibleFile(err: Error, path?: string): void {
this.bus.emit('mongosh:error', err, 'config');
if (this.warnedAboutInaccessibleFiles) {
// If one of the files mongosh tries to access, it's also likely that
// the others are as well. In that case, there is no point in spamming the
// user with repeated warnings.
return;
}
this.warnedAboutInaccessibleFiles = true;
const msg = `Warning: Could not access file${path ? 'at ' + path : ''}: ${
err.message
}\n`;
this.output.write(this.clr(msg, 'mongosh:warning'));
}
/**
* Connect to the cluster.
*
* @param {string} driverUri - The driver URI.
* @param {DevtoolsConnectOptions} driverOptions - The driver options.
*/
async connect(
driverUri: string,
driverOptions: DevtoolsConnectOptions
): Promise<NodeDriverServiceProvider> {
const { quiet } = CliRepl.getFileAndEvalInfo(this.cliOptions);
if (!this.cliOptions.nodb && !quiet) {
this.output.write(
i18n.__(CONNECTING) +
'\t\t' +
this.clr(redactURICredentials(driverUri), 'mongosh:uri') +
'\n'
);
}
return await NodeDriverServiceProvider.connect(
driverUri,
driverOptions,
this.cliOptions,
this.bus
);
}
/** Return the file path used for the REPL history. */
getHistoryFilePath(): string {
return this.shellHomeDirectory.roamingPath('mongosh_repl_history');
}
/**
* Implements getConfig from the {@link ConfigProvider} interface.
*/
// eslint-disable-next-line @typescript-eslint/require-await
async getConfig<K extends keyof CliUserConfig>(
key: K
): Promise<CliUserConfig[K]> {
return (
(this.config as CliUserConfig)[key] ??
(this.globalConfig as CliUserConfig)?.[key] ??
new CliUserConfig()[key]
);
}
/**
* Implements setConfig from the {@link ConfigProvider} interface.
*/
async setConfig<K extends keyof CliUserConfig>(
key: K,
value: CliUserConfig[K]
): Promise<'success'> {
if (key === 'forceDisableTelemetry') {
throw new MongoshRuntimeError(
"The 'forceDisableTelemetry' setting cannot be modified"
);
}
this.config[key] = value;
if (key === 'enableTelemetry') {
if (this.forceDisableTelemetry) {
throw new MongoshRuntimeError(
"Cannot modify telemetry settings while 'forceDisableTelemetry' is set to true"
);
}
this.setTelemetryEnabled(this.config.enableTelemetry);
this.bus.emit('mongosh:update-user', {
userId: this.config.userId,
anonymousId: this.config.telemetryAnonymousId,
});
}
if (key === 'disableLogging') {
await this.setLoggingEnabled(!value);
}
try {
await this.configDirectory.writeConfigFile(this.config);
} catch (err: any) {
this.warnAboutInaccessibleFile(err, this.configDirectory.path());
}
return 'success';
}
/**
* Implements listConfigOptions from the {@link ConfigProvider} interface.
*/
listConfigOptions(): string[] {
const hiddenKeys = [
'userId',
'telemetryAnonymousId',
'disableGreetingMessage',
'forceDisableTelemetry',
];
const keys = Object.keys(new CliUserConfig());
return keys.filter((key) => !hiddenKeys.includes(key));
}
/**
* Verify that we are running on a supported Node.js version, and error out if not.
*/
async verifyNodeVersion(): Promise<void> {
if (process.env.MONGOSH_SKIP_NODE_VERSION_CHECK) {
return;
}
const { engines } = require('../package.json');
// Strip -rc.0, -pre, etc. from the Node.js version because semver rejects those otherwise.
const baseNodeVersion = process.version.replace(/-.*$/, '');
if (!semver.satisfies(baseNodeVersion, engines.node)) {
const warning = new MongoshWarning(
`Mismatched node version. Required version: ${engines.node}. Currently using: ${process.version}. Exiting...\n\n`,
CliReplErrors.NodeVersionMismatch
);
await this._fatalError(warning);
}
}
// Factored out for testing
getGlibcVersion = getGlibcVersion;
verifyPlatformSupport(): void {
const { quiet } = CliRepl.getFileAndEvalInfo(this.cliOptions);
if (quiet) {
return;
}
const glibcVersion = this.getGlibcVersion();
const warnings: string[] = [];
const RECOMMENDED_GLIBC = '>=2.28.0';
const RECOMMENDED_OPENSSL = '>=3.0.0';
const RECOMMENDED_NODEJS = '>=20.0.0';
const semverRangeCheck = (
semverLikeVersion: string,