protected RemoteConfigurationManager() : base() { //取得远程配置管理文件RemoteConfigurationManager.config string configFile = GetRemoteConfigFile(); try { config = ConfigWatcher.CreateAndSetupWatcher <RemoteConfigurationManagerConfiguration>(configFile); if (config.CheckRemoteConfig) { System.Timers.Timer timer = new System.Timers.Timer(config.TimerInterval); timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerCallback); timer.Start(); // TimerCallback(null,null); } } catch (Exception ex) { HandleException(ex, "无法加载 RemoteConfigurationManager 配置文件, 请在appSettings中设置'" + RemoteConfigFileAppSettingKey + "' ", "RemoteConfigurationManager"); throw ex; } }
/// <summary> /// 重写基类OnCreate方法来创建本地配置实例 /// </summary> /// <param name="sectionName">节点名称</param> /// <param name="type">The type.</param> /// <param name="major">主版本号</param> /// <param name="minor">次版本号</param> /// <returns></returns> protected override object OnCreate(string sectionName, Type type, out int major, out int minor) { major = XmlSerializerSectionHandler.GetConfigurationClassMajorVersion(type); minor = XmlSerializerSectionHandler.DefaultUninitMinorVersion; string configPath = GetConfigSectionFileName(sectionName); if (configPath.Length == 0) { return(null); } object retVal; try { XmlDocument doc = new XmlDocument(); doc.Load(configPath); //初始化配置实例 retVal = XmlSerializerSectionHandler.GetConfigInstance(doc.DocumentElement, type, out major, out minor); // XmlSerializerSectionHandler.GetConfigVersion( doc.DocumentElement , out major , out minor ); } catch (Exception ex) { HandleException(ex, "创建本地配置时出错: sectionName=" + sectionName + ",type=" + type.Name + ", 会创建空实例替代", sectionName); //出现异常通过反射初始化为空配置实例 retVal = Activator.CreateInstance(type); } //为配置文件添加FileWatcher ConfigWatcher.SetupWatcher(configPath, retVal); return(retVal); }
public override void Dispose() { CoinJoinFeeRateStatStore.NewStat -= FeeRateStatStore_NewStat; Arena.CoinJoinBroadcast -= Arena_CoinJoinBroadcast; ConfigWatcher.Dispose(); Warden.Dispose(); base.Dispose(); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await ConfigWatcher.StartAsync(stoppingToken).ConfigureAwait(false); await Warden.StartAsync(stoppingToken).ConfigureAwait(false); await Arena.StartAsync(stoppingToken).ConfigureAwait(false); }
public override async Task StopAsync(CancellationToken cancellationToken) { await base.StopAsync(cancellationToken).ConfigureAwait(false); await ConfigWatcher.StopAsync(cancellationToken).ConfigureAwait(false); await Warden.StopAsync(cancellationToken).ConfigureAwait(false); }
public static void LoadKeys() { var jStore = ConfigWatcher.GetSection("keyStore"); var cStore = jStore.ConvertValue <keyStore>(); client = Convert(cStore.Client); server = Convert(cStore.Server); }
/// <summary> /// Disposes of the Watcher. Removes all events. Class will have to be reinstantiated as the underlying <see cref="FileSystemWatcher"/> was disposed of /// </summary> public void Dispose() { ConfigWatcher.EnableRaisingEvents = false; ConfigWatcher.Changed -= OnChangedConfig; ConfigWatcher.Dispose(); LocationDataWatcher.EnableRaisingEvents = false; LocationDataWatcher.Changed -= OnChangedConfig; LocationDataWatcher.Dispose(); }
public override async Task StopAsync(CancellationToken cancellationToken) { await base.StopAsync(cancellationToken).ConfigureAwait(false); await Arena.StopAsync(cancellationToken).ConfigureAwait(false); await ConfigWatcher.StopAsync(cancellationToken).ConfigureAwait(false); await Warden.StopAsync(cancellationToken).ConfigureAwait(false); await CoinJoinFeeRateStatStore.StopAsync(cancellationToken).ConfigureAwait(false); }
public static T GetSection <T>(string name, string path, out bool fromRemote) { if (System.IO.File.Exists(path)) { fromRemote = false; return(ConfigWatcher.CreateAndSetupWatcher <T>(LocalConfigurationManager.MapConfigPath(path))); } else { fromRemote = true; return(RemoteConfigurationManager.Instance.GetSection <T>(name)); } }
private void MonitorConfigFileChanges(Project project) { var projectName = project.Name; if (_configWatchers.ContainsKey(projectName)) { return; } var configWatcher = new ConfigWatcher(project); _configWatchers[projectName] = configWatcher; configWatcher.AppConfigFileChanged += OnAppConfigFileChanged; }
private void OnStartup(object sender, StartupEventArgs e) { CurrentConfiguration.HostName = System.Net.Dns.GetHostName(); CurrentConfiguration.HostIp = System.Net.Dns.GetHostAddresses(CurrentConfiguration.HostName).Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(ip => ip.ToString()).ToArray(); CurrentConfiguration.RootPath = AppDomain.CurrentDomain.BaseDirectory; CurrentConfiguration.ConfigPath = Path.Combine(CurrentConfiguration.RootPath, "config"); ConfigWatcher.Init(CurrentConfiguration.ConfigPath); KeyStore.LoadKeys(); }
internal Core(string[] args) { Console.Title = $"Initializing..."; Logger = InternalLogger.GetOrCreateLogger <Core>(this, nameof(Core)); OS.Init(true); RuntimeSpanCounter.Restart(); File.WriteAllText("version.txt", Constants.Version?.ToString()); ParseStartupArguments(); if (File.Exists(Constants.TraceLogFile)) { File.Delete(Constants.TraceLogFile); } Config = new CoreConfig(this); Config.LoadAsync().Wait(); IsUpdatesAllowed = !NoUpdates && Config.AutoUpdates; Config.LocalIP = Helpers.GetLocalIpAddress()?.ToString() ?? "-Invalid-"; Config.PublicIP = Helpers.GetPublicIP()?.ToString() ?? "-Invalid-"; if (!IsNetworkAvailable) { Logger.Warn("No Internet connection."); Logger.Info($"Starting offline mode..."); } Pins = new PinsWrapper( Config.GpioConfiguration.OutputModePins, Config.GpioConfiguration.InputModePins, Constants.BcmGpioPins, Config.GpioConfiguration.RelayPins, Config.GpioConfiguration.InfraredSensorPins, Config.GpioConfiguration.SoundSensorPins ); Controller = new GpioCore(Pins, this, Config.GpioConfiguration.GpioSafeMode); ModuleLoader = new ModuleLoader(); RestServer = new RestCore(Config.RestServerPort, Config.Debug); JobManager.AddJob(() => SetConsoleTitle(), (s) => s.WithName("ConsoleUpdater").ToRunEvery(1).Seconds()); Logger.CustomLog(FiggleFonts.Ogre.Render("LUNA"), ConsoleColor.Green); Logger.CustomLog($"---------------- Starting Luna v{Constants.Version} ----------------", ConsoleColor.Blue); IsBaseInitiationCompleted = true; PostInitiation().Wait(); InternalConfigWatcher = new ConfigWatcher(this); InternalModuleWatcher = new ModuleWatcher(this); InitiationCompleted = true; }
public async Task InitializeAsync(Config config, CoordinatorRoundConfig roundConfig, RPCClient rpc, CancellationToken cancel) { Config = Guard.NotNull(nameof(config), config); RoundConfig = Guard.NotNull(nameof(roundConfig), roundConfig); RpcClient = Guard.NotNull(nameof(rpc), rpc); // Make sure RPC works. await AssertRpcNodeFullyInitializedAsync(); // Make sure P2P works. await InitializeP2pAsync(config.Network, config.GetBitcoinP2pEndPoint(), cancel); // Initialize index building var indexBuilderServiceDir = Path.Combine(DataDir, "IndexBuilderService"); var indexFilePath = Path.Combine(indexBuilderServiceDir, $"Index{RpcClient.Network}.dat"); var utxoSetFilePath = Path.Combine(indexBuilderServiceDir, $"UtxoSet{RpcClient.Network}.dat"); IndexBuilderService = new IndexBuilderService(RpcClient, BlockNotifier, indexFilePath, utxoSetFilePath); Coordinator = new Coordinator(RpcClient.Network, BlockNotifier, Path.Combine(DataDir, "CcjCoordinator"), RpcClient, roundConfig); IndexBuilderService.Synchronize(); Logger.LogInfo($"{nameof(IndexBuilderService)} is successfully initialized and started synchronization."); await Coordinator.MakeSureTwoRunningRoundsAsync(); Logger.LogInfo("Chaumian CoinJoin Coordinator is successfully initialized and started two new rounds."); if (roundConfig.FilePath != null) { RoundConfigWatcher = new ConfigWatcher( TimeSpan.FromSeconds(10), // Every 10 seconds check the config RoundConfig, async() => { try { await Coordinator.RoundConfig.UpdateOrDefaultAsync(RoundConfig, toFile: false); Coordinator.AbortAllRoundsInInputRegistration($"{nameof(RoundConfig)} has changed."); } catch (Exception ex) { Logger.LogDebug(ex); } }); RoundConfigWatcher.Start(); Logger.LogInfo($"{nameof(RoundConfigWatcher)} is successfully started."); } }
private static void Postfix() { try { Components.BuildingCompletes.OnAdd += Painter.UpdateBuildingColor; Watcher = new ConfigWatcher(); SimAndRenderScheduler.instance.render1000ms.Add(Watcher); Painter.Refresh(); } catch (Exception e) { State.Logger.Log("MaterialColor init failed"); State.Logger.Log(e); } }
/// <summary> /// HttpProxy 配置,主要配置那些微服务可以提供外部api服务 /// </summary> /// <param name="proxyName">proxyName</param> /// <param name="updateAction">updateAction</param> /// <returns>HttpProxy</returns> public static Configuration GetHttpProxy(string proxyName, Action <Configuration> updateAction) { switch (configCenter.ConfigType) { case ConfigType.Local: case ConfigType.HttpFile: return(config); // 直接返回本地配置 case ConfigType.Zookeeper: Action <Configuration> callBack = (Configuration cfgValue) => { GetHttpProxy(proxyName, updateAction); // 调用一次方法,挂载回调 updateAction(cfgValue); // 重连之后要执行回调,做变更 }; callBackList[proxyName] = callBack; // 断线重连之后,要把当前方法封装起来,作为回调 var router = new ConfigWatcher(); router.OnChange += (string path) => { if (updateAction != null && !string.IsNullOrEmpty(path)) { var proxyStr = ZookeeperManager.GetNodeData(path, router); if (string.IsNullOrEmpty(proxyStr)) { return; } var httpProxy = Newtonsoft.Json.JsonConvert.DeserializeObject <Configuration>(proxyStr); config.HttpProxy = httpProxy.HttpProxy; updateAction(config); } }; string p = ZookeeperManager.getConfigPath(proxyName); var cfg = ZookeeperManager.GetNodeData(p + "/" + SuperHttpProxy.HttpProxy, router); if (string.IsNullOrEmpty(cfg)) { logger.LogWarning("获取代理层配置为空,这个代理层将无法提供代理服务 ServerSetting.GetHttpProxy is Null"); } else { var proxy = Newtonsoft.Json.JsonConvert.DeserializeObject <Configuration>(cfg); config.HttpProxy = proxy.HttpProxy; } return(config); } return(null); }
/// <summary> /// 注册zookeeper使用 /// </summary> /// <param name="serverName"></param> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="enable"></param> /// <param name="timeout"></param> public static void RegisterRouter(string serverName, string ip, int port, bool enable, int timeout) { if (configCenter.ConfigType != ConfigType.Zookeeper) { return; // 本地配置不走zookeeper; } string path = ZookeeperManager.SetRouter(serverName, ip, port, enable, timeout); var cfgWatcher = new ConfigWatcher(); cfgWatcher.OnChange += (string p) => { var changeData = ZookeeperManager.GetNodeData(path, cfgWatcher); if (!string.IsNullOrEmpty(changeData)) { try { var clientItem = Newtonsoft.Json.JsonConvert.DeserializeObject <ClientItem>(changeData); logger.LogWarning($"我的配置被修改为:{changeData}"); if (clientItem != null && !clientItem.Enable) { // 我被下线了,更新本地配置"Enable": false,下一次重启需要带上这个状态 logger.LogInformation($"我被管理员下线了,哼。。。。serverName={serverName},ip={ip},port = {port}"); } else { logger.LogInformation($"我被管理员上线了,哈哈哈哈。。。。serverName={serverName},ip={ip},port = {port}"); } // 在这里修改本地配置快照 if (clientItem == null || string.IsNullOrEmpty(clientItem.Ip) || clientItem.Port < 1) { return; } config.ServerConfig.RpcService.Ip = clientItem.Ip; config.ServerConfig.RpcService.Port = clientItem.Port; config.ServerConfig.RpcService.Pool = clientItem.Pool; config.ServerConfig.RpcService.Enable = clientItem.Enable; config.ServerConfig.RpcService.TimeOut = clientItem.TimeOut; //copyConfig(); 暂时注掉,这里还没思考好 } catch (Exception e) { logger.LogCritical(e, $"RegisterRouter.cfgWatcher.OnChange.Error,serverName={serverName},ip={ip},port = {port}"); } } }; ZookeeperManager.GetNodeData(path, cfgWatcher); // 监控自己router节点的内容,有可能被置为下线; }
public async Task InitializeAsync(Config config, CcjRoundConfig roundConfig, RPCClient rpc) { Config = Guard.NotNull(nameof(config), config); RoundConfig = Guard.NotNull(nameof(roundConfig), roundConfig); RpcClient = Guard.NotNull(nameof(rpc), rpc); // Make sure RPC works. await AssertRpcNodeFullyInitializedAsync(); // Make sure P2P works. await InitializeP2pAsync(config.Network, config.GetBitcoinCoreEndPoint()); // Initialize index building var indexBuilderServiceDir = Path.Combine(DataDir, nameof(IndexBuilderService)); var indexFilePath = Path.Combine(indexBuilderServiceDir, $"Index{RpcClient.Network}.dat"); var utxoSetFilePath = Path.Combine(indexBuilderServiceDir, $"UtxoSet{RpcClient.Network}.dat"); IndexBuilderService = new IndexBuilderService(RpcClient, TrustedNodeNotifyingBehavior, indexFilePath, utxoSetFilePath); Coordinator = new CcjCoordinator(RpcClient.Network, TrustedNodeNotifyingBehavior, Path.Combine(DataDir, nameof(CcjCoordinator)), RpcClient, roundConfig); IndexBuilderService.Synchronize(); Logger.LogInfo <IndexBuilderService>("IndexBuilderService is successfully initialized and started synchronization."); await Coordinator.MakeSureTwoRunningRoundsAsync(); Logger.LogInfo <CcjCoordinator>("Chaumian CoinJoin Coordinator is successfully initialized and started two new rounds."); if (roundConfig.FilePath != null) { RoundConfigWatcher = new ConfigWatcher(RoundConfig); RoundConfigWatcher.Start(TimeSpan.FromSeconds(10), () => { try { Coordinator.UpdateRoundConfig(RoundConfig); Coordinator.AbortAllRoundsInInputRegistration(nameof(ConfigWatcher), $"{nameof(RoundConfig)} has changed."); } catch (Exception ex) { Logger.LogDebug <ConfigWatcher>(ex); } return(Task.CompletedTask); }); // Every 10 seconds check the config Logger.LogInfo <ConfigWatcher>($"{nameof(RoundConfigWatcher)} is successfully started."); } }
static void Main() { var receiver = new Receiver(new FileManager()); var configWatcher = new ConfigWatcher(); var cts = new CancellationTokenSource(); var token = cts.Token; var task = receiver.Run(token); configWatcher.Start(token); Console.WriteLine("Service started"); Console.WriteLine("Press any key to stop service"); Console.ReadKey(); cts.Cancel(); Task.WaitAll(task); Console.WriteLine("Service stopped"); Thread.Sleep(1000); }
/// <summary> /// 重写基类OnCreate方法来创建远程配置实例(原理其实还是把远程配置下载到本地创建本地配置实例) /// </summary> /// <param name="sectionName">Name of the section.</param> /// <param name="type">The type.</param> /// <param name="major">The major.</param> /// <param name="minor">The minor.</param> /// <returns></returns> protected override object OnCreate(string sectionName, Type type, out int major, out int minor) { string fileName = GetFileName(sectionName); //string path = GetPath( sectionName ); string path = ConfigUtility.Combine(config.LocalApplicationFolder, fileName); object obj = CreateLocalObject(type, path, out major, out minor); if (obj != null) { return(obj); } major = XmlSerializerSectionHandler.GetConfigurationClassMajorVersion(type); minor = XmlSerializerSectionHandler.DefaultUninitMinorVersion; try { RemoteConfigSectionParam newParams = GetServerVersion(sectionName, major); if (newParams != null) { //从远程下载! if (Download(newParams.SectionName, newParams.DownloadUrl, path, CheckDownloadStream)) { obj = CreateLocalObject(type, path, out major, out minor);//下载远程配置到本地后创建配置实例 } } } catch (Exception ex) { HandleException(ex, "从远程服务器下载配置 '" + sectionName + "' 时出错", sectionName); } //如果对象为null通过反射默认对象替代 if (obj == null) { LoggerWrapper.Logger.Info("无法从 RemoteConfiguration 取得拥有类型'" + type.Name + "' 的'" + sectionName + "' 节点,通将过反射创建空实例替代"); obj = Activator.CreateInstance(type); //为配置添加文件更改监控 ConfigWatcher.SetupWatcher(path, obj); ConfigWatcher.RegisterReloadNotification(path, OnConfigFileChanged); } return(obj); }
private static void initlizeData(string appName) { // 检查标准配置,第一次可能zk是空 // 检查标准配置节点,帮助初始化 var standConfig = getStandConfig(); ZookeeperManager.CheckConfig(appName, standConfig); // 拉取当前AppName的配置,需要注册watcher var dataWatcher = new ConfigWatcher(); dataWatcher.OnChange += (string path) => { string configData = ZookeeperManager.GetNodeData(path, dataWatcher); if (string.IsNullOrEmpty(configData)) { return; } UpdateZookeeper(path, configData); }; List <string> childrens = ZookeeperManager.GetConfigChildren(appName, null); // 配置是整个获取节点,分别获取配置和分别增加watcher if (childrens != null && childrens.Count > 0) { string root = ZookeeperManager.getConfigPath(appName); if (string.IsNullOrEmpty(root)) { return; } foreach (var item in childrens) { // 需要根据节点路径来判断是哪个节点变化了 string path = root + "/" + item; string configData = ZookeeperManager.GetNodeData(path, dataWatcher); UpdateZookeeper(path, configData); } } }
private object CreateLocalObject(Type type, string path, out int major, out int minor) { try { if (File.Exists(path)) { XmlDocument doc = new XmlDocument(); doc.Load(path); object obj = ConfigWatcher.CreateAndSetupWatcher(doc.DocumentElement, path, type, OnConfigFileChanged); XmlSerializerSectionHandler.GetConfigVersion(doc.DocumentElement, out major, out minor); return(obj); } } catch (Exception ex) { HandleException(ex, "RemoteConfigurationManager.CreateLocalObject,type=" + type.Name + ",path=" + path, type.Name); } major = XmlSerializerSectionHandler.GetConfigurationClassMajorVersion(type); minor = XmlSerializerSectionHandler.DefaultUninitMinorVersion; return(null); }
public static async Task Start() { try { log.LogInformation("Инициализация"); wsTunnelConfig = ConfigWatcher.GetSection("wstunnel").ConvertValue <WSTunnelConfig>(); client = new WsClient(); await client.OpenManagerTunnel(wsTunnelConfig, DisconnectTunnel, DisconnectSocket); await client.Auth(); var tunnelGuid = await client.OpenDataTunnel(DataReceiver, DisconnecDataTunnel); dataConnections.TryAdd(tunnelGuid, new WSDataConnectionInfo { TunnelId = tunnelGuid }); var testObj = new EchoReq { ReqId = Guid.NewGuid(), Timestamp = DateTime.UtcNow }; var buffer = Encoding.UTF8.GetBytes(testObj.ToJson()); await client.SendData(tunnelGuid, Guid.Empty, buffer, buffer.Length); log.LogInformation($"Послали echo - {testObj.ReqId}"); server = new Socks5Server(); server.Start(wsTunnelConfig.Port, RequireNewConnection, TransferData, CloseSocket); } catch (Exception e) { log.LogError($"Ошибка инициализации: {e.Message}"); server?.Dispose(); client?.Dispose(); } }
public override void Dispose() { ConfigWatcher.Dispose(); Warden.Dispose(); base.Dispose(); }
private static void WatchConfig(string configPath) { FileInfo configFile = new FileInfo(configPath); configWatcher = new ConfigWatcher(configFile.Directory.FullName, configFile.Name); configWatcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite; configWatcher.Changed += new FileSystemEventHandler(OnConfigFileChanged); configWatcher.Start(); }