Program.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using CommandLine;
  13. using Emby.Drawing;
  14. using Emby.Server.Implementations;
  15. using Emby.Server.Implementations.HttpServer;
  16. using Emby.Server.Implementations.IO;
  17. using Emby.Server.Implementations.Networking;
  18. using Jellyfin.Drawing.Skia;
  19. using MediaBrowser.Common.Configuration;
  20. using MediaBrowser.Controller.Drawing;
  21. using MediaBrowser.Controller.Extensions;
  22. using MediaBrowser.WebDashboard.Api;
  23. using Microsoft.AspNetCore.Hosting;
  24. using Microsoft.Extensions.Configuration;
  25. using Microsoft.Extensions.DependencyInjection;
  26. using Microsoft.Extensions.DependencyInjection.Extensions;
  27. using Microsoft.Extensions.Logging;
  28. using Microsoft.Extensions.Logging.Abstractions;
  29. using Serilog;
  30. using Serilog.Extensions.Logging;
  31. using SQLitePCL;
  32. using ILogger = Microsoft.Extensions.Logging.ILogger;
  33. namespace Jellyfin.Server
  34. {
  35. /// <summary>
  36. /// Class containing the entry point of the application.
  37. /// </summary>
  38. public static class Program
  39. {
  40. /// <summary>
  41. /// The name of logging configuration file containing application defaults.
  42. /// </summary>
  43. public static readonly string LoggingConfigFileDefault = "logging.default.json";
  44. /// <summary>
  45. /// The name of the logging configuration file containing the system-specific override settings.
  46. /// </summary>
  47. public static readonly string LoggingConfigFileSystem = "logging.json";
  48. private static readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
  49. private static readonly ILoggerFactory _loggerFactory = new SerilogLoggerFactory();
  50. private static ILogger _logger = NullLogger.Instance;
  51. private static bool _restartOnShutdown;
  52. /// <summary>
  53. /// The entry point of the application.
  54. /// </summary>
  55. /// <param name="args">The command line arguments passed.</param>
  56. /// <returns><see cref="Task" />.</returns>
  57. public static Task Main(string[] args)
  58. {
  59. // For backwards compatibility.
  60. // Modify any input arguments now which start with single-hyphen to POSIX standard
  61. // double-hyphen to allow parsing by CommandLineParser package.
  62. const string Pattern = @"^(-[^-\s]{2})"; // Match -xx, not -x, not --xx, not xx
  63. const string Substitution = @"-$1"; // Prepend with additional single-hyphen
  64. var regex = new Regex(Pattern);
  65. for (var i = 0; i < args.Length; i++)
  66. {
  67. args[i] = regex.Replace(args[i], Substitution);
  68. }
  69. // Parse the command line arguments and either start the app or exit indicating error
  70. return Parser.Default.ParseArguments<StartupOptions>(args)
  71. .MapResult(StartApp, _ => Task.CompletedTask);
  72. }
  73. /// <summary>
  74. /// Shuts down the application.
  75. /// </summary>
  76. internal static void Shutdown()
  77. {
  78. if (!_tokenSource.IsCancellationRequested)
  79. {
  80. _tokenSource.Cancel();
  81. }
  82. }
  83. /// <summary>
  84. /// Restarts the application.
  85. /// </summary>
  86. internal static void Restart()
  87. {
  88. _restartOnShutdown = true;
  89. Shutdown();
  90. }
  91. private static async Task StartApp(StartupOptions options)
  92. {
  93. var stopWatch = new Stopwatch();
  94. stopWatch.Start();
  95. // Log all uncaught exceptions to std error
  96. static void UnhandledExceptionToConsole(object sender, UnhandledExceptionEventArgs e) =>
  97. Console.Error.WriteLine("Unhandled Exception\n" + e.ExceptionObject.ToString());
  98. AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionToConsole;
  99. ServerApplicationPaths appPaths = CreateApplicationPaths(options);
  100. // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
  101. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
  102. await InitLoggingConfigFile(appPaths).ConfigureAwait(false);
  103. // Create an instance of the application configuration to use for application startup
  104. IConfiguration startupConfig = CreateAppConfiguration(options, appPaths);
  105. // Initialize logging framework
  106. InitializeLoggingFramework(startupConfig, appPaths);
  107. _logger = _loggerFactory.CreateLogger("Main");
  108. // Log uncaught exceptions to the logging instead of std error
  109. AppDomain.CurrentDomain.UnhandledException -= UnhandledExceptionToConsole;
  110. AppDomain.CurrentDomain.UnhandledException += (sender, e)
  111. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
  112. // Intercept Ctrl+C and Ctrl+Break
  113. Console.CancelKeyPress += (sender, e) =>
  114. {
  115. if (_tokenSource.IsCancellationRequested)
  116. {
  117. return; // Already shutting down
  118. }
  119. e.Cancel = true;
  120. _logger.LogInformation("Ctrl+C, shutting down");
  121. Environment.ExitCode = 128 + 2;
  122. Shutdown();
  123. };
  124. // Register a SIGTERM handler
  125. AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
  126. {
  127. if (_tokenSource.IsCancellationRequested)
  128. {
  129. return; // Already shutting down
  130. }
  131. _logger.LogInformation("Received a SIGTERM signal, shutting down");
  132. Environment.ExitCode = 128 + 15;
  133. Shutdown();
  134. };
  135. _logger.LogInformation(
  136. "Jellyfin version: {Version}",
  137. Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3));
  138. ApplicationHost.LogEnvironmentInfo(_logger, appPaths);
  139. // Make sure we have all the code pages we can get
  140. // Ref: https://docs.microsoft.com/en-us/dotnet/api/system.text.codepagesencodingprovider.instance?view=netcore-3.0#remarks
  141. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  142. // Increase the max http request limit
  143. // The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.
  144. ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
  145. // Disable the "Expect: 100-Continue" header by default
  146. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  147. ServicePointManager.Expect100Continue = false;
  148. Batteries_V2.Init();
  149. if (raw.sqlite3_enable_shared_cache(1) != raw.SQLITE_OK)
  150. {
  151. _logger.LogWarning("Failed to enable shared cache for SQLite");
  152. }
  153. var appHost = new CoreAppHost(
  154. appPaths,
  155. _loggerFactory,
  156. options,
  157. new ManagedFileSystem(_loggerFactory.CreateLogger<ManagedFileSystem>(), appPaths),
  158. GetImageEncoder(appPaths),
  159. new NetworkManager(_loggerFactory.CreateLogger<NetworkManager>()));
  160. try
  161. {
  162. // If hosting the web client, validate the client content path
  163. if (startupConfig.HostWebClient())
  164. {
  165. string webContentPath = DashboardService.GetDashboardUIPath(startupConfig, appHost.ServerConfigurationManager);
  166. if (!Directory.Exists(webContentPath) || Directory.GetFiles(webContentPath).Length == 0)
  167. {
  168. throw new InvalidOperationException(
  169. "The server is expected to host the web client, but the provided content directory is either " +
  170. $"invalid or empty: {webContentPath}. If you do not want to host the web client with the " +
  171. "server, you may set the '--nowebclient' command line flag, or set" +
  172. $"'{MediaBrowser.Controller.Extensions.ConfigurationExtensions.HostWebClientKey}=false' in your config settings.");
  173. }
  174. }
  175. ServiceCollection serviceCollection = new ServiceCollection();
  176. await appHost.InitAsync(serviceCollection, startupConfig).ConfigureAwait(false);
  177. var webHost = CreateWebHostBuilder(appHost, serviceCollection, options, startupConfig, appPaths).Build();
  178. // Re-use the web host service provider in the app host since ASP.NET doesn't allow a custom service collection.
  179. appHost.ServiceProvider = webHost.Services;
  180. appHost.InitializeServices();
  181. appHost.FindParts();
  182. Migrations.MigrationRunner.Run(appHost, _loggerFactory);
  183. try
  184. {
  185. await webHost.StartAsync().ConfigureAwait(false);
  186. }
  187. catch
  188. {
  189. _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in system.xml and try again.");
  190. throw;
  191. }
  192. await appHost.RunStartupTasksAsync().ConfigureAwait(false);
  193. stopWatch.Stop();
  194. _logger.LogInformation("Startup complete {Time:g}", stopWatch.Elapsed);
  195. // Block main thread until shutdown
  196. await Task.Delay(-1, _tokenSource.Token).ConfigureAwait(false);
  197. }
  198. catch (TaskCanceledException)
  199. {
  200. // Don't throw on cancellation
  201. }
  202. catch (Exception ex)
  203. {
  204. _logger.LogCritical(ex, "Error while starting server.");
  205. }
  206. finally
  207. {
  208. appHost?.Dispose();
  209. }
  210. if (_restartOnShutdown)
  211. {
  212. StartNewInstance(options);
  213. }
  214. }
  215. private static IWebHostBuilder CreateWebHostBuilder(
  216. ApplicationHost appHost,
  217. IServiceCollection serviceCollection,
  218. StartupOptions commandLineOpts,
  219. IConfiguration startupConfig,
  220. IApplicationPaths appPaths)
  221. {
  222. return new WebHostBuilder()
  223. .UseKestrel(options =>
  224. {
  225. var addresses = appHost.ServerConfigurationManager
  226. .Configuration
  227. .LocalNetworkAddresses
  228. .Select(appHost.NormalizeConfiguredLocalAddress)
  229. .Where(i => i != null)
  230. .ToList();
  231. if (addresses.Any())
  232. {
  233. foreach (var address in addresses)
  234. {
  235. _logger.LogInformation("Kestrel listening on {IpAddress}", address);
  236. options.Listen(address, appHost.HttpPort);
  237. if (appHost.EnableHttps && appHost.Certificate != null)
  238. {
  239. options.Listen(
  240. address,
  241. appHost.HttpsPort,
  242. listenOptions => listenOptions.UseHttps(appHost.Certificate));
  243. }
  244. }
  245. }
  246. else
  247. {
  248. _logger.LogInformation("Kestrel listening on all interfaces");
  249. options.ListenAnyIP(appHost.HttpPort);
  250. if (appHost.EnableHttps && appHost.Certificate != null)
  251. {
  252. options.ListenAnyIP(
  253. appHost.HttpsPort,
  254. listenOptions => listenOptions.UseHttps(appHost.Certificate));
  255. }
  256. }
  257. })
  258. .ConfigureAppConfiguration(config => config.ConfigureAppConfiguration(commandLineOpts, appPaths, startupConfig))
  259. .UseSerilog()
  260. .ConfigureServices(services =>
  261. {
  262. // Merge the external ServiceCollection into ASP.NET DI
  263. services.TryAdd(serviceCollection);
  264. })
  265. .UseStartup<Startup>();
  266. }
  267. /// <summary>
  268. /// Create the data, config and log paths from the variety of inputs(command line args,
  269. /// environment variables) or decide on what default to use. For Windows it's %AppPath%
  270. /// for everything else the
  271. /// <a href="https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG approach</a>
  272. /// is followed.
  273. /// </summary>
  274. /// <param name="options">The <see cref="StartupOptions" /> for this instance.</param>
  275. /// <returns><see cref="ServerApplicationPaths" />.</returns>
  276. private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options)
  277. {
  278. // dataDir
  279. // IF --datadir
  280. // ELSE IF $JELLYFIN_DATA_DIR
  281. // ELSE IF windows, use <%APPDATA%>/jellyfin
  282. // ELSE IF $XDG_DATA_HOME then use $XDG_DATA_HOME/jellyfin
  283. // ELSE use $HOME/.local/share/jellyfin
  284. var dataDir = options.DataDir;
  285. if (string.IsNullOrEmpty(dataDir))
  286. {
  287. dataDir = Environment.GetEnvironmentVariable("JELLYFIN_DATA_DIR");
  288. if (string.IsNullOrEmpty(dataDir))
  289. {
  290. // LocalApplicationData follows the XDG spec on unix machines
  291. dataDir = Path.Combine(
  292. Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  293. "jellyfin");
  294. }
  295. }
  296. // configDir
  297. // IF --configdir
  298. // ELSE IF $JELLYFIN_CONFIG_DIR
  299. // ELSE IF --datadir, use <datadir>/config (assume portable run)
  300. // ELSE IF <datadir>/config exists, use that
  301. // ELSE IF windows, use <datadir>/config
  302. // ELSE IF $XDG_CONFIG_HOME use $XDG_CONFIG_HOME/jellyfin
  303. // ELSE $HOME/.config/jellyfin
  304. var configDir = options.ConfigDir;
  305. if (string.IsNullOrEmpty(configDir))
  306. {
  307. configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
  308. if (string.IsNullOrEmpty(configDir))
  309. {
  310. if (options.DataDir != null
  311. || Directory.Exists(Path.Combine(dataDir, "config"))
  312. || RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  313. {
  314. // Hang config folder off already set dataDir
  315. configDir = Path.Combine(dataDir, "config");
  316. }
  317. else
  318. {
  319. // $XDG_CONFIG_HOME defines the base directory relative to which
  320. // user specific configuration files should be stored.
  321. configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
  322. // If $XDG_CONFIG_HOME is either not set or empty,
  323. // a default equal to $HOME /.config should be used.
  324. if (string.IsNullOrEmpty(configDir))
  325. {
  326. configDir = Path.Combine(
  327. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  328. ".config");
  329. }
  330. configDir = Path.Combine(configDir, "jellyfin");
  331. }
  332. }
  333. }
  334. // cacheDir
  335. // IF --cachedir
  336. // ELSE IF $JELLYFIN_CACHE_DIR
  337. // ELSE IF windows, use <datadir>/cache
  338. // ELSE IF XDG_CACHE_HOME, use $XDG_CACHE_HOME/jellyfin
  339. // ELSE HOME/.cache/jellyfin
  340. var cacheDir = options.CacheDir;
  341. if (string.IsNullOrEmpty(cacheDir))
  342. {
  343. cacheDir = Environment.GetEnvironmentVariable("JELLYFIN_CACHE_DIR");
  344. if (string.IsNullOrEmpty(cacheDir))
  345. {
  346. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  347. {
  348. // Hang cache folder off already set dataDir
  349. cacheDir = Path.Combine(dataDir, "cache");
  350. }
  351. else
  352. {
  353. // $XDG_CACHE_HOME defines the base directory relative to which
  354. // user specific non-essential data files should be stored.
  355. cacheDir = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
  356. // If $XDG_CACHE_HOME is either not set or empty,
  357. // a default equal to $HOME/.cache should be used.
  358. if (string.IsNullOrEmpty(cacheDir))
  359. {
  360. cacheDir = Path.Combine(
  361. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
  362. ".cache");
  363. }
  364. cacheDir = Path.Combine(cacheDir, "jellyfin");
  365. }
  366. }
  367. }
  368. // webDir
  369. // IF --webdir
  370. // ELSE IF $JELLYFIN_WEB_DIR
  371. // ELSE <bindir>/jellyfin-web
  372. var webDir = options.WebDir;
  373. if (string.IsNullOrEmpty(webDir))
  374. {
  375. webDir = Environment.GetEnvironmentVariable("JELLYFIN_WEB_DIR");
  376. if (string.IsNullOrEmpty(webDir))
  377. {
  378. // Use default location under ResourcesPath
  379. webDir = Path.Combine(AppContext.BaseDirectory, "jellyfin-web");
  380. }
  381. }
  382. // logDir
  383. // IF --logdir
  384. // ELSE IF $JELLYFIN_LOG_DIR
  385. // ELSE IF --datadir, use <datadir>/log (assume portable run)
  386. // ELSE <datadir>/log
  387. var logDir = options.LogDir;
  388. if (string.IsNullOrEmpty(logDir))
  389. {
  390. logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  391. if (string.IsNullOrEmpty(logDir))
  392. {
  393. // Hang log folder off already set dataDir
  394. logDir = Path.Combine(dataDir, "log");
  395. }
  396. }
  397. // Ensure the main folders exist before we continue
  398. try
  399. {
  400. Directory.CreateDirectory(dataDir);
  401. Directory.CreateDirectory(logDir);
  402. Directory.CreateDirectory(configDir);
  403. Directory.CreateDirectory(cacheDir);
  404. }
  405. catch (IOException ex)
  406. {
  407. Console.Error.WriteLine("Error whilst attempting to create folder");
  408. Console.Error.WriteLine(ex.ToString());
  409. Environment.Exit(1);
  410. }
  411. return new ServerApplicationPaths(dataDir, logDir, configDir, cacheDir, webDir);
  412. }
  413. /// <summary>
  414. /// Initialize the logging configuration file using the bundled resource file as a default if it doesn't exist
  415. /// already.
  416. /// </summary>
  417. private static async Task InitLoggingConfigFile(IApplicationPaths appPaths)
  418. {
  419. // Do nothing if the config file already exists
  420. string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, LoggingConfigFileDefault);
  421. if (File.Exists(configPath))
  422. {
  423. return;
  424. }
  425. // Get a stream of the resource contents
  426. // NOTE: The .csproj name is used instead of the assembly name in the resource path
  427. const string ResourcePath = "Jellyfin.Server.Resources.Configuration.logging.json";
  428. await using Stream? resource = typeof(Program).Assembly.GetManifestResourceStream(ResourcePath)
  429. ?? throw new InvalidOperationException($"Invalid resource path: '{ResourcePath}'");
  430. // Copy the resource contents to the expected file path for the config file
  431. await using Stream dst = File.Open(configPath, FileMode.CreateNew);
  432. await resource.CopyToAsync(dst).ConfigureAwait(false);
  433. }
  434. private static IConfiguration CreateAppConfiguration(StartupOptions commandLineOpts, IApplicationPaths appPaths)
  435. {
  436. return new ConfigurationBuilder()
  437. .ConfigureAppConfiguration(commandLineOpts, appPaths)
  438. .Build();
  439. }
  440. private static IConfigurationBuilder ConfigureAppConfiguration(
  441. this IConfigurationBuilder config,
  442. StartupOptions commandLineOpts,
  443. IApplicationPaths appPaths,
  444. IConfiguration? startupConfig = null)
  445. {
  446. // Use the swagger API page as the default redirect path if not hosting the web client
  447. var inMemoryDefaultConfig = ConfigurationOptions.DefaultConfiguration;
  448. if (startupConfig != null && !startupConfig.HostWebClient())
  449. {
  450. inMemoryDefaultConfig[HttpListenerHost.DefaultRedirectKey] = "swagger/index.html";
  451. }
  452. return config
  453. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  454. .AddInMemoryCollection(inMemoryDefaultConfig)
  455. .AddJsonFile(LoggingConfigFileDefault, optional: false, reloadOnChange: true)
  456. .AddJsonFile(LoggingConfigFileSystem, optional: true, reloadOnChange: true)
  457. .AddEnvironmentVariables("JELLYFIN_")
  458. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  459. }
  460. /// <summary>
  461. /// Initialize Serilog using configuration and fall back to defaults on failure.
  462. /// </summary>
  463. private static void InitializeLoggingFramework(IConfiguration configuration, IApplicationPaths appPaths)
  464. {
  465. try
  466. {
  467. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  468. Serilog.Log.Logger = new LoggerConfiguration()
  469. .ReadFrom.Configuration(configuration)
  470. .Enrich.FromLogContext()
  471. .Enrich.WithThreadId()
  472. .CreateLogger();
  473. }
  474. catch (Exception ex)
  475. {
  476. Serilog.Log.Logger = new LoggerConfiguration()
  477. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}")
  478. .WriteTo.Async(x => x.File(
  479. Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
  480. rollingInterval: RollingInterval.Day,
  481. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}"))
  482. .Enrich.FromLogContext()
  483. .Enrich.WithThreadId()
  484. .CreateLogger();
  485. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  486. }
  487. }
  488. private static IImageEncoder GetImageEncoder(IApplicationPaths appPaths)
  489. {
  490. try
  491. {
  492. // Test if the native lib is available
  493. SkiaEncoder.TestSkia();
  494. return new SkiaEncoder(
  495. _loggerFactory.CreateLogger<SkiaEncoder>(),
  496. appPaths);
  497. }
  498. catch (Exception ex)
  499. {
  500. _logger.LogWarning(ex, $"Skia not available. Will fallback to {nameof(NullImageEncoder)}.");
  501. }
  502. return new NullImageEncoder();
  503. }
  504. private static void StartNewInstance(StartupOptions options)
  505. {
  506. _logger.LogInformation("Starting new instance");
  507. var module = options.RestartPath;
  508. if (string.IsNullOrWhiteSpace(module))
  509. {
  510. module = Environment.GetCommandLineArgs()[0];
  511. }
  512. string commandLineArgsString;
  513. if (options.RestartArgs != null)
  514. {
  515. commandLineArgsString = options.RestartArgs ?? string.Empty;
  516. }
  517. else
  518. {
  519. commandLineArgsString = string.Join(
  520. ' ',
  521. Environment.GetCommandLineArgs().Skip(1).Select(NormalizeCommandLineArgument));
  522. }
  523. _logger.LogInformation("Executable: {0}", module);
  524. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  525. Process.Start(module, commandLineArgsString);
  526. }
  527. private static string NormalizeCommandLineArgument(string arg)
  528. {
  529. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  530. {
  531. return arg;
  532. }
  533. return "\"" + arg + "\"";
  534. }
  535. }
  536. }