Example #1
0
 private void CreateSingletonProxy()
 {
     Sys.ActorOf(ClusterSingletonProxy.Props(
                     singletonManagerPath: "/user/consumer",
                     settings: ClusterSingletonProxySettings.Create(Sys).WithRole("worker")),
                 name: "consumerProxy");
 }
Example #2
0
        /// <summary>
        /// Static factory method for creating the a singleton manager and proxy
        /// of the <see cref="ClusterCommandActor"/>
        /// </summary>
        /// <param name="system">The <see cref="ActorSystem"/>within which to create the singleton</param>
        /// <returns>A tuple containing <see cref="Props"/> for the proxy and manager in a given system</returns>
        public static (Props proxy, Props manager) CreateSingleton(ActorSystem system, string role)
        {
            var managerSettings = ClusterSingletonManagerSettings
                                  .Create(system)
                                  .WithSingletonName("cluster-command")
                                  .WithRemovalMargin(TimeSpan.FromSeconds(2))
                                  .WithHandOverRetryInterval(TimeSpan.FromMilliseconds(200));

            managerSettings = role != null?managerSettings.WithRole(role) : managerSettings;

            var proxySettings = ClusterSingletonProxySettings
                                .Create(system)
                                .WithSingletonName("cluster-command-proxy")
                                .WithBufferSize(1000);

            proxySettings = role != null?proxySettings.WithRole(role) : proxySettings;

            var manager = ClusterSingletonManager.Props(
                Props.Create(() => new ClusterCommandActor()),
                PoisonPill.Instance,
                managerSettings
                );

            var proxy = ClusterSingletonProxy.Props(
                "/user/cluster-command",
                proxySettings
                );

            return(proxy : proxy, manager : manager);
        }
Example #3
0
 protected ClusterSingletonManagerStartupSpec() : base(new ClusterSingletonManagerStartupConfig())
 {
     EchoProxy = new Lazy <IActorRef>(() => Sys.ActorOf(ClusterSingletonProxy.Props(
                                                            singletonManagerPath: "/user/echo",
                                                            settings: ClusterSingletonProxySettings.Create(Sys)),
                                                        name: "echoProxy"));
 }
Example #4
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");
 }
Example #5
0
        public static ClusterStartupTask Apply(
            ActorSystem system, string taskName,
            Func <Task <Done> > task, TimeSpan taskTimeout,
            Option <string> role, TimeSpan minBackoff,
            TimeSpan maxBackoff, double randomBackoffFactor)
        {
            var startupTaskProps = Akka.Actor.Props.Create(
                () => new ClusterStartupTaskActor(
                    task, taskTimeout
                    )
                );
            var backoffProps = BackoffSupervisor.PropsWithSupervisorStrategy(
                startupTaskProps, taskName, minBackoff, maxBackoff, randomBackoffFactor, SupervisorStrategy.StoppingStrategy
                );
            var singletonProps = ClusterSingletonManager.Props(
                backoffProps, PoisonPill.Instance, ClusterSingletonManagerSettings.Create(system)
                );
            var singleton      = system.ActorOf(singletonProps, $"{taskName}-singleton");
            var singletonProxy = system.ActorOf(
                ClusterSingletonProxy.Props(
                    singletonManagerPath: singleton.Path.ToStringWithoutAddress(),
                    settings: ClusterSingletonProxySettings.Create(system).WithRole(role.Value)
                    ),
                $"{taskName}-singletonProxy"
                );

            return(new ClusterStartupTask(singletonProxy));
        }
Example #6
0
        private static async Task Main()
        {
            Console.WriteLine("Starting sender system...");
            var system = ActorSystem.Create("ClusterSys", ConfigurationFactory.ParseString(File.ReadAllText("Akka.hocon")));

            Console.ReadKey();

            system.ActorOf(ClusterSingletonManager.Props(
                               Props.Create <SingletonActor>(),
                               PoisonPill.Instance,
                               ClusterSingletonManagerSettings.Create(system).WithRole("b")
                               ), "single");

            system.ActorOf(ClusterSingletonProxy.Props("/user/single",
                                                       ClusterSingletonProxySettings.Create(system).WithRole("b")),
                           "singleProxy").Tell("Hello to singletone!");

            var message  = "initial message";
            var mediator = DistributedPubSub.Get(system).Mediator;

            mediator.Tell(new Send("/user/invoker", "Remote hello to singleton!"));

            while (!message.Equals("Stop"))
            {
                Console.WriteLine("New message:");
                message = Console.ReadLine();

                mediator.Tell(new Send("/user/ping", message, false));
            }

            Console.WriteLine("Terminating system.");
            await system.Terminate();

            Console.WriteLine("Bye...");
        }
        protected ClusterSingletonManagerLeaveSpec(ClusterSingletonManagerLeaveSpecConfig config) : base(config, typeof(ClusterSingletonManagerLeaveSpec))
        {
            _config = config;

            _echoProxy = new Lazy <IActorRef>(() => Watch(Sys.ActorOf(ClusterSingletonProxy.Props(
                                                                          singletonManagerPath: "/user/echo",
                                                                          settings: ClusterSingletonProxySettings.Create(Sys)),
                                                                      name: "echoProxy")));
        }
Example #8
0
        IActorRef GetClusterSingletonProxy(ActorSystem ActorSystem)
        {
            Props clusterSingletonProxyProps = ClusterSingletonProxy.Props(
                singletonManagerPath: "/user/singletonManager",
                settings: ClusterSingletonProxySettings.Create(ActorSystem));

            var proxy = ActorSystem.ActorOf(clusterSingletonProxyProps, name: "consumerProxy");

            return(proxy);
        }
Example #9
0
        public void ClusterSingletonProxySettings_must_have_default_config()
        {
            var clusterSingletonProxySettings = ClusterSingletonProxySettings.Create(Sys);

            clusterSingletonProxySettings.ShouldNotBe(null);
            clusterSingletonProxySettings.SingletonName.ShouldBe("singleton");
            clusterSingletonProxySettings.Role.ShouldBe(null);
            clusterSingletonProxySettings.SingletonIdentificationInterval.TotalSeconds.ShouldBe(1);
            clusterSingletonProxySettings.BufferSize.ShouldBe(1000);
        }
        public void Restarting_cluster_node_during_hand_over_must_restart_singletons_in_restarted_node()
        {
            Join(_sys1, _sys1);
            Join(_sys2, _sys1);
            Join(_sys3, _sys1);

            var proxy3 = _sys3.ActorOf(
                ClusterSingletonProxy.Props("user/echo", ClusterSingletonProxySettings.Create(_sys3).WithRole("singleton")), "proxy3");

            Within(TimeSpan.FromSeconds(5), () =>
            {
                AwaitAssert(() =>
                {
                    var probe = CreateTestProbe(_sys3);
                    proxy3.Tell("hello", probe.Ref);
                    probe.ExpectMsg <UniqueAddress>(TimeSpan.FromSeconds(1))
                    .Should()
                    .Be(Cluster.Get(_sys1).SelfUniqueAddress);
                });
            });

            Cluster.Get(_sys1).Leave(Cluster.Get(_sys1).SelfAddress);

            // at the same time, shutdown sys2, which would be the expected next singleton node
            Shutdown(_sys2);
            // it will be downed by the join attempts of the new incarnation

            // then restart it
            // ReSharper disable once PossibleInvalidOperationException
            var sys2Port   = Cluster.Get(_sys2).SelfAddress.Port.Value;
            var sys4Config = ConfigurationFactory.ParseString(@"akka.remote.dot-netty.tcp.port=" + sys2Port)
                             .WithFallback(_sys1.Settings.Config);

            _sys4 = ActorSystem.Create(_sys1.Name, sys4Config);

            Join(_sys4, _sys3);

            // let it stabilize
            Task.Delay(TimeSpan.FromSeconds(5)).Wait();

            Within(TimeSpan.FromSeconds(10), () =>
            {
                AwaitAssert(() =>
                {
                    var probe = CreateTestProbe(_sys3);
                    proxy3.Tell("hello2", probe.Ref);

                    // note that sys3 doesn't have the required singleton role, so singleton instance should be
                    // on the restarted node
                    probe.ExpectMsg <UniqueAddress>(TimeSpan.FromSeconds(1))
                    .Should()
                    .Be(Cluster.Get(_sys4).SelfUniqueAddress);
                });
            });
        }
Example #11
0
        public static void AddSystemActor(this IServiceCollection services)
        {
            var sc = services.BuildServiceProvider();

            services.AddSingleton <ActorSystem>(s =>
            {
                var serilogger = s.GetService <ILogger>();
                var fs         = sc.GetService <IBaseFileFactory>();
                var conf       = ConfigurationFactory.ParseString(fs.ReadRelative("web.hocon"));
                var system     = ActorSystem.Create("sbk", conf);

                // Create actors
                var playerMgr = system.ActorOf(Props.Empty.WithRouter(FromConfig.Instance),
                                               "player-managers");


                var playerHub = s.GetService <IHubContext <PlayerHub> >();

                // local hub actor
                var webHub = system.ActorOf(WebHub.Props(playerHub), "web-hub");
                // cluster-enabled hub router
                system.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), "hub");

                var logger = system.Log;
                logger.Info($"Player Manager:  ------->>>  {playerMgr}");
                logger.Info($"{system.Name}");

                return(system);
            });

            services.AddTransient <Startup.PlayerManagerProvider>(s =>
            {
                var sys = s.GetService <ActorSystem>();
                return(() => sys.ActorSelection("/user/player-managers"));
            });

            services.AddTransient <Startup.PlayerBookProxyProvider>(s =>
            {
                var sys        = s.GetService <ActorSystem>();
                var logger     = sys.Log;
                var playerBook = sys.ActorOf(ClusterSingletonProxy.Props(
                                                 singletonManagerPath: "/user/playerbook",
                                                 settings: ClusterSingletonProxySettings.Create(sys)
                                                 .WithRole("player-manager")),
                                             name: "playerbook-proxy");
                logger.Info($"Playerbook ----->> {playerBook}");
                return(() => playerBook);
            });

            services.AddTransient <Startup.WebHubProvider>(s =>
            {
                var sys = s.GetService <ActorSystem>();
                return(() => sys.ActorSelection("/user/web-hub"));
            });
        }
        protected ClusterSingletonManagerLeaveSpec(ClusterSingletonManagerLeaveSpecConfig config) : base(config)
        {
            _first  = config.First;
            _second = config.Second;
            _third  = config.Third;

            _echoProxy = new Lazy <IActorRef>(() => Sys.ActorOf(ClusterSingletonProxy.Props(
                                                                    singletonManagerPath: "/user/echo",
                                                                    settings: ClusterSingletonProxySettings.Create(Sys)),
                                                                "echoProxy"));
        }
        public static IActorRef StartSingletonSubscriberProxy(ActorSystem actorSystem, string roleName)
        {
            var name = typeof(TDomainEventSubscriber).Name;

            var proxy = actorSystem.ActorOf(ClusterSingletonProxy.Props(
                                                $"/user/{name}",
                                                ClusterSingletonProxySettings.Create(actorSystem).WithRole(roleName).WithSingletonName(name)),
                                            $"{name}Proxy");

            return(proxy);
        }
Example #14
0
        static void Main(string[] args)
        {
            var config = ConfigurationFactory.ParseString(File.ReadAllText("App.Akka.conf"));

            //
            // "{app-name} - akka.tcp://{actorysystem-name}@{hostname}:{port}"
            //
            Console.Title = $"{config.GetString("akka.system.app-name")}" +
                            $" - akka.tcp://{config.GetString("akka.system.actorsystem-name")}" +
                            $"@{config.GetString("akka.remote.dot-netty.tcp.hostname")}" +
                            $":{config.GetString("akka.remote.dot-netty.tcp.port")}";

            ActorSystem system = ActorSystem.Create("ClusterLab", config);

            system.ActorOf(ClusterSingletonManager
                           .Props(
                               singletonProps: MySingletonActor.Props(),
                               terminationMessage: PoisonPill.Instance,
                               settings: ClusterSingletonManagerSettings.Create(system)
                               .WithRole("Provider")),
                           name: "ConsumerSingleton");

            IActorRef singletonProxyActor = system.ActorOf(ClusterSingletonProxy
                                                           .Props(
                                                               singletonManagerPath: "/user/ConsumerSingleton",
                                                               settings: ClusterSingletonProxySettings.Create(system)
                                                               .WithRole("Provider")),
                                                           name: "ConsumerProxy");

            system.Scheduler.ScheduleTellRepeatedly(
                TimeSpan.Zero,
                TimeSpan.FromSeconds(4),
                singletonProxyActor,
                $"Message from process {Process.GetCurrentProcess().Id}",
                Nobody.Instance);

            //
            // TODO ClusterSingletonManagerSettings 세부 설정
            //  - WithHandOverRetryInterval
            //  - WithRemovalMargin
            //  - WithRole
            //  - WithSingletonName
            //

            Console.WriteLine();
            Console.WriteLine("NonSeedNode1 is running...");
            Console.WriteLine();

            Console.ReadLine();
        }
Example #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello from MemoryWallet!");

            var system = DI.Provider.GetService <ActorSystem>();

            var logger = system.Log;

            logger.Info($"Joining cluster {system.Name}");

            // Singleton actor that keeps book of record of a player
            system.ActorOf(ClusterSingletonManager.Props(
                               singletonProps: PlayerBook.Props(),
                               terminationMessage: PoisonPill.Instance,
                               settings: ClusterSingletonManagerSettings.Create(system).WithRole("player-manager")
                               ), "playerbook");

            system.ActorOf(ClusterSingletonProxy.Props(
                               singletonManagerPath: "/user/playerbook",
                               settings: ClusterSingletonProxySettings.Create(system)
                               .WithRole("player-manager")),
                           name: "playerbook-proxy");

            // Register web hub across cluster
            var hub = system.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), "hub");

            // create local player manager instances with router.
            var pm = system.ActorOf(PlayerManagerActor.Props(), "player-manager");

//            var pm = system.ActorOf(
//                PlayerManagerActor.Props().WithRouter(FromConfig.Instance),
//                "player-manager");

            hub.Tell("dsadsada");

            pm.Tell(new PlayerManagerActor.HelloWorld("hello world"));

            logger.Info($"{pm.Path} created.");



            Console.ReadLine();

            CoordinatedShutdown.Get(system)
            .Run(CoordinatedShutdown.ClrExitReason.Instance)
            .Wait();
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            var config    = ConfigurationFactory.ParseString(File.ReadAllText("app.conf")).BootstrapFromDocker();
            var bootstrap = BootstrapSetup.Create()
                            .WithConfig(config)                                        // load HOCON
                            .WithActorRefProvider(ProviderSelection.Cluster.Instance); // launch Akka.Cluster

            // N.B. `WithActorRefProvider` isn't actually needed here - the HOCON file already specifies Akka.Cluster

            // enable DI support inside this ActorSystem, if needed
            var diSetup = ServiceProviderSetup.Create(_serviceProvider);

            // merge this setup (and any others) together into ActorSystemSetup
            var actorSystemSetup = bootstrap.And(diSetup);

            ThreadPool.GetMinThreads(out var workerThreads, out var completionThreads);
            Console.WriteLine("Min threads: {0}, Min I/O threads: {1}", workerThreads, completionThreads);
            ThreadPool.SetMinThreads(0, 0);

            // start ActorSystem
            _clusterSystem = ActorSystem.Create("ClusterSys", actorSystemSetup);

            DebugConfigurator("akka.actor.default-dispatcher", _clusterSystem);
            DebugConfigurator("akka.actor.internal-dispatcher", _clusterSystem);
            DebugConfigurator("akka.remote.default-remote-dispatcher", _clusterSystem);
            DebugConfigurator("akka.remote.backoff-remote-dispatcher", _clusterSystem);

            // instantiate actors
            BenchmarkHostRouter = _clusterSystem.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), "host-router");

            BenchmarkCoordinatorManager = _clusterSystem.ActorOf(ClusterSingletonManager.Props(
                                                                     singletonProps: Props.Create(() => new BenchmarkCoordinator(2, 6, BenchmarkHostRouter)),
                                                                     terminationMessage: PoisonPill.Instance,
                                                                     settings: ClusterSingletonManagerSettings.Create(_clusterSystem)), "coordinator");

            BenchmarkCoordinator = _clusterSystem.ActorOf(ClusterSingletonProxy.Props(
                                                              singletonManagerPath: "/user/coordinator",
                                                              settings: ClusterSingletonProxySettings.Create(_clusterSystem)), "coordinator-proxy");

            BenchmarkHost = _clusterSystem.ActorOf(Props.Create(() => new BenchmarkHost(BenchmarkCoordinator)), "host");

            Akka.Cluster.Cluster.Get(_clusterSystem).RegisterOnMemberRemoved(() => {
                _lifetime.StopApplication(); // when the ActorSystem terminates, terminate the process
            });

            return(Task.CompletedTask);
        }
Example #17
0
        public IActorRef Start()
        {
            var dispatcher = _system.ActorOf(ClusterSingletonManager.Props(
                                                 Props.Create <ReportingActor>(),
                                                 PoisonPill.Instance,
                                                 ClusterSingletonManagerSettings.Create(_system).WithRole(KnownRoles.Projection)
                                                 ),
                                             name: "reporting");

            ReportingActor = _system.ActorOf(ClusterSingletonProxy.Props(
                                                 singletonManagerPath: "/user/reporting",
                                                 settings: ClusterSingletonProxySettings.Create(_system).WithRole(KnownRoles.Projection)),
                                             name: "reportingProxy");

            ReportingActor.Tell(Reports.ReportingActor.Start.Instance);
            return(ReportingActor);
        }
Example #18
0
        private void BecomeReady()
        {
            Become(Ready);
            _logger.Info("JobMaster is becoming ready.");

            var proxy = Context.ActorOf(ClusterSingletonProxy.Props(
                                            singletonManagerPath: "/user/jobmanager",
                                            settings: ClusterSingletonProxySettings.Create(Context.System).WithRole("worker")),
                                        name: "managerProxy");

            _workerRouter = Context.ActorOf(new ClusterRouterPool(
                                                local: new RandomPool(1),
                                                settings: new ClusterRouterPoolSettings(30, 1, true, "worker")
                                                ).Props(Props.Create(() => new Worker(proxy))));

            Context.ActorOf(Props.Create(() => new JobTasker(Self)), "jobtasker");

            _workItem = 0;
        }
Example #19
0
        static void Main(string[] args)
        {
            var config = ConfigurationFactory.ParseString(configString).WithFallback(ClusterSingletonManager.DefaultConfig());
            var system = ActorSystem.Create("cluster-system", config);

            var client =
                system
                .ActorOf(
                    ClusterSingletonProxy.Props("/user/consumer",
                                                ClusterSingletonProxySettings.Create(system).WithRole("worker")));

            while (true)
            {
                Thread.Sleep(1000);
                client.Tell(DateTime.Now.ToLongTimeString());
            }

            Console.ReadKey();
        }
Example #20
0
            public ActorSys(string name = "ClusterSingletonProxySystem", Address joinTo = null)
                : base(ActorSystem.Create(name, ConfigurationFactory.ParseString(_cfg).WithFallback(TestKit.Configs.TestConfigs.DefaultConfig)))
            {
                Cluster = Cluster.Get(Sys);
                if (joinTo != null)
                {
                    Cluster.Join(joinTo);
                }

                Cluster.RegisterOnMemberUp(() =>
                {
                    Sys.ActorOf(ClusterSingletonManager.Props(Props.Create(() => new Singleton()), PoisonPill.Instance,
                                                              ClusterSingletonManagerSettings.Create(Sys)
                                                              .WithRemovalMargin(TimeSpan.FromSeconds(5))), "singletonmanager");
                });

                Proxy =
                    Sys.ActorOf(ClusterSingletonProxy.Props("user/singletonmanager",
                                                            ClusterSingletonProxySettings.Create(Sys)), $"singletonProxy-{Cluster.SelfAddress.Port ?? 0}");
            }
Example #21
0
        internal static async Task Main()
        {
            Console.WriteLine("Starting Akka System...");
            var system = ActorSystem.Create("ClusterSys", ConfigurationFactory.ParseString(File.ReadAllText("Akka.hocon")));

            system.ActorOf(Props.Create <AMediatorReceiver>(), "ping");
            system.ActorOf(Props.Create <AClusterInvoker>(), "invoker");

            // singleton proxy
            system.ActorOf(ClusterSingletonProxy.Props("/user/single",
                                                       ClusterSingletonProxySettings.Create(system).WithRole("b")),
                           "singletonProxy");

            Console.WriteLine("System started. Press Enter to terminate...");
            Console.ReadLine();

            await system.Terminate();

            Console.WriteLine("Cluster is terminated. Bye...");
        }
Example #22
0
        public static async Task Main(string[] args)
        {
            var config        = ConfigurationFactory.ParseString(AtmHocon);
            var actorSystem   = ActorSystem.Create(ClusterName, config);
            var clusterSystem = Cluster.Get(actorSystem);

            clusterSystem.RegisterOnMemberUp(() =>
            {
                var atm       = actorSystem.ActorOf(Props.Create(() => new AtmV3Actor()), "atm-terry-avenue");
                var bankProxy = actorSystem.ActorOf(ClusterSingletonProxy.Props(
                                                        singletonManagerPath: $"/user/{BankActorName}",
                                                        settings: ClusterSingletonProxySettings.Create(actorSystem).WithRole(BankRoleName)),
                                                    name: $"{BankActorName}-proxy");

                atm.Tell(new BasicBank.Messages.Bank.SetBank(bankProxy));
            });

            while (true)
            {
                await Task.Delay(10);
            }
        }
        public void Cluster_singleton_manager_with_lease_should_Start_singleton_and_ping_from_all_nodes()
        {
            RunOn(() =>
            {
                Sys.ActorOf(
                    ClusterSingletonManager.Props(
                        ClusterSingletonManagerLeaseSpecConfig.ImportantSingleton.Props, PoisonPill.Instance, ClusterSingletonManagerSettings.Create(Sys).WithRole("worker")),
                    "important");
            }, _config.First, _config.Second, _config.Third, _config.Fourth);
            EnterBarrier("singleton-started");

            var proxy = Sys.ActorOf(
                ClusterSingletonProxy.Props(
                    singletonManagerPath: "/user/important",
                    settings: ClusterSingletonProxySettings.Create(Sys).WithRole("worker")));

            RunOn(() =>
            {
                proxy.Tell("Ping");
                // lease has not been granted so now allowed to come up
                ExpectNoMsg(TimeSpan.FromSeconds(2));
            }, _config.First, _config.Second, _config.Third, _config.Fourth);
            EnterBarrier("singleton-pending");

            RunOn(() =>
            {
                TestLeaseActorClientExt.Get(Sys).GetLeaseActor().Tell(TestLeaseActor.GetRequests.Instance);
                ExpectMsg <TestLeaseActor.LeaseRequests>(msg => msg.Requests.Should().BeEquivalentTo(new TestLeaseActor.Acquire(GetAddress(_config.First).HostPort())));
                TestLeaseActorClientExt.Get(Sys).GetLeaseActor().Tell(new TestLeaseActor.ActionRequest(new TestLeaseActor.Acquire(GetAddress(_config.First).HostPort()), true));
            }, _config.Controller);
            EnterBarrier("lease-acquired");

            RunOn(() =>
            {
                ExpectMsg(new ClusterSingletonManagerLeaseSpecConfig.ImportantSingleton.Response("Ping", GetAddress(_config.First)));
            }, _config.First, _config.Second, _config.Third, _config.Fourth);
            EnterBarrier("pinged");
        }
Example #24
0
        public static async Task Main(string[] args)
        {
            var config        = ConfigurationFactory.ParseString(BankHocon);
            var actorSystem   = ActorSystem.Create(ClusterName, config);
            var clusterSystem = Cluster.Get(actorSystem);

            clusterSystem.RegisterOnMemberUp(() =>
            {
                actorSystem.ActorOf(ClusterSingletonManager.Props(
                                        Props.Create(() => new BasicBank.Actors.BankV2Actor()),
                                        settings: ClusterSingletonManagerSettings.Create(actorSystem).WithRole(BankRoleName)),
                                    BankActorName);

                var bankProxy = actorSystem.ActorOf(ClusterSingletonProxy.Props(
                                                        singletonManagerPath: $"/user/{BankActorName}",
                                                        settings: ClusterSingletonProxySettings.Create(actorSystem).WithRole(BankRoleName)),
                                                    name: $"{BankActorName}-proxy");

                Console.BackgroundColor = ConsoleColor.Black;
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("BANK NODE UP!");

                Console.WriteLine("ADD Billy White.");
                bankProxy.Tell(new CreateCustomerRequest(new Customer(123, "Billy White")));
                Console.WriteLine("ADD Sally Brown.");
                bankProxy.Tell(new CreateCustomerRequest(new Customer(456, "Sally Brown")));
                Console.WriteLine("ADD Wally Green.");
                bankProxy.Tell(new CreateCustomerRequest(new Customer(789, "Wally Green")));
                Console.ResetColor();
            });

            while (true)
            {
                await Task.Delay(10);
            }
        }
        public void Restarting_cluster_node_with_same_hostname_and_port_must_handover_to_next_oldest()
        {
            Join(_sys1, _sys1);
            Join(_sys2, _sys1);

            var proxy2 = _sys2.ActorOf(
                ClusterSingletonProxy.Props("user/echo", ClusterSingletonProxySettings.Create(_sys2)), "proxy2");

            Within(TimeSpan.FromSeconds(5), () =>
            {
                AwaitAssert(() =>
                {
                    var probe = CreateTestProbe(_sys2);
                    proxy2.Tell("hello", probe.Ref);
                    probe.ExpectMsg("hello", TimeSpan.FromSeconds(1));
                });
            });

            Shutdown(_sys1);
            // it will be downed by the join attempts of the new incarnation

            // ReSharper disable once PossibleInvalidOperationException
            var sys1Port   = Cluster.Get(_sys1).SelfAddress.Port.Value;
            var sys3Config = ConfigurationFactory.ParseString(@"akka.remote.dot-netty.tcp.port=" + sys1Port)
                             .WithFallback(_sys1.Settings.Config);

            _sys3 = ActorSystem.Create(_sys1.Name, sys3Config);

            Join(_sys3, _sys2);

            Within(TimeSpan.FromSeconds(5), () =>
            {
                AwaitAssert(() =>
                {
                    var probe = CreateTestProbe(_sys2);
                    proxy2.Tell("hello2", probe.Ref);
                    probe.ExpectMsg("hello2", TimeSpan.FromSeconds(1));
                });
            });

            Cluster.Get(_sys2).Leave(Cluster.Get(_sys2).SelfAddress);

            Within(TimeSpan.FromSeconds(15), () =>
            {
                AwaitAssert(() =>
                {
                    Cluster.Get(_sys3)
                    .State.Members.Select(x => x.UniqueAddress)
                    .Should()
                    .Equal(Cluster.Get(_sys3).SelfUniqueAddress);
                });
            });

            var proxy3 =
                _sys3.ActorOf(ClusterSingletonProxy.Props("user/echo", ClusterSingletonProxySettings.Create(_sys3)),
                              "proxy3");

            Within(TimeSpan.FromSeconds(5), () =>
            {
                AwaitAssert(() =>
                {
                    var probe = CreateTestProbe(_sys3);
                    proxy3.Tell("hello3", probe.Ref);
                    probe.ExpectMsg("hello3", TimeSpan.FromSeconds(1));
                });
            });
        }
Example #26
0
        /// <summary>
        /// Creates a new actor system according to the supplied parameters and the
        /// "hub.hocon" file
        ///
        /// Assumed transport used is tcp
        /// </summary>
        /// <param name="systemName">System name</param>
        /// <param name="hostname">IP address or hostname</param>
        /// <param name="requestedPort">Non-zero port</param>
        /// <returns>The Actor System</returns>
        public static ActorSystem Create(string systemName, string hostname, int?requestedPort)
        {
            if (!File.Exists("hub.hocon"))
            {
                throw new FileLoadException($"Could not find 'hub.hocon' file in {Directory.GetCurrentDirectory()}");
            }

            // Reads in the entire hocon configuration and parses to a Config object
            var configText    = File.ReadAllText("hub.hocon");
            var clusterConfig = ConfigurationFactory.ParseString(configText);

            // Find the "hub" specific configuration
            var hubConfig = clusterConfig.GetConfig("hub");

            // Set the actor system name if supplied value is null or empty
            if (hubConfig != null && string.IsNullOrEmpty(systemName))
            {
                systemName = hubConfig.GetString("actorsystem");
            }

            var remoteConfig = clusterConfig.GetConfig("akka.remote");

            if (string.IsNullOrEmpty(hostname))
            {
                // Defaults to localhost as final step
                hostname = remoteConfig.GetString("dot-netty.tcp.public-hostname") ?? "127.0.0.1";
            }

            int port = requestedPort ?? remoteConfig.GetInt("dot-netty.tcp.port");

            if (port == 0)
            {
                throw new ConfigurationException("An explicit port must be specified for the Hub. Zero is unnacceptable.");
            }

            // Display configuration
            Log.Information($"[Cluster Hub] ActorSystem: {systemName}; IP: {hostname}; PORT: {port}");
            Log.Information($"[Cluster Hub] Parsing address");
            Log.Information("[Cluster Hub] Parse successful");
            Log.Information("[Cluster Hub] Public hostname {PublicHubHostname}", hostname);

            var selfAddress = new Address("akka.tcp", systemName, hostname.Trim(), port).ToString();

            var seeds = clusterConfig.GetStringList("akka.cluster.seed-nodes");

            seeds.Add(selfAddress);

            var injectedClusterConfigString = seeds.Aggregate("akka.cluster.seed-nodes = [", (current, seed) => current + (@"""" + seed + @""","));

            injectedClusterConfigString += "]";

            var finalConfig = ConfigurationFactory.ParseString(
                string.Format("akka.remote.dot-netty.tcp.public-hostname = {0}, akka.remote.dot-netty.tcp.port = {1}", hostname, port)
                )
                              .WithFallback(ConfigurationFactory.ParseString(injectedClusterConfigString))
                              .WithFallback(clusterConfig);

            // Create the actor system
            var system = ActorSystem.Create(systemName, finalConfig);

            var proxySettings = ClusterSingletonProxySettings.Create(system).WithBufferSize(1000);

            var name = "manager";

            // Create the cluster singleton proxy for the node manager
            var managerProxy = system.ActorOf(
                ClusterSingletonProxy.Props(
                    singletonManagerPath: $"/user/{name}",
                    settings: proxySettings
                    ),
                $"{name}-proxy");

            // Subscribe the forwarder to the client receptionist topic
            var forwarder = system.ActorOf(Props.Create(() => new PublisherActor("client-messages")), "forwarder");

            ClusterClientReceptionist.Get(system).RegisterSubscriber("client-messages", forwarder);
            // ClusterClientReceptionist.Get(system).RegisterService(managerProxy);

            return(system);
        }
Example #27
0
 /// <summary>
 /// Creates a cluster singleton proxy. Unlike <see cref="SingletonOf"/>, it will not create
 /// an actor, but it can be used to communicate with cluster singleton without need to route
 /// to it. In case of transition i.e. when cluster singleton will migrate from one node
 /// to another, proxy will buffer the messages.
 /// </summary>
 /// <param name="system"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 public static IActorRef SingletonProxy(this ActorSystem system, string name)
 {
     return(system.ActorOf(ClusterSingletonProxy.Props(
                               singletonManagerPath: $"/user/{name}",
                               settings: ClusterSingletonProxySettings.Create(system).WithRole(name)), $"{name}-proxy"));
 }
Example #28
0
        public void Start()
        {
            SystemActors.ClusterSystem = SystemHostFactory.Launch();

            // Create and build the container
            var container = new Ninject.StandardKernel();

            container.Bind <IFileProcessorRepository>().To(typeof(FileProcessorRepository)).InTransientScope();
            container.Bind <DistributedPubSub>().ToConstant(DistributedPubSub.Get(SystemActors.ClusterSystem));


            // Create the dependency resolver for the actor system
            IDependencyResolver resolver = new NinjectDependencyResolver(container, SystemActors.ClusterSystem);

            var pbm = PetabridgeCmd.Get(SystemActors.ClusterSystem);

            pbm.RegisterCommandPalette(ClusterCommands.Instance); // enable cluster management commands
            pbm.Start();

            SystemActors.SettingsWatcherRef = SystemActors.ClusterSystem.ActorOf(SystemActors.ClusterSystem.DI().Props <DatabaseWatcherActor>(), "DatabaseWatcher");
            SystemActors.Mediator           = DistributedPubSub.Get(SystemActors.ClusterSystem).Mediator;

            SystemActors.LocationManagerActorRef = SystemActors.ClusterSystem.ActorOf(ClusterSingletonManager.Props(
                                                                                          singletonProps: Props.Create(() => new LocationManagerActor()),                                                               // Props used to create actor singleton
                                                                                          terminationMessage: PoisonPill.Instance,                                                                                      // message used to stop actor gracefully
                                                                                          settings: ClusterSingletonManagerSettings.Create(SystemActors.ClusterSystem).WithRole(StaticMethods.GetServiceWorkerRole())), // cluster singleton manager settings
                                                                                      name: ActorPaths.SingletonManagerActor.Name);

            SystemActors.LocationManagerProxyRef = SystemActors.ClusterSystem.ActorOf(ClusterSingletonProxy.Props(
                                                                                          singletonManagerPath: ActorPaths.SingletonManagerActor.Path,
                                                                                          settings: ClusterSingletonProxySettings.Create(SystemActors.ClusterSystem).WithRole(StaticMethods.GetServiceWorkerRole())),
                                                                                      name: ActorPaths.SingletonManagerProxy.Name);
        }
Example #29
0
        static async Task Main(string[] args)
        {
            var myPort = int.Parse(args[0]);

            var portConfig = ConfigurationFactory.ParseString($"akka.remote.dot-netty.tcp.port = {myPort}");
            var config     = ConfigurationFactory.ParseString(File.ReadAllText("app.conf")).WithFallback(portConfig);

            using var system = ActorSystem.Create("MyCluster", config);

            var broadcaster = system.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), "broadcaster");


            #region Echo singleton service example

            system.ActorOf(ClusterSingletonManager.Props(
                               singletonProps: Props.Create <EchoService>(),
                               terminationMessage: PoisonPill.Instance,
                               settings: ClusterSingletonManagerSettings.Create(system)
                               ), "echo-single");

            var echoSingleton = new Lazy <IActorRef>(() =>
                                                     system.ActorOf(ClusterSingletonProxy.Props(singletonManagerPath: "/user/echo-single",
                                                                                                settings: ClusterSingletonProxySettings.Create(system)),
                                                                    "echo-proxy"));

            #endregion

            var       quit = false;
            IActorRef echo = ActorRefs.Nobody;
            while (!quit)
            {
                switch (Menu())
                {
                case '1':
                    echo = system.ActorOf(Props.Create(typeof(EchoService)).WithRouter(FromConfig.Instance), "echo");
                    Console.WriteLine("Echo service is created.");
                    break;

                case '2':
                    Console.Write("Input: ");
                    echo.Tell(Console.ReadLine());
                    break;

                case '3':
                    Console.Write("Broadcast: ");
                    broadcaster.Tell(Console.ReadLine());
                    break;

                case '4':
                    Console.Write("To singleton: ");
                    echoSingleton.Value.Tell(Console.ReadLine());
                    break;

                case 'Q':
                    quit = true;
                    break;
                }
            }
            await CoordinatedShutdown.Get(system).Run(CoordinatedShutdown.ClusterLeavingReason.Instance);

            Console.WriteLine("End..");
        }
        public void Cluster_singleton_manager_with_lease_should_Move_singleton_when_oldest_node_downed()
        {
            Cluster.State.Members.Count.ShouldBe(5);

            RunOn(() =>
            {
                Cluster.Down(GetAddress(_config.First));
                AwaitAssert(() =>
                {
                    Cluster.State.Members.Select(i => i.Status).Should().BeEquivalentTo(MemberStatus.Up, MemberStatus.Up, MemberStatus.Up, MemberStatus.Up);
                }, TimeSpan.FromSeconds(20));

                TestLeaseActor.LeaseRequests requests = null;
                AwaitAssert(() =>
                {
                    TestLeaseActorClientExt.Get(Sys).GetLeaseActor().Tell(TestLeaseActor.GetRequests.Instance);
                    var msg = ExpectMsg <TestLeaseActor.LeaseRequests>();

                    msg.Requests.Count.ShouldBe(2, "Requests: " + msg);
                    requests = msg;
                }, TimeSpan.FromSeconds(10));

                requests.Requests.Should().Contain(new TestLeaseActor.Release(GetAddress(_config.First).HostPort()));
                requests.Requests.Should().Contain(new TestLeaseActor.Acquire(GetAddress(_config.Second).HostPort()));
            }, _config.Controller);

            RunOn(() =>
            {
                AwaitAssert(() =>
                {
                    Cluster.State.Members.Select(i => i.Status).Should().BeEquivalentTo(MemberStatus.Up, MemberStatus.Up, MemberStatus.Up, MemberStatus.Up);
                }, TimeSpan.FromSeconds(20));
            }, _config.Second, _config.Third, _config.Fourth);

            EnterBarrier("first node downed");

            var proxy = Sys.ActorOf(
                ClusterSingletonProxy.Props(
                    singletonManagerPath: "/user/important",
                    settings: ClusterSingletonProxySettings.Create(Sys).WithRole("worker")));

            RunOn(() =>
            {
                proxy.Tell("Ping");
                // lease has not been granted so now allowed to come up
                ExpectNoMsg(TimeSpan.FromSeconds(2));
            }, _config.Second, _config.Third, _config.Fourth);
            EnterBarrier("singleton-not-migrated");

            RunOn(() =>
            {
                TestLeaseActorClientExt.Get(Sys).GetLeaseActor().Tell(new TestLeaseActor.ActionRequest(new TestLeaseActor.Acquire(GetAddress(_config.Second).HostPort()), true));
            }, _config.Controller);

            EnterBarrier("singleton-moved-to-second");

            RunOn(() =>
            {
                proxy.Tell("Ping");
                ExpectMsg(new ClusterSingletonManagerLeaseSpecConfig.ImportantSingleton.Response("Ping", GetAddress(_config.Second)), TimeSpan.FromSeconds(20));
            }, _config.Second, _config.Third, _config.Fourth);
            EnterBarrier("finished");
        }