internal VirtualBucketsRingProvider(SiloAddress siloAddress, ILoggerFactory loggerFactory, int numVirtualBuckets)
        {
            numBucketsPerSilo = numVirtualBuckets;

            if (numBucketsPerSilo <= 0)
            {
                throw new IndexOutOfRangeException("numBucketsPerSilo is out of the range. numBucketsPerSilo = " + numBucketsPerSilo);
            }

            logger = loggerFactory.CreateLogger <VirtualBucketsRingProvider>();

            statusListeners   = new List <IRingRangeListener>();
            bucketsMap        = new SortedDictionary <uint, SiloAddress>();
            sortedBucketsList = new List <Tuple <uint, SiloAddress> >();
            myAddress         = siloAddress;
            lockable          = new object();
            running           = true;
            myRange           = RangeFactory.CreateFullRange();

            logger.Info("Starting {0} on silo {1}.", typeof(VirtualBucketsRingProvider).Name, siloAddress.ToStringWithHashCode());

            StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RING, ToString);
            IntValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RINGSIZE, () => GetRingSize());
            StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGDISTANCE, () => String.Format("x{0,8:X8}", ((IRingRangeInternal)myRange).RangeSize()));
            FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGPERCENTAGE, () => (float)((IRingRangeInternal)myRange).RangePercentage());
            FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_AVERAGERINGPERCENTAGE, () =>
            {
                int size = GetRingSize();
                return(size == 0 ? 0 : ((float)100.0 / (float)size));
            });

            // add myself to the list of members
            AddServer(myAddress);
        }
        public override void Update(ICoordinateCalculator <double> xCoordCalc, ICoordinateCalculator <double> yCoordCalc)
        {
            base.Update(xCoordCalc, yCoordCalc);

            if (Y1.CompareTo(Y2) > 0)
            {
                MeasureText.VerticalAnchorPoint = VerticalAnchorPoint.Top;
                MeasureText.Margin = new Thickness(0, 5, 0, 0);
            }
            else
            {
                MeasureText.VerticalAnchorPoint = VerticalAnchorPoint.Bottom;
                MeasureText.Margin = new Thickness(0, -5, 0, 0);
            }

            var rangeX = X1.CompareTo(X2) > 0 ? RangeFactory.NewRange(X2, X1) : RangeFactory.NewRange(X1, X2);
            var rangeY = Y1.CompareTo(Y2) > 0 ? RangeFactory.NewRange(Y2, Y1) : RangeFactory.NewRange(Y1, Y2);

            string xText;

            if (xCoordCalc is ICategoryCoordinateCalculator <DateTime> )
            {
                var categoryCalc = (ICategoryCoordinateCalculator <DateTime>)xCoordCalc;
                var indexRange   = (IntegerRange)rangeX;
                var difference   = categoryCalc.TransformIndexToData(indexRange.Max) - categoryCalc.TransformIndexToData(indexRange.Min);
                xText = string.Format("{0:dd} days", difference);
            }
            else
            {
                xText = rangeX.Diff.ToString();
            }


            MeasureText.Text = string.Format("{0:#.##}\n{1}", rangeY.Diff, xText);
        }
示例#3
0
        /// <summary>
        /// Calculates the difference between adjoining elements along the specified axes.
        /// </summary>
        /// <param name="axis">The axis to operate along.</param>
        /// <param name="source">The NdArray containing the source values.</param>
        /// <returns>The differences NdArray. It has one element less in dimension <paramref name="axis"/> as the source NdArray.</returns>
        public static NdArray <T> DiffAxis(int axis, NdArray <T> source)
        {
            NdArray <T> .CheckAxis(axis, source);

            var shiftRanges = new List <IRange>();
            var cutRanges   = new List <IRange>();

            for (var index = 0; index < source.NumDimensions; index++)
            {
                if (index == axis)
                {
                    shiftRanges.Add(RangeFactory.Range(1, SpecialIdx.None));
                    cutRanges.Add(RangeFactory.Range(SpecialIdx.None, source.Shape[index] - 2));
                }
                else
                {
                    shiftRanges.Add(RangeFactory.All);
                    cutRanges.Add(RangeFactory.All);
                }
            }

            var shiftArray = source[shiftRanges.ToArray()];
            var cutArray   = source[cutRanges.ToArray()];

            return(shiftArray - cutArray);
        }
        public Task <ReminderTableData> ReadRows(uint begin, uint end)
        {
            var range = RangeFactory.CreateRange(begin, end);

            var list = reminderTable.Where(e => range.InRange(e.Key)).SelectMany(e => e.Value.Values).ToList();

            if (logger.IsEnabled(LogLevel.Trace))
            {
                logger.LogTrace(
                    "Selected {SelectCount} out of {TotalCount} reminders from memory for {Range}. Selected: {Reminders}",
                    list.Count,
                    reminderTable.Values.Sum(r => r.Count),
                    range.ToString(),
                    Utils.EnumerableToString(list, e => e.ToString()));
            }

            var result = new ReminderTableData(list);

            if (logger.IsEnabled(LogLevel.Debug))
            {
                logger.LogDebug("Read {ReminderCount} reminders from memory: {Reminders}", result.Reminders.Count, Utils.EnumerableToString(result.Reminders));
            }

            return(Task.FromResult(result));
        }
示例#5
0
            public ReminderTableData ReadRows(uint begin, uint end)
            {
                var range = RangeFactory.CreateRange(begin, end);
                IEnumerable <GrainReference> keys = reminderTable.Keys.Where(range.InRange);

                // is there a sleaker way of doing this in C#?
                var list = new List <ReminderEntry>();

                foreach (GrainReference k in keys)
                {
                    list.AddRange(reminderTable[k].Values);
                }

                if (logger.IsEnabled(LogLevel.Trace))
                {
                    logger.LogTrace(
                        "Selected {SelectCount} out of {TotalCount} reminders from memory for {Range}. Selected: {Reminders}",
                        list.Count,
                        reminderTable.Count,
                        range.ToString(),
                        Utils.EnumerableToString(list, e => e.ToString()));
                }

                return(new ReminderTableData(list));
            }
示例#6
0
        /// <summary>
        /// Attempt to retrieve reminders from the global reminder table
        /// </summary>
        private async Task ReadAndUpdateReminders()
        {
            // try to retrieve reminder from all my subranges
            myRange = ring.GetMyRange();
            if (logger.IsVerbose2)
            {
                logger.Verbose2("My range= {0}", myRange);
            }
            var acks = new List <Task>();

            foreach (SingleRange range in RangeFactory.GetSubRanges(myRange))
            {
                if (logger.IsVerbose2)
                {
                    logger.Verbose2("Reading rows for range {0}", range);
                }
                acks.Add(ReadTableAndStartTimers(range));
            }
            await Task.WhenAll(acks);

            if (logger.IsVerbose3)
            {
                PrintReminders();
            }
        }
示例#7
0
        public void DoRangeTest()
        {
            Range <string> stringRange = RangeFactory.CreateRange(null, "cdf");
            string         actual      = stringRange.ToString();

            Assert.AreEqual("{ NULL : cdf }", actual);
            Assert.IsTrue(stringRange.Contains("abc"));
            Assert.IsFalse(stringRange.Contains("xyz"));

            stringRange = RangeFactory.CreateRange("xyz", "abc");
            actual      = stringRange.ToString();
            Assert.AreEqual("{ abc : xyz }", actual);
            Assert.IsTrue(stringRange.Contains("abc"));
            Assert.IsTrue(stringRange.Contains("cfdes"));
            Assert.IsTrue(stringRange.Contains("xyz"));
            Assert.IsFalse(stringRange.Contains("aa"));
            Assert.IsFalse(stringRange.Contains("zz"));

            ValueRange <int> intRange = RangeFactory.CreateValueRange <int>(1, null);

            actual = intRange.ToString();
            Assert.AreEqual("{ 1 : NULL }", actual);
            Assert.IsTrue(intRange.Contains(2));
            Assert.IsTrue(intRange.Contains(int.MaxValue));
            Assert.IsFalse(intRange.Contains(int.MinValue));
        }
示例#8
0
        /// <summary>
        /// Attempt to retrieve reminders from the global reminder table
        /// </summary>
        private async Task ReadAndUpdateReminders()
        {
            if (StoppedCancellationTokenSource.IsCancellationRequested)
            {
                return;
            }

            RemoveOutOfRangeReminders();

            // try to retrieve reminders from all my subranges
            var rangeSerialNumberCopy = RangeSerialNumber;

            if (Logger.IsVerbose2)
            {
                Logger.Verbose2($"My range= {RingRange}, RangeSerialNumber {RangeSerialNumber}. Local reminders count {localReminders.Count}");
            }
            var acks = new List <Task>();

            foreach (SingleRange range in RangeFactory.GetSubRanges(RingRange))
            {
                acks.Add(ReadTableAndStartTimers(range, rangeSerialNumberCopy));
            }
            await Task.WhenAll(acks);

            if (Logger.IsVerbose3)
            {
                PrintReminders();
            }
        }
        public void CheckElementRange_TooBigIndex_ThrowException()
        {
            // arrange
            var shape  = new int[] { 1, 2, 3, 4, 5 };
            var layout = new Layout(shape, 0, Layout.CStride(shape));

            // action
            Layout.CheckElementRange(false, 10, 100, new[] { RangeFactory.Elem(0) }, layout.Shape);
        }
示例#10
0
        public void Elem_ReturnElem()
        {
            // arrange & action
            var rng = RangeFactory.Elem(100) as Elem;

            // assert
            Assert.IsInstanceOfType(rng, typeof(Elem));
            Assert.AreEqual(100, rng.Pos);
        }
示例#11
0
        /// <summary>
        /// Concatenates NdArrays along an axis.
        /// </summary>
        /// <param name="axis">The concatenation axis.</param>
        /// <param name="sources">Sequence of NdArrays to concatenate.</param>
        /// <returns>The concatenated NdArray.</returns>
        public static NdArray <T> Concat(int axis, NdArray <T>[] sources)
        {
            if (sources.Length == 0)
            {
                throw new ArgumentException("Cannot concatenate empty sequence of NdArray.", "sources");
            }

            var shape = sources[0].Shape.Select(s => s).ToArray();

            if (!(axis >= 0 && axis < shape.Length))
            {
                var errorMessage = string.Format("Concatenation axis {0} is out of range for shape {1}.", axis, ErrorMessage.ShapeToString(shape));
                throw new ArgumentOutOfRangeException("axis", errorMessage);
            }

            var arrayIndex = 0;

            foreach (var source in sources)
            {
                if (!Enumerable.SequenceEqual(List.Without(axis, source.Shape), List.Without(axis, shape)))
                {
                    var errorMessage = string.Format("Concatentation element with index {0} with shape{1} must be equal to shape {2} of the first element, except in the concatenation axis {3}", arrayIndex, ErrorMessage.ShapeToString(source.Shape), ErrorMessage.ShapeToString(shape), axis);
                    throw new ArgumentException(errorMessage, "sources");
                }

                arrayIndex++;
            }

            var totalSize   = sources.Sum(i => i.Shape[axis]);
            var concatShape = List.Set(axis, totalSize, shape);

            var result   = new NdArray <T>(concatShape, sources[0].Storage.Device);
            var position = 0;

            foreach (var source in sources)
            {
                var arrayLength = source.Shape[axis];
                if (arrayLength > 0)
                {
                    var range = Enumerable.Range(0, shape.Length).Select(idx =>
                    {
                        if (idx == axis)
                        {
                            return(RangeFactory.Range(position, position + arrayLength - 1));
                        }

                        return(RangeFactory.All);
                    });
                    result[range.ToArray()] = source;
                    position += arrayLength;
                }
            }

            return(result);
        }
示例#12
0
        public void Range_ReturnRange()
        {
            // arrange & action
            var rng = RangeFactory.Range(10, 30, 2) as Range;

            // assert
            Assert.IsInstanceOfType(rng, typeof(Range));
            Assert.AreEqual(10, rng.Start);
            Assert.AreEqual(30, rng.Stop);
            Assert.AreEqual(2, rng.Step);
        }
示例#13
0
        public void Parse_RangeArgs_ReturnSameRanges()
        {
            // arrange
            var args = new IRange[] { RangeFactory.Elem(9) };

            // action
            var ranges = RangeArgParser.Parse(args);

            // assert
            Assert.AreSame(args[0], ranges[0]);
        }
示例#14
0
        public void RangeArgsToString_TwoRangesWithStep()
        {
            // arrange
            var objects = new[] { RangeFactory.Range(0, 4, 2), RangeFactory.Range(0, 3) };

            // action
            var message = ErrorMessage.RangeArgsToString(objects);

            // assert
            Assert.AreEqual("[0:4:2, 0:3]", message);
        }
示例#15
0
        public void RangeArgsToString_RangeDefault()
        {
            // arrange
            var objects = new[] { RangeFactory.Range(0, 2) };

            // action
            var message = ErrorMessage.RangeArgsToString(objects);

            // assert
            Assert.AreEqual("[0:2]", message);
        }
示例#16
0
        public void RangeArgsToString_Elem()
        {
            // arrange
            var objects = new[] { RangeFactory.Elem(8) };

            // action
            var message = ErrorMessage.RangeArgsToString(objects);

            // assert
            Assert.AreEqual("[8]", message);
        }
示例#17
0
        private bool SetVisibleRange(IAxis axis, IComparable min, IComparable max)
        {
            if (CheckVisibleRange(min, max))
            {
                axis.VisibleRange = RangeFactory.NewWithMinMax(axis.VisibleRange, min, max);

                return(true);
            }

            return(false);
        }
        public void ConsistentRingProvider_Test3()
        {
            int    NUM_SILOS  = 100;
            double NUM_QUEUES = 10024.0;
            int    NUM_AGENTS = 4;

            Random      random = new Random();
            SiloAddress silo1  = SiloAddressUtils.NewLocalSiloAddress(random.Next(100000));
            VirtualBucketsRingProvider ring = new VirtualBucketsRingProvider(silo1, NullLoggerFactory.Instance, 50);

            //ring.logger.SetSeverityLevel(Severity.Warning);

            for (int i = 1; i <= NUM_SILOS - 1; i++)
            {
                ring.SiloStatusChangeNotification(SiloAddressUtils.NewLocalSiloAddress(random.Next(100000)), SiloStatus.Active);
            }

            IDictionary <SiloAddress, IRingRangeInternal>   siloRanges       = ring.GetRanges();
            List <Tuple <SiloAddress, IRingRangeInternal> > sortedSiloRanges =
                siloRanges.Select(kv => new Tuple <SiloAddress, IRingRangeInternal>(kv.Key, kv.Value)).ToList();

            sortedSiloRanges.Sort((t1, t2) => t1.Item2.RangePercentage().CompareTo(t2.Item2.RangePercentage()));

            Dictionary <SiloAddress, List <IRingRangeInternal> > allAgentRanges = new Dictionary <SiloAddress, List <IRingRangeInternal> >();

            foreach (var siloRange in siloRanges)
            {
                var multiRange = RangeFactory.CreateEquallyDividedMultiRange(siloRange.Value, NUM_AGENTS);
                List <IRingRangeInternal> agentRanges = new List <IRingRangeInternal>();
                for (int i = 0; i < NUM_AGENTS; i++)
                {
                    IRingRangeInternal agentRange = (IRingRangeInternal)multiRange.GetSubRange(i);
                    agentRanges.Add(agentRange);
                }
                allAgentRanges.Add(siloRange.Key, agentRanges);
            }

            Dictionary <SiloAddress, List <int> > queueHistogram = GetQueueHistogram(allAgentRanges, (int)NUM_QUEUES);
            string str = Utils.EnumerableToString(sortedSiloRanges,
                                                  tuple => String.Format("Silo {0} -> Range {1:0.000}%, {2} queues: {3}",
                                                                         tuple.Item1,
                                                                         tuple.Item2.RangePercentage(),
                                                                         queueHistogram[tuple.Item1].Sum(),
                                                                         Utils.EnumerableToString(queueHistogram[tuple.Item1])), "\n");

            output.WriteLine("\n\n*** The whole ring with {0} silos is:\n{1}\n\n", NUM_SILOS, str);

            output.WriteLine("Total number of queues is: {0}", queueHistogram.Values.Select(list => list.Sum()).Sum());
            output.WriteLine("Expected average range per silo is: {0:0.00}%, expected #queues per silo is: {1:0.00}, expected #queues per agent is: {2:0.000}.",
                             100.0 / NUM_SILOS, NUM_QUEUES / NUM_SILOS, NUM_QUEUES / (NUM_SILOS * NUM_AGENTS));
            output.WriteLine("Min #queues per silo is: {0}, Max #queues per silo is: {1}.",
                             queueHistogram.Values.Select(list => list.Sum()).ToList().Min(), queueHistogram.Values.Select(list => list.Sum()).ToList().Max());
        }
示例#19
0
        public ConsistentRingProvider(SiloAddress siloAddr)
        {
            log = TraceLogger.GetLogger(typeof(ConsistentRingProvider).Name);
            membershipRingList = new List <SiloAddress>();
            MyAddress          = siloAddr;
            myKey = MyAddress.GetConsistentHashCode();

            // add myself to the list of members
            AddServer(MyAddress);
            MyRange         = RangeFactory.CreateFullRange(); // i am responsible for the whole range
            statusListeners = new List <IRingRangeListener>();

            Start();
        }
示例#20
0
        public UnitMonitor()
        {
            this.allyTeam      = EntityManager9.Owner.Team;
            this.damageFactory = new DamageFactory();
            this.rangeFactory  = new RangeFactory();

            Entity.NetworkPropertyChanged   += this.OnNetworkPropertyChanged;
            Entity.AnimationChanged         += this.OnAnimationChanged;
            ModifierManager.ModifierAdded   += this.OnModifierAdded;
            ModifierManager.ModifierRemoved += this.OnModifierRemoved;
            GameManager.GameEvent           += this.OnGameEvent;
            OrderManager.OrderAdding        += this.OnOrderAdding;

            UpdateManager.CreateUpdate(OnUpdate);
        }
        public void ConsistentRingProvider_Test2()
        {
            SiloAddress silo1 = SiloAddressUtils.NewLocalSiloAddress(0);
            VirtualBucketsRingProvider ring = new VirtualBucketsRingProvider(silo1, NullLoggerFactory.Instance, 30);

            //ring.logger.SetSeverityLevel(Severity.Warning);
            output.WriteLine("\n\n*** Silo1 range: {0}.\n*** The whole ring with 1 silo is:\n{1}\n\n", ring.GetMyRange(), ring.ToString());

            for (int i = 1; i <= 10; i++)
            {
                ring.SiloStatusChangeNotification(SiloAddressUtils.NewLocalSiloAddress(i), SiloStatus.Active);
                var range = RangeFactory.CreateEquallyDividedMultiRange(ring.GetMyRange(), 5);
                output.WriteLine("\n\n*** Silo1 range: {0}. \n*** The whole ring with {1} silos is:\n{2}\n\n", range.ToCompactString(), i + 1, ring.ToString());
            }
        }
示例#22
0
        internal void AddServer(SiloAddress silo)
        {
            lock (membershipRingList)
            {
                if (membershipRingList.Contains(silo))
                {
                    return;                                    // we already have this silo
                }
                int myOldIndex = membershipRingList.FindIndex(elem => elem.Equals(MyAddress));

                if (!(membershipRingList.Count == 0 || myOldIndex != -1))
                {
                    throw new OrleansException(string.Format("{0}: Couldn't find my position in the ring {1}.", MyAddress, Utils.EnumerableToString(membershipRingList)));
                }


                // insert new silo in the sorted order
                int hash = silo.GetConsistentHashCode();

                // Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former.
                // Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then
                // 'index' will get 0, as needed.
                int index = membershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
                membershipRingList.Insert(index, silo);

                // relating to triggering handler ... new node took over some of my responsibility
                if (index == myOldIndex ||                                      // new node was inserted in my place
                    (myOldIndex == 0 && index == membershipRingList.Count - 1)) // I am the first node, and the new server is the last node
                {
                    IRingRange oldRange = MyRange;
                    try
                    {
                        MyRange = RangeFactory.CreateRange(unchecked ((uint)hash), unchecked ((uint)myKey));
                    }
                    catch (OverflowException exc)
                    {
                        log.Error(ErrorCode.ConsistentRingProviderBase + 5,
                                  String.Format("OverflowException: hash as int= x{0, 8:X8}, hash as uint= x{1, 8:X8}, myKey as int x{2, 8:X8}, myKey as uint x{3, 8:X8}.",
                                                hash, (uint)hash, myKey, (uint)myKey), exc);
                    }
                    NotifyLocalRangeSubscribers(oldRange, MyRange, false);
                }

                log.Info("Added Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString());
            }
        }
示例#23
0
        public void RangeChangeNotification(IRingRange old, IRingRange now, bool increased)
        {
            myRange = CalcMyRange();

            var        oldMultiRange = RangeFactory.CreateEquallyDividedMultiRange(old, numSubRanges);
            IRingRange oldSubRange   = oldMultiRange.GetSubRange(mySubRangeIndex);
            var        newMultiRange = RangeFactory.CreateEquallyDividedMultiRange(now, numSubRanges);
            IRingRange newSubRange   = newMultiRange.GetSubRange(mySubRangeIndex);

            if (oldSubRange.Equals(newSubRange))
            {
                return;
            }

            // For now, always say your range increased and the listeners need to deal with the situation when they get the same range again anyway.
            // In the future, check sub range inclusion. Note that it is NOT correct to just return the passed increased argument.
            // It will be wrong: the multi range may have decreased, while some individual sub range may partialy increase (shift).

            logger.Info("-NotifyLocal GrainRangeSubscribers about old {0} and new {1} increased? {2}.", oldSubRange.ToString(), newSubRange.ToString(), increased);

            List <IAsyncRingRangeListener> copy;

            lock (grainStatusListeners)
            {
                copy = grainStatusListeners.ToList();
            }
            foreach (IAsyncRingRangeListener listener in copy)
            {
                try
                {
                    Task task = listener.RangeChangeNotification(oldSubRange, newSubRange);
                    // We don't want to await it here since it will delay delivering notifications to other listeners.
                    // We only want to log an error if it happends, so use ContinueWith.
                    task.LogException(logger, ErrorCode.CRP_ForGrains_Local_Subscriber_Exception_1,
                                      String.Format("Local IGrainRingRangeListener {0} has thrown an asynchronous exception when was notified about RangeChangeNotification about old {1} new {2}.",
                                                    listener.GetType().FullName, oldSubRange, newSubRange))
                    .Ignore();
                }
                catch (Exception exc)
                {
                    logger.Error(ErrorCode.CRP_ForGrains_Local_Subscriber_Exception_2,
                                 String.Format("Local IGrainRingRangeListener {0} has thrown an exception when was notified about RangeChangeNotification about old {1} new {2}.",
                                               listener.GetType().FullName, oldSubRange, newSubRange), exc);
                }
            }
        }
        private static IRingRange CalculateRange(List <Tuple <uint, SiloAddress> > list, SiloAddress silo)
        {
            var ranges = new List <IRingRange>();

            for (int i = 0; i < list.Count; i++)
            {
                var curr = list[i];
                var next = list[(i + 1) % list.Count];
                // 'backward/clockwise' definition to assign responsibilities on the ring.
                if (next.Item2.Equals(silo))
                {
                    IRingRange range = RangeFactory.CreateRange(curr.Item1, next.Item1);
                    ranges.Add(range);
                }
            }
            return(RangeFactory.CreateRange(ranges));
        }
示例#25
0
        internal void RemoveServer(SiloAddress silo)
        {
            lock (membershipRingList)
            {
                int indexOfFailedSilo = membershipRingList.FindIndex(elem => elem.Equals(silo));
                if (indexOfFailedSilo < 0)
                {
                    return;                        // we have already removed this silo
                }
                membershipRingList.Remove(silo);

                // related to triggering handler
                int myNewIndex = membershipRingList.FindIndex(elem => elem.Equals(MyAddress));

                if (myNewIndex == -1)
                {
                    throw new OrleansException(string.Format("{0}: Couldn't find my position in the ring {1}.", MyAddress, this.ToString()));
                }

                bool wasMyPred = ((myNewIndex == indexOfFailedSilo) || (myNewIndex == 0 && indexOfFailedSilo == membershipRingList.Count)); // no need for '- 1'
                if (wasMyPred)                                                                                                              // failed node was our predecessor
                {
                    if (log.IsVerbose)
                    {
                        log.Verbose("Failed server was my pred? {0}, updated view {1}", wasMyPred, this.ToString());
                    }

                    IRingRange oldRange = MyRange;
                    if (membershipRingList.Count == 1) // i'm the only one left
                    {
                        MyRange = RangeFactory.CreateFullRange();
                        NotifyLocalRangeSubscribers(oldRange, MyRange, true);
                    }
                    else
                    {
                        int myNewPredIndex     = myNewIndex == 0 ? membershipRingList.Count - 1 : myNewIndex - 1;
                        int myPredecessorsHash = membershipRingList[myNewPredIndex].GetConsistentHashCode();

                        MyRange = RangeFactory.CreateRange(unchecked ((uint)myPredecessorsHash), unchecked ((uint)myKey));
                        NotifyLocalRangeSubscribers(oldRange, MyRange, true);
                    }
                }
                log.Info("Removed Server {0} hash {1}. Current view {2}", silo, silo.GetConsistentHashCode(), this.ToString());
            }
        }
示例#26
0
        public UnitMonitor()
        {
            this.allyTeam      = EntityManager9.Owner.Team;
            this.damageFactory = new DamageFactory();
            this.rangeFactory  = new RangeFactory();

            Entity.OnInt32PropertyChange  += this.OnInt32PropertyChange;
            Entity.OnAnimationChanged     += this.OnAnimationChanged;
            Unit.OnModifierAdded          += this.OnModifierAdded;
            Unit.OnModifierRemoved        += this.OnModifierRemoved;
            Entity.OnHandlePropertyChange += this.OnHandlePropertyChange;
            Game.OnFireEvent             += this.OnFireEvent;
            Entity.OnBoolPropertyChange  += OnBoolPropertyChange;
            Player.OnExecuteOrder        += OnExecuteOrder;
            Entity.OnInt64PropertyChange += OnInt64PropertyChange;

            Drawing.OnDraw += OnUpdateDraw;
            UpdateManager.Subscribe(OnUpdate);
        }
示例#27
0
        public async Task <ReminderTableData> ReadRows(uint begin, uint end)
        {
            try
            {
                var entries = await remTableManager.FindReminderEntries(begin, end);

                ReminderTableData data = ConvertFromTableEntryList(entries);
                if (logger.IsEnabled(LogLevel.Trace))
                {
                    logger.Trace("Read in {0} Table=" + Environment.NewLine + "{1}", RangeFactory.CreateRange(begin, end), data);
                }
                return(data);
            }
            catch (Exception exc)
            {
                logger.Warn((int)AzureUtils.Utilities.ErrorCode.AzureTable_40,
                            $"Intermediate error reading reminders in range {RangeFactory.CreateRange(begin, end)} for table {remTableManager.TableName}.", exc);
                throw;
            }
        }
示例#28
0
        public async Task <ReminderTableData> ReadRows(uint begin, uint end)
        {
            try
            {
                var entries = await remTableManager.FindReminderEntries(begin, end);

                ReminderTableData data = ConvertFromTableEntryList(entries);
                if (logger.IsVerbose2)
                {
                    logger.Verbose2("Read in {0} Table=" + Environment.NewLine + "{1}", RangeFactory.CreateRange(begin, end), data);
                }
                return(data);
            }
            catch (Exception exc)
            {
                logger.Warn(ErrorCode.AzureTable_40, String.Format("Intermediate error reading reminders in range {0} for table {1}.",
                                                                   RangeFactory.CreateRange(begin, end), remTableManager.TableName), exc);
                throw;
            }
        }
示例#29
0
        /// <summary>
        /// Return all rows that have their GrainReference's.GetUniformHashCode() in the range (start, end]
        /// </summary>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ReminderTableData ReadRows(uint begin, uint end)
        {
            var range = RangeFactory.CreateRange(begin, end);
            IEnumerable <GrainReference> keys = reminderTable.Keys.Where(range.InRange);

            // is there a sleaker way of doing this in C#?
            var list = new List <ReminderEntry>();

            foreach (GrainReference k in keys)
            {
                list.AddRange(reminderTable[k].Values);
            }

            if (logger.IsVerbose3)
            {
                logger.Verbose3("Selected {0} out of {1} reminders from memory for {2}. List is: {3}{4}", list.Count, reminderTable.Count, range.ToString(),
                                Environment.NewLine, Utils.EnumerableToString(list, e => e.ToString()));
            }

            return(new ReminderTableData(list));
        }
示例#30
0
        public override string ToString()
        {
            lock (membershipRingList)
            {
                if (membershipRingList.Count == 1)
                {
                    return(Utils.EnumerableToString(membershipRingList, silo => String.Format("{0} -> {1}", silo.ToStringWithHashCode(), RangeFactory.CreateFullRange())));
                }

                var sb = new StringBuilder("[");
                for (int i = 0; i < membershipRingList.Count; i++)
                {
                    SiloAddress curr  = membershipRingList[i];
                    SiloAddress next  = membershipRingList[(i + 1) % membershipRingList.Count];
                    IRingRange  range = RangeFactory.CreateRange(unchecked ((uint)curr.GetConsistentHashCode()), unchecked ((uint)next.GetConsistentHashCode()));
                    sb.Append(String.Format("{0} -> {1},  ", curr.ToStringWithHashCode(), range));
                }
                sb.Append("]");
                return(sb.ToString());
            }
        }