Program.cs 25 KB

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