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