-
Notifications
You must be signed in to change notification settings - Fork 13
/
MongoRunner.cs
251 lines (212 loc) · 10 KB
/
MongoRunner.cs
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
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using MongoDB.Bson;
using MongoDB.Driver;
namespace EphemeralMongo;
public sealed class MongoRunner
{
private readonly IFileSystem _fileSystem;
private readonly IPortFactory _portFactory;
private readonly IMongoExecutableLocator _executableLocator;
private readonly IMongoProcessFactory _processFactory;
private readonly MongoRunnerOptions _options;
private IMongoProcess? _process;
private string? _dataDirectory;
private MongoRunner(IFileSystem fileSystem, IPortFactory portFactory, IMongoExecutableLocator executableLocator, IMongoProcessFactory processFactory, MongoRunnerOptions options)
{
this._fileSystem = fileSystem;
this._portFactory = portFactory;
this._executableLocator = executableLocator;
this._processFactory = processFactory;
this._options = options;
}
public static IMongoRunner Run(MongoRunnerOptions? options = null)
{
var optionsCopy = options == null ? new MongoRunnerOptions() : new MongoRunnerOptions(options);
var runner = new MongoRunner(new FileSystem(), new PortFactory(), new MongoExecutableLocator(), new MongoProcessFactory(), optionsCopy);
return runner.RunInternal();
}
private IMongoRunner RunInternal()
{
try
{
// Find MongoDB and make it executable
var executablePath = this._executableLocator.FindMongoExecutablePath(this._options, MongoProcessKind.Mongod);
this._fileSystem.MakeFileExecutable(executablePath);
// Ensure data directory exists...
this._dataDirectory = this._options.DataDirectory ?? Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
this._fileSystem.CreateDirectory(this._dataDirectory);
try
{
// ...and has no existing MongoDB lock file
// https://stackoverflow.com/a/6857973/825695
var lockFilePath = Path.Combine(this._dataDirectory, "mongod.lock");
this._fileSystem.DeleteFile(lockFilePath);
}
catch
{
// Ignored - this data directory might already be in use, we'll see later how mongod reacts
}
this._options.MongoPort ??= this._portFactory.GetRandomAvailablePort();
// Build MongoDB executable arguments
var arguments = string.Format(CultureInfo.InvariantCulture, "--dbpath {0} --port {1} --bind_ip 127.0.0.1", ProcessArgument.Escape(this._dataDirectory), this._options.MongoPort);
arguments += RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? string.Empty : " --tlsMode disabled";
arguments += this._options.UseSingleNodeReplicaSet ? " --replSet " + this._options.ReplicaSetName : string.Empty;
arguments += string.IsNullOrWhiteSpace(this._options.AdditionalArguments) ? string.Empty : " " + this._options.AdditionalArguments;
this._process = this._processFactory.CreateMongoProcess(this._options, MongoProcessKind.Mongod, executablePath, arguments);
this._process.Start();
var connectionStringFormat = this._options.UseSingleNodeReplicaSet ? "mongodb://127.0.0.1:{0}/?connect=direct&replicaSet={1}&readPreference=primary" : "mongodb://127.0.0.1:{0}";
var connectionString = string.Format(CultureInfo.InvariantCulture, connectionStringFormat, this._options.MongoPort, this._options.ReplicaSetName);
return new StartedMongoRunner(this, connectionString);
}
catch
{
this.Dispose(throwOnException: false);
throw;
}
}
private void Dispose(bool throwOnException)
{
var exceptions = new List<Exception>(1);
try
{
this._process?.Dispose();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
try
{
// Do not dispose data directory if it was a user input
if (this._dataDirectory != null && this._options.DataDirectory == null)
{
this._fileSystem.DeleteDirectory(this._dataDirectory);
}
}
catch (Exception ex)
{
exceptions.Add(ex);
}
if (throwOnException)
{
if (exceptions.Count == 1)
{
ExceptionDispatchInfo.Capture(exceptions[0]).Throw();
}
else if (exceptions.Count > 1)
{
throw new AggregateException(exceptions);
}
}
}
private sealed class StartedMongoRunner : IMongoRunner
{
private readonly MongoRunner _runner;
private int _isDisposed;
public StartedMongoRunner(MongoRunner runner, string connectionString)
{
this._runner = runner;
this.ConnectionString = connectionString;
}
public string ConnectionString { get; }
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1117:Parameters should be on same line or separate lines", Justification = "Would have used too many lines, and this way string.Format is still very readable")]
public void Import(string database, string collection, string inputFilePath, string? additionalArguments = null, bool drop = false)
{
if (Interlocked.CompareExchange(ref this._isDisposed, 0, 0) == 1)
{
throw new ObjectDisposedException("MongoDB runner is already disposed");
}
if (string.IsNullOrWhiteSpace(database))
{
throw new ArgumentException("Database name is required", nameof(database));
}
if (string.IsNullOrWhiteSpace(collection))
{
throw new ArgumentException("Collection name is required", nameof(collection));
}
if (string.IsNullOrWhiteSpace(inputFilePath))
{
throw new ArgumentException("Input file path is required", nameof(inputFilePath));
}
var executablePath = this._runner._executableLocator.FindMongoExecutablePath(this._runner._options, MongoProcessKind.MongoImport);
this._runner._fileSystem.MakeFileExecutable(executablePath);
var arguments = string.Format(
CultureInfo.InvariantCulture,
@"--uri=""{0}"" --db={1} --collection={2} --file={3} {4} {5}",
this.ConnectionString, database, collection, ProcessArgument.Escape(inputFilePath), drop ? " --drop" : string.Empty, additionalArguments ?? string.Empty);
using (var process = this._runner._processFactory.CreateMongoProcess(this._runner._options, MongoProcessKind.MongoImport, executablePath, arguments))
{
process.Start();
}
}
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1117:Parameters should be on same line or separate lines", Justification = "Would have used too many lines, and this way string.Format is still very readable")]
public void Export(string database, string collection, string outputFilePath, string? additionalArguments = null)
{
if (Interlocked.CompareExchange(ref this._isDisposed, 0, 0) == 1)
{
throw new ObjectDisposedException("MongoDB runner is already disposed");
}
if (string.IsNullOrWhiteSpace(database))
{
throw new ArgumentException("Database name is required", nameof(database));
}
if (string.IsNullOrWhiteSpace(collection))
{
throw new ArgumentException("Collection name is required", nameof(collection));
}
if (string.IsNullOrWhiteSpace(outputFilePath))
{
throw new ArgumentException("Output file path is required", nameof(outputFilePath));
}
var executablePath = this._runner._executableLocator.FindMongoExecutablePath(this._runner._options, MongoProcessKind.MongoExport);
this._runner._fileSystem.MakeFileExecutable(executablePath);
var arguments = string.Format(
CultureInfo.InvariantCulture,
@"--uri=""{0}"" --db={1} --collection={2} --out={3} {4}",
this.ConnectionString, database, collection, ProcessArgument.Escape(outputFilePath), additionalArguments ?? string.Empty);
using (var process = this._runner._processFactory.CreateMongoProcess(this._runner._options, MongoProcessKind.MongoExport, executablePath, arguments))
{
process.Start();
}
}
public void Dispose()
{
if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) == 0)
{
this.TryShutdownQuietly();
this._runner.Dispose(throwOnException: true);
}
}
private void TryShutdownQuietly()
{
// https://www.mongodb.com/docs/v4.4/reference/command/shutdown/
const int defaultShutdownTimeoutInSeconds = 10;
var shutdownCommand = new BsonDocument
{
{ "shutdown", 1 },
{ "force", true },
{ "timeoutSecs", defaultShutdownTimeoutInSeconds },
};
try
{
var client = new MongoClient(this.ConnectionString);
var admin = client.GetDatabase("admin");
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(defaultShutdownTimeoutInSeconds)))
{
admin.RunCommand<BsonDocument>(shutdownCommand, cancellationToken: cts.Token);
}
}
catch (MongoConnectionException)
{
// FYI this is the expected behavior as mongod is shutting down
}
catch
{
// Ignore other exceptions as well, we'll kill the process anyway
}
}
}
}