-
Notifications
You must be signed in to change notification settings - Fork 330
Expand file tree
/
Copy pathProgram.cs
More file actions
492 lines (443 loc) · 21.6 KB
/
Program.cs
File metadata and controls
492 lines (443 loc) · 21.6 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.CommandLine;
using System.CommandLine.Parsing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Azure.DataApiBuilder.Config;
using Azure.DataApiBuilder.Core.Telemetry;
using Azure.DataApiBuilder.Service.Exceptions;
using Azure.DataApiBuilder.Service.Telemetry;
using Azure.DataApiBuilder.Service.Utilities;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.ApplicationInsights;
using OpenTelemetry.Exporter;
using OpenTelemetry.Logs;
using OpenTelemetry.Resources;
using Serilog;
using Serilog.Core;
using Serilog.Extensions.Logging;
namespace Azure.DataApiBuilder.Service
{
public class Program
{
public static bool IsHttpsRedirectionDisabled { get; private set; }
public static DynamicLogLevelProvider LogLevelProvider = new();
public static void Main(string[] args)
{
bool runMcpStdio = McpStdioHelper.ShouldRunMcpStdio(args, out string? mcpRole);
if (runMcpStdio)
{
Console.OutputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
Console.InputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
}
if (!ValidateAspNetCoreUrls())
{
Console.Error.WriteLine("Invalid ASPNETCORE_URLS format. e.g.: ASPNETCORE_URLS=\"http://localhost:5000;https://localhost:5001\"");
Environment.ExitCode = -1;
return;
}
if (!StartEngine(args, runMcpStdio, mcpRole))
{
Environment.ExitCode = -1;
}
}
public static bool StartEngine(string[] args, bool runMcpStdio, string? mcpRole)
{
try
{
// Initialize log level EARLY, before building the host.
// This ensures logging filters are effective during the entire host build process.
LogLevel initialLogLevel = GetLogLevelFromCommandLineArgs(args, runMcpStdio, out bool isCliOverridden, out bool isConfigOverridden);
LogLevelProvider.SetInitialLogLevel(initialLogLevel, isCliOverridden, isConfigOverridden);
// For MCP stdio mode, redirect Console.Out to keep stdout clean for JSON-RPC.
// MCP SDK uses Console.OpenStandardOutput() which gets the real stdout, unaffected by this redirect.
if (runMcpStdio)
{
// When LogLevel.None, redirect to null stream for ZERO output.
// Otherwise redirect to stderr so logs don't pollute JSON-RPC.
if (initialLogLevel == LogLevel.None)
{
Console.SetOut(TextWriter.Null);
Console.SetError(TextWriter.Null);
}
else
{
Console.SetOut(Console.Error);
}
}
IHost host = CreateHostBuilder(args, runMcpStdio, mcpRole).Build();
if (runMcpStdio)
{
return McpStdioHelper.RunMcpStdioHost(host);
}
// Normal web mode
host.Run();
return true;
}
// Catch exception raised by explicit call to IHostApplicationLifetime.StopApplication()
catch (TaskCanceledException)
{
// Do not log the exception here because exceptions raised during startup
// are already automatically written to the console.
Console.Error.WriteLine("Unable to launch the Data API builder engine.");
return false;
}
// Catch all remaining unhandled exceptions which may be due to server host operation.
catch (Exception ex)
{
Console.Error.WriteLine($"Unable to launch the runtime due to: {ex}");
return false;
}
}
// Compatibility overload used by external callers that do not pass the runMcpStdio flag.
public static bool StartEngine(string[] args)
{
bool runMcpStdio = McpStdioHelper.ShouldRunMcpStdio(args, out string? mcpRole);
return StartEngine(args, runMcpStdio, mcpRole: mcpRole);
}
public static IHostBuilder CreateHostBuilder(string[] args, bool runMcpStdio, string? mcpRole)
{
return Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
AddConfigurationProviders(builder, args);
if (runMcpStdio)
{
McpStdioHelper.ConfigureMcpStdio(builder, mcpRole);
}
})
.ConfigureServices((context, services) =>
{
services.AddSingleton(LogLevelProvider);
services.AddSingleton<ILogLevelController>(LogLevelProvider);
})
.ConfigureLogging(logging =>
{
// Set minimum level at the framework level - this affects all loggers.
// For MCP stdio mode, Console.Out is redirected to stderr in Main(),
// so any logging output goes to stderr and doesn't pollute the JSON-RPC channel.
logging.SetMinimumLevel(LogLevelProvider.CurrentLogLevel);
// Add filter for dynamic log level changes (e.g., via MCP logging/setLevel)
logging.AddFilter(logLevel => LogLevelProvider.ShouldLog(logLevel));
})
.ConfigureWebHostDefaults(webBuilder =>
{
// LogLevelProvider was already initialized in StartEngine before CreateHostBuilder.
// Use the already-set values to avoid re-parsing args.
Startup.MinimumLogLevel = LogLevelProvider.CurrentLogLevel;
Startup.IsLogLevelOverriddenByCli = LogLevelProvider.IsCliOverridden;
ILoggerFactory loggerFactory = GetLoggerFactoryForLogLevel(Startup.MinimumLogLevel, stdio: runMcpStdio);
ILogger<Startup> startupLogger = loggerFactory.CreateLogger<Startup>();
DisableHttpsRedirectionIfNeeded(args);
webBuilder.UseStartup(builder => new Startup(builder.Configuration, startupLogger));
});
}
/// <summary>
/// Using System.CommandLine Parser to parse args and return
/// the correct log level. We save if there is a log level in args through
/// the out param. For log level out of range we throw an exception.
/// When in MCP stdio mode without explicit --LogLevel, defaults to None without CLI override.
/// </summary>
/// <param name="args">array that may contain log level information.</param>
/// <param name="runMcpStdio">whether running in MCP stdio mode.</param>
/// <param name="isLogLevelOverridenByCli">sets if log level is found in the args from CLI.</param>
/// <param name="isLogLevelOverridenByConfig">sets if log level came from config file.</param>
/// <returns>Appropriate log level.</returns>
private static LogLevel GetLogLevelFromCommandLineArgs(string[] args, bool runMcpStdio, out bool isLogLevelOverridenByCli, out bool isLogLevelOverridenByConfig)
{
Command cmd = new(name: "start");
Option<LogLevel> logLevelOption = new(name: "--LogLevel");
Option<bool> logLevelFromConfigOption = new(name: "--LogLevelFromConfig");
cmd.AddOption(logLevelOption);
cmd.AddOption(logLevelFromConfigOption);
ParseResult result = GetParseResult(cmd, args);
bool matchedToken = result.Tokens.Count - result.UnmatchedTokens.Count - result.UnparsedTokens.Count > 1;
// Check if --LogLevelFromConfig flag is present (indicates config override, not CLI)
bool isFromConfig = result.GetValueForOption(logLevelFromConfigOption);
LogLevel logLevel;
if (matchedToken)
{
logLevel = result.GetValueForOption(logLevelOption);
if (isFromConfig)
{
// Log level came from config file (passed by CLI with --LogLevelFromConfig marker)
isLogLevelOverridenByCli = false;
isLogLevelOverridenByConfig = true;
}
else
{
// User explicitly set --LogLevel via CLI (highest priority)
isLogLevelOverridenByCli = true;
isLogLevelOverridenByConfig = false;
}
}
else if (runMcpStdio)
{
// MCP stdio mode without explicit --LogLevel: default to None to keep stdout clean.
// This is NOT a CLI or config override, so MCP logging/setLevel can still change it.
logLevel = LogLevel.None;
isLogLevelOverridenByCli = false;
isLogLevelOverridenByConfig = false;
}
else
{
// Normal mode without explicit --LogLevel
logLevel = LogLevel.Error;
isLogLevelOverridenByCli = false;
isLogLevelOverridenByConfig = false;
}
if (logLevel is > LogLevel.None or < LogLevel.Trace)
{
throw new DataApiBuilderException(
message: $"LogLevel's valid range is 0 to 6, your value: {logLevel}, see: " +
$"https://learn.microsoft.com/dotnet/api/microsoft.extensions.logging.loglevel",
statusCode: System.Net.HttpStatusCode.ServiceUnavailable,
subStatusCode: DataApiBuilderException.SubStatusCodes.ErrorInInitialization);
}
return logLevel;
}
/// <summary>
/// Helper function returns ParseResult for a given command and
/// arguments.
/// </summary>
/// <param name="cmd">The command.</param>
/// <param name="args">The arguments.</param>
/// <returns>ParsedResult</returns>
private static ParseResult GetParseResult(Command cmd, string[] args)
{
CommandLineConfiguration cmdConfig = new(cmd);
Parser parser = new(cmdConfig);
return parser.Parse(args);
}
/// <summary>
/// Creates a LoggerFactory and add filter with the given LogLevel.
/// </summary>
/// <param name="logLevel">Minimum log level.</param>
/// <param name="appTelemetryClient">Telemetry client</param>
/// <param name="logLevelInitializer">Hot-reloadable log level</param>
/// <param name="serilogLogger">Core Serilog logging pipeline</param>
/// <param name="stdio">Whether the logger is for stdio mode</param>
/// <returns>ILoggerFactory</returns>
public static ILoggerFactory GetLoggerFactoryForLogLevel(
LogLevel logLevel,
TelemetryClient? appTelemetryClient = null,
LogLevelInitializer? logLevelInitializer = null,
Logger? serilogLogger = null,
bool stdio = false)
{
return LoggerFactory
.Create(builder =>
{
// Category defines the namespace we will log from,
// including all subdomains. ie: "Azure" includes
// "Azure.DataApiBuilder.Service"
if (logLevelInitializer is null)
{
builder.AddFilter(category: "Microsoft", logLevel => LogLevelProvider.ShouldLog(logLevel));
builder.AddFilter(category: "Azure", logLevel => LogLevelProvider.ShouldLog(logLevel));
builder.AddFilter(category: "Default", logLevel => LogLevelProvider.ShouldLog(logLevel));
}
else
{
builder.AddFilter(category: "Microsoft", level => level >= logLevelInitializer.MinLogLevel);
builder.AddFilter(category: "Azure", level => level >= logLevelInitializer.MinLogLevel);
builder.AddFilter(category: "Default", level => level >= logLevelInitializer.MinLogLevel);
}
// For Sending all the ILogger logs to Application Insights
if (Startup.AppInsightsOptions.Enabled && !string.IsNullOrWhiteSpace(Startup.AppInsightsOptions.ConnectionString))
{
builder.AddApplicationInsights(configureTelemetryConfiguration: (config) =>
{
config.ConnectionString = Startup.AppInsightsOptions.ConnectionString;
if (Startup.CustomTelemetryChannel is not null)
{
config.TelemetryChannel = Startup.CustomTelemetryChannel;
}
},
configureApplicationInsightsLoggerOptions: _ => { }
);
if (logLevelInitializer is null)
{
builder.AddFilter<ApplicationInsightsLoggerProvider>(category: string.Empty, logLevel);
}
else
{
builder.AddFilter<ApplicationInsightsLoggerProvider>(category: string.Empty, level => level >= logLevelInitializer.MinLogLevel);
}
}
if (Startup.OpenTelemetryOptions.Enabled
&& Uri.TryCreate(Startup.OpenTelemetryOptions.Endpoint, UriKind.Absolute, out Uri? otlpEndpoint))
{
builder.AddOpenTelemetry(logging =>
{
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
logging.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(Startup.OpenTelemetryOptions.ServiceName!));
logging.AddOtlpExporter(configure =>
{
configure.Endpoint = otlpEndpoint;
configure.Headers = Startup.OpenTelemetryOptions.Headers;
configure.Protocol = OtlpExportProtocol.Grpc;
});
});
}
if (Startup.IsAzureLogAnalyticsAvailable(Startup.AzureLogAnalyticsOptions))
{
builder.AddProvider(new AzureLogAnalyticsLoggerProvider(Startup.CustomLogCollector));
if (logLevelInitializer is null)
{
builder.AddFilter<AzureLogAnalyticsLoggerProvider>(category: string.Empty, logLevel);
}
else
{
builder.AddFilter<AzureLogAnalyticsLoggerProvider>(category: string.Empty, level => level >= logLevelInitializer.MinLogLevel);
}
}
if (Startup.FileSinkOptions.Enabled && serilogLogger is not null)
{
builder.AddSerilog(serilogLogger);
if (logLevelInitializer is null)
{
builder.AddFilter<SerilogLoggerProvider>(category: string.Empty, logLevel);
}
else
{
builder.AddFilter<SerilogLoggerProvider>(category: string.Empty, level => level >= logLevelInitializer.MinLogLevel);
}
}
// In stdio mode, route console logs to STDERR to keep STDOUT clean for MCP JSON
if (stdio)
{
builder.ClearProviders();
builder.AddConsole(options =>
{
options.LogToStandardErrorThreshold = LogLevel.Trace;
});
}
else
{
builder.AddConsole();
}
});
}
/// <summary>
/// Use CommandLine parser to check for the flag `--no-https-redirect`.
/// If it is present, https redirection is disabled.
/// By Default, it is enabled.
/// </summary>
/// <param name="args">array that may contain flag to disable https redirection.</param>
private static void DisableHttpsRedirectionIfNeeded(string[] args)
{
Command cmd = new(name: "start");
Option<string> httpsRedirectFlagOption = new(name: Startup.NO_HTTPS_REDIRECT_FLAG);
cmd.AddOption(httpsRedirectFlagOption);
ParseResult result = GetParseResult(cmd, args);
if (result.Tokens.Count - result.UnmatchedTokens.Count - result.UnparsedTokens.Count > 0)
{
Console.WriteLine("Redirecting to https is disabled.");
IsHttpsRedirectionDisabled = true;
return;
}
IsHttpsRedirectionDisabled = false;
}
// This is used for testing purposes only. The test web server takes in a
// IWebHostBuilder, instead of a IHostBuilder.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost
.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((_, builder) =>
{
AddConfigurationProviders(builder, args);
DisableHttpsRedirectionIfNeeded(args);
})
.UseStartup<Startup>();
// This is used for testing purposes only. The test web server takes in a
// IWebHostBuilder, instead of a IHostBuilder.
public static IWebHostBuilder CreateWebHostFromInMemoryUpdatableConfBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
/// <summary>
/// Adds the various configuration providers.
/// </summary>
/// <param name="configurationBuilder">The configuration builder.</param>
/// <param name="args">The command line arguments.</param>
private static void AddConfigurationProviders(
IConfigurationBuilder configurationBuilder,
string[] args)
{
configurationBuilder
.AddEnvironmentVariables(prefix: FileSystemRuntimeConfigLoader.ENVIRONMENT_PREFIX)
.AddCommandLine(args);
}
/// <summary>
/// Validates the URLs specified in the ASPNETCORE_URLS environment variable.
/// Ensures that each URL is valid and properly formatted.
/// </summary>
internal static bool ValidateAspNetCoreUrls()
{
if (Environment.GetEnvironmentVariable("ASPNETCORE_URLS") is not { } urls)
{
return true; // If the environment variable is missing, then it cannot be invalid.
}
if (string.IsNullOrWhiteSpace(urls))
{
return false;
}
char[] separators = [';', ',', ' '];
string[] urlList = urls.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (string url in urlList)
{
if (IsUnixDomainSocketUrl(url))
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || !ValidateUnixDomainSocketUrl(url))
{
return false;
}
continue;
}
string testUrl = ReplaceWildcardHost(url);
if (!CheckSanityOfUrl(testUrl))
{
return false;
}
}
return true;
static bool IsUnixDomainSocketUrl(string url) =>
Regex.IsMatch(url, @"^https?://unix:", RegexOptions.IgnoreCase);
static bool ValidateUnixDomainSocketUrl(string url) =>
Regex.IsMatch(url, @"^https?://unix:/\S+");
static string ReplaceWildcardHost(string url) =>
Regex.Replace(url, @"^(https?://)[\+\*]", "$1localhost", RegexOptions.IgnoreCase);
}
public static bool CheckSanityOfUrl(string uri)
{
if (!Uri.TryCreate(uri, UriKind.Absolute, out Uri? parsedUri))
{
return false;
}
// Only allow HTTP or HTTPS schemes
if (parsedUri.Scheme != Uri.UriSchemeHttp && parsedUri.Scheme != Uri.UriSchemeHttps)
{
return false;
}
// Disallow empty hostnames
if (string.IsNullOrWhiteSpace(parsedUri.Host))
{
return false;
}
return true;
}
}
}