Exemplo n.º 1
0
        /// <summary>
        /// Scans for activations that are due for collection.
        /// </summary>
        /// <returns>A list of activations that are due for collection.</returns>
        public List <ActivationData> ScanStale()
        {
            var now = DateTime.UtcNow;
            List <ActivationData>        result = null;
            IEnumerable <ActivationData> activations;

            while (DequeueQuantum(out activations, now))
            {
                // at this point, all tickets associated with activations are cancelled and any attempts to reschedule will fail silently. if the activation is to be reactivated, it's our job to clear the activation's copy of the ticket.
                foreach (var activation in activations)
                {
                    lock (activation)
                    {
                        activation.ResetCollectionTicket();
                        if (activation.State != ActivationState.Valid)
                        {
                            // Do nothing: don't collect, don't reschedule.
                            // The activation can't be in Created or Activating, since we only ScheduleCollection after successfull activation.
                            // If the activation is already in Deactivating or Invalid state, its already being collected or was collected
                            // (both mean a bug, this activation should not be in the collector)
                            // So in any state except for Valid we should just not collect and not reschedule.
                            logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_1,
                                        "ActivationCollector found an activation in a non Valid state. All activation inside the ActivationCollector should be in Valid state. Activation: {0}",
                                        activation.ToDetailedString());
                        }
                        else if (activation.ShouldBeKeptAlive)
                        {
                            // Consider: need to reschedule to what is the remaining time for ShouldBeKeptAlive, not the full CollectionAgeLimit.
                            ScheduleCollection(activation);
                        }
                        else if (!activation.IsInactive)
                        {
                            // This is essentialy a bug, an active activation should not be in the last bucket.
                            logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_2,
                                        "ActivationCollector found an active activation in it's last bucket. This is violation of ActivationCollector invariants. " +
                                        "For now going to defer it's collection. Activation: {0}",
                                        activation.ToDetailedString());
                            ScheduleCollection(activation);
                        }
                        else if (!activation.IsStale(now))
                        {
                            // This is essentialy a bug, a non stale activation should not be in the last bucket.
                            logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_3,
                                        "ActivationCollector found a non stale activation in it's last bucket. This is violation of ActivationCollector invariants. Now: {0}" +
                                        "For now going to defer it's collection. Activation: {1}",
                                        TraceLogger.PrintDate(now),
                                        activation.ToDetailedString());
                            ScheduleCollection(activation);
                        }
                        else
                        {
                            // Atomically set Deactivating state, to disallow any new requests or new timer ticks to be dispatched on this activation.
                            activation.PrepareForDeactivation();
                            DecideToCollectActivation(activation, ref result);
                        }
                    }
                }
            }
            return(result ?? nothing);
        }
Exemplo n.º 2
0
        public static bool CheckTimerDelay(DateTime previousTickTime, int totalNumTicks,
                                           TimeSpan dueTime, TimeSpan timerFrequency, TraceLogger logger, Func <string> getName, ErrorCode errorCode, bool freezeCheck)
        {
            TimeSpan timeSinceLastTick     = DateTime.UtcNow - previousTickTime;
            TimeSpan exceptedTimeToNexTick = totalNumTicks == 0 ? dueTime : timerFrequency;
            TimeSpan exceptedTimeWithSlack;

            if (exceptedTimeToNexTick >= TimeSpan.FromSeconds(6))
            {
                exceptedTimeWithSlack = exceptedTimeToNexTick + TimeSpan.FromSeconds(3);
            }
            else
            {
                exceptedTimeWithSlack = exceptedTimeToNexTick.Multiply(1.5);
            }
            if (timeSinceLastTick <= exceptedTimeWithSlack)
            {
                return(true);
            }

            // did not tick in the last period.
            var errMsg = String.Format("{0}{1} did not fire on time. Last fired at {2}, {3} since previous fire, should have fired after {4}.",
                                       freezeCheck ? "Watchdog Freeze Alert: " : "-", // 0
                                       getName == null ? "" : getName(),              // 1
                                       TraceLogger.PrintDate(previousTickTime),       // 2
                                       timeSinceLastTick,                             // 3
                                       exceptedTimeToNexTick);                        // 4

            if (freezeCheck)
            {
                logger.Error(errorCode, errMsg);
            }
            else
            {
                logger.Warn(errorCode, errMsg);
            }
            return(false);
        }
Exemplo n.º 3
0
        protected string FormatLogMessage_Impl(
            DateTime timestamp,
            Logger.Severity severity,
            TraceLogger.LoggerType loggerType,
            string caller,
            string message,
            IPEndPoint myIPEndPoint,
            Exception exception,
            int errorCode,
            bool includeStackTrace)
        {
            if (severity == Logger.Severity.Error)
            {
                message = "!!!!!!!!!! " + message;
            }

            string ip = myIPEndPoint == null ? String.Empty : myIPEndPoint.ToString();

            if (loggerType.Equals(TraceLogger.LoggerType.Grain))
            {
                // Grain identifies itself, so I don't want an additional long string in the prefix.
                // This is just a temporal solution to ease the dev. process, can remove later.
                ip = String.Empty;
            }
            string exc = includeStackTrace ? TraceLogger.PrintException(exception) : TraceLogger.PrintExceptionWithoutStackTrace(exception);
            string msg = String.Format("[{0} {1,5}\t{2}\t{3}\t{4}\t{5}]\t{6}\t{7}",
                                       TraceLogger.ShowDate ? TraceLogger.PrintDate(timestamp) : TraceLogger.PrintTime(timestamp), //0
                                       Thread.CurrentThread.ManagedThreadId,                                                       //1
                                       TraceLogger.SeverityTable[(int)severity],                                                   //2
                                       errorCode,                                                                                  //3
                                       caller,                                                                                     //4
                                       ip,                                                                                         //5
                                       message,                                                                                    //6
                                       exc);                                                                                       //7

            return(msg);
        }
Exemplo n.º 4
0
        internal Silo(string name, SiloType siloType, ClusterConfiguration config, ILocalDataStore keyStore)
        {
            SystemStatus.Current = SystemStatus.Creating;

            CurrentSilo = this;

            var startTime = DateTime.UtcNow;

            this.siloType = siloType;
            Name          = name;

            siloTerminatedEvent = new ManualResetEvent(false);

            OrleansConfig = config;
            globalConfig  = config.Globals;
            config.OnConfigChange("Defaults", () => nodeConfig = config.GetConfigurationForNode(name));

            if (!TraceLogger.IsInitialized)
            {
                TraceLogger.Initialize(nodeConfig);
            }

            config.OnConfigChange("Defaults/Tracing", () => TraceLogger.Initialize(nodeConfig, true), false);
            LimitManager.Initialize(nodeConfig);
            ActivationData.Init(config);
            StatisticsCollector.Initialize(nodeConfig);
            SerializationManager.Initialize(globalConfig.UseStandardSerializer);
            initTimeout = globalConfig.MaxJoinAttemptTime;
            if (Debugger.IsAttached)
            {
                initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), globalConfig.MaxJoinAttemptTime);
                stopTimeout = initTimeout;
            }

            IPEndPoint here       = nodeConfig.Endpoint;
            int        generation = nodeConfig.Generation;

            if (generation == 0)
            {
                generation            = SiloAddress.AllocateNewGeneration();
                nodeConfig.Generation = generation;
            }
            TraceLogger.MyIPEndPoint = here;
            logger = TraceLogger.GetLogger("Silo", TraceLogger.LoggerType.Runtime);
            logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing {0} silo on {1} at {2}, gen {3} --------------", siloType, nodeConfig.DNSHostName, here, generation);
            logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0} with runtime Version='{1}' Config= \n{2}", name, RuntimeVersion.Current, config.ToString(name));

            if (keyStore != null)
            {
                // Re-establish reference to shared local key store in this app domain
                LocalDataStoreInstance.LocalDataStore = keyStore;
            }
            healthCheckParticipants = new List <IHealthCheckParticipant>();

            BufferPool.InitGlobalBufferPool(globalConfig);
            PlacementStrategy.Initialize(globalConfig);

            UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnobservedExceptionHandler);
            AppDomain.CurrentDomain.UnhandledException +=
                (obj, ev) => DomainUnobservedExceptionHandler(obj, (Exception)ev.ExceptionObject);

            typeManager = new GrainTypeManager(here.Address.Equals(IPAddress.Loopback));

            // Performance metrics
            siloStatistics = new SiloStatisticsManager(globalConfig, nodeConfig);
            config.OnConfigChange("Defaults/LoadShedding", () => siloStatistics.MetricsTable.NodeConfig = nodeConfig, false);

            // The scheduler
            scheduler = new OrleansTaskScheduler(globalConfig, nodeConfig);
            healthCheckParticipants.Add(scheduler);

            // Initialize the message center
            var mc = new MessageCenter(here, generation, globalConfig, siloStatistics.MetricsTable);

            if (nodeConfig.IsGatewayNode)
            {
                mc.InstallGateway(nodeConfig.ProxyGatewayEndpoint);
            }

            messageCenter = mc;

            // Now the router/directory service
            // This has to come after the message center //; note that it then gets injected back into the message center.;
            localGrainDirectory = new LocalGrainDirectory(this);

            // Now the activation directory.
            // This needs to know which router to use so that it can keep the global directory in synch with the local one.
            activationDirectory = new ActivationDirectory();

            // Now the consistent ring provider
            RingProvider = GlobalConfig.UseVirtualBucketsConsistentRing ?
                           (IConsistentRingProvider) new VirtualBucketsRingProvider(SiloAddress, GlobalConfig.NumVirtualBucketsConsistentRing)
                : new ConsistentRingProvider(SiloAddress);

            Action <Dispatcher> setDispatcher;

            catalog = new Catalog(Constants.CatalogId, SiloAddress, Name, LocalGrainDirectory, typeManager, scheduler, activationDirectory, config, out setDispatcher);
            var dispatcher = new Dispatcher(scheduler, messageCenter, catalog, config);

            setDispatcher(dispatcher);

            RuntimeClient.Current = new InsideRuntimeClient(
                dispatcher,
                catalog,
                LocalGrainDirectory,
                SiloAddress,
                config,
                RingProvider,
                typeManager);
            messageCenter.RerouteHandler       = InsideRuntimeClient.Current.RerouteMessage;
            messageCenter.SniffIncomingMessage = InsideRuntimeClient.Current.SniffIncomingMessage;
            messageCenter.ClientDropHandler    = grainIds =>
            {
                catalog.DeleteGrainsLocal(grainIds).Ignore();
                scheduler.RunOrQueueAction(() =>
                {
                    // Consider: batch delete
                    foreach (var id in grainIds)
                    {
                        LocalGrainDirectory.DeleteGrain(id).Ignore();
                    }
                }, catalog.SchedulingContext);
            };

            siloStatistics.MetricsTable.Scheduler           = scheduler;
            siloStatistics.MetricsTable.ActivationDirectory = activationDirectory;
            siloStatistics.MetricsTable.ActivationCollector = catalog.ActivationCollector;
            siloStatistics.MetricsTable.MessageCenter       = messageCenter;

            DeploymentLoadPublisher.CreateDeploymentLoadPublisher(this, globalConfig);
            PlacementDirectorsManager.CreatePlacementDirectorsManager(globalConfig);

            // Now the incoming message agents
            incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, dispatcher);
            incomingPingAgent   = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, dispatcher);
            incomingAgent       = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, dispatcher);

            membershipFactory = new MembershipFactory();
            reminderFactory   = new LocalReminderServiceFactory();

            SystemStatus.Current = SystemStatus.Created;

            StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME,
                                              () => TraceLogger.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs.

            TestHookup = new TestHookups(this);

            logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
        }
Exemplo n.º 5
0
        internal Silo(string name, SiloType siloType, ClusterConfiguration config, ILocalDataStore keyStore)
        {
            SystemStatus.Current = SystemStatus.Creating;

            CurrentSilo = this;

            var startTime = DateTime.UtcNow;

            this.siloType = siloType;
            Name          = name;

            siloTerminatedEvent = new ManualResetEvent(false);

            OrleansConfig = config;
            globalConfig  = config.Globals;
            config.OnConfigChange("Defaults", () => nodeConfig = config.GetConfigurationForNode(name));

            if (!TraceLogger.IsInitialized)
            {
                TraceLogger.Initialize(nodeConfig);
            }

            config.OnConfigChange("Defaults/Tracing", () => TraceLogger.Initialize(nodeConfig, true), false);

            ActivationData.Init(config, nodeConfig);
            StatisticsCollector.Initialize(nodeConfig);
            SerializationManager.Initialize(globalConfig.UseStandardSerializer);
            initTimeout = globalConfig.MaxJoinAttemptTime;
            if (Debugger.IsAttached)
            {
                initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), globalConfig.MaxJoinAttemptTime);
                stopTimeout = initTimeout;
            }

            IPEndPoint here       = nodeConfig.Endpoint;
            int        generation = nodeConfig.Generation;

            if (generation == 0)
            {
                generation            = SiloAddress.AllocateNewGeneration();
                nodeConfig.Generation = generation;
            }
            TraceLogger.MyIPEndPoint = here;
            logger = TraceLogger.GetLogger("Silo", TraceLogger.LoggerType.Runtime);

            logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode));
            if (!GCSettings.IsServerGC || !GCSettings.LatencyMode.Equals(GCLatencyMode.Batch))
            {
                logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on or with GCLatencyMode.Batch enabled - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\"> and <configuration>-<runtime>-<gcConcurrent enabled=\"false\"/>");
            }

            logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing {0} silo on host {1} MachineName {2} at {3}, gen {4} --------------",
                        siloType, nodeConfig.DNSHostName, Environment.MachineName, here, generation);
            logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0} with runtime Version='{1}' .NET version='{2}' Is .NET 4.5={3} OS version='{4}' Config= " + Environment.NewLine + "{5}",
                        name, RuntimeVersion.Current, Environment.Version, ConfigUtilities.IsNet45OrNewer(), Environment.OSVersion, config.ToString(name));

            if (keyStore != null)
            {
                // Re-establish reference to shared local key store in this app domain
                LocalDataStoreInstance.LocalDataStore = keyStore;
            }
            healthCheckParticipants = new List <IHealthCheckParticipant>();
            allSiloProviders        = new List <IProvider>();

            BufferPool.InitGlobalBufferPool(globalConfig);
            PlacementStrategy.Initialize(globalConfig);

            UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnobservedExceptionHandler);
            AppDomain.CurrentDomain.UnhandledException +=
                (obj, ev) => DomainUnobservedExceptionHandler(obj, (Exception)ev.ExceptionObject);

            grainFactory = new GrainFactory();
            typeManager  = new GrainTypeManager(here.Address.Equals(IPAddress.Loopback), grainFactory);

            // Performance metrics
            siloStatistics = new SiloStatisticsManager(globalConfig, nodeConfig);
            config.OnConfigChange("Defaults/LoadShedding", () => siloStatistics.MetricsTable.NodeConfig = nodeConfig, false);

            // The scheduler
            scheduler = new OrleansTaskScheduler(globalConfig, nodeConfig);
            healthCheckParticipants.Add(scheduler);

            // Initialize the message center
            var mc = new MessageCenter(here, generation, globalConfig, siloStatistics.MetricsTable);

            if (nodeConfig.IsGatewayNode)
            {
                mc.InstallGateway(nodeConfig.ProxyGatewayEndpoint);
            }

            messageCenter = mc;

            SiloIdentity = SiloAddress.ToLongString();

            // GrainRuntime can be created only here, after messageCenter was created.
            grainRuntime = new GrainRuntime(
                globalConfig.ServiceId,
                SiloIdentity,
                grainFactory,
                new TimerRegistry(),
                new ReminderRegistry(),
                new StreamProviderManager());


            // Now the router/directory service
            // This has to come after the message center //; note that it then gets injected back into the message center.;
            localGrainDirectory = new LocalGrainDirectory(this);

            // Now the activation directory.
            // This needs to know which router to use so that it can keep the global directory in synch with the local one.
            activationDirectory = new ActivationDirectory();

            // Now the consistent ring provider
            RingProvider = GlobalConfig.UseVirtualBucketsConsistentRing ?
                           (IConsistentRingProvider) new VirtualBucketsRingProvider(SiloAddress, GlobalConfig.NumVirtualBucketsConsistentRing)
                : new ConsistentRingProvider(SiloAddress);

            Action <Dispatcher> setDispatcher;

            catalog = new Catalog(Constants.CatalogId, SiloAddress, Name, LocalGrainDirectory, typeManager, scheduler, activationDirectory, config, grainRuntime, out setDispatcher);
            var dispatcher = new Dispatcher(scheduler, messageCenter, catalog, config);

            setDispatcher(dispatcher);

            RuntimeClient.Current = new InsideRuntimeClient(
                dispatcher,
                catalog,
                LocalGrainDirectory,
                SiloAddress,
                config,
                RingProvider,
                typeManager,
                grainFactory);
            messageCenter.RerouteHandler       = InsideRuntimeClient.Current.RerouteMessage;
            messageCenter.SniffIncomingMessage = InsideRuntimeClient.Current.SniffIncomingMessage;

            siloStatistics.MetricsTable.Scheduler           = scheduler;
            siloStatistics.MetricsTable.ActivationDirectory = activationDirectory;
            siloStatistics.MetricsTable.ActivationCollector = catalog.ActivationCollector;
            siloStatistics.MetricsTable.MessageCenter       = messageCenter;

            DeploymentLoadPublisher.CreateDeploymentLoadPublisher(this, globalConfig);
            PlacementDirectorsManager.CreatePlacementDirectorsManager(globalConfig);

            // Now the incoming message agents
            incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, dispatcher);
            incomingPingAgent   = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, dispatcher);
            incomingAgent       = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, dispatcher);

            membershipFactory = new MembershipFactory();
            reminderFactory   = new LocalReminderServiceFactory();

            SystemStatus.Current = SystemStatus.Created;

            StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME,
                                              () => TraceLogger.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs.

            TestHookup = new TestHookups(this);

            logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
        }