示例#1
0
 public Task Start(CancellationToken cancellationToken) => _webHost.StartAsync(cancellationToken);
示例#2
0
 /// <inheritdoc />
 public Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)) => _host.StartAsync(cancellationToken);
示例#3
0
        public static async Task Main(string[] args)
        {
            string mode = Environment.GetEnvironmentVariable("PTDASYNCALL_MODE") ?? "inspect";
            bool   doSynchronizations   = mode == "sync";
            string sfAppDir             = Environment.GetEnvironmentVariable("SF_APP_DIR") ?? "../../SIL.XForge.Scripture";
            string sfProjectIdsSubset   = Environment.GetEnvironmentVariable("SYNC_SET");
            string sfAdminRequestValues = Environment.GetEnvironmentVariable("SF_PROJECT_ADMINS");

            Directory.SetCurrentDirectory(sfAppDir);
            IWebHostBuilder builder = CreateWebHostBuilder(args);
            IWebHost        webHost = builder.Build();

            Logger = webHost.Services.GetService <IProgramLogger>();
            Logger.Log($"Starting. Will sync: {doSynchronizations}");

            HashSet <string> projectSubset = null;

            try
            {
                if (sfProjectIdsSubset != null)
                {
                    projectSubset = new HashSet <string>(sfProjectIdsSubset.Split(' '));
                }
            }
            catch
            {
                Logger.Log($"There was a problem parsing the SYNC_SET SF project ids "
                           + $"environment variable. Rethrowing.");
                throw;
            }

            Dictionary <string, string> sfAdminsToUse = null;

            try
            {
                if (sfAdminRequestValues != null)
                {
                    sfAdminsToUse = new Dictionary <string, string>();
                    foreach (string sfAdminRequest in sfAdminRequestValues.Split(' '))
                    {
                        string[] request = sfAdminRequest.Split(':');
                        sfAdminsToUse.Add(request[0], request[1]);
                    }
                }
            }
            catch
            {
                Logger.Log($"There was a problem parsing SF_PROJECT_ADMINS. Rethrowing.");
                throw;
            }

            try
            {
                await webHost.StartAsync();
            }
            catch (HttpRequestException)
            {
                Logger.Log("There was an error starting the program before getting to the inspection or migration. "
                           + "Maybe the SF server is running on this machine and needs shut down? Rethrowing.");
                throw;
            }
            ISyncAllService tool = webHost.Services.GetService <ISyncAllService>();
            await tool.SynchronizeAllProjectsAsync(doSynchronizations, projectSubset, sfAdminsToUse);

            await webHost.StopAsync();

            Logger.Log("Done.");
        }
 public ServerFixture WithDownstreamApi(RequestDelegate mockServerHandler)
 {
     _downstreamApiHost = HostMockApi(mockServerHandler);
     _downstreamApiHost.StartAsync();
     return(this);
 }
示例#5
0
        public static async Task Start()
        {
            if (KestrelWebHost != null)
            {
                return;
            }

            Logger.Log("Starting Kestrel IPC server...", Enums.LogLevels.Trace);
            IWebHostBuilder builder = new WebHostBuilder();
            string          absoluteConfigDirectory = Path.Combine(Directory.GetCurrentDirectory(), Constants.ConfigDirectory);

            builder.ConfigureLogging(logging => logging.SetMinimumLevel(Core.Config.Debug ? LogLevel.Trace : LogLevel.Warning));
            if (File.Exists(Path.Combine(absoluteConfigDirectory, Constants.KestrelConfigurationFile)))
            {
                builder.UseConfiguration(new ConfigurationBuilder().SetBasePath(absoluteConfigDirectory).AddJsonFile(Constants.KestrelConfigurationFile, false, true).Build());
                builder.UseKestrel((builderContext, options) => options.Configure(builderContext.Configuration.GetSection("Kestrel")));
                if (Helpers.IsNullOrEmpty(Core.Config.KestrelServerUrl))
                {
                    builder.UseUrls("http://localhost:9090");
                }
                else
                {
                    builder.UseUrls(Core.Config.KestrelServerUrl);
                }
                builder.ConfigureLogging((hostingContext, logging) => logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")));
            }
            else
            {
                builder.UseKestrel();
                if (Helpers.IsNullOrEmpty(Core.Config.KestrelServerUrl))
                {
                    builder.UseUrls("http://localhost:9090/");
                }
                else
                {
                    builder.UseUrls(Core.Config.KestrelServerUrl);
                }
            }

            builder.UseNLog();
            builder.UseStartup <Startup>();
            IWebHost kestrelWebHost = builder.Build();

            try {
                await kestrelWebHost.StartAsync().ConfigureAwait(false);
            }
            catch (Exception e) {
                Logger.Log(e);
                kestrelWebHost.Dispose();
                IsServerOnline = false;
                return;
            }

            KestrelWebHost = kestrelWebHost;
            IsServerOnline = true;
            if (Helpers.IsNullOrEmpty(Core.Config.KestrelServerUrl))
            {
                Logger.Log($"Kestrel server is running at http://localhost:9090/");
            }
            else
            {
                Logger.Log($"Kestrel server is running at {Core.Config.KestrelServerUrl}");
            }
        }
 public async Task InitializeAsync()
 => await _host.StartAsync().ConfigureAwait(false);
示例#7
0
文件: Server.cs 项目: gamediy/AServer
        public Task Run()
        {
            Host =
                new WebHostBuilder()
                .UseKestrel(op =>
            {
                if (_ip.Equals("localhost", StringComparison.CurrentCultureIgnoreCase))
                {
                    op.ListenLocalhost(_port);
                }
                else
                {
                    op.Listen(IPAddress.Parse(_ip), _port);
                }
            })
                .Configure(app =>
            {
                app.Run(http =>
                {
                    return(Task.Run(() =>
                    {
                        var req = http.Request;
                        var resp = http.Response;
                        var method = http.Request.Method;
                        var path = req.Path;

                        var cacheKey = $"Request:{method}-{path}";
                        ConsoleUtil.WriteToConsole(cacheKey);

                        //cors
                        var corsResult = CorsHandler.Handler(_corsOption, http);
                        if (corsResult != null)
                        {
                            return corsResult;
                        }

                        _handlersCache.TryGetValue(cacheKey, out HttpHandler handler);
                        if (handler == null)
                        {
                            handler = _handlers.FirstOrDefault(
                                h => h.Method == method && PathUtil.IsMatch(path, h.Path));
                            if (handler != null)
                            {
                                _handlersCache.TryAdd(cacheKey, handler);
                            }
                        }

                        if (handler != null)
                        {
                            try
                            {
                                return handler.Handler(new Request(req, handler.Path), new Response(resp));
                            }
                            catch (Exception e)
                            {
                                ConsoleUtil.WriteToConsole(e.ToString());
                                resp.StatusCode = (int)HttpStatusCode.InternalServerError;
                                ConsoleUtil.WriteToConsole(
                                    $"Response:{resp.StatusCode} {HttpStatusCode.InternalServerError}");

                                return resp.WriteAsync("InternalServerError");
                            }
                        }

                        resp.StatusCode = (int)HttpStatusCode.NotFound;
                        ConsoleUtil.WriteToConsole($"Response:{resp.StatusCode} {HttpStatusCode.NotFound}");

                        return resp.WriteAsync("NotFound");
                    }));
                });
            })
                .Build();
            var task = Host.StartAsync();

            ConsoleUtil.WriteToConsole($"AServer listening {_ip}:{_port} now .");

            return(task);
        }
示例#8
0
 public Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     return(webHost.StartAsync(cancellationToken));
 }
示例#9
0
 public Task StartAsync(CancellationToken cancellationToken)
 {
     _logger.LogInformation("App started successfully {appName} ({version}) [{env}]",
                            _appInfo.Name, _appInfo.Version, _appInfo.Environment);
     return(_host.StartAsync(cancellationToken));
 }
示例#10
0
 /// <summary>
 /// Start web server on separate thread
 /// </summary>
 public async Task StartAsync(CancellationToken cancellationToken = default)
 {
     await webHost.StartAsync(cancellationToken).ConfigureAwait(false);
 }
示例#11
0
 public Task Start() => _host.StartAsync();
示例#12
0
        public async Task Start(CancellationToken cancellationToken)
        {
            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Configuring Web Host: {0}", _configuration.HostAddress);
            }

            IPHostEntry entries = await Dns.GetHostEntryAsync(_configuration.Settings.Host).ConfigureAwait(false);

            IWebHost BuildWebHost(params string[] args)
            {
                return(WebHost.CreateDefaultBuilder(args)
                       .Configure(Configure)
                       .UseKestrel(options =>
                {
                    foreach (var ipAddress in entries.AddressList)
                    {
                        options.Listen(ipAddress, HostSettings.Port);
                    }

                    //                        options.Listen(IPAddress.Loopback, 5001, listenOptions =>
                    //                        {
                    //                            listenOptions.UseHttps("testCert.pfx", "testPassword");
                    //                        });
                })
                       .Build());
            }

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Building Web Host: {0}", _configuration.HostAddress);
            }

            _webHost = BuildWebHost();

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Starting Web Host: {0}", _configuration.HostAddress);
            }

            try
            {
                await _webHost.StartAsync(cancellationToken).ConfigureAwait(false);

                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Started Web Host: {0}", _configuration.HostAddress);
                }
            }
            catch (Exception exception)
            {
                if (_log.IsErrorEnabled)
                {
                    _log.Error($"Fault Starting Web Host: {_configuration.HostAddress}", exception);
                }

                throw;
            }

            _started = true;
        }
示例#13
0
        public override async Task StartAsync(CancellationToken token)
        {
            await base.StartAsync(token).ConfigureAwait(false);

            await host.StartAsync(token).ConfigureAwait(false);
        }
        /// <summary>
        /// Opens a connection using the parameters resolved by the referenced connection
        /// resolver and creates a REST server(service) using the set options and parameters.
        /// </summary>
        /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
        public virtual async Task OpenAsync(string correlationId)
        {
            if (IsOpen())
            {
                return;
            }

            var connection = await _connectionResolver.ResolveAsync(correlationId);

            var credential = connection.GetSection("credential");

            var protocol = connection.Protocol;
            var host     = connection.Host;
            var port     = connection.Port;

            _address = protocol + "://" + host + ":" + port;

            try
            {
                var builder = new WebHostBuilder()
                              .UseKestrel(options =>
                {
                    // Convert localhost to IP Address
                    if (host == "localhost")
                    {
                        host = IPAddress.Loopback.ToString();
                    }

                    if (protocol == "https")
                    {
                        var sslPfxFile  = credential.GetAsNullableString("ssl_pfx_file");
                        var sslPassword = credential.GetAsNullableString("ssl_password");

                        options.Listen(IPAddress.Parse(host), port, listenOptions =>
                        {
                            listenOptions.UseHttps(sslPfxFile, sslPassword);
                        });
                    }
                    else
                    {
                        options.Listen(IPAddress.Parse(host), port);
                    }
                })
                              .ConfigureServices(ConfigureServices)
                              .Configure(ConfigureApplication)
                              .UseContentRoot(Directory.GetCurrentDirectory());

                _server = builder.Build();

                _logger.Info(correlationId, "Opened REST service at {0}", _address);

                await _server.StartAsync();
            }
            catch (Exception ex)
            {
                if (_server != null)
                {
                    _server.Dispose();
                    _server = null;
                }

                throw new ConnectionException(correlationId, "CANNOT_CONNECT", "Opening REST service failed")
                      .WithCause(ex).WithDetails("url", _address);
            }
        }
示例#15
0
 internal async Task StartAsync() => await _host.StartAsync();
示例#16
0
        public Task Run()
        {
            string url  = String.Format("http://{0}:{1}", _ip, _port);
            var    urls = new List <string>();

            if (!_urls.Any())
            {
                urls.Add(url);
            }
            else
            {
                urls = _urls.ToList();
            }

            Host =
                new WebHostBuilder()
                .UseUrls(urls.ToArray())
                .UseKestrel()
                .Configure(app =>
            {
                app.Run(http =>
                {
                    return(Task.Run(() =>
                    {
                        var req = http.Request;
                        var resp = http.Response;
                        var method = http.Request.Method;
                        var path = req.Path;

                        var cacheKey = $"Request:{method}-{path}";
                        ConsoleUtil.DebugConsole(cacheKey);

                        //cors
                        var corsResult = CorsHandler.Handler(_corsOption, http);
                        if (corsResult != null)
                        {
                            return corsResult;
                        }

                        _handlersCache.TryGetValue(cacheKey, out HttpHandler handler);
                        if (handler == null)
                        {
                            handler = _handlers.FirstOrDefault(
                                h => h.Method.Equals(method, StringComparison.OrdinalIgnoreCase) && PathUtil.IsMatch(path, h.Path));
                            if (handler != null)
                            {
                                _handlersCache.TryAdd(cacheKey, handler);
                            }
                        }

                        if (handler != null)
                        {
                            try
                            {
                                return handler.Handler(new Request(req, handler.Path), new Response(resp));
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.ToString());
                                resp.StatusCode = (int)HttpStatusCode.InternalServerError;
                                Console.WriteLine(
                                    $"Response:{resp.StatusCode} {HttpStatusCode.InternalServerError}");

                                return resp.WriteAsync("InternalServerError");
                            }
                        }

                        resp.StatusCode = (int)HttpStatusCode.NotFound;
                        Console.WriteLine($"Response:{resp.StatusCode} {HttpStatusCode.NotFound}");

                        return resp.WriteAsync("NotFound");
                    }));
                });
            })
                .Build();
            var task = Host.StartAsync();

            urls.ForEach(u =>
            {
                Console.WriteLine($"AServer listen on {u} .");
            });

            return(task);
        }
示例#17
0
 public void Initialized(InitializedContext context)
 {
     // 在本地地址上启动Web服务,可以根据需求改变端口
     _webHost.StartAsync("http://localhost:8080", _mahuaApi.GetSourceContainer());
 }
示例#18
0
 internal Task StartAsync()
 => host.StartAsync();
示例#19
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static async Task Main(string[] args)
        {
            const string siteDir = "/var/lib/scriptureforge";
            string       syncDir = Path.Combine(siteDir, "sync");
            bool         doWrite = (args.Length >= 1 ? args[0] : string.Empty) == "run";

            MigrationsDisabled = !doWrite;
            string sfAppDir = args.Length >= 2 ? args[1] : string.Empty;

            if (string.IsNullOrWhiteSpace(sfAppDir))
            {
                // This calculated from "web-xforge\src\Migrations\SourceTargetSplitting\bin\Debug\netcoreapp3.1"
                sfAppDir = Environment.GetEnvironmentVariable("SF_APP_DIR") ?? "../../../../../SIL.XForge.Scripture";
            }

            Log("Split Source and Target Projects.");
            Log(string.Empty);
            if (!Directory.Exists(siteDir))
            {
                Log($"Site folder doesn't exist: {siteDir}");
                Environment.Exit(1);
            }

            if (!Directory.Exists(syncDir))
            {
                Log($"Sync folder doesn't exist: {syncDir}");
                Environment.Exit(1);
            }

            if (!doWrite)
            {
                Log("Test Mode ONLY - no files are changed. Run `SourceTargetSplitting run` to change files.");
                Log(string.Empty);
            }

            // Set up the web host, and start the real time server
            Log("Starting Scripture Forge Server...");
            Directory.SetCurrentDirectory(sfAppDir);
            IWebHostBuilder builder = CreateWebHostBuilder(args);
            IWebHost        webHost = builder.Build();

            try
            {
                await webHost.StartAsync();
            }
            catch (HttpRequestException)
            {
                Log("There was an error starting the program before getting to the migration"
                    + " part. Maybe the SF server is running and needs shut down? Rethrowing.");
                throw;
            }

            // The following serializer is required for serializing TextData
            BsonSerializer.RegisterSerializer(new JTokenSerializer());

            // Get the object migrator
            objectMigrator = webHost.Services.GetService <ObjectMigrator>();

            // Set up the scripture text collections
            objectMigrator.TargetScrTextCollection.Initialize(syncDir);
            if (!doWrite)
            {
                objectMigrator.SourceScrTextCollection.Initialize(syncDir);
            }

            // Migrate the files, and get a list of source mappings so we can migrate the database objects
            await MigrateFilesAsync(syncDir, doWrite);

            // Migrate the database objects
            await objectMigrator.MigrateObjectsAsync(doWrite);

            // Migrate the chapter and book permissions
            await objectMigrator.MigrateChapterAndBookPermissions(doWrite);

            // Stop the web host and real time server
            Log("Stopping Scripture Forge Server...");
            await webHost.StopAsync();

            Log(string.Empty);
            Log("Finished Migration.");
        }
        public virtual async Task InitializeAsync()
        {
            await _node.StartAsync(true);

            await _host.StartAsync();
        }
示例#21
0
        internal static async Task Start()
        {
            if (KestrelWebHost != null)
            {
                return;
            }

            ASF.ArchiLogger.LogGenericInfo(Strings.IPCStarting);

            // The order of dependency injection matters, pay attention to it
            IWebHostBuilder builder = new WebHostBuilder();

            string customDirectory = Path.Combine(Directory.GetCurrentDirectory(), SharedInfo.WebsiteDirectory);

            if (Directory.Exists(customDirectory))
            {
                WebsiteDirectory = customDirectory;
            }

            // Set default directories
            builder.UseContentRoot(SharedInfo.HomeDirectory);
            builder.UseWebRoot(WebsiteDirectory);

            // Check if custom config is available
            string absoluteConfigDirectory = Path.Combine(Directory.GetCurrentDirectory(), SharedInfo.ConfigDirectory);

            // Firstly initialize settings that user is free to override
            builder.ConfigureLogging(logging => logging.SetMinimumLevel(Debugging.IsUserDebugging ? LogLevel.Trace : LogLevel.Warning));

            // Now conditionally initialize settings that are not possible to override
            if (File.Exists(Path.Combine(absoluteConfigDirectory, ConfigurationFile)))
            {
                // Set up custom config to be used
                builder.UseConfiguration(new ConfigurationBuilder().SetBasePath(absoluteConfigDirectory).AddJsonFile(ConfigurationFile, false, true).Build());

                // Use custom config for Kestrel and Logging configuration
                builder.UseKestrel((builderContext, options) => options.Configure(builderContext.Configuration.GetSection("Kestrel")));
                builder.ConfigureLogging((hostingContext, logging) => logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")));
            }
            else
            {
                // Use ASF defaults for Kestrel
                builder.UseKestrel(options => options.ListenLocalhost(1242));
            }

            // Enable NLog integration for logging
            builder.UseNLog();

            // Specify Startup class for IPC
            builder.UseStartup <Startup>();

            // Init history logger for /Api/Log usage
            Logging.InitHistoryLogger();

            // Start the server
            IWebHost kestrelWebHost = builder.Build();

            try {
                await kestrelWebHost.StartAsync().ConfigureAwait(false);
            } catch (Exception e) {
                ASF.ArchiLogger.LogGenericException(e);
                kestrelWebHost.Dispose();

                return;
            }

            KestrelWebHost = kestrelWebHost;
            ASF.ArchiLogger.LogGenericInfo(Strings.IPCReady);
        }
示例#22
0
 public Task StartAsync(CancellationToken cancellationToken = new CancellationToken())
 {
     return(_webHost.StartAsync(cancellationToken));
 }
 public async Task StartAsync(CancellationToken cancellationToken = default)
 {
     await _internalWebHost.StartAsync(cancellationToken);
 }
示例#24
0
 public async Task StartAsync(CancellationToken cancellationToken)
 {
     await _host.StartAsync();
 }
示例#25
0
 private Task StartWebHostAsync(AppSettings settings)
 {
     _webHost = WebHostFactory.CreateWebHost(settings, Port);
     return(_webHost.StartAsync());
 }
示例#26
0
 protected override Task Start()
 {
     return(Task.WhenAll(_node.StartAsync(false), _host.StartAsync()));
 }
示例#27
0
 public Task StartAsync(CancellationToken cancellationToken) =>
 host.StartAsync(cancellationToken);
 public void Initialized(InitializedContext context)
 {
     _webHost.StartAsync("http://localhost:65238", _mahuaApi.GetSourceContainer());
 }
示例#29
0
 public static async Task SetupAsync(TestContext context)
 {
     apiHost = ApiHostBuilder.Build();
     await apiHost.StartAsync();
 }
示例#30
0
 public Task StartAsync(CancellationToken cancellationToken)
 {
     _host.StartAsync();
     return(Task.CompletedTask);
 }