public Task <SiloAddress> SelectSiloPowerOfK(PlacementStrategy strategy, PlacementTarget target, IPlacementContext context)
        {
            var compatibleSilos = context.GetCompatibleSilos(target);
            // Exclude overloaded and non-compatible silos
            var relevantSilos = new List <CachedLocalStat>();

            foreach (CachedLocalStat current in localCache.Values)
            {
                if (IsSiloOverloaded(current.SiloStats))
                {
                    continue;
                }
                if (!compatibleSilos.Contains(current.Address))
                {
                    continue;
                }

                relevantSilos.Add(current);
            }

            if (relevantSilos.Count > 0)
            {
                int chooseFrom           = Math.Min(relevantSilos.Count, chooseHowMany);
                var chooseFromThoseSilos = new List <CachedLocalStat>();
                while (chooseFromThoseSilos.Count < chooseFrom)
                {
                    int index      = random.Next(relevantSilos.Count);
                    var pickedSilo = relevantSilos[index];
                    relevantSilos.RemoveAt(index);
                    chooseFromThoseSilos.Add(pickedSilo);
                }

                CachedLocalStat minLoadedSilo = chooseFromThoseSilos.First();
                foreach (CachedLocalStat s in chooseFromThoseSilos)
                {
                    if (SiloLoad_ByRecentActivations(s) < SiloLoad_ByRecentActivations(minLoadedSilo))
                    {
                        minLoadedSilo = s;
                    }
                }

                return(MakePlacement(minLoadedSilo));
            }

            var debugLog = string.Format("Unable to select a candidate from {0} silos: {1}", localCache.Count,
                                         Utils.EnumerableToString(
                                             localCache,
                                             kvp => String.Format("SiloAddress = {0} -> {1}", kvp.Key.ToString(), kvp.Value.ToString())));

            logger.Warn(ErrorCode.Placement_ActivationCountBasedDirector_NoSilos, debugLog);
            throw new OrleansException(debugLog);
        }
        private PlacementResult SelectActivationCore(PlacementStrategy strategy, GrainId target, IPlacementRuntime context)
        {
            if (target.IsClient)
            {
                throw new InvalidOperationException("Cannot use StatelessWorkerStrategy to route messages to client grains.");
            }

            // If there are available (not busy with a request) activations, it returns the first one.
            // If all are busy and the number of local activations reached or exceeded MaxLocal, it randomly returns one of them.
            // Otherwise, it requests creation of a new activation.
            List <ActivationData> local;

            if (!context.LocalLookup(target, out local) || local.Count == 0)
            {
                return(null);
            }

            var placement = (StatelessWorkerPlacement)strategy;

            foreach (var activation in local)
            {
                ActivationData info;
                if (!context.TryGetActivationData(activation.ActivationId, out info) ||
                    info.State != ActivationState.Valid || !info.IsInactive)
                {
                    continue;
                }

                return(PlacementResult.IdentifySelection(ActivationAddress.GetAddress(context.LocalSilo, target, activation.ActivationId)));
            }

            if (local.Count >= placement.MaxLocal)
            {
                var id = local[local.Count == 1 ? 0 : random.Next(local.Count)].ActivationId;
                return(PlacementResult.IdentifySelection(ActivationAddress.GetAddress(context.LocalSilo, target, id)));
            }

            return(null);
        }
        public Task <SiloAddress> OnAddActivation(PlacementStrategy strategy, PlacementTarget target, IPlacementContext context)
        {
            var silos = context.GetCompatibleSilos(target).OrderBy(s => s).ToArray();
            //尽量把每一个隔开
            long grainid = target.GrainIdentity.PrimaryKeyLong;

            if (silos.Length > grainid)
            {
                return(Task.FromResult(silos[grainid]));
            }
            else
            {
                return(Task.FromResult(silos[random.Next(silos.Length)]));
            }
        }
        protected PlacementResult ChooseRandomActivation(List <ActivationAddress> places, IPlacementRuntime context)
        {
            if (places.Count <= 0)
            {
                // we return null to indicate that we were unable to select a target from places activations.
                return(null);
            }
            if (places.Count == 1)
            {
                return(PlacementResult.IdentifySelection(places[0]));
            }
            // places.Count >= 2
            // Choose randomly if there is one, else make a new activation of the target
            // pick local if available (consider making this a purely random assignment of grains).
            var here  = context.LocalSilo;
            var local = places.Where(a => a.Silo.Equals(here)).ToList();

            if (local.Count > 0)
            {
                return(PlacementResult.IdentifySelection(local[random.Next(local.Count)]));
            }

            return(PlacementResult.IdentifySelection(places[random.Next(places.Count)]));
        }
        public void RandomEqualTest()
        {
            SafeRandom rnd = new SafeRandom();

            for (int loop = 0; loop < 100000; loop++)
            {
                byte[] a = new byte[rnd.Next(1, 100)];
                rnd.NextBytes(a);

                byte[] b = DeepCopy(a);

                bool actual = ByteArrayEqualityComparer.AreEqual(a, b);
                Assert.IsTrue(actual);
            }
        }
Beispiel #6
0
        private static byte GenerateSocketCount(int itemId, int moblevel)
        {
            if (itemId < 410000 || itemId > 601999)
            {
                return(0);
            }

            var nRate = SafeRandom.Next(0, 200 - moblevel / 2);

            if (nRate < 5)
            {
                return(2);
            }

            return((byte)(nRate < 20 ? 1 : 0));
        }
Beispiel #7
0
        public static Storage Create(YiObj owner, int npcId)
        {
            var storage = new Storage
            {
                OwnerId     = owner.UniqueId,
                NpcId       = npcId,
                StorageId   = SafeRandom.Next(0, 1000),
                AccessCode  = "",
                StorageName = "Unnamed Storage",
                Contents    = new ConcurrentDictionary <int, Item>(),
                Members     = new ConcurrentDictionary <int, StorageAccess>()
            };

            storage.Members.AddOrUpdate(owner.UniqueId, StorageAccess.Owner);
            return(storage);
        }
Beispiel #8
0
        public bool AddItem(Item item, int count = 1)
        {
            if (Items.Count + count > 40)
            {
                return(false);
            }

            for (var i = 0; i < count; i++)
            {
                var clone = CloneChamber.Clone(item);
                clone.UniqueId = SafeRandom.Next(1000, 100000);
                Items.TryAdd(clone.UniqueId, clone);
                (_owner as Player)?.Send(new MsgItemInformation(clone, MsgItemPosition.Inventory));
            }
            return(true);
        }
Beispiel #9
0
        private static void ACTION_RANDACTION(YiObj target, YiObj attacker, cq_action cqaction, SquigglyContext db)
        {
            var nextIds = cqaction.param.Trim().Split(' ');

            var nextIndex = SafeRandom.Next(nextIds.Length);

            var nextId = long.Parse(nextIds[nextIndex]);

            cqaction = db.cq_action.Find(nextId);
            //Output.WriteLine($"Mob Action -> Data: {cqaction.data} Param: {cqaction.param.Trim()}",ConsoleColor.Green);

            var dropId = cqaction.param.Trim().Split(' ')[1];
            var item   = ItemFactory.Create(int.Parse(dropId));

            FloorItemSystem.Drop(attacker, target, item);
        }
Beispiel #10
0
        /// <summary>
        /// Get a random ItemTemplate.
        /// </summary>
        /// <returns>A random ItemTemplate. Will not be null.</returns>
        public IItemTemplateTable GetRandomTemplate()
        {
            var max = Length;

            IItemTemplateTable template;

            do
            {
                var i = _rnd.Next(0, max);
                if (!TryGetValue(new ItemTemplateID(i), out template))
                {
                    template = null;
                }
            }while (template == null);

            return(template);
        }
Beispiel #11
0
        /// <summary>
        /// Connection loop used to reconnect and keep the connection open.
        /// </summary>
        public void ConnectLoop()
        {
            // TODO: do not re-use object
            while (!_token.IsCancellationRequested)
            {
                if (!Connected)
                {
                    Host host = _hosts.GetNextHost();

                    bool ipv4_addr = string.IsNullOrEmpty(host.IPv4Address.ToString());
                    bool ipv6_addr = string.IsNullOrEmpty(host.IPv6Address.ToString());

                    if (!ipv4_addr && !ipv6_addr)
                    {
                        base.Connect(AddressFamily.InterNetwork, host.IPv4Address, host.Port, false);
                        base.Connect(AddressFamily.InterNetworkV6, host.IPv6Address, host.Port);
                    }
                    else if (!ipv4_addr && ipv6_addr)
                    {
                        base.Connect(AddressFamily.InterNetwork, host.IPv4Address, host.Port);
                    }
                    else if (ipv4_addr && !ipv6_addr)
                    {
                        base.Connect(AddressFamily.InterNetworkV6, host.IPv6Address, host.Port);
                    }
                    else
                    {
                        Debug.WriteLine("Client Fail - Exception Message: IPv4 and IPv6 are empty...");
                    }
                }

                while (Connected) // hold client open
                {
                    _token.WaitHandle.WaitOne(1000);
                }

                if (_token.IsCancellationRequested)
                {
                    Disconnect();
                    return;
                }

                Thread.Sleep(Settings.RECONNECTDELAY + _random.Next(250, 750));
            }
        }
        /// <summary>
        /// Creates an instance of the <see cref="ItemEntity"/> from the template.
        /// </summary>
        /// <returns>The instance of the <see cref="ItemEntity"/>, or null if the creation chance failed.</returns>
        public static ItemEntity CreateInstance(this CharacterTemplateInventoryItem v)
        {
            if (!v.Chance.Test())
            {
                return(null);
            }

            var amount = (byte)_random.Next(v.Min, v.Max + 1);

            if (amount == 0)
            {
                return(null);
            }

            var instance = new ItemEntity(v.ItemTemplate, Vector2.Zero, amount);

            return(instance);
        }
Beispiel #13
0
        private static byte GenerateQuality(int moblevel)
        {
            var i = SafeRandom.Next(1, 1000);

            i -= moblevel / 25;

            if (i < 1)
            {
                return(9);//super
            }
            if (i < 11)
            {
                return(8);//eli
            }
            if (i < 31)
            {
                return(7);//uni
            }
            return((byte)(i < 55 ? 6 : 3));
        }
Beispiel #14
0
 private static void QueueDrop(FloorItem drop)
 {
     YiScheduler.Instance.Do(SchedulerPriority.Medium, () =>
     {
         for (var i = 0; i < 10; i++)
         {
             if (!GameWorld.Maps[drop.MapId].ItemValid(drop.Location.X, drop.Location.Y))
             {
                 drop.Location.X += (ushort)SafeRandom.Next(-1, 2);
                 drop.Location.Y += (ushort)SafeRandom.Next(-1, 2);
             }
             else
             {
                 AddCountdown(drop);
                 ScheduleDestruction(drop);
                 ScheduleOwnerRemove(drop);
                 ScreenSystem.Create(drop);
                 FloorItems.AddOrUpdate(drop.UniqueId, drop);
                 GameWorld.Maps[drop.MapId].Enter(drop);
                 if (drop.Original.Valid() && drop.Owner is Player player)
                 {
                     var packet = MsgItem.Create(drop.Original.UniqueId, drop.Original.UniqueId, drop.Original.UniqueId, MsgItemType.RemoveInventory);
                     player.Send(packet);
                 }
                 ScreenSystem.Send(drop, MsgFloorItem.Create(drop, MsgFloorItemType.Create), true);
                 drop.AddStatusEffect(StatusEffect.SuperMan);
                 return;
             }
         }
         if (drop.Original.Valid() && drop.Owner is Player owner)
         {
             owner.Inventory.AddOrUpdate(drop.Original.UniqueId, drop.Original);
             owner.Send(new MsgItemInformation(drop.Original, MsgItemPosition.Inventory));
         }
         else
         {
             drop.Owner.Money += drop.Amount;
         }
     });
 }
        /// <summary>
        /// Async method to put an entry into the remider table
        /// </summary>
        /// <param name="entry"> The entry to put </param>
        /// <returns> Return the entry ETag if entry was upsert successfully </returns>
        public async Task <string> UpsertRow(ReminderEntry entry)
        {
            var reminderId = ConstructReminderId(serviceId, entry.GrainRef, entry.ReminderName);

            var fields = new Dictionary <string, AttributeValue>
            {
                { REMINDER_ID_PROPERTY_NAME, new AttributeValue(reminderId) },
                { GRAIN_HASH_PROPERTY_NAME, new AttributeValue {
                      N = entry.GrainRef.GetUniformHashCode().ToString()
                  } },
                { SERVICE_ID_PROPERTY_NAME, new AttributeValue(serviceId.ToString()) },
                { GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue(entry.GrainRef.ToKeyString()) },
                { PERIOD_PROPERTY_NAME, new AttributeValue(entry.Period.ToString()) },
                { START_TIME_PROPERTY_NAME, new AttributeValue(entry.StartAt.ToString()) },
                { REMINDER_NAME_PROPERTY_NAME, new AttributeValue(entry.ReminderName) },
                { ETAG_PROPERTY_NAME, new AttributeValue {
                      N = random.Next(int.MaxValue).ToString()
                  } }
            };

            try
            {
                if (logger.IsEnabled(LogLevel.Debug))
                {
                    logger.Debug("UpsertRow entry = {0}, etag = {1}", entry.ToString(), entry.ETag);
                }

                await storage.PutEntryAsync(TABLE_NAME_DEFAULT_VALUE, fields);

                entry.ETag = fields[ETAG_PROPERTY_NAME].N;
                return(entry.ETag);
            }
            catch (Exception exc)
            {
                logger.Warn(ErrorCode.ReminderServiceBase,
                            $"Intermediate error updating entry {entry.ToString()} to the table {TABLE_NAME_DEFAULT_VALUE}.", exc);
                throw;
            }
        }
Beispiel #16
0
        private void FindRespawnLocation()
        {
            var spawn = Collections.Spawns[SpawnId];

            var spawnAttempts = 0;

            while (true)
            {
                if (spawnAttempts > 1000)
                {
                    break;
                }

                Location.X = (ushort)SafeRandom.Next(spawn.Xstart - 10, spawn.Xstart + spawn.Xend + 10);
                Location.Y = (ushort)SafeRandom.Next(spawn.Ystart - 10, spawn.Ystart + spawn.Yend + 10);

                spawnAttempts++;
                if (GameWorld.Maps[MapId].MobValid(Location.X, Location.Y))
                {
                    break;
                }
            }
            SpawnPoint = Location;
        }
Beispiel #17
0
        public async Task RequestContext_MultiThreads_ExportToMessage()
        {
            const int NumLoops = 50;
            string id = "key" + random.Next();

            Message msg = new Message();
            Task[] promises = new Task[NumLoops];
            ManualResetEventSlim flag = new ManualResetEventSlim(false);
            for (int i = 0; i < NumLoops; i++)
            {
                string key = id + "-" + i;
                RequestContext.Set(key, i);
                promises[i] = Task.Run(() =>
                {
                    flag.Wait(); 
                    msg.RequestContextData = RequestContext.Export();
                });
                flag.Set();
                Thread.Sleep(1);
                RequestContext.Remove(key);
            }
            await Task.WhenAll(promises);
        }
Beispiel #18
0
 public static int GetRandomTransferId()
 {
     return(Random.Next(0, int.MaxValue));
 }
Beispiel #19
0
        private async Task Run()
        {
            var random = new SafeRandom();
            ClusterMembershipSnapshot activeMembersSnapshot = default;

            SiloAddress[] otherNodes    = default;
            TimeSpan?     overrideDelay = random.NextTimeSpan(_clusterMembershipOptions.CurrentValue.ProbeTimeout);

            while (await _pingTimer.NextTick(overrideDelay))
            {
                ProbeResult probeResult;
                overrideDelay = default;

                try
                {
                    // Discover the other active nodes in the cluster, if there are any.
                    var membershipSnapshot = _membershipService.CurrentSnapshot;
                    if (otherNodes is null || !object.ReferenceEquals(activeMembersSnapshot, membershipSnapshot))
                    {
                        activeMembersSnapshot = membershipSnapshot;
                        otherNodes            = membershipSnapshot.Members.Values
                                                .Where(v => v.Status == SiloStatus.Active && v.SiloAddress != this.SiloAddress && v.SiloAddress != _localSiloDetails.SiloAddress)
                                                .Select(s => s.SiloAddress)
                                                .ToArray();
                    }

                    var isDirectProbe = !_clusterMembershipOptions.CurrentValue.EnableIndirectProbes || _failedProbes < _clusterMembershipOptions.CurrentValue.NumMissedProbesLimit - 1 || otherNodes.Length == 0;
                    var timeout       = GetTimeout(isDirectProbe);
                    var cancellation  = new CancellationTokenSource(timeout);

                    if (isDirectProbe)
                    {
                        // Probe the silo directly.
                        probeResult = await this.ProbeDirectly(cancellation.Token).ConfigureAwait(false);
                    }
                    else
                    {
                        // Pick a random other node and probe the target indirectly, using the selected node as an intermediary.
                        var intermediary = otherNodes[random.Next(0, otherNodes.Length - 1)];

                        // Select a timeout which will allow the intermediary node to attempt to probe the target node and still respond to this node
                        // if the remote node does not respond in time.
                        // Attempt to account for local health degradation by extending the timeout period.
                        probeResult = await this.ProbeIndirectly(intermediary, timeout, cancellation.Token).ConfigureAwait(false);

                        // If the intermediary is not entirely healthy, remove it from consideration and continue to probe.
                        // Note that all recused silos will be included in the consideration set the next time cluster membership changes.
                        if (probeResult.Status != ProbeResultStatus.Succeeded && probeResult.IntermediaryHealthDegradationScore > 0)
                        {
                            _log.LogInformation("Recusing unhealthy intermediary {Intermediary} and trying again with remaining nodes", intermediary);
                            otherNodes    = otherNodes.Where(node => !node.Equals(intermediary)).ToArray();
                            overrideDelay = TimeSpan.FromMilliseconds(250);
                        }
                    }

                    if (!_stoppingCancellation.IsCancellationRequested)
                    {
                        await _onProbeResult(this, probeResult).ConfigureAwait(false);
                    }
                }
                catch (Exception exception)
                {
                    _log.LogError(exception, "Exception monitoring silo {SiloAddress}", SiloAddress);
                }
            }

            TimeSpan GetTimeout(bool isDirectProbe)
            {
                var additionalTimeout = 0;

                if (_clusterMembershipOptions.CurrentValue.ExtendProbeTimeoutDuringDegradation)
                {
                    // Attempt to account for local health degradation by extending the timeout period.
                    var localDegradationScore = _localSiloHealthMonitor.GetLocalHealthDegradationScore(DateTime.UtcNow);
                    additionalTimeout += localDegradationScore;
                }

                if (!isDirectProbe)
                {
                    // Indirect probes need extra time to account for the additional hop.
                    additionalTimeout += 1;
                }

                return(_clusterMembershipOptions.CurrentValue.ProbeTimeout.Multiply(1 + additionalTimeout));
            }
        }
Beispiel #20
0
        public GatewayManager(ClientConfiguration cfg, IGatewayListProvider gatewayListProvider)
        {
            config    = cfg;
            knownDead = new Dictionary <Uri, DateTime>();
            rand      = new SafeRandom();
            logger    = TraceLogger.GetLogger("Messaging.GatewayManager", TraceLogger.LoggerType.Runtime);
            lockable  = new object();
            gatewayRefreshCallInitiated = false;

            ListProvider = gatewayListProvider;

            var knownGateways = ListProvider.GetGateways().ToList();

            if (knownGateways.Count == 0)
            {
                string gatewayProviderType = gatewayListProvider.GetType().FullName;
                string err = String.Format("Could not find any gateway in {0}. Orleans client cannot initialize.", gatewayProviderType);
                logger.Error(ErrorCode.GatewayManager_NoGateways, err);
                throw new OrleansException(err);
            }

            logger.Info(ErrorCode.GatewayManager_FoundKnownGateways, "Found {0} knownGateways from Gateway listProvider {1}", knownGateways.Count, Utils.EnumerableToString(knownGateways));

            if (ListProvider is IGatewayListObservable)
            {
                ((IGatewayListObservable)ListProvider).SubscribeToGatewayNotificationEvents(this);
            }

            roundRobinCounter = cfg.PreferedGatewayIndex >= 0 ? cfg.PreferedGatewayIndex : rand.Next(knownGateways.Count);

            cachedLiveGateways = knownGateways;

            lastRefreshTime = DateTime.UtcNow;
            if (ListProvider.IsUpdatable)
            {
                gatewayRefreshTimer = new SafeTimer(RefreshSnapshotLiveGateways_TimerCallback, null, config.GatewayListRefreshPeriod, config.GatewayListRefreshPeriod);
            }
        }
        public async Task RunChecksOnGrainClass(string grainClass, bool may_update_in_all_clusters, int phases, ITestOutputHelper output)
        {
            var        random    = new SafeRandom();
            Func <int> GetRandom = () => random.Next();

            Func <Task> checker1 = () => Task.Run(() =>
            {
                int x             = GetRandom();
                var grainidentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
                // force creation of replicas
                for (int i = 0; i < numclusters; i++)
                {
                    Assert.Equal(0, Client[i].GetALocal(grainClass, x));
                }
                // write global on client 0
                Client[0].SetAGlobal(grainClass, x, Xyz);
                // read global on other clients
                for (int i = 1; i < numclusters; i++)
                {
                    int r = Client[i].GetAGlobal(grainClass, x);
                    Assert.Equal(Xyz, r);
                }
                // check local stability
                for (int i = 0; i < numclusters; i++)
                {
                    Assert.Equal(Xyz, Client[i].GetALocal(grainClass, x));
                }
                // check versions
                for (int i = 0; i < numclusters; i++)
                {
                    Assert.Equal(1, Client[i].GetConfirmedVersion(grainClass, x));
                }
            });

            Func <Task> checker2 = () => Task.Run(() =>
            {
                int x             = GetRandom();
                var grainidentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
                // increment on replica 0
                Client[0].IncrementAGlobal(grainClass, x);
                // expect on other replicas
                for (int i = 1; i < numclusters; i++)
                {
                    int r = Client[i].GetAGlobal(grainClass, x);
                    Assert.Equal(1, r);
                }
                // check versions
                for (int i = 0; i < numclusters; i++)
                {
                    Assert.Equal(1, Client[i].GetConfirmedVersion(grainClass, x));
                }
            });

            Func <Task> checker2b = () => Task.Run(() =>
            {
                int x             = GetRandom();
                var grainidentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
                // force first creation on replica 1
                Assert.Equal(0, Client[1].GetAGlobal(grainClass, x));
                // increment on replica 0
                Client[0].IncrementAGlobal(grainClass, x);
                // expect on other replicas
                for (int i = 1; i < numclusters; i++)
                {
                    int r = Client[i].GetAGlobal(grainClass, x);
                    Assert.Equal(1, r);
                }
                // check versions
                for (int i = 0; i < numclusters; i++)
                {
                    Assert.Equal(1, Client[i].GetConfirmedVersion(grainClass, x));
                }
            });

            Func <int, Task> checker3 = (int numupdates) => Task.Run(() =>
            {
                int x             = GetRandom();
                var grainidentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));

                // concurrently chaotically increment (numupdates) times
                Parallel.For(0, numupdates, i =>
                {
                    var target = may_update_in_all_clusters ? i % numclusters : 0;
                    Client[target].IncrementALocal(grainClass, x);
                });

                if (may_update_in_all_clusters)
                {
                    for (int i = 1; i < numclusters; i++)
                    {
                        Client[i].Synchronize(grainClass, x); // push all changes
                    }
                }

                // push & get all
                Assert.Equal(numupdates, Client[0].GetAGlobal(grainClass, x));

                for (int i = 1; i < numclusters; i++)
                {
                    Assert.Equal(numupdates, Client[i].GetAGlobal(grainClass, x)); // get all
                }
                // check versions
                for (int i = 0; i < numclusters; i++)
                {
                    Assert.Equal(numupdates, Client[i].GetConfirmedVersion(grainClass, x));
                }
            });

            Func <Task> checker4 = () => Task.Run(() =>
            {
                int x = GetRandom();
                var t = new List <Task>();
                for (int i = 0; i < numclusters; i++)
                {
                    int c = i;
                    t.Add(Task.Run(() => Assert.True(Client[c].GetALocal(grainClass, x) == 0)));
                }
                for (int i = 0; i < numclusters; i++)
                {
                    int c = i;
                    t.Add(Task.Run(() => Assert.True(Client[c].GetAGlobal(grainClass, x) == 0)));
                }
                return(Task.WhenAll(t));
            });

            Func <Task> checker5 = () => Task.Run(() =>
            {
                var x = GetRandom();
                Task.WaitAll(
                    Task.Run(() =>
                {
                    Client[0].AddReservationLocal(grainClass, x, 0);
                    Client[0].RemoveReservationLocal(grainClass, x, 0);
                    Client[0].Synchronize(grainClass, x);
                }),
                    Task.Run(() =>
                {
                    Client[1].AddReservationLocal(grainClass, x, 1);
                    Client[1].RemoveReservationLocal(grainClass, x, 1);
                    Client[1].AddReservationLocal(grainClass, x, 2);
                    Client[1].Synchronize(grainClass, x);
                })
                    );
                var result = Client[0].GetReservationsGlobal(grainClass, x);
                Assert.Single(result);
                Assert.Equal(2, result[0]);
            });

            Func <int, Task> checker6 = async(int preload) =>
            {
                var x = GetRandom();

                if (preload % 2 == 0)
                {
                    Client[1].GetAGlobal(grainClass, x);
                }
                if ((preload / 2) % 2 == 0)
                {
                    Client[0].GetAGlobal(grainClass, x);
                }

                bool[] done = new bool[numclusters - 1];

                var t = new List <Task>();

                // create listener tasks
                for (int i = 1; i < numclusters; i++)
                {
                    int c = i;
                    t.Add(Task.Run(async() =>
                    {
                        while (Client[c].GetALocal(grainClass, x) != 1)
                        {
                            await Task.Delay(100);
                        }
                        done[c - 1] = true;
                    }));
                }

                // send notification
                Client[0].SetALocal(grainClass, x, 1);

                await Task.WhenAny(
                    Task.Delay(20000),
                    Task.WhenAll(t)
                    );

                Assert.True(done.All(b => b), string.Format("checker6({0}): update did not propagate within 20 sec", preload));
            };

            Func <int, Task> checker7 = (int variation) => Task.Run(async() =>
            {
                int x = GetRandom();

                if (variation % 2 == 0)
                {
                    Client[1].GetAGlobal(grainClass, x);
                }
                if ((variation / 2) % 2 == 0)
                {
                    Client[0].GetAGlobal(grainClass, x);
                }

                var grainidentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));

                // write conditional on client 0, should always succeed
                {
                    var result = Client[0].SetAConditional(grainClass, x, Xyz);
                    Assert.Equal(0, result.Item1);
                    Assert.True(result.Item2);
                    Assert.Equal(1, Client[0].GetConfirmedVersion(grainClass, x));
                }

                if ((variation / 4) % 2 == 1)
                {
                    await Task.Delay(100);
                }

                // write conditional on Client[1], may or may not succeed based on timing
                {
                    var result = Client[1].SetAConditional(grainClass, x, 444);
                    if (result.Item1 == 0) // was stale, thus failed
                    {
                        Assert.False(result.Item2);
                        // must have updated as a result
                        Assert.Equal(1, Client[1].GetConfirmedVersion(grainClass, x));
                        // check stability
                        Assert.Equal(Xyz, Client[0].GetALocal(grainClass, x));
                        Assert.Equal(Xyz, Client[1].GetALocal(grainClass, x));
                        Assert.Equal(Xyz, Client[0].GetAGlobal(grainClass, x));
                        Assert.Equal(Xyz, Client[1].GetAGlobal(grainClass, x));
                    }
                    else // was up-to-date, thus succeeded
                    {
                        Assert.True(result.Item2);
                        Assert.Equal(1, result.Item1);
                        // version is now 2
                        Assert.Equal(2, Client[1].GetConfirmedVersion(grainClass, x));
                        // check stability
                        Assert.Equal(444, Client[1].GetALocal(grainClass, x));
                        Assert.Equal(444, Client[0].GetAGlobal(grainClass, x));
                        Assert.Equal(444, Client[1].GetAGlobal(grainClass, x));
                    }
                }
            });

            output.WriteLine("Running individual short tests");

            // first, run short ones in sequence
            await checker1();
            await checker2();
            await checker2b();
            await checker3(4);
            await checker3(20);
            await checker4();

            if (may_update_in_all_clusters)
            {
                await checker5();
            }

            await checker6(0);
            await checker6(1);
            await checker6(2);
            await checker6(3);

            if (may_update_in_all_clusters)
            {
                await checker7(0);
                await checker7(4);
                await checker7(7);

                // run tests under blocked notification to force race one way
                MultiCluster.SetProtocolMessageFilterForTesting(Cluster[0], msg => !(msg is INotificationMessage));
                await checker7(0);
                await checker7(1);
                await checker7(2);
                await checker7(3);

                MultiCluster.SetProtocolMessageFilterForTesting(Cluster[0], _ => true);
            }

            output.WriteLine("Running individual longer tests");

            // then, run slightly longer tests
            if (phases != 0)
            {
                await checker3(20);
                await checker3(phases);
            }

            output.WriteLine("Running many concurrent test instances");

            var tasks = new List <Task>();

            for (int i = 0; i < phases; i++)
            {
                tasks.Add(checker1());
                tasks.Add(checker2());
                tasks.Add(checker2b());
                tasks.Add(checker3(4));
                tasks.Add(checker4());

                if (may_update_in_all_clusters)
                {
                    tasks.Add(checker5());
                }

                tasks.Add(checker6(0));
                tasks.Add(checker6(1));
                tasks.Add(checker6(2));
                tasks.Add(checker6(3));

                if (may_update_in_all_clusters)
                {
                    tasks.Add(checker7(0));
                    tasks.Add(checker7(1));
                    tasks.Add(checker7(2));
                    tasks.Add(checker7(3));
                    tasks.Add(checker7(4));
                    tasks.Add(checker7(5));
                    tasks.Add(checker7(6));
                    tasks.Add(checker7(7));
                }
            }
            await Task.WhenAll(tasks);
        }
        public void RandomNotEqualTest()
        {
            SafeRandom rnd = new SafeRandom();
            for (int loop = 0; loop < 1000000; loop++)
            {
                byte[] a = new byte[rnd.Next(1, 100)];
                rnd.NextBytes(a);

                byte[] b = DeepCopy(a);

                b[rnd.Next(0, b.Length)]++; // Increment at a random index

                bool actual = ByteArrayEqualityComparer.AreEqual(a, b);
                Assert.IsFalse(actual);
            }
        }
Beispiel #23
0
        public GatewayManager(GatewayOptions gatewayOptions, IGatewayListProvider gatewayListProvider, ILoggerFactory loggerFactory)
        {
            this.gatewayOptions = gatewayOptions;
            knownDead           = new Dictionary <Uri, DateTime>();
            rand                        = new SafeRandom();
            logger                      = loggerFactory.CreateLogger <GatewayManager>();
            this.loggerFactory          = loggerFactory;
            lockable                    = new object();
            gatewayRefreshCallInitiated = false;

            ListProvider = gatewayListProvider;

            var knownGateways = ListProvider.GetGateways().GetResult();

            if (knownGateways.Count == 0)
            {
                string gatewayProviderType = gatewayListProvider.GetType().FullName;
                string err = String.Format("Could not find any gateway in {0}. Orleans client cannot initialize.", gatewayProviderType);
                logger.Error(ErrorCode.GatewayManager_NoGateways, err);
                throw new OrleansException(err);
            }

            logger.Info(ErrorCode.GatewayManager_FoundKnownGateways, "Found {0} knownGateways from Gateway listProvider {1}", knownGateways.Count, Utils.EnumerableToString(knownGateways));

            if (ListProvider is IGatewayListObservable)
            {
                ((IGatewayListObservable)ListProvider).SubscribeToGatewayNotificationEvents(this);
            }

            roundRobinCounter = this.gatewayOptions.PreferedGatewayIndex >= 0 ? this.gatewayOptions.PreferedGatewayIndex : rand.Next(knownGateways.Count);

            cachedLiveGateways = knownGateways;

            lastRefreshTime = DateTime.UtcNow;
            if (ListProvider.IsUpdatable)
            {
                gatewayRefreshTimer = new SafeTimer(this.loggerFactory.CreateLogger <SafeTimer>(), RefreshSnapshotLiveGateways_TimerCallback, null, this.gatewayOptions.GatewayListRefreshPeriod, this.gatewayOptions.GatewayListRefreshPeriod);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Handles initialization of the GameScreen. This will be invoked after the GameScreen has been
        /// completely and successfully added to the ScreenManager. It is highly recommended that you
        /// use this instead of the constructor. This is invoked only once.
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();

            topForm = new Form(GUIManager, new Vector2(5, 5), new Vector2(700, 550))
            {
                Text = "Primary form"
            };

            var tb = new TextBox(topForm, new Vector2(10, 10), new Vector2(150, 300));

            _textBox = new TextBox(topForm, new Vector2(350, 10), new Vector2(200, 200))
            {
                Font = GUIManager.Font, Text = "abcdef\nghi\r\njklj\n"
            };

            for (var i = 0; i < 150; i++)
            {
                var c = new Color((byte)rnd.Next(0, 256), (byte)rnd.Next(256), (byte)rnd.Next(256), 255);
                _textBox.Append(new StyledText(i + " ", c));
            }

            var styledTexts = new List <StyledText>
            {
                new StyledText("Black ", Color.Black),
                new StyledText("Red ", Color.Red),
                new StyledText("Green ", Color.Green),
                new StyledText("Yellow ", Color.Yellow),
                new StyledText("Voilet ", Color.Violet),
                new StyledText("Orange ", Color.Orange),
                new StyledText("Tomato ", Color.Tomato),
                new StyledText("DarkRed ", Color.DarkRed),
            };

            tb.Append(styledTexts);

            var form = new Form(topForm, new Vector2(50, 50), new Vector2(200, 200))
            {
                Text = "My form"
            };

            var b = new Button(form, new Vector2(20, 20), new Vector2(80, 30))
            {
                Text = "Press me"
            };

            b.Clicked += b_Clicked;

            new CheckBox(form, new Vector2(20, 200))
            {
                Text = "Checkbox"
            };

            var f2 = new Form(topForm, new Vector2(200, 250), new Vector2(275, 270))
            {
                Text = "My form 2"
            };
            var f3 = new Form(f2, Vector2.Zero, new Vector2(200, 200))
            {
                Text = "form 3"
            };
            var f4 = new Form(f3, Vector2.Zero, new Vector2(100, 100))
            {
                Text = "form 4"
            };

            var testLabelF4 = new Label(f4, Vector2.Zero)
            {
                Text = "Click me"
            };

            testLabelF4.Clicked += testLabelF4_Clicked;

            _dragLbl = new Label(topForm, topForm.Size - new Vector2(75, 30));

            topForm.BeginDrag += DragControl;
            topForm.EndDrag   += DragControl;
            form.BeginDrag    += DragControl;
            form.EndDrag      += DragControl;
            f2.BeginDrag      += DragControl;
            f2.EndDrag        += DragControl;
            f3.BeginDrag      += DragControl;
            f3.EndDrag        += DragControl;
            f4.BeginDrag      += DragControl;
            f4.EndDrag        += DragControl;

            // Set up the tooltips
            foreach (var c in GUIManager.GetAllControls())
            {
                if (c.GetType() == typeof(Button))
                {
                    c.Tooltip = Tooltip_Button;
                }
                else if (c.GetType() == typeof(Label))
                {
                    c.Tooltip += Tooltip_Label;
                }
            }

            // Paged list
            var items = new List <string>();

            for (var i = 0; i < 100; i++)
            {
                items.Add(i.ToString());
            }

            new ListBox <string>(topForm, new Vector2(500, 250), new Vector2(100, 100))
            {
                Items = items, ShowPaging = true, CanSelect = true
            };
        }
        public void RandomEqualTest()
        {
            SafeRandom rnd = new SafeRandom();
            for (int loop = 0; loop < 100000; loop++)
            {
                byte[] a = new byte[rnd.Next(1, 100)];
                rnd.NextBytes(a);

                byte[] b = DeepCopy(a);

                bool actual = ByteArrayEqualityComparer.AreEqual(a, b);
                Assert.IsTrue(actual);
            }
        }
Beispiel #26
0
        internal async Task RemindersRange(int iterations = 1000)
        {
            await Task.WhenAll(Enumerable.Range(1, iterations).Select(async i =>
            {
                GrainReference grainRef = MakeTestGrainReference();
                await remindersTable.UpsertRow(CreateReminder(grainRef, i.ToString()));
            }));

            var rows = await remindersTable.ReadRows(0, uint.MaxValue);

            Assert.AreEqual(rows.Reminders.Count, iterations);

            rows = await remindersTable.ReadRows(0, 0);

            Assert.AreEqual(rows.Reminders.Count, iterations);

            var remindersHashes = rows.Reminders.Select(r => r.GrainRef.GetUniformHashCode()).ToArray();

            SafeRandom random = new SafeRandom();

            await Task.WhenAll(Enumerable.Range(0, iterations).Select(i =>
                                                                      TestRemindersHashInterval(remindersTable, (uint)random.Next(), (uint)random.Next(),
                                                                                                remindersHashes)));
        }
Beispiel #27
0
 private string RandomKey()
 {
     return(keys[random.Next(keys.Length)]);
 }
Beispiel #28
0
 public static bool Success(float chance) => SafeRandom.Next(0, 101) <= chance;
Beispiel #29
0
        public async Task ActivationSched_WhenAny_Busy_Timeout()
        {
            TaskScheduler scheduler = masterScheduler.GetWorkItemGroup(context).TaskRunner;

            var        pause1  = new TaskCompletionSource <bool>();
            var        pause2  = new TaskCompletionSource <bool>();
            var        finish  = new TaskCompletionSource <bool>();
            Task <int> task1   = null;
            Task <int> task2   = null;
            Task       join    = null;
            Task       wrapper = new Task(() =>
            {
                task1 = Task <int> .Factory.StartNew(() =>
                {
                    output.WriteLine("Task-1 Started");
                    Assert.Equal(scheduler, TaskScheduler.Current);
                    int num1 = 1;
                    while (!pause1.Task.Result) // Infinite busy loop
                    {
                        num1 = random.Next();
                    }
                    output.WriteLine("Task-1 Done");
                    return(num1);
                });
                task2 = Task <int> .Factory.StartNew(() =>
                {
                    output.WriteLine("Task-2 Started");
                    Assert.Equal(scheduler, TaskScheduler.Current);
                    int num2 = 2;
                    while (!pause2.Task.Result) // Infinite busy loop
                    {
                        num2 = random.Next();
                    }
                    output.WriteLine("Task-2 Done");
                    return(num2);
                });

                join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2)));

                finish.SetResult(true);
            });

            wrapper.Start(scheduler);

            var timeoutLimit = TimeSpan.FromSeconds(1);

            try
            {
                await finish.Task.WithTimeout(timeoutLimit);
            }
            catch (TimeoutException)
            {
                Assert.True(false, "Result did not arrive before timeout " + timeoutLimit);
            }

            Assert.NotNull(join); // Joined promise assigned
            await join;

            Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status);
            Assert.False(task1.IsFaulted, "Task-1 Faulted " + task1.Exception);
            Assert.False(task1.IsCompleted, "Task-1 Status " + task1.Status);
            Assert.False(task2.IsFaulted, "Task-2 Faulted " + task2.Exception);
            Assert.False(task2.IsCompleted, "Task-2 Status " + task2.Status);
        }
Beispiel #30
0
        public static int MagicDmg(YiObj attacker, YiObj target)
        {
            float damage;

            var reborn = 1.00f;

            if (target.Reborn > 0)
            {
                reborn -= 0.30f; //30%
            }
            var dodge = 1.00f;

            dodge -= target.Dexterity / 100;

            if (attacker.CurrentSkill.Id == 1115 || attacker.CurrentSkill.Info.WeaponSubType != 0 && attacker.CurrentSkill.Info.WeaponSubType != 500)
            {
                damage = SafeRandom.Next(attacker.MinimumPhsyicalAttack, attacker.MaximumPhsyicalAttack);
                if (attacker.HasFlag(StatusEffect.SuperMan) && target is Player)
                {
                    damage *= 0.2f; //PvP Reduction!
                }
                if (attacker.CurrentSkill.Info.Power > 30000)
                {
                    damage *= (float)(attacker.CurrentSkill.Info.Power - 30000) / 100;
                }
                else
                {
                    damage += attacker.CurrentSkill.Info.Power;
                }

                damage -= target.Defense;
            }
            else if (attacker.CurrentSkill.Info.WeaponSubType == 500)
            {
                damage = SafeRandom.Next(attacker.MinimumPhsyicalAttack, attacker.MaximumPhsyicalAttack);
                if (attacker.HasFlag(StatusEffect.SuperMan) && target is Player)
                {
                    damage *= 0.2f; //PvP Reduction!
                }
                if (attacker.CurrentSkill.Info.Power > 30000)
                {
                    damage *= (float)(attacker.CurrentSkill.Info.Power - 30000) / 100;
                }
                else
                {
                    damage += attacker.CurrentSkill.Info.Power;
                }
            }
            else
            {
                damage = attacker.MagicAttack;
                if (attacker.CurrentSkill.Info.Power > 30000)
                {
                    damage *= (float)(attacker.CurrentSkill.Info.Power - 3000) / 100;
                }
                else
                {
                    damage += attacker.CurrentSkill.Info.Power;
                }

                damage *= (float)(100 - Math.Min(target.MagicDefense, 95)) / 100;
                damage -= target.MagicDefense; //target.MagicBlock;
                damage *= 0.65f;
            }

            damage *= reborn;

            if (damage < 1)
            {
                damage = 1;
            }

            return((int)Math.Round(damage, 0));
        }
        protected async Task RemindersRange(int iterations = 1000)
        {
            await Task.WhenAll(Enumerable.Range(1, iterations).Select(async i =>
            {
                GrainReference grainRef = MakeTestGrainReference();

                await RetryHelper.RetryOnExceptionAsync <Task>(10, RetryOperation.Sigmoid, async() =>
                {
                    await remindersTable.UpsertRow(CreateReminder(grainRef, i.ToString()));
                    return(Task.CompletedTask);
                });
            }));

            var rows = await remindersTable.ReadRows(0, uint.MaxValue);

            Assert.Equal(rows.Reminders.Count, iterations);

            rows = await remindersTable.ReadRows(0, 0);

            Assert.Equal(rows.Reminders.Count, iterations);

            var remindersHashes = rows.Reminders.Select(r => r.GrainRef.GetUniformHashCode()).ToArray();

            SafeRandom random = new SafeRandom();

            await Task.WhenAll(Enumerable.Range(0, iterations).Select(i =>
                                                                      TestRemindersHashInterval(remindersTable, (uint)random.Next(), (uint)random.Next(),
                                                                                                remindersHashes)));
        }
 public static long GetRandomGrainId()
 {
     return safeRandom.Next();
 }