Exemplo n.º 1
0
 public IActorRef ChildActorOf <T>()
     where T : ActorBase
 {
     return(((TestKitBase)this).ChildActorOf(Props.Create <T>()));
 }
Exemplo n.º 2
0
        public void ConnectToStreamingServerAndProcessSnapshot()
        {
            //
            //Arrange
            //
            Fixture snapshot;
            Mock <IResourceFacade> resourceFacadeMock;

            SetupCommonMockObjects(
                /*sport*/ FootabllSportMock.Object.Name,
                /*fixtureData*/ FixtureSamples.football_setup_snapshot_2,
                /*storedData*/ new { Epoch = 3, Sequence = 1, MatchStatus = MatchStatus.Setup },
                out snapshot,
                out resourceFacadeMock);
            ServiceMock.Setup(o => o.GetResources(It.Is <string>(s => s.Equals(FootabllSportMock.Object.Name))))
            .Returns(new List <IResourceFacade> {
                resourceFacadeMock.Object
            });
            StreamHealthCheckValidationMock.Setup(a =>
                                                  a.CanConnectToStreamServer(
                                                      It.IsAny <IResourceFacade>(),
                                                      It.IsAny <StreamListenerState>()))
            .Returns(false);
            SettingsMock.SetupGet(a => a.AllowFixtureStreamingInSetupMode).Returns(false);
            FixtureValidationMock.Setup(a =>
                                        a.IsSnapshotNeeded(
                                            It.IsAny <IResourceFacade>(),
                                            It.IsAny <FixtureState>()))
            .Returns(true);

            //
            //Act
            //
            var streamListenerManagerActor =
                ActorOfAsTestActorRef <StreamListenerManagerActor>(
                    Props.Create(() =>
                                 new StreamListenerManagerActor(
                                     SettingsMock.Object,
                                     PluginMock.Object,
                                     StateManagerMock.Object,
                                     SuspensionManagerMock.Object,
                                     StreamHealthCheckValidationMock.Object,
                                     FixtureValidationMock.Object)),
                    StreamListenerManagerActor.ActorName);
            var sportProcessorRouterActor =
                ActorOfAsTestActorRef <SportProcessorRouterActor>(
                    Props.Create(() => new SportProcessorRouterActor(ServiceMock.Object))
                    .WithRouter(new SmallestMailboxPool(SettingsMock.Object.FixtureCreationConcurrency)),
                    SportProcessorRouterActor.ActorName);

            sportProcessorRouterActor.Tell(new ProcessSportMsg {
                Sport = FootabllSportMock.Object.Name
            });

            IActorRef           streamListenerActorRef;
            StreamListenerActor streamListenerActor = null;
            IActorRef           resourceActorRef;
            IActorRef           healthCheckActorRef;

            //Get child actors instances
            AwaitAssert(() =>
            {
                streamListenerActorRef =
                    GetChildActorRef(
                        streamListenerManagerActor,
                        StreamListenerActor.GetName(resourceFacadeMock.Object.Id));
                streamListenerActor = GetUnderlyingActor <StreamListenerActor>(streamListenerActorRef);
                resourceActorRef    = GetChildActorRef(streamListenerActorRef, ResourceActor.ActorName);
                healthCheckActorRef = GetChildActorRef(streamListenerActorRef, StreamHealthCheckActor.ActorName);
                Assert.NotNull(streamListenerActorRef);
                Assert.NotNull(streamListenerActor);
                Assert.NotNull(resourceActorRef);
                Assert.NotNull(healthCheckActorRef);

                Assert.AreEqual(StreamListenerState.Initialized, streamListenerActor.State);
            },
                        TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT),
                        TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL));

            StreamHealthCheckValidationMock.Reset();
            StreamHealthCheckValidationMock.Setup(a =>
                                                  a.CanConnectToStreamServer(
                                                      It.IsAny <IResourceFacade>(),
                                                      It.IsAny <StreamListenerState>()))
            .Returns(true);
            StreamHealthCheckValidationMock.Setup(a =>
                                                  a.ValidateStream(
                                                      It.IsAny <IResourceFacade>(),
                                                      It.IsAny <StreamListenerState>(),
                                                      It.IsAny <int>()))
            .Returns(true);
            //This call will trigger health check message
            sportProcessorRouterActor.Tell(new ProcessSportMsg {
                Sport = FootabllSportMock.Object.Name
            });

            //
            //Assert
            //
            AwaitAssert(() =>
            {
                resourceFacadeMock.Verify(a => a.GetSnapshot(), Times.Exactly(2));
                PluginMock.Verify(a =>
                                  a.ProcessSnapshot(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), false),
                                  Times.Exactly(2));
                PluginMock.Verify(a =>
                                  a.ProcessSnapshot(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), true),
                                  Times.Never);
                PluginMock.Verify(a =>
                                  a.ProcessMatchStatus(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id))),
                                  Times.Never);
                SuspensionManagerMock.Verify(a =>
                                             a.Unsuspend(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id))),
                                             Times.Never);
                SuspensionManagerMock.Verify(a =>
                                             a.Suspend(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)),
                                                       SuspensionReason.SUSPENSION),
                                             Times.Never);
                Assert.AreEqual(StreamListenerState.Streaming, streamListenerActor.State);
            },
                        TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT),
                        TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL));
        }
 public static IActorRef CategoryQueryAggregate(this IActorRefFactory system)
 {
     return(system.ActorOf(Props.Create <CategoryQueryActor>(), SystemData.CategoryQueryActor.Name));
 }
 protected override void PreStart()
 {
     _child = Context.ActorOf(Props.Create(() => new RequesterActor(_providerActor)));
 }
Exemplo n.º 5
0
        /// <summary>
        ///		Create a new <see cref="Connector"/> actor.
        /// </summary>
        public Connector()
        {
            Receive <Tcp.Bound>(bound =>
            {
                _listenerEndPoint = bound.LocalAddress as IPEndPoint;

                Log.Verbose("Connection manager is now listening on {ListenEndPoint}.", FormatEndPointIPv4(_listenerEndPoint));
            });

            // Remote client has connected. For now, we just assume they're JVM Akka (big-endian).
            Receive <Tcp.Connected>(connected =>
            {
                IPEndPoint remoteEndPoint = connected.RemoteAddress as IPEndPoint;
                string remoteEndPointIPv4 = FormatEndPointIPv4(remoteEndPoint);

                Log.Verbose("Connection manager is handling connection from {RemoteEndPoint}.", remoteEndPointIPv4);

                string handlerActorName = "printer-for-" + remoteEndPointIPv4;

                IActorRef printHandler = Context.ActorOf(
                    Props.Create(
                        () => new Printer(remoteEndPoint)
                        ),
                    handlerActorName
                    );
                _printHandlers.Add(printHandler);

                Context.Watch(printHandler);

                Sender.Tell(
                    new Tcp.Register(printHandler)
                    );
            });

            // Client has been disconnected.
            Receive <Disconnected>(disconnected =>
            {
                Log.Verbose(
                    "Connection manager is handling disconnection from {RemoteEndPoint}.",
                    FormatEndPointIPv4(disconnected.RemoteEndPoint)
                    );

                IActorRef printer = Sender;
                if (!_printHandlers.Contains(printer))
                {
                    Log.Warning(
                        "Connection manager received disconnection notice for unknown end-point {RemoteEndPoint}.",
                        FormatEndPointIPv4(disconnected.RemoteEndPoint)
                        );

                    return;
                }

                printer.Tell(PoisonPill.Instance);                 // Like tears in rain, time to die.
            });

            // A Printer actor has been terminated.
            Receive <Terminated>(terminated =>
            {
                IActorRef printer = _printHandlers.Find(handler => handler.Path == Sender.Path);
                if (printer == null)
                {
                    Log.Warning(
                        "Connection manager was notified of termination for unknown child actor '{TerminatedActorName}'.",
                        terminated.ActorRef.Path.ToStringWithoutAddress()
                        );

                    Unhandled(terminated);

                    return;
                }

                Log.Verbose(
                    "Connection manager is handling termination of child actor '{TerminatedActorName}'.",
                    terminated.ActorRef.Path.Name
                    );
                _printHandlers.Remove(printer);
            });
        }
Exemplo n.º 6
0
        public void GivenIHaveAVillager()
        {
            var props = Props.Create <VillagerActor>(_resourcesSupervisor, _subroutinesFactory);

            _villagerActor = ActorOfAsTestActorRef <VillagerActor>(props);
        }
        public void TestConcurrentStreamListenerCreationLimit()
        {
            //
            //Arrange
            //
            SettingsMock.SetupGet(a => a.FixtureCreationConcurrency).Returns(3);
            var resource1FacadeMock = new Mock <IResourceFacade>();
            var resource2FacadeMock = new Mock <IResourceFacade>();
            var resource3FacadeMock = new Mock <IResourceFacade>();
            var resource4FacadeMock = new Mock <IResourceFacade>();
            var resource5FacadeMock = new Mock <IResourceFacade>();

            resource1FacadeMock.Setup(o => o.Id).Returns("Fixture1Id");
            resource2FacadeMock.Setup(o => o.Id).Returns("Fixture2Id");
            resource3FacadeMock.Setup(o => o.Id).Returns("Fixture3Id");
            resource4FacadeMock.Setup(o => o.Id).Returns("Fixture4Id");
            resource5FacadeMock.Setup(o => o.Id).Returns("Fixture5Id");

            //
            //Act
            //
            var streamListenerBuilderActorRef =
                ActorOfAsTestActorRef <StreamListenerBuilderActor>(
                    Props.Create(() =>
                                 new StreamListenerBuilderActor(
                                     SettingsMock.Object,
                                     new Mock <IActorContext>().Object,
                                     PluginMock.Object,
                                     StateManagerMock.Object,
                                     SuspensionManagerMock.Object,
                                     StreamHealthCheckValidationMock.Object,
                                     FixtureValidationMock.Object)),
                    StreamListenerBuilderActor.ActorName);

            //
            //Assert
            //
            AwaitAssert(() =>
            {
                Assert.AreEqual(
                    StreamListenerBuilderState.Active,
                    streamListenerBuilderActorRef.UnderlyingActor.State);
            },
                        TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT),
                        TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL));

            //
            //Act
            //
            streamListenerBuilderActorRef.Tell(new CreateStreamListenerMsg {
                Resource = resource1FacadeMock.Object
            });
            Task.Delay(TimeSpan.FromMilliseconds(50));
            streamListenerBuilderActorRef.Tell(new CreateStreamListenerMsg {
                Resource = resource2FacadeMock.Object
            });
            Task.Delay(TimeSpan.FromMilliseconds(50));
            streamListenerBuilderActorRef.Tell(new CreateStreamListenerMsg {
                Resource = resource3FacadeMock.Object
            });
            Task.Delay(TimeSpan.FromMilliseconds(50));
            streamListenerBuilderActorRef.Tell(new CreateStreamListenerMsg {
                Resource = resource4FacadeMock.Object
            });
            Task.Delay(TimeSpan.FromMilliseconds(50));
            streamListenerBuilderActorRef.Tell(new CreateStreamListenerMsg {
                Resource = resource5FacadeMock.Object
            });

            //
            //Assert
            //
            AwaitAssert(() =>
            {
                Assert.AreEqual(
                    StreamListenerBuilderState.Busy,
                    streamListenerBuilderActorRef.UnderlyingActor.State);
            },
                        TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT),
                        TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL));

            //
            //Act
            //
            Task.Delay(TimeSpan.FromMilliseconds(50));
            streamListenerBuilderActorRef.Tell(new StreamListenerCreationCompletedMsg {
                FixtureId = resource1FacadeMock.Object.Id
            });
            Task.Delay(TimeSpan.FromMilliseconds(50));
            streamListenerBuilderActorRef.Tell(new StreamListenerCreationCompletedMsg {
                FixtureId = resource2FacadeMock.Object.Id
            });
            Task.Delay(TimeSpan.FromMilliseconds(50));
            streamListenerBuilderActorRef.Tell(new StreamListenerCreationFailedMsg {
                FixtureId = resource4FacadeMock.Object.Id
            });

            //
            //Assert
            //
            AwaitAssert(() =>
            {
                Assert.AreEqual(
                    StreamListenerBuilderState.Active,
                    streamListenerBuilderActorRef.UnderlyingActor.State);
            },
                        TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT),
                        TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL));
        }
Exemplo n.º 8
0
 /// <summary>
 /// Create a new actor as child of <see cref="Sys" />.
 /// </summary>
 /// <typeparam name="TActor">The type of the actor. It must have a parameterless public constructor</typeparam>
 public IActorRef ActorOf <TActor>() where TActor : ActorBase, new()
 {
     return(Sys.ActorOf(Props.Create <TActor>(), null));
 }
Exemplo n.º 9
0
 /// <summary>
 /// Create a new actor as child of <see cref="Sys" />.
 /// </summary>
 /// <typeparam name="TActor">The type of the actor. It must have a parameterless public constructor</typeparam>
 /// <param name="name">The name of the actor.</param>
 public IActorRef ActorOf <TActor>(string name) where TActor : ActorBase, new()
 {
     return(Sys.ActorOf(Props.Create <TActor>(), name));
 }
Exemplo n.º 10
0
 /// <summary>
 /// Create a new <see cref="FSM{TState,TData}"/> as child of <see cref="Sys"/>
 /// and returns it as <see cref="TestFSMRef{TActor,TState,TData}"/> to enable inspecting and modifying the FSM directly.
 /// <typeparamref name="TFsmActor"/> must have a public parameterless constructor.
 /// </summary>
 /// <typeparam name="TFsmActor">The type of the actor. It must have a parameterless public constructor</typeparam>
 /// <typeparam name="TState">The type of state name</typeparam>
 /// <typeparam name="TData">The type of state data</typeparam>
 /// <param name="name">Optional: The name.</param>
 /// <param name="withLogging">Optional: If set to <c>true</c> logs state changes of the FSM as Debug messages. Default is <c>false</c>.</param>
 public TestFSMRef <TFsmActor, TState, TData> ActorOfAsTestFSMRef <TFsmActor, TState, TData>(string name = null, bool withLogging = false)
     where TFsmActor : FSM <TState, TData>, new()
 {
     return(new TestFSMRef <TFsmActor, TState, TData>(Sys, Props.Create <TFsmActor>(), NoSupervisor, name, withLogging));
 }
Exemplo n.º 11
0
 /// <summary>
 /// Create a new <see cref="FSM{TState,TData}"/> as child of <see cref="Sys"/>
 /// and returns it as <see cref="TestFSMRef{TActor,TState,TData}"/> to enable inspecting and modifying the FSM directly.
 /// Uses an expression that calls the constructor of <typeparamref name="TFsmActor"/>.
 /// </summary>
 /// <typeparam name="TFsmActor">The type of the actor.</typeparam>
 /// <typeparam name="TState">The type of state name</typeparam>
 /// <typeparam name="TData">The type of state data</typeparam>
 /// <param name="factory">An expression that calls the constructor of <typeparamref name="TFsmActor"/></param>
 /// <param name="name">Optional: The name.</param>
 /// <param name="withLogging">Optional: If set to <c>true</c> logs state changes of the FSM as Debug messages. Default is <c>false</c>.</param>
 public TestFSMRef <TFsmActor, TState, TData> ActorOfAsTestFSMRef <TFsmActor, TState, TData>(Expression <Func <TFsmActor> > factory, string name = null, bool withLogging = false)
     where TFsmActor : FSM <TState, TData>
 {
     return(new TestFSMRef <TFsmActor, TState, TData>(Sys, Props.Create(factory), NoSupervisor, name, withLogging));
 }
Exemplo n.º 12
0
 /// <summary>
 /// Create a new actor as child of <see cref="Sys"/> and returns it as <see cref="TestActorRef{TActor}"/>
 /// to enable access to the underlying actor instance via <see cref="TestActorRefBase{TActor}.UnderlyingActor"/>.
 /// </summary>
 /// <typeparam name="TActor">The type of the actor. It must have a parameterless public constructor</typeparam>
 /// <param name="name">Optional: The name.</param>
 public TestActorRef <TActor> ActorOfAsTestActorRef <TActor>(string name = null) where TActor : ActorBase, new()
 {
     return(new TestActorRef <TActor>(Sys, Props.Create <TActor>(), NoSupervisor, name));
 }
Exemplo n.º 13
0
 /// <summary>
 /// Create a new actor as child of <see cref="Sys"/> and returns it as <see cref="TestActorRef{TActor}"/>
 /// to enable access to the underlying actor instance via <see cref="TestActorRefBase{TActor}.UnderlyingActor"/>.
 /// Uses an expression that calls the constructor of <typeparamref name="TActor"/>.
 /// <example>
 /// <code>ActorOf&lt;MyActor&gt;(()=>new MyActor("value", 4711), "test-actor")</code>
 /// </example>
 /// </summary>
 /// <typeparam name="TActor">The type of the actor.</typeparam>
 /// <param name="factory">An expression that calls the constructor of <typeparamref name="TActor"/></param>
 /// <param name="name">Optional: The name.</param>
 public TestActorRef <TActor> ActorOfAsTestActorRef <TActor>(Expression <Func <TActor> > factory, string name = null) where TActor : ActorBase
 {
     return(new TestActorRef <TActor>(Sys, Props.Create(factory), NoSupervisor, name));
 }
Exemplo n.º 14
0
 public StoppingStrategySupervisor(IActorRef testProbe)
 {
     _crashingActor = Context.ActorOf(Props.Create(() => new CrashingActor(testProbe)), "CrashingActor");
 }
Exemplo n.º 15
0
        private void InitDownloaders()
        {
            int numberOfDownloaders;

            if (!int.TryParse(ConfigurationManager.AppSettings["numberOfDownloaders"], out numberOfDownloaders))
            {
                numberOfDownloaders = 2;
            }

            m_Downloader = Context.ActorOf(new RoundRobinPool(numberOfDownloaders).Props(Props.Create <Downloader>()), "downloaders");
        }
Exemplo n.º 16
0
 /// <summary>
 /// Create a new actor as child of <see cref="Sys" /> using an expression that calls the constructor
 /// of <typeparamref name="TActor"/>.
 /// <example>
 /// <code>ActorOf&lt;MyActor&gt;(()=>new MyActor("value", 4711), "test-actor")</code>
 /// </example>
 /// </summary>
 /// <typeparam name="TActor">The type of the actor.</typeparam>
 /// <param name="factory">An expression that calls the constructor of <typeparamref name="TActor"/></param>
 /// <param name="name">The name of the actor.</param>
 public IActorRef ActorOf <TActor>(Expression <Func <TActor> > factory, string name) where TActor : ActorBase
 {
     return(Sys.ActorOf(Props.Create(factory), name));
 }
Exemplo n.º 17
0
        private static void Main(string[] args)
        {
            var NUM_ACTORS = 0;
            var FILENAME   = "";

            try
            {
                NUM_ACTORS = int.Parse(Environment.GetEnvironmentVariable("NUM_ACTORS"));
                Console.WriteLine("ENV NUM_ACTORS={0}", NUM_ACTORS);
                FILENAME = Environment.GetEnvironmentVariable("FILENAME");
                Console.WriteLine("ENV FILENAME={0}", FILENAME);
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR trying to obtain value for Env var: ENV NUM_ACTORS & FILENAME. Exception msg={0}", e.Message);
                //return;
            }

            // TODO - Remove these items
            NUM_ACTORS = 60060;
            FILENAME   = @"c:\temp\datagen.bin";

            // Get the configuration of the akka system
            var config = ConfigurationFactory.ParseString(GetConfiguration());

            // Create the containers for all the actors. Using multiple systems to see if startup time is reduced
            var actorSystem = ActorSystem.Create("csl-arch-poc1", config);

            // Create the AccountGenertor actor
            var accountGeneratorActorProps = Props.Create(() => new AccountGenerator());
            var agref = actorSystem.ActorOf(accountGeneratorActorProps, "AccountGenerator");

            // Generate the accounts
            agref.Tell(new GenerateAccounts(FILENAME, NUM_ACTORS));

            Console.WriteLine(
                "Press return to send the created account actors a message causing them to save a snapshot");
            Console.ReadLine();

            agref.Tell(new SendMsgs());

            Console.WriteLine("Enter an actor id to probe or E to stop");
            var finished  = false;
            var actorPath = "/user/AccountGenerator/testActor-";

            while (finished != true)
            {
                var line = Console.ReadLine();
                if (line.Equals("E"))
                {
                    finished = true;
                }
                else
                {
                    // Get the actor reference and send it a display message
                    Console.WriteLine("Sending a display message to " + actorPath + line);
                    actorSystem.ActorSelection(actorPath + line).Tell(new DisplayState());
                }
            }

            Console.WriteLine("Press return to terminate the system");
            Console.ReadLine();

            // Wait until actor system terminated
            actorSystem.Terminate();
        }
Exemplo n.º 18
0
 protected override void PreStart()
 {
     Console.WriteLine("first started");
     Context.ActorOf(Props.Create <StartStopActor2>(), nameof(StartStopActor2));
 }
Exemplo n.º 19
0
 public void CanSerializeProps()
 {
     var message = Props.Create<BlackHoleActor>().WithMailbox("abc").WithDispatcher("def");
     AssertEqual(message);
 }
Exemplo n.º 20
0
        /// <summary>
        /// Start assumes that it cannot be followed by another Start() without having a Shutdown() first
        /// </summary>
        /// <exception cref="ConfigurationException">
        /// This exception is thrown when no transports are enabled under the "akka.remote.enabled-transports" configuration setting.
        /// </exception>
        /// <exception cref="TaskCanceledException">
        /// This exception is thrown when startup is canceled due to a timeout.
        /// </exception>
        /// <exception cref="TimeoutException">
        /// This exception is thrown when startup times out.
        /// </exception>
        /// <exception cref="Exception">
        /// This exception is thrown when a general error occurs during startup.
        /// </exception>
        public override void Start()
        {
            if (_endpointManager == null)
            {
                _log.Info("Starting remoting");
                _endpointManager =
                    System.SystemActorOf(RARP.For(System).ConfigureDispatcher(
                                             Props.Create(() => new EndpointManager(System.Settings.Config, _log)).WithDeploy(Deploy.Local)),
                                         EndpointManagerName);

                try
                {
                    var addressPromise = new TaskCompletionSource <IList <ProtocolTransportAddressPair> >();

                    // tells the EndpointManager to start all transports and bind them to listenable addresses, and then set the results
                    // of this promise to include them.
                    _endpointManager.Tell(new EndpointManager.Listen(addressPromise));

                    addressPromise.Task.Wait(Provider.RemoteSettings.StartupTimeout);
                    var akkaProtocolTransports = addressPromise.Task.Result;
                    if (akkaProtocolTransports.Count == 0)
                    {
                        throw new ConfigurationException(@"No transports enabled under ""akka.remote.enabled-transports""");
                    }
                    _addresses = new HashSet <Address>(akkaProtocolTransports.Select(a => a.Address));

                    IEnumerable <IGrouping <string, ProtocolTransportAddressPair> > tmp =
                        akkaProtocolTransports.GroupBy(t => t.ProtocolTransport.SchemeIdentifier);
                    _transportMapping = new Dictionary <string, HashSet <ProtocolTransportAddressPair> >();
                    foreach (var g in tmp)
                    {
                        var set = new HashSet <ProtocolTransportAddressPair>(g);
                        _transportMapping.Add(g.Key, set);
                    }

                    _defaultAddress = akkaProtocolTransports.Head().Address;
                    _addresses      = new HashSet <Address>(akkaProtocolTransports.Select(x => x.Address));

                    _log.Info("Remoting started; listening on addresses : [{0}]", string.Join(",", _addresses.Select(x => x.ToString())));

                    _endpointManager.Tell(new EndpointManager.StartupFinished());
                    _eventPublisher.NotifyListeners(new RemotingListenEvent(_addresses.ToList()));
                }
                catch (TaskCanceledException ex)
                {
                    NotifyError("Startup was canceled due to timeout", ex);
                    throw;
                }
                catch (TimeoutException ex)
                {
                    NotifyError("Startup timed out", ex);
                    throw;
                }
                catch (Exception ex)
                {
                    NotifyError("Startup failed", ex);
                    throw;
                }
            }
            else
            {
                _log.Warning("Remoting was already started. Ignoring start attempt.");
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Creates an <see cref="EchoReceiver"/> actor which subscribes to the distributed pub/sub topic.
        /// This topic is filled with messages from the cluster seed job.
        /// </summary>
        static void RunDistributedPubSubClient(ActorSystem system)
        {
            var echo = system.ActorOf(Props.Create(() => new EchoReceiver()));

            echo.Tell(new object());
        }
        private void RemoteNodeDeathWatch_must_cleanup_after_stop()
        {
            RunOn(() =>
            {
                var p1 = CreateTestProbe();
                var p2 = CreateTestProbe();
                var p3 = CreateTestProbe();
                var a1 = Sys.ActorOf(Props.Create(() => new ProbeActor(p1.Ref)), "a1");
                var a2 = Sys.ActorOf(Props.Create(() => new ProbeActor(p2.Ref)), "a2");
                var a3 = Sys.ActorOf(Props.Create(() => new ProbeActor(p3.Ref)), "a3");

                EnterBarrier("actors-started-5");

                var b1 = _identify(_config.Second, "b1");
                var b2 = _identify(_config.Second, "b2");
                var b3 = _identify(_config.Second, "b3");

                a1.Tell(new WatchIt(b1));
                ExpectMsg <RemoteNodeDeathWatchMultiNetSpec.Ack>(TimeSpan.FromSeconds(1));
                a1.Tell(new WatchIt(b2));
                ExpectMsg <RemoteNodeDeathWatchMultiNetSpec.Ack>(TimeSpan.FromSeconds(1));
                a2.Tell(new WatchIt(b2));
                ExpectMsg <RemoteNodeDeathWatchMultiNetSpec.Ack>(TimeSpan.FromSeconds(1));
                a3.Tell(new WatchIt(b3));
                ExpectMsg <RemoteNodeDeathWatchMultiNetSpec.Ack>(TimeSpan.FromSeconds(1));
                Sleep();
                a2.Tell(new UnwatchIt(b2));
                ExpectMsg <RemoteNodeDeathWatchMultiNetSpec.Ack>(TimeSpan.FromSeconds(1));

                EnterBarrier("watch-established-5");

                Sleep();

                a1.Tell(PoisonPill.Instance);
                a2.Tell(PoisonPill.Instance);
                a3.Tell(PoisonPill.Instance);

                EnterBarrier("stopped-5");
                EnterBarrier("terminated-verified-5");

                // verify that things are cleaned up, and heartbeating is stopped
                AssertCleanup();
                ExpectNoMsg(TimeSpan.FromSeconds(2));
                AssertCleanup();
            }, _config.First);

            RunOn(() =>
            {
                var p1 = CreateTestProbe();
                var p2 = CreateTestProbe();
                var p3 = CreateTestProbe();
                var b1 = Sys.ActorOf(Props.Create(() => new ProbeActor(p1.Ref)), "b1");
                var b2 = Sys.ActorOf(Props.Create(() => new ProbeActor(p2.Ref)), "b2");
                var b3 = Sys.ActorOf(Props.Create(() => new ProbeActor(p3.Ref)), "b3");

                EnterBarrier("actors-started-5");

                var a1 = _identify(_config.First, "a1");
                var a2 = _identify(_config.First, "a2");
                var a3 = _identify(_config.First, "a3");

                b1.Tell(new WatchIt(a1));
                ExpectMsg <RemoteNodeDeathWatchMultiNetSpec.Ack>(TimeSpan.FromSeconds(1));
                b1.Tell(new WatchIt(a2));
                ExpectMsg <RemoteNodeDeathWatchMultiNetSpec.Ack>(TimeSpan.FromSeconds(1));
                b2.Tell(new WatchIt(a2));
                ExpectMsg <RemoteNodeDeathWatchMultiNetSpec.Ack>(TimeSpan.FromSeconds(1));
                b3.Tell(new WatchIt(a3));
                ExpectMsg <RemoteNodeDeathWatchMultiNetSpec.Ack>(TimeSpan.FromSeconds(1));
                Sleep();
                b2.Tell(new UnwatchIt(a2));
                ExpectMsg <RemoteNodeDeathWatchMultiNetSpec.Ack>(TimeSpan.FromSeconds(1));

                EnterBarrier("watch-established-5");
                EnterBarrier("stopped-5");

                p1.ReceiveN(2, TimeSpan.FromSeconds(20))
                .Cast <WrappedTerminated>()
                .Select(w => w.T.ActorRef)
                .OrderBy(r => r.Path.Name)
                .ShouldBe(new[] { a1, a2 });
                p3.ExpectMsg <WrappedTerminated>(TimeSpan.FromSeconds(5)).T.ActorRef.ShouldBe(a3);
                p2.ExpectNoMsg(TimeSpan.FromSeconds(2));
                EnterBarrier("terminated-verified-5");

                // verify that things are cleaned up, and heartbeating is stopped
                AssertCleanup();
                ExpectNoMsg(TimeSpan.FromSeconds(2));
                p1.ExpectNoMsg(100);
                p2.ExpectNoMsg(100);
                p3.ExpectNoMsg(100);
                AssertCleanup();
            }, _config.Second);

            RunOn(() =>
            {
                EnterBarrier("actors-started-5");
                EnterBarrier("watch-established-5");
                EnterBarrier("stopped-5");
                EnterBarrier("terminated-verified-5");
            }, _config.Third);

            EnterBarrier("after-5");
        }
Exemplo n.º 23
0
        public void Start(string serverEndPoint         = null, string serverActorSystemName   = null,
                          ActorSystem serverActorSystem = null, string serverActorSystemConfig = null)
        {
            try
            {
                ActorSystemFactory.CreateOrSetUpActorSystem(serverActorSystemName: serverActorSystemName, actorSystem: serverActorSystem, actorSystemConfig: serverActorSystemConfig);
                var inventoryNotificationActorAddress = ConfigurationManager.AppSettings["RemoteInventoryInventoryQueryActorAddress"];
                var RemoteInventoryActorAddress       = ConfigurationManager.AppSettings["RemoteInventoryActorAddress"];
                var signalRInventoryQueryActorRef     = ActorSystemFactory.InventoryServiceActorSystem.ActorOf(Props.Create(() => new SignalRInventoryQueryActor(inventoryNotificationActorAddress, RemoteInventoryActorAddress)).WithMailbox(nameof(GetAllInventoryListMailbox)), typeof(SignalRInventoryQueryActor).Name);

                const string message = "signalRInventoryQueryActor created !!!!";
                Log.Debug(message);
                Console.WriteLine(message);

                Log.Debug("Starting inventory service ...");
                serverEndPoint = serverEndPoint ?? ConfigurationManager.AppSettings["ServerEndPoint"];

                if (!string.IsNullOrEmpty(serverEndPoint))
                {
                    OwinRef = WebApp.Start(serverEndPoint, (appBuilder) =>
                    {
                        if (Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "/web"))
                        {
                            var builder = new ContainerBuilder();
                            builder.Register(c => signalRInventoryQueryActorRef).ExternallyOwned();
                            // Register your SignalR hubs.
                            builder.RegisterType <InventoryServiceHub>().ExternallyOwned();

                            var container = builder.Build();
                            //var config = new HubConfiguration {Resolver = new AutofacDependencyResolver(container)};
                            GlobalHost.DependencyResolver = new AutofacDependencyResolver(container);
                            appBuilder.UseAutofacMiddleware(container);

                            appBuilder.MapSignalR();

                            var fileSystem = new PhysicalFileSystem(AppDomain.CurrentDomain.BaseDirectory + "/web");
                            var options    = new FileServerOptions
                            {
                                EnableDirectoryBrowsing = true,
                                FileSystem         = fileSystem,
                                EnableDefaultFiles = true
                            };

                            appBuilder.UseFileServer(options);
                        }

                        //  InventoryServiceSignalRContext.Push();
                    });
                }

                Log.Debug("WebUIDeployment initialized successfully");
            }
            catch (Exception e)
            {
                Log.Error(e, "Unable to start inventory service UI");
                throw;
            }
        }
Exemplo n.º 24
0
 protected override void PreStart()
 {
     _githubWorker = Context.ActorOf(Props.Create(() => new GithubWorkerActor(GithubClientFactory.GetClient))
                                     .WithRouter(new RoundRobinPool(10)));
 }
Exemplo n.º 25
0
        public void WhenStartStreamingIsNotRespondingThenStopStreamListener()
        {
            //
            //Arrange
            //
            Fixture snapshot;
            Mock <IResourceFacade> resourceFacadeMock;

            SetupCommonMockObjects(
                /*sport*/ FootabllSportMock.Object.Name,
                /*fixtureData*/ FixtureSamples.football_inplay_snapshot_2,
                /*storedData*/ new { Epoch = 7, Sequence = 1, MatchStatus = MatchStatus.InRunning },
                out snapshot,
                out resourceFacadeMock);
            StreamHealthCheckValidationMock.Setup(a =>
                                                  a.CanConnectToStreamServer(
                                                      It.IsAny <IResourceFacade>(),
                                                      It.IsAny <StreamListenerState>()))
            .Returns(true);
            SettingsMock.SetupGet(o => o.StartStreamingTimeoutInSeconds).Returns(1);
            SettingsMock.SetupGet(o => o.StartStreamingAttempts).Returns(3);
            ServiceMock.Setup(o => o.GetResources(It.Is <string>(s => s.Equals(FootabllSportMock.Object.Name))))
            .Returns(new List <IResourceFacade> {
                resourceFacadeMock.Object
            });
            resourceFacadeMock.Reset();
            resourceFacadeMock.Setup(o => o.Id).Returns(snapshot.Id);
            resourceFacadeMock.Setup(o => o.Sport).Returns(FootabllSportMock.Object.Name);
            resourceFacadeMock.Setup(o => o.MatchStatus).Returns((MatchStatus)Convert.ToInt32(snapshot.MatchStatus));
            resourceFacadeMock.Setup(o => o.Content).Returns(new Summary
            {
                Id          = snapshot.Id,
                Sequence    = snapshot.Sequence,
                MatchStatus = Convert.ToInt32(snapshot.MatchStatus),
                StartTime   = snapshot.StartTime?.ToString("yyyy-MM-ddTHH:mm:ssZ")
            });

            //
            //Act
            //
            var streamListenerManagerActor =
                ActorOfAsTestActorRef <StreamListenerManagerActor>(
                    Props.Create(() =>
                                 new StreamListenerManagerActor(
                                     SettingsMock.Object,
                                     PluginMock.Object,
                                     StateManagerMock.Object,
                                     SuspensionManagerMock.Object,
                                     StreamHealthCheckValidationMock.Object,
                                     FixtureValidationMock.Object)),
                    StreamListenerManagerActor.ActorName);
            var sportProcessorRouterActor =
                ActorOfAsTestActorRef <SportProcessorRouterActor>(
                    Props.Create(() => new SportProcessorRouterActor(ServiceMock.Object))
                    .WithRouter(new SmallestMailboxPool(SettingsMock.Object.FixtureCreationConcurrency)),
                    SportProcessorRouterActor.ActorName);

            sportProcessorRouterActor.Tell(new ProcessSportMsg {
                Sport = FootabllSportMock.Object.Name
            });

            //wait for 5 seconds while the health checks run every second and after 3 attempts the manager kills the actor
            Task.Delay(5000).Wait();

            //
            //Assert
            //
            AwaitAssert(() =>
            {
                resourceFacadeMock.Verify(a => a.GetSnapshot(), Times.Never);
                PluginMock.Verify(a =>
                                  a.ProcessSnapshot(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), false),
                                  Times.Never);
                PluginMock.Verify(a =>
                                  a.ProcessSnapshot(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), true),
                                  Times.Never);
                PluginMock.Verify(a =>
                                  a.ProcessStreamUpdate(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)), false),
                                  Times.Never);
                SuspensionManagerMock.Verify(a =>
                                             a.Unsuspend(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id))),
                                             Times.Never);
                SuspensionManagerMock.Verify(a =>
                                             a.Suspend(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)),
                                                       SuspensionReason.SUSPENSION),
                                             Times.Never);
                SuspensionManagerMock.Verify(a =>
                                             a.Suspend(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)),
                                                       SuspensionReason.FIXTURE_ERRORED),
                                             Times.Never);
                SuspensionManagerMock.Verify(a =>
                                             a.Suspend(It.Is <Fixture>(f => f.Id.Equals(resourceFacadeMock.Object.Id)),
                                                       SuspensionReason.DISCONNECT_EVENT),
                                             Times.Never);

                Assert.Throws <AggregateException>(() =>
                {
                    Sys.ActorSelection(
                        streamListenerManagerActor,
                        StreamListenerActor.GetName(resourceFacadeMock.Object.Id))
                    .ResolveOne(TimeSpan.FromSeconds(5)).Wait();
                }).InnerException.Should().BeOfType <ActorNotFoundException>();
            },
                        TimeSpan.FromMilliseconds(ASSERT_WAIT_TIMEOUT),
                        TimeSpan.FromMilliseconds(ASSERT_EXEC_INTERVAL));
        }
Exemplo n.º 26
0
 public PlaybackActor()
 {
     Context.ActorOf(Props.Create <UserCoordinatorActor>(), "UserCoordinator");
     Context.ActorOf(Props.Create <PlaybackStatisticsActor>(), "PlaybackStatistics");
 }
Exemplo n.º 27
0
 protected ActorRef CreateSubscriber(ActorRef actor)
 {
     return(Sys.ActorOf(Props.Create(() => new TestActorWrapperActor(actor))));
 }
Exemplo n.º 28
0
 public static Props CreateProps()
 {
     return(Props.Create(() => new Printer()));
 }
Exemplo n.º 29
0
        // 1
        private static IActorRef Single(ActorSystem system)
        {
            var props = Props.Create <WorkerActor>();

            return(system.ActorOf(props, "worker"));
        }
Exemplo n.º 30
0
 public IActorRef ChildActorOf <T>(SupervisorStrategy supervisorStrategy)
     where T : ActorBase
 {
     return(((TestKitBase)this).ChildActorOf(Props.Create <T>(), supervisorStrategy));
 }