Ejemplo n.º 1
0
        // Token: 0x06001238 RID: 4664 RVA: 0x0001E47C File Offset: 0x0001C67C
        public void Connect(string endpointAddress)
        {
            if (this.Monitor.IsEnabled)
            {
                this.Monitor.AddEvent("Connect " + endpointAddress);
            }
            string ipAddress = new ConnectionAddress(endpointAddress).IpAddress;

            if (CrossdomainPolicy.HasValidPolicy(ipAddress))
            {
                this.ConnectToServer(endpointAddress);
            }
            else
            {
                UnityRuntime.Instance.StartCoroutine(CrossdomainPolicy.CheckPolicyRoutine(ipAddress, delegate
                {
                    if (CrossdomainPolicy.HasValidPolicy(ipAddress))
                    {
                        this.ConnectToServer(endpointAddress);
                    }
                    else
                    {
                        this.OnConnectionFail(endpointAddress);
                    }
                }));
            }
        }
Ejemplo n.º 2
0
        /// <summary>获取Storage连接
        /// </summary>
        public IConnection GetStorageConnection(ConnectionAddress connectionAddress)
        {
            if (!_storageConnectionPools.TryGetValue(connectionAddress, out IConnectionPool connectionPool))
            {
                lock (_storageSyncObject)
                {
                    if (!_storageConnectionPools.TryGetValue(connectionAddress, out connectionPool))
                    {
                        var connectionPoolOption = new ConnectionPoolOption()
                        {
                            ConnectionAddress          = connectionAddress,
                            ConnectionLifeTime         = _option.ConnectionLifeTime,
                            ConnectionConcurrentThread = _option.ConnectionConcurrentThread,
                            MaxConnection = _option.StorageMaxConnection,
                            ScanTimeoutConnectionInterval = _option.ScanTimeoutConnectionInterval
                        };

                        connectionPool = _connectionPoolFactory.CreateConnectionPool(connectionPoolOption);
                        if (!_storageConnectionPools.TryAdd(connectionAddress, connectionPool))
                        {
                            _logger.LogWarning("Fail to add connection pool to storage connection pools! ConnectionAddress:{0}", connectionAddress);
                        }
                    }
                }
            }

            if (connectionPool == null)
            {
                throw new ArgumentException($"Can't find any connection pools for {connectionAddress}");
            }
            return(connectionPool.GetConnection());
        }
Ejemplo n.º 3
0
        private async Task DownloadInternal(string fid, Action <Stream> writer)
        {
            ConnectionAddress connectionAddress;

            if (_option.RestOption.EnableReadJwt)
            {
                var lookupRequest  = new LookupRequest(fid, true);
                var lookupResponse = await _executer.ExecuteAsync(lookupRequest);

                var url = lookupResponse.Locations.FirstOrDefault().Url;
                connectionAddress = new ConnectionAddress(url);
            }
            else
            {
                var connection = _connectionManager.GetVolumeConnectionByVolumeIdOrFid(fid);
                connectionAddress = connection.ConnectionAddress;
            }
            await Task.Factory.StartNew(() =>
            {
                var client           = GetDownloadClient(connectionAddress);
                IRestRequest request = new RestRequest("/{fid}");
                request.AddUrlSegment("fid", fid);
                request.ResponseWriter = writer;
                var response           = client.DownloadData(request);
            });
        }
Ejemplo n.º 4
0
        /// <summary>根据链接地址获取Volume连接
        /// </summary>
        private Connection GetVolumeConnectionInternal(ConnectionAddress connectionAddress)
        {
            var volumeConnection = _volumeConnections.GetOrAdd(connectionAddress, addr =>
            {
                return(_connectionFactory.CreateConnection(addr, ConnectionType.Volume));
            });

            return(volumeConnection);
        }
Ejemplo n.º 5
0
 // Token: 0x060010C9 RID: 4297 RVA: 0x00017288 File Offset: 0x00015488
 public static void Serialize(Stream stream, ConnectionAddress instance)
 {
     using (MemoryStream memoryStream = new MemoryStream())
     {
         Int32Proxy.Serialize(memoryStream, instance.Ipv4);
         UInt16Proxy.Serialize(memoryStream, instance.Port);
         memoryStream.WriteTo(stream);
     }
 }
Ejemplo n.º 6
0
 /// <summary>Ctor
 /// </summary>
 public Connection(ILoggerFactory loggerFactory, SeaweedfsOption option, ConnectionAddress connectionAddress, ConnectionType connectionType)
 {
     _logger           = loggerFactory.CreateLogger(SeaweedfsConsts.LoggerName);
     _option           = option;
     ConnectionAddress = connectionAddress;
     _connectionType   = connectionType;
     BaseUrl           = UrlUtil.ToUrl(option.RestOption.Scheme, connectionAddress.IPAddress, connectionAddress.Port);
     Client            = new RestClient(BaseUrl);
 }
Ejemplo n.º 7
0
        /// <summary>同步集群中MasterLeader
        /// </summary>
        private async void GrpcSyncMasterLeader()
        {
            if (_masterLeaderChannel == null)
            {
                _logger.LogError("同步MasterLeader出错,当前MasterLeaderChannel为空.");
                return;
            }

            try
            {
                var client  = GetMasterClient();
                var request = new MasterPb.KeepConnectedRequest()
                {
                    Name = Guid.NewGuid().ToString("N")
                };

                using (var call = client.KeepConnected())
                {
                    var responseReaderTask = Task.Run(() =>
                    {
                        while (call.ResponseStream.MoveNext(CancellationToken.None).WaitResult(5000))
                        {
                            var volumeLocation = call.ResponseStream.Current;

                            //接收到VolumeLocation信息后处理...
                            if (!volumeLocation.Leader.IsNullOrWhiteSpace() && !volumeLocation.Leader.Equals(_masterLeaderChannel.Target, StringComparison.OrdinalIgnoreCase))
                            {
                                //不相等,创建新的连接
                                lock (SyncObject)
                                {
                                    var connectionAddress = new ConnectionAddress(volumeLocation.Leader);
                                    _masterLeaderChannel  = CreateChannel(connectionAddress);
                                }
                            }
                        }
                    });
                    await call.RequestStream.WriteAsync(request);

                    await call.RequestStream.CompleteAsync();

                    await responseReaderTask;
                }
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    _logger.LogError(e.InnerException, "同步MasterLeader出现线程异常,{0}", ex.Message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "同步MasterLeader出错,{0}", ex.Message);
            }
        }
Ejemplo n.º 8
0
 /// <summary>获取下载的客户端
 /// </summary>
 private IRestClient GetDownloadClient(ConnectionAddress connectionAddress)
 {
     if (!_clientDict.TryGetValue(connectionAddress, out IRestClient client))
     {
         lock (SyncObject)
         {
             client = new RestClient(UrlUtil.ToUrl(_option.RestOption.Scheme, connectionAddress.IPAddress, connectionAddress.Port));
             _clientDict.TryAdd(connectionAddress, client);
         }
     }
     return(client);
 }
Ejemplo n.º 9
0
        /// <summary>重写Equals方法
        /// </summary>
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return(false);
            }
            if (!(obj is ConnectionAddress))
            {
                return(false);
            }
            ConnectionAddress connectionAddress = (ConnectionAddress)obj;

            return(IPAddress.Equals(connectionAddress.IPAddress) && Port.Equals(connectionAddress.Port));
        }
Ejemplo n.º 10
0
        /// <summary>请求执行器
        /// </summary>
        /// <typeparam name="T">请求的类型<see cref="FastDFSCore.Protocols.FastDFSReq"/></typeparam>
        /// <param name="request">请求</param>
        /// <param name="connectionAddress">返回</param>
        /// <returns></returns>
        public async Task <T> Execute <T>(FastDFSReq <T> request, ConnectionAddress connectionAddress = null) where T : FastDFSResp, new()
        {
            var connection = connectionAddress == null?_connectionManager.GetTrackerConnection() : _connectionManager.GetStorageConnection(connectionAddress);

            if (connection == null)
            {
                throw new NullReferenceException($"Can't find connection,ipaddr:{connectionAddress} ");
            }
            connection.Open();
            var response = await connection.SendRequestAsync <T>(request);

            connection.Close();
            return(response as T);
        }
Ejemplo n.º 11
0
        public IConnection CreateConnection(ConnectionAddress connectionAddress)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var injectConnectionAddress = scope.ServiceProvider.GetService <ConnectionAddress>();

                injectConnectionAddress.IPAddress = connectionAddress.IPAddress;
                injectConnectionAddress.Port      = connectionAddress.Port;

                //连接
                var connection = scope.ServiceProvider.GetService <IConnection>();

                return(connection);
            }
        }
Ejemplo n.º 12
0
        public BaseConnection(ILogger <BaseConnection> logger, IServiceProvider serviceProvider, ClusterConfiguration configuration, ConnectionAddress connectionAddress)
        {
            CreationTime = DateTime.Now;
            LastUseTime  = DateTime.Now;
            IsUsing      = false;
            IsConnected  = false;


            Logger          = logger;
            Configuration   = configuration;
            ServiceProvider = serviceProvider;

            ConnectionAddress = connectionAddress;

            Id = Guid.NewGuid().ToString();
        }
Ejemplo n.º 13
0
        public BaseConnection(ILogger <BaseConnection> logger, IServiceProvider serviceProvider, IOptions <FastDFSOption> option, ConnectionAddress connectionAddress)
        {
            _creationTime = DateTime.Now;
            _lastUseTime  = DateTime.Now;
            _isUsing      = false;
            IsRunning     = false;


            Logger          = logger;
            Option          = option.Value;
            ServiceProvider = serviceProvider;

            ConnectionAddress = connectionAddress;

            Id = Guid.NewGuid().ToString();
        }
Ejemplo n.º 14
0
 /// <summary>同步集群中MasterLeader
 /// </summary>
 private void SyncMasterLeader()
 {
     if (_masterLeaderConnection == null)
     {
         _logger.LogError("同步MasterLeader出错,当前MasterConnection为空.");
         return;
     }
     try
     {
         //查询集群中的状态
         var request = new ClusterStatusRequest();
         //执行结果
         var task = _seaweedfsExecuter.ExecuteAsync(request);
         task.Wait();
         //集群状态
         var clusterStatus = task.Result;
         if (!clusterStatus.IsSuccessful)
         {
             //如果不成功,Master可能废了,需要构建新的
             _masterLeaderConnection = CreateMasterConnection(_masterLeaderConnection.ConnectionAddress);
             SyncMasterLeader();
             return;
         }
         //判断集群中的Master服务器的Leader是否发生了改变
         if (!clusterStatus.IsLeader || clusterStatus.Leader != _masterLeaderConnection.ConnectionAddress.ToString())
         {
             //更新当前Master连接
             lock (SyncObject)
             {
                 var connectionAddress = new ConnectionAddress(clusterStatus.Leader);
                 _masterLeaderConnection = _connectionFactory.CreateConnection(connectionAddress, ConnectionType.Master);
             }
         }
     }
     catch (AggregateException ex)
     {
         foreach (var e in ex.InnerExceptions)
         {
             _logger.LogError(e.InnerException, "同步MasterLeader出现线程异常,{0}", ex.Message);
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "同步MasterLeader出错,{0}", ex.Message);
     }
 }
Ejemplo n.º 15
0
        public void Initialize()
        {
            if (_isInitialized)
            {
                _logger.LogDebug("ConnectionManager is already initialized!");
                return;
            }

            foreach (var tracker in _option.Trackers)
            {
                var connectionAddress = new ConnectionAddress(tracker.IPAddress, tracker.Port);
                _trackerConnectionAddresses.Add(connectionAddress);
            }

            _logger.LogDebug("'ConnectionManager' initialize for '{0}' ConnectionAddress,[{1}]", _trackerConnectionAddresses.Count, string.Join(",", _trackerConnectionAddresses));

            _isInitialized = true;
        }
Ejemplo n.º 16
0
    // Token: 0x060017D7 RID: 6103 RVA: 0x00081444 File Offset: 0x0007F644
    public PhotonServer(PhotonView view)
    {
        this._address.Ipv4 = ConnectionAddress.ToInteger(view.IP);
        this._address.Port = (ushort)view.Port;
        this._view         = view;
        int num  = (!string.IsNullOrEmpty(this._view.Name)) ? this._view.Name.IndexOf('[') : 0;
        int num2 = (!string.IsNullOrEmpty(this._view.Name)) ? this._view.Name.IndexOf(']') : 0;

        if (num >= 0 && num2 > 1 && num2 > num)
        {
            this.Region = this._view.Name.Substring(num + 1, num2 - num - 1);
        }
        else
        {
            this.Region = "Default";
        }
        this.Flag = new DynamicTexture(ApplicationDataManager.ImagePath + "flags/" + this.Region + ".png", this.Region != "Default");
    }
        public void CreateConnection_Test()
        {
            var mockConnection = new Mock <IConnection>();

            mockConnection.Setup(x => x.Id)
            .Returns("123456");

            var connectionAddress        = new ConnectionAddress("192.168.0.6", 22122);
            var mockScopeServiceProvider = new Mock <IServiceProvider>();

            mockScopeServiceProvider.Setup(x => x.GetService(typeof(ConnectionAddress)))
            .Returns(connectionAddress);
            mockScopeServiceProvider.Setup(x => x.GetService(typeof(IConnection)))
            .Returns(mockConnection.Object);

            var mockServiceScope = new Mock <IServiceScope>();

            mockServiceScope.Setup(x => x.ServiceProvider)
            .Returns(mockScopeServiceProvider.Object);

            var mockScopeFactory = new Mock <IServiceScopeFactory>();

            mockScopeFactory.Setup(x => x.CreateScope())
            .Returns(mockServiceScope.Object);

            var mockServiceProvider = new Mock <IServiceProvider>();

            mockServiceProvider.Setup(x => x.GetService(typeof(IServiceScopeFactory)))
            .Returns(mockScopeFactory.Object);


            IConnectionBuilder connectionBuilder = new DefaultConnectionBuilder(mockServiceProvider.Object);
            var connection = connectionBuilder.CreateConnection(connectionAddress);

            Assert.Equal("123456", connection.Id);

            mockScopeServiceProvider.Verify(x => x.GetService(typeof(IConnection)), Times.Once);
            mockScopeServiceProvider.Verify(x => x.GetService(typeof(ConnectionAddress)), Times.Once);
        }
Ejemplo n.º 18
0
        /// <summary>根据VolumeId(可以是Fid)获取Volume连接
        /// </summary>
        public Connection GetVolumeConnectionByVolumeIdOrFid(string volumeIdOrFid)
        {
            //如果是Fid,就转换成VolumeId
            if (StringUtil.IsFid(volumeIdOrFid))
            {
                volumeIdOrFid = StringUtil.GetVolumeId(volumeIdOrFid);
            }

            if (_volumeIdAddressMappers.TryGetValue(volumeIdOrFid, out ConnectionAddress connectionAddress))
            {
                return(GetVolumeConnectionInternal(connectionAddress));
            }
            else
            {
                var request = new LookupVolumeRequest(volumeIdOrFid);
                var task    = _seaweedfsExecuter.ExecuteAsync(request);
                task.Wait();
                //查询Volume返回
                var lookupVolumeResponse = task.Result;
                if (lookupVolumeResponse.IsSuccessful)
                {
                    //成功
                    lock (SyncObject)
                    {
                        //连接地址
                        connectionAddress = new ConnectionAddress(lookupVolumeResponse.Locations.FirstOrDefault().Url);
                        //添加映射
                        _volumeIdAddressMappers.TryAdd(volumeIdOrFid, connectionAddress);
                        return(GetVolumeConnectionInternal(connectionAddress));
                    }
                }
                else
                {
                    _logger.LogInformation("根据VolumeId获取Volume信息时出错,VolumeId:{0},HttpStatus:{1}", volumeIdOrFid, lookupVolumeResponse.StatusCode);
                    throw new Exception($"获取Volume信息出错,{lookupVolumeResponse.ErrorMessage}");
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>创建默认的Master连接
        /// </summary>
        private Connection CreateMasterConnection(ConnectionAddress exceptMaster = null)
        {
            var masterServers = _option.RestOption.Masters;

            if (exceptMaster != null)
            {
                masterServers = masterServers.Where(x => x.IPAddress != exceptMaster.IPAddress && x.Port != exceptMaster.Port).ToList();
            }
            var master = masterServers.FirstOrDefault();

            if (master == null)
            {
                throw new ArgumentException("配置文件中不包含任何Master节点的配置.");
            }

            var connectionAddress = new ConnectionAddress()
            {
                IPAddress = master.IPAddress,
                Port      = master.Port
            };

            return(_connectionFactory.CreateConnection(connectionAddress, ConnectionType.Master));
        }
Ejemplo n.º 20
0
        /// <summary>创建默认的Master连接
        /// </summary>
        private GoogleGrpc.Channel CreateMasterChannel(ConnectionAddress exceptMaster = null)
        {
            var masterServers = _option.GrpcOption.GrpcMasters;

            if (exceptMaster != null)
            {
                masterServers = masterServers.Where(x => x.IPAddress != exceptMaster.IPAddress && x.Port != exceptMaster.Port).ToList();
            }
            var master = masterServers.FirstOrDefault();

            if (master == null)
            {
                throw new ArgumentException("配置文件中不包含任何Master节点的配置.");
            }

            var connectionAddress = new ConnectionAddress()
            {
                IPAddress = master.IPAddress,
                Port      = master.Port
            };

            return(CreateChannel(connectionAddress));
        }
Ejemplo n.º 21
0
 public DotNettyConnection(ILogger <BaseConnection> logger, IServiceProvider serviceProvider, IOptions <FastDFSOption> option, ConnectionAddress connectionAddress) : base(logger, serviceProvider, option, connectionAddress)
 {
     _semaphoreSlim = new SemaphoreSlim(1);
 }
Ejemplo n.º 22
0
 public SuperSocketConnection(ILogger <BaseConnection> logger, IServiceProvider serviceProvider, IOptions <FastDFSOption> option, ConnectionAddress connectionAddress) : base(logger, serviceProvider, option, connectionAddress)
 {
 }
Ejemplo n.º 23
0
 // Token: 0x06000E4B RID: 3659 RVA: 0x00061C24 File Offset: 0x0005FE24
 public static bool IsLocalConnection(ConnectionAddress address)
 {
     return(address.IpAddress.StartsWith("10.") || address.IpAddress.StartsWith("172.16.") || address.IpAddress.StartsWith("192.168.") || address.IpAddress.StartsWith("127."));
 }
 public SuperSocketConnection(ILogger <BaseConnection> logger, IServiceProvider serviceProvider, ClusterConfiguration configuration, ConnectionAddress connectionAddress) : base(logger, serviceProvider, configuration, connectionAddress)
 {
 }
Ejemplo n.º 25
0
 public DotNettyConnection(ILogger <BaseConnection> logger, IServiceProvider serviceProvider, ClusterConfiguration configuration, IOptions <DotNettyOption> dotNettyOption, ConnectionAddress connectionAddress) : base(logger, serviceProvider, configuration, connectionAddress)
 {
     _dotNettyOption = dotNettyOption.Value;
 }
Ejemplo n.º 26
0
        /// <summary>请求执行器
        /// </summary>
        /// <typeparam name="T">请求的类型<see cref="FastDFSReq"/></typeparam>
        /// <param name="request">请求</param>
        /// <param name="clusterName">集群名</param>
        /// <param name="connectionAddress">返回</param>
        /// <returns></returns>
        public async ValueTask <T> Execute <T>(FastDFSReq <T> request, string clusterName, ConnectionAddress connectionAddress = null) where T : FastDFSResp, new()
        {
            var cluster = _clusterFactory.Get(clusterName);

            var connection = connectionAddress == null?cluster.GetTrackerConnection() : cluster.GetStorageConnection(connectionAddress);

            if (connection == null)
            {
                throw new NullReferenceException($"Can't find connection,ipaddr:{connectionAddress} ");
            }
            await connection.OpenAsync();

            var response = await connection.SendRequestAsync <T>(request);

            await connection.CloseAsync();

            return(response as T);
        }
Ejemplo n.º 27
0
        /// <summary>根据Url获取Volume连接
        /// </summary>
        public Connection GetVolumeConnectionByUrl(string url)
        {
            var connectionAddress = new ConnectionAddress(url);

            return(GetVolumeConnectionInternal(connectionAddress));
        }
Ejemplo n.º 28
0
 /// <summary>创建连接对象
 /// </summary>
 /// <param name="connectionAddress"></param>
 /// <param name="connectionType"></param>
 /// <returns></returns>
 public Connection CreateConnection(ConnectionAddress connectionAddress, ConnectionType connectionType)
 {
     return(_provider.CreateInstance <Connection>(connectionAddress, connectionType));
 }
Ejemplo n.º 29
0
 public StorageNode(string groupName, string ipAddress, int port, byte storePathIndex)
 {
     GroupName         = groupName;
     ConnectionAddress = new ConnectionAddress(ipAddress, port);
     StorePathIndex    = storePathIndex;
 }
Ejemplo n.º 30
0
 /// <summary>根据连接地址创建Channel
 /// </summary>
 private GoogleGrpc.Channel CreateChannel(ConnectionAddress connectionAddress)
 {
     GoogleGrpc.Channel channel = new GoogleGrpc.Channel(connectionAddress.IPAddress, connectionAddress.Port, GoogleGrpc.ChannelCredentials.Insecure);
     return(channel);
 }