private async Task <int> Run(HostCommandContext context, string pipeName, long maxMemory, int affinityMask, int maxCpu) { var currentProcess = SDProcess.GetCurrentProcess(); var logger = context.ServiceProvider.GetService <ILoggerFactory>().CreateLogger <HostProcessImpl>(); logger.HostProcessStart(currentProcess.Id); string name = "pihost." + currentProcess.Id; var limits = new IsolationLimits(maxMemory, maxCpu, affinityMask); if (limits.IsAnyEnabled) { s_jobObject = new JobObject(name); s_jobObject.AddProcess(currentProcess); s_jobObject.Enable(limits, (l, v) => logger.ProcessLimitSet(l, v)); } var host = new IpcServiceHostBuilder(context.ServiceProvider) .AddNamedPipeEndpoint <IHostProcess>(name, pipeName, includeFailureDetailsInResponse: true) .Build(); logger.IpcServiceHostStarting(pipeName); context.SetStartComplete(); await host.RunAsync(context.Token).ConfigureAwait(false); return(0); }
/// <inheritdoc /> public Task StartAsync(CancellationToken cancellationToken) { if (_taskInformation != null) { throw new InvalidOperationException("Start called twice."); } var appLifetime = _serviceProvider.GetRequiredService <IHostApplicationLifetime>(); var ipcServiceHost = new IpcServiceHostBuilder(_serviceProvider) .AddNamedPipeEndpoint <Api.IFtpServerHost>("ftpserver", "ftpserver") .Build(); _taskInformation = new TaskInformation(appLifetime, ipcServiceHost); return(Task.CompletedTask); }
static void Main(string[] args) { // configure DI IServiceCollection services = ConfigureServices(new ServiceCollection()); // build and run service host IIpcServiceHost host = new IpcServiceHostBuilder(services.BuildServiceProvider()) .AddNamedPipeEndpoint <IComputingService>("computingEndpoint", "pipeName") .AddTcpEndpoint <ISystemService>("systemEndpoint", IPAddress.Loopback, 45684) .Build(); var source = new CancellationTokenSource(); Task.WaitAll(host.RunAsync(source.Token), Task.Run(() => { Console.WriteLine("Press any key to shutdown."); Console.ReadKey(); source.Cancel(); })); }
public static async Task Main() { // configure DI var services = ConfigureServices(new ServiceCollection()); // build and run service host var host = new IpcServiceHostBuilder(services.BuildServiceProvider()) .AddTcpEndpoint <IExecutionService>(name: "endpoint2", ipEndpoint: IPAddress.Loopback, port: SharedSettings.PortNumber) .Build(); Console.WriteLine("CodeGolf execution service"); var source = new CancellationTokenSource(); await Task.WhenAll(host.RunAsync(source.Token), Task.Run(() => { Console.WriteLine("Press any key to shutdown."); Console.ReadKey(); source.Cancel(); })); Console.WriteLine("Server stopped."); }
private static async Task <int> Main(string[] args) { var configPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "SharpFtpServer"); NLog.LogManager.LoadConfiguration("NLog.config"); var hostBuilder = new HostBuilder() .UseConsoleLifetime() .ConfigureHostConfiguration( configHost => { configHost.AddEnvironmentVariables("FTPSERVER_"); }) .ConfigureAppConfiguration( (hostContext, configApp) => { configApp .AddJsonFile("appsettings.json") .AddJsonFile(Path.Combine(configPath, "appsettings.json"), true) .AddJsonFile( $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true) .AddJsonFile( Path.Combine( configPath, $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json"), optional: true) .AddEnvironmentVariables("FTPSERVER_") .Add(new OptionsConfigSource(args)); }) .ConfigureLogging( (hostContext, loggingBuilder) => { loggingBuilder.ClearProviders(); }) .ConfigureServices( (hostContext, services) => { var options = hostContext.Configuration.Get <FtpOptions>(); options.Validate(); services .AddLogging(cfg => cfg.SetMinimumLevel(LogLevel.Trace)) .AddOptions() .AddFtpServices(options) .AddHostedService <HostedFtpService>() .AddIpc( builder => { builder .AddNamedPipe(opt => opt.ThreadCount = 1) .AddService <Api.IFtpServerHost, FtpServerHostApi>(); }); }) .UseNLog( new NLogAspNetCoreOptions() { CaptureMessageTemplates = true, CaptureMessageProperties = true, }); try { using (var host = hostBuilder.Build()) { var appLifetime = host.Services.GetRequiredService <IApplicationLifetime>(); var ipcServiceHost = new IpcServiceHostBuilder(host.Services) .AddNamedPipeEndpoint <Api.IFtpServerHost>("ftpserver", "ftpserver") .Build(); // Catch request to stop the application var appStopCts = new CancellationTokenSource(); using (appLifetime.ApplicationStopping.Register(() => appStopCts.Cancel())) { // Start the host await host.StartAsync(appStopCts.Token).ConfigureAwait(false); // Run the shell await ipcServiceHost.RunAsync(appStopCts.Token) .ConfigureAwait(false); // Ignore. Shell not available? await host.WaitForShutdownAsync(CancellationToken.None).ConfigureAwait(false); } } } catch (Exception ex) { Console.Error.WriteLine(ex); return(1); } return(0); }
public static async Task Main(string[] args) { var host = new HostBuilder() .ConfigureHostConfiguration(configHost => { #region Host环境设置 configHost.SetBasePath(Directory.GetCurrentDirectory()); configHost.AddJsonFile("hostsettings.json", optional: true); configHost.AddEnvironmentVariables(prefix: "PREFIX_"); configHost.AddCommandLine(args); #endregion }) .ConfigureAppConfiguration((hostContext, configApp) => { #region 序配置 configApp.AddJsonFile("appsettings.json", optional: true); configApp.AddJsonFile( $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); configApp.AddEnvironmentVariables(prefix: "PREFIX_"); configApp.AddCommandLine(args); #endregion }) .ConfigureServices((hostContext, services) => { //程序都在这里注入 #region IRepository var infrastructureAssembly = Assembly.Load("ManjuuInfrastructure"); var repositoryTypes = infrastructureAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(IRepository).IsAssignableFrom(p)); foreach (var item in repositoryTypes) { foreach (var itemIntface in item.GetInterfaces()) { if (typeof(IRepository) == itemIntface) { continue; } services.AddSingleton(itemIntface, item); } } #endregion #region ICustomLog var commonAssembly = Assembly.Load("ManjuuCommon"); var customLogTypes = commonAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(ICustomLog <NLog.ILogger>).IsAssignableFrom(p)); foreach (var item in customLogTypes) { foreach (var itemIntface in item.GetInterfaces()) { if (typeof(ICustomLog <NLog.ILogger>) == itemIntface) { continue; } services.AddSingleton(itemIntface, item); } } #endregion #region IApplication var applicationAssembly = Assembly.Load("ManjuuApplications"); var applicationTypes = applicationAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(IApplication).IsAssignableFrom(p)); foreach (var item in applicationTypes) { foreach (var itemIntface in item.GetInterfaces()) { if (typeof(IApplication) == itemIntface) { continue; } //同一个请求下单例 services.AddScoped(itemIntface, item); } } #endregion #region Quartz.Net services.AddSingleton <ISchedulerFactory, StdSchedulerFactory>(); //注册ISchedulerFactory的实例。 #endregion #region Ipc services.AddLogging(l => { l.AddConsole(); l.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug); }) .AddIpc(action => { action.AddNamedPipe(pipeOpt => { pipeOpt.ThreadCount = 2; }).AddService <IDemoServiceContract, DemoServiceContract>() .AddService <ICheckConfigServiceContract, PingServiceContract>() .AddService <ICheckTargetServiceContract, PingServiceContract>(); }); #region Server var ipcServerHost = new IpcServiceHostBuilder(services.BuildServiceProvider()) //.AddNamedPipeEndpoint<IDemoServiceContract>("demoEnpoint", "pipeName") .AddNamedPipeEndpoint <ICheckConfigServiceContract>("ConfigServiceEnpoint", "configPipe") .AddNamedPipeEndpoint <ICheckTargetServiceContract>("TargetServiceEnpoint", "targetPipe") //.AddTcpEndpoint<IDemoServiceContract>("demoTcpEndpoiint", IPAddress.Loopback, 2324) .Build(); services.AddSingleton <IIpcServiceHost>(ipcServerHost); #endregion #region Client IpcServiceClient <ICheckConfigServiceContract> configClient = new IpcServiceClientBuilder <ICheckConfigServiceContract>() .UseNamedPipe("configPipe") // or .UseTcp(IPAddress.Loopback, 45684) to invoke using TCP .Build(); IpcServiceClient <ICheckTargetServiceContract> targetJobClient = new IpcServiceClientBuilder <ICheckTargetServiceContract>() .UseNamedPipe("targetPipe") .Build(); services.AddSingleton <IpcServiceClient <ICheckConfigServiceContract> >(configClient); services.AddSingleton <IpcServiceClient <ICheckTargetServiceContract> >(targetJobClient); #endregion #endregion NLogMgr.SetVariable(NLogMgr.ConfigurationVariables.Terrace, "检测工具"); services.AddHostedService <PingHostedService>(); }) .ConfigureLogging((hostContext, configLogging) => { //日志中间件 //configLogging.AddConsole(); //configLogging.AddDebug(); }) .UseConsoleLifetime() .Build(); await host.RunAsync(); }
public static int Run(Logger logger, int parentProcessId) { // get parent process which will be monitored Process?parentProcess = null; if (parentProcessId != 0) { try { parentProcess = Process.GetProcessById(parentProcessId); } catch (Exception e) { logger.Error(e, "Cannot find parentProcess (Id={0})", parentProcessId); return(1); } } // open service var cts = new CancellationTokenSource(); try { var services = ConfigureServices(new ServiceCollection()); var address = CompilerServiceHelper.BaseAddress + parentProcessId; var host = new IpcServiceHostBuilder(services.BuildServiceProvider()) .AddNamedPipeEndpoint <ICompilerService>(name: "endpoint1", pipeName: address) //.AddTcpEndpoint<ICompilerService>(name: "endpoint2", ipEndpoint: IPAddress.Loopback, port: 45684) .Build(); host.RunAsync(cts.Token); } catch (Exception e) { /*if (serviceHost != null) * { * serviceHost.Close(); * }*/ logger.Error(e, "Service Host got an error"); return(1); } if (parentProcess != null) { // WaitForExit returns immediately instead of waiting on Mac so use while loop if (PlatformHelper.CurrentPlatform == Platform.Mac) { while (!parentProcess.HasExited) { Thread.Sleep(100); } } else { parentProcess.WaitForExit(); } cts.Cancel(); logger.Info("Parent process just exited. (PID={0})", parentProcess.Id); } return(0); }