Ejemplo n.º 1
0
        public async Task<(DatabasePutResult Result, List<RavenServer> Servers)> CreateDatabaseInClusterInner(DatabaseRecord record, int replicationFactor, string leadersUrl, X509Certificate2 certificate)
        {
            var serverCount = Servers.Count(s => s.Disposed == false);
            if (serverCount < replicationFactor)
            {
                throw new InvalidOperationException($"Cannot create database with replication factor = {replicationFactor} when there is only {serverCount} servers in the cluster.");
            }

            DatabasePutResult databaseResult;
            string[] urls;
            using (var store = new DocumentStore()
            {
                Urls = new[] { leadersUrl },
                Database = record.DatabaseName,
                Certificate = certificate
            }.Initialize())
            {
                try
                {
                    databaseResult = store.Maintenance.Server.Send(new CreateDatabaseOperation(record, replicationFactor));
                }
                catch (ConcurrencyException inner)
                {
                    //catch debug logs
                    var sb = new StringBuilder();
                    await GetClusterDebugLogs(sb);
                    throw new ConcurrencyException($"Couldn't create database on time, cluster debug logs: {sb}", inner);
                }
                urls = await GetClusterNodeUrlsAsync(leadersUrl, store);
            }

            var firstUrlNode = databaseResult.NodesAddedTo.First();
            var currentCluster = Servers.Where(s => s.Disposed == false && s.ServerStore.GetClusterTopology().TryGetNodeTagByUrl(firstUrlNode).HasUrl).ToArray();

            int numberOfInstances = 0;
            foreach (var server in currentCluster)
            {
                await server.ServerStore.Cluster.WaitForIndexNotification(databaseResult.RaftCommandIndex);
            }

            var relevantServers = currentCluster.Where(s => databaseResult.Topology.RelevantFor(s.ServerStore.NodeTag)).ToArray();
            foreach (var server in relevantServers)
            {
                await server.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(record.DatabaseName);
                numberOfInstances++;
            }

            if (numberOfInstances != replicationFactor)
                throw new InvalidOperationException($@"Couldn't create the db on all nodes, just on {numberOfInstances}
                                                    out of {replicationFactor}{Environment.NewLine}
                                                    Server urls are {string.Join(",", Servers.Select(x => $"[{x.WebUrl}|{x.Disposed}]"))}; Current cluster (members) urls are : {string.Join(",", urls)}; The relevant servers are : {string.Join(",", relevantServers.Select(x => x.WebUrl))}; current servers are : {string.Join(",", currentCluster.Select(x => x.WebUrl))}");
            return (databaseResult, relevantServers.ToList());
        }
Ejemplo n.º 2
0
        public async Task <(long Index, List <RavenServer> Servers)> CreateDatabaseInCluster(DatabaseRecord record, int replicationFactor, string leadersUrl, X509Certificate2 certificate = null)
        {
            var serverCount = Servers.Count(s => s.Disposed == false);

            if (serverCount < replicationFactor)
            {
                throw new InvalidOperationException($"Cannot create database with replication factor = {replicationFactor} when there is only {serverCount} servers in the cluster.");
            }

            DatabasePutResult databaseResult;

            string[] urls;
            using (var store = new DocumentStore()
            {
                Urls = new[] { leadersUrl },
                Database = record.DatabaseName,
                Certificate = certificate
            }.Initialize())
            {
                databaseResult = store.Maintenance.Server.Send(new CreateDatabaseOperation(record, replicationFactor));
                urls           = await GetClusterNodeUrlsAsync(leadersUrl, store);
            }

            var currentServers = Servers.Where(s => s.Disposed == false &&
                                               urls.Contains(s.WebUrl, StringComparer.CurrentCultureIgnoreCase)).ToArray();
            int numberOfInstances = 0;

            foreach (var server in currentServers)
            {
                await server.ServerStore.Cluster.WaitForIndexNotification(databaseResult.RaftCommandIndex);
            }

            var relevantServers = currentServers.Where(s => databaseResult.Topology.RelevantFor(s.ServerStore.NodeTag)).ToArray();

            foreach (var server in relevantServers)
            {
                await server.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(record.DatabaseName);

                numberOfInstances++;
            }

            if (numberOfInstances != replicationFactor)
            {
                throw new InvalidOperationException($@"Couldn't create the db on all nodes, just on {numberOfInstances}
                                                    out of {replicationFactor}{Environment.NewLine}
                                                    Server urls are {string.Join(",", Servers.Select(x => $"[{x.WebUrl}|{x.Disposed}]"))}; Current cluster urls are : {string.Join(",", urls)}; The relevant servers are : {string.Join(",", relevantServers.Select(x => x.WebUrl))}; current servers are : {string.Join(",", currentServers.Select(x => x.WebUrl))}");
            }
            return(databaseResult.RaftCommandIndex,
                   relevantServers.ToList());
        }
        protected override async Task OnInitializedAsync()
        {
            Settings      = (await HttpClient.GetFromJsonAsync <List <Setting> >("api/settings")).ToDictionary(x => x.SettingId);
            UnturnedItems = await HttpClient.GetFromJsonAsync <IEnumerable <UnturnedItem> >("api/unturneditems");

            Servers = await HttpClient.GetFromJsonAsync <IEnumerable <Server> >("api/servers");

            if (PlayersService.CurrentUserInfo?.IsGlobalAdmin ?? false)
            {
                steamDevKey = Settings["SteamDevKey"];
                apiKey      = Settings["APIKey"];
                admins      = Settings["Admins"];
            }

            indexLayout    = Settings["IndexLayout"];
            itemPageLayout = Settings["ItemPageLayout"];
            productsLayout = Settings["ProductsLayout"];

            unturnedItemsCount    = UnturnedItems.Count();
            marketItemsCount      = UnturnedItems.Sum(x => x.MarketItemsCount);
            connectedServersCount = Servers.Count(x => x.IsConnected);
        }
        //==================================PIRIORITY=====================================================================================
        public void piriority(int customer, SimulationSystem s)
        {
            for (int i = 0; i < Servers.Count(); i++)
            {
                if (Servers[i].FinishTime <= s.SimulationTable[customer - 1].ArrivalTime)
                {
                    Servers[i].IsIdle = true;
                }
            }

            for (int x = 0; x < Servers.Count(); x++)
            {
                if (s.Servers[x].IsIdle == true)
                {
                    s.SimulationTable[customer - 1].AssignedServer.ID     = x + 1;
                    s.SimulationTable[customer - 1].AssignedServer.IsIdle = false;
                    s.Servers[x].IsIdle = false;
                    for (int j = 0; j < Servers[x].TimeDistribution.Count(); j++)
                    {
                        if (s.SimulationTable[customer - 1].RandomService <= Servers[x].TimeDistribution[j].MaxRange && s.SimulationTable[customer - 1].RandomService >= Servers[x].TimeDistribution[j].MinRange)
                        {
                            s.SimulationTable[customer - 1].ServiceTime = Servers[x].TimeDistribution[j].Time;
                            s.SimulationTable[customer - 1].StartTime   = s.SimulationTable[customer - 1].ArrivalTime;
                            s.SimulationTable[customer - 1].TimeInQueue = s.SimulationTable[customer - 1].StartTime - s.SimulationTable[customer - 1].ArrivalTime;
                            s.SimulationTable[customer - 1].StartTime   = s.SimulationTable[customer - 1].ArrivalTime + s.SimulationTable[customer - 1].TimeInQueue;
                            s.SimulationTable[customer - 1].EndTime     = s.SimulationTable[customer - 1].ServiceTime + s.SimulationTable[customer - 1].StartTime;
                            Servers[x].FinishTime = s.SimulationTable[customer - 1].EndTime;
                            counterToAddInQueue   = 0;
                            break;
                        }
                    }
                    if (counterToAddInQueue == 0)
                    {
                        break;
                    }
                }
                counterToAddInQueue++;
            }
            if (counterToAddInQueue == Servers.Count())
            {
                int min   = 9999999;
                int id    = 0;
                int index = 0;
                for (int i = 0; i < Servers.Count(); i++)
                {
                    int z = Servers[i].FinishTime;

                    if (z < min)
                    {
                        min   = z;
                        id    = i + 1;
                        index = i;
                    }
                    s.SimulationTable[customer - 1].AssignedServer.ID = id;
                }


                for (int j = 0; j < Servers[id - 1].TimeDistribution.Count(); j++)
                {
                    if (s.SimulationTable[customer - 1].RandomService <= Servers[id - 1].TimeDistribution[j].MaxRange && s.SimulationTable[customer - 1].RandomService >= Servers[id - 1].TimeDistribution[j].MinRange)
                    {
                        s.SimulationTable[customer - 1].ServiceTime = Servers[id - 1].TimeDistribution[j].Time;
                        s.SimulationTable[customer - 1].StartTime   = min;
                        s.SimulationTable[customer - 1].TimeInQueue = min - s.SimulationTable[customer - 1].ArrivalTime;
                        if (s.SimulationTable[customer - 1].TimeInQueue < 0)
                        {
                            s.SimulationTable[customer - 1].TimeInQueue = 0;
                        }
                        s.SimulationTable[customer - 1].StartTime = s.SimulationTable[customer - 1].ArrivalTime + s.SimulationTable[customer - 1].TimeInQueue;
                        if (min > s.SimulationTable[customer - 1].ArrivalTime)
                        {
                            s.SimulationTable[customer - 1].StartTime = min;
                        }

                        s.SimulationTable[customer - 1].EndTime = s.SimulationTable[customer - 1].ServiceTime + s.SimulationTable[customer - 1].StartTime;
                        Servers[id - 1].FinishTime = s.SimulationTable[customer - 1].EndTime;
                        counterToAddInQueue        = 0;
                        break;
                    }
                }
            }
        }
        //==================================RANDOOOOOM==========================================================================
        public void Random(int customer, SimulationSystem s)
        {
            List <int> FreeServers = new List <int>();
            int        counter     = 0;


            for (int i = 0; i < Servers.Count(); i++)
            {
                FreeServers.Add(new int());
            }

            for (int i = 0; i < Servers.Count(); i++)
            {
                if (Servers[i].FinishTime <= s.SimulationTable[customer - 1].ArrivalTime)
                {
                    Servers[i].IsIdle = true;
                    counter++;
                    FreeServers[i] = s.Servers[i].ID;
                }
            }

            for (int x = 0; x < Servers.Count(); x++)
            {
                if (s.Servers[x].IsIdle == true)
                {
                    if (counter > 1)
                    {
                        int y = 0;
                        y = r.Next(0, counter - 1);
                        x = FreeServers[y];
                        x--;
                        counter = 0;
                    }
                    s.SimulationTable[customer - 1].AssignedServer.ID     = x + 1;
                    s.SimulationTable[customer - 1].AssignedServer.IsIdle = false;
                    s.Servers[x].IsIdle = false;
                    for (int j = 0; j < Servers[x].TimeDistribution.Count(); j++)
                    {
                        if (s.SimulationTable[customer - 1].RandomService <= Servers[x].TimeDistribution[j].MaxRange && s.SimulationTable[customer - 1].RandomService >= Servers[x].TimeDistribution[j].MinRange)
                        {
                            s.SimulationTable[customer - 1].ServiceTime = Servers[x].TimeDistribution[j].Time;
                            s.SimulationTable[customer - 1].StartTime   = s.SimulationTable[customer - 1].ArrivalTime;
                            s.SimulationTable[customer - 1].TimeInQueue = s.SimulationTable[customer - 1].StartTime - s.SimulationTable[customer - 1].ArrivalTime;
                            s.SimulationTable[customer - 1].StartTime   = s.SimulationTable[customer - 1].ArrivalTime + s.SimulationTable[customer - 1].TimeInQueue;
                            s.SimulationTable[customer - 1].EndTime     = s.SimulationTable[customer - 1].ServiceTime + s.SimulationTable[customer - 1].StartTime;
                            Servers[x].FinishTime = s.SimulationTable[customer - 1].EndTime;
                            counterToAddInQueue   = 0;
                            break;
                        }
                    }
                    if (counterToAddInQueue == 0)
                    {
                        break;
                    }
                }
                counterToAddInQueue++;
            }
            if (counterToAddInQueue == s.Servers.Count())
            {
                int counterr = -1;
                int jj       = 0;
                int min      = 9999999;
                int id       = 0;
                int index    = 0;
                for (int i = 0; i < Servers.Count(); i++)
                {
                    int z = Servers[i].FinishTime;

                    if (z < min)
                    {
                        min   = z;
                        id    = i + 1;
                        index = i;
                    }
                }
                FreeServers[jj] = id;
                jj++;
                for (int i = 0; i < Servers.Count(); i++)
                {
                    if (min == Servers[i].FinishTime)
                    {
                        counterr++;
                    }
                    if (counterr > 0)
                    {
                        FreeServers[jj] = i + 1;
                        jj++;
                    }
                }
                id = FreeServers[r.Next(0, jj - 1)];
                s.SimulationTable[customer - 1].AssignedServer.ID = id;
                for (int j = 0; j < Servers[id - 1].TimeDistribution.Count(); j++)
                {
                    if (s.SimulationTable[customer - 1].RandomService <= Servers[id - 1].TimeDistribution[j].MaxRange && s.SimulationTable[customer - 1].RandomService >= Servers[id - 1].TimeDistribution[j].MinRange)
                    {
                        s.SimulationTable[customer - 1].ServiceTime = Servers[id - 1].TimeDistribution[j].Time;
                        s.SimulationTable[customer - 1].StartTime   = min;
                        s.SimulationTable[customer - 1].TimeInQueue = min - s.SimulationTable[customer - 1].ArrivalTime;
                        if (s.SimulationTable[customer - 1].TimeInQueue < 0)
                        {
                            s.SimulationTable[customer - 1].TimeInQueue = 0;
                        }
                        s.SimulationTable[customer - 1].StartTime = s.SimulationTable[customer - 1].ArrivalTime + s.SimulationTable[customer - 1].TimeInQueue;
                        if (min > s.SimulationTable[customer - 1].ArrivalTime)
                        {
                            s.SimulationTable[customer - 1].StartTime = min;
                        }

                        s.SimulationTable[customer - 1].EndTime = s.SimulationTable[customer - 1].ServiceTime + s.SimulationTable[customer - 1].StartTime;
                        Servers[id - 1].FinishTime = s.SimulationTable[customer - 1].EndTime;
                        counterToAddInQueue        = 0;
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// Loads the most updated configuration creating any resources as needed.
        /// </summary>
        /// <param name="bucketConfig">The latest <see cref="IBucketConfig"/>
        /// that will drive the recreation if the configuration context.</param>
        public override void LoadConfig(IBucketConfig bucketConfig, bool force = false)
        {
            try
            {
                Lock.EnterWriteLock();
                if (bucketConfig == null)
                {
                    throw new ArgumentNullException("bucketConfig");
                }
                if (BucketConfig == null || !BucketConfig.Nodes.AreEqual <Node>(bucketConfig.Nodes) || !Servers.Any() ||
                    force)
                {
                    Log.Info(m => m("o1-Creating the Servers {0} list using rev#{1}", Servers.Count(), bucketConfig.Rev));
                    var clientBucketConfig = ClientConfig.BucketConfigs[bucketConfig.Name];
                    var servers            = new List <IServer>();
                    var nodes = bucketConfig.GetNodes();
                    foreach (var adapter in nodes)
                    {
                        var endpoint = IPEndPointExtensions.GetEndPoint(adapter, clientBucketConfig, BucketConfig);
                        try
                        {
                            var poolConfiguration = ClientConfig.BucketConfigs[bucketConfig.Name].PoolConfiguration;
                            var connectionPool    = ConnectionPoolFactory(poolConfiguration, endpoint);
                            var ioStrategy        = IOStrategyFactory(connectionPool);
                            var saslMechanism     = SaslFactory(bucketConfig.Name, bucketConfig.Password, ioStrategy, Converter);
                            ioStrategy.SaslMechanism = saslMechanism;

                            var server = new Core.Server(ioStrategy, adapter, ClientConfig, bucketConfig);
                            servers.Add(server);
                        }
                        catch (Exception e)
                        {
                            Log.ErrorFormat("Could not add server {0}. Exception: {1}", endpoint, e);
                        }
                    }
                    var old = Interlocked.Exchange(ref Servers, servers);
                    if (old != null)
                    {
                        old.ForEach(x => x.Dispose());
                        old.Clear();
                    }
                }
                Log.Info(m => m("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev));
                Interlocked.Exchange(ref _bucketConfig, bucketConfig);
                Interlocked.Exchange(ref KeyMapper, new VBucketKeyMapper(Servers, _bucketConfig.VBucketServerMap)
                {
                    Rev = _bucketConfig.Rev
                });
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            finally
            {
                Lock.ExitWriteLock();
            }
        }
        /// <summary>
        /// Прослушивает поток, на наличие сообщений от сервера
        /// Прежде чем добавить какой-нибудь объект в swich подумай 10 раз!
        /// Т.к. создатель этого метода не шибко умный, тебе придется либо увеличивать switch
        /// Либо писать огромный метод, который будет все это обрабатывать, что тоже не оч. верно
        /// </summary>
        private void TakeMessageOfServer()
        {
            Object ob = null;

            do
            {
                try
                {
                    ob = SendMessageToServer.TakeMessageSerialize();
                }
                catch (Exception)
                {
                    break;
                }

                switch (ob)
                {
                /// Получаем сообщения и отправляем их на текстовые чаты
                case Message message:
                    var text = TextChats.Find(x => x.ID == message.IDTextChat);
                    text.Message.Add(message);

                    //// выполняются полиморфные вызовы
                    EventUpMessage((IEnumerable <Message>)text.Message);
                    break;

                /// Получаем пользователя и меняем его статус на сервере
                case ServerUser user:
                    if (user.StatusObj == StatusObj.Add)
                    {
                        User.ServerUser.Add(user);

                        var server = user.Server;
                        Servers.Add(server);

                        EventUpServer?.Invoke(Servers);

                        EventUpServersFromUser?.Invoke(Servers);

                        break;
                    }
                    else if (user.StatusObj == StatusObj.Delete)
                    {
                        User.ServerUser = User.ServerUser.Where(x => user.ID != x.ID).ToList();

                        var server = user.Server;
                        var asd    = Servers.Where(x => server.ID != x.ID).ToList();
                        Servers.Clear();
                        foreach (var item in asd)
                        {
                            Servers.Add(item);
                        }

                        EventUpServer?.Invoke(Servers);

                        EventUpServersFromUser?.Invoke(Servers);

                        break;
                    }

                    if (Users is null)
                    {
                        break;
                    }

                    var a = Users.FirstOrDefault(x => x.IDUser == user.IDUser);
                    if (a is null)
                    {
                        break;
                    }

                    EventUpUserStatus(Users);
                    break;

                /// Получаем пользователей на сервере запоминаем и отправляем в окно редактирования, если оно открыто
                case (List <ServerUser> SU):
                    if (SU is null)
                    {
                        break;
                    }

                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(SU);
                        return;
                    }
                    if (WFAU is not null)
                    {
                        EventUpFriendsAndUsers?.Invoke(SU);
                        return;
                    }

                    Users = SU;
                    EventUpUserStatus?.Invoke(SU);

                    break;

                /// получаем список серверов у пользователя или в окне поиска (TODO)
                case (List <Server> Servers):
                    if (Servers is null || Servers.Count() == 0)
                    {
                        break;
                    }

                    EventUpServerSearch(Servers);
                    break;

                /// получаем сервер, если он обновился и отправляем в окно редактирования, если оно открыто
                case (Server Server):
                    if (Server is null)
                    {
                        break;
                    }

                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(Server);
                    }

                    break;

                /// получаем текстовые чаты и отправляем их в окно редактирования, если оно открыто
                case List <TextChat> textChat:
                    if (textChat is null)
                    {
                        break;
                    }

                    TextChats = textChat;
                    this.EventUpTextChat?.Invoke(textChat);

                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(textChat);
                    }

                    break;

                /// получаем Отзывы о сервере и отправляем их в окно редактирования, если оно открыто
                case List <Opinion> Opinions:
                    if (Opinions is null)
                    {
                        break;
                    }

                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(Opinions);
                    }

                    EventUpOpinion(Opinions);

                    break;

                /// получаем Роли на сервере и отправляем их в окно редактирования, если оно открыто
                case List <Role> Role:
                    if (Role is null)
                    {
                        break;
                    }

                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(Role);
                    }

                    break;

                /// получаем Журнал событий сервера и отправляем его в окно редактирования, если оно открыто
                case List <EventLog> EL:
                    if (EL is null)
                    {
                        break;
                    }

                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(EL);
                    }

                    break;

                /// получаем Журнал событий сервера и отправляем его в окно редактирования, если оно открыто
                case List <Request> RL:
                    if (RL is null)
                    {
                        break;
                    }

                    EventUpFriendsAndUsers.Invoke(RL);
                    break;

                case List <User> UL:
                    if (UL is null)
                    {
                        break;
                    }

                    EventUpFriendsAndUsers.Invoke(UL);
                    break;

                case List <UserLog> UL:
                    if (UL is null)
                    {
                        break;
                    }

                    EventUpFriendsAndUsers.Invoke(UL);
                    break;

                case User user:
                    EventUpFriendsAndUsers.Invoke(user);
                    break;

                case String str:
                    if (str == "closestream")
                    {
                        Environment.Exit(0);
                    }
                    break;

                default:
                    MessageBox
                    .Show("Сервер отправил какой-то странный объект.." + ob.GetType().Name);
                    break;
                }
            } while (true);
        }
Ejemplo n.º 8
0
 public bool HasServer(HttpRequest request)
 {
     return(Servers.Count(s => s.Agent.WebSocket == request.WebSocket) > 0);
 }
        /// <summary>
        /// Loads the most updated configuration creating any resources as needed.
        /// </summary>
        /// <param name="bucketConfig">The latest <see cref="IBucketConfig"/>
        /// that will drive the recreation if the configuration context.</param>
        /// <param name="force">True to force the reconfiguration.</param>
        public override void LoadConfig(IBucketConfig bucketConfig, bool force = false)
        {
            try
            {
                Lock.EnterWriteLock();
                var nodes = bucketConfig.GetNodes();
                if (BucketConfig == null || !nodes.AreEqual(_bucketConfig.GetNodes()) || !Servers.Any() || force)
                {
                    var clientBucketConfig = ClientConfig.BucketConfigs[bucketConfig.Name];
                    var servers            = new Dictionary <IPAddress, IServer>();
                    foreach (var adapter in nodes)
                    {
                        var endpoint = adapter.GetIPEndPoint(clientBucketConfig.UseSsl);
                        try
                        {
                            Log.Info(
                                m =>
                                m("o1-Creating the Servers {0} list using rev#{1}", Servers.Count(),
                                  bucketConfig.Rev));
                            var poolConfiguration = ClientConfig.BucketConfigs[bucketConfig.Name].PoolConfiguration;

                            var connectionPool = ConnectionPoolFactory(poolConfiguration, endpoint);
                            var ioStrategy     = IOStrategyFactory(connectionPool);

                            var server = new Core.Server(ioStrategy, adapter, ClientConfig, bucketConfig, Transcoder, QueryCache)
                            {
                                SaslFactory = SaslFactory
                            };
                            server.CreateSaslMechanismIfNotExists();
                            SupportsEnhancedDurability = ioStrategy.SupportsEnhancedDurability;

                            servers.Add(endpoint.Address, server);
                        }
                        catch (Exception e)
                        {
                            Log.ErrorFormat("Could not add server {0}. Exception: {1}", endpoint, e);
                        }
                    }

                    UpdateServices(servers);

                    var old = Interlocked.Exchange(ref Servers, servers);
                    Log.Info(m => m("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev));
                    var vBucketKeyMapper = new VBucketKeyMapper(Servers, bucketConfig.VBucketServerMap, bucketConfig.Rev);
                    Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper);
                    Interlocked.Exchange(ref _bucketConfig, bucketConfig);

                    if (old != null)
                    {
                        foreach (var server in old.Values)
                        {
                            server.Dispose();
                        }
                        old.Clear();
                    }
                }
                else
                {
                    if (BucketConfig == null || !BucketConfig.IsVBucketServerMapEqual(bucketConfig) || force)
                    {
                        Log.Info(m => m("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev));
                        var vBucketKeyMapper = new VBucketKeyMapper(Servers, bucketConfig.VBucketServerMap,
                                                                    bucketConfig.Rev);
                        Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper);
                        Interlocked.Exchange(ref _bucketConfig, bucketConfig);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            finally
            {
                Lock.ExitWriteLock();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Прослушивает поток, на наличие сообщений от сервера
        /// Прежде чем добавить какой-нибудь объект в swich подумай 10 раз!
        /// Т.к. создатель этого метода не шибко умный, тебе придется либо увеличивать switch
        /// Либо писать огромный метод, который будет все это обрабатывать, что тоже не оч. верно
        /// </summary>
        private void TakeMessageOfServer()
        {
            Object ob = null;

            do
            {
                try
                {
                    ob = TakeMessageSerialize();
                }
                catch (Exception)
                {
                    break;
                }

                switch (ob)
                {
                /// Получаем сообщения и отправляем их на текстовые чаты
                case Message message:
                    var text = TextChats.Find(x => x.ID == message.IDTextChat);
                    text.Message.Add(message);

                    EventUpMessage(text.Message.ToList());
                    break;

                /// Получаем пользователя и меняем его статус на сервере
                case ServerUser user:
                    if (Users is null)
                    {
                        break;
                    }

                    var a = Users.FirstOrDefault(x => x.IDUser == user.IDUser);
                    if (a is null)
                    {
                        break;
                    }

                    EventUpUserStatus(Users);
                    break;

                /// Получаем пользователей на сервере запоминаем и отправляем в окно редактирования, если оно открыто
                case (List <ServerUser> SU):
                    if (SU is null)
                    {
                        break;
                    }

                    Users = SU;
                    EventUpUserStatus(SU);
                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(SU);
                    }
                    break;

                /// получаем список серверов у пользователя или в окне поиска (TODO)
                case (List <Server> Servers):
                    if (Servers is null || Servers.Count() == 0)
                    {
                        break;
                    }

                    EventUpServer(Servers);
                    break;

                /// получаем сервер, если он обновился и отправляем в окно редактирования, если оно открыто
                case (Server Server):
                    if (Server is null)
                    {
                        break;
                    }

                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(Server);
                    }

                    break;

                /// получаем текстовые чаты и отправляем их в окно редактирования, если оно открыто
                case List <TextChat> textChat:
                    if (textChat is null)
                    {
                        break;
                    }

                    TextChats = textChat;
                    this.EventUpTextChat?.Invoke(textChat);

                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(textChat);
                    }

                    break;

                /// получаем Отзывы о сервере и отправляем их в окно редактирования, если оно открыто
                case List <Opinion> Opinions:
                    if (Opinions is null)
                    {
                        return;
                    }

                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(Opinions);
                    }

                    break;

                /// получаем Роли на сервере и отправляем их в окно редактирования, если оно открыто
                case List <Role> Role:
                    if (Role is null)
                    {
                        return;
                    }

                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(Role);
                    }

                    break;

                /// получаем Журнал событий сервера и отправляем его в окно редактирования, если оно открыто
                case List <EventLog> EL:
                    if (EL is null)
                    {
                        return;
                    }

                    if (WEditingServer is not null)
                    {
                        WEditingServer.StartEventOfObject(EL);
                    }

                    break;

                case String str:
                    if (str == "closestream")
                    {
                        Environment.Exit(0);
                    }
                    break;

                default:
                    MessageBox
                    .Show("Сервер отправил какой-то странный объект.." + ob.GetType().Name);
                    break;
                }
            } while (true);
        }