Program.cs 25 KB

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