public MembershipEntry ToEntry()
 {
     return(new MembershipEntry
     {
         FaultZone = FaultZone,
         HostName = HostName,
         IAmAliveTime = LogFormatter.ParseDate(IAmAliveTime),
         ProxyPort = ProxyPort,
         RoleName = RoleName,
         SiloAddress = SiloAddressClass.FromParsableString(SiloAddress),
         SiloName = SiloName,
         Status = (SiloStatus)Status,
         StartTime = LogFormatter.ParseDate(StartTime),
         SuspectTimes = SuspectTimes.Select(x => x.ToTuple()).ToList(),
         UpdateZone = UpdateZone
     });
 }
Exemplo n.º 2
0
        private async Task <KeyValuePair <SiloAddress, GrainInterfaceMap> > GetTargetSiloGrainInterfaceMap(SiloAddress siloAddress)
        {
            try
            {
                var remoteTypeManager = this.grainFactory.GetSystemTarget <ISiloTypeManager>(Constants.TypeManagerId, siloAddress);
                var siloTypeCodeMap   = await scheduler.QueueTask(() => remoteTypeManager.GetSiloTypeCodeMap(), this);

                return(new KeyValuePair <SiloAddress, GrainInterfaceMap>(siloAddress, siloTypeCodeMap));
            }
            catch (Exception ex)
            {
                // Will be retried on the next timer hit
                logger.Error(ErrorCode.TypeManager_GetSiloGrainInterfaceMapError, $"Exception when trying to get GrainInterfaceMap for silos {siloAddress}", ex);
                hasToRefreshClusterGrainInterfaceMap = true;
                return(new KeyValuePair <SiloAddress, GrainInterfaceMap>(siloAddress, null));
            }
        }
Exemplo n.º 3
0
        public static ActivationAddress NewActivationAddress(SiloAddress silo, GrainId grain)
        {
            var activation = ActivationId.NewId();

            return(GetAddress(silo, grain, activation));
        }
Exemplo n.º 4
0
 private ActivationAddress(SiloAddress silo, GrainId grain, ActivationId activation)
 {
     Silo       = silo;
     Grain      = grain;
     Activation = activation;
 }
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);
            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= " + Environment.NewLine + "{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;

            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.º 6
0
        public Uri ToGatewayUri()
        {
            var siloAddress = SiloAddressClass.FromParsableString(SiloAddress);

            return(SiloAddressClass.New(new IPEndPoint(siloAddress.Endpoint.Address, ProxyPort), siloAddress.Generation).ToGatewayUri());
        }
Exemplo n.º 7
0
        /// <summary>
        /// Called from generated code.
        /// </summary>
        protected Task <T> InvokeMethodAsync <T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
        {
            object[] argsDeepCopy = null;
            if (arguments != null)
            {
                CheckForGrainArguments(arguments);
                SetGrainCancellationTokensTarget(arguments, this);
                argsDeepCopy = (object[])this.RuntimeClient.SerializationManager.DeepCopy(arguments);
            }

            var request = new InvokeMethodRequest(this.InterfaceId, this.InterfaceVersion, methodId, argsDeepCopy);

            if (IsUnordered)
            {
                options |= InvokeMethodOptions.Unordered;
            }

            Task <object> resultTask = InvokeMethod_Impl(request, null, options);

            if (resultTask == null)
            {
                if (typeof(T) == typeof(object))
                {
                    // optimize for most common case when using one way calls.
                    return(PublicOrleansTaskExtensions.CompletedTask as Task <T>);
                }

                return(Task.FromResult(default(T)));
            }

            resultTask = OrleansTaskExtentions.ConvertTaskViaTcs(resultTask);
            return(resultTask.Unbox <T>());
        }
Exemplo n.º 8
0
 /// <summary>Constructs a reference to the grain with the specified ID.</summary>
 /// <param name="grainId">The ID of the grain to refer to.</param>
 /// <param name="runtimeClient">The runtime client</param>
 /// <param name="genericArguments">Type arguments in case of a generic grain.</param>
 /// <param name="systemTargetSilo">Target silo in case of a system target reference.</param>
 internal static GrainReference FromGrainId(GrainId grainId, IRuntimeClient runtimeClient, string genericArguments = null, SiloAddress systemTargetSilo = null)
 {
     return(new GrainReference(grainId, genericArguments, systemTargetSilo, null, runtimeClient));
 }
Exemplo n.º 9
0
 internal SystemTarget(GrainId grainId, SiloAddress silo)
     : this(grainId, silo, false)
 {
 }
Exemplo n.º 10
0
 /// <summary>
 /// Called from generated code.
 /// </summary>
 protected Task <T> InvokeMethodAsync <T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
 {
     return(this.Runtime.InvokeMethodAsync <T>(this, methodId, arguments, options | invokeMethodOptions, silo));
 }
Exemplo n.º 11
0
 /// <summary>
 /// Called from generated code.
 /// </summary>
 protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
 {
     this.Runtime.InvokeOneWayMethod(this, methodId, arguments, options | invokeMethodOptions, silo);
 }
Exemplo n.º 12
0
        /// <inheritdoc />
        public void InvokeOneWayMethod(GrainReference reference, int methodId, object[] arguments, InvokeMethodOptions options, SiloAddress silo)
        {
            Task <object> resultTask = InvokeMethodAsync <object>(reference, methodId, arguments, options | InvokeMethodOptions.OneWay, silo);

            if (!resultTask.IsCompleted && resultTask.Result != null)
            {
                throw new OrleansException("Unexpected return value: one way InvokeMethod is expected to return null.");
            }
        }
Exemplo n.º 13
0
 public ClusterMember(SiloAddress siloAddress, SiloStatus status)
 {
     this.SiloAddress = siloAddress ?? throw new ArgumentNullException(nameof(siloAddress));
     this.Status      = status;
 }
Exemplo n.º 14
0
        /// <inheritdoc />
        public Task <T> InvokeMethodAsync <T>(GrainReference reference, int methodId, object[] arguments, InvokeMethodOptions options, SiloAddress silo)
        {
            if (arguments != null)
            {
                CheckForGrainArguments(arguments);
                SetGrainCancellationTokensTarget(arguments, reference);
                this.serializationManager.DeepCopyElementsInPlace(arguments);
            }

            var request = new InvokeMethodRequest(reference.InterfaceId, reference.InterfaceVersion, methodId, arguments);

            if (IsUnordered(reference))
            {
                options |= InvokeMethodOptions.Unordered;
            }

            Task <object> resultTask = InvokeMethod_Impl(reference, request, options);

            if (resultTask == null)
            {
                if (typeof(T) == typeof(object))
                {
                    // optimize for most common case when using one way calls.
                    return(OrleansTaskExtentions.CompletedTask as Task <T>);
                }

                return(Task.FromResult(default(T)));
            }
#if !NETCOREAPP
            resultTask = OrleansTaskExtentions.ConvertTaskViaTcs(resultTask);
#endif
            return(resultTask.ToTypedTask <T>());
        }
Exemplo n.º 15
0
        /// <summary>
        /// Called from generated code.
        /// </summary>
        protected async Task <T> InvokeMethodAsync <T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
        {
            CheckForGrainArguments(arguments);

            var argsDeepCopy = (object[])SerializationManager.DeepCopy(arguments);
            var request      = new InvokeMethodRequest(this.InterfaceId, methodId, argsDeepCopy);

            if (IsUnordered)
            {
                options |= InvokeMethodOptions.Unordered;
            }

            Task <object> resultTask = InvokeMethod_Impl(request, null, options);

            if (resultTask == null)
            {
                return(default(T));
            }

            resultTask = OrleansTaskExtentions.ConvertTaskViaTcs(resultTask);
            return((T)await resultTask);
        }
Exemplo n.º 16
0
 public Task <ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(SiloAddress silo)
 {
     return(Task.FromResult(implicitStreamSubscriberTable));
 }
Exemplo n.º 17
0
 /// <inheritdoc />
 TGrainInterface IInternalGrainFactory.GetSystemTarget <TGrainInterface>(GrainType grainType, SiloAddress destination)
 {
     return(this.grainFactory.GetSystemTarget <TGrainInterface>(grainType, destination));
 }
Exemplo n.º 18
0
 internal static void OnPingReceive(SiloAddress destination)
 {
     FindCounter(perSiloPingReceiveCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_RECEIVED_PER_SILO, destination.ToString()), CounterStorage.LogOnly).Increment();
 }
Exemplo n.º 19
0
        /// <summary>
        /// Called from generated code.
        /// </summary>
        protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
        {
            Task <object> resultTask = InvokeMethodAsync <object>(methodId, arguments, options | InvokeMethodOptions.OneWay);

            if (!resultTask.IsCompleted && resultTask.Result != null)
            {
                throw new OrleansException("Unexpected return value: one way InvokeMethod is expected to return null.");
            }
        }
Exemplo n.º 20
0
 internal static void OnPingReplyMissed(SiloAddress replier)
 {
     FindCounter(perSiloPingReplyMissedCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_REPLYMISSED_PER_SILO, replier.ToString()), CounterStorage.LogOnly).Increment();
 }
Exemplo n.º 21
0
        private void SendRequestMessage(
            GrainReference target,
            Message message,
            TaskCompletionSource <object> context,
            Action <Message, TaskCompletionSource <object> > callback,
            string debugContext,
            InvokeMethodOptions options,
            string genericArguments = null)
        {
            // fill in sender
            if (message.SendingSilo == null)
            {
                message.SendingSilo = MySilo;
            }
            if (!String.IsNullOrEmpty(genericArguments))
            {
                message.GenericGrainType = genericArguments;
            }

            SchedulingContext schedulingContext = RuntimeContext.Current != null ?
                                                  RuntimeContext.Current.ActivationContext as SchedulingContext : null;

            ActivationData sendingActivation = null;

            if (schedulingContext == null)
            {
                throw new InvalidOperationException(
                          String.Format("Trying to send a message {0} on a silo not from within grain and not from within system target (RuntimeContext is not set to SchedulingContext) "
                                        + "RuntimeContext.Current={1} TaskScheduler.Current={2}",
                                        message,
                                        RuntimeContext.Current == null ? "null" : RuntimeContext.Current.ToString(),
                                        TaskScheduler.Current));
            }
            switch (schedulingContext.ContextType)
            {
            case SchedulingContextType.SystemThread:
                throw new ArgumentException(
                          String.Format("Trying to send a message {0} on a silo not from within grain and not from within system target (RuntimeContext is of SchedulingContextType.SystemThread type)", message), "context");

            case SchedulingContextType.Activation:
                message.SendingActivation = schedulingContext.Activation.ActivationId;
                message.SendingGrain      = schedulingContext.Activation.Grain;
                sendingActivation         = schedulingContext.Activation;
                break;

            case SchedulingContextType.SystemTarget:
                message.SendingActivation = schedulingContext.SystemTarget.ActivationId;
                message.SendingGrain      = ((ISystemTargetBase)schedulingContext.SystemTarget).GrainId;
                break;
            }

            // fill in destination
            var targetGrainId = target.GrainId;

            message.TargetGrain = targetGrainId;
            if (targetGrainId.IsSystemTarget)
            {
                SiloAddress targetSilo = (target.SystemTargetSilo ?? MySilo);
                message.TargetSilo       = targetSilo;
                message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, targetSilo);
                message.Category         = targetGrainId.Equals(Constants.MembershipOracleId) ?
                                           Message.Categories.Ping : Message.Categories.System;
            }
            if (target.IsObserverReference)
            {
                message.TargetObserverId = target.ObserverId;
            }

            if (debugContext != null)
            {
                message.DebugContext = debugContext;
            }

            var oneWay = (options & InvokeMethodOptions.OneWay) != 0;

            if (context == null && !oneWay)
            {
                logger.Warn(ErrorCode.IGC_SendRequest_NullContext, "Null context {0}: {1}", message, Utils.GetStackTrace());
            }

            if (message.IsExpirableMessage(Config.Globals))
            {
                message.TimeToLive = ResponseTimeout;
            }

            if (!oneWay)
            {
                var callbackData = new CallbackData(
                    callback,
                    tryResendMessage,
                    context,
                    message,
                    unregisterCallback,
                    Config.Globals,
                    this.callbackDataLogger,
                    this.timerLogger);
                callbacks.TryAdd(message.Id, callbackData);
                callbackData.StartTimer(ResponseTimeout);
            }

            if (targetGrainId.IsSystemTarget)
            {
                // Messages to system targets bypass the task system and get sent "in-line"
                this.Dispatcher.TransportMessage(message);
            }
            else
            {
                this.Dispatcher.SendMessage(message, sendingActivation);
            }
        }
Exemplo n.º 22
0
 public SiloStatus GetSiloStatus(SiloAddress siloAddress)
 {
     return(Silo.CurrentSilo.LocalSiloStatusOracle.GetApproximateSiloStatus(siloAddress));
 }
Exemplo n.º 23
0
        public Silo(ILocalSiloDetails siloDetails, IServiceProvider services)
        {
            string name = siloDetails.Name;

            // Temporarily still require this. Hopefuly gone when 2.0 is released.
            this.siloDetails       = siloDetails;
            this.SystemStatus      = SystemStatus.Creating;
            AsynchAgent.IsStarting = true; // todo. use ISiloLifecycle instead?

            var startTime = DateTime.UtcNow;

            IOptions <ClusterMembershipOptions> clusterMembershipOptions = services.GetRequiredService <IOptions <ClusterMembershipOptions> >();

            initTimeout = clusterMembershipOptions.Value.MaxJoinAttemptTime;
            if (Debugger.IsAttached)
            {
                initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), clusterMembershipOptions.Value.MaxJoinAttemptTime);
                stopTimeout = initTimeout;
            }

            var localEndpoint = this.siloDetails.SiloAddress.Endpoint;

            services.GetService <SerializationManager>().RegisterSerializers(services.GetService <IApplicationPartManager>());

            this.Services = services;
            this.Services.InitializeSiloUnobservedExceptionsHandler();
            //set PropagateActivityId flag from node config
            IOptions <SiloMessagingOptions> messagingOptions = services.GetRequiredService <IOptions <SiloMessagingOptions> >();

            RequestContext.PropagateActivityId = messagingOptions.Value.PropagateActivityId;
            this.loggerFactory = this.Services.GetRequiredService <ILoggerFactory>();
            logger             = this.loggerFactory.CreateLogger <Silo>();

            logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode));
            if (!GCSettings.IsServerGC)
            {
                logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\">");
                logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines).");
            }

            logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing silo on host {0} MachineName {1} at {2}, gen {3} --------------",
                        this.siloDetails.DnsHostName, Environment.MachineName, localEndpoint, this.siloDetails.SiloAddress.Generation);
            logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0}", name);

            var siloMessagingOptions = this.Services.GetRequiredService <IOptions <SiloMessagingOptions> >();

            BufferPool.InitGlobalBufferPool(siloMessagingOptions.Value);

            try
            {
                grainFactory = Services.GetRequiredService <GrainFactory>();
            }
            catch (InvalidOperationException exc)
            {
                logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc);
                throw;
            }

            // Performance metrics
            siloStatistics = Services.GetRequiredService <SiloStatisticsManager>();

            // The scheduler
            scheduler = Services.GetRequiredService <OrleansTaskScheduler>();
            healthCheckParticipants.Add(scheduler);

            runtimeClient = Services.GetRequiredService <InsideRuntimeClient>();

            // Initialize the message center
            messageCenter = Services.GetRequiredService <MessageCenter>();
            var dispatcher = this.Services.GetRequiredService <Dispatcher>();

            messageCenter.RerouteHandler       = dispatcher.RerouteMessage;
            messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage;

            // 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 = Services.GetRequiredService <LocalGrainDirectory>();

            // Now the activation directory.
            activationDirectory = Services.GetRequiredService <ActivationDirectory>();

            // Now the consistent ring provider
            RingProvider = Services.GetRequiredService <IConsistentRingProvider>();

            catalog = Services.GetRequiredService <Catalog>();

            executorService = Services.GetRequiredService <ExecutorService>();

            // Now the incoming message agents
            var messageFactory = this.Services.GetRequiredService <MessageFactory>();

            incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory);
            incomingPingAgent   = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory);
            incomingAgent       = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory);

            membershipOracle    = Services.GetRequiredService <IMembershipOracle>();
            this.clusterOptions = Services.GetRequiredService <IOptions <ClusterOptions> >().Value;
            var multiClusterOptions = Services.GetRequiredService <IOptions <MultiClusterOptions> >().Value;

            if (!multiClusterOptions.HasMultiClusterNetwork)
            {
                logger.Info("Skip multicluster oracle creation (no multicluster network configured)");
            }
            else
            {
                multiClusterOracle = Services.GetRequiredService <IMultiClusterOracle>();
            }

            this.SystemStatus      = SystemStatus.Created;
            AsynchAgent.IsStarting = false;

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

            this.siloLifecycle = this.Services.GetRequiredService <ISiloLifecycleSubject>();
            // register all lifecycle participants
            IEnumerable <ILifecycleParticipant <ISiloLifecycle> > lifecycleParticipants = this.Services.GetServices <ILifecycleParticipant <ISiloLifecycle> >();

            foreach (ILifecycleParticipant <ISiloLifecycle> participant in lifecycleParticipants)
            {
                participant?.Participate(this.siloLifecycle);
            }
            // register all named lifecycle participants
            IKeyedServiceCollection <string, ILifecycleParticipant <ISiloLifecycle> > namedLifecycleParticipantCollection = this.Services.GetService <IKeyedServiceCollection <string, ILifecycleParticipant <ISiloLifecycle> > >();

            foreach (ILifecycleParticipant <ISiloLifecycle> participant in namedLifecycleParticipantCollection
                     ?.GetServices(this.Services)
                     ?.Select(s => s.GetService(this.Services)))
            {
                participant?.Participate(this.siloLifecycle);
            }

            // add self to lifecycle
            this.Participate(this.siloLifecycle);

            logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
        }
Exemplo n.º 24
0
        public Silo(ILocalSiloDetails siloDetails, IServiceProvider services)
        {
            string name = siloDetails.Name;

            // Temporarily still require this. Hopefuly gone when 2.0 is released.
            this.siloDetails  = siloDetails;
            this.SystemStatus = SystemStatus.Creating;

            var startTime = DateTime.UtcNow;

            IOptions <ClusterMembershipOptions> clusterMembershipOptions = services.GetRequiredService <IOptions <ClusterMembershipOptions> >();

            initTimeout = clusterMembershipOptions.Value.MaxJoinAttemptTime;
            if (Debugger.IsAttached)
            {
                initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), clusterMembershipOptions.Value.MaxJoinAttemptTime);
                stopTimeout = initTimeout;
            }

            var localEndpoint = this.siloDetails.SiloAddress.Endpoint;

            this.Services = services;

            //set PropagateActivityId flag from node config
            IOptions <SiloMessagingOptions> messagingOptions = services.GetRequiredService <IOptions <SiloMessagingOptions> >();

            RequestContext.PropagateActivityId       = messagingOptions.Value.PropagateActivityId;
            this.waitForMessageToBeQueuedForOutbound = messagingOptions.Value.WaitForMessageToBeQueuedForOutboundTime;

            this.loggerFactory = this.Services.GetRequiredService <ILoggerFactory>();
            logger             = this.loggerFactory.CreateLogger <Silo>();

            logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode));
            if (!GCSettings.IsServerGC)
            {
                logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\">");
                logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines).");
            }

            if (logger.IsEnabled(LogLevel.Debug))
            {
                var highestLogLevel = logger.IsEnabled(LogLevel.Trace) ? nameof(LogLevel.Trace) : nameof(LogLevel.Debug);
                logger.LogWarning(
                    new EventId((int)ErrorCode.SiloGcWarning),
                    $"A verbose logging level ({highestLogLevel}) is configured. This will impact performance. The recommended log level is {nameof(LogLevel.Information)}.");
            }

            logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing silo on host {0} MachineName {1} at {2}, gen {3} --------------",
                        this.siloDetails.DnsHostName, Environment.MachineName, localEndpoint, this.siloDetails.SiloAddress.Generation);
            logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0}", name);

            try
            {
                grainFactory = Services.GetRequiredService <GrainFactory>();
            }
            catch (InvalidOperationException exc)
            {
                logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc);
                throw;
            }

            // Performance metrics
            siloStatistics = Services.GetRequiredService <SiloStatisticsManager>();

            runtimeClient = Services.GetRequiredService <InsideRuntimeClient>();

            // Initialize the message center
            messageCenter = Services.GetRequiredService <MessageCenter>();
            messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage;

            // 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 = Services.GetRequiredService <LocalGrainDirectory>();

            // Now the consistent ring provider
            RingProvider = Services.GetRequiredService <IConsistentRingProvider>();

            catalog = Services.GetRequiredService <Catalog>();

            siloStatusOracle       = Services.GetRequiredService <ISiloStatusOracle>();
            this.membershipService = Services.GetRequiredService <IMembershipService>();

            this.SystemStatus = SystemStatus.Created;

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

            this.siloLifecycle = this.Services.GetRequiredService <ISiloLifecycleSubject>();
            // register all lifecycle participants
            IEnumerable <ILifecycleParticipant <ISiloLifecycle> > lifecycleParticipants = this.Services.GetServices <ILifecycleParticipant <ISiloLifecycle> >();

            foreach (ILifecycleParticipant <ISiloLifecycle> participant in lifecycleParticipants)
            {
                participant?.Participate(this.siloLifecycle);
            }
            // register all named lifecycle participants
            IKeyedServiceCollection <string, ILifecycleParticipant <ISiloLifecycle> > namedLifecycleParticipantCollection = this.Services.GetService <IKeyedServiceCollection <string, ILifecycleParticipant <ISiloLifecycle> > >();

            foreach (ILifecycleParticipant <ISiloLifecycle> participant in namedLifecycleParticipantCollection
                     ?.GetServices(this.Services)
                     ?.Select(s => s.GetService(this.Services)))
            {
                participant?.Participate(this.siloLifecycle);
            }

            // add self to lifecycle
            this.Participate(this.siloLifecycle);

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