コード例 #1
0
        public Task Start(CancellationToken cancellationToken)
        {
            if (_logger.IsDebug)
            {
                _logger.Debug("Initializing JSON RPC");
            }
            string[] urls    = _jsonRpcUrlCollection.Urls;
            var      webHost = WebHost.CreateDefaultBuilder()
                               .ConfigureServices(s =>
            {
                s.AddSingleton(_configurationProvider);
                s.AddSingleton(_jsonRpcProcessor);
                s.AddSingleton(_jsonRpcUrlCollection);
                s.AddSingleton(_webSocketsManager);
                s.AddSingleton(_rpcAuthentication);
                foreach (var plugin in _api.Plugins.OfType <INethermindServicesPlugin>())
                {
                    plugin.AddServices(s);
                }
                ;
            })
                               .UseStartup <Startup>()
                               .UseUrls(urls)
                               .ConfigureLogging(logging =>
            {
                logging.SetMinimumLevel(LogLevel.Information);
                logging.ClearProviders();
                logging.AddProvider(new CustomMicrosoftLoggerProvider(_logManager));
            })
                               .Build();

            string urlsString = string.Join(" ; ", urls);

            // TODO: replace http with ws where relevant

            ThisNodeInfo.AddInfo("JSON RPC     :", $"{urlsString}");

            _webHost = webHost;

            if (!cancellationToken.IsCancellationRequested)
            {
                _webHost.Start();
                if (_logger.IsDebug)
                {
                    _logger.Debug($"JSON RPC     : {urlsString}");
                }
            }

            return(Task.CompletedTask);
        }
コード例 #2
0
ファイル: RunnerAppBase.cs プロジェクト: rlanga/nethermind
 private void LogMemoryConfiguration()
 {
     if (Logger.IsDebug)
     {
         Logger.Debug($"Server GC           : {System.Runtime.GCSettings.IsServerGC}");
     }
     if (Logger.IsDebug)
     {
         Logger.Debug($"GC latency mode     : {System.Runtime.GCSettings.LatencyMode}");
     }
     if (Logger.IsDebug)
     {
         Logger.Debug($"LOH compaction mode : {System.Runtime.GCSettings.LargeObjectHeapCompactionMode}");
     }
 }
コード例 #3
0
        private ChainSpec LoadChainSpec(IJsonSerializer ethereumJsonSerializer)
        {
            bool hiveEnabled         = Environment.GetEnvironmentVariable("NETHERMIND_HIVE_ENABLED")?.ToLowerInvariant() == "true";
            bool hiveChainSpecExists = File.Exists(_initConfig.HiveChainSpecPath);

            string chainSpecFile;

            if (hiveEnabled && hiveChainSpecExists)
            {
                chainSpecFile = _initConfig.HiveChainSpecPath;
            }
            else
            {
                chainSpecFile = _initConfig.ChainSpecPath;
            }

            if (_logger.IsDebug)
            {
                _logger.Debug($"Loading chain spec from {chainSpecFile}");
            }

            ThisNodeInfo.AddInfo("Chainspec    :", $"{chainSpecFile}");

            IChainSpecLoader loader = new ChainSpecLoader(ethereumJsonSerializer);

            return(loader.LoadFromFile(chainSpecFile));
        }
コード例 #4
0
        public Task Start()
        {
            if (_logger.IsDebug)
            {
                _logger.Debug("Initializing JSON RPC");
            }
            var hostVariable = Environment.GetEnvironmentVariable("NETHERMIND_URL");
            var host         = string.IsNullOrWhiteSpace(hostVariable)
                ? $"http://{_initConfig.HttpHost}:{_initConfig.HttpPort}"
                : hostVariable;

            if (_logger.IsInfo)
            {
                _logger.Info($"Running server, url: {host}");
            }
            var webHost = WebHost.CreateDefaultBuilder()
                          .ConfigureServices(s =>
            {
                s.AddSingleton(_configurationProvider);
                s.AddSingleton(_jsonRpcProcessor);
                s.AddSingleton(_webSocketsManager);
            })
                          .UseStartup <Startup>()
                          .UseUrls(host)
                          .ConfigureLogging(logging =>
            {
                logging.SetMinimumLevel(LogLevel.Information);
                logging.ClearProviders();
                logging.AddProvider(new CustomMicrosoftLoggerProvider(_logManager));
            })
                          .Build();

            var modules = GetModules(_initConfig.JsonRpcEnabledModules)?.ToList();

            if (modules != null && modules.Any())
            {
                _jsonRpcConfig.EnabledModules = modules;
            }

            _webHost = webHost;
            _webHost.Start();
            if (_logger.IsInfo)
            {
                _logger.Info($"JSON RPC     : {host}");
            }
            if (_logger.IsInfo)
            {
                _logger.Info($"RPC modules  : {string.Join(", ", _moduleProvider.GetEnabledModules().Select(m => m.ModuleType.ToString()).OrderBy(x => x))}");
            }
            return(Task.CompletedTask);
        }
コード例 #5
0
ファイル: RunnerAppBase.cs プロジェクト: fosfuan/nethermind
        public void Run(string[] args)
        {
            var(app, buildConfigProvider, getDbBasePath) = BuildCommandLineApp();
            ManualResetEventSlim appClosed = new ManualResetEventSlim(true);

            app.OnExecute(async() =>
            {
                appClosed.Reset();
                var configProvider       = buildConfigProvider();
                var initConfig           = configProvider.GetConfig <IInitConfig>();
                LogManager.Configuration = new XmlLoggingConfiguration("NLog.config".GetApplicationResourcePath());
                _logger = new NLogLogger(initConfig.LogFileName, initConfig.LogDirectory);
                LogMemoryConfiguration();

                var pathDbPath = getDbBasePath();
                if (!string.IsNullOrWhiteSpace(pathDbPath))
                {
                    var newDbPath = Path.Combine(pathDbPath, initConfig.BaseDbPath);
                    if (_logger.IsDebug)
                    {
                        _logger.Debug($"Adding prefix to baseDbPath, new value: {newDbPath}, old value: {initConfig.BaseDbPath}");
                    }
                    initConfig.BaseDbPath = newDbPath ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "db");
                }

                Console.Title           = initConfig.LogFileName;
                Console.CancelKeyPress += ConsoleOnCancelKeyPress;

                var serializer = new EthereumJsonSerializer();
                if (_logger.IsInfo)
                {
                    _logger.Info($"Nethermind config:\n{serializer.Serialize(initConfig, true)}\n");
                }

                _cancelKeySource = new TaskCompletionSource <object>();

                await StartRunners(configProvider);
                await _cancelKeySource.Task;

                Console.WriteLine("Closing, please wait until all functions are stopped properly...");
                StopAsync().Wait();
                Console.WriteLine("All done, goodbye!");
                appClosed.Set();

                return(0);
            });

            app.Execute(args);
            appClosed.Wait();
        }
コード例 #6
0
        public EthereumRunnerContextFactory(IConfigProvider configProvider, IJsonSerializer ethereumJsonSerializer, ILogManager logManager)
        {
            _configProvider = configProvider;
            _logManager     = logManager;

            IInitConfig initConfig = configProvider.GetConfig <IInitConfig>();
            ILogger     logger     = _logManager.GetClassLogger();

            bool hiveEnabled         = Environment.GetEnvironmentVariable("NETHERMIND_HIVE_ENABLED")?.ToLowerInvariant() == "true";
            bool hiveChainSpecExists = File.Exists(initConfig.HiveChainSpecPath);

            string chainSpecFile;

            if (hiveEnabled && hiveChainSpecExists)
            {
                chainSpecFile = initConfig.HiveChainSpecPath;
            }
            else
            {
                chainSpecFile = initConfig.ChainSpecPath;
            }

            if (logger.IsDebug)
            {
                logger.Debug($"Loading chain spec from {chainSpecFile}");
            }

            ThisNodeInfo.AddInfo("Chainspec    :", $"{chainSpecFile}");
            IChainSpecLoader loader = new ChainSpecLoader(ethereumJsonSerializer);

            ChainSpec chainSpec = loader.LoadFromFile(chainSpecFile);

            logManager.SetGlobalVariable("chain", chainSpec.Name);
            logManager.SetGlobalVariable("chainId", chainSpec.ChainId);
            logManager.SetGlobalVariable("engine", chainSpec.SealEngineType);

            Context              = Create(chainSpec.SealEngineType);
            Context.ChainSpec    = chainSpec;
            Context.SpecProvider = new ChainSpecBasedSpecProvider(Context.ChainSpec);
        }
コード例 #7
0
        public EthereumRunnerContextFactory(IConfigProvider configProvider, IJsonSerializer ethereumJsonSerializer, ILogManager logManager)
        {
            _configProvider = configProvider;
            _logManager     = logManager;

            IInitConfig initConfig = configProvider.GetConfig <IInitConfig>();
            ILogger     logger     = _logManager.GetClassLogger();

            if (logger.IsDebug)
            {
                logger.Debug($"Loading chain spec from {initConfig.ChainSpecPath}");
            }
            ThisNodeInfo.AddInfo("Chainspec    :", $"{initConfig.ChainSpecPath}");
            IChainSpecLoader loader    = new ChainSpecLoader(ethereumJsonSerializer);
            ChainSpec        chainSpec = loader.LoadFromFile(initConfig.ChainSpecPath);

            logManager.SetGlobalVariable("chain", chainSpec.Name);
            logManager.SetGlobalVariable("chainId", chainSpec.ChainId);
            logManager.SetGlobalVariable("engine", chainSpec.SealEngineType);

            Context              = Create(chainSpec.SealEngineType);
            Context.ChainSpec    = chainSpec;
            Context.SpecProvider = new ChainSpecBasedSpecProvider(Context.ChainSpec);
        }
コード例 #8
0
        public Task Start(CancellationToken cancellationToken)
        {
            IEnumerable <string> GetUrls()
            {
                const string nethermindUrlVariable = "NETHERMIND_URL";
                string       host        = _jsonRpcConfig.Host;
                string       scheme      = "http";
                var          defaultUrl  = $"{scheme}://{host}:{_jsonRpcConfig.Port}";
                var          urlVariable = Environment.GetEnvironmentVariable(nethermindUrlVariable);
                string       url         = defaultUrl;

                if (!string.IsNullOrWhiteSpace(urlVariable))
                {
                    if (Uri.TryCreate(urlVariable, UriKind.Absolute, out var uri))
                    {
                        url    = urlVariable;
                        host   = uri.Host;
                        scheme = uri.Scheme;
                    }
                    else
                    {
                        if (_logger.IsWarn)
                        {
                            _logger.Warn($"Environment variable '{nethermindUrlVariable}' value '{urlVariable}' is not valid JSON RPC URL, using default url : '{defaultUrl}'");
                        }
                    }
                }

                yield return(url);

                if (_initConfig.WebSocketsEnabled && _jsonRpcConfig.WebSocketsPort != _jsonRpcConfig.Port)
                {
                    yield return($"{scheme}://{host}:{_jsonRpcConfig.WebSocketsPort}");
                }
            }

            if (_logger.IsDebug)
            {
                _logger.Debug("Initializing JSON RPC");
            }
            var urls    = GetUrls().ToArray();
            var webHost = WebHost.CreateDefaultBuilder()
                          .ConfigureServices(s =>
            {
                s.AddSingleton(_configurationProvider);
                s.AddSingleton(_jsonRpcProcessor);
                s.AddSingleton(_webSocketsManager);
            })
                          .UseStartup <Startup>()
                          .UseUrls(urls)
                          .ConfigureLogging(logging =>
            {
                logging.SetMinimumLevel(LogLevel.Information);
                logging.ClearProviders();
                logging.AddProvider(new CustomMicrosoftLoggerProvider(_logManager));
            })
                          .Build();

            string urlsString = string.Join(" ; ", urls);

            ThisNodeInfo.AddInfo("JSON RPC     :", $"{urlsString}");
            ThisNodeInfo.AddInfo("RPC modules  :", $"{string.Join(", ", _moduleProvider.Enabled.OrderBy(x => x))}");

            _webHost = webHost;

            if (!cancellationToken.IsCancellationRequested)
            {
                _webHost.Start();
                if (_logger.IsDebug)
                {
                    _logger.Debug($"JSON RPC     : {urlsString}");
                }
                if (_logger.IsDebug)
                {
                    _logger.Debug($"RPC modules  : {string.Join(", ", _moduleProvider.Enabled.OrderBy(x => x))}");
                }
            }

            return(Task.CompletedTask);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: uzbekdev1/nethermind
        private static void Run(string[] args)
        {
            _logger.Info("Nethermind starting initialization.");

            AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnProcessExit;
            IFileSystem fileSystem = new FileSystem();;

            PluginLoader pluginLoader = new PluginLoader(
                "plugins", fileSystem, typeof(CliquePlugin), typeof(EthashPlugin), typeof(NethDevPlugin));

            pluginLoader.Load(SimpleConsoleLogManager.Instance);

            Type configurationType         = typeof(IConfig);
            IEnumerable <Type> configTypes = new TypeDiscovery().FindNethermindTypes(configurationType)
                                             .Where(ct => ct.IsInterface);

            CommandLineApplication app = new CommandLineApplication {
                Name = "Nethermind.Runner"
            };

            app.HelpOption("-?|-h|--help");
            app.VersionOption("-v|--version", () => ClientVersion.Version, () => ClientVersion.Description);

            GlobalDiagnosticsContext.Set("version", ClientVersion.Version);

            CommandOption dataDir            = app.Option("-dd|--datadir <dataDir>", "data directory", CommandOptionType.SingleValue);
            CommandOption configFile         = app.Option("-c|--config <configFile>", "config file path", CommandOptionType.SingleValue);
            CommandOption dbBasePath         = app.Option("-d|--baseDbPath <baseDbPath>", "base db path", CommandOptionType.SingleValue);
            CommandOption logLevelOverride   = app.Option("-l|--log <logLevel>", "log level", CommandOptionType.SingleValue);
            CommandOption configsDirectory   = app.Option("-cd|--configsDirectory <configsDirectory>", "configs directory", CommandOptionType.SingleValue);
            CommandOption loggerConfigSource = app.Option("-lcs|--loggerConfigSource <loggerConfigSource>", "path to the NLog config file", CommandOptionType.SingleValue);

            foreach (Type configType in configTypes.OrderBy(c => c.Name))
            {
                if (configType == null)
                {
                    continue;
                }

                ConfigCategoryAttribute?typeLevel = configType.GetCustomAttribute <ConfigCategoryAttribute>();
                if (typeLevel?.HiddenFromDocs ?? false)
                {
                    continue;
                }

                foreach (PropertyInfo propertyInfo in configType
                         .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                         .OrderBy(p => p.Name))
                {
                    ConfigItemAttribute?configItemAttribute = propertyInfo.GetCustomAttribute <ConfigItemAttribute>();
                    if (!(configItemAttribute?.HiddenFromDocs ?? false))
                    {
                        app.Option($"--{configType.Name.Substring(1).Replace("Config", String.Empty)}.{propertyInfo.Name}", $"{(configItemAttribute == null ? "<missing documentation>" : configItemAttribute.Description + $" (DEFAULT: {configItemAttribute.DefaultValue})" ?? "<missing documentation>")}", CommandOptionType.SingleValue);
                    }
                }
            }

            ManualResetEventSlim appClosed = new ManualResetEventSlim(true);

            app.OnExecute(async() =>
            {
                appClosed.Reset();
                IConfigProvider configProvider = BuildConfigProvider(app, loggerConfigSource, logLevelOverride, configsDirectory, configFile);
                IInitConfig initConfig         = configProvider.GetConfig <IInitConfig>();
                IKeyStoreConfig keyStoreConfig = configProvider.GetConfig <IKeyStoreConfig>();

                Console.Title           = initConfig.LogFileName;
                Console.CancelKeyPress += ConsoleOnCancelKeyPress;

                SetFinalDataDirectory(dataDir.HasValue() ? dataDir.Value() : null, initConfig, keyStoreConfig);
                NLogManager logManager = new(initConfig.LogFileName, initConfig.LogDirectory);

                _logger = logManager.GetClassLogger();
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Nethermind version: {ClientVersion.Description}");
                }

                ConfigureSeqLogger(configProvider);
                SetFinalDbPath(dbBasePath.HasValue() ? dbBasePath.Value() : null, initConfig);
                LogMemoryConfiguration();

                EthereumJsonSerializer serializer = new();
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Nethermind config:{Environment.NewLine}{serializer.Serialize(initConfig, true)}{Environment.NewLine}");
                }

                ApiBuilder apiBuilder        = new(configProvider, logManager);
                INethermindApi nethermindApi = apiBuilder.Create();
                foreach (Type pluginType in pluginLoader.PluginTypes)
                {
                    if (Activator.CreateInstance(pluginType) is INethermindPlugin plugin)
                    {
                        nethermindApi.Plugins.Add(plugin);
                    }
                }

                EthereumRunner ethereumRunner = new EthereumRunner(nethermindApi);
                await ethereumRunner.Start(_processCloseCancellationSource.Token).ContinueWith(x =>
                {
                    if (x.IsFaulted && _logger.IsError)
                    {
                        _logger.Error("Error during ethereum runner start", x.Exception);
                    }
                });

                await Task.WhenAny(_cancelKeySource.Task, _processExit.Task);

                _logger.Info("Closing, please wait until all functions are stopped properly...");
                await ethereumRunner.StopAsync();
                _logger.Info("All done, goodbye!");
                appClosed.Set();

                return(0);
            });

            app.Execute(args);
            appClosed.Wait();
        }