This repository has been archived by the owner on Aug 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 370
/
BlobWriteStream.cs
414 lines (371 loc) · 18.8 KB
/
BlobWriteStream.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
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
// -----------------------------------------------------------------------------------------
// <copyright file="BlobWriteStream.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// 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.
// </copyright>
// -----------------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.Blob
{
using Microsoft.WindowsAzure.Storage.Blob.Protocol;
using Microsoft.WindowsAzure.Storage.Core;
using Microsoft.WindowsAzure.Storage.Core.Util;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
internal sealed class BlobWriteStream : BlobWriteStreamBase
{
/// <summary>
/// Initializes a new instance of the BlobWriteStream class for a block blob.
/// </summary>
/// <param name="blockBlob">Blob reference to write to.</param>
/// <param name="accessCondition">An object that represents the access conditions for the blob. If null, no condition is used.</param>
/// <param name="options">An object that specifies additional options for the request.</param>
/// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
internal BlobWriteStream(CloudBlockBlob blockBlob, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
: base(blockBlob, accessCondition, options, operationContext)
{
}
/// <summary>
/// Initializes a new instance of the BlobWriteStream class for a page blob.
/// </summary>
/// <param name="pageBlob">Blob reference to write to.</param>
/// <param name="pageBlobSize">Size of the page blob.</param>
/// <param name="createNew">Use <c>true</c> if the page blob is newly created, <c>false</c> otherwise.</param>
/// <param name="accessCondition">An object that represents the access conditions for the blob. If null, no condition is used.</param>
/// <param name="options">An object that specifies additional options for the request.</param>
/// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
internal BlobWriteStream(CloudPageBlob pageBlob, long pageBlobSize, bool createNew, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
: base(pageBlob, pageBlobSize, createNew, accessCondition, options, operationContext)
{
}
/// <summary>
/// Initializes a new instance of the BlobWriteStream class for an append blob.
/// </summary>
/// <param name="appendBlob">Blob reference to write to.</param>
/// <param name="accessCondition">An object that represents the access conditions for the blob. If null, no condition is used.</param>
/// <param name="options">An object that specifies additional options for the request.</param>
/// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
internal BlobWriteStream(CloudAppendBlob appendBlob, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
: base(appendBlob, accessCondition, options, operationContext)
{
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type <c>SeekOrigin</c> indicating the reference
/// point used to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
long oldOffset = this.currentOffset;
long newOffset = this.GetNewOffset(offset, origin);
if (oldOffset != newOffset)
{
if (this.blobMD5 != null)
{
this.blobMD5.Dispose();
this.blobMD5 = null;
}
this.Flush();
}
this.currentOffset = newOffset;
this.currentBlobOffset = newOffset;
return this.currentOffset;
}
/// <summary>
/// Writes a sequence of bytes to the current stream and advances the current
/// position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies count bytes from
/// buffer to the current stream.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin
/// copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
public override void Write(byte[] buffer, int offset, int count)
{
CommonUtility.RunWithoutSynchronizationContext(() => this.WriteAsync(buffer, offset, count).Wait());
}
/// <summary>
/// Asynchronously writes a sequence of bytes to the current stream, advances the current
/// position within this stream by the number of bytes written, and monitors cancellation requests.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies count bytes from
/// buffer to the current stream.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin
/// copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CommonUtility.AssertNotNull("buffer", buffer);
CommonUtility.AssertInBounds("offset", offset, 0, buffer.Length);
CommonUtility.AssertInBounds("count", count, 0, buffer.Length - offset);
if (this.lastException != null)
{
throw this.lastException;
}
if (this.committed)
{
throw new InvalidOperationException(SR.BlobStreamAlreadyCommitted);
}
if (this.blobMD5 != null)
{
this.blobMD5.UpdateHash(buffer, offset, count);
}
this.currentOffset += count;
while (count > 0)
{
int maxBytesToWrite = this.streamWriteSizeInBytes - (int)this.internalBuffer.Length;
int bytesToWrite = Math.Min(count, maxBytesToWrite);
this.internalBuffer.Write(buffer, offset, bytesToWrite);
if (this.blockMD5 != null)
{
this.blockMD5.UpdateHash(buffer, offset, bytesToWrite);
}
count -= bytesToWrite;
offset += bytesToWrite;
if (bytesToWrite == maxBytesToWrite)
{
await this.DispatchWriteAsync().ConfigureAwait(false);
}
}
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written to the underlying blob.
/// </summary>
public override void Flush()
{
CommonUtility.RunWithoutSynchronizationContext(() => this.FlushAsync().Wait());
}
/// <summary>
/// Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous flush operation.</returns>
public override async Task FlushAsync(CancellationToken cancellationToken)
{
if (this.lastException != null)
{
throw this.lastException;
}
if (this.committed)
{
throw new InvalidOperationException(SR.BlobStreamAlreadyCommitted);
}
await this.DispatchWriteAsync().ConfigureAwait(false);
await Task.Run(() => this.noPendingWritesEvent.Wait(), cancellationToken);
if (this.lastException != null)
{
throw this.lastException;
}
}
/// <summary>
/// Releases the blob resources used by the Stream.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (!this.disposed)
{
this.disposed = true;
if (disposing)
{
if (!this.committed)
{
CommonUtility.RunWithoutSynchronizationContext(() => this.CommitAsync().Wait());
}
}
}
base.Dispose(disposing);
}
/// <summary>
/// Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying blob, and commits the blob.
/// </summary>
/// <returns>A task that represents the asynchronous commit operation.</returns>
public override async Task CommitAsync()
{
await this.FlushAsync().ConfigureAwait(false);
this.committed = true;
try
{
if (this.blockBlob != null)
{
if (this.blobMD5 != null)
{
this.blockBlob.Properties.ContentMD5 = this.blobMD5.ComputeHash();
}
await this.blockBlob.PutBlockListAsync(this.blockList, this.accessCondition, this.options, this.operationContext).ConfigureAwait(false);
}
else
{
if (this.blobMD5 != null)
{
this.Blob.Properties.ContentMD5 = this.blobMD5.ComputeHash();
await this.Blob.SetPropertiesAsync(this.accessCondition, this.options, this.operationContext).ConfigureAwait(false);
}
}
}
catch (Exception e)
{
this.lastException = e;
throw;
}
}
/// <summary>
/// Asynchronously dispatches a write operation.
/// </summary>
/// <returns>A task that represents the asynchronous write operation.</returns>
private async Task DispatchWriteAsync()
{
if (this.internalBuffer.Length == 0)
{
return;
}
MultiBufferMemoryStream bufferToUpload = this.internalBuffer;
this.internalBuffer = new MultiBufferMemoryStream(this.Blob.ServiceClient.BufferManager);
bufferToUpload.Seek(0, SeekOrigin.Begin);
string bufferMD5 = null;
if (this.blockMD5 != null)
{
bufferMD5 = this.blockMD5.ComputeHash();
this.blockMD5.Dispose();
this.blockMD5 = new MD5Wrapper();
}
if (this.blockBlob != null)
{
string blockId = this.GetCurrentBlockId();
this.blockList.Add(blockId);
await this.WriteBlockAsync(bufferToUpload, blockId, bufferMD5).ConfigureAwait(false);
}
else if (this.pageBlob != null)
{
if ((bufferToUpload.Length % Constants.PageSize) != 0)
{
this.lastException = new IOException(SR.InvalidPageSize);
throw this.lastException;
}
long offset = this.currentBlobOffset;
this.currentBlobOffset += bufferToUpload.Length;
await this.WritePagesAsync(bufferToUpload, offset, bufferMD5).ConfigureAwait(false);
}
else
{
long offset = this.currentBlobOffset;
this.currentBlobOffset += bufferToUpload.Length;
// We cannot differentiate between max size condition failing only in the retry versus failing in the
// first attempt and retry even for a single writer scenario. So we will eliminate the latter and handle
// the former in the append operation call.
if (this.accessCondition.IfMaxSizeLessThanOrEqual.HasValue && this.currentBlobOffset > this.accessCondition.IfMaxSizeLessThanOrEqual.Value)
{
this.lastException = new IOException(SR.InvalidBlockSize);
throw this.lastException;
}
await this.WriteAppendBlockAsync(bufferToUpload, offset, bufferMD5).ConfigureAwait(false);
}
}
/// <summary>
/// Starts an asynchronous PutBlock operation as soon as the parallel
/// operation semaphore becomes available.
/// </summary>
/// <param name="blockData">Data to be uploaded</param>
/// <param name="blockId">Block ID</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
private async Task WriteBlockAsync(Stream blockData, string blockId, string blockMD5)
{
this.noPendingWritesEvent.Increment();
await this.parallelOperationSemaphore.WaitAsync().ConfigureAwait(false);
Task putBlockTask = this.blockBlob.PutBlockAsync(blockId, blockData, blockMD5, this.accessCondition, this.options, this.operationContext).ContinueWith(task =>
{
if (task.Exception != null)
{
this.lastException = task.Exception;
}
this.noPendingWritesEvent.Decrement();
this.parallelOperationSemaphore.Release();
});
}
/// <summary>
/// Starts an asynchronous WritePages operation as soon as the parallel
/// operation semaphore becomes available.
/// </summary>
/// <param name="pageData">Data to be uploaded</param>
/// <param name="offset">Offset within the page blob</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
private async Task WritePagesAsync(Stream pageData, long offset, string contentMD5)
{
this.noPendingWritesEvent.Increment();
await this.parallelOperationSemaphore.WaitAsync().ConfigureAwait(false);
Task writePagesTask = this.pageBlob.WritePagesAsync(pageData, offset, contentMD5, this.accessCondition, this.options, this.operationContext).ContinueWith(task =>
{
if (task.Exception != null)
{
this.lastException = task.Exception;
}
this.noPendingWritesEvent.Decrement();
this.parallelOperationSemaphore.Release();
});
}
/// <summary>
/// Starts an asynchronous AppendBlock operation as soon as the parallel
/// operation semaphore becomes available. Since parallelism is always set
/// to 1 for append blobs, appendblock operations are called serially.
/// </summary>
/// <param name="blockData">Data to be uploaded</param>
/// <param name="offset">Offset within the append blob to be used to set the append offset conditional header.</param>
/// <param name="blockMD5">MD5 hash of the data to be uploaded</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
private async Task WriteAppendBlockAsync(Stream blockData, long offset, string blockMD5)
{
this.noPendingWritesEvent.Increment();
await this.parallelOperationSemaphore.WaitAsync().ConfigureAwait(false);
this.accessCondition.IfAppendPositionEqual = offset;
int previousResultsCount = this.operationContext.RequestResults.Count;
Task writeBlockTask = this.appendBlob.AppendBlockAsync(blockData, blockMD5, this.accessCondition, this.options, this.operationContext).ContinueWith(task =>
{
if (task.Exception != null)
{
if (this.options.AbsorbConditionalErrorsOnRetry.Value
&& this.operationContext.LastResult.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed)
{
StorageExtendedErrorInformation extendedInfo = this.operationContext.LastResult.ExtendedErrorInformation;
#pragma warning disable 618
if (extendedInfo != null
&& (extendedInfo.ErrorCode == BlobErrorCodeStrings.InvalidAppendCondition || extendedInfo.ErrorCode == BlobErrorCodeStrings.InvalidMaxBlobSizeCondition)
&& (this.operationContext.RequestResults.Count - previousResultsCount > 1))
#pragma warning restore 618
{
// Pre-condition failure on a retry should be ignored in a single writer scenario since the request
// succeeded in the first attempt.
Logger.LogWarning(this.operationContext, SR.PreconditionFailureIgnored);
}
else
{
this.lastException = task.Exception;
}
}
else
{
this.lastException = task.Exception;
}
}
this.noPendingWritesEvent.Decrement();
this.parallelOperationSemaphore.Release();
});
}
}
}