public OutsideRuntimeClient(ClientConfiguration cfg, bool secondary = false)
        {
            this.clientId = GrainId.NewClientId();

            if (cfg == null)
            {
                Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object.");
                throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg");
            }

            this.config = cfg;

            if (!TraceLogger.IsInitialized)
            {
                TraceLogger.Initialize(config);
            }
            StatisticsCollector.Initialize(config);
            SerializationManager.Initialize(config.UseStandardSerializer);
            logger    = TraceLogger.GetLogger("OutsideRuntimeClient", TraceLogger.LoggerType.Runtime);
            appLogger = TraceLogger.GetLogger("Application", TraceLogger.LoggerType.Application);

            try
            {
                LoadAdditionalAssemblies();

                PlacementStrategy.Initialize();

                callbacks           = new ConcurrentDictionary <CorrelationId, CallbackData>();
                localObjects        = new ConcurrentDictionary <GuidId, LocalObjectData>();
                CallbackData.Config = config;

                if (!secondary)
                {
                    UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException);
                }
                // Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked
                SerializationManager.GetDeserializer(typeof(String));
                // Ensure that any assemblies that get loaded in the future get recorded
                AppDomain.CurrentDomain.AssemblyLoad += NewAssemblyHandler;

                // Load serialization info for currently-loaded assemblies
                foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    if (!assembly.ReflectionOnly)
                    {
                        SerializationManager.FindSerializationInfo(assembly);
                    }
                }

                statisticsProviderManager = new StatisticsProviderManager("Statistics", ClientProviderRuntime.Instance);
                var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations)
                                        .WaitForResultWithThrow(initTimeout);
                if (statsProviderName != null)
                {
                    config.StatisticsProviderName = statsProviderName;
                }

                responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout;
                BufferPool.InitGlobalBufferPool(config);
                var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface);

                // Client init / sign-on message
                logger.Info(ErrorCode.ClientInitializing, string.Format(
                                "{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}",
                                BARS, config.DNSHostName, localAddress, clientId));
                string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}'", BARS, RuntimeVersion.Current);
                startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config);
                logger.Info(ErrorCode.ClientStarting, startMsg);

                if (TestOnlyThrowExceptionDuringInit)
                {
                    throw new ApplicationException("TestOnlyThrowExceptionDuringInit");
                }

                config.CheckGatewayProviderSettings();

                var generation          = -SiloAddress.AllocateNewGeneration(); // Client generations are negative
                var gatewayListProvider = GatewayProviderFactory.CreateGatewayListProvider(config)
                                          .WithTimeout(initTimeout).Result;
                transport = new ProxiedMessageCenter(config, localAddress, generation, clientId, gatewayListProvider);

                if (StatisticsCollector.CollectThreadTimeTrackingStats)
                {
                    incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver");
                }
            }
            catch (Exception exc)
            {
                if (logger != null)
                {
                    logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc);
                }
                ConstructorReset();
                throw;
            }
        }
Example #2
0
        public OutsideRuntimeClient(ClientConfiguration cfg, bool secondary = false)
        {
            if (cfg == null)
            {
                Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object.");
                throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg");
            }

            var services = new ServiceCollection();

            services.AddSingleton(cfg);
            services.AddSingleton <TypeMetadataCache>();
            services.AddSingleton <AssemblyProcessor>();
            services.AddSingleton(this);
            services.AddSingleton <IRuntimeClient>(this);
            services.AddSingleton <GrainFactory>();
            services.AddFromExisting <IGrainFactory, GrainFactory>();
            services.AddFromExisting <IInternalGrainFactory, GrainFactory>();
            services.AddFromExisting <IGrainReferenceConverter, GrainFactory>();
            services.AddSingleton <ClientProviderRuntime>();
            services.AddFromExisting <IMessagingConfiguration, ClientConfiguration>();
            services.AddSingleton <IGatewayListProvider>(
                sp => ActivatorUtilities.CreateInstance <GatewayProviderFactory>(sp).CreateGatewayListProvider());
            services.AddSingleton <SerializationManager>();
            services.AddSingleton <MessageFactory>();
            services.AddSingleton <Func <string, Logger> >(LogManager.GetLogger);
            services.AddSingleton <StreamProviderManager>();
            services.AddSingleton <ClientStatisticsManager>();
            services.AddFromExisting <IStreamProviderManager, StreamProviderManager>();
            services.AddSingleton <CodeGeneratorManager>();

            this.ServiceProvider = services.BuildServiceProvider();

            this.InternalGrainFactory = this.ServiceProvider.GetRequiredService <IInternalGrainFactory>();
            this.ClientStatistics     = this.ServiceProvider.GetRequiredService <ClientStatisticsManager>();
            this.SerializationManager = this.ServiceProvider.GetRequiredService <SerializationManager>();
            this.messageFactory       = this.ServiceProvider.GetService <MessageFactory>();

            this.config = cfg;

            if (!LogManager.IsInitialized)
            {
                LogManager.Initialize(config);
            }
            StatisticsCollector.Initialize(config);
            this.assemblyProcessor = this.ServiceProvider.GetRequiredService <AssemblyProcessor>();
            this.assemblyProcessor.Initialize();

            logger    = LogManager.GetLogger("OutsideRuntimeClient", LoggerType.Runtime);
            appLogger = LogManager.GetLogger("Application", LoggerType.Application);

            BufferPool.InitGlobalBufferPool(config);
            this.handshakeClientId = GrainId.NewClientId();

            tryResendMessage   = TryResendMessage;
            unregisterCallback = msg => UnRegisterCallback(msg.Id);

            try
            {
                LoadAdditionalAssemblies();

                callbacks    = new ConcurrentDictionary <CorrelationId, CallbackData>();
                localObjects = new ConcurrentDictionary <GuidId, LocalObjectData>();

                if (!secondary)
                {
                    UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException);
                }
                AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;

                clientProviderRuntime     = this.ServiceProvider.GetRequiredService <ClientProviderRuntime>();
                statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime);
                var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations)
                                        .WaitForResultWithThrow(initTimeout);
                if (statsProviderName != null)
                {
                    config.StatisticsProviderName = statsProviderName;
                }

                responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout;
                var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface);

                // Client init / sign-on message
                logger.Info(ErrorCode.ClientInitializing, string.Format(
                                "{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}",
                                BARS, config.DNSHostName, localAddress, handshakeClientId));
                string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}",
                                                BARS, RuntimeVersion.Current, PrintAppDomainDetails());
                startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config);
                logger.Info(ErrorCode.ClientStarting, startMsg);

                if (TestOnlyThrowExceptionDuringInit)
                {
                    throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit");
                }

                config.CheckGatewayProviderSettings();

                var generation          = -SiloAddress.AllocateNewGeneration(); // Client generations are negative
                var gatewayListProvider = this.ServiceProvider.GetRequiredService <IGatewayListProvider>();
                gatewayListProvider.InitializeGatewayListProvider(cfg, LogManager.GetLogger(gatewayListProvider.GetType().Name))
                .WaitWithThrow(initTimeout);
                transport = ActivatorUtilities.CreateInstance <ProxiedMessageCenter>(this.ServiceProvider, localAddress, generation, handshakeClientId);

                if (StatisticsCollector.CollectThreadTimeTrackingStats)
                {
                    incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver");
                }
            }
            catch (Exception exc)
            {
                if (logger != null)
                {
                    logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc);
                }
                ConstructorReset();
                throw;
            }
        }
Example #3
0
        // used for testing to (carefully!) allow two clients in the same process
        private async Task StartInternal(Func <Exception, Task <bool> > retryFilter)
        {
            // Initialize the gateway list provider, since information from the cluster is required to successfully
            // initialize subsequent services.
            var initializedGatewayProvider = new[] { false };

            await ExecuteWithRetries(async() =>
            {
                if (!initializedGatewayProvider[0])
                {
                    await this.gatewayListProvider.InitializeGatewayListProvider();
                    initializedGatewayProvider[0] = true;
                }

                var gateways = await this.gatewayListProvider.GetGateways();
                if (gateways.Count == 0)
                {
                    var gatewayProviderType = this.gatewayListProvider.GetType().GetParseableName();
                    var err = $"Could not find any gateway in {gatewayProviderType}. Orleans client cannot initialize.";
                    logger.Error(ErrorCode.GatewayManager_NoGateways, err);
                    throw new SiloUnavailableException(err);
                }
            },
                                     retryFilter);

            var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative

            transport = ActivatorUtilities.CreateInstance <ClientMessageCenter>(this.ServiceProvider, localAddress, generation, handshakeClientId);
            transport.Start();
            CurrentActivationAddress = ActivationAddress.NewActivationAddress(transport.MyAddress, handshakeClientId);

            listeningCts = new CancellationTokenSource();
            var ct = listeningCts.Token;

            listenForMessages = true;

            // Keeping this thread handling it very simple for now. Just queue task on thread pool.
            Task.Run(
                () =>
            {
                while (listenForMessages && !ct.IsCancellationRequested)
                {
                    try
                    {
                        RunClientMessagePump(ct);
                    }
                    catch (Exception exc)
                    {
                        logger.Error(ErrorCode.Runtime_Error_100326, "RunClientMessagePump has thrown exception", exc);
                    }
                }
            },
                ct).Ignore();

            await ExecuteWithRetries(
                async() => this.GrainTypeResolver = await transport.GetGrainTypeResolver(this.InternalGrainFactory),
                retryFilter);

            this.typeMapRefreshTimer = new AsyncTaskSafeTimer(
                this.logger,
                RefreshGrainTypeResolver,
                null,
                this.typeMapRefreshInterval,
                this.typeMapRefreshInterval);

            ClientStatistics.Start(transport, clientId);

            await ExecuteWithRetries(StreamingInitialize, retryFilter);

            async Task ExecuteWithRetries(Func <Task> task, Func <Exception, Task <bool> > shouldRetry)
            {
                while (true)
                {
                    try
                    {
                        await task();

                        return;
                    }
                    catch (Exception exception) when(shouldRetry != null)
                    {
                        var retry = await shouldRetry(exception);

                        if (!retry)
                        {
                            throw;
                        }
                    }
                }
            }
        }
Example #4
0
        // used for testing to (carefully!) allow two clients in the same process
        private async Task StartInternal(Func <Exception, Task <bool> > retryFilter)
        {
            // Initialize the gateway list provider, since information from the cluster is required to successfully
            // initialize subsequent services.
            var initializedGatewayProvider = new[] { false };

            await ExecuteWithRetries(async() =>
            {
                if (!initializedGatewayProvider[0])
                {
                    await this.gatewayListProvider.InitializeGatewayListProvider();
                    initializedGatewayProvider[0] = true;
                }

                var gateways = await this.gatewayListProvider.GetGateways();
                if (gateways.Count == 0)
                {
                    var gatewayProviderType = this.gatewayListProvider.GetType().GetParseableName();
                    var err = $"Could not find any gateway in {gatewayProviderType}. Orleans client cannot initialize.";
                    logger.Error(ErrorCode.GatewayManager_NoGateways, err);
                    throw new SiloUnavailableException(err);
                }
            },
                                     retryFilter);

            var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative

            transport = ActivatorUtilities.CreateInstance <ClientMessageCenter>(this.ServiceProvider, localAddress, generation, clientId);
            transport.RegisterLocalMessageHandler(this.HandleMessage);
            transport.Start();
            CurrentActivationAddress = ActivationAddress.NewActivationAddress(transport.MyAddress, clientId);

            await ExecuteWithRetries(
                async() => this.GrainTypeResolver = await transport.GetGrainTypeResolver(this.InternalGrainFactory),
                retryFilter);

            this.typeMapRefreshTimer = new AsyncTaskSafeTimer(
                this.logger,
                RefreshGrainTypeResolver,
                null,
                this.typeMapRefreshInterval,
                this.typeMapRefreshInterval);

            ClientStatistics.Start(transport, clientId);

            await ExecuteWithRetries(StreamingInitialize, retryFilter);

            async Task ExecuteWithRetries(Func <Task> task, Func <Exception, Task <bool> > shouldRetry)
            {
                while (true)
                {
                    try
                    {
                        await task();

                        return;
                    }
                    catch (Exception exception) when(shouldRetry != null)
                    {
                        var retry = await shouldRetry(exception);

                        if (!retry)
                        {
                            throw;
                        }
                    }
                }
            }
        }
Example #5
0
        /// <summary>
        /// Initialize this Orleans silo for execution with the specified Azure deploymentId
        /// </summary>
        /// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param>
        /// <param name="deploymentId">Azure DeploymentId this silo is running under</param>
        /// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
        /// <returns><c>true</c> if the silo startup was successful</returns>
        internal bool Start(ClusterConfiguration config, string deploymentId, string connectionString)
        {
            if (config != null && deploymentId != null)
            {
                throw new ArgumentException("Cannot use config and deploymentId on the same time");
            }

            // Program ident
            Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current);

            // Read endpoint info for this instance from Azure config
            string instanceName = serviceRuntimeWrapper.InstanceName;

            // Configure this Orleans silo instance
            if (config == null)
            {
                host = new SiloHost(instanceName);
                host.LoadOrleansConfig(); // Load config from file + Initializes logger configurations
            }
            else
            {
                host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations
            }

            IPEndPoint myEndpoint    = serviceRuntimeWrapper.GetIPEndpoint(SiloEndpointConfigurationKeyName);
            IPEndPoint proxyEndpoint = serviceRuntimeWrapper.GetIPEndpoint(ProxyEndpointConfigurationKeyName);

            host.SetSiloType(Silo.SiloType.Secondary);

            int generation = SiloAddress.AllocateNewGeneration();

            // Bootstrap this Orleans silo instance

            // If deploymentId was not direclty provided, take the value in the config. If it is not
            // in the config too, just take the DeploymentId from Azure
            if (deploymentId == null)
            {
                deploymentId = string.IsNullOrWhiteSpace(host.Config.Globals.DeploymentId)
                    ? serviceRuntimeWrapper.DeploymentId
                    : host.Config.Globals.DeploymentId;
            }

            myEntry = new SiloInstanceTableEntry
            {
                DeploymentId = deploymentId,
                Address      = myEndpoint.Address.ToString(),
                Port         = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
                Generation   = generation.ToString(CultureInfo.InvariantCulture),

                HostName  = host.Config.GetOrCreateNodeConfigurationForSilo(host.Name).DNSHostName,
                ProxyPort = (proxyEndpoint != null ? proxyEndpoint.Port : 0).ToString(CultureInfo.InvariantCulture),

                RoleName   = serviceRuntimeWrapper.RoleName,
                SiloName   = instanceName,
                UpdateZone = serviceRuntimeWrapper.UpdateDomain.ToString(CultureInfo.InvariantCulture),
                FaultZone  = serviceRuntimeWrapper.FaultDomain.ToString(CultureInfo.InvariantCulture),
                StartTime  = LogFormatter.PrintDate(DateTime.UtcNow),

                PartitionKey = deploymentId,
                RowKey       = myEndpoint.Address + "-" + myEndpoint.Port + "-" + generation
            };

            if (connectionString == null)
            {
                connectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
            }

            try
            {
                siloInstanceManager = OrleansSiloInstanceManager.GetManager(
                    deploymentId, connectionString, this.loggerFactory).WithTimeout(AzureTableDefaultPolicies.TableCreationTimeout).Result;
            }
            catch (Exception exc)
            {
                var error = String.Format("Failed to create OrleansSiloInstanceManager. This means CreateTableIfNotExist for silo instance table has failed with {0}",
                                          LogFormatter.PrintException(exc));
                Trace.TraceError(error);
                logger.Error(ErrorCode.AzureTable_34, error, exc);
                throw new OrleansException(error, exc);
            }

            // Always use Azure table for membership when running silo in Azure
            host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable);
            if (host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified ||
                host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain)
            {
                host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
            }
            host.SetExpectedClusterSize(serviceRuntimeWrapper.RoleInstanceCount);
            siloInstanceManager.RegisterSiloInstance(myEntry);

            // Initialize this Orleans silo instance
            host.SetDeploymentId(deploymentId, connectionString);
            host.SetSiloEndpoint(myEndpoint, generation);
            host.SetProxyEndpoint(proxyEndpoint);

            host.InitializeOrleansSilo();
            return(StartSilo());
        }
Example #6
0
        public OutsideRuntimeClient(ClientConfiguration cfg, bool secondary = false)
        {
            this.typeCache         = new TypeMetadataCache();
            this.assemblyProcessor = new AssemblyProcessor(this.typeCache);
            this.grainFactory      = new GrainFactory(this, this.typeCache);

            if (cfg == null)
            {
                Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object.");
                throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg");
            }

            this.config = cfg;

            if (!LogManager.IsInitialized)
            {
                LogManager.Initialize(config);
            }
            StatisticsCollector.Initialize(config);
            SerializationManager.Initialize(cfg.SerializationProviders, cfg.FallbackSerializationProvider);
            this.assemblyProcessor.Initialize();

            logger    = LogManager.GetLogger("OutsideRuntimeClient", LoggerType.Runtime);
            appLogger = LogManager.GetLogger("Application", LoggerType.Application);

            BufferPool.InitGlobalBufferPool(config);
            this.handshakeClientId = GrainId.NewClientId();

            tryResendMessage   = TryResendMessage;
            unregisterCallback = msg => UnRegisterCallback(msg.Id);

            try
            {
                LoadAdditionalAssemblies();

                callbacks    = new ConcurrentDictionary <CorrelationId, CallbackData>();
                localObjects = new ConcurrentDictionary <GuidId, LocalObjectData>();

                if (!secondary)
                {
                    UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException);
                }
                AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;

                // Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked
                SerializationManager.GetDeserializer(typeof(String));

                clientProviderRuntime     = new ClientProviderRuntime(grainFactory, null);
                statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime);
                var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations)
                                        .WaitForResultWithThrow(initTimeout);
                if (statsProviderName != null)
                {
                    config.StatisticsProviderName = statsProviderName;
                }

                responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout;
                var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface);

                // Client init / sign-on message
                logger.Info(ErrorCode.ClientInitializing, string.Format(
                                "{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}",
                                BARS, config.DNSHostName, localAddress, handshakeClientId));
                string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}",
                                                BARS, RuntimeVersion.Current, PrintAppDomainDetails());
                startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config);
                logger.Info(ErrorCode.ClientStarting, startMsg);

                if (TestOnlyThrowExceptionDuringInit)
                {
                    throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit");
                }

                config.CheckGatewayProviderSettings();

                var generation          = -SiloAddress.AllocateNewGeneration(); // Client generations are negative
                var gatewayListProvider = GatewayProviderFactory.CreateGatewayListProvider(config)
                                          .WithTimeout(initTimeout).Result;
                transport = new ProxiedMessageCenter(config, localAddress, generation, handshakeClientId, gatewayListProvider);

                if (StatisticsCollector.CollectThreadTimeTrackingStats)
                {
                    incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver");
                }
            }
            catch (Exception exc)
            {
                if (logger != null)
                {
                    logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc);
                }
                ConstructorReset();
                throw;
            }
        }
Example #7
0
        /// <summary>
        /// Initialize this Orleans silo for execution with the specified Azure deploymentId and role instance
        /// </summary>
        /// <param name="deploymentId">Azure DeploymentId this silo is running under</param>
        /// <param name="myRoleInstance">Azure role instance info this silo is running under</param>
        /// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param>
        /// <returns><c>true</c> is the silo startup was successfull</returns>
        public bool Start(string deploymentId, RoleInstance myRoleInstance, ClusterConfiguration config)
        {
            if (string.IsNullOrWhiteSpace(deploymentId))
            {
                throw new ArgumentException("deploymentId is null or whitespace", "deploymentId");
            }

            if (myRoleInstance == null)
            {
                throw new ArgumentException("myRoleInstance is null", "myRoleInstance");
            }

            // Program ident
            Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current);

            // Read endpoint info for this instance from Azure config
            string instanceName = AzureConfigUtils.GetInstanceName(myRoleInstance);

            // Configure this Orleans silo instance

            if (config == null)
            {
                host = new SiloHost(instanceName);
                host.LoadOrleansConfig(); // Load config from file + Initializes logger configurations
            }
            else
            {
                host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations
            }

            RoleInstanceEndpoint myEndpoint    = GetEndpointInfo(myRoleInstance, SiloEndpointConfigurationKeyName);
            RoleInstanceEndpoint proxyEndpoint = GetEndpointInfo(myRoleInstance, ProxyEndpointConfigurationKeyName);

            host.SetSiloType(Silo.SiloType.Secondary);

            int generation = SiloAddress.AllocateNewGeneration();

            // Bootstrap this Orleans silo instance

            myEntry = new SiloInstanceTableEntry
            {
                DeploymentId = deploymentId,
                Address      = myEndpoint.IPEndpoint.Address.ToString(),
                Port         = myEndpoint.IPEndpoint.Port.ToString(CultureInfo.InvariantCulture),
                Generation   = generation.ToString(CultureInfo.InvariantCulture),

                HostName  = host.Config.GetConfigurationForNode(host.Name).DNSHostName,
                ProxyPort = (proxyEndpoint != null ? proxyEndpoint.IPEndpoint.Port : 0).ToString(CultureInfo.InvariantCulture),

                RoleName     = myRoleInstance.Role.Name,
                InstanceName = instanceName,
                UpdateZone   = myRoleInstance.UpdateDomain.ToString(CultureInfo.InvariantCulture),
                FaultZone    = myRoleInstance.FaultDomain.ToString(CultureInfo.InvariantCulture),
                StartTime    = TraceLogger.PrintDate(DateTime.UtcNow),

                PartitionKey = deploymentId,
                RowKey       = myEndpoint.IPEndpoint.Address + "-" + myEndpoint.IPEndpoint.Port + "-" + generation
            };

            var connectionString = RoleEnvironment.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);

            try
            {
                siloInstanceManager = OrleansSiloInstanceManager.GetManager(
                    deploymentId, connectionString).WithTimeout(AzureTableDefaultPolicies.TableCreationTimeout).Result;
            }
            catch (Exception exc)
            {
                var error = String.Format("Failed to create OrleansSiloInstanceManager. This means CreateTableIfNotExist for silo instance table has failed with {0}",
                                          TraceLogger.PrintException(exc));
                Trace.TraceError(error);
                logger.Error(ErrorCode.AzureTable_34, error, exc);
                throw new OrleansException(error, exc);
            }

            // Always use Azure table for membership when running silo in Azure
            host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable);
            host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
            siloInstanceManager.RegisterSiloInstance(myEntry);

            // Initialise this Orleans silo instance
            host.SetDeploymentId(deploymentId, connectionString);
            host.SetSiloEndpoint(myEndpoint.IPEndpoint, generation);
            host.SetProxyEndpoint(proxyEndpoint.IPEndpoint);

            host.InitializeOrleansSilo();
            logger.Info(ErrorCode.Runtime_Error_100288, "Successfully initialized Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
            return(StartSilo());
        }