Beispiel #1
0
        public RlpxPeer(IMessageSerializationService serializationService,
                        PublicKey localNodeId,
                        int localPort,
                        IHandshakeService handshakeService,
                        ISessionMonitor sessionMonitor,
                        IDisconnectsAnalyzer disconnectsAnalyzer,
                        ILogManager logManager)
        {
            // .NET Core definitely got the easy logging setup right :D
            // ResourceLeakDetector.Level = ResourceLeakDetector.DetectionLevel.Paranoid;
            // ConfigureNamedOptions<ConsoleLoggerOptions> configureNamedOptions = new("", null);
            // OptionsFactory<ConsoleLoggerOptions> optionsFactory = new(
            //     new []{ configureNamedOptions },
            //     Enumerable.Empty<IPostConfigureOptions<ConsoleLoggerOptions>>());
            // OptionsMonitor<ConsoleLoggerOptions> optionsMonitor = new(
            //     optionsFactory,
            //     Enumerable.Empty<IOptionsChangeTokenSource<ConsoleLoggerOptions>>(),
            //     new OptionsCache<ConsoleLoggerOptions>());
            // LoggerFactory loggerFactory = new(
            //     new[] { new ConsoleLoggerProvider(optionsMonitor) },
            //     new LoggerFilterOptions { MinLevel = Microsoft.Extensions.Logging.LogLevel.Warning });
            // InternalLoggerFactory.DefaultFactory = loggerFactory;

            _group = new SingleThreadEventLoop();
            _serializationService = serializationService ?? throw new ArgumentNullException(nameof(serializationService));
            _logManager           = logManager ?? throw new ArgumentNullException(nameof(logManager));
            _logger              = logManager.GetClassLogger();
            _sessionMonitor      = sessionMonitor ?? throw new ArgumentNullException(nameof(sessionMonitor));
            _disconnectsAnalyzer = disconnectsAnalyzer ?? throw new ArgumentNullException(nameof(disconnectsAnalyzer));
            _handshakeService    = handshakeService ?? throw new ArgumentNullException(nameof(handshakeService));
            LocalNodeId          = localNodeId ?? throw new ArgumentNullException(nameof(localNodeId));
            LocalPort            = localPort;
        }
Beispiel #2
0
 public ApiBuilder(IConfigProvider configProvider, ILogManager logManager)
 {
     _logManager     = logManager ?? throw new ArgumentNullException(nameof(logManager));
     _logger         = _logManager.GetClassLogger();
     _configProvider = configProvider ?? throw new ArgumentNullException(nameof(configProvider));
     _initConfig     = configProvider.GetConfig <IInitConfig>();
     _jsonSerializer = new EthereumJsonSerializer();
 }
Beispiel #3
0
 public JsonRpcRunner(IConfigProvider configurationProvider, IRpcModuleProvider moduleProvider,
                      ILogManager logManager, IJsonRpcProcessor jsonRpcProcessor, IWebSocketsManager webSocketsManager)
 {
     _jsonRpcConfig         = configurationProvider.GetConfig <IJsonRpcConfig>();
     _configurationProvider = configurationProvider;
     _moduleProvider        = moduleProvider ?? throw new ArgumentNullException(nameof(moduleProvider));
     _logManager            = logManager;
     _jsonRpcProcessor      = jsonRpcProcessor;
     _webSocketsManager     = webSocketsManager;
     _logger = logManager.GetClassLogger();
 }
Beispiel #4
0
        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();
        }
Beispiel #5
0
 public JsonRpcRunner(
     IJsonRpcProcessor jsonRpcProcessor,
     IWebSocketsManager webSocketsManager,
     IConfigProvider configurationProvider,
     ILogManager logManager,
     INethermindApi api)
 {
     _jsonRpcConfig         = configurationProvider.GetConfig <IJsonRpcConfig>();
     _initConfig            = configurationProvider.GetConfig <IInitConfig>();
     _configurationProvider = configurationProvider;
     _logManager            = logManager;
     _jsonRpcProcessor      = jsonRpcProcessor;
     _webSocketsManager     = webSocketsManager;
     _logger = logManager.GetClassLogger();
     _api    = api;
 }
        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);
        }
Beispiel #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);
        }
Beispiel #8
0
 protected RunnerAppBase(ILogger logger)
 {
     Logger = logger;
     AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnProcessExit;
 }
Beispiel #9
0
        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();
        }
Beispiel #10
0
        private static IConfigProvider BuildConfigProvider(
            CommandLineApplication app,
            CommandOption loggerConfigSource,
            CommandOption logLevelOverride,
            CommandOption configsDirectory,
            CommandOption configFile)
        {
            ILogger logger = SimpleConsoleLogger.Instance;

            if (loggerConfigSource.HasValue())
            {
                string nLogPath = loggerConfigSource.Value();
                logger.Info($"Loading NLog configuration file from {nLogPath}.");

                try
                {
                    LogManager.Configuration = new XmlLoggingConfiguration(nLogPath);
                }
                catch (Exception e)
                {
                    logger.Info($"Failed to load NLog configuration from {nLogPath}. {e}");
                }
            }
            else
            {
                logger.Info($"Loading standard NLog.config file from {"NLog.config".GetApplicationResourcePath()}.");
                Stopwatch stopwatch = Stopwatch.StartNew();
                LogManager.Configuration = new XmlLoggingConfiguration("NLog.config".GetApplicationResourcePath());
                stopwatch.Stop();

                logger.Info($"NLog.config loaded in {stopwatch.ElapsedMilliseconds}ms.");
            }

            // TODO: dynamically switch log levels from CLI!
            if (logLevelOverride.HasValue())
            {
                NLogConfigurator.ConfigureLogLevels(logLevelOverride);
            }

            ConfigProvider configProvider          = new ConfigProvider();
            Dictionary <string, string> configArgs = new Dictionary <string, string>();

            foreach (CommandOption commandOption in app.Options)
            {
                if (commandOption.HasValue())
                {
                    configArgs.Add(commandOption.LongName, commandOption.Value());
                }
            }

            IConfigSource argsSource = new ArgsConfigSource(configArgs);

            configProvider.AddSource(argsSource);
            configProvider.AddSource(new EnvConfigSource());

            string configDir          = configsDirectory.HasValue() ? configsDirectory.Value() : DefaultConfigsDirectory;
            string configFilePath     = configFile.HasValue() ? configFile.Value() : DefaultConfigFile;
            string?configPathVariable = Environment.GetEnvironmentVariable("NETHERMIND_CONFIG");

            if (!string.IsNullOrWhiteSpace(configPathVariable))
            {
                configFilePath = configPathVariable;
            }

            if (!PathUtils.IsExplicitlyRelative(configFilePath))
            {
                if (configDir == DefaultConfigsDirectory)
                {
                    configFilePath = configFilePath.GetApplicationResourcePath();
                }
                else
                {
                    configFilePath = Path.Combine(configDir, string.Concat(configFilePath));
                }
            }

            if (!Path.HasExtension(configFilePath) && !configFilePath.Contains(Path.DirectorySeparatorChar))
            {
                string redirectedConfigPath = Path.Combine(configDir, string.Concat(configFilePath, ".cfg"));
                configFilePath = redirectedConfigPath;
                if (!File.Exists(configFilePath))
                {
                    throw new InvalidOperationException($"Configuration: {configFilePath} was not found.");
                }
            }

            if (!Path.HasExtension(configFilePath))
            {
                configFilePath = string.Concat(configFilePath, ".cfg");
            }

            // Fallback to "{executingDirectory}/configs/{configFile}" if "configs" catalog was not specified.
            if (!File.Exists(configFilePath))
            {
                string configName           = Path.GetFileName(configFilePath);
                string?configDirectory      = Path.GetDirectoryName(configFilePath);
                string redirectedConfigPath = Path.Combine(configDirectory ?? string.Empty, configDir, configName);
                configFilePath = redirectedConfigPath;
                if (!File.Exists(configFilePath))
                {
                    throw new InvalidOperationException($"Configuration: {configFilePath} was not found.");
                }
            }

            logger.Info($"Reading config file from {configFilePath}");
            configProvider.AddSource(new JsonConfigSource(configFilePath));
            configProvider.Initialize();
            logger.Info("Configuration initialized.");
            return(configProvider);
        }
Beispiel #11
0
 public RunnerApp(ILogger logger) : base(logger)
 {
 }