Esempio n. 1
0
 public InsideRuntimeClient(
     Dispatcher dispatcher,
     Catalog catalog,
     ILocalGrainDirectory directory,
     SiloAddress silo,
     ClusterConfiguration config,
     IConsistentRingProvider ring,
     GrainTypeManager typeManager,
     GrainFactory grainFactory)
 {
     this.dispatcher = dispatcher;
     MySilo = silo;
     this.directory = directory;
     ConsistentRingProvider = ring;
     Catalog = catalog;
     disposables = new List<IDisposable>();
     callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>();
     Config = config;
     config.OnConfigChange("Globals/Message", () => ResponseTimeout = Config.Globals.ResponseTimeout);
     RuntimeClient.Current = this;
     this.typeManager = typeManager;
     this.InternalGrainFactory = grainFactory;
 }
        public Task <Immutable <EventConsumerInfo> > StopAsync(string consumerName)
        {
            var eventConsumer = GrainFactory.GetGrain <IEventConsumerGrain>(consumerName);

            return(eventConsumer.StopAsync());
        }
Esempio n. 3
0
 public Task <uint> GetNotifyRange() => GrainFactory.Get <IUnit>(this).GetSightRange();
Esempio n. 4
0
        public Task GrainCallToThrowsAggregateExceptionWrappingInvalidOperationException(long otherGrainId)
        {
            var otherGrain = GrainFactory.GetGrain <IExceptionGrain>(otherGrainId);

            return(otherGrain.ThrowsAggregateExceptionWrappingInvalidOperationException());
        }
Esempio n. 5
0
        public async Task DispatchPacket(LoginStart packet)
        {
            var settingsGrain = GrainFactory.GetGrain <IServerSettings>(0);
            var settings      = await settingsGrain.GetSettings();

            if (settings.OnlineMode)
            {
                // TODO auth and compression
                var user = GrainFactory.GetGrain <INonAuthenticatedUser>(packet.Name);

                if (await user.GetProtocolVersion() > MineCase.Protocol.Protocol.Version)
                {
                    await SendLoginDisconnect($"{{\"text\":\"Outdated server!I'm still on {Protocol.Protocol.VersionName}\"}}");
                }
                else if (await user.GetProtocolVersion() < MineCase.Protocol.Protocol.Version)
                {
                    await SendLoginDisconnect($"{{\"text\":\"Outdated client!Please use {Protocol.Protocol.VersionName}\"}}");
                }
                else
                {
                    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                    Random verifyRandom          = new Random();
                    Byte[] verifyToken           = new byte[64];

                    verifyRandom.NextBytes(verifyToken);
                    var keys = rsa.ExportParameters(false);

                    await SendEncryptionRequest("", keys.Exponent, verifyToken);
                }
            }
            else
            {
                var nonAuthenticatedUser = GrainFactory.GetGrain <INonAuthenticatedUser>(packet.Name);

                if (await nonAuthenticatedUser.GetProtocolVersion() > MineCase.Protocol.Protocol.Version)
                {
                    await SendLoginDisconnect($"{{\"text\":\"Outdated server!I'm still on {Protocol.Protocol.VersionName}\"}}");
                }
                else if (await nonAuthenticatedUser.GetProtocolVersion() < MineCase.Protocol.Protocol.Version)
                {
                    await SendLoginDisconnect($"{{\"text\":\"Outdated client!Please use {Protocol.Protocol.VersionName}\"}}");
                }
                else
                {
                    // TODO refuse him if server is full
                    var user = await nonAuthenticatedUser.GetUser();

                    var world = await user.GetWorld();

                    var gameSession = GrainFactory.GetGrain <IGameSession>(world.GetPrimaryKeyString());

                    await SendSetCompression();

                    var uuid = user.GetPrimaryKey();
                    await SendLoginSuccess(packet.Name, uuid);

                    await user.SetClientPacketSink(GrainFactory.GetGrain <IClientboundPacketSink>(this.GetPrimaryKey()));

                    var packetRouter = GrainFactory.GetGrain <IPacketRouter>(this.GetPrimaryKey());
                    await user.SetPacketRouter(packetRouter);

                    await packetRouter.BindToUser(user);

                    var game = GrainFactory.GetGrain <IGameSession>(world.GetPrimaryKeyString());
                    await game.JoinGame(user);
                }
            }
        }
Esempio n. 6
0
 private ISimpleObserverableGrain GetGrain()
 {
     return(GrainFactory.GetGrain <ISimpleObserverableGrain>(GetRandomGrainId()));
 }
Esempio n. 7
0
 public async Task <bool> IsBlacklisted()
 {
     return(await GrainFactory.GetGrain <IBlacklistGrain>(0).IsBlacklisted(await GetUsername()));
 }
Esempio n. 8
0
 public Task<IGrainTypeResolver> GetTypeCodeMap(GrainFactory grainFactory)
 {
     var silo = GetLiveGatewaySiloAddress();
     return GetTypeManager(silo, grainFactory).GetClusterTypeCodeMap();
 }
Esempio n. 9
0
 private ISagaCancellationGrain GetSagaCancellationGrain()
 {
     return(GrainFactory.GetGrain <ISagaCancellationGrain>(this.GetPrimaryKey()));
 }
        public override Task OnActivateAsync()
        {
            _messageBatchGrain = GrainFactory.GetGrain <IMessageBatch>(Guid.Empty);

            return(base.OnActivateAsync());
        }
 public override Task OnActivateAsync()
 {
     Worker = GrainFactory.GetGrain <ICalculatorWorkerGrain>(new Random(Guid.NewGuid().GetHashCode()).Next());
     return(base.OnActivateAsync());
 }
        public override async Task Execute()
        {
            var sourceAccount = GrainFactory.GetGrain <IBankAccountGrain>(Config.Account);

            await sourceAccount.ModifyBalance(SagaId, Config.Amount);
        }
        public override async Task Compensate()
        {
            var sourceAccount = GrainFactory.GetGrain <IBankAccountGrain>(Config.Account);

            await sourceAccount.RevertBalanceModification(SagaId);
        }
Esempio n. 14
0
 public async Task AmountAddEventHandler(AmountTransferEvent value)
 {
     var toActor = GrainFactory.GetGrain <IAccount>(value.ToAccountId);
     await toActor.AddAmount(value.Amount, value.GetUniqueId());
 }
Esempio n. 15
0
        /// <summary>
        /// Initializes client runtime from client configuration object.
        /// </summary>
        private static void DoInternalInitialize(ClientConfiguration config, OutsideRuntimeClient runtimeClient = null)
        {
            if (IsInitialized)
                return;

            lock (initLock)
            {
                if (!IsInitialized)
                {
                    try
                    {
                        // this is probably overkill, but this ensures isFullyInitialized false
                        // before we make a call that makes RuntimeClient.Current not null
                        isFullyInitialized = false;
                        grainFactory = new GrainFactory();

                        if (runtimeClient == null)
                        {
                            runtimeClient = new OutsideRuntimeClient(config, grainFactory);
                        }
                        outsideRuntimeClient = runtimeClient;  // Keep reference, to avoid GC problems
                        outsideRuntimeClient.Start();
         
                        // this needs to be the last successful step inside the lock so 
                        // IsInitialized doesn't return true until we're fully initialized
                        isFullyInitialized = true;
                    }
                    catch (Exception exc)
                    {
                        // just make sure to fully Uninitialize what we managed to partially initialize, so we don't end up in inconsistent state and can later on re-initialize.
                        Console.WriteLine("Initialization failed. {0}", exc);
                        InternalUninitialize();
                        throw;
                    }
                }
            }
        }
Esempio n. 16
0
 public Task<GrainInterfaceMap> GetTypeCodeMap(GrainFactory grainFactory)
 {
     var silo = GetLiveGatewaySiloAddress();
     return GetTypeManager(silo, grainFactory).GetTypeCodeMap(silo);
 }
Esempio n. 17
0
        public Task EventHandle(TransferEvent evt, EventBase eventBase)
        {
            var toActor = GrainFactory.GetGrain <IAccount>(evt.ToId);

            return(toActor.TransferArrived(evt.Amount, new EventUID(eventBase.GetEventId(GrainId.ToString()), eventBase.Timestamp)));
        }
Esempio n. 18
0
 private IClusterTypeManager GetTypeManager(SiloAddress destination, GrainFactory grainFactory)
 {
     return grainFactory.GetSystemTarget<IClusterTypeManager>(Constants.TypeManagerId, destination);
 }
Esempio n. 19
0
 public async Task Generic_SimpleGrain_GetGrain()
 {
     var grain = GrainFactory.GetGrain <ISimpleGenericGrain1 <int> >(grainId++);
     await grain.GetA();
 }
Esempio n. 20
0
 public async Task TaskCancelationPropagation()
 {
     IExceptionGrain grain = GrainFactory.GetGrain <IExceptionGrain>(GetRandomGrainId());
     await Assert.ThrowsAsync <TaskCanceledException>(
         () => grain.Canceled());
 }
Esempio n. 21
0
 public TGrainInterface GetGrain <TGrainInterface>(int i) where TGrainInterface : IGrainWithIntegerKey
 {
     return(GrainFactory.GetGrain <TGrainInterface>(i));
 }
Esempio n. 22
0
 protected override void InitializePreLoadComponent()
 {
     SetComponent(new StateComponent <StateHolder>());
     _tickEmitter = GrainFactory.GetPartitionGrain <ITickEmitter>(this);
 }
Esempio n. 23
0
 public TGrainInterface GetGrain <TGrainInterface>() where TGrainInterface : IGrainWithIntegerKey
 {
     return(GrainFactory.GetGrain <TGrainInterface>(GetRandomGrainId()));
 }
Esempio 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.legacyConfiguration = services.GetRequiredService <LegacyConfigurationWrapper>();
            this.siloDetails         = siloDetails;
            this.SystemStatus        = SystemStatus.Creating;
            AsynchAgent.IsStarting   = true;

            var startTime = DateTime.UtcNow;

            services?.GetService <TelemetryManager>()?.AddFromConfiguration(services, LocalConfig.TelemetryConfiguration);
            StatisticsCollector.Initialize(LocalConfig.StatisticsCollectionLevel);

            initTimeout = GlobalConfig.MaxJoinAttemptTime;
            if (Debugger.IsAttached)
            {
                initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), GlobalConfig.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 cofnig
            RequestContext.PropagateActivityId = this.legacyConfiguration.NodeConfig.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 {0} silo on host {1} MachineName {2} at {3}, gen {4} --------------",
                        this.legacyConfiguration.Type, this.siloDetails.DnsHostName, Environment.MachineName, localEndpoint, this.siloDetails.SiloAddress.Generation);
            logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0} with the following configuration= " + Environment.NewLine + "{1}",
                        name, this.legacyConfiguration.ClusterConfig.ToString(name));

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

            BufferPool.InitGlobalBufferPool(siloMessagingOptions);

            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;

            // GrainRuntime can be created only here, after messageCenter was created.
            this.grainRuntime = Services.GetRequiredService <IGrainRuntime>();

            // 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>();
            siloStatistics.MetricsTable.Scheduler           = scheduler;
            siloStatistics.MetricsTable.ActivationDirectory = activationDirectory;
            siloStatistics.MetricsTable.ActivationCollector = catalog.ActivationCollector;
            siloStatistics.MetricsTable.MessageCenter       = messageCenter;

            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.siloOptions = Services.GetRequiredService <IOptions <SiloOptions> >().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.

            var fullSiloLifecycle = this.Services.GetRequiredService <SiloLifecycle>();

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

            foreach (ILifecycleParticipant <ISiloLifecycle> participant in lifecycleParticipants)
            {
                participant?.Participate(fullSiloLifecycle);
            }
            // 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(fullSiloLifecycle);
            }

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

            logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
        }
        private IContainerNodeGrain <T> GetRandomContainerGrain <T>()
        {
            var grain = GrainFactory.GetGrain <IContainerNodeGrain <T> >(Guid.NewGuid());

            return(grain);
        }
Esempio n. 26
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.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);

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

            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());
        }
Esempio n. 27
0
 public void VerifyGrainAccess(int count)
 {
     A.CallTo(() => GrainFactory.GetGrain <IAppGrain>(AppId.Id.ToString(), null))
     .MustHaveHappenedANumberOfTimesMatching(x => x == count);
 }
Esempio n. 28
0
 public virtual Task CopyTo(IEntity target)
 {
     return(GrainFactory.GetGrain <IComponent <TComponent> >(target.GetPrimaryKey()).SetData(State));
 }
Esempio n. 29
0
        // make a move during the game
        public async Task <GameState> MakeMove(GameMove move)
        {
            // check if its a legal move to make
            if (this.GameState != GameState.InPlay)
            {
                throw new ApplicationException("This game is not in play");
            }

            if (ListOfPlayers.IndexOf(move.PlayerId) < 0)
            {
                throw new ArgumentException("No such playerid for this game", "move");
            }
            if (move.PlayerId != ListOfPlayers[indexNextPlayerToMove])
            {
                throw new ArgumentException("The wrong player tried to make a move", "move");
            }

            if (move.X < 0 || move.X > 2 || move.Y < 0 || move.Y > 2)
            {
                throw new ArgumentException("Bad co-ordinates for a move", "move");
            }
            if (theBoard[move.X, move.Y] != -1)
            {
                throw new ArgumentException("That square is not empty", "move");
            }

            // record move
            this.ListOfMoves.Add(move);
            this.theBoard[move.X, move.Y] = indexNextPlayerToMove;

            // check for a winning move
            var win = false;

            if (!win)
            {
                for (int i = 0; i < 3 && !win; i++)
                {
                    win = isWinningLine(theBoard[i, 0], theBoard[i, 1], theBoard[i, 2]);
                }
            }
            if (!win)
            {
                for (int i = 0; i < 3 && !win; i++)
                {
                    win = isWinningLine(theBoard[0, i], theBoard[1, i], theBoard[2, i]);
                }
            }
            if (!win)
            {
                win = isWinningLine(theBoard[0, 0], theBoard[1, 1], theBoard[2, 2]);
            }
            if (!win)
            {
                win = isWinningLine(theBoard[0, 2], theBoard[1, 1], theBoard[2, 0]);
            }

            // check for draw

            var draw = false;

            if (this.ListOfMoves.Count() == 9)
            {
                draw = true;  // we could try to look for stalemate earlier, if we wanted
            }
            // handle end of game
            if (win || draw)
            {
                // game over
                this.GameState = GameState.Finished;
                if (win)
                {
                    WinnerId = ListOfPlayers[indexNextPlayerToMove];
                    LoserId  = ListOfPlayers[(indexNextPlayerToMove + 1) % 2];
                }

                // collect tasks up, so we await both notifications at the same time
                var promises = new List <Task>();
                // inform this player of outcome
                var playerGrain = GrainFactory.GetGrain <IPlayerGrain>(ListOfPlayers[indexNextPlayerToMove]);
                promises.Add(playerGrain.LeaveGame(this.GetPrimaryKey(), win ? GameOutcome.Win : GameOutcome.Draw));

                // inform other player of outcome
                playerGrain = GrainFactory.GetGrain <IPlayerGrain>(ListOfPlayers[(indexNextPlayerToMove + 1) % 2]);
                promises.Add(playerGrain.LeaveGame(this.GetPrimaryKey(), win ? GameOutcome.Lose : GameOutcome.Draw));
                await Task.WhenAll(promises);

                return(this.GameState);
            }

            // if game hasnt ended, prepare for next players move
            indexNextPlayerToMove = (indexNextPlayerToMove + 1) % 2;
            return(this.GameState);
        }
Esempio n. 30
0
        internal Silo(SiloInitializationParameters initializationParams)
        {
            string name = initializationParams.Name;
            ClusterConfiguration config = initializationParams.ClusterConfig;
            this.initializationParams = initializationParams;

            SystemStatus.Current = SystemStatus.Creating;

            CurrentSilo = this;

            var startTime = DateTime.UtcNow;
            
            siloTerminatedEvent = new ManualResetEvent(false);
            
            if (!LogManager.IsInitialized)
                LogManager.Initialize(LocalConfig);

            config.OnConfigChange("Defaults/Tracing", () => LogManager.Initialize(LocalConfig, true), false);
            MultiClusterRegistrationStrategy.Initialize(config.Globals);
            StatisticsCollector.Initialize(LocalConfig);
            
            SerializationManager.Initialize(GlobalConfig.SerializationProviders, this.GlobalConfig.FallbackSerializationProvider);
            initTimeout = GlobalConfig.MaxJoinAttemptTime;
            if (Debugger.IsAttached)
            {
                initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), GlobalConfig.MaxJoinAttemptTime);
                stopTimeout = initTimeout;
            }

            var localEndpoint = this.initializationParams.SiloAddress.Endpoint;
            LogManager.MyIPEndPoint = localEndpoint;
            logger = LogManager.GetLogger("Silo", 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.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 {0} silo on host {1} MachineName {2} at {3}, gen {4} --------------",
                this.initializationParams.Type, LocalConfig.DNSHostName, Environment.MachineName, localEndpoint, this.initializationParams.SiloAddress.Generation);
            logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0} with the following configuration= " + Environment.NewLine + "{1}",
                name, config.ToString(name));
            
            // Configure DI using Startup type
            this.Services = StartupBuilder.ConfigureStartup(
                this.LocalConfig.StartupTypeName,
                (services, usingCustomServiceProvider) =>
                {
                    // add system types
                    // Note: you can replace IGrainFactory with your own implementation, but 
                    // we don't recommend it, in the aspect of performance and usability
                    services.TryAddSingleton(sp => sp);
                    services.TryAddSingleton(this);
                    services.TryAddSingleton(initializationParams);
                    services.TryAddSingleton<ILocalSiloDetails>(initializationParams);
                    services.TryAddSingleton(initializationParams.ClusterConfig);
                    services.TryAddSingleton(initializationParams.GlobalConfig);
                    services.TryAddTransient(sp => initializationParams.NodeConfig);
                    services.TryAddSingleton<ITimerRegistry, TimerRegistry>();
                    services.TryAddSingleton<IReminderRegistry, ReminderRegistry>();
                    services.TryAddSingleton<IStreamProviderManager, StreamProviderManager>();
                    services.TryAddSingleton<GrainRuntime>();
                    services.TryAddSingleton<IGrainRuntime, GrainRuntime>();
                    services.TryAddSingleton<OrleansTaskScheduler>();
                    services.TryAddSingleton<GrainFactory>(sp => sp.GetService<InsideRuntimeClient>().ConcreteGrainFactory);
                    services.TryAddExisting<IGrainFactory, GrainFactory>();
                    services.TryAddExisting<IInternalGrainFactory, GrainFactory>();
                    services.TryAddSingleton<TypeMetadataCache>();
                    services.TryAddSingleton<AssemblyProcessor>();
                    services.TryAddSingleton<ActivationDirectory>();
                    services.TryAddSingleton<LocalGrainDirectory>();
                    services.TryAddExisting<ILocalGrainDirectory, LocalGrainDirectory>();
                    services.TryAddSingleton<SiloStatisticsManager>();
                    services.TryAddSingleton<ISiloPerformanceMetrics>(sp => sp.GetRequiredService<SiloStatisticsManager>().MetricsTable);
                    services.TryAddSingleton<SiloAssemblyLoader>();
                    services.TryAddSingleton<GrainTypeManager>();
                    services.TryAddExisting<IMessagingConfiguration, GlobalConfiguration>();
                    services.TryAddSingleton<MessageCenter>();
                    services.TryAddExisting<IMessageCenter, MessageCenter>();
                    services.TryAddExisting<ISiloMessageCenter, MessageCenter>();
                    services.TryAddSingleton<Catalog>();
                    services.TryAddSingleton(sp => sp.GetRequiredService<Catalog>().Dispatcher);
                    services.TryAddSingleton<InsideRuntimeClient>();
                    services.TryAddExisting<IRuntimeClient, InsideRuntimeClient>();
                    services.TryAddExisting<ISiloRuntimeClient, InsideRuntimeClient>();
                    services.TryAddSingleton<MembershipFactory>();
                    services.TryAddSingleton<MultiClusterOracleFactory>();
                    services.TryAddSingleton<LocalReminderServiceFactory>();
                    services.TryAddSingleton<DeploymentLoadPublisher>();
                    services.TryAddSingleton<IMembershipTable>(
                        sp => sp.GetRequiredService<MembershipFactory>().GetMembershipTable(sp.GetRequiredService<GlobalConfiguration>()));
                    services.TryAddSingleton<MembershipOracle>(
                        sp =>
                        sp.GetRequiredService<MembershipFactory>()
                          .CreateMembershipOracle(sp.GetRequiredService<Silo>(), sp.GetRequiredService<IMembershipTable>()));
                    services.TryAddExisting<IMembershipOracle, MembershipOracle>();
                    services.TryAddExisting<ISiloStatusOracle, MembershipOracle>();
                    services.TryAddSingleton<Func<ISiloStatusOracle>>(sp => () => sp.GetRequiredService<ISiloStatusOracle>());
                    services.TryAddSingleton<MultiClusterOracleFactory>();
                    services.TryAddSingleton<LocalReminderServiceFactory>();
                    services.TryAddSingleton<ClientObserverRegistrar>();
                    services.TryAddSingleton<SiloProviderRuntime>();
                    services.TryAddExisting<IStreamProviderRuntime, SiloProviderRuntime>();
                    services.TryAddSingleton<ImplicitStreamSubscriberTable>();

                    // Placement
                    services.TryAddSingleton<PlacementDirectorsManager>();
                    services.TryAddSingleton<IPlacementDirector<RandomPlacement>, RandomPlacementDirector>();
                    services.TryAddSingleton<IPlacementDirector<PreferLocalPlacement>, PreferLocalPlacementDirector>();
                    services.TryAddSingleton<IPlacementDirector<StatelessWorkerPlacement>, StatelessWorkerDirector>();
                    services.TryAddSingleton<IPlacementDirector<ActivationCountBasedPlacement>, ActivationCountPlacementDirector>();
                    services.TryAddSingleton<DefaultPlacementStrategy>();
                    services.TryAddSingleton<ClientObserversPlacementDirector>();
                    
                    services.TryAddSingleton<Func<IGrainRuntime>>(sp => () => sp.GetRequiredService<IGrainRuntime>());
                    services.TryAddSingleton<GrainCreator>();

                    if (initializationParams.GlobalConfig.UseVirtualBucketsConsistentRing)
                    {
                        services.TryAddSingleton<IConsistentRingProvider>(
                            sp =>
                            new VirtualBucketsRingProvider(
                                this.initializationParams.SiloAddress,
                                this.initializationParams.GlobalConfig.NumVirtualBucketsConsistentRing));
                    }
                    else
                    {
                        services.TryAddSingleton<IConsistentRingProvider>(
                            sp => new ConsistentRingProvider(this.initializationParams.SiloAddress));
                    }
                });

            this.assemblyProcessor = this.Services.GetRequiredService<AssemblyProcessor>();
            this.assemblyProcessor.Initialize();

            BufferPool.InitGlobalBufferPool(GlobalConfig);

            UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnobservedExceptionHandler);
            AppDomain.CurrentDomain.UnhandledException += this.DomainUnobservedExceptionHandler;

            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;
            }

            grainTypeManager = Services.GetRequiredService<GrainTypeManager>();

            // 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>();
            messageCenter.RerouteHandler = runtimeClient.RerouteMessage;
            messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage;

            // GrainRuntime can be created only here, after messageCenter was created.
            grainRuntime = Services.GetRequiredService<IGrainRuntime>();

            // 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>();

            // to preserve backwards compatibility, only use the service provider to inject grain dependencies if the user supplied his own
            // service provider, meaning that he is explicitly opting into it.
            catalog = Services.GetRequiredService<Catalog>();

            siloStatistics.MetricsTable.Scheduler = scheduler;
            siloStatistics.MetricsTable.ActivationDirectory = activationDirectory;
            siloStatistics.MetricsTable.ActivationCollector = catalog.ActivationCollector;
            siloStatistics.MetricsTable.MessageCenter = messageCenter;
            
            // Now the incoming message agents
            incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, catalog.Dispatcher);
            incomingPingAgent = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, catalog.Dispatcher);
            incomingAgent = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, catalog.Dispatcher);

            membershipFactory = Services.GetRequiredService<MembershipFactory>();
            membershipOracle = Services.GetRequiredService<IMembershipOracle>();
            
            SystemStatus.Current = SystemStatus.Created;

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

            logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
        }
Esempio n. 31
0
 private Task InvokeGrainAsync(TaskScheduler orleansTaskScheduler, Func <IBackgroundWorkload <TRequest, TResponse>, Task> action) =>
 Task.Factory.StartNew(async() =>
 {
     var grain = GrainFactory.GetGrain <IBackgroundWorkload <TRequest, TResponse> >(this.GetPrimaryKeyString());
     await action(grain);
 }, CancellationToken.None, TaskCreationOptions.None, orleansTaskScheduler);
Esempio n. 32
0
        /// <summary>
        /// This is the lock free version of uninitilize so we can share 
        /// it between the public method and error paths inside initialize.
        /// This should only be called inside a lock(initLock) block.
        /// </summary>
        private static void InternalUninitialize(bool cleanup = true)
        {
            // Update this first so IsInitialized immediately begins returning
            // false.  Since this method should be protected externally by 
            // a lock(initLock) we should be able to reset everything else 
            // before the next init attempt.
            isFullyInitialized = false;

            if (RuntimeClient.Current != null)
            {
                try
                {
                    RuntimeClient.Current.Reset(cleanup);
                }
                catch (Exception) { }

                RuntimeClient.Current = null;
            }
            outsideRuntimeClient = null;
            grainFactory = null;
        }
Esempio n. 33
0
        public Task <GrainInterfaceMap> GetTypeCodeMap(GrainFactory grainFactory)
        {
            var silo = GetLiveGatewaySiloAddress();

            return(GetTypeManager(silo, grainFactory).GetTypeCodeMap(silo));
        }
Esempio n. 34
0
        public Task <Streams.ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(GrainFactory grainFactory)
        {
            var silo = GetLiveGatewaySiloAddress();

            return(GetTypeManager(silo, grainFactory).GetImplicitStreamSubscriberTable(silo));
        }
Esempio n. 35
0
 private ITypeManager GetTypeManager(SiloAddress destination, GrainFactory grainFactory)
 {
     return(grainFactory.GetSystemTarget <ITypeManager>(Constants.TypeManagerId, destination));
 }
Esempio n. 36
0
 public Task<Streams.ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(GrainFactory grainFactory)
 {
     var silo = GetLiveGatewaySiloAddress();
     return GetTypeManager(silo, grainFactory).GetImplicitStreamSubscriberTable(silo);
 }
Esempio n. 37
0
        public Task EventHandler(AmountTransferEvent value, EventBase eventBase)
        {
            var toActor = GrainFactory.GetGrain <IAccount>(value.ToAccountId);

            return(toActor.AddAmount(value.Amount, new EventUID(eventBase.GetEventId(GrainId.ToString()), eventBase.Timestamp)));
        }
Esempio n. 38
0
        public OutsideRuntimeClient(ClientConfiguration cfg, GrainFactory grainFactory, bool secondary = false)
        {
            this.grainFactory = grainFactory;
            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, cfg.SerializationProviders, config.UseJsonFallbackSerializer);
            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>();

                if (!secondary)
                {
                    UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException);
                }
                // Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked
                SerializationManager.GetDeserializer(typeof(String));

                clientProviderRuntime = new ClientProviderRuntime(grainFactory, new DefaultServiceProvider());
                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;
                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 Exception("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;
            }
        }
Esempio n. 39
0
 public async Task SerializationTests_Generic_CircularReferenceTest()
 {
     var grainId = Guid.NewGuid();
     var grain   = GrainFactory.GetGrain <ICircularStateTestGrain>(primaryKey: grainId, keyExtension: grainId.ToString("N"));
     var c1      = await grain.GetState();
 }