ravendb /Raven.Database/Server/RavenFS/Controllers/RavenFsApiController.cs

Language C# Lines 525
MD5 Hash 7c6a4bab08fb629e0f17ece95b832b5d
Repository https://github.com/nwendel/ravendb.git View Raw File
  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
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Routing;
using Raven.Abstractions;
using Raven.Abstractions.Extensions;
using Raven.Abstractions.Exceptions;
using Raven.Abstractions.Logging;
using Raven.Abstractions.Util.Streams;
using Raven.Database.Config;
using Raven.Database.Server.Controllers;
using Raven.Database.Server.RavenFS.Infrastructure;
using Raven.Database.Server.RavenFS.Notifications;
using Raven.Database.Server.RavenFS.Search;
using Raven.Database.Server.RavenFS.Storage;
using Raven.Database.Server.RavenFS.Synchronization;
using Raven.Database.Server.RavenFS.Synchronization.Conflictuality;
using Raven.Database.Server.RavenFS.Synchronization.Rdc.Wrapper;
using Raven.Database.Server.Security;
using Raven.Database.Server.Tenancy;
using Raven.Database.Server.WebApi;
using Raven.Json.Linq;
using System.Collections.Generic;
using Raven.Abstractions.FileSystem;
using Raven.Abstractions.Data;

namespace Raven.Database.Server.RavenFS.Controllers
{
	public abstract class RavenFsApiController : RavenBaseApiController
	{
	    private static readonly ILog Logger = LogManager.GetCurrentClassLogger();

		private PagingInfo paging;
		private NameValueCollection queryString;

	    private FileSystemsLandlord landlord;
	    private RequestManager requestManager;

		public override LogTenantType TenantType
		{
			get { return LogTenantType.Filesystem; }
		}

        public RequestManager RequestManager
        {
            get
            {
                if (Configuration == null)
                    return requestManager;
                return (RequestManager)Configuration.Properties[typeof(RequestManager)];
            }
        }
	    public RavenFileSystem FileSystem
		{
			get
			{
			    var fs = FileSystemsLandlord.GetFileSystemInternal(FileSystemName);
                if (fs == null)
                {
                    throw new InvalidOperationException("Could not find a file system named: " + FileSystemName);
                }

                return fs.Result;
			}
		}

		public override async Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
		{
			InnerInitialization(controllerContext);
            var authorizer = (MixedModeRequestAuthorizer)controllerContext.Configuration.Properties[typeof(MixedModeRequestAuthorizer)];
            var result = new HttpResponseMessage();
            if (InnerRequest.Method.Method != "OPTIONS")
            {
                result = await RequestManager.HandleActualRequest(this, async () =>
                {
                    RequestManager.SetThreadLocalState(InnerHeaders, FileSystemName);
                    return await ExecuteActualRequest(controllerContext, cancellationToken, authorizer);
                }, httpException => GetMessageWithObject(new { Error = httpException.Message }, HttpStatusCode.ServiceUnavailable));
            }

            RequestManager.AddAccessControlHeaders(this, result);
            RequestManager.ResetThreadLocalState();

            return result;
		}


        private async Task<HttpResponseMessage> ExecuteActualRequest(HttpControllerContext controllerContext, CancellationToken cancellationToken,
            MixedModeRequestAuthorizer authorizer)
        {
            HttpResponseMessage authMsg;
            if (authorizer.TryAuthorize(this, out authMsg) == false)
                return authMsg;

            var internalHeader = GetHeader("Raven-internal-request");
            if (internalHeader == null || internalHeader != "true")
                RequestManager.IncrementRequestCount();

            var fileSystemInternal = await FileSystemsLandlord.GetFileSystemInternal(FileSystemName);
            if (fileSystemInternal == null)
            {
                var msg = "Could not find a file system named: " + FileSystemName;
                return GetMessageWithObject(new { Error = msg }, HttpStatusCode.ServiceUnavailable);
            }

            var sp = Stopwatch.StartNew();

            var result = await base.ExecuteAsync(controllerContext, cancellationToken);
            sp.Stop();
            AddRavenHeader(result, sp);

            return result;
        }


		protected override void InnerInitialization(HttpControllerContext controllerContext)
		{
            base.InnerInitialization(controllerContext);
            landlord = (FileSystemsLandlord)controllerContext.Configuration.Properties[typeof(FileSystemsLandlord)];
            requestManager = (RequestManager)controllerContext.Configuration.Properties[typeof(RequestManager)];

            var values = controllerContext.Request.GetRouteData().Values;
            if (values.ContainsKey("MS_SubRoutes"))
            {
                var routeDatas = (IHttpRouteData[])controllerContext.Request.GetRouteData().Values["MS_SubRoutes"];
                var selectedData = routeDatas.FirstOrDefault(data => data.Values.ContainsKey("fileSystemName"));

                if (selectedData != null)
                    FileSystemName = selectedData.Values["fileSystemName"] as string;
            }
            else
            {
                if (values.ContainsKey("fil"))
                    FileSystemName = values["fileSystemName"] as string;
            }
		    if (FileSystemName == null)
		        throw new InvalidOperationException("Could not find file system name for this request");
		}

	    public string FileSystemName { get; private set; }

	    public FileSystemsLandlord FileSystemsLandlord
        {
            get
            {
                if (Configuration == null)
                    return landlord;
                return (FileSystemsLandlord)Configuration.Properties[typeof(FileSystemsLandlord)];
            }
        }


		public NotificationPublisher Publisher
		{
			get { return FileSystem.Publisher; }
		}

		public BufferPool BufferPool
		{
			get { return FileSystem.BufferPool; }
		}

		public SigGenerator SigGenerator
		{
			get { return FileSystem.SigGenerator; }
		}

		public Historian Historian
		{
			get { return FileSystem.Historian; }
		}

	    public override InMemoryRavenConfiguration SystemConfiguration
	    {
	        get { return FileSystemsLandlord.SystemConfiguration; }
	    }

	    private NameValueCollection QueryString
		{
			get { return queryString ?? (queryString = HttpUtility.ParseQueryString(Request.RequestUri.Query)); }
		}

		protected ITransactionalStorage Storage
		{
			get { return FileSystem.Storage; }
		}

		protected IndexStorage Search
		{
			get { return FileSystem.Search; }
		}

		protected FileLockManager FileLockManager
		{
			get { return FileSystem.FileLockManager; }
		}

		protected ConflictArtifactManager ConflictArtifactManager
		{
			get { return FileSystem.ConflictArtifactManager; }
		}

		protected ConflictDetector ConflictDetector
		{
			get { return FileSystem.ConflictDetector; }
		}

		protected ConflictResolver ConflictResolver
		{
			get { return FileSystem.ConflictResolver; }
		}

		protected SynchronizationTask SynchronizationTask
		{
			get { return FileSystem.SynchronizationTask; }
		}

		protected StorageOperationsTask StorageOperationsTask
		{
			get { return FileSystem.StorageOperationsTask; }
		}

		protected PagingInfo Paging
		{
			get
			{
				if (paging != null)
					return paging;

				int start;
				int.TryParse(QueryString["start"], out start);

				int pageSize;
				if (int.TryParse(QueryString["pageSize"], out pageSize) == false)
					pageSize = 25;

				paging = new PagingInfo
					         {
						         PageSize = Math.Min(1024, Math.Max(1, pageSize)),
						         Start = Math.Max(start, 0)
					         };

				return paging;
			}
		}

		protected Task<T> Result<T>(T result)
		{
			var tcs = new TaskCompletionSource<T>();
			tcs.SetResult(result);
			return tcs.Task;
		}

		protected HttpResponseMessage StreamResult(string filename, Stream resultContent)
		{
			var response = new HttpResponseMessage
				               {
					               Headers =
						               {
							               TransferEncodingChunked = false
						               }
				               };
			long length;
			ContentRangeHeaderValue contentRange = null;
			if (Request.Headers.Range != null)
			{
				if (Request.Headers.Range.Ranges.Count != 1)
				{
					throw new InvalidOperationException("Can't handle multiple range values");
				}
				var range = Request.Headers.Range.Ranges.First();
				var from = range.From ?? 0;
				var to = range.To ?? resultContent.Length;

				length = (to - from);

				// "to" in Content-Range points on the last byte. In other words the set is: <from..to>  not <from..to)
				if (from < to)
				{
					contentRange = new ContentRangeHeaderValue(from, to - 1, resultContent.Length);
					resultContent = new LimitedStream(resultContent, from, to);
				}
				else
				{
					contentRange = new ContentRangeHeaderValue(0);
					resultContent = Stream.Null;
				}
			}
			else
			{
				length = resultContent.Length;
			}

			response.Content = new StreamContent(resultContent)
				                   {
					                   Headers =
						                   {
							                   ContentDisposition = new ContentDispositionHeaderValue("attachment")
								                                        {
									                                        FileName = filename
								                                        },
							                  // ContentLength = length,
							                   ContentRange = contentRange,
						                   }
				                   };

			return response;
		}

		protected void AssertFileIsNotBeingSynced(string fileName, IStorageActionsAccessor accessor,
		                                          bool wrapByResponseException = false)
		{
			if (FileLockManager.TimeoutExceeded(fileName, accessor))
			{
				FileLockManager.UnlockByDeletingSyncConfiguration(fileName, accessor);
			}
			else
			{
				Log.Debug("Cannot execute operation because file '{0}' is being synced", fileName);

				var beingSyncedException = new SynchronizationException(string.Format("File {0} is being synced", fileName));

				if (wrapByResponseException)
				{
					throw new HttpResponseException(Request.CreateResponse((HttpStatusCode)420, beingSyncedException));
				}

				throw beingSyncedException;
			}
		}

		protected HttpResponseException BadRequestException(string message)
		{
			return
				new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) {Content = new StringContent(message)});
		}

		protected HttpResponseException ConcurrencyResponseException(ConcurrencyException concurrencyException)
		{
			return new HttpResponseException(Request.CreateResponse(HttpStatusCode.MethodNotAllowed, concurrencyException));
		}

		protected class PagingInfo
		{
			public int PageSize;
			public int Start;
		}



        public override bool SetupRequestToProperDatabase(RequestManager rm)
        {
            var tenantId = FileSystemName;

            if (string.IsNullOrWhiteSpace(tenantId))
            {
                throw new HttpException(503, "Could not find a file system with no name");
            }

            Task<RavenFileSystem> resourceStoreTask;
            bool hasDb;
            try
            {
                hasDb = landlord.TryGetOrCreateResourceStore(tenantId, out resourceStoreTask);
            }
            catch (Exception e)
            {
                var msg = "Could not open file system named: " + tenantId;
                Logger.WarnException(msg, e);
                throw new HttpException(503, msg, e);
            }
            if (hasDb)
            {
                try
                {
                    if (resourceStoreTask.Wait(TimeSpan.FromSeconds(30)) == false)
                    {
                        var msg = "The filesystem " + tenantId +
                                  " is currently being loaded, but after 30 seconds, this request has been aborted. Please try again later, file system loading continues.";
                        Logger.Warn(msg);
                        throw new HttpException(503, msg);
                    }
                    var args = new BeforeRequestWebApiEventArgs()
                    {
                        Controller = this,
                        IgnoreRequest = false,
                        TenantId = tenantId,
                        FileSystem = resourceStoreTask.Result
                    };
                    rm.OnBeforeRequest(args);
                    if (args.IgnoreRequest)
                        return false;
                }
                catch (Exception e)
                {
                    var msg = "Could not open file system named: " + tenantId;
                    Logger.WarnException(msg, e);
                    throw new HttpException(503, msg, e);
                }

                landlord.LastRecentlyUsed.AddOrUpdate(tenantId, SystemTime.UtcNow, (s, time) => SystemTime.UtcNow);
            }
            else
            {
                var msg = "Could not find a file system named: " + tenantId;
                Logger.Warn(msg);
                throw new HttpException(503, msg);
            }
            return true;
        }

	    public override string TenantName
	    {
	        get { return "fs/" + FileSystemName; }
	    }

	    public override void MarkRequestDuration(long duration)
	    {
	        FileSystem.MetricsCounters.RequestDuationMetric.Update(duration);
	    }

        #region Metadata Headers Handling


        private static readonly HashSet<string> HeadersToIgnoreClient = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
		{
			// Raven internal headers
			"Raven-Server-Build",
			"Non-Authoritive-Information",
			"Raven-Timer-Request",

            //proxy
            "Reverse-Via",

            "Allow",
            "Content-Disposition",
            "Content-Encoding",
            "Content-Language",
            "Content-Location",
            "Content-MD5",
            "Content-Range",
            "Content-Type",
            "Expires",
			// ignoring this header, we handle this internally
			Constants.LastModified,
			// Ignoring this header, since it may
			// very well change due to things like encoding,
			// adding metadata, etc
			"Content-Length",
			// Special things to ignore
			"Keep-Alive",
			"X-Powered-By",
			"X-AspNet-Version",
			"X-Requested-With",
			"X-SourceFiles",
			// Request headers
			"Accept-Charset",
			"Accept-Encoding",
			"Accept",
			"Accept-Language",
			"Authorization",
			"Cookie",
			"Expect",
			"From",
			"Host",
			"If-Match",
			"If-Modified-Since",
			"If-None-Match",
			"If-Range",
			"If-Unmodified-Since",
			"Max-Forwards",
			"Referer",
			"TE",
			"User-Agent",
			//Response headers
			"Accept-Ranges",
			"Age",
			"Allow",
			Constants.MetadataEtagField,
			"Location",
			"Origin",
			"Retry-After",
			"Server",
			"Set-Cookie2",
			"Set-Cookie",
			"Vary",
			"Www-Authenticate",
			// General
			"Cache-Control",
			"Connection",
			"Date",
			"Pragma",
			"Trailer",
			"Transfer-Encoding",
			"Upgrade",
			"Via",
			"Warning",
            
            // Azure specific
            "X-LiveUpgrade",
            "DISGUISED-HOST",
            "X-SITE-DEPLOYMENT-ID",
		};

        protected static readonly IList<string> ReadOnlyHeaders = new List<string> { Constants.LastModified, Constants.MetadataEtagField }.AsReadOnly();

        protected virtual RavenJObject GetFilteredMetadataFromHeaders(HttpHeaders headers)
        {            
            return headers.FilterHeadersToObject();
        }

        #endregion Metadata Headers Handling

    }
}
Back to Top