forked from Azure-App-Service/KuduLite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Startup.cs
763 lines (626 loc) · 37.1 KB
/
Startup.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
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
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Http.Formatting;
using System.Reflection;
using AspNetCore.RouteAnalyzer;
using Kudu.Contracts;
using Kudu.Contracts.Infrastructure;
using Kudu.Contracts.Scan;
using Kudu.Contracts.Settings;
using Kudu.Contracts.SourceControl;
using Kudu.Contracts.Tracing;
using Kudu.Core;
using Kudu.Core.Commands;
using Kudu.Core.Deployment;
using Kudu.Core.Helpers;
using Kudu.Core.Infrastructure;
using Kudu.Core.Scan;
using Kudu.Core.Settings;
using Kudu.Core.SourceControl;
using Kudu.Core.SSHKey;
using Kudu.Core.Tracing;
using Kudu.Services.Diagnostics;
using Kudu.Services.GitServer;
using Kudu.Services.Performance;
using Kudu.Services.Scan;
using Kudu.Services.TunnelServer;
using Kudu.Services.Web.Infrastructure;
using Kudu.Services.Web.Tracing;
using Kudu.Services.LinuxConsumptionInstanceAdmin;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing.Constraints;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using Swashbuckle.AspNetCore.Swagger;
using Environment = Kudu.Core.Environment;
using ILogger = Kudu.Core.Deployment.ILogger;
using Microsoft.AspNetCore.Authentication;
using Kudu.Services.Web.Services;
using Kudu.Core.K8SE;
namespace Kudu.Services.Web
{
public class Startup
{
private readonly IHostingEnvironment _hostingEnvironment;
private IEnvironment _webAppRuntimeEnvironment;
private IDeploymentSettingsManager _noContextDeploymentsSettingsManager;
private static readonly ServerConfiguration ServerConfiguration = new ServerConfiguration();
public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
{
Console.WriteLine(@"Startup : " + DateTime.Now.ToString("hh.mm.ss.ffffff"));
Configuration = configuration;
_hostingEnvironment = hostingEnvironment;
}
private IConfiguration Configuration { get; }
/// <summary>
/// This method gets called by the runtime. It is used to add services
/// to the container. It uses the Extension pattern.
/// </summary>
/// <todo>
/// CORE TODO Remove initializing contextAccessor : See if over time we can refactor away the need for this?
/// It's kind of a quick hack/compatibility shim. Ideally you want to get the request context only from where
/// it's specifically provided to you (Request.HttpContext in a controller, or as an Invoke() parameter in
/// a middleware) and pass it wherever its needed.
/// </todo>
public void ConfigureServices(IServiceCollection services)
{
Console.WriteLine(@"Configure Services : " + DateTime.Now.ToString("hh.mm.ss.ffffff"));
FileSystemHelpers.DeleteDirectorySafe("/home/site/locks/deployment");
// configure basic authentication
services.Configure<FormOptions>(options =>
{
options.MultipartBodyLengthLimit = 52428800;
options.ValueCountLimit = 1000000;
options.KeyLengthLimit = 1000000;
});
services.AddRouteAnalyzer();
// Kudu.Services contains all the Controllers
var kuduServicesAssembly = Assembly.Load("Kudu.Services");
services.AddMvcCore()
.AddRazorPages()
.AddJsonFormatters()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
.AddApplicationPart(kuduServicesAssembly).AddControllersAsServices()
.AddApiExplorer();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info {Title = "Kudu API Docs"});
// Setting the comments path for the Swagger JSON and UI.
var xmlFile = $"Kudu.Services.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
services.AddGZipCompression();
services.AddDirectoryBrowser();
services.AddDataProtection();
services.AddLogging(
builder =>
{
builder.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning)
.AddConsole();
});
services.AddSingleton<IHttpContextAccessor>(new HttpContextAccessor());
services.AddSingleton<ILinuxConsumptionEnvironment, LinuxConsumptionEnvironment>();
services.AddSingleton<ILinuxConsumptionInstanceManager, LinuxConsumptionInstanceManager>();
KuduWebUtil.EnsureHomeEnvironmentVariable();
KuduWebUtil.EnsureSiteBitnessEnvironmentVariable();
IEnvironment environment = KuduWebUtil.GetEnvironment(_hostingEnvironment);
_webAppRuntimeEnvironment = environment;
KuduWebUtil.EnsureDotNetCoreEnvironmentVariable(environment);
// CORE TODO Check this
// fix up invalid /home/site/deployments/settings.xml
KuduWebUtil.EnsureValidDeploymentXmlSettings(environment);
// Add various folders that never change to the process path. All child processes will inherit this
KuduWebUtil.PrependFoldersToPath(environment);
// Add middleware for Linux Consumption authentication and authorization
// when KuduLIte is running in service fabric mesh
services.AddLinuxConsumptionAuthentication();
services.AddLinuxConsumptionAuthorization(environment);
// General
services.AddScoped<IServerConfiguration, ServerConfiguration>();
// CORE TODO Looks like this doesn't ever actually do anything, can refactor out?
services.AddSingleton<IBuildPropertyProvider>(new BuildPropertyProvider());
_noContextDeploymentsSettingsManager =
new DeploymentSettingsManager(new XmlSettings.Settings(KuduWebUtil.GetSettingsPath(environment)));
TraceServices.TraceLevel = _noContextDeploymentsSettingsManager.GetTraceLevel();
// Its required to register the IHttpContextAccessor first
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IEnvironment>(provider => {
var httpContext = provider.GetRequiredService<IHttpContextAccessor>().HttpContext;
return KuduWebUtil.GetEnvironment(_hostingEnvironment, provider.GetRequiredService<IDeploymentSettingsManager>(), httpContext);
});
// Per request environment
services.AddScoped(sp =>
KuduWebUtil.GetEnvironment(_hostingEnvironment, sp.GetRequiredService<IDeploymentSettingsManager>()));
services.AddDeploymentServices(environment);
/*
* CORE TODO Refactor ITracerFactory/ITracer/GetTracer()/
* ILogger needs serious refactoring:
* - Names should be changed to make it clearer that ILogger is for deployment
* logging and ITracer and friends are for Kudu tracing
* - ILogger is a first-class citizen in .NET core and has it's own meaning. We should be using it
* where appropriate (and not name-colliding with it)
* - ITracer vs. ITraceFactory is redundant and confusing.
* - TraceServices only serves to confuse stuff now that we're avoiding
*/
Func<IServiceProvider, ITracer> resolveTracer = KuduWebUtil.GetTracer;
ITracer CreateTracerThunk() => resolveTracer(services.BuildServiceProvider());
// First try to use the current request profiler if any, otherwise create a new one
var traceFactory = new TracerFactory(() =>
{
var sp = services.BuildServiceProvider();
var context = sp.GetRequiredService<IHttpContextAccessor>().HttpContext;
return TraceServices.GetRequestTracer(context) ?? resolveTracer(sp);
});
services.AddScoped<ITracer>(sp =>
{
var context = sp.GetRequiredService<IHttpContextAccessor>().HttpContext;
return TraceServices.GetRequestTracer(context) ?? NullTracer.Instance;
});
services.AddSingleton<ITraceFactory>(traceFactory);
TraceServices.SetTraceFactory(CreateTracerThunk);
services.AddSingleton<IDictionary<string, IOperationLock>>(
KuduWebUtil.GetNamedLocks(traceFactory, environment));
// CORE TODO ShutdownDetector, used by LogStreamManager.
//var shutdownDetector = new ShutdownDetector();
//shutdownDetector.Initialize()
var noContextTraceFactory = new TracerFactory(() =>
KuduWebUtil.GetTracerWithoutContext(environment, _noContextDeploymentsSettingsManager));
services.AddTransient<IAnalytics>(sp => new Analytics(sp.GetRequiredService<IDeploymentSettingsManager>(),
sp.GetRequiredService<IServerConfiguration>(),
noContextTraceFactory));
// CORE TODO
// Trace shutdown event
// Cannot use shutdownDetector.Token.Register because of race condition
// with NinjectServices.Stop via WebActivator.ApplicationShutdownMethodAttribute
// Shutdown += () => TraceShutdown(environment, noContextDeploymentsSettingsManager);
// LogStream service
services.AddLogStreamService(_webAppRuntimeEnvironment,traceFactory);
// Deployment Service
services.AddWebJobsDependencies();
services.AddScoped<ILogger>(KuduWebUtil.GetDeploymentLogger);
services.AddScoped<IDeploymentManager, DeploymentManager>();
services.AddScoped<IFetchDeploymentManager, FetchDeploymentManager>();
services.AddScoped<IScanManager, ScanManager>();
services.AddScoped<ISSHKeyManager, SSHKeyManager>();
services.AddScoped<IRepositoryFactory>(
sp => KuduWebUtil.GetDeploymentLock(traceFactory, environment).RepositoryFactory =
new RepositoryFactory(
sp.GetRequiredService<IEnvironment>(), sp.GetRequiredService<IDeploymentSettingsManager>(),
sp.GetRequiredService<ITraceFactory>()));
services.AddScoped<IApplicationLogsReader, ApplicationLogsReader>();
// Git server
services.AddGitServer(KuduWebUtil.GetDeploymentLock(traceFactory, environment));
// Git Servicehook Parsers
services.AddGitServiceHookParsers();
services.AddScoped<ICommandExecutor, CommandExecutor>();
// KuduWebUtil.MigrateSite(environment, noContextDeploymentsSettingsManager);
// RemoveOldTracePath(environment);
// RemoveTempFileFromUserDrive(environment);
// CORE TODO Windows Fix: Temporary fix for https://github.com/npm/npm/issues/5905
//EnsureNpmGlobalDirectory();
//EnsureUserProfileDirectory();
//// Skip SSL Certificate Validate
//if (Environment.SkipSslValidation)
//{
// ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//}
//// Make sure webpages:Enabled is true. Even though we set it in web.config, it could be overwritten by
//// an Azure AppSetting that's supposed to be for the site only but incidently affects Kudu as well.
ConfigurationManager.AppSettings["webpages:Enabled"] = "true";
//// Kudu does not rely owin:appStartup. This is to avoid Azure AppSetting if set.
if (ConfigurationManager.AppSettings?["owin:appStartup"] != null)
{
// Set the appSetting to null since we cannot use AppSettings.Remove(key) (ReadOnly exception!)
ConfigurationManager.AppSettings["owin:appStartup"] = null;
}
//RegisterRoutes(kernel, RouteTable.Routes);
//// Register the default hubs route: ~/signalr
//GlobalHost.DependencyResolver = new SignalRNinjectDependencyResolver(kernel);
//GlobalConfiguration.Configuration.Filters.Add(
// new TraceDeprecatedActionAttribute(
// kernel.Get<IAnalytics>(),
// kernel.Get<ITraceFactory>()));
//GlobalConfiguration.Configuration.Filters.Add(new EnsureRequestIdHandlerAttribute());
//FileTarget target = LogManager.Configuration.FindTargetByName("file") as FileTarget;
//String logfile = _webAppRuntimeEnvironment.LogFilesPath + "/.txt";
//target.FileName = logfile;
}
// CORE TODO See NinjectServices.Stop
// CORE TODO See signalr stuff in NinjectServices
private static Uri GetAbsoluteUri(HttpContext httpContext)
{
var request = httpContext.Request;
UriBuilder uriBuilder = new UriBuilder();
uriBuilder.Scheme = request.Scheme;
uriBuilder.Host = request.Host.Host;
uriBuilder.Path = request.Path.ToString();
uriBuilder.Query = request.QueryString.ToString();
return uriBuilder.Uri;
}
public void Configure(IApplicationBuilder app,
IApplicationLifetime applicationLifetime,
ILoggerFactory loggerFactory)
{
Console.WriteLine(@"Configure : " + DateTime.Now.ToString("hh.mm.ss.ffffff"));
loggerFactory.AddEventSourceLogger();
KuduWebUtil.MigrateToNetCorePatch(_webAppRuntimeEnvironment);
if (_hostingEnvironment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
if (_webAppRuntimeEnvironment.IsOnLinuxConsumption)
{
app.UseLinuxConsumptionRouteMiddleware();
}
var webSocketOptions = new WebSocketOptions()
{
KeepAliveInterval = TimeSpan.FromSeconds(15)
};
app.UseWebSockets(webSocketOptions);
var containsRelativePath = new Func<HttpContext, bool>(i =>
i.Request.Path.Value.StartsWith("/Default", StringComparison.OrdinalIgnoreCase));
app.MapWhen(containsRelativePath, application => application.Run(async context =>
{
await context.Response.WriteAsync("Kestrel Running");
}));
var containsRelativeProvisionPath = new Func<HttpContext, bool>(i =>
i.Request.Path.Value.StartsWith("/api/provision", StringComparison.OrdinalIgnoreCase));
app.UseTraceMiddleware();
if (K8SEDeploymentHelper.IsK8SEEnvironment())
{
app.UseKubeMiddleware();
}
app.MapWhen(containsRelativeProvisionPath, application => application.Run(async context =>
{
FileSystemHelpers.EnsureDirectory("/home/apps/"+context.Request.Path.Value.Replace("/api/provision/", ""));
FileSystemHelpers.EnsureDirectory("/home/apps/" + context.Request.Path.Value.Replace("/api/provision/", "")+"/site");
await context.Response.WriteAsync("App Provisioned");
}));
var containsRelativePath2 = new Func<HttpContext, bool>(i =>
i.Request.Path.Value.StartsWith("/info", StringComparison.OrdinalIgnoreCase));
app.MapWhen(containsRelativePath2,
application => application.Run(async context =>
{
await context.Response.WriteAsync("{\"Version\":\"" + Constants.KuduBuild + "\"}");
}));
app.UseResponseCompression();
var containsRelativePath3 = new Func<HttpContext, bool>(i =>
i.Request.Path.Value.StartsWith("/AppServiceTunnel/Tunnel.ashx", StringComparison.OrdinalIgnoreCase));
app.MapWhen(containsRelativePath3, builder => builder.UseMiddleware<DebugExtensionMiddleware>());
applicationLifetime.ApplicationStopping.Register(OnShutdown);
app.UseStaticFiles();
ProxyRequestIfRelativeUrlMatches(@"/webssh", "http", "127.0.0.1", KuduWebUtil.GetWebSSHProxyPort() , app);
var configuration = app.ApplicationServices.GetRequiredService<IServerConfiguration>();
// CORE TODO any equivalent for this? Needed?
//var configuration = kernel.Get<IServerConfiguration>();
//GlobalConfiguration.Configuration.Formatters.Clear();
//GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
var jsonFormatter = new JsonMediaTypeFormatter();
// CORE TODO concept of "deprecation" in routes for traces, Do we need this for linux ?
app.MapWhen(
c => c.Request.Path.ToString().EndsWith("/git-receive-pack", StringComparison.OrdinalIgnoreCase),
appBranch => appBranch.RunReceivePackHandler());
app.MapWhen(
c => c.Request.Path.ToString().EndsWith("/git-upload-pack", StringComparison.OrdinalIgnoreCase),
appBranch => appBranch.RunUploadPackHandler());
//app.MapWhen("/{repository}/git-upload-pack", appBranch => appBranch.RunUploadPackHandler());
// Push url
// Fetch hook
app.Map("/deploy", appBranch => appBranch.RunFetchHandler());
// Log streaming
app.Map("/api/logstream", appBranch => appBranch.RunLogStreamHandler());
// Clone url
// Custom GIT repositories, which can be served from any directory that has a git repo
// Sets up the file server to web app's wwwroot
KuduWebUtil.SetupFileServer(app, _webAppRuntimeEnvironment.WebRootPath, "/wwwroot");
// Sets up the file server to LogFiles
KuduWebUtil.SetupFileServer(app, Path.Combine(_webAppRuntimeEnvironment.LogFilesPath,"kudu","deployment"), "/deploymentlogs");
app.UseSwagger();
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Kudu API Docs"); });
app.UseMvc(routes =>
{
Console.WriteLine(@"Setting Up Routes : " + DateTime.Now.ToString("hh.mm.ss.ffffff"));
routes.MapRouteAnalyzer("/routes"); // Add
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
// Git Service
routes.MapRoute("git-info-refs", "/{repository}" + "/info/refs",
new {controller = "InfoRefs", action = "Execute"});
// Scm (deployment repository)
routes.MapHttpRouteDual("scm-info", "scm/info",
new {controller = "LiveScm", action = "GetRepositoryInfo"});
routes.MapHttpRouteDual("scm-clean", "scm/clean", new {controller = "LiveScm", action = "Clean"});
routes.MapHttpRouteDual("scm-delete", "scm", new {controller = "LiveScm", action = "Delete"},
new {verb = new HttpMethodRouteConstraint("DELETE")});
// Scm files editor
routes.MapHttpRouteDual("scm-get-files", "scmvfs/{*path}",
new {controller = "LiveScmEditor", action = "GetItem"},
new {verb = new HttpMethodRouteConstraint("GET", "HEAD")});
routes.MapHttpRouteDual("scm-put-files", "scmvfs/{*path}",
new {controller = "LiveScmEditor", action = "PutItem"},
new {verb = new HttpMethodRouteConstraint("PUT")});
routes.MapHttpRouteDual("scm-delete-files", "scmvfs/{*path}",
new {controller = "LiveScmEditor", action = "DeleteItem"},
new {verb = new HttpMethodRouteConstraint("DELETE")});
// Live files editor
routes.MapHttpRouteDual("vfs-get-files", "vfs/{*path}", new {controller = "Vfs", action = "GetItem"},
new {verb = new HttpMethodRouteConstraint("GET", "HEAD")});
routes.MapHttpRouteDual("vfs-put-files", "vfs/{*path}", new {controller = "Vfs", action = "PutItem"},
new {verb = new HttpMethodRouteConstraint("PUT")});
routes.MapHttpRouteDual("vfs-delete-files", "vfs/{*path}",
new {controller = "Vfs", action = "DeleteItem"},
new {verb = new HttpMethodRouteConstraint("DELETE")});
// Zip file handler
routes.MapHttpRouteDual("zip-get-files", "zip/{*path}", new {controller = "Zip", action = "GetItem"},
new {verb = new HttpMethodRouteConstraint("GET", "HEAD")});
routes.MapHttpRouteDual("zip-put-files", "zip/{*path}", new {controller = "Zip", action = "PutItem"},
new {verb = new HttpMethodRouteConstraint("PUT")});
// Zip push deployment
routes.MapRoute("zip-push-deploy", "api/zipdeploy",
new {controller = "PushDeployment", action = "ZipPushDeploy"},
new {verb = new HttpMethodRouteConstraint("POST")});
routes.MapRoute("zip-push-deploy-url", "api/zipdeploy",
new {controller = "PushDeployment", action = "ZipPushDeployViaUrl"},
new {verb = new HttpMethodRouteConstraint("PUT")});
routes.MapRoute("zip-war-deploy", "api/wardeploy",
new {controller = "PushDeployment", action = "WarPushDeploy"},
new {verb = new HttpMethodRouteConstraint("POST")});
routes.MapHttpRouteDual("onedeploy", "publish",
new { controller = "PushDeployment", action = "OneDeploy" });
// Support Linux Consumption Function app on Service Fabric Mesh
routes.MapRoute("admin-instance-info", "admin/instance/info",
new {controller = "LinuxConsumptionInstanceAdmin", action = "Info"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapRoute("admin-instance-assign", "admin/instance/assign",
new {controller = "LinuxConsumptionInstanceAdmin", action = "AssignAsync" },
new {verb = new HttpMethodRouteConstraint("POST")});
// Live Command Line
routes.MapHttpRouteDual("execute-command", "command",
new {controller = "Command", action = "ExecuteCommand"},
new {verb = new HttpMethodRouteConstraint("POST")});
// Deployments
routes.MapHttpRouteDual("all-deployments", "deployments",
new {controller = "Deployment", action = "GetDeployResults"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpRouteDual("one-deployment-get", "deployments/{id}",
new {controller = "Deployment", action = "GetResult"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpRouteDual("one-deployment-put", "deployments/{id?}",
new {controller = "Deployment", action = "Deploy"},
new {verb = new HttpMethodRouteConstraint("PUT")});
routes.MapHttpRouteDual("one-deployment-delete", "deployments/{id}",
new {controller = "Deployment", action = "Delete"},
new {verb = new HttpMethodRouteConstraint("DELETE")});
routes.MapHttpRouteDual("one-deployment-log", "deployments/{id}/log",
new {controller = "Deployment", action = "GetLogEntry"});
routes.MapHttpRouteDual("one-deployment-log-details", "deployments/{id}/log/{logId}",
new {controller = "Deployment", action = "GetLogEntryDetails"});
routes.MapHttpRouteDual("update-container-tag", "app/update",
new { controller = "Deployment", action = "UpdateContainerTag" });
// Deployment script
routes.MapRoute("get-deployment-script", "api/deploymentscript",
new {controller = "Deployment", action = "GetDeploymentScript"},
new {verb = new HttpMethodRouteConstraint("GET")});
// Revision script
routes.MapRoute("get-deployment-revision", "api/revisions/{appName}",
new { controller = "Revision", action = "GetMyRevisions" },
new { verb = new HttpMethodRouteConstraint("GET") });
// Revision script
routes.MapRoute("revert-deployment-revision", "api/revisions/redeploy/{appName}/{deploymentId}",
new { controller = "Revision", action = "RedployDeployemnt" },
new { verb = new HttpMethodRouteConstraint("GET") });
// IsDeploying status
routes.MapRoute("is-deployment-underway", "api/isdeploying",
new {controller = "Deployment", action = "IsDeploying"},
new {verb = new HttpMethodRouteConstraint("GET")});
// Initiate Scan
routes.MapRoute("start-clamscan", "api/scan/start/",
new { controller = "Scan", action = "ExecuteScan" },
new { verb = new HttpMethodRouteConstraint("GET") });
//Get scan status
routes.MapRoute("get-scan-status", "/api/scan/{scanId}/track",
new { controller = "Scan", action = "GetScanStatus" },
new { verb = new HttpMethodRouteConstraint("GET") });
//Get unique scan result
routes.MapRoute("get-scan-result", "/api/scan/{scanId}/result",
new { controller = "Scan", action = "GetScanLog" },
new { verb = new HttpMethodRouteConstraint("GET") });
//Get all scan result
routes.MapRoute("get-all-scan-result", "/api/scan/results",
new { controller = "Scan", action = "GetScanResults" },
new { verb = new HttpMethodRouteConstraint("GET") });
//Stop scan
routes.MapRoute("stop-scan", "/api/scan/stop",
new { controller = "Scan", action = "StopScan" },
new { verb = new HttpMethodRouteConstraint("DELETE") });
// SSHKey
routes.MapHttpRouteDual("get-sshkey", "api/sshkey",
new {controller = "SSHKey", action = "GetPublicKey"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpRouteDual("put-sshkey", "api/sshkey",
new {controller = "SSHKey", action = "SetPrivateKey"},
new {verb = new HttpMethodRouteConstraint("PUT")});
routes.MapHttpRouteDual("delete-sshkey", "api/sshkey",
new {controller = "SSHKey", action = "DeleteKeyPair"},
new {verb = new HttpMethodRouteConstraint("DELETE")});
// Environment
routes.MapHttpRouteDual("get-env", "environment", new {controller = "Environment", action = "Get"},
new {verb = new HttpMethodRouteConstraint("GET")});
// Settings
routes.MapHttpRouteDual("set-setting", "settings", new {controller = "Settings", action = "Set"},
new {verb = new HttpMethodRouteConstraint("POST")});
routes.MapHttpRouteDual("get-all-settings", "settings",
new {controller = "Settings", action = "GetAll"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpRouteDual("get-setting", "settings/{key}", new {controller = "Settings", action = "Get"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpRouteDual("delete-setting", "settings/{key}",
new {controller = "Settings", action = "Delete"},
new {verb = new HttpMethodRouteConstraint("DELETE")});
// Diagnostics
routes.MapHttpRouteDual("diagnostics", "dump", new {controller = "Diagnostics", action = "GetLog"});
routes.MapHttpRouteDual("diagnostics-set-setting", "diagnostics/settings",
new {controller = "Diagnostics", action = "Set"},
new {verb = new HttpMethodRouteConstraint("POST")});
routes.MapHttpRouteDual("diagnostics-get-all-settings", "diagnostics/settings",
new {controller = "Diagnostics", action = "GetAll"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpRouteDual("diagnostics-get-setting", "diagnostics/settings/{key}",
new {controller = "Diagnostics", action = "Get"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpRouteDual("diagnostics-delete-setting", "diagnostics/settings/{key}",
new {controller = "Diagnostics", action = "Delete"},
new {verb = new HttpMethodRouteConstraint("DELETE")});
// Logs
foreach (var url in new[] {"/logstream", "/logstream/{*path}"})
{
app.Map(url, appBranch => appBranch.RunLogStreamHandler());
}
routes.MapHttpRouteDual("recent-logs", "api/logs/recent",
new {controller = "Diagnostics", action = "GetRecentLogs"},
new {verb = new HttpMethodRouteConstraint("GET")});
// Enable these for Linux and Windows Containers.
if (!OSDetector.IsOnWindows() || (OSDetector.IsOnWindows() && EnvironmentHelper.IsWindowsContainers()))
{
routes.MapRoute("current-docker-logs-zip", "api/logs/docker/zip",
new {controller = "Diagnostics", action = "GetDockerLogsZip"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapRoute("current-docker-logs", "api/logs/docker",
new {controller = "Diagnostics", action = "GetDockerLogs"},
new {verb = new HttpMethodRouteConstraint("GET")});
}
var processControllerName = OSDetector.IsOnWindows() ? "Process" : "LinuxProcess";
// Processes
routes.MapHttpProcessesRoute("all-processes", "",
new {controller = processControllerName, action = "GetAllProcesses"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpProcessesRoute("one-process-get", "/{id}",
new {controller = processControllerName, action = "GetProcess"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpProcessesRoute("one-process-delete", "/{id}",
new {controller = processControllerName, action = "KillProcess"},
new {verb = new HttpMethodRouteConstraint("DELETE")});
routes.MapHttpProcessesRoute("one-process-dump", "/{id}/dump",
new {controller = processControllerName, action = "MiniDump"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpProcessesRoute("start-process-profile", "/{id}/profile/start",
new {controller = processControllerName, action = "StartProfileAsync"},
new {verb = new HttpMethodRouteConstraint("POST")});
routes.MapHttpProcessesRoute("stop-process-profile", "/{id}/profile/stop",
new {controller = processControllerName, action = "StopProfileAsync"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpProcessesRoute("all-threads", "/{id}/threads",
new {controller = processControllerName, action = "GetAllThreads"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpProcessesRoute("one-process-thread", "/{processId}/threads/{threadId}",
new {controller = processControllerName, action = "GetThread"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpProcessesRoute("all-modules", "/{id}/modules",
new {controller = processControllerName, action = "GetAllModules"},
new {verb = new HttpMethodRouteConstraint("GET")});
routes.MapHttpProcessesRoute("one-process-module", "/{id}/modules/{baseAddress}",
new {controller = processControllerName, action = "GetModule"},
new {verb = new HttpMethodRouteConstraint("GET")});
// Runtime
routes.MapHttpRouteDual("runtime", "diagnostics/runtime",
new {controller = "Runtime", action = "GetRuntimeVersions"},
new {verb = new HttpMethodRouteConstraint("GET")});
// Docker Hook Endpoint
if (!OSDetector.IsOnWindows() || (OSDetector.IsOnWindows() && EnvironmentHelper.IsWindowsContainers()))
{
routes.MapHttpRouteDual("docker", "docker/hook",
new {controller = "Docker", action = "ReceiveHook"},
new {verb = new HttpMethodRouteConstraint("POST")});
}
routes.MapHttpRouteDual("sync-function-triggers-put", "operations/settriggers",
new { controller = "Function", action = "SyncTrigger" },
new { verb = new HttpMethodRouteConstraint("PUT") });
// catch all unregistered url to properly handle not found
// routes.MapRoute("error-404", "{*path}", new {controller = "Error404", action = "Handle"});
});
Console.WriteLine(@"Exiting Configure : " + DateTime.Now.ToString("hh.mm.ss.ffffff"));
}
// <summary>
// Used for Reverse Proxying. Forwards a request to another path based on a
// relative path to Kestrel
// </summary>
// <param name="app">
// Object to configure an application's request pipeline.
// </param>
// <param name="relativeUrl">
// String is matched if the request URI path is prepended by it
// </param>
// <param name="scheme">
// A String that contains the scheme for the proxy URI
// </param>
// <param name="host">
// A String that contains the host for the proxy URI
// </param>
// <param name="port">
// A String that contains the host for the proxy URI. Cannot be null
// </param>
private static void ProxyRequestIfRelativeUrlMatches(
string relativeUrl,
string scheme,
string host,
string port,
IApplicationBuilder app)
{
var containsRelativePath = new Func<HttpContext, bool>(i =>
i.Request.Path.Value.StartsWith(relativeUrl, StringComparison.OrdinalIgnoreCase));
app.MapWhen(containsRelativePath, builder => builder.RunProxy(new ProxyOptions
{
Scheme = scheme,
Host = host,
Port = port
}));
}
// <summary>
// Returns a lambda function that checks if an incoming request object's url path
// is prepended by a string
// </summary>
// <param name="relativeUrl">
// String keyword with which incoming request's path is matched
// </param>
// <param name="httpContext">
// The HttpContext object of an incoming request
// </param>
private static Func<HttpContext, bool> ContainsRelativeUrl(string relativeUrl, HttpContext httpContext)
{
return x => httpContext.Request.Path.Value.StartsWith(relativeUrl, StringComparison.OrdinalIgnoreCase);
}
// <summary>
// Returns a lambda function that checks if an incoming request object's url path
// is prepended by a string
// </summary>
// <param name="relativeUrl">
// String keyword with which incoming request's path is matched
// </param>
// <param name="httpContext">
// The HttpContext object of an incoming request
// </param>
private void OnShutdown()
{
KuduWebUtil.TraceShutdown(_webAppRuntimeEnvironment, _noContextDeploymentsSettingsManager);
// Cleaning up deployment locks
Console.WriteLine(@"Removing Deployment Locks");
FileSystemHelpers.DeleteDirectorySafe("/home/site/locks/deployment");
Console.WriteLine(@"Shutting Down!");
}
}
}