コード例 #1
0
        public ConfigItem[] GetLastUpdatedConfigItems(string appName, ref byte[] lastRowVersion, int limit)
        {
            try
            {
                using (ConfigDbContext context = new ConfigDbContext())
                {
                    ConfigItem[] configItems;
                    if (lastRowVersion == null)
                    {
                        configItems = context.Database.SqlQuery <ConfigItem>(
                            string.Format("SELECT TOP {0} * FROM ConfigItem WHERE (AppName IS NULL OR AppName = @AppName) ORDER BY RowVersion", limit),
                            new SqlParameter("AppName", appName)).ToArray();
                    }
                    else
                    {
                        configItems = context.Database.SqlQuery <ConfigItem>(
                            string.Format("SELECT TOP {0} * FROM ConfigItem  WHERE (AppName IS NULL OR AppName = @AppName)  AND (RowVersion > @RowVersion) ORDER BY RowVersion", limit),
                            new SqlParameter("RowVersion", lastRowVersion), new SqlParameter("AppName", appName)).ToArray();
                    }

                    if (configItems != null && configItems.Length != 0)
                    {
                        lastRowVersion = configItems[configItems.Length - 1].RowVersion;
                    }
                    return(configItems);
                }
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error(ex.ToString());
            }
            return(null);
        }
コード例 #2
0
        private void BatchLoadConfigItems()
        {
            int loadedItemsCount = 0;

            LocalLoggingService.Info("开始批量加载配置项");
            try
            {
                ConfigItem[] configItems = null;
                int          batchCount  = 0;
                do
                {
                    configItems = ConfigServer.GetLastUpdatedConfigItems(_appName, ref _lastRowVersion, _batchLoadSize);
                    if (configItems != null && configItems.Length > 0)
                    {
                        foreach (ConfigItem configItem in configItems)
                        {
                            UpdateConfigItemCache(configItem);
                            loadedItemsCount++;
                        }
                        batchCount++;
                        LocalLoggingService.Info("加载第 {0} 批配置项结束", batchCount);
                    }
                }while (configItems != null && configItems.Length > 0);
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("批量加载配置项错误!{0}", ex);
            }
            LocalLoggingService.Info("结束批量加载配置项,共加载 {0} 个配置项。", loadedItemsCount);
        }
コード例 #3
0
        protected static void ProcessInfo(AbstractInfo info)
        {
            var strategy = GetIncludeInfoStrategy(info);

            infoProviderList.Each(provider =>
            {
                try
                {
                    if (strategy == null)
                    {
                        throw new Exception("ProcessInfo strategy == null");
                    }
                    if (info == null)
                    {
                        throw new Exception("ProcessInfo info == null");
                    }

                    provider.ProcessInfo(strategy, info);
                }
                catch (Exception ex)
                {
                    LocalLoggingService.Error(string.Format("处理数据出错!步骤名:{0},异常信息:{1}", provider.GetType().Name, ex.ToString()));
                }
            });
        }
コード例 #4
0
        public override TaskContinuation Execute()
        {
            try
            {
                if (!AppInfoCenterService.HealthActionRegistered)
                {
                    LocalLoggingService.Debug("请调用AppInfoCenterService.RegisterHealthAction()注册健康检测回调方法!");
                }

                //应用程序域未处理异常
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                //页面性能统计服务
                //PagePerformanceService.Init();

                //applicationStateService = AppInfoCenterService.StateService;
                //applicationStateService.Init(new StateServiceConfiguration(typeof(ApplicationStateInfo).FullName, ApplicationStateService.GetState));
                //if (HttpContext.Current != null)
                //{
                //    activeRequestStateService = AppInfoCenterService.StateService;
                //    activeRequestStateService.Init(new StateServiceConfiguration(typeof(WebsiteRequestStateInfo).FullName, ActiveRequestStateService.GetState));
                //}
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("初始化信息中心服务出错,异常信息:{0}", ex);
                return(TaskContinuation.Break);
            }
            return(TaskContinuation.Continue);
        }
コード例 #5
0
 private void NodeError(ClientNode node)
 {
     LocalLoggingService.Warning("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientCluster", "NodeError",
                                 string.Format("集群 {0} 中节点 {1} 出现错误,尝试从集群中移除节点", config.Name, node.Name));
     locker.EnterWriteLock();
     try
     {
         if (!deadClientNodes.ContainsKey(node.Name))
         {
             deadClientNodes.Add(node.Name, node);
         }
         if (clientNodes.ContainsKey(node.Name))
         {
             clientNodes.Remove(node.Name);
         }
         if (clientNodes.Count == 0)
         {
             LocalLoggingService.Error("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientCluster", "NodeError",
                                       string.Format("严重错误,集群 {0} 中的所有节点都已经失效!", config.Name));
         }
         node.Destory();
         InitNodeLocator();
         LocalLoggingService.Warning("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientCluster", "NodeError",
                                     string.Format("集群 {0} 中节点 {1} 出现错误,已经从集群中移除", config.Name, node.Name));
     }
     catch (Exception ex)
     {
         LocalLoggingService.Error("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientCluster", "NodeError", ex.Message);
     }
     finally
     {
         locker.ExitWriteLock();
     }
 }
コード例 #6
0
 private void InternalLog(LogLevel logLevel, string moduleName, string categoryName, string subcategoryName, string message, ExtraInfo extraInfo)
 {
     try
     {
         if (AppInfoCenterConfiguration.GetConfig().LoggingServiceConfig.Enabled)
         {
             var strategy = GetLogStrategy(moduleName, logLevel);
             if (strategy != null)
             {
                 if (strategy.LocalLog)
                 {
                     LocalLog(logLevel, moduleName, categoryName, subcategoryName, message, extraInfo);
                 }
                 if (strategy.RemoteLog)
                 {
                     var info = new LogInfo();
                     info.LogLevel        = logLevel;
                     info.ModuleName      = moduleName;
                     info.CategoryName    = categoryName;
                     info.SubCategoryName = subcategoryName;
                     info.Message         = message;
                     info.ExtraInfo       = extraInfo;
                     ProcessInfo(info);
                     MongodbService.MongodbInsertService.Insert(info);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         LocalLoggingService.Error("InternalLog出现错误,异常信息为:" + ex.ToString());
     }
 }
コード例 #7
0
        public static T GetClient(string clusterName)
        {
            if (!clusters.ContainsKey(clusterName))
            {
                lock (clusters)
                {
                    if (!clusters.ContainsKey(clusterName))
                    {
                        var config = DistributedServerConfiguration.GetClientClusterConfiguration(clusterName);
                        if (config == null)
                        {
                            throw new Exception(string.Format("没有找到集群 {0} 的配置信息!", clusterName));
                        }
                        LocalLoggingService.Info("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "AbstractClient", "GetClient", string.Format("开始初始化集群 {0}", clusterName));
                        var cluster = new ClientCluster(config);
                        clusters.Add(clusterName, cluster);
                    }
                }
            }

            var instance = new T();

            instance.ClusterName = clusterName;
            return(instance);
        }
コード例 #8
0
 internal static void Reset()
 {
     Collector.Reset();
     LocalLoggingService.Info("收集器重启成功");
     Aggregator.Reset();
     LocalLoggingService.Info("聚合器重启成功");
 }
コード例 #9
0
 private void InternalGetTableData(Detail detail, Dictionary <string, string> row)
 {
     try
     {
         if (detail.SubDetails != null)
         {
             foreach (var sub in detail.SubDetails)
             {
                 var subdic = new Dictionary <string, string>();
                 InternalGetTableData(sub, subdic);
                 foreach (var item in subdic)
                 {
                     if (!row.ContainsKey(item.Key))
                     {
                         row.Add(item.Key, item.Value);
                     }
                 }
             }
         }
         else
         {
             if (!row.ContainsKey(detail.DisplayName.Replace('.', '_')))
             {
                 row.Add(detail.DisplayName.Replace('.', '_'), detail.Value == null ? "" : detail.Value.ToString());
             }
         }
     }
     catch (Exception ex)
     {
         LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServer_Table", "InternalGetTableData", ex.Message);
         throw;
     }
 }
コード例 #10
0
        private MongodbData ConvertItemToMongodbData(object item)
        {
            var type         = item.GetType();
            var typeFullName = type.FullName;

            try
            {
                var data = new MongodbData();
                data.TypeFullName = typeFullName;
                data.TableName    = "General";

                if (!mongodbDatabaseDescriptionCache.ContainsKey(typeFullName))
                {
                    LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServiceConfiguration.ModuleName, "ConvertItemToMongodbData", typeFullName,
                                              string.Format("没取到类型为 '{0}' 的元数据!", typeFullName));
                    return(null);
                }

                var mongodbDatabaseDescription = mongodbDatabaseDescriptionCache[typeFullName];
                data.DatabaseName = mongodbDatabaseDescription.DatabasePrefix;

                JavaScriptSerializer s = new JavaScriptSerializer();
                var rawData            = GetMongodbData(data, type, item);
                var jsonData           = s.Serialize(rawData);
                data.Data = jsonData;
                return(data);
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServiceConfiguration.ModuleName, "ConvertItemToMongodbData", typeFullName, ex.Message);
                throw;
            }
        }
コード例 #11
0
        private void InternalSubmitData(IList <object> items)
        {
            if (items == null || items.Count == 0)
            {
                return;
            }

            var item         = items.First();
            var type         = item.GetType();
            var typeFullName = type.FullName;

            try
            {
                Stopwatch sw = Stopwatch.StartNew();
                var       mongodbDataList = items.Select(_ => ConvertItemToMongodbData(_)).Where(_ => _ != null).ToList();
                var       desc            = mongodbDatabaseDescriptionCache[typeFullName];
                MongodbServiceLocator.GetService().SubmitData(mongodbDataList, desc.SentToServer ? null : desc);
                //LocalLoggingService.Debug("AdhesiveFramework.MongodbInsertService 提交了 {0} 条数据到服务端,类型是 '{1}',提交了描述信息?{2},耗时:{3}毫秒", mongodbDataList.Count.ToString(), typeFullName, (!desc.SentToServer).ToString(), sw.ElapsedMilliseconds.ToString());
                desc.SentToServer = true;
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServiceConfiguration.ModuleName, "InternalSubmitData", typeFullName, ex.Message);
            }
        }
コード例 #12
0
 private void SyncConfigCacheWorker()
 {
     while (!_isStoped)
     {
         LocalLoggingService.Debug("开始配置项缓存同步");
         int syncedItemsCount = 0;
         try
         {
             ConfigItem[] lastUpdatedConfigItems = ConfigServer.GetLastUpdatedConfigItems(_appName, ref _lastRowVersion, true);
             if (lastUpdatedConfigItems != null && lastUpdatedConfigItems.Length > 0)
             {
                 LocalLoggingService.Info(string.Format("获取 {0} 个变更的配置项", lastUpdatedConfigItems.Length));
                 foreach (ConfigItem updatedConfigItem in lastUpdatedConfigItems)
                 {
                     ConfigItemState configItemState = UpdateConfigItemCache(updatedConfigItem);
                     LocalLoggingService.Info("配置项缓存已同步,Id:{0},State:{1}", updatedConfigItem.Id, configItemState);
                     syncedItemsCount++;
                 }
             }
         }
         catch (Exception ex)
         {
             LocalLoggingService.Error("配置项缓存同步错误。 {0}", ex);
         }
         LocalLoggingService.Debug("结束配置项缓存同步,共同步 {0} 个配置项,本次同步版本号:{1},休眠 {2} ms。", syncedItemsCount, _lastRowVersion == null ? "NULL" : BitConverter.ToString(_lastRowVersion), _syncConfigCacheInterval);
         Thread.Sleep(_syncConfigCacheInterval);
     }
 }
コード例 #13
0
        private SubCategory GetSubCategory(MongodbDatabaseDescription description, ServerInfo serverInfo)
        {
            try
            {
                var subCategory = new SubCategory()
                {
                    DatabasePrefix = description.DatabasePrefix,
                    DisplayName    = description.DisplayName,
                    Name           = description.Name,
                    TableNames     = new List <string>(),
                    TypeFullName   = description.TypeFullName,
                };

                subCategory.TableNames = serverInfo.Databases
                                         .Where(database => database.DatabaseName.StartsWith(description.DatabasePrefix))
                                         .SelectMany(database => database.Collections).Select(collection => collection.CollectionName).Distinct().ToList();

                return(subCategory);
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServer_Slave", "GetSubCategory", ex.Message);
                throw;
            }
        }
コード例 #14
0
 public override TaskContinuation Execute()
 {
     LocalLoggingService.Info("开始初始化持久化服务");
     try
     {
         BuildManagerWrapper.Current.PublicTypes.Where(e => e != null && e.IsSubclassOf(typeof(StorageContext)) && !e.IsAbstract)
         .Each(e =>
         {
             using (StorageContext context = LocalServiceLocator.GetService <IDbContextFactory>().CreateContext(e))
             {
                 context.Database.CreateIfNotExists();
                 var script = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();
                 if (!string.IsNullOrEmpty(script))
                 {
                     try
                     {
                         context.Database.ExecuteSqlCommand(script);
                     }
                     catch (Exception ex)
                     {
                         LocalLoggingService.Warning(ex.ToString());
                     }
                 }
                 //Console.WriteLine(script);
             }
         });
         LocalLoggingService.Info("初始化持久化服务完成");
     }
     catch (Exception ex)
     {
         LocalLoggingService.Error("开始初始化持久化服务失败,异常信息:{0}", ex);
         return(TaskContinuation.Break);
     }
     return(TaskContinuation.Continue);
 }
コード例 #15
0
        private void LocalLog(ExceptionInfo info, Exception exception, string moduleName, string categoryName, string subcategoryName, string description, ExtraInfo extraInfo)
        {
            var message = new StringBuilder();

            if (info != null)
            {
                message.Append(string.Format("异常类型:{0} ", info.GetType().Name));
            }
            if (!string.IsNullOrEmpty(moduleName))
            {
                message.Append(string.Format("模块名:{0} ", moduleName));
            }
            if (!string.IsNullOrEmpty(categoryName))
            {
                message.Append(string.Format("大类:{0} ", categoryName));
            }
            if (!string.IsNullOrEmpty(subcategoryName))
            {
                message.Append(string.Format("小类:{0} ", subcategoryName));
            }
            if (!string.IsNullOrEmpty(description))
            {
                message.Append(string.Format("描述:{0} ", description));
            }
            if (extraInfo != null)
            {
                message.Append(string.Format("额外信息:{0} ", extraInfo));
            }
            message.Append(string.Format("异常信息:{0} ", exception.ToString()));
            LocalLoggingService.Error(message.ToString());
        }
コード例 #16
0
        internal ClientNode(ClientNodeConfiguration config, Action <ClientNode> errorAction)
        {
            if (string.IsNullOrEmpty(config.Address))
            {
                throw new ArgumentNullException(string.Format("{0}.Address"), config.Name);
            }
            if (config.Address.Split(':').Length != 2)
            {
                throw new ArgumentException(string.Format("{0}.Address格式必须为IP:Port", config.Name), "Address");
            }
            var port = 0;

            if (!int.TryParse(config.Address.Split(':')[1], out port))
            {
                throw new ArgumentException(string.Format("{0}.Address的端口号不是数字", config.Name), "Address");
            }
            if (config.MaxConnections < config.MinConnections)
            {
                throw new ArgumentException(string.Format("{0}.MaxConnections不能小于{0}.MinConnections", config.Name), "MaxConnections");
            }

            if (config.ConnectTimeout < TimeSpan.FromMilliseconds(100))
            {
                config.ConnectTimeout = TimeSpan.FromMilliseconds(100);
            }
            if (config.ReceiveTimeout < TimeSpan.FromMilliseconds(100))
            {
                config.ReceiveTimeout = TimeSpan.FromMilliseconds(100);
            }
            if (config.SendTimeout < TimeSpan.FromMilliseconds(100))
            {
                config.SendTimeout = TimeSpan.FromMilliseconds(100);
            }

            if (config.MaxIdleTime < TimeSpan.FromSeconds(1))
            {
                config.MaxIdleTime = TimeSpan.FromSeconds(1);
            }
            if (config.MaxBusyTime < TimeSpan.FromSeconds(1))
            {
                config.MaxBusyTime = TimeSpan.FromSeconds(1);
            }
            if (config.MaintenanceInterval < TimeSpan.FromSeconds(1))
            {
                config.MaintenanceInterval = TimeSpan.FromSeconds(1);
            }

            this.config = config;
            this.nodeErrorCallbackAction = errorAction;
            LocalLoggingService.Info("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientNode", "ClientNode",
                                     string.Format("开始初始化一个新的节点:{0}", Name));
            Init();
            maintainThread = new Thread(MaintainThreadAction)
            {
                IsBackground = true,
                Name         = string.Format("{0}_{1}", "Adhesive.DistributedComponentClient_NodeMaintainThread", config.Name),
            };
            maintainThread.Start();
            IsAlive = true;
        }
コード例 #17
0
 internal void Recover()
 {
     Init();
     IsAlive = true;
     LocalLoggingService.Info("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientNode", "Recover",
                              string.Format("节点 {0} 成功恢复", Name));
 }
コード例 #18
0
        private ClientSocket CreateClientSocket(bool isDirectSocket, Action <ClientSocket> disposeAction, Action <ClientSocket> lowlevelErrorAction, Action <ClientSocket> highLevelErrorAction)
        {
            var ip     = config.Address.Split(':')[0];
            var port   = Convert.ToInt16(config.Address.Split(':')[1]);
            var socket = new ClientSocket(disposeAction, lowlevelErrorAction, highLevelErrorAction,
                                          Convert.ToInt16(((TimeSpan)config.SendTimeout).TotalMilliseconds),
                                          Convert.ToInt16(((TimeSpan)config.ReceiveTimeout).TotalMilliseconds), ip, port);

            try
            {
                socket.Connect(Convert.ToInt16(((TimeSpan)config.ConnectTimeout).TotalMilliseconds));
                return(socket);
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientNode", "Init", ex, string.Format("节点 {0} 连接socket出错", config.Name), ex.Message);
                if (!isDirectSocket)
                {
                    CloseClientSocketAndNode(socket);
                }
                else
                {
                    socket.Destroy();
                }
            }

            return(null);
        }
コード例 #19
0
        public static void Start()
        {
            AdhesiveFramework.Start();
            LocalLoggingService.Info("框架启动成功");
            StartService();
            LocalLoggingService.Info("WCF服务启动成功");
            var config = Configuration.GetConfig();
            var pp     = new GreneralPerformanceCollector(config.PagePerformance);

            pp.Start();
            collectors.Add(config.PagePerformance.Name, pp);
            //var wcp = new GreneralPerformanceCollector(config.WcfClientPerformance);
            //wcp.Start();
            //collectors.Add(config.WcfClientPerformance.Name, wcp);
            var wsp = new GreneralPerformanceCollector(config.WcfServerPerformance);

            wsp.Start();
            collectors.Add(config.WcfServerPerformance.Name, wsp);
            LocalLoggingService.Info("收集器启动成功");

            var ppg = new GeneralPerformanceAggregator(config.PagePerformance);

            ppg.Start();
            aggregators.Add(config.PagePerformance.Name, ppg);
            //var wcpg = new GeneralPerformanceAggregator(config.WcfClientPerformance);
            //wcpg.Start();
            //aggregators.Add(config.WcfClientPerformance.Name, wcpg);
            var wspg = new GeneralPerformanceAggregator(config.WcfServerPerformance);

            wspg.Start();
            aggregators.Add(config.WcfServerPerformance.Name, wspg);
            LocalLoggingService.Info("聚合器启动成功");
        }
コード例 #20
0
        private void Init()
        {
            locker.EnterWriteLock();

            idleSockets.Clear();
            busySockets.Clear();

            locker.ExitWriteLock();

            for (int i = 0; i < config.MinConnections; i++)
            {
                var socket = CreateClientSocket(false, ReturnClientSocket, CloseClientSocket, CloseClientSocketAndNode);
                if (socket != null)
                {
                    locker.EnterWriteLock();
                    try
                    {
                        idleSockets.Add(socket);
                    }
                    finally
                    {
                        locker.ExitWriteLock();
                    }
                }
                else
                {
                    LocalLoggingService.Warning("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientNode", "Init",
                                                string.Format("节点 {0} 中Init尝试创建一个新的socket失败", config.Name));
                    break;
                }
            }
            LocalLoggingService.Info("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientNode", "Init",
                                     string.Format("节点 {0} 初始化 {1} 个socket", config.Name, idleSockets.Count));
        }
コード例 #21
0
        private void Reset()
        {
            try
            {
                if (socket == null)
                {
                    return;
                }

                if (stream != null)
                {
                    stream.Flush();
                }

                int available = socket.Available;

                if (available > 0)
                {
                    byte[] data = new byte[available];
                    socket.Receive(data, 0, available, SocketFlags.None);
                    LocalLoggingService.Warning("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientSocket", "Reset",
                                                string.Format("Reset socket {0} 时候还有未读取完的数据: {1}!", Endpoint.ToString(), FormatData(data)));
                }
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientSocket", "Reset", string.Format("从 {0} 接受数据出错", Endpoint.ToString()), ex.ToString());
                lowlevelErrorAction(this);
            }
        }
コード例 #22
0
        public DetailData GetDetailDataOnlyById(string databasePrefix, string Id)
        {
            try
            {
                var databaseInfos      = MongodbServerMaintainceCenter.GetDatabaseInfos(databasePrefix);
                var columnDescriptions = MongodbServerMaintainceCenter.GetMongodbColumnDescriptions(databasePrefix);
                var pkColumn           = columnDescriptions.FirstOrDefault(desc => desc.IsPrimaryKey);
                if (pkColumn == null)
                {
                    return(null);
                }

                foreach (var databaseInfo in databaseInfos)
                {
                    foreach (var collectionInfo in databaseInfo.Collections)
                    {
                        var data = GetDetailData(databasePrefix, databaseInfo.DatabaseName, collectionInfo.CollectionName, pkColumn.ColumnName, Id);
                        if (data != null)
                        {
                            return(data);
                        }
                    }
                }

                return(null);
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServer_Detail", "GetDetailDataOnlyById", ex.Message);
                throw;
            }
        }
コード例 #23
0
 internal static List <DatabaseInfo> GetDatabaseInfos(string databasePrefix, DateTime beginTime, DateTime endTime)
 {
     locker.EnterReadLock();
     try
     {
         var rtn = servers.Select(item => item.Value).Where(item => item.Databases != null)
                   .SelectMany(s => s.Databases).Where(database => database != null && database.DatabasePrefix == databasePrefix &&
                                                       database.DatabaseDate.ToLocalTime() >= new DateTime(beginTime.Year, beginTime.Month, 1) && database.DatabaseDate.ToLocalTime() <= endTime).OrderByDescending(d => d.DatabaseDate).ToList();
         if (rtn == null || rtn.Count == 0)
         {
             LocalLoggingService.Warning("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "GetDatabaseInfos",
                                         string.Format("没取到数据,参数:{0},{1},{2}", databasePrefix, beginTime, endTime));
         }
         return(rtn);
     }
     catch (Exception ex)
     {
         LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "GetDatabaseInfos", ex.Message);
         return(null);
     }
     finally
     {
         locker.ExitReadLock();
     }
 }
コード例 #24
0
        internal void Write(byte[] data, int offset, int length)
        {
            if (socket == null)
            {
                LocalLoggingService.Error("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientSocket", "Write",
                                          string.Format("Write 发送时没有获取到socket {0}", Endpoint.ToString()));
                return;
            }

            SocketError status;

            try
            {
                socket.Send(data, offset, length, SocketFlags.None, out status);

                if (status != SocketError.Success)
                {
                    Status = ClientSocketStatus.Error;
                    LocalLoggingService.Error("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientSocket", "Write",
                                              string.Format("Write 发送数据到 {0} 出错,错误为:{1}", Endpoint.ToString(), status.ToString()));
                    highLevelErrorAction(this);
                }
            }
            catch (Exception ex)
            {
                Status = ClientSocketStatus.Error;
                LocalLoggingService.Error("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientSocket", "Write", string.Format("发送数据到 {0} 出错", Endpoint.ToString()), ex.ToString());
                highLevelErrorAction(this);
            }
        }
コード例 #25
0
 internal static List <MongodbColumnDescription> GetMongodbColumnDescriptions(string databasePrefix)
 {
     locker.EnterReadLock();
     try
     {
         var rtn = servers.Select(item => item.Value).Where(item => item.Descriptions != null)
                   .SelectMany(s => s.Descriptions).Where(description => description != null && description.DatabasePrefix == databasePrefix)
                   .SelectMany(desc => desc.MongodbColumnDescriptionList).ToList();
         if (rtn == null || rtn.Count == 0)
         {
             LocalLoggingService.Warning("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "GetMongodbColumnDescriptions",
                                         string.Format("没取到数据,参数:{0}", databasePrefix));
         }
         return(rtn);
     }
     catch (Exception ex)
     {
         LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "GetMongodbColumnDescriptions", ex.Message);
         return(null);
     }
     finally
     {
         locker.ExitReadLock();
     }
 }
コード例 #26
0
        //internal static List<MongodbServerStateInfo> GetState()
        //{
        //    lock (submitDataMemoryQueueServices)
        //    {
        //        var state = new List<MongodbServerStateInfo>()
        //        {
        //            new MongodbServerStateInfo
        //            {
        //                MemoryQueueServiceStates = submitDataMemoryQueueServices.ToDictionary(s=>s.Key, s=>s.Value.GetState()),
        //            }
        //        };
        //        return state;
        //    }
        //}

        private static MongoServer CreateMasterMongoServer(string typeName)
        {
            if (!masterServerCache.ContainsKey(typeName))
            {
                lock (masterServerCache)
                {
                    if (!masterServerCache.ContainsKey(typeName))
                    {
                        var config = MongodbServerConfiguration.GetMongodbServerConfigurationItem(typeName);
                        if (config == null)
                        {
                            LocalLoggingService.Warning("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServer_Master", "CreateMasterMongoServer",
                                                        string.Format("没取到服务器配置项,参数:{0}", typeName));
                            return(null);
                        }
                        var server = MongodbServerConfiguration.GetMongodbServerUrl(config.MongodbServerUrlName);
                        if (server == null)
                        {
                            LocalLoggingService.Warning("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServer_Master", "CreateMasterMongoServer",
                                                        string.Format("没取到服务器地址,参数:{0}", config.MongodbServerUrlName));
                            return(null);
                        }
                        masterServerCache.Add(typeName, MongoServer.Create(server.Master));
                    }
                }
            }
            return(masterServerCache[typeName]);
        }
コード例 #27
0
        private void InternalSubmitData(IList <object> items)
        {
            var mongodbDataList = items.Cast <MongodbData>().ToList();
            var typeFullName    = mongodbDataList.First().TypeFullName;

            var sw = Stopwatch.StartNew();

            var server = CreateMasterMongoServer(typeFullName);

            if (server != null)
            {
                mongodbDataList.ForEach(item =>
                {
                    try
                    {
                        var database     = server.GetDatabase(item.DatabaseName);
                        var collection   = database.GetCollection(item.TableName);
                        var documentList = new List <BsonDocument>();

                        var dic      = s.DeserializeObject(item.Data) as IDictionary;
                        var document = new BsonDocument().Add(dic);
                        HandleDistinctData(document, item.DatabaseName, item.TableName);
                        collection.Insert(document);
                    }
                    catch (Exception ex)
                    {
                        LocalLoggingService.Error("{0} {1} {2} {3} {4}", MongodbServerConfiguration.ModuleName, "MongodbServer_Master", "InternalSubmitData", string.Format("写入数据出现错误,参数:{0}", typeFullName), ex.Message);
                    }
                });

                //LocalLoggingService.Debug("Mongodb服务端成功服务提交 {0} 条数据到数据库,类型是 '{1}',耗时 {2} 毫秒", mongodbDataList.Count.ToString(), typeFullName, sw.ElapsedMilliseconds.ToString());
            }
        }
コード例 #28
0
        private void InternalHandle(ExceptionInfo info, Exception exception, string moduleName, string categoryName, string subcategoryName, string description, ExtraInfo extraInfo)
        {
            if (exception == null)
            {
                return;
            }
            try
            {
                if (AppInfoCenterConfiguration.GetConfig().ExceptionServiceConfig.Enabled)
                {
                    var strategy = GetExceptionStrategy(moduleName, info.GetType().Name, exception.GetType().Name);
                    if (strategy != null)
                    {
                        if (strategy.LocalLog)
                        {
                            LocalLog(info, exception, moduleName, categoryName, subcategoryName, description, extraInfo);
                        }
                        if (strategy.RemoteLog)
                        {
                            info.Exception         = MapException(exception);
                            info.Description       = description;
                            info.ExceptionTypeName = exception.GetType().FullName;
                            info.ExtraInfo         = extraInfo;
                            info.ModuleName        = moduleName;
                            info.CategoryName      = categoryName;
                            info.SubCategoryName   = subcategoryName;
                            info.ExceptionMessage  = exception.Message;
                            ProcessInfo(info);
                            MongodbService.MongodbInsertService.Insert(info);
                        }

                        if (info is WebSiteUnhandledExceptionInfo && HttpContext.Current != null)
                        {
                            HttpContext.Current.Response.Clear();

                            //HttpContext.Current.Response.StatusCode = strategy.ResponseStatusCode;

                            if (!HttpContext.Current.Request.IsLocal && strategy.ClearException)
                            {
                                HttpContext.Current.Server.ClearError();

                                if (!string.IsNullOrEmpty(strategy.RedirectUrl))
                                {
                                    HttpContext.Current.Response.Redirect(string.Format("{0}/?ID={1}", strategy.RedirectUrl.TrimEnd('/'), info.ID), false);
                                }
                                else
                                {
                                    HttpContext.Current.Response.Write(string.Format(AppInfoCenterConfiguration.GetConfig().ExceptionServiceConfig.UnhandledExceptionMessage, info.ID));
                                    HttpContext.Current.Response.End();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("InternalHandle出现错误,异常信息为:" + ex.ToString());
            }
        }
コード例 #29
0
 private void CloseClientSocketAndNode(ClientSocket socket)
 {
     LocalLoggingService.Warning("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "ClientNode", "CloseClientSocketAndNode",
                                 string.Format("节点 {0} 已经无效", config.Name));
     this.IsAlive = false;
     socket.Destroy();
     nodeErrorCallbackAction(this);
 }
コード例 #30
0
 internal static void ConfigUpdateCallbackForSlave()
 {
     LocalLoggingService.Info("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServer_Slave", "ConfigUpdateCallbackForSlave", "配置改变,重新初始化");
     lock (slaveServerCache)
     {
         slaveServerCache.Clear();
     }
 }