public static void ConfigureRoute(IContainer mapper, string mappingIp, int mappingPort, string serviceToken)
        {
            var serviceEntryManager = mapper.Resolve <IServiceEntryManager>();

            if (AppConfig.ServerOptions.Protocol == CommunicationProtocol.Tcp || AppConfig.ServerOptions.Protocol == CommunicationProtocol.None)
            {
                new ServiceRouteWatch(mapper.Resolve <CPlatformContainer>(), () =>
                {
                    var addess = new IpAddressModel
                    {
                        Ip            = mappingIp,
                        Port          = mappingPort,
                        ProcessorTime = Math.Round(Convert.ToDecimal(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds), 2, MidpointRounding.AwayFromZero),
                    };
                    RpcContext.GetContext().SetAttachment("Host", addess);

                    var addressDescriptors = serviceEntryManager.GetEntries().Select(i =>
                    {
                        i.Descriptor.Token = serviceToken;
                        return(new ServiceRoute
                        {
                            Address = new[] { addess },
                            ServiceDescriptor = i.Descriptor
                        });
                    }).ToList();
                    mapper.Resolve <IServiceRouteManager>().SetRoutesAsync(addressDescriptors).Wait();
                });
            }
        }
        public override async Task Register(IEnumerable <ServiceRoute> routes)
        {
            var host = new IpAddressModel(_address.Host, _address.Port) as AddressModel;

            var serviceRoutes = await GetRoutes(routes.Select(p => $"{ _config.RoutePath}{p.ServiceDescriptor.Id}"));

            foreach (var route in routes)
            {
                var serviceRoute = serviceRoutes.Where(p => p.ServiceDescriptor.Id == route.ServiceDescriptor.Id).FirstOrDefault();

                if (serviceRoute != null)
                {
                    var addresses = serviceRoute.Address.Concat(
                        route.Address.Except(serviceRoute.Address)).ToList();

                    foreach (var address in route.Address)
                    {
                        addresses.Remove(addresses.Where(p => p.ToString() == address.ToString()).FirstOrDefault());
                        addresses.Add(address);
                    }
                    route.Address = addresses;
                }
            }
            await RemoveExceptRoutesAsync(routes, host);

            await base.Register(routes);
        }
        public static void RegisterRoutes(IContainer mapper, string mappingIp, int mappingPort, string serviceToken, decimal processorTime)
        {
            var serviceEntryManager = mapper.Resolve <IServiceEntryManager>();
            var ports  = AppConfig.ServerOptions.Ports;
            var addess = new IpAddressModel
            {
                Ip            = mappingIp,
                WanIp         = AppConfig.ServerOptions.WanIp,
                HttpPort      = ports.HttpPort == 0? default(int?) : ports.HttpPort,
                MqttPort      = ports.MQTTPort == 0 ? default(int?) : ports.MQTTPort,
                WsPort        = ports.WSPort == 0 ? default(int?): ports.WSPort,
                Port          = mappingPort,
                ProcessorTime = processorTime,
            };

            RpcContext.GetContext().SetAttachment("Host", addess);
            var addressDescriptors = serviceEntryManager.GetEntries().Select(i =>
            {
                i.Descriptor.Token = serviceToken;
                return(new ServiceRoute
                {
                    Address = new[] { addess },
                    ServiceDescriptor = i.Descriptor
                });
            }).ToList();

            mapper.Resolve <IServiceRouteManager>().SetRoutesAsync(addressDescriptors).Wait();
        }
Exemplo n.º 4
0
        public void IpAddressModelEqualsTest()
        {
            AddressModel model1 = new IpAddressModel("127.0.0.1", 1234);
            AddressModel model2 = new IpAddressModel("127.0.0.1", 1234);
            AddressModel model3 = new IpAddressModel("127.0.0.1", 12345);
            AddressModel model4 = new IpAddressModel("127.0.0.2", 1234);
            AddressModel model5 = new IpAddressModel("127.0.0.2", 12345);

            Assert.IsTrue(model1.Equals(model2));
            Assert.IsTrue(model1 == model2);

            Assert.IsFalse(!model1.Equals(model2));
            Assert.IsFalse(model1 != model2);

            Assert.IsFalse(model1.Equals(model3));
            Assert.IsFalse(model1 == model3);
            Assert.IsFalse(model1.Equals(model4));
            Assert.IsFalse(model1 == model4);
            Assert.IsFalse(model1.Equals(model5));
            Assert.IsFalse(model1 == model5);

            Assert.IsTrue(!model1.Equals(model3));
            Assert.IsTrue(model1 != model3);
            Assert.IsTrue(!model1.Equals(model4));
            Assert.IsTrue(model1 != model4);
            Assert.IsTrue(!model1.Equals(model5));
            Assert.IsTrue(model1 != model5);

            var array1 = new[] { new IpAddressModel("127.0.0.1", 1234), new IpAddressModel("127.0.0.2", 1234) };
            var array2 = new[] { new IpAddressModel("127.0.0.1", 1234), new IpAddressModel("127.0.0.2", 1234) };

            Assert.IsFalse(array1.Except(array2).Any());
            Assert.AreEqual(2, array1.Intersect(array2).Count());
        }
Exemplo n.º 5
0
 protected (ManualResetEvent, ZooKeeper) CreateZooKeeper(IpAddressModel ipAddress)
 {
     if (!_zookeeperClients.TryGetValue(ipAddress, out (ManualResetEvent, ZooKeeper)result))
     {
         var connectionWait = new ManualResetEvent(false);
         result = new ValueTuple <ManualResetEvent, ZooKeeper>(connectionWait, new ZooKeeper($"{ipAddress.Ip}:{ipAddress.Port}", (int)_config.SessionTimeout.TotalMilliseconds
                                                                                             , new ReconnectionWatcher(
                                                                                                 () =>
         {
             connectionWait.Set();
         },
                                                                                                 () =>
         {
             connectionWait.Close();
         },
                                                                                                 async() =>
         {
             connectionWait.Reset();
             if (_zookeeperClients.TryRemove(ipAddress, out (ManualResetEvent, ZooKeeper)value))
             {
                 await value.Item2.closeAsync();
                 value.Item1.Close();
             }
             CreateZooKeeper(ipAddress);
         })));
 private async Task MarkServiceHealth(IChannelHandlerContext context)
 {
     var iPEndPoint     = context.Channel.RemoteAddress as IPEndPoint;
     var ipAddressModel = new IpAddressModel(iPEndPoint.Address.MapToIPv4().ToString(),
                                             iPEndPoint.Port);
     await _healthCheckService.MarkHealth(ipAddressModel);
 }
 private async Task MarkServiceProviderHealth(IChannelHandlerContext context)
 {
     var providerServerEndpoint = context.Channel.RemoteAddress as IPEndPoint;
     var providerServerAddress  = new IpAddressModel(providerServerEndpoint.Address.MapToIPv4().ToString(),
                                                     providerServerEndpoint.Port);
     await _healthCheckService.MarkHealth(providerServerAddress);
 }
Exemplo n.º 8
0
        public override async Task DeregisterAsync()
        {
            var host = new IpAddressModel(_address.Host, _address.Port) as AddressModel;



            if (_consul.KV.Keys(_config.RoutePath).Result.Response?.Count() > 0)
            {
                var keys = await _consul.KV.Keys(_config.RoutePath);

                var routes = await GetRoutes(keys.Response);
                await DeRegisterRoutesAsync(routes, host);
            }


            //var queryResult = await _consul.KV.List(_config.RoutePath);
            //var response = queryResult.Response;
            //if (response != null)
            //{
            //    foreach (var result in response)
            //    {
            //        await _consul.KV.DeleteCAS(result);
            //    }
            //}
        }
            private async Task MarkServiceUnHealth(IChannelHandlerContext context)
            {
                var providerServerEndpoint = context.Channel.RemoteAddress as IPEndPoint;
                var providerServerAddress  = new IpAddressModel(providerServerEndpoint.Address.MapToIPv4().ToString(),
                                                                providerServerEndpoint.Port);

                _factory.RemoveClient(providerServerEndpoint);
                _factory.RemoveClient(context.Channel.GetAttribute(origEndPointKey).Get());
                await _healthCheckService.MarkFailure(providerServerAddress);
            }
 public Task MarkHealth(IpAddressModel address)
 {
     return(Task.Run(() =>
     {
         var ipAddress = address as IpAddressModel;
         var entry = _dictionaries.GetOrAdd(new Tuple <string, int>(ipAddress.Ip, ipAddress.Port), k => new MonitorEntry(address, true));
         entry.Health = true;
         entry.UnhealthyTimes = 0;
         OnChanged(new HealthCheckEventArgs(address, true));
     }));
 }
Exemplo n.º 11
0
        ///// <summary>
        ///// 最大链接数
        ///// </summary>
        //public int MaxConnections { get; set; } = 30;

        public GrpcChannel GetOrAddChannelPool(IpAddressModel address, GrpcChannelOptions options)
        {
            var key = $"{address.Ip}:{address.Port}";

            var model = _dictionary.GetOrAdd(key, new ChannelModel
            {
                IsUse    = true,
                Channel  = GrpcChannel.ForAddress($"http://{address.Ip}:{address.Port}", options),
                LastTime = DateTime.Now
            });

            return(model.Channel);
        }
Exemplo n.º 12
0
        public override async Task Register(IEnumerable <ServiceRoute> routes)
        {
            var host = new IpAddressModel(_address.Host, _address.Port) as AddressModel;

            var serviceRoutes = await GetRoutes(routes.Select(p => $"{ _config.RoutePath}{p.ServiceDescriptor.Id}"));

            var arrRoutes = routes.ToArray();
            var cnt       = routes.Count();

            for (var i = 0; i < cnt; i++)
            {
                var route        = arrRoutes[i];
                var serviceRoute = serviceRoutes.Where(p => p.ServiceDescriptor.Id == route.ServiceDescriptor.Id).FirstOrDefault();

                if (serviceRoute != null)
                {
                    var addresses = serviceRoute.Address.Concat(
                        route.Address.Except(serviceRoute.Address)).ToList();

                    foreach (var address in route.Address)
                    {
                        addresses.Remove(addresses.Where(p => p.ToString() == address.ToString()).FirstOrDefault());
                        addresses.Add(address);
                    }
                    route.Address = addresses;
                }
                arrRoutes[i] = route;
            }
            #region MyRegion
            //foreach (var route in routes)
            //{
            //    var serviceRoute = serviceRoutes.Where(p => p.ServiceDescriptor.Id == route.ServiceDescriptor.Id).FirstOrDefault();

            //    if (serviceRoute != null)
            //    {
            //        var addresses = serviceRoute.Address.Concat(
            //          route.Address.Except(serviceRoute.Address)).ToList();

            //        foreach (var address in route.Address)
            //        {
            //            addresses.Remove(addresses.Where(p => p.ToString() == address.ToString()).FirstOrDefault());
            //            addresses.Add(address);
            //        }
            //        route.Address = addresses;
            //    }
            //}
            #endregion
            await RemoveExceptRoutesAsync(arrRoutes, host);

            await base.Register(arrRoutes);
        }
Exemplo n.º 13
0
        public async Task <string> Locate(string routePath, string key)
        {
            var route = await _serviceRouteProvider.SearchRoute(routePath);

            AddressModel result = new IpAddressModel();

            if (route != null)
            {
                result = await _addressSelector.SelectAsync(new AddressSelectContext()
                {
                    Address    = route.Address,
                    Descriptor = route.ServiceDescriptor,
                    HashCode   = _hashAlgorithm.Hash(key)
                });
            }
            return(result.ToString());
        }
Exemplo n.º 14
0
        public ActionResult GetNearSchools()
        {
            List <string> nearSchools = null;
            //根据用户ip地址获取用户所在地,然后根据用户所在地查询附近的学校
            string ip     = Util.CommonMethod.GetHostAddress();
            var    strUrl = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" + "59.39.128.0";

            WebClient      client = new WebClient();
            string         reply  = client.DownloadString(strUrl);
            IpAddressModel i      = Util.JsonHelper.Jso_DeJSON <IpAddressModel>(reply);
            List <City>    city   = _cityService.getCityByCityName(i.city);

            if (city.Count == 1)
            {
                nearSchools = _schoolService.getSchoolNamesByCityId(city[0].cityId);
            }
            return(Json(nearSchools, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 15
0
        public IEnumerable <AddressModel> ConvertAddressModel(string connection)
        {
            var addressModels = new List <AddressModel>();
            var addresses     = connection.Split(",");

            foreach (var addr in addresses)
            {
                var addressSegment = addr.Split(":");
                if (addressSegment.Length > 1)
                {
                    int port;
                    int.TryParse(addressSegment[1], out port);
                    var ipAddesssModel = new IpAddressModel(addressSegment[0], port);
                    addressModels.Add(ipAddesssModel);
                }
            }

            return(null);
        }
Exemplo n.º 16
0
        public async Task <IHttpActionResult> Add(IpAddressModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var response = await _ipAddressManagerService.AddIpAddress(Mapper.Map <IpAddress>(model));

                    return(Ok(response));
                }

                return(BadRequest(ModelState));
            }
            catch (Exception ex)
            {
                _log.FatalException("Failed add Ip Address.", ex);
                return(InternalServerError());
            }
        }
Exemplo n.º 17
0
        public async Task <IpAddressModel> Locate(string routePath, string key)
        {
            var route = await _serviceRouteProvider.SearchRoute(routePath);

            AddressModel result = new IpAddressModel();

            if (route != null)
            {
                result = await _addressSelector.SelectAsync(new AddressSelectContext()
                {
                    Address    = route.Address,
                    Descriptor = route.ServiceDescriptor,
                    Item       = key,
                });
            }
            var ipAddress = result as IpAddressModel;

            return(ipAddress);
        }
Exemplo n.º 18
0
        public async Task <IpAddressModel> Locate(string key, string routePath, HttpMethod httpMethod)
        {
            var route = await _serviceRouteProvider.SearchRoute(routePath, httpMethod.ToString());

            AddressModel result = new IpAddressModel();

            if (route != null)
            {
                result = await _addressSelector.SelectAsync(new AddressSelectContext()
                {
                    Address    = route.Address,
                    Descriptor = route.ServiceDescriptor,
                    Item       = key,
                });

                _serviceHeartbeatManager.AddWhitelist(route.ServiceDescriptor.Id);
            }
            var ipAddress = result as IpAddressModel;

            return(ipAddress);
        }
        public async override void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            if (evt is IdleStateEvent @event)
            {
                if (@event.State == IdleState.ReaderIdle)
                {
                    var iPEndPoint     = context.Channel.RemoteAddress as IPEndPoint;
                    var ipAddressModel = new IpAddressModel(iPEndPoint.Address.MapToIPv4().ToString(),
                                                            iPEndPoint.Port);
                    await _healthCheckService.MarkHealth(ipAddressModel);

                    if (context.Channel.Active)
                    {
                        await context.Channel.CloseAsync();
                    }
                }
            }
            else
            {
                base.UserEventTriggered(context, evt);
            }
        }
Exemplo n.º 20
0
 /// <summary>
 /// 初始化consul配置信息。
 /// </summary>
 /// <param name="connectionString">连接字符串。</param>
 /// <param name="sessionTimeout">会话超时时间。</param>
 /// <param name="commandPath">服务命令配置命令。</param>
 /// <param name="subscriberPath">订阅者配置命令。</param>
 /// <param name="routePath">路由路径配置路径</param>
 /// <param name="cachePath">缓存中心配置路径</param>
 /// <param name="mqttRoutePath">Mqtt路由路径配置路径</param>
 public ConfigInfo(string connectionString, TimeSpan sessionTimeout, int lockDelay,
                   string routePath      = "services/serviceRoutes/",
                   string subscriberPath = "services/serviceSubscribers/",
                   string commandPath    = "services/serviceCommands/",
                   string cachePath      = "services/serviceCaches/",
                   string mqttRoutePath  = "services/mqttServiceRoutes/",
                   bool reloadOnChange   = false, bool enableChildrenMonitor = false)
 {
     CachePath             = cachePath;
     ReloadOnChange        = reloadOnChange;
     SessionTimeout        = sessionTimeout;
     RoutePath             = routePath;
     LockDelay             = lockDelay;
     SubscriberPath        = subscriberPath;
     CommandPath           = commandPath;
     MqttRoutePath         = mqttRoutePath;
     EnableChildrenMonitor = enableChildrenMonitor;
     if (!string.IsNullOrEmpty(connectionString))
     {
         var addresses = connectionString.Split(",");
         if (addresses.Length > 1)
         {
             Addresses = addresses.Select(p => ConvertAddressModel(p));
         }
         else
         {
             var address = ConvertAddressModel(connectionString);
             if (address != null)
             {
                 var ipAddress = address as IpAddressModel;
                 Host = ipAddress.Ip;
                 Port = ipAddress.Port;
             }
             Addresses = new IpAddressModel[] {
                 new IpAddressModel(Host, Port)
             };
         }
     }
 }
        public static void RegisterRoutes(IContainer mapper, string mappingIp, int mappingPort, string serviceToken)
        {
            var serviceEntryManager = mapper.Resolve <IServiceEntryManager>();
            var addess = new IpAddressModel
            {
                Ip            = mappingIp,
                Port          = mappingPort,
                ProcessorTime = Math.Round(Convert.ToDecimal(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds), 2, MidpointRounding.AwayFromZero),
            };

            RpcContext.GetContext().SetAttachment("Host", addess);
            var addressDescriptors = serviceEntryManager.GetEntries().Select(i =>
            {
                i.Descriptor.Token = serviceToken;
                return(new ServiceRoute
                {
                    Address = new[] { addess },
                    ServiceDescriptor = i.Descriptor
                });
            }).ToList();

            mapper.Resolve <IServiceRouteManager>().SetRoutesAsync(addressDescriptors).Wait();
        }
Exemplo n.º 22
0
 /// <summary>
 /// 初始化Zookeeper配置信息。
 /// </summary>
 /// <param name="connectionString">连接字符串。</param>
 /// <param name="routePath">路由配置路径。</param>
 /// <param name="commandPath">服务命令配置路径</param>
 /// <param name="subscriberPath">订阅者配置路径</param>
 /// <param name="sessionTimeout">会话超时时间。</param>
 /// <param name="cachePath">缓存中心配置路径</param>
 /// <param name="mqttRoutePath">mqtt路由配置路径</param>
 /// <param name="chRoot">根节点。</param>
 public ConfigInfo(string connectionString, TimeSpan sessionTimeout, string routePath = "/services/serviceRoutes",
                   string subscriberPath = "/services/serviceSubscribers",
                   string commandPath    = "/services/serviceCommands",
                   string cachePath      = "/services/serviceCaches",
                   string mqttRoutePath  = "/services/mqttServiceRoutes",
                   string chRoot         = null,
                   bool reloadOnChange   = false, bool enableChildrenMonitor = false)
 {
     CachePath             = cachePath;
     ReloadOnChange        = reloadOnChange;
     ChRoot                = chRoot;
     CommandPath           = commandPath;
     SubscriberPath        = subscriberPath;
     ConnectionString      = connectionString;
     RoutePath             = routePath;
     SessionTimeout        = sessionTimeout;
     MqttRoutePath         = mqttRoutePath;
     EnableChildrenMonitor = enableChildrenMonitor;
     if (!string.IsNullOrEmpty(connectionString))
     {
         var addresses = connectionString.Split(",");
         if (addresses.Length > 1)
         {
             Addresses = addresses.Select(p => ConvertAddressModel(p));
         }
         else
         {
             var address = ConvertAddressModel(connectionString);
             if (address != null)
             {
                 var ipAddress = address as IpAddressModel;
                 Addresses = new IpAddressModel[] { ipAddress };
             }
         }
     }
 }
        public async Task <IActionResult> EditServiceToken([FromServices] IServiceDiscoveryProvider serviceDiscoveryProvider, IpAddressModel model)
        {
            await serviceDiscoveryProvider.EditServiceToken(model);

            return(Json(ServiceResult.Create(true)));
        }
        public async Task <IActionResult> EditServiceToken(IpAddressModel model)
        {
            await ServiceLocator.GetService <IServiceDiscoveryProvider>().EditServiceToken(model);

            return(Json(ServiceResult.Create(true)));
        }