-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMinIoStorageService.cs
386 lines (313 loc) · 18.6 KB
/
MinIoStorageService.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
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
/*
* Copyright 2021-2022 MONAI Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Text;
using Amazon.SecurityToken.Model;
using Ardalis.GuardClauses;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Minio;
using Monai.Deploy.Storage.API;
using Monai.Deploy.Storage.Configuration;
using Monai.Deploy.Storage.S3Policy;
using Newtonsoft.Json;
namespace Monai.Deploy.Storage.MinIO
{
public class MinIoStorageService : IStorageService
{
private readonly IMinIoClientFactory _minioClientFactory;
private readonly IAmazonSecurityTokenServiceClientFactory _amazonSecurityTokenServiceClientFactory;
private readonly ILogger<MinIoStorageService> _logger;
private readonly StorageServiceConfiguration _options;
public string Name => "MinIO Storage Service";
public MinIoStorageService(IMinIoClientFactory minioClientFactory, IAmazonSecurityTokenServiceClientFactory amazonSecurityTokenServiceClientFactory, IOptions<StorageServiceConfiguration> options, ILogger<MinIoStorageService> logger)
{
Guard.Against.Null(options);
_minioClientFactory = minioClientFactory ?? throw new ArgumentNullException(nameof(IMinIoClientFactory));
_amazonSecurityTokenServiceClientFactory = amazonSecurityTokenServiceClientFactory ?? throw new ArgumentNullException(nameof(amazonSecurityTokenServiceClientFactory));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
var configuration = options.Value;
ValidateConfiguration(configuration);
_options = configuration;
}
private void ValidateConfiguration(StorageServiceConfiguration configuration)
{
Guard.Against.Null(configuration);
foreach (var key in ConfigurationKeys.RequiredKeys)
{
if (!configuration.Settings.ContainsKey(key))
{
throw new ConfigurationException($"{Name} is missing configuration for {key}.");
}
}
}
#region ServiceAccount
public async Task CopyObjectAsync(string sourceBucketName, string sourceObjectName, string destinationBucketName, string destinationObjectName, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(sourceBucketName);
Guard.Against.NullOrWhiteSpace(sourceObjectName);
Guard.Against.NullOrWhiteSpace(destinationBucketName);
Guard.Against.NullOrWhiteSpace(destinationObjectName);
var client = _minioClientFactory.GetObjectOperationsClient();
await CopyObjectUsingClient(client, sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName, cancellationToken).ConfigureAwait(false);
}
public async Task<Stream> GetObjectAsync(string bucketName, string objectName, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrWhiteSpace(objectName);
var client = _minioClientFactory.GetObjectOperationsClient();
var stream = new MemoryStream();
await GetObjectUsingClient(client, bucketName, objectName, (s) => s.CopyTo(stream), cancellationToken).ConfigureAwait(false);
stream.Seek(0, SeekOrigin.Begin);
return stream;
}
public async Task<IList<VirtualFileInfo>> ListObjectsAsync(string bucketName, string? prefix = "", bool recursive = false, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
var client = _minioClientFactory.GetBucketOperationsClient();
return await ListObjectsUsingClient(client, bucketName, prefix, recursive, cancellationToken).ConfigureAwait(false);
}
public async Task<Dictionary<string, bool>> VerifyObjectsExistAsync(string bucketName, IReadOnlyList<string> artifactList, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.Null(artifactList);
var existingObjectsDict = new Dictionary<string, bool>();
foreach (var artifact in artifactList)
{
try
{
var fileObjects = await ListObjectsAsync(bucketName, artifact).ConfigureAwait(false);
var folderObjects = await ListObjectsAsync(bucketName, artifact.EndsWith("/") ? artifact : $"{artifact}/", true).ConfigureAwait(false);
if (!folderObjects.Any() && !fileObjects.Any())
{
_logger.FileNotFoundError(bucketName, $"{artifact}");
existingObjectsDict.Add(artifact, false);
continue;
}
existingObjectsDict.Add(artifact, true);
}
catch (Exception e)
{
_logger.VerifyObjectError(bucketName, e);
existingObjectsDict.Add(artifact, false);
}
}
return existingObjectsDict;
}
public async Task<bool> VerifyObjectExistsAsync(string bucketName, string artifactName, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrWhiteSpace(artifactName);
var fileObjects = await ListObjectsAsync(bucketName, artifactName).ConfigureAwait(false);
var folderObjects = await ListObjectsAsync(bucketName, artifactName.EndsWith("/") ? artifactName : $"{artifactName}/", true).ConfigureAwait(false);
if (folderObjects.Any() || fileObjects.Any())
{
return true;
}
_logger.FileNotFoundError(bucketName, $"{artifactName}");
return false;
}
public async Task PutObjectAsync(string bucketName, string objectName, Stream data, long size, string contentType, Dictionary<string, string>? metadata, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrWhiteSpace(objectName);
Guard.Against.Null(data);
Guard.Against.NullOrWhiteSpace(contentType);
var client = _minioClientFactory.GetObjectOperationsClient();
await PutObjectUsingClient(client, bucketName, objectName, data, size, contentType, metadata, cancellationToken).ConfigureAwait(false);
}
public async Task RemoveObjectAsync(string bucketName, string objectName, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrWhiteSpace(objectName);
var client = _minioClientFactory.GetObjectOperationsClient();
await RemoveObjectUsingClient(client, bucketName, objectName, cancellationToken).ConfigureAwait(false);
}
public async Task RemoveObjectsAsync(string bucketName, IEnumerable<string> objectNames, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrEmpty(objectNames);
var client = _minioClientFactory.GetObjectOperationsClient();
await RemoveObjectsUsingClient(client, bucketName, objectNames, cancellationToken).ConfigureAwait(false);
}
public async Task CreateFolderAsync(string bucketName, string folderPath, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrEmpty(folderPath);
var stubFile = folderPath + "/stubFile.txt";
var data = Encoding.UTF8.GetBytes("stub file");
var length = data.Length;
var stream = new MemoryStream(data);
await PutObjectAsync(bucketName, stubFile, stream, length, "application/octet-stream", null, cancellationToken).ConfigureAwait(false);
}
#endregion ServiceAccount
#region TemporaryCredentials
public async Task<Credentials> CreateTemporaryCredentialsAsync(string bucketName, string folderName, int durationSeconds = 3600, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrEmpty(folderName);
var policy = PolicyExtensions.ToPolicy(bucketName, folderName);
var policyString = JsonConvert.SerializeObject(policy, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
_logger.TemporaryCredentialPolicy(policyString);
var assumeRoleRequest = new AssumeRoleRequest
{
DurationSeconds = durationSeconds,
Policy = policyString
};
var client = _amazonSecurityTokenServiceClientFactory.GetClient();
var role = await client.AssumeRoleAsync(assumeRoleRequest, cancellationToken: cancellationToken).ConfigureAwait(false);
return role.Credentials;
}
public async Task CopyObjectWithCredentialsAsync(string sourceBucketName, string sourceObjectName, string destinationBucketName, string destinationObjectName, Credentials credentials, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(sourceBucketName);
Guard.Against.NullOrWhiteSpace(sourceObjectName);
Guard.Against.NullOrWhiteSpace(destinationBucketName);
Guard.Against.NullOrWhiteSpace(destinationObjectName);
var client = _minioClientFactory.GetObjectOperationsClient(credentials, _options.Settings[ConfigurationKeys.Region]);
await CopyObjectUsingClient(client, sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName, cancellationToken).ConfigureAwait(false);
}
public async Task<Stream> GetObjectWithCredentialsAsync(string bucketName, string objectName, Credentials credentials, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrWhiteSpace(objectName);
var client = _minioClientFactory.GetObjectOperationsClient(credentials, _options.Settings[ConfigurationKeys.Region]);
var stream = new MemoryStream();
await GetObjectUsingClient(client, bucketName, objectName, (s) => s.CopyTo(stream), cancellationToken).ConfigureAwait(false);
stream.Seek(0, SeekOrigin.Begin);
return stream;
}
public async Task<IList<VirtualFileInfo>> ListObjectsWithCredentialsAsync(string bucketName, Credentials credentials, string? prefix = "", bool recursive = false, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
var client = _minioClientFactory.GetBucketOperationsClient(credentials, _options.Settings[ConfigurationKeys.Region]);
return await ListObjectsUsingClient(client, bucketName, prefix, recursive, cancellationToken).ConfigureAwait(false);
}
public async Task PutObjectWithCredentialsAsync(string bucketName, string objectName, Stream data, long size, string contentType, Dictionary<string, string> metadata, Credentials credentials, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrWhiteSpace(objectName);
Guard.Against.Null(data);
Guard.Against.NullOrWhiteSpace(contentType);
var client = _minioClientFactory.GetObjectOperationsClient(credentials, _options.Settings[ConfigurationKeys.Region]);
await PutObjectUsingClient(client, bucketName, objectName, data, size, contentType, metadata, cancellationToken).ConfigureAwait(false);
}
public async Task RemoveObjectWithCredentialsAsync(string bucketName, string objectName, Credentials credentials, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrWhiteSpace(objectName);
var client = _minioClientFactory.GetObjectOperationsClient(credentials, _options.Settings[ConfigurationKeys.Region]);
await RemoveObjectUsingClient(client, bucketName, objectName, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task RemoveObjectsWithCredentialsAsync(string bucketName, IEnumerable<string> objectNames, Credentials credentials, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrEmpty(objectNames);
var client = _minioClientFactory.GetObjectOperationsClient(credentials, _options.Settings[ConfigurationKeys.Region]);
await RemoveObjectsUsingClient(client, bucketName, objectNames, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public async Task CreateFolderWithCredentialsAsync(string bucketName, string folderPath, Credentials credentials, CancellationToken cancellationToken = default)
{
Guard.Against.NullOrWhiteSpace(bucketName);
Guard.Against.NullOrEmpty(folderPath);
var stubFile = folderPath + "/stubFile.txt";
var data = Encoding.UTF8.GetBytes("stub file");
var length = data.Length;
var stream = new MemoryStream(data);
var client = _minioClientFactory.GetObjectOperationsClient(credentials, _options.Settings[ConfigurationKeys.Region]);
await PutObjectUsingClient(client, bucketName, stubFile, stream, length, "application/octet-stream", null, cancellationToken: cancellationToken).ConfigureAwait(false);
}
#endregion TemporaryCredentials
#region Internal Helper Methods
private static async Task CopyObjectUsingClient(IObjectOperations client, string sourceBucketName, string sourceObjectName, string destinationBucketName, string destinationObjectName, CancellationToken cancellationToken)
{
var copySourceObjectArgs = new CopySourceObjectArgs()
.WithBucket(sourceBucketName)
.WithObject(sourceObjectName);
var copyObjectArgs = new CopyObjectArgs()
.WithBucket(destinationBucketName)
.WithObject(destinationObjectName)
.WithCopyObjectSource(copySourceObjectArgs);
await client.CopyObjectAsync(copyObjectArgs, cancellationToken).ConfigureAwait(false);
}
private static async Task GetObjectUsingClient(IObjectOperations client, string bucketName, string objectName, Action<Stream> callback, CancellationToken cancellationToken)
{
var args = new GetObjectArgs()
.WithBucket(bucketName)
.WithObject(objectName)
.WithCallbackStream(callback);
await client.GetObjectAsync(args, cancellationToken).ConfigureAwait(false);
}
private async Task<IList<VirtualFileInfo>> ListObjectsUsingClient(IBucketOperations client, string bucketName, string? prefix, bool recursive, CancellationToken cancellationToken)
{
return await Task.Run(() =>
{
var files = new List<VirtualFileInfo>();
var listArgs = new ListObjectsArgs()
.WithBucket(bucketName)
.WithPrefix(prefix)
.WithRecursive(recursive);
var objservable = client.ListObjectsAsync(listArgs, cancellationToken);
var completedEvent = new ManualResetEventSlim(false);
objservable.Subscribe(item =>
{
if (!item.IsDir)
{
files.Add(new VirtualFileInfo(Path.GetFileName(item.Key), item.Key, item.ETag, item.Size)
{
LastModifiedDateTime = item.LastModifiedDateTime
});
}
},
error =>
{
_logger.ListObjectError(bucketName, error.Message);
},
() => completedEvent.Set(), cancellationToken);
completedEvent.Wait(cancellationToken);
return files;
}).ConfigureAwait(false);
}
private static async Task RemoveObjectUsingClient(IObjectOperations client, string bucketName, string objectName, CancellationToken cancellationToken)
{
var args = new RemoveObjectArgs()
.WithBucket(bucketName)
.WithObject(objectName);
await client.RemoveObjectAsync(args, cancellationToken).ConfigureAwait(false);
}
private static async Task PutObjectUsingClient(IObjectOperations client, string bucketName, string objectName, Stream data, long size, string contentType, Dictionary<string, string>? metadata, CancellationToken cancellationToken)
{
var args = new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(objectName)
.WithStreamData(data)
.WithObjectSize(size)
.WithContentType(contentType);
if (metadata is not null)
{
args.WithHeaders(metadata);
}
await client.PutObjectAsync(args, cancellationToken).ConfigureAwait(false);
}
private static async Task RemoveObjectsUsingClient(IObjectOperations client, string bucketName, IEnumerable<string> objectNames, CancellationToken cancellationToken)
{
var args = new RemoveObjectsArgs()
.WithBucket(bucketName)
.WithObjects(objectNames.ToList());
await client.RemoveObjectsAsync(args, cancellationToken).ConfigureAwait(false);
}
#endregion Internal Helper Methods
}
}