Program.cs 26 KB

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