Esempio n. 1
17
        private TestKitBase(TestKitAssertions assertions, ActorSystem system, Config config, string actorSystemName, string testActorName)
        {
            if(assertions == null) throw new ArgumentNullException("assertions");
            if(system == null)
            {
                var configWithDefaultFallback = config.SafeWithFallback(_defaultConfig);
                system = ActorSystem.Create(actorSystemName ?? "test", configWithDefaultFallback);
            }

            _assertions = assertions;
            _system = system;
            system.RegisterExtension(new TestKitExtension());
            system.RegisterExtension(new TestKitAssertionsExtension(assertions));
            _testKitSettings = TestKitExtension.For(_system);
            _queue = new BlockingQueue<MessageEnvelope>();
            _log = Logging.GetLogger(system, GetType());
            _eventFilterFactory = new EventFilterFactory(this);
            if (string.IsNullOrEmpty(testActorName))
                testActorName = "testActor" + _testActorId.IncrementAndGet();

            var testActor = CreateTestActor(system, testActorName);
            //Wait for the testactor to start
            AwaitCondition(() =>
            {
                var repRef = testActor as RepointableRef;
                return repRef == null || repRef.IsStarted;
            }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10));

            if(!(this is NoImplicitSender))
            {
                InternalCurrentActorCellKeeper.Current = (ActorCell)((ActorRefWithCell)testActor).Underlying;
            }
            _testActor = testActor;

        }
Esempio n. 2
0
        private static void SetupDependencyInjection(ActorSystem system)
        {
            var containerBuilder = new ContainerBuilder();
            containerBuilder.RegisterAssemblyTypes(typeof (ClaimsProcessorManager).Assembly).AsSelf().AsImplementedInterfaces();

            new AutoFacDependencyResolver(containerBuilder.Build(), system);
        }
Esempio n. 3
0
        public void SimpleTestAskContX()
        {
            bool f = false;

            int res = 0;

            var acts = new ActorSystem();
            var act = acts.CreateActor<SimpleTestActor>();

            var m = new acttestmsg()
            {
                act = () =>
                {

                    return 10;
                },
                msg = "test message"
            };

            Task<int> tsk = null;
            tsk = act.Ask<int>((x) =>
               {
               res = x;
               if (tsk == null) return;
               if (tsk.IsCompleted) return;
               f = true;
               }, m);

            tsk.Wait();

            Assert.IsTrue(f);
            Assert.AreEqual(10, res);
            Assert.AreEqual(10, tsk.Result);
            Console.WriteLine("test complete");
        }
        private static void AtLeastOnceDelivery(ActorSystem system)
        {
            Console.WriteLine("\n--- AT LEAST ONCE DELIVERY EXAMPLE ---\n");
            var delivery = system.ActorOf(Props.Create(()=> new DeliveryActor()),"delivery");

            var deliverer = system.ActorOf(Props.Create(() => new AtLeastOnceDeliveryExampleActor(delivery.Path)));
            delivery.Tell("start");
            deliverer.Tell(new Message("foo"));
            

            System.Threading.Thread.Sleep(1000); //making sure delivery stops before send other commands
            delivery.Tell("stop");

            deliverer.Tell(new Message("bar"));

            Console.WriteLine("\nSYSTEM: Throwing exception in Deliverer\n");
            deliverer.Tell("boom");
            System.Threading.Thread.Sleep(1000);

            deliverer.Tell(new Message("bar1"));
            Console.WriteLine("\nSYSTEM: Enabling confirmations in 3 seconds\n");

            System.Threading.Thread.Sleep(3000);
            Console.WriteLine("\nSYSTEM: Enabled confirmations\n");
            delivery.Tell("start");
            
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            // initialize MyActorSystem
            MyActorSystem = ActorSystem.Create("MyActorSystem");

            // time to make your first actors!
            var consoleWriterActor = MyActorSystem.ActorOf(Props.Create<ConsoleWriterActor>(), "MyConsoleWriter"); // Generic syntax

            // make tailCoordinatorActor
            Props tailCoordinatorProps = Props.Create(() => new TailCoordinatorActor());
            var tailCoordinatorActor = MyActorSystem.ActorOf(tailCoordinatorProps, "tailCoordinatorActor");

            // pass tailCoordinatorActor to fileValidatorActorProps (just adding one extra arg)
            Props fileValidatorActorProps = Props.Create(() => new FileValidatorActor(consoleWriterActor));
            var validationActor = MyActorSystem.ActorOf(fileValidatorActorProps, "validationActor");


            var consoleReaderActor = MyActorSystem.ActorOf(Props.Create(() => new ConsoleReaderActor()), "MyConsoleReader");

            // tell console reader to begin
            consoleReaderActor.Tell(ConsoleReaderActor.StartCommand);

            // Fake start with 
            validationActor.Tell(@"c:\MyFile.txt");

            // blocks the main thread from exiting until the actor system is shut down
            MyActorSystem.AwaitTermination();
        }
        private static void SnapshotedActor(ActorSystem system)
        {
            Console.WriteLine("\n--- SNAPSHOTED ACTOR EXAMPLE ---\n");
            var pref = system.ActorOf(Props.Create<SnapshotedExampleActor>(), "snapshoted-actor");

            // send two messages (a, b) and persist them
            pref.Tell("a");
            pref.Tell("b");

            // make a snapshot: a, b will be stored in durable memory
            pref.Tell("snap");

            // send next two messages - those will be cleared, since MemoryJournal is not "persistent"
            pref.Tell("c");
            pref.Tell("d");

            // print internal actor's state
            pref.Tell("print");

            // result after first run should be like:

            // Current actor's state: d, c, b, a

            // after second run:

            // Offered state (from snapshot): b, a      - taken from the snapshot
            // Current actor's state: d, c, b, a, b, a  - 2 last messages loaded from the snapshot, rest send in this run

            // after third run:

            // Offered state (from snapshot): b, a, b, a        - taken from the snapshot
            // Current actor's state: d, c, b, a, b, a, b, a    - 4 last messages loaded from the snapshot, rest send in this run

            // etc...
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            var config =
                ConfigurationFactory.ParseString(
                    File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "akka.config")));

            // make actor system
            MyActorSystem = ActorSystem.Create("MyActorSystem", config);

            // create top-level actors within the actor system
            Props consoleWriterProps = Props.Create<ConsoleWriterActor>();
            IActorRef consoleWriterActor = MyActorSystem.ActorOf(consoleWriterProps, "consoleWriterActor");

            Props tailCoordinatorProps = Props.Create(() => new TailCoordinatorActor());
            IActorRef tailCoordinatorActor = MyActorSystem.ActorOf(tailCoordinatorProps, "tailCoordinatorActor");

            Props fileValidatorActorProps = Props.Create(() => new FileValidatorActor(consoleWriterActor));
            IActorRef fileValidatorActor = MyActorSystem.ActorOf(fileValidatorActorProps, "validationActor");

            Props consoleReaderProps = Props.Create<ConsoleReaderActor>();
            IActorRef consoleReaderActor = MyActorSystem.ActorOf(consoleReaderProps, "consoleReaderActor");

            // begin processing
            consoleReaderActor.Tell(ConsoleReaderActor.StartCommand);

            // blocks the main thread from exiting until the actor system is shut down
            MyActorSystem.AwaitTermination();
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            var section = (AkkaConfigurationSection)ConfigurationManager.GetSection("akka");
            _system = ActorSystem.Create("test", section.AkkaConfig);

            _coordinator = _system.ActorOf(Props.Create(() => new IdentityActor())
                .WithRouter(FromConfig.Instance), "fred");

            //_coordinator =
            //    _system.ActorOf(Props.Create(() => new IdentityActor()).WithRouter(new ConsistentHashingPool(5000)),
            //        "fred2");

            int routees = _coordinator.Ask<Routees>(new GetRoutees()).Result.Members.Count();
            Console.WriteLine(routees);

            // Lazy wait for the co-ordinator to deploy.
            Thread.Sleep(5000);

            for (int i = 1; i <= 5000; i++)
            {
                for (int x = 1; x <= 4; x++)
                {
                    _coordinator.Tell(new EntityMessage<long>(i));
                }
            }

            Thread.Sleep(500);

            Console.ReadLine();
        }
Esempio n. 9
0
        public RemoteDeploySpec()
            : base(@"
            akka {
                loglevel = INFO 
                log-dead-letters-during-shutdown = false
              //  actor.provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""
                remote.helios.tcp = {
                    hostname = localhost
                    port = 0
                }

                actor.deployment {
                  /router1 {
                    router = round-robin-pool
                    nr-of-instances = 3
                  }
                  /router2 {
                    router = round-robin-pool
                    nr-of-instances = 3
                  }
                  /router3 {
                    router = round-robin-pool
                    nr-of-instances = 0
                  }
                }
            }
")
        {
            _remoteSystem = ActorSystem.Create("RemoteSystem", Sys.Settings.Config);
            _remoteAddress = _remoteSystem.AsInstanceOf<ExtendedActorSystem>().Provider.DefaultAddress;
            var remoteAddressUid = AddressUidExtension.Uid(_remoteSystem);


        }
Esempio n. 10
0
        /// <summary>
        /// Starts a job, which publishes <see cref="Echo"/> message to distributed cluster pub sub in 5 sec periods.
        /// </summary>
        static void RunDistributedPubSubSeed(ActorSystem system)
        {
            var mediator = DistributedPubSub.Get(system).Mediator;

            system.Scheduler.ScheduleTellRepeatedly(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5), mediator,
                new Publish("echo", new Echo("hello world")), ActorRefs.NoSender);
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            // initialize MyActorSystem
            MyActorSystem = ActorSystem.Create("MyActorSystem");

            // time to make your first actors!
            Props consoleWriterProps = Props.Create<ConsoleWriterActor>();
            IActorRef consoleWriterActor = MyActorSystem.ActorOf(consoleWriterProps, "consoleWriterActor");

            Props tailCoordinatorProps = Props.Create(() => new TailCoordinatorActor());
            IActorRef tailCoordinatorActor = MyActorSystem.ActorOf(tailCoordinatorProps, "tailCoordinatorActor");

            Props fileValidatorActorProps = Props.Create(() => new FileValidatorActor(consoleWriterActor));
            IActorRef validationActor = MyActorSystem.ActorOf(fileValidatorActorProps, "validationActor");

            Props consoleReaderProps = Props.Create<ConsoleReaderActor>();
            IActorRef consoleReaderActor = MyActorSystem.ActorOf(consoleReaderProps, "consoleReaderActor");
            

            // tell console reader to begin
            consoleReaderActor.Tell(ConsoleReaderActor.StartCommand);

            // blocks the main thread from exiting until the actor system is shut down
            MyActorSystem.AwaitTermination();
        }
        /// <summary>
        ///     Construct an <see cref="Akka.Actor.ActorSelection"/> from the given path, which is
        ///     parsed for wildcards (these are replaced by regular expressions
        ///     internally). No attempt is made to verify the existence of any part of
        ///     the supplied path, it is recommended to send a message and gather the
        ///     replies in order to resolve the matching set of actors.
        /// </summary>
        public static ActorSelection ActorSelection(string path, ActorSystem system, ActorRef lookupRoot)
        {
            var provider = ((ActorSystemImpl)system).Provider;
            if(Uri.IsWellFormedUriString(path, UriKind.Absolute))
            {
                ActorPath actorPath;
                if(!ActorPath.TryParse(path, out actorPath))
                    return new ActorSelection(provider.DeadLetters, "");

                var actorRef = provider.RootGuardianAt(actorPath.Address);
                return new ActorSelection(actorRef, actorPath.Elements);
            }
            //no path given
            if(string.IsNullOrEmpty(path))
            {
                return new ActorSelection(system.DeadLetters, "");
            }

            //absolute path
            var elements = path.Split('/');
            if(elements[0] == "")
            {
                return new ActorSelection(provider.RootGuardian, elements.Skip(1));
            }

            return new ActorSelection(lookupRoot, path);
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            // Akka prefers creation of objects via factories
            // this is due to the fact that internally Akka does a lot of system internally
            UntypedActorSystem = ActorSystem.Create("UntypedActorSystem");
            Console.WriteLine("Actor system created");

            // Akka uses the movie industry to name a few items
            // To create an Actor you use the Props class
            Props whatsMyTypeAgainProps = Props.Create<WhatsMyTypeAgainActor>();

            // ActorOf will create the Actor
            // You can get a reference to the Actor using the ActorOf which returns an IActorRef
            UntypedActorSystem.ActorOf(whatsMyTypeAgainProps, "WhatsMyTypeAgain");

            // Alternatively you can use ActorSelection and a path to the Actor
            ActorSelection whatsMyTypeAgainActor = UntypedActorSystem.ActorSelection("/user/WhatsMyTypeAgain");

            // Tell is void
            whatsMyTypeAgainActor.Tell("I'm 30");

            // Ask with return a value (request response)
            var askTask = whatsMyTypeAgainActor.Ask<int>("Hey what's my age again?");
            Task.WaitAll(askTask);
            Console.WriteLine(askTask.Result);

            Console.ReadKey();
            UntypedActorSystem.Shutdown();
            UntypedActorSystem.AwaitTermination();
        }
Esempio n. 14
0
 public Remoting(ActorSystem system, RemoteActorRefProvider provider)
     : base(system, provider)
 {
     log = Logging.GetLogger(system, "remoting");
     _eventPublisher = new EventPublisher(system, log, Logging.LogLevelFor(provider.RemoteSettings.RemoteLifecycleEventsLogLevel));
     _transportSupervisor = system.SystemActorOf(Props.Create<TransportSupervisor>(), "transports");
 }
        /// <summary>
        /// Creates cluster publish/subscribe settings from the default configuration `akka.cluster.pub-sub`.
        /// </summary>
        public static DistributedPubSubSettings Create(ActorSystem system)
        {
            var config = system.Settings.Config.GetConfig("akka.cluster.pub-sub");
            if (config == null) throw new ArgumentException("Actor system settings has no configuration for akka.cluster.pub-sub defined");

            return Create(config);
        }
Esempio n. 16
0
 static void Main()
 {
     ChartActors = ActorSystem.Create("ChartActors");
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Main());
 }
Esempio n. 17
0
        private static void Main(string[] args)
        {
            MovieStreamingActorSystem = ActorSystem.Create("MovieStreamingActorSystem");
            MovieStreamingActorSystem.ActorOf(Props.Create<PlaybackActor>(), "Playback");

            do
            {
                ShortPause();

                Console.WriteLine();
                Console.WriteLine("enter a command and hit enter");

                var command = Console.ReadLine();

                if (command.StartsWith("play"))
                {
                    int userId = int.Parse(command.Split(',')[1]);
                    string movieTitle = command.Split(',')[2];

                    var message = new PlayMovieMessage(movieTitle, userId);
                    MovieStreamingActorSystem.ActorSelection("/user/Playback/UserCoordinator").Tell(message);
                }

                if (command.StartsWith("stop"))
                {
                    int userId = int.Parse(command.Split(',')[1]);

                    var message = new StopMovieMessage(userId);
                    MovieStreamingActorSystem.ActorSelection("/user/Playback/UserCoordinator").Tell(message);
                }

            } while (true);
        }
Esempio n. 18
0
        public YakkaBootstrapper()
        {
            var hocon = string.Format(@"
            akka {{
            loglevel = DEBUG
            loggers = [""Akka.Logger.NLog.NLogLogger, Akka.Logger.NLog""]
            actor {{
            provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""
            }}
            remote {{
            helios.tcp {{
            port = 0
            hostname = {0}
            }}
            }}
            }}", Dns.GetHostName());
            var config = ConfigurationFactory.ParseString(hocon);

            var clientName = $"{ClientId}";
            _clientActorSystem = ActorSystem.Create(clientName, config);

            //Create root level actors. This is the actual root of the actor system, the view model bridge actors exchange messages with these
            var errorHandler = _clientActorSystem.ActorOf(Props.Create(() => new ErrorDialogActor()), ClientActorPaths.ErrorDialogActor.Name);
            var settingsActor = _clientActorSystem.ActorOf(Props.Create(() => new SettingsActor(errorHandler)), ClientActorPaths.SettingsActor.Name);
            var clientsActor = _clientActorSystem.ActorOf(Props.Create(() => new ClientsActor()), ClientActorPaths.ClientsActor.Name);
            var messager = _clientActorSystem.ActorOf(Props.Create(() => new MessagingActor()), ClientActorPaths.ChatMessageRouter.Name);
            var connectionActor = _clientActorSystem.ActorOf(Props.Create(() => new ConnectionActor()), ClientActorPaths.ConnectionActor.Name);
            var lockMonitor = _clientActorSystem.ActorOf(Props.Create(() => new LockMonitorActor()), ClientActorPaths.LockMonitor.Name);

            Initialize();
        }
Esempio n. 19
0
 /// <summary>
 /// Creates a proxy to communicate with cluster singleton initialized by the seed.
 /// </summary>
 static void RunClusterSingletonClient(ActorSystem system)
 {
     var proxyRef = system.ActorOf(ClusterSingletonProxy.Props(
         singletonManagerPath: "/user/manager",
         settings: ClusterSingletonProxySettings.Create(system).WithRole("worker")),
         name: "managerProxy");
 }
Esempio n. 20
0
 /// <summary>
 /// Creates a cluster client, that allows to connect to cluster even thou current actor system is not part of it.
 /// </summary>
 static void RunClusterClient(ActorSystem system)
 {
     //NOTE: to properly run cluster client set up actor ref provider for nodes on `provider = "Akka.Remote.RemoteActorRefProvider, Akka.Remote"`
     system.Settings.InjectTopLevelFallback(ClusterClientReceptionist.DefaultConfig());
     var clusterClient = system.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(system)));
     clusterClient.Tell(new ClusterClient.Send("/user/my-service", new Echo("hello from cluster client")));
 }
Esempio n. 21
0
        static void Main(string[] args)
        {
            // make an actor system 
            MyActorSystem = ActorSystem.Create("MyActorSystem");

            // this is here to show you what NOT to do
            // this approach to props has no type safety
            // it will compile, but can easily blow up in your face at runtime :(
            // UNCOMMENT THE BELOW TWO LINES, BUILD THE SOLUTION, AND THEN TRY TO RUN IT TO SEE
            //Props fakeActorProps = Props.Create(typeof(FakeActor));
            //IActorRef fakeActor = MyActorSystem.ActorOf(fakeActorProps, "fakeActor");

            // set up actors, using props (split props onto own line so easier to read)
            Props consoleWriterProps = Props.Create<ConsoleWriterActor>();
            IActorRef consoleWriterActor = MyActorSystem.ActorOf(consoleWriterProps, "consoleWriterActor");

            Props validationActorProps = Props.Create(() => new ValidationActor(consoleWriterActor));
            IActorRef validationActor = MyActorSystem.ActorOf(validationActorProps, "validationActor");
            
            Props consoleReaderProps = Props.Create<ConsoleReaderActor>(validationActor);
            IActorRef consoleReaderActor = MyActorSystem.ActorOf(consoleReaderProps, "consoleReaderActor");

            // tell console reader to begin
            consoleReaderActor.Tell(ConsoleReaderActor.StartCommand);

            // blocks the main thread from exiting until the actor system is shut down
            MyActorSystem.AwaitTermination();
        }
Esempio n. 22
0
 public AkkaProtocolTransport(Transport wrappedTransport, ActorSystem actorSystem,
     AkkaProtocolSettings akkaProtocolSettings)
 {
     Transport = wrappedTransport;
     this.actorSystem = actorSystem;
     this.akkaProtocolSettings = akkaProtocolSettings;
 }
        public static Server.GatewayRef CreateGateway(ActorSystem system, ChannelType type, string name, IPEndPoint endPoint,
                                                      XunitOutputLogger.Source outputSource,
                                                      Action<Server.GatewayInitiator> clientInitiatorSetup = null)
        {
            // initialize gateway initiator

            var initiator = new Server.GatewayInitiator()
            {
                GatewayLogger = new XunitOutputLogger($"Gateway({name})", outputSource),
                ListenEndPoint = endPoint,
                ConnectEndPoint = endPoint,
                TokenRequired = false,
                CreateChannelLogger = (_, o) => new XunitOutputLogger($"ServerChannel({name})", outputSource),
                CheckCreateChannel = (_, o) => true,
                ConnectionSettings = new Server.TcpConnectionSettings { PacketSerializer = s_serverSerializer },
                PacketSerializer = s_serverSerializer,
            };

            clientInitiatorSetup?.Invoke(initiator);

            // create gateway and start it

            var gateway = (type == ChannelType.Tcp)
                ? system.ActorOf(Props.Create(() => new Server.TcpGateway(initiator))).Cast<Server.GatewayRef>()
                : system.ActorOf(Props.Create(() => new Server.UdpGateway(initiator))).Cast<Server.GatewayRef>();
            gateway.Start().Wait();

            return gateway;
        }
Esempio n. 24
0
        public FixServer(int port)
        {
            _actorSystem = ActorSystem.Create("FIXServer");

            // Some invented FX spot rates
            var prices = new Dictionary<string, double>()
            {
                { "USDGBP", 0.65575 },
                { "USDJPY", 119.75 }
            };

            var fixParser = new FixParser();

            var tcpServerProps = Props.Create(() => new TcpServerActor(port,
                FixParser.ExtractFixMessages));
            Func<IActorRefFactory, IActorRef> tcpServerCreator =
                (context) => context.ActorOf(tcpServerProps, "TcpServer");

            var fixInterpreterProps = Props.Create(() => new FixInterpreterActor(fixParser));
            Func<IActorRefFactory, IActorRef> fixInterpreterCreator =
                (context) => context.ActorOf(fixInterpreterProps, "FixInterpreter");

            var fixServerProps = Props.Create(() => new Actors.FixServerActor(tcpServerCreator,
                fixInterpreterCreator, prices));
            _fixServerActor = _actorSystem.ActorOf(fixServerProps, "FixServer");
        }
Esempio n. 25
0
 /// <summary>
 /// Creates a surrogate representation of the current <see cref="RandomGroup"/>.
 /// </summary>
 /// <param name="system">The actor system that owns this router.</param>
 /// <returns>The surrogate representation of the current <see cref="RandomGroup"/>.</returns>
 public override ISurrogate ToSurrogate(ActorSystem system)
 {
     return new RandomGroupSurrogate
     {
         Paths = Paths
     };
 }
Esempio n. 26
0
        static void Main(string[] args)
        {
            // initialize MyActorSystem
            // YOU NEED TO FILL IN HERE
            MyActorSystem = ActorSystem.Create("MyActorSystem");

            // time to make your first actors!

            var consoleWriterProps = Props.Create(() => new ConsoleWriterActor());
            var consoleWriterActor = MyActorSystem.ActorOf(consoleWriterProps, "consoleWriterActor");

            var tailCoordinatorActor = MyActorSystem.ActorOf(Props.Create<TailCoordinatorActor>(), "tailCoordinatorActor");

            var validationActorProps = Props.Create(() => new FileValidatorActor(consoleWriterActor));
            var validationActor = MyActorSystem.ActorOf(validationActorProps, "validationActor");
            var consoleReaderProps = Props.Create<ConsoleReaderActor>();
            var readerActor = MyActorSystem.ActorOf(consoleReaderProps, "consoleReaderActor");

            // tell console reader to begin
            //YOU NEED TO FILL IN HERE
            readerActor.Tell(ConsoleReaderActor.StartCommand);

            // blocks the main thread from exiting until the actor system is shut down
            MyActorSystem.AwaitTermination();
        }
 private void MainWindow_Loaded(object sender, RoutedEventArgs e)
 {
     system = ActorSystem.Create("MyClientSystem");
     serverActor = system.ActorSelection("akka.tcp://TestServer@localhost:8081/user/MyServerActor");
     uiActor = system.ActorOf(Props.Create(() => new UIActor(this.textBox)), "MyClient");
     clientActor = system.ActorOf(Props.Create(() => new ClientActor(serverActor, uiActor)), Guid.NewGuid().ToString());
 }
Esempio n. 28
0
 public RootGuardianActorRef(ActorSystem system, Props props, MessageDispatcher dispatcher, Func<Mailbox> createMailbox, //TODO: switch from  Func<Mailbox> createMailbox to MailboxType mailboxType
     InternalActorRef supervisor, ActorPath path, InternalActorRef deadLetters, IReadOnlyDictionary<string, InternalActorRef> extraNames)
     : base(system,props,dispatcher,createMailbox,supervisor,path)
 {
     _deadLetters = deadLetters;
     _extraNames = extraNames;
 }
Esempio n. 29
0
        public void Initialize(ActorSystem system)
        {
            var context = new ClusterNodeContext { System = system };

            context.ClusterActorDiscovery = system.ActorOf(
                Props.Create(() => new ClusterActorDiscovery(null)));

            context.UserTable = new DistributedActorTableRef<long>(system.ActorOf(
                Props.Create(() => new DistributedActorTable<long>(
                    "User", context.ClusterActorDiscovery, null, null)),
                "UserTable"));

            var userTableContainer = system.ActorOf(
                Props.Create(() => new DistributedActorTableContainer<long>(
                    "User", context.ClusterActorDiscovery, typeof(UserActorFactory), new object[] { context }, InterfacedPoisonPill.Instance)),
                "UserTableContainer");

            context.GameTable = new DistributedActorTableRef<long>(system.ActorOf(
                Props.Create(() => new DistributedActorTable<long>(
                    "Game", context.ClusterActorDiscovery, typeof(IncrementalIntegerIdGenerator), null)),
                "GameTable"));

            var gameTableContainer = system.ActorOf(
                Props.Create(() => new DistributedActorTableContainer<long>(
                    "Game", context.ClusterActorDiscovery, typeof(GameActorFactory), new object[] { context }, InterfacedPoisonPill.Instance)),
                "GameTableContainer");

            var gamePairMaker = system.ActorOf(Props.Create(() => new GamePairMakerActor(context)));
            context.GamePairMaker = gamePairMaker.Cast<GamePairMakerRef>();

            Context = context;
        }
Esempio n. 30
0
        private static void Main()
        {
            ConfigureLogging();

            LogTo.Debug($"Creating ActorSystem '{ActorSystemName}'.");
            _actorSystem = ActorSystem.Create(ActorSystemName);

            LogTo.Debug($"Creating Props '{nameof(ProductsActor)}'.");
            var props = Props.Create<ProductsActor>();

            LogTo.Debug($"Creating ActorOf '{nameof(ProductsActor)}'.");
            var products = _actorSystem.ActorOf(props);

            LogTo.Information("Adding products.");
            products.Tell(new AddProduct("Product 1"));
            products.Tell(new AddProduct("Product 2"));

            LogTo.Debug("Stopping products actor.");
            products.GracefulStop(TimeSpan.FromMinutes(1)).Wait();
            LogTo.Debug("Stopped products actor.");

            LogTo.Debug("Shutting down ActorSystem");
            _actorSystem.Shutdown();

            LogTo.Debug("Waiting for ActorSystem to complete shutdown.");
            _actorSystem.AwaitTermination();

            LogTo.Information("Finished shopping :-)");
        }
Esempio n. 31
0
 /// <summary>
 /// Create a new <see cref="IDependencyResolver"/> instance that we're going to use
 /// in the context of all of our tests.
 /// </summary>
 /// <returns>An <see cref="IDependencyResolver"/> instance.</returns>
 protected abstract IDependencyResolver NewDependencyResolver(object diContainer, ActorSystem system);
Esempio n. 32
0
        public void GetNullActorRefForUnknownPath()
        {
            ActorSystem system = new ActorSystem();

            Assert.IsNull(system.ActorSelect("unknown"));
        }
Esempio n. 33
0
 /// <summary>
 /// Initializes a Table Storage persistence plugin inside provided <paramref name="actorSystem"/>.
 /// </summary>
 public static void Init(ActorSystem actorSystem)
 {
     Instance.Apply(actorSystem);
 }
Esempio n. 34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ServiceProviderDependencyResolver"/> class.
 /// </summary>
 /// <param name="serviceProvider">The container used to resolve references.</param>
 /// <param name="system">The actor system to plug into.</param>
 /// <exception cref="ArgumentNullException">
 /// Either the <paramref name="serviceProvider"/> or the <paramref name="system"/> was null.
 /// </exception>
 public ServiceProviderDependencyResolver(IServiceProvider serviceProvider, ActorSystem system)
 {
     _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
     _system          = system ?? throw new ArgumentNullException(nameof(system));
     _system.AddDependencyResolver(this);
 }
Esempio n. 35
0
 public TcpTransport(ActorSystem system, Config config) : base(system, config)
 {
 }
Esempio n. 36
0
        public static ActorSystem getSystem()
        {
            if (_system == null)
            {
                // var port = 5000;
                // var host = "localhost";
                // var config = ConfigurationFactory.ParseString(@"
                //     akka {
                //         loggers                 = [""Akka.Logger.NLog.NLogLogger, Akka.Logger.NLog""]
                //         loglevel                = info
                //         log-config-on-start     = on
                //         actor {
                //             provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
                //             serializers {
                //                 hyperion = ""Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion""
                //             }
                //             serialization-bindings {
                //                 ""System.Object"" = hyperion
                //             }

                //             debug{
                //                 receive         = on  # log any received message
                //                 autoreceive     = on  # log automatically received messages, e.g. PoisonPill
                //                 lifecycle       = on  # log actor lifecycle changes
                //                 event-stream    = on  # log subscription changes for Akka.NET event stream
                //                 unhandled       = on  # log unhandled messages sent to actors
                //             }
                //         }
                //         remote {
                //             helios.tcp {
                //             public-hostname = """ + host + @"""
                //             hostname = """ + host + @"""
                //             port = """ + port.ToString() + @"""
                //             }
                //         }
                //         cluster {
                //             auto-down-unreachable-after = 5s
                //             seed-nodes = [""akka.tcp://cluster-system@""" + host + ":" + port.ToString() + @"/""]
                //         }
                //     }
                //     ");

                // var port = 5000;
                // var host = "localhost";
                var config = ConfigurationFactory.ParseString(@"
                    akka {
                        loggers                 = [""Akka.Logger.NLog.NLogLogger, Akka.Logger.NLog""]
                        loglevel                = info
                        log-config-on-start     = on
                        actor {
                            serializers {
                                hyperion = ""Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion""
                            }
                            serialization-bindings {
                                ""System.Object"" = hyperion
                            }

                            debug{
                                receive         = on  # log any received message
                                autoreceive     = on  # log automatically received messages, e.g. PoisonPill
                                lifecycle       = on  # log actor lifecycle changes
                                event-stream    = on  # log subscription changes for Akka.NET event stream
                                unhandled       = on  # log unhandled messages sent to actors
                            }
                        }
                    }
                    ");

                config.WithFallback(ClusterSingletonManager.DefaultConfig());

                _system = ActorSystem.Create("cluster-system", config);
            }

            return(_system);
        }
Esempio n. 37
0
 public LoggerMailbox(IActorRef owner, ActorSystem system) : base(new UnboundedMessageQueue())
 {
     _owner  = owner;
     _system = system;
 }
Esempio n. 38
0
 /// <summary>
 /// TBD
 /// </summary>
 /// <param name="system">TBD</param>
 /// <returns>TBD</returns>
 public static FlowNameCounter Instance(ActorSystem system)
 => system.WithExtension <FlowNameCounter, FlowNameCounter>();
Esempio n. 39
0
 public void Start(ActorSystem system)
 {
     this.system = system;
     cluster     = Cluster.Get(system);
 }
Esempio n. 40
0
 protected MultiNodeSpec(MultiNodeConfig config, Type type) :
     this(config.Myself, ActorSystem.Create(type.Name, config.Config), config.Roles, config.Deployments)
 {
 }
Esempio n. 41
0
 /// <summary>
 /// Creates a router that is responsible for routing messages to routees within the provided <paramref name="system" />.
 /// </summary>
 /// <param name="system">The ActorSystem this router belongs to.</param>
 /// <returns>The newly created router tied to the given system.</returns>
 public override Router CreateRouter(ActorSystem system)
 {
     return(Local.CreateRouter(system));
 }
Esempio n. 42
0
 public LogForStandaloneActorSystemTest(ITestOutputHelper output)
 {
     _logger = new XUnitAutoTestLoggerConfiguration(output).CreateLogger();
     Sys     = new AutoTestNodeConfiguration().CreateInMemorySystem();
     Sys.AttachSerilogLogging(_logger);
 }
 public DemoException(ActorSystem system, string[] args)
 {
     _system = system;
 }
Esempio n. 44
0
 /// <summary>
 /// Creates a surrogate representation of the current router.
 /// </summary>
 /// <param name="system">The actor system that owns this router.</param>
 /// <returns>The surrogate representation of the current router.</returns>
 public override ISurrogate ToSurrogate(ActorSystem system)
 {
     return(Local.ToSurrogate(system));
 }
Esempio n. 45
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApplicationLifetime lifetime)
        {
            app.UseSwagger();
            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            MetricServer metricServer = null;
            var          appConfig    = app.ApplicationServices.GetService <AppSettings>();

            AppSettings = appConfig;


            //APP Life Cycle
            lifetime.ApplicationStarted.Register(() =>
            {
                app.ApplicationServices.GetService <ILogger>();

                var actorSystem = app.ApplicationServices.GetService <ActorSystem>(); // start Akka.NET
                ActorSystem     = actorSystem;

                //싱글톤 클러스터 액터
                actorSystem.BootstrapSingleton <SingleToneActor>("SingleToneActor", "akkanet");
                var singleToneActor = actorSystem.BootstrapSingletonProxy("SingleToneActor", "akkanet", "/user/SingleToneActor", "singleToneActorProxy");
                AkkaLoad.RegisterActor("SingleToneActor", singleToneActor);


                // ###########  로드 테스트 전용

                // 클러스터내 싱글톤은 하나만 존재할수있음 : akka.cluster.singleton  - akka.conf참고

                //액터 선택 : AkkaLoad.ActorSelect("ClusterWorkerPoolActor")
                var worker = AkkaLoad.RegisterActor(
                    "ClusterWorkerPoolActor",
                    actorSystem.ActorOf(Props.Create <ClusterWorkerPoolActor>()
                                        .WithDispatcher("fast-dispatcher")
                                        .WithRouter(FromConfig.Instance),
                                        "cluster-workerpool"
                                        ));

                //커멘드 액터( 로드테스트용)
                //액터생성
                AkkaLoad.RegisterActor(
                    "TPSCommandActor",
                    actorSystem.ActorOf(Props.Create <TPSCommandActor>(worker),
                                        "TPSCommandActor"
                                        ));

                // ###########  로드 테스트 전용


                //액터생성
                AkkaLoad.RegisterActor(
                    "basic",
                    actorSystem.ActorOf(Props.Create <BasicActor>(),
                                        "basic"
                                        ));

                // DI 연동
                AkkaLoad.RegisterActor(
                    "toner",
                    actorSystem.ActorOf(actorSystem.DI().Props <TonerActor>()
                                        .WithRouter(new RoundRobinPool(1)),
                                        "toner"
                                        ));

                AkkaLoad.RegisterActor(
                    "printer",
                    actorSystem.ActorOf(actorSystem.DI().Props <PrinterActor>()
                                        .WithDispatcher("custom-dispatcher")
                                        .WithRouter(FromConfig.Instance).WithDispatcher("custom-task-dispatcher"),
                                        "printer-pool"
                                        ));

                // DI 미연동
                AkkaLoad.RegisterActor(
                    "highpass",
                    actorSystem.ActorOf(Props.Create <HighPassGateActor>()
                                        .WithDispatcher("fast-dispatcher")
                                        .WithRouter(FromConfig.Instance),
                                        "highpass-gate-pool"
                                        ));

                AkkaLoad.RegisterActor(
                    "cashpass",
                    actorSystem.ActorOf(Props.Create <CashGateActor>()
                                        .WithDispatcher("slow-dispatcher")
                                        .WithRouter(FromConfig.Instance),
                                        "cashpass-gate-pool"
                                        ));

                AkkaLoad.RegisterActor(
                    "clusterRoundRobin",
                    actorSystem.ActorOf(Props.Create <ClusterPoolActor>()
                                        .WithDispatcher("fast-dispatcher")
                                        .WithRouter(FromConfig.Instance),
                                        "cluster-roundrobin"
                                        ));

                // 스트림 - 밸브조절액터
                int timeSec       = 1;
                var throttleActor = AkkaLoad.RegisterActor(
                    "throttleActor",
                    actorSystem.ActorOf(Props.Create <ThrottleActor>(timeSec)
                                        ));
                var throttleWork = actorSystem.ActorOf(Props.Create <ThrottleWork>(5, 1));
                throttleActor.Tell(new SetTarget(throttleWork));

                try
                {
                    var MonitorTool         = Environment.GetEnvironmentVariable("MonitorTool");
                    var MonitorToolCon      = Environment.GetEnvironmentVariable("MonitorToolCon");
                    var MonitorToolCons     = MonitorToolCon.Split(":");
                    string StatsdServerName = MonitorToolCons[0];
                    int StatsdPort          = 8125;
                    if (MonitorToolCons.Length > 1 && 10 > MonitorToolCons.Length)
                    {
                        StatsdPort = int.Parse(MonitorToolCons[1]);
                    }
                    switch (MonitorTool)
                    {
                    case "win":
                        var win = ActorMonitoringExtension.RegisterMonitor(actorSystem,
                                                                           new ActorPerformanceCountersMonitor(
                                                                               new CustomMetrics
                        {
                            Counters =
                            {
                                "akka.custom.metric1",   "akka.custom.metric2", "akka.custom.metric3",
                                "akka.custom.received1", "akka.custom.received2"
                            },
                            Gauges = { "akka.gauge.msg10", "akka.gauge.msg100", "akka.gauge.msg1000", "akka.gauge.msg10000" },
                            Timers = { "akka.handlertime" }
                        }));

                        // 윈도우 성능 모니터링 수집대상항목은 최초 Admin권한으로 akka항목으로 레지스트리에 프로그램실행시 자동 등록되며
                        // 커스텀항목 결정및 최초 1번 작동후 변경되지 않음으로
                        // 수집 항목 변경시 아래 Register 삭제후 다시 최초 Admin권한으로 작동
                        // Actor명으로 매트릭스가 분류됨으로 기능단위의 네이밍이 권장됨
                        // HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Akka\Performance
                        break;

                    case "azure":
                        var azure = ActorMonitoringExtension.RegisterMonitor(actorSystem, new ActorAppInsightsMonitor(appConfig.MonitorToolCon));
                        break;

                    case "prometheus":
                        // prometheusMonotor 를 사용하기위해서, MerticServer를 켠다...(수집형 모니터)
                        // http://localhost:10250/metrics
                        metricServer = new MetricServer(10250);
                        metricServer.Start();
                        var prometheus = ActorMonitoringExtension.RegisterMonitor(actorSystem, new ActorPrometheusMonitor(actorSystem));
                        break;

                    case "datadog":
                        var statsdConfig = new StatsdConfig
                        {
                            StatsdServerName = StatsdServerName,
                            StatsdPort       = StatsdPort
                        };
                        var dataDog = ActorMonitoringExtension.
                                      RegisterMonitor(actorSystem, new ActorDatadogMonitor(statsdConfig));
                        break;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("=============== Not Suport Window Monitor Tools ===============");
                }

                ActorMonitoringExtension.Monitors(actorSystem).IncrementDebugsLogged();
            });

            lifetime.ApplicationStopping.Register(() =>
            {
                Console.WriteLine("=============== Start Graceful Down ===============");
                var actorSystem = app.ApplicationServices.GetService <ActorSystem>();

                if (appConfig.MonitorTool == "prometheus")
                {
                    metricServer.Stop();
                }

                // Graceful Down Test,Using CashGateActor Actor
                AkkaLoad.ActorSelect("cashpass").Ask(new StopActor()).Wait();


                var cluster = Akka.Cluster.Cluster.Get(actorSystem);
                cluster.RegisterOnMemberRemoved(() => MemberRemoved(actorSystem));
                cluster.Leave(cluster.SelfAddress);
                asTerminatedEvent.WaitOne();

                Console.WriteLine($"=============== Completed Graceful Down : {cluster.SelfAddress} ===============");
            });
        }
Esempio n. 46
0
 /// <summary>
 /// N/A
 /// </summary>
 /// <param name="system">N/A</param>
 /// <exception cref="NotImplementedException">
 /// This exception is thrown automatically since surrogates aren't supported by this router.
 /// </exception>
 /// <returns>N/A</returns>
 public override ISurrogate ToSurrogate(ActorSystem system)
 {
     throw new NotImplementedException();
 }
Esempio n. 47
0
 public override IMessageQueue Create(IActorRef owner, ActorSystem system)
 {
     return(new PriorityMessageQueue(ShallDrop, IsHighPriority));
 }
Esempio n. 48
0
        private async void MemberRemoved(ActorSystem actorSystem)
        {
            await actorSystem.Terminate();

            asTerminatedEvent.Set();
        }
Esempio n. 49
0
 /// <summary>
 ///     Performs all of the setup and initialization needed to get the Zipkin Kafka reporting engine up and running.
 /// </summary>
 /// <param name="kafkaBrokerEndpoint">A single kafka broker endpoint.</param>
 /// <param name="actorSystem">
 ///     Optional. If using Akka.NET, you can hook your own <see cref="ActorSystem" /> into our
 ///     reporting engine.
 /// </param>
 /// <returns></returns>
 public static ZipkinKafkaSpanReporter Create(string kafkaBrokerEndpoint,
                                              ActorSystem actorSystem = null)
 {
     return(Create(new[] { kafkaBrokerEndpoint }, actorSystem));
 }
Esempio n. 50
0
 public static RARP For(ActorSystem system)
 {
     return(system.WithExtension <RARP, RARP>());
 }
Esempio n. 51
0
 public void Teardown(BenchmarkContext context)
 {
     _system.Terminate().Wait(TimeSpan.FromSeconds(2.0d));
     _system = null;
 }
Esempio n. 52
0
 /// <summary>
 ///     Performs all of the setup and initialization needed to get the Zipkin Kafka reporting engine up and running.
 /// </summary>
 /// <param name="kafkaBrokerEndpoints">A list of kafka broker endpoints.</param>
 /// <param name="actorSystem">
 ///     Optional. If using Akka.NET, you can hook your own <see cref="ActorSystem" /> into our
 ///     reporting engine.
 /// </param>
 /// <returns></returns>
 public static ZipkinKafkaSpanReporter Create(IReadOnlyList <string> kafkaBrokerEndpoints,
                                              ActorSystem actorSystem = null)
 {
     return(Create(new ZipkinKafkaReportingOptions(kafkaBrokerEndpoints), actorSystem));
 }
Esempio n. 53
0
 private MyActor(ActorSystem system) => _system = system;
Esempio n. 54
0
 internal ZipkinKafkaSpanReporter(IActorRef reporterActorRef, ActorSystem ownedActorSystem = null)
 {
     _reporterActorRef = reporterActorRef;
     _ownedActorSystem = ownedActorSystem;
 }
Esempio n. 55
0
 public TestTransport(ActorSystem system, Config conf)
     : this(
         Address.Parse(GetConfigString(conf, "local-address")), AssociationRegistry.Get(GetConfigString(conf, "registry-key")),
         GetConfigString(conf, "scheme-identifier"))
 {
 }
Esempio n. 56
0
 public void Setup(BenchmarkContext context)
 {
     _system = ActorSystem.Create("ActorMemoryFootprintSpec" + Counter.GetAndIncrement());
     _createActorThroughput = context.GetCounter(CreateThroughputCounter);
 }
Esempio n. 57
0
 protected AbstractSerializationTransportInformationSpec(Config config, ITestOutputHelper helper = null)
     : base(config.WithFallback(Config), output: helper)
 {
     System2 = ActorSystem.Create(Sys.Name, Sys.Settings.Config);
 }
Esempio n. 58
0
 public AkkaNinjectDependencyResolver(IKernel kernel, ActorSystem system)
     : base(kernel)
 {
     RawAkkaNinjectDependencyResolver = new global::Akka.DI.Ninject.NinjectDependencyResolver(kernel, AkkaSystem = system);
     AkkaActors       = new ConcurrentDictionary <Type, IActorRef>();
     AggregateFactory = Resolve <IAggregateFactory>();
 }
 public void Cleanup()
 {
     _actorSystem.Terminate().Wait();
     _actorSystem = null;
 }
 /// <summary>
 /// TBD
 /// </summary>
 /// <param name="system">TBD</param>
 /// <returns>TBD</returns>
 protected DefaultFailureDetectorRegistry <Address> CreateRemoteWatcherFailureDetector(ActorSystem system)
 {
     return(new DefaultFailureDetectorRegistry <Address>(() =>
                                                         FailureDetectorLoader.Load(RemoteSettings.WatchFailureDetectorImplementationClass,
                                                                                    RemoteSettings.WatchFailureDetectorConfig, _system)));
 }