Пример #1
0
        public AsyncReqReplyServiceSpecs()
        {
            Reply   = string.Empty;
            Replied = new ManualResetEvent(false);
            Console.WriteLine("Start client fiber");
            Func <byte[], string> unmarshaller = x => Encoding.Unicode.GetString(x);
            Func <string, byte[]> marshaller   = x => Encoding.Unicode.GetBytes(x);

            ServerFiber   = PoolFiber.StartNew();
            ServerContext = NetMQContext.Create();
            Service       = new AsyncRequestHandlerSocket <string, string>(ServerContext,
                                                                           "tcp://localhost:9997",
                                                                           unmarshaller,
                                                                           marshaller);
            Service.SetRequestHandler(ServerFiber, request => request.Reply(request.Request.ToUpper()));
            Console.WriteLine("Start service");
            ClientFiber = StubFiber.StartNew();

            ClientContext = NetMQContext.Create();
            Client        = new AsyncRequestSocket <string, string>(ClientContext,
                                                                    "tcp://localhost:9997",
                                                                    marshaller,
                                                                    unmarshaller);
            Console.WriteLine("Start client");
        }
Пример #2
0
 public ApplicationStatsPublisher(GameApplication application, int publishIntervalMilliseconds)
 {
     this.application = application;
     this.publishIntervalMilliseconds = publishIntervalMilliseconds;
     this.fiber = new PoolFiber();
     this.fiber.Start();
 }
 public ApplicationStatsPublisher(GameApplication application, int publishIntervalMilliseconds)
 {
     this.application = application;
     this.publishIntervalMilliseconds = publishIntervalMilliseconds;
     this.fiber = new PoolFiber();
     this.fiber.Start();
 }
Пример #4
0
        public void InOrderExecution()
        {
            PoolFiber fiber = new PoolFiber(new DefaultThreadPool(), new BatchExecutor());

            fiber.Start();

            int            count   = 0;
            AutoResetEvent reset   = new AutoResetEvent(false);
            List <int>     result  = new List <int>();
            Command        command = delegate
            {
                result.Add(count++);
                if (count == 100)
                {
                    reset.Set();
                }
            };

            for (int i = 0; i < 100; i++)
            {
                fiber.Enqueue(command);
            }

            Assert.IsTrue(reset.WaitOne(10000, false));
            Assert.AreEqual(100, count);
        }
Пример #5
0
        public void SingleConsumerWithException()
        {
            var failed = new List <Exception>();
            var exec   = new ExceptionHandlingExecutor(failed.Add);

            using (IFiber one = PoolFiber.StartNew(exec))
                using (var reset = new AutoResetEvent(false))
                {
                    var channel = new QueueChannel <int>();

                    void OnMsg(int num)
                    {
                        if (num == 0)
                        {
                            throw new Exception();
                        }
                        reset.Set();
                    }

                    channel.Subscribe(one, OnMsg);
                    channel.Publish(0);
                    channel.Publish(1);
                    Assert.IsTrue(reset.WaitOne(10000, false));
                    Assert.AreEqual(1, failed.Count);
                }
        }
Пример #6
0
		public void Adding_operations_to_a_fiber()
		{
			_count = 10000;
			_values = new int[_count];
			Fiber fiber = new PoolFiber();

			int index = 0;
			var completed = new Future<int>();

			var go = new Future<bool>();

			fiber.Add(() => { go.WaitUntilCompleted(10.Seconds()); });

			for (int i = 0; i < _count; i++)
			{
				int offset = i;
				fiber.Add(() =>
					{
						_values[offset] = index++;

						if (offset == _count - 1)
							completed.Complete(offset);
					});
			}

			go.Complete(true);

			completed.WaitUntilCompleted(10.Seconds()).ShouldBeTrue();
		}
        public void SynchronousRequestWithMultipleReplies()
        {
            IFiber responder = new PoolFiber();

            responder.Start();
            var countChannel = new RequestReplyChannel <string, int>();

            var allSent = new AutoResetEvent(false);
            Action <IRequest <string, int> > onRequest =
                delegate(IRequest <string, int> req)
            {
                for (var i = 0; i <= 5; i++)
                {
                    req.SendReply(i);
                }
                allSent.Set();
            };

            countChannel.Subscribe(responder, onRequest);
            var response = countChannel.SendRequest("hello");
            int result;

            using (response)
            {
                for (var i = 0; i < 5; i++)
                {
                    Assert.IsTrue(response.Receive(10000, out result));
                    Assert.AreEqual(result, i);
                }
                allSent.WaitOne(10000, false);
            }
            Assert.IsTrue(response.Receive(30000, out result));
            Assert.AreEqual(5, result);
            Assert.IsFalse(response.Receive(30000, out result));
        }
Пример #8
0
        public void RunForTime()
        {
            WorldCache.Instance.Clear();
            World world;

            WorldCache.Instance.TryCreate("TestWorld", new BoundingBox(new Vector(0f, 0f), new Vector(400f, 400f)), new Vector(40f, 40f), out world);


            List <Client> clients = SetupClients(world);

            Stopwatch t = Stopwatch.StartNew();

            using (var fiber = new PoolFiber(new FailSafeBatchExecutor()))
            {
                fiber.Start();
                fiber.ScheduleOnInterval(() => PrintStatsPerSecond(t), 1000, 1000);

                while (t.ElapsedMilliseconds < 10000)
                {
                    MoveClients(clients);
                    PrintStats(t);
                }
            }

            DisconnectClients(clients);
        }
Пример #9
0
        protected override void Setup()
        {
            Instance = this;
            this.InitLogging();

            log.InfoFormat("Setup: serverId={0}", ServerId);

            Protocol.AllowRawCustomValues = true;

            this.PublicIpAddress = PublicIPAddressReader.ParsePublicIpAddress(GameServerSettings.Default.PublicIPAddress);

            bool isMaster =
                PublicIPAddressReader.IsLocalIpAddress(this.MasterEndPoint.Address) ||
                this.MasterEndPoint.Address == this.PublicIpAddress;

            Counter.IsMasterServer.RawValue = isMaster ? 1 : 0;

            this.SetupFeedbackControlSystem();
            this.ConnectToMaster();

            if (GameServerSettings.Default.AppStatsPublishInterval > 0)
            {
                this.AppStatsPublisher = new ApplicationStatsPublisher(GameServerSettings.Default.AppStatsPublishInterval);
            }

            CounterPublisher.DefaultInstance.AddStaticCounterClass(
                typeof(Lite.Diagnostics.Counter), this.ApplicationName);
            CounterPublisher.DefaultInstance.AddStaticCounterClass(typeof(Counter), this.ApplicationName);

            this.executionFiber = new PoolFiber();
            this.executionFiber.Start();
            this.executionFiber.ScheduleOnInterval(this.CheckGames, 60000, 60000);
        }
Пример #10
0
        // ReSharper disable UnusedMember.Local
        void InitializeAndCreateHostedService <T>(Bootstrapper <T> bootstrapper)
        // ReSharper restore UnusedMember.Local
            where T : class
        {
            _log.DebugFormat("[{0}] Creating service type: {1}", _serviceName, typeof(T).ToShortTypeName());

            _fiber = new PoolFiber();

            _channel = HostChannelFactory.CreateShelfHost(_serviceName, AddEventForwarders);

            _controllerChannel.Send(new ShelfCreated(_serviceName, _channel.Address, _channel.PipeName));

            _host = HostFactory.New(x =>
            {
                x.SetServiceName(_serviceName);
                x.UseBuilder(description => new ShelfBuilder(description, _channel));

                x.Service <T>(s =>
                {
                    var serviceConfigurator = new ServiceConfiguratorImpl <T>(s);

                    bootstrapper.InitializeHostedService(serviceConfigurator);

                    s.SetServiceName(_serviceName);
                });
            });

            _host.Run();
        }
Пример #11
0
 // Methods
 private TemporaryServerPeer()
 {
     this.protocol       = DefaultProtocol;
     this.syncRoot       = new object();
     this.executionFiber = new PoolFiber();
     this.executionFiber.Start();
 }
Пример #12
0
        public void SingleConsumer()
        {
            var one = new PoolFiber();

            one.Start();
            var oneConsumed = 0;
            var reset       = new AutoResetEvent(false);

            using (one)
            {
                var          channel = new QueueChannel <int>();
                Action <int> onMsg   = delegate
                {
                    oneConsumed++;
                    if (oneConsumed == 20)
                    {
                        reset.Set();
                    }
                };
                channel.Subscribe(one, onMsg);
                for (var i = 0; i < 20; i++)
                {
                    channel.Publish(i);
                }
                Assert.IsTrue(reset.WaitOne(10000, false));
            }
        }
Пример #13
0
        public void Should_run_the_action_until_disabled()
        {
            Fiber     fiber     = new PoolFiber();
            Scheduler scheduler = new TimerScheduler(new PoolFiber());

            Stopwatch elapsed = Stopwatch.StartNew();

            int count  = 0;
            var called = new Future <int>();
            var failed = new Future <bool>();

            ScheduledOperation scheduledAction = null;

            scheduledAction = scheduler.Schedule(TimeSpan.Zero, 100.Milliseconds(), fiber, () =>
            {
                count++;
                if (count == 10)
                {
                    called.Complete(count);
                    scheduledAction.Cancel();
                }
                else if (count > 10)
                {
                    failed.Complete(true);
                }
            });

            called.WaitUntilCompleted(5.Seconds()).ShouldBeTrue();

            elapsed.Stop();

            failed.WaitUntilCompleted(200.Milliseconds()).ShouldBeFalse();

            Trace.WriteLine("Time Period: " + elapsed.ElapsedMilliseconds);
        }
Пример #14
0
        public void PointToPointPerfTest()
        {
            Channel <int> channel = new Channel <int>();
            IFiber        bus     = new PoolFiber();

            bus.Start();
            int            max   = 5000000;
            AutoResetEvent reset = new AutoResetEvent(false);
            Action <int>   onMsg = delegate(int count)
            {
                if (count == max)
                {
                    reset.Set();
                }
            };

            channel.Subscribe(bus, onMsg);
            using (new PerfTimer(max))
            {
                for (int i = 0; i <= max; i++)
                {
                    channel.Publish(i);
                }
                Assert.IsTrue(reset.WaitOne(30000, false));
            }
        }
Пример #15
0
        public void Run()
        {
            MmoWorld world;
            MmoWorldCache.Instance.Clear();
            MmoWorldCache.Instance.TryCreate("TestWorld", (new[] { 0f, 0f }).ToVector(), (new[] { 299f, 299f }).ToVector(), (new[] { 10f, 10f }).ToVector(), out world);

            List<Client> clients = SetupClients(world);

            Stopwatch t = Stopwatch.StartNew();
            using (var fiber = new PoolFiber(new FailSafeBatchExecutor()))
            {
                fiber.Start();
                fiber.ScheduleOnInterval(() => PrintStatsPerSecond(t), 1000, 1000);

                MoveClients(clients);
                PrintStats(t);
                MoveClients(clients);
                PrintStats(t);
                MoveClients(clients);
                PrintStats(t);
                MoveClients(clients);
                PrintStats(t);
                MoveClients(clients);
                PrintStats(t);
                log.Info("move completed");
                Assert.AreEqual(0, Client.Exceptions, "Exceptions occured at exit");

                DisconnectClients(clients);
            }
        }
Пример #16
0
        public void Run()
        {
            World world;

            WorldCache.Instance.Clear();
            WorldCache.Instance.TryCreate("TestWorld", new BoundingBox(new Vector(0f, 0f), new Vector(400f, 400f)), new Vector(40f, 40f), out world);

            List <Client> clients = SetupClients(world);

            Stopwatch t = Stopwatch.StartNew();

            using (var fiber = new PoolFiber(new FailSafeBatchExecutor()))
            {
                fiber.Start();
                fiber.ScheduleOnInterval(() => PrintStatsPerSecond(t), 1000, 1000);

                MoveClients(clients);
                PrintStats(t);
                MoveClients(clients);
                PrintStats(t);
                MoveClients(clients);
                PrintStats(t);
                MoveClients(clients);
                PrintStats(t);
                MoveClients(clients);
                PrintStats(t);
                log.Info("move completed");
                Assert.AreEqual(0, Client.Exceptions, "Exceptions occured at exit");

                DisconnectClients(clients);
            }
        }
        public IPluginFiber CreateFiber()
        {
            var fiber = new PoolFiber();

            fiber.Start();
            return(new PluginFiber(fiber));
        }
Пример #18
0
        public IFiber Build()
        {
            if (_executor == null)
            {
                _executor = new Executor();
            }
            IFiber fiber;

            switch (_type)
            {
            case FiberType.Thread:
                fiber = new ThreadFiber(_executor, new TimerScheduler(), _queue, _name, true, _priority);
                break;

            case FiberType.Pool:
                fiber = new PoolFiber(_executor);
                break;

            case FiberType.Stub:
                fiber = new StubFiber(_executor);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            return(fiber);
        }
Пример #19
0
 public void TestTwoFibers()
 {
     FiberTester.TestPubSubWExtraFiber(ThreadFiber.StartNew(), ThreadFiber.StartNew());
     FiberTester.TestPubSubWExtraFiber(PoolFiber.StartNew(), ThreadFiber.StartNew());
     FiberTester.TestPubSubWExtraFiber(PoolFiber.StartNew(), PoolFiber.StartNew());
     FiberTester.TestPubSubWExtraFiber(PoolFiber.StartNew(), StubFiber.StartNew());
 }
Пример #20
0
        public void Should_properly_invoke_the_message_receiver()
        {
            var fiber = new PoolFiber();
            _engine = new DynamicRoutingEngine(fiber);

            _receivedA = new Future<A>();
            _receivedB = new Future<B>();
            _receivedC = new Future<C>();
            _receivedMessageB = new Future<Message<B>>();
            _receivedMessageC = new Future<Message<C>>();

            _engine.Configure(x =>
                {
                    x.Receive<A>(_receivedA.Complete);
                    x.Receive<B>(_receivedB.Complete);
                    x.Receive<C>(_receivedC.Complete);
                    x.Receive<Message<B>>(_receivedMessageB.Complete);
                    x.Receive<Message<C>>(_receivedMessageC.Complete);
                });

            _engine.Send(new B());
            _engine.Send(new C());
            _engine.Send(new B());
            _engine.Send(new C());

            fiber.Shutdown(5.Minutes());
        }
Пример #21
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "Room" /> class.
 /// </summary>
 /// <param name = "name">
 ///   The room name.
 /// </param>
 /// <param name = "executionFiber">
 ///   The execution fiber used to synchronize access to this instance.
 /// </param>
 protected Room(string name, PoolFiber executionFiber)
 {
     this.name           = name;
     this.ExecutionFiber = executionFiber;
     this.Actors         = new ActorCollection();
     this.Properties     = new PropertyBag <object>();
 }
Пример #22
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "Room" /> class.
 /// </summary>
 /// <param name = "name">
 ///   The room name.
 /// </param>
 /// <param name = "executionFiber">
 ///   The execution fiber used to synchronize access to this instance.
 /// </param>
 protected Room(string name, PoolFiber executionFiber)
 {
     this.name = name;
     this.ExecutionFiber = executionFiber;
     this.Actors = new ActorCollection();
     this.Properties = new PropertyBag<object>();
 }
Пример #23
0
        public void SingleConsumerWithException()
        {
            var exec = new StubExecutor();
            var one  = new PoolFiber(new DefaultThreadPool(), exec);

            one.Start();
            var reset = new AutoResetEvent(false);

            using (one)
            {
                var          channel = new QueueChannel <int>();
                Action <int> onMsg   = delegate(int num)
                {
                    if (num == 0)
                    {
                        throw new Exception();
                    }
                    reset.Set();
                };
                channel.Subscribe(one, onMsg);
                channel.Publish(0);
                channel.Publish(1);
                Assert.IsTrue(reset.WaitOne(10000, false));
                Assert.AreEqual(1, exec.failed.Count);
            }
        }
Пример #24
0
        public static void Run()
        {
            loopFiber = new PoolFiber();
            loopFiber.Start();

            updateLoop = loopFiber.ScheduleOnInterval(Update, 0, 1000);
        }
Пример #25
0
        public void SingleConsumer()
        {
            int oneConsumed = 0;

            using (IFiber one = PoolFiber.StartNew())
                using (var reset = new AutoResetEvent(false))
                {
                    var channel = new QueueChannel <int>();

                    void OnMsg(int obj)
                    {
                        oneConsumed++;
                        if (oneConsumed == 20)
                        {
                            reset.Set();
                        }
                    }

                    channel.Subscribe(one, OnMsg);
                    for (int i = 0; i < 20; i++)
                    {
                        channel.Publish(i);
                    }
                    Assert.IsTrue(reset.WaitOne(10000, false));
                }
        }
Пример #26
0
        public void Adding_operations_to_a_fiber()
        {
            _count  = 10000;
            _values = new int[_count];
            Fiber fiber = new PoolFiber();

            int index     = 0;
            var completed = new Future <int>();

            var go = new Future <bool>();

            fiber.Add(() => { go.WaitUntilCompleted(10.Seconds()); });

            for (int i = 0; i < _count; i++)
            {
                int offset = i;
                fiber.Add(() =>
                {
                    _values[offset] = index++;

                    if (offset == _count - 1)
                    {
                        completed.Complete(offset);
                    }
                });
            }

            go.Complete(true);

            completed.WaitUntilCompleted(10.Seconds()).ShouldBeTrue();
        }
Пример #27
0
        public void Should_properly_invoke_the_message_receiver()
        {
            var fiber = new PoolFiber();

            _engine = new DynamicRoutingEngine(fiber);

            _receivedA        = new Future <A>();
            _receivedB        = new Future <B>();
            _receivedC        = new Future <C>();
            _receivedMessageB = new Future <Message <B> >();
            _receivedMessageC = new Future <Message <C> >();

            _engine.Configure(x =>
            {
                x.Receive <A>(_receivedA.Complete);
                x.Receive <B>(_receivedB.Complete);
                x.Receive <C>(_receivedC.Complete);
                x.Receive <Message <B> >(_receivedMessageB.Complete);
                x.Receive <Message <C> >(_receivedMessageC.Complete);
            });

            _engine.Send(new B());
            _engine.Send(new C());
            _engine.Send(new B());
            _engine.Send(new C());

            fiber.Shutdown(5.Minutes());
        }
Пример #28
0
 public void Setup()
 {
     _pool1 = PoolFiber.StartNew();
     _pool2 = new PoolFiber2();
     _pool2.Start();
     _spinPool = new SpinLockPoolFiber();
     _spinPool.Start();
 }
Пример #29
0
 private void StopExecute()
 {
     if (ExecuteFiber != null)
     {
         ExecuteFiber.Dispose();
         ExecuteFiber = new PoolFiber();
     }
 }
Пример #30
0
            public Ponger()
            {
                _fiber = new PoolFiber();

                Pinged = new Future <Ping>();

                PongChannel = new ConsumerChannel <Ping>(_fiber, HandlePing);
            }
Пример #31
0
        public DirectoryMonitor(string directory, IServiceChannel serviceChannel)
        {
            _pendingNotifications = new Dictionary<string, ScheduledOperation>();

            _baseDirectory = directory;
            _serviceChannel = serviceChannel;
            _fiber = new PoolFiber();
        }
Пример #32
0
        public TestClient(IPhotonPeerListener listener)
        {
            Listener = listener;

            PhotonClient = new PhotonPeer(this, ConnectionProtocol.Tcp);
            ServiceFiber = new PoolFiber();
            ExecuteFiber = new PoolFiber();
        }
Пример #33
0
 protected PeerBase(IRpcProtocol protocol, IPhotonPeer unmanagedPeer)
 {
     this.unmanagedPeer   = unmanagedPeer;
     this.connectionState = Photon.SocketServer.PeerConnectionStateMachine.Connected.Instance;
     this.protocol        = protocol;
     this.requestFiber    = new PoolFiber();
     this.requestFiber.Start();
 }
Пример #34
0
            public Auction(Guid id)
            {
                Id = id;

                Fiber = new PoolFiber();

                BidChannel = new ConsumerChannel <Bid>(Fiber, ReceiveBid);
            }
Пример #35
0
        public SomeActorInstance()
        {
            _fiber  = new PoolFiber();
            _future = new Future <MyMessage>();

            MessageChannel       = new ConsumerChannel <MyMessage>(_fiber, Consume);
            LambdaMessageChannel = new ConsumerChannel <MyMessage>(_fiber, message => _future.Complete(message));
        }
Пример #36
0
        public DirectoryMonitor(string directory, IServiceChannel serviceChannel)
        {
            _pendingNotifications = new Dictionary <string, ScheduledOperation>();

            _baseDirectory  = directory;
            _serviceChannel = serviceChannel;
            _fiber          = new PoolFiber();
        }
Пример #37
0
			public Auction(Guid id)
			{
				Id = id;

				Fiber = new PoolFiber();

				BidChannel = new ConsumerChannel<Bid>(Fiber, ReceiveBid);
			}
Пример #38
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "ClientConnection" /> class.
 /// </summary>
 /// <param name = "gameName">
 ///   The game Name.
 /// </param>
 /// <param name = "number">the player number</param>
 public ClientConnection(string gameName, int number)
 {
     // movement channel + data channel
     this.Peer = new PhotonPeer(this, Settings.Protocol) { ChannelCount = 2, DebugOut = Settings.LogLevel, TimePingInterval = Settings.PingInterval };
     this.GameName = gameName;
     this.Number = number;
     this.State = Disconnected.Instance;
     this.fiber = new PoolFiber(new FailSafeBatchExecutor());
     this.fiber.Start();
     this.Peer.DebugOut = DebugLevel.WARNING;
 }
Пример #39
0
		public void Should_wait_until_the_appropriate_time_for_the_action_to_execute()
		{
			Fiber fiber = new PoolFiber();
			Scheduler scheduler = new TimerScheduler(new SynchronousFiber());

			var called = new Future<bool>();

			scheduler.Schedule(100.Milliseconds(), fiber, () => called.Complete(true));

			called.IsCompleted.ShouldBeFalse();

			called.WaitUntilCompleted(1.Seconds()).ShouldBeTrue();
		}
Пример #40
0
		public void Should_not_run_any_pending_actions()
		{
			Fiber fiber = new PoolFiber();
			Scheduler scheduler = new TimerScheduler(new PoolFiber());

			var called = new Future<bool>();

			scheduler.Schedule(1.Seconds(), fiber, () => called.Complete(true));

			scheduler.Stop(60.Seconds());

			called.WaitUntilCompleted(2.Seconds()).ShouldBeFalse();
		}
Пример #41
0
        public LobbyStatsPublisher(LobbyFactory lobbyFactory, int publishIntervalSeconds, int maxLobbyStatsCount)
        {
            this.lobbyFactory = lobbyFactory;
            this.maxLobbyStatsCount = maxLobbyStatsCount;
            this.subscriber = new HashSet<PeerBase>();

            this.fiber = new PoolFiber();
            this.fiber.Start();

            if (publishIntervalSeconds > 0)
            {
                this.schedule = this.fiber.ScheduleOnInterval(this.BroadcastStatisticEvent, 0, publishIntervalSeconds * 1000);
            }
        }
Пример #42
0
		public void Should_prevent_new_actions_from_being_queued()
		{
			Fiber fiber = new PoolFiber();

			var called = new Future<bool>();

			fiber.Stop();

			fiber.Add(() => called.Complete(true));

			fiber.Shutdown(10.Seconds());

			called.IsCompleted.ShouldBeFalse();
		}
Пример #43
0
		public void Should_properly_release_one_waiting_writer()
		{
			const int writerCount = 10;
			const int messageCount = 1000;

			var complete = new Future<bool>();
			int total = 0;

			Fiber reader = new ThreadFiber();
			
			try
			{
				Thread.Sleep(100);

				Stopwatch timer = Stopwatch.StartNew();

				var writers = new List<Fiber>();
				for (int i = 0; i < writerCount; i++)
				{
					Fiber fiber = new PoolFiber();
					for (int j = 0; j < messageCount; j++)
					{
						fiber.Add(() =>
							{
								SuperSleeper.Wait(1);

								reader.Add(() =>
									{
										total++;
										if (total == writerCount*messageCount)
											complete.Complete(true);
									});
							});
					}

					writers.Add(fiber);
				}

				complete.WaitUntilCompleted(20.Seconds()).ShouldBeTrue();

				timer.Stop();

				Trace.WriteLine("Elapsed time: " + timer.ElapsedMilliseconds + "ms (expected " + writerCount*messageCount + ")");
			}
			finally
			{
				reader.Stop();
			}
		}
Пример #44
0
		public void Should_result_in_no_waiting_actions_in_the_queue()
		{
			Fiber fiber = new PoolFiber();

			var called = new Future<bool>();

			10.Times(() => fiber.Add(() => Thread.Sleep(100)));
			fiber.Add(() => called.Complete(true));

			Stopwatch timer = Stopwatch.StartNew();

			fiber.Shutdown(8.Seconds());

			timer.Stop();

			called.IsCompleted.ShouldBeTrue();

			timer.ElapsedMilliseconds.ShouldBeLessThan(2000);
		}
Пример #45
0
        public GameApplication(string applicationId, string version, LoadBalancer<IncomingGameServerPeer> loadBalancer)
        {
            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Creating application: appId={0}", applicationId);
            }

            this.ApplicationId = applicationId;
            this.LoadBalancer = loadBalancer;
            this.Version = version;
            this.PlayerOnlineCache = new PlayerCache();
            this.LobbyFactory = new LobbyFactory(this);
            this.LobbyFactory.Initialize();
            this.LobbyStatsPublisher = new LobbyStatsPublisher(
                this.LobbyFactory,
                MasterServerSettings.Default.LobbyStatsPublishInterval,
                MasterServerSettings.Default.LobbyStatsLimit);

            this.fiber = new PoolFiber();
            this.fiber.Start();

            if (MasterServerSettings.Default.PersistentGameExpiryMinute != 0)
            {
                var checkTime = MasterServerSettings.Default.GameExpiryCheckPeriod * 60000;
                this.expiryCheckDisposable = this.fiber.Schedule(this.CheckExpiredGames, checkTime);
            }

            this.SetupTokenCreator();

            this.UpdatePluginTraits();

            if (!this.ConnectToRedis())
            {
                return;
            }

            this.PopulateGameListFromRedis();
        }
Пример #46
0
 protected GameLogic(PoolFiber executionFiber)
 {
     this.ExecutionFiber = executionFiber;
     currentRound = 1;
     this.ScheduleUpdate();
 }
Пример #47
0
        protected override void Setup()
        {
            this.InitLogging();

            log.InfoFormat("Setup: serverId={0}", ServerId);

            Protocol.AllowRawCustomValues = true;
            Protocol.RegisterTypeMapper(new UnknownTypeMapper());

            this.PublicIpAddress = PublicIPAddressReader.ParsePublicIpAddress(GameServerSettings.Default.PublicIPAddress);
            this.PublicIpAddressIPv6 = string.IsNullOrEmpty(GameServerSettings.Default.PublicIPAddressIPv6) ? null : IPAddress.Parse(GameServerSettings.Default.PublicIPAddressIPv6);

            this.IsMaster = PublicIPAddressReader.IsLocalIpAddress(this.MasterEndPoint.Address) || this.MasterEndPoint.Address.Equals(this.PublicIpAddress);

            Counter.IsMasterServer.RawValue = this.IsMaster ? 1 : 0;

            this.GameCache = new GameCache(this);

            if (CommonSettings.Default.EnablePerformanceCounters)
            {
                HttpQueuePerformanceCounters.Initialize();
            }
            else
            {
                log.Info("Performance counters are disabled");
            }

            this.SetupTokenCreator();
            this.SetupFeedbackControlSystem();
            this.SetupServerStateMonitor();
            this.SetupMasterConnection();

            if (GameServerSettings.Default.AppStatsPublishInterval > 0)
            {
                this.AppStatsPublisher = new ApplicationStatsPublisher(this, GameServerSettings.Default.AppStatsPublishInterval);
            }

            CounterPublisher.DefaultInstance.AddStaticCounterClass(typeof(Hive.Diagnostics.Counter), this.ApplicationName);
            CounterPublisher.DefaultInstance.AddStaticCounterClass(typeof(Counter), this.ApplicationName);

            this.executionFiber = new PoolFiber();
            this.executionFiber.Start();
            this.executionFiber.ScheduleOnInterval(this.CheckGames, 60000, 60000);
        }
Пример #48
0
 public ApplicationStats(int publishIntervalMs)
 {
     this.publishIntervalMs = publishIntervalMs;
     this.fiber = new PoolFiber();
     this.fiber.Start();
 }
Пример #49
0
 public PlayerCache()
 {
     this.fiber = new PoolFiber();
     this.fiber.Start();
 }
Пример #50
0
		public void Should_run_the_action_until_disabled()
		{
			Fiber fiber = new PoolFiber();
			Scheduler scheduler = new TimerScheduler(new PoolFiber());

			Stopwatch elapsed = Stopwatch.StartNew();

			int count = 0;
			var called = new Future<int>();
			var failed = new Future<bool>();

			ScheduledOperation scheduledAction = null;
			scheduledAction = scheduler.Schedule(TimeSpan.Zero, 100.Milliseconds(), fiber, () =>
				{
					count++;
					if (count == 10)
					{
						called.Complete(count);
						scheduledAction.Cancel();
					}
					else if (count > 10)
					{
						failed.Complete(true);
					}
				});

			called.WaitUntilCompleted(5.Seconds()).ShouldBeTrue();

			elapsed.Stop();

			failed.WaitUntilCompleted(200.Milliseconds()).ShouldBeFalse();

			Trace.WriteLine("Time Period: " + elapsed.ElapsedMilliseconds);
		}
Пример #51
0
		public void Should_not_stall_the_scheduler()
		{
			Fiber stopped = new PoolFiber();
			stopped.Stop();

			Fiber running = new PoolFiber();
			Scheduler scheduler = new TimerScheduler(new PoolFiber());

			var called = new Future<bool>();

			scheduler.Schedule(200.Milliseconds(), stopped, () => { });
			scheduler.Schedule(400.Milliseconds(), running, () => called.Complete(true));

			called.WaitUntilCompleted(2.Seconds()).ShouldBeTrue();
		}
        public ClientAuthenticationQueue(string uri, string queryStringParameters, bool rejectIfUnavailable, int requestTimeout)
        {
            this.Uri = uri;
            this.QueryStringParameters = queryStringParameters;

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Create authentication queue for adress {0}", this.Uri);
            }

            this.requestTimeoutMilliseconds = requestTimeout;
            this.RejectIfUnavailable = rejectIfUnavailable;

            this.fiber = new PoolFiber();

            this.httpRequestQueue = new HttpRequestQueue(this.fiber);
        }
Пример #53
0
 public DirectoryMonitor(string directory, IServiceChannel serviceChannel)
 {
     _baseDirectory = directory;
     _serviceChannel = serviceChannel;
     _fiber = new PoolFiber();
 }
Пример #54
0
 public CustomAuthHandler(IHttpRequestQueueCountersFactory factory)
 {
     this.fiber = new PoolFiber();
     this.fiber.Start();
     this.httpQueueCountersFactory = factory;
 }
Пример #55
0
 public GameRoom(int id)
 {
     this.id = id;
     ExecutionFiber = new PoolFiber();
     ExecutionFiber.Start();
 }
Пример #56
0
        public void RunForTime()
        {
            MmoWorldCache.Instance.Clear();
            MmoWorld world;
            MmoWorldCache.Instance.TryCreate("TestWorld", (new[] { 0f, 0f }).ToVector(), (new[] { 299f, 299f }).ToVector(), (new[] { 10f, 10f }).ToVector(), out world);

            List<Client> clients = SetupClients(world);

            Stopwatch t = Stopwatch.StartNew();
            using (var fiber = new PoolFiber(new FailSafeBatchExecutor()))
            {
                fiber.Start();
                fiber.ScheduleOnInterval(() => PrintStatsPerSecond(t), 1000, 1000);

                while (t.ElapsedMilliseconds < 10000)
                {
                    MoveClients(clients);
                    PrintStats(t);
                }
            }

            DisconnectClients(clients);
        }
Пример #57
0
        protected override void Setup()
        {
            Instance = this;
            this.InitLogging();

            log.InfoFormat("Setup: serverId={0}", ServerId);

            Protocol.AllowRawCustomValues = true;

            this.PublicIpAddress = PublicIPAddressReader.ParsePublicIpAddress(GameServerSettings.Default.PublicIPAddress);

            bool isMaster =
                PublicIPAddressReader.IsLocalIpAddress(this.MasterEndPoint.Address)
                || this.MasterEndPoint.Address.Equals(this.PublicIpAddress);

            Counter.IsMasterServer.RawValue = isMaster ? 1 : 0; 

            this.SetupFeedbackControlSystem();
            this.ConnectToMaster();

            if (GameServerSettings.Default.AppStatsPublishInterval > 0)
            {
                this.AppStatsPublisher = new ApplicationStatsPublisher(GameServerSettings.Default.AppStatsPublishInterval);
            }

            CounterPublisher.DefaultInstance.AddStaticCounterClass(
                typeof(Lite.Diagnostics.Counter), this.ApplicationName);
            CounterPublisher.DefaultInstance.AddStaticCounterClass(typeof(Counter), this.ApplicationName);

            this.executionFiber = new PoolFiber();
            this.executionFiber.Start();
            this.executionFiber.ScheduleOnInterval(this.CheckGames, 60000, 60000);
        }
        public WorkloadController(
            ApplicationBase application, string instanceName, string applicationName, IPEndPoint latencyEndpointTcp, IPEndPoint latencyEndpointUdp, byte latencyOperationCode, long updateIntervalInMs)
        {
            this.latencyOperationCode = latencyOperationCode;
            this.updateIntervalInMs = updateIntervalInMs;
            this.FeedbackLevel = FeedbackLevel.Normal;
            this.application = application;
            this.applicationName = applicationName;

            this.fiber = new PoolFiber();
            this.fiber.Start();

            this.remoteEndPointTcp = latencyEndpointTcp;
            this.remoteEndPointUdp = latencyEndpointUdp;

            this.cpuCounter = new AverageCounterReader(AverageHistoryLength, "Processor", "% Processor Time", "_Total");
            if (!this.cpuCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.cpuCounter.Name);
            }

            this.businessLogicQueueCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: Threads and Queues", "Business Logic Queue", instanceName);
            if (!this.businessLogicQueueCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.businessLogicQueueCounter.Name);
            }

            this.enetQueueCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: Threads and Queues", "ENet Queue", instanceName);
            if (!this.enetQueueCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.enetQueueCounter.Name);
            }

            // amazon instances do not have counter for network interfaces
            this.bytesInCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server", "bytes in/sec", instanceName);
            if (!this.bytesInCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.bytesInCounter.Name);
            }

            this.bytesOutCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server", "bytes out/sec", instanceName);
            if (!this.bytesOutCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.bytesOutCounter.Name);
            }

            this.enetThreadsProcessingCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: Threads and Queues", "ENet Threads Processing", instanceName);
            if (!this.enetThreadsProcessingCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.enetThreadsProcessingCounter.Name);
            }

            this.enetThreadsActiveCounter = new PerformanceCounterReader("Photon Socket Server: Threads and Queues", "ENet Threads Active", instanceName);
            if (!this.enetThreadsActiveCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.enetThreadsActiveCounter.Name);
            }

            this.timeSpentInServerInCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: ENet", "Time Spent In Server: In (ms)", instanceName);
            if (!this.timeSpentInServerInCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.timeSpentInServerInCounter.Name);
            }

            this.timeSpentInServerOutCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: ENet", "Time Spent In Server: Out (ms)", instanceName);
            if (!this.timeSpentInServerOutCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.timeSpentInServerOutCounter.Name);
            }
            
            this.tcpDisconnectsPerSecondCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: TCP", "TCP: Disconnected Peers +/sec", instanceName); 
            if (!this.tcpDisconnectsPerSecondCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.tcpDisconnectsPerSecondCounter.Name);
            }

            this.tcpClientDisconnectsPerSecondCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: TCP", "TCP: Disconnected Peers (C) +/sec", instanceName);
            if (!this.tcpClientDisconnectsPerSecondCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.tcpClientDisconnectsPerSecondCounter.Name);
            }


            this.tcpPeersCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: TCP", "TCP: Peers", instanceName);
            if (!this.tcpPeersCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.tcpPeersCounter.Name);
            }

            this.udpDisconnectsPerSecondCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: UDP", "UDP: Disconnected Peers +/sec", instanceName);
            if (!this.udpDisconnectsPerSecondCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.udpDisconnectsPerSecondCounter.Name);
            }

            this.udpClientDisconnectsPerSecondCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: UDP", "UDP: Disconnected Peers (C) +/sec", instanceName);
            if (!this.udpClientDisconnectsPerSecondCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.udpClientDisconnectsPerSecondCounter.Name);
            }

            this.udpPeersCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: UDP", "UDP: Peers", instanceName);
            if (!this.udpPeersCounter.InstanceExists)
            {
                log.WarnFormat("Did not find counter {0}", this.udpPeersCounter.Name);
            }

            this.feedbackControlSystem = new FeedbackControlSystem(1000, this.application.ApplicationRootPath);
        }
Пример #59
0
        public WorkloadController(
            ApplicationBase application, string instanceName, long updateIntervalInMs, string serverId, string workLoadConfigFile)
        {
            try
            {
                this.updateIntervalInMs = updateIntervalInMs;
                this.FeedbackLevel = FeedbackLevel.Normal;
                this.application = application;

                this.fiber = new PoolFiber();
                this.fiber.Start();
                this.serverId = serverId;

                this.cpuCounter = new AverageCounterReader(AverageHistoryLength, "Processor", "% Processor Time", "_Total");
                if (!this.cpuCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.cpuCounter.Name);
                }

                this.businessLogicQueueCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: Threads and Queues", "Business Logic Queue", instanceName);
                if (!this.businessLogicQueueCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.businessLogicQueueCounter.Name);
                }

                this.enetQueueCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: Threads and Queues", "ENet Queue", instanceName);
                if (!this.enetQueueCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.enetQueueCounter.Name);
                }

                // amazon instances do not have counter for network interfaces
                this.bytesInCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server", "bytes in/sec", instanceName);
                if (!this.bytesInCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.bytesInCounter.Name);
                }

                this.bytesOutCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server", "bytes out/sec", instanceName);
                if (!this.bytesOutCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.bytesOutCounter.Name);
                }

                this.enetThreadsProcessingCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: Threads and Queues", "ENet Threads Processing", instanceName);
                if (!this.enetThreadsProcessingCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.enetThreadsProcessingCounter.Name);
                }

                this.enetThreadsActiveCounter = new PerformanceCounterReader("Photon Socket Server: Threads and Queues", "ENet Threads Active", instanceName);
                if (!this.enetThreadsActiveCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.enetThreadsActiveCounter.Name);
                }

                this.timeSpentInServerInCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: ENet", "Time Spent In Server: In (ms)", instanceName);
                if (!this.timeSpentInServerInCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.timeSpentInServerInCounter.Name);
                }

                this.timeSpentInServerOutCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: ENet", "Time Spent In Server: Out (ms)", instanceName);
                if (!this.timeSpentInServerOutCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.timeSpentInServerOutCounter.Name);
                }

                this.tcpDisconnectsPerSecondCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: TCP", "TCP: Disconnected Peers +/sec", instanceName);
                if (!this.tcpDisconnectsPerSecondCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.tcpDisconnectsPerSecondCounter.Name);
                }

                this.tcpClientDisconnectsPerSecondCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: TCP", "TCP: Disconnected Peers (C) +/sec", instanceName);
                if (!this.tcpClientDisconnectsPerSecondCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.tcpClientDisconnectsPerSecondCounter.Name);
                }

                this.tcpPeersCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: TCP", "TCP: Peers", instanceName);
                if (!this.tcpPeersCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.tcpPeersCounter.Name);
                }

                this.udpDisconnectsPerSecondCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: UDP", "UDP: Disconnected Peers +/sec", instanceName);
                if (!this.udpDisconnectsPerSecondCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.udpDisconnectsPerSecondCounter.Name);
                }

                this.udpClientDisconnectsPerSecondCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: UDP", "UDP: Disconnected Peers (C) +/sec", instanceName);
                if (!this.udpClientDisconnectsPerSecondCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.udpClientDisconnectsPerSecondCounter.Name);
                }

                this.udpPeersCounter = new AverageCounterReader(AverageHistoryLength, "Photon Socket Server: UDP", "UDP: Peers", instanceName);
                if (!this.udpPeersCounter.InstanceExists)
                {
                    log.WarnFormat("Did not find counter {0}", this.udpPeersCounter.Name);
                }

                this.feedbackControlSystem = new FeedbackControlSystem(1000, this.application.ApplicationRootPath, workLoadConfigFile);

                this.IsInitialized = true;
            }
            catch (Exception e)
            {
                log.ErrorFormat("Exception during WorkloadController construction. Exception: {0}", e);
            }
        }
Пример #60
-1
		public void Should_run_the_action_immediately()
		{
			Fiber fiber = new PoolFiber();
			Scheduler scheduler = new TimerScheduler(new SynchronousFiber());

			var called = new Future<bool>();

			scheduler.Schedule(TimeSpan.Zero, fiber, () => called.Complete(true));

			called.WaitUntilCompleted(1.Seconds()).ShouldBeTrue();
		}