public void Start()
        {
            Logger.Info("Starting shard");

            var system = ActorSystem.Create(Constants.ActorSystemName, ConfigurationFactory.Load()
                                            .WithFallback(config)
                                            .WithFallback(ClusterSingletonManager.DefaultConfig()));
            var sharding = ClusterSharding.Get(system);

            shardRegion = sharding.Start(
                typeName: nameof(MyActor),
                entityProps: Props.Create(() => new MyActor(nodeId)),
                settings: ClusterShardingSettings.Create(system),
                messageExtractor: new MessageExtractor(Constants.MaxNumberOfNodes * 10)
                );
            ClusterClientReceptionist.Get(system).RegisterService(shardRegion);
        }
        static void Main(string[] args)
        {
            var akkaConfigSection = ((AkkaConfigurationSection)ConfigurationManager.GetSection("akka")).AkkaConfig;
            var actorSystem       = ActorSystem.Create("AkkaSingleton", akkaConfigSection);

            var worker1 = actorSystem.ActorOf(WorkerActor.CreateProps("1"), "worker1");
            var worker2 = actorSystem.ActorOf(WorkerActor.CreateProps("2"), "worker2");
            var worker3 = actorSystem.ActorOf(WorkerActor.CreateProps("3"), "worker3");

            var singletonActorRef = actorSystem.ActorOf(ClusterSingletonManager.Props(
                                                            singletonProps: ManagerSingletonActor.CreateProps("1"),
                                                            terminationMessage: PoisonPill.Instance,
                                                            settings: ClusterSingletonManagerSettings.Create(actorSystem).WithSingletonName("singleton").WithRole("singletons")),
                                                        name: "ClusterSingletonManager");

            Console.ReadLine();
        }
        public ClusterSingletonManagerLeave2SpecConfig()
        {
            First  = Role("first");
            Second = Role("second");
            Third  = Role("third");
            Fourth = Role("fourth");
            Fifth  = Role("fifth");

            CommonConfig = ConfigurationFactory.ParseString(@"
                akka.loglevel = INFO
                akka.actor.provider = ""cluster""
                akka.remote.log-remote-lifecycle-events = off
                akka.cluster.auto-down-unreachable-after = off
            ")
                           .WithFallback(ClusterSingletonManager.DefaultConfig())
                           .WithFallback(ClusterSingletonProxy.DefaultConfig())
                           .WithFallback(MultiNodeClusterSpec.ClusterConfig());
        }
Esempio n. 4
0
        public ClusterSingletonManagerChaos2Config()
        {
            Controller = Role("controller");
            First      = Role("_config.First");
            Second     = Role("second");
            Third      = Role("third");
            Fourth     = Role("fourth");

            CommonConfig = ConfigurationFactory.ParseString(@"
                akka.loglevel = DEBUG
                akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
                akka.remote.log-remote-lifecycle-events = off
                akka.cluster.auto-down-unreachable-after = 0s
            ")
                           .WithFallback(ClusterSingletonManager.DefaultConfig())
                           .WithFallback(ClusterSingletonProxy.DefaultConfig())
                           .WithFallback(MultiNodeClusterSpec.ClusterConfig());
        }
Esempio n. 5
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();
        }
Esempio n. 6
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="system">TBD</param>
        public ClusterSharding(ExtendedActorSystem system)
        {
            _system = system;
            _system.Settings.InjectTopLevelFallback(DefaultConfig());
            _system.Settings.InjectTopLevelFallback(ClusterSingletonManager.DefaultConfig());
            _cluster = Cluster.Get(_system);
            Settings = ClusterShardingSettings.Create(system);

            _guardian = new Lazy <IActorRef>(() =>
            {
                var guardianName = system.Settings.Config.GetString("akka.cluster.sharding.guardian-name");
                var dispatcher   = system.Settings.Config.GetString("akka.cluster.sharding.use-dispatcher");
                if (string.IsNullOrEmpty(dispatcher))
                {
                    dispatcher = Dispatchers.DefaultDispatcherId;
                }
                return(system.SystemActorOf(Props.Create(() => new ClusterShardingGuardian()).WithDispatcher(dispatcher), guardianName));
            });
        }
        public void Join(ActorSystem from, ActorSystem to)
        {
            from.ActorOf(ClusterSingletonManager.Props(Echo.Props,
                                                       PoisonPill.Instance,
                                                       ClusterSingletonManagerSettings.Create(from)), "echo");

            Within(TimeSpan.FromSeconds(10), () =>
            {
                AwaitAssert(() =>
                {
                    Cluster.Get(from).Join(Cluster.Get(to).SelfAddress);
                    Cluster.Get(from).State.Members.Select(x => x.UniqueAddress).Should().Contain(Cluster.Get(from).SelfUniqueAddress);
                    Cluster.Get(from)
                    .State.Members.Select(x => x.Status)
                    .ToImmutableHashSet()
                    .Should()
                    .Equal(ImmutableHashSet <MemberStatus> .Empty.Add(MemberStatus.Up));
                });
            });
        }
Esempio n. 8
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}");
            }
 public static Config GetConfig()
 {
     return(ConfigurationFactory.ParseString(@"
         akka.loglevel = DEBUG
         #akka.loggers = [""akka.testkit.SilenceAllTestEventListener""]
         akka.loggers = [Akka.Event.DefaultLogger]
         akka.actor.provider = ""cluster""
         akka.remote.dot-netty.tcp.port = 0
         akka.cluster.sharding {
             use-lease = ""test-lease""
             lease-retry-interval = 200ms
             distributed-data.durable {
                 keys = []
             }
         }
         ")
            .WithFallback(ClusterSharding.DefaultConfig())
            .WithFallback(ClusterSingletonManager.DefaultConfig())
            .WithFallback(TestLease.Configuration));
 }
        public void ClusterSingleton_with_lease_should_do_not_start_if_lease_acquire_returns_false()
        {
            var probe    = CreateTestProbe();
            var settings = NextSettings();

            Sys.ActorOf(
                ClusterSingletonManager.Props(Props.Create(() => new ImportantSingleton(probe.Ref)), PoisonPill.Instance, settings),
                settings.SingletonName);

            TestLease testLease = null;

            AwaitAssert(() =>
            {
                testLease = testLeaseExt.GetTestLease(LeaseNameFor(settings));
            }); // allow singleton manager to create the lease

            probe.ExpectNoMsg(shortDuration);
            testLease.InitialPromise.SetResult(false);
            probe.ExpectNoMsg(shortDuration);
        }
Esempio n. 11
0
        public static async Task Main(string[] args)
        {
            #region Console shutdown setup

            var exitEvent = new ManualResetEvent(false);
            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                eventArgs.Cancel = true;
                exitEvent.Set();
            };
            AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) =>
            {
                exitEvent.Set();
            };

            #endregion

            var config = ConfigurationFactory.ParseString(await File.ReadAllTextAsync("app.conf"))
                         .BootstrapFromDocker()
                         .WithFallback(ClusterSingletonManager.DefaultConfig())
                         .WithFallback(SqlitePersistence.DefaultConfiguration());

            var system = ActorSystem.Create("sharded-cluster-system", config);

            var sharding    = ClusterSharding.Get(system);
            var shardRegion = await sharding.StartAsync(
                typeName : "customer",
                entityPropsFactory : e => Props.Create(() => new Customer(e)),
                settings : ClusterShardingSettings.Create(system),
                messageExtractor : new MessageExtractor(10));

            var cluster = Cluster.Get(system);
            cluster.RegisterOnMemberUp(() =>
            {
                ProduceMessages(system, shardRegion);
            });

            exitEvent.WaitOne();
            await system.Terminate();
        }
        public ShardedDaemonProcessSpecConfig()
        {
            First  = Role("first");
            Second = Role("second");
            Third  = Role("third");

            CommonConfig = DebugConfig(false)
                           .WithFallback(ConfigurationFactory.ParseString(@"
                    akka.loglevel = INFO
                    akka.cluster.sharded-daemon-process {{
                      sharding {{
                        # First is likely to be ignored as shard coordinator not ready
                        retry-interval = 0.2s
                      }}
                      # quick ping to make test swift
                      keep-alive-interval = 1s
                    }}
                "))
                           .WithFallback(ClusterSharding.DefaultConfig())
                           .WithFallback(ClusterSingletonManager.DefaultConfig())
                           .WithFallback(MultiNodeClusterSpec.ClusterConfig());
        }
Esempio n. 13
0
        public static IActorRef StartSingletonSubscriber(
            ActorSystem actorSystem,
            Expression <Func <TDomainEventSubscriber> > domainEventSubscriberFactory,
            string roleName)
        {
            var name = typeof(TDomainEventSubscriber).Name;

            var domainEventSubscriberProps = Props.Create(domainEventSubscriberFactory);

            actorSystem.ActorOf(ClusterSingletonManager.Props(
                                    singletonProps: Props.Create(() => new ClusterParentProxy(domainEventSubscriberProps, true)),
                                    terminationMessage: PoisonPill.Instance,
                                    settings: ClusterSingletonManagerSettings.Create(actorSystem).WithRole(roleName).WithSingletonName(name)),
                                name: name);

            var proxy = StartSingletonSubscriberProxy(actorSystem, roleName);

            actorSystem.ActorOf(Props.Create(() =>
                                             new SingletonDomainEventSubscriberDispatcher <TDomainEventSubscriber>(proxy)), $"{typeof(TDomainEventSubscriber).Name}Dispatcher");

            return(proxy);
        }
        public ClusterSingletonManagerSpecConfig()
        {
            Controller = Role("controller");
            Observer   = Role("observer");
            First      = Role("first");
            Second     = Role("second");
            Third      = Role("third");
            Fourth     = Role("fourth");
            Fifth      = Role("fifth");
            Sixth      = Role("sixth");

            CommonConfig = ConfigurationFactory.ParseString(@"
                akka.loglevel = DEBUG
                akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
                akka.remote.log-remote-lifecycle-events = off
                akka.cluster.auto-down-unreachable-after = 0s
            ")
                           .WithFallback(ClusterSingletonManager.DefaultConfig())
                           .WithFallback(MultiNodeClusterSpec.ClusterConfig());

            NodeConfig(new[] { First, Second, Third, Fourth, Fifth, Sixth }, new[] { ConfigurationFactory.ParseString(@"akka.cluster.roles =[worker]") });
        }
        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");
        }
        public void ClusterSingleton_with_lease_should_release_lease_when_leaving_oldest()
        {
            var singletonProbe = CreateTestProbe();
            var settings       = NextSettings();

            Sys.ActorOf(
                ClusterSingletonManager.Props(Props.Create(() => new ImportantSingleton(singletonProbe.Ref)), PoisonPill.Instance, settings),
                settings.SingletonName);

            TestLease testLease = null;

            AwaitAssert(() =>
            {
                testLease = testLeaseExt.GetTestLease(LeaseNameFor(settings));
            }); // allow singleton manager to create the lease

            singletonProbe.ExpectNoMsg(shortDuration);
            testLease.Probe.ExpectMsg(new TestLease.AcquireReq(leaseOwner));
            testLease.InitialPromise.SetResult(true);
            singletonProbe.ExpectMsg("preStart");
            cluster.Leave(cluster.SelfAddress);
            testLease.Probe.ExpectMsg(new TestLease.ReleaseReq(leaseOwner));
        }
Esempio n. 17
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);
            }
        }
        static int Main(string[] args)
        {
            var mongoConnectionString = Environment.GetEnvironmentVariable("MONGO_CONNECTION_STR")?.Trim();

            if (string.IsNullOrEmpty(mongoConnectionString))
            {
                Console.WriteLine("ERROR! MongoDb connection string not provided. Can't start.");
                return(-1);
            }
            else
            {
                Console.WriteLine("Connecting to MongoDb at {0}", mongoConnectionString);
            }

            var config = File.ReadAllText("app.conf");
            var conf   = ConfigurationFactory.ParseString(config).WithFallback(GetMongoHocon(mongoConnectionString))
                         .WithFallback(OpsConfig.GetOpsConfig())
                         .WithFallback(ClusterSharding.DefaultConfig())
                         .WithFallback(DistributedPubSub.DefaultConfig());

            var actorSystem     = ActorSystem.Create("AkkaPricing", conf.BootstrapFromDocker());
            var readJournal     = actorSystem.ReadJournalFor <MongoDbReadJournal>(MongoDbReadJournal.Identifier);
            var priceViewMaster = actorSystem.ActorOf(Props.Create(() => new PriceViewMaster()), "prices");

            Cluster.Cluster.Get(actorSystem).RegisterOnMemberUp(() =>
            {
                var sharding = ClusterSharding.Get(actorSystem);

                var shardRegion = sharding.Start("priceAggregator",
                                                 s => Props.Create(() => new MatchAggregator(s, readJournal)),
                                                 ClusterShardingSettings.Create(actorSystem),
                                                 new StockShardMsgRouter());

                // used to seed pricing data
                var singleton = ClusterSingletonManager.Props(
                    Props.Create(() => new PriceInitiatorActor(readJournal, shardRegion)),
                    ClusterSingletonManagerSettings.Create(
                        actorSystem.Settings.Config.GetConfig("akka.cluster.price-singleton")));

                // start the creation of the pricing views
                priceViewMaster.Tell(new PriceViewMaster.BeginTrackPrices(shardRegion));
            });

            // start Petabridge.Cmd (for external monitoring / supervision)
            var pbm = PetabridgeCmd.Get(actorSystem);

            void RegisterPalette(CommandPaletteHandler h)
            {
                if (pbm.RegisterCommandPalette(h))
                {
                    Console.WriteLine("Petabridge.Cmd - Registered {0}", h.Palette.ModuleName);
                }
                else
                {
                    Console.WriteLine("Petabridge.Cmd - DID NOT REGISTER {0}", h.Palette.ModuleName);
                }
            }

            RegisterPalette(ClusterCommands.Instance);
            RegisterPalette(RemoteCommands.Instance);
            RegisterPalette(ClusterShardingCommands.Instance);
            RegisterPalette(new PriceCommands(priceViewMaster));
            pbm.Start();

            actorSystem.WhenTerminated.Wait();
            return(0);
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            Config config = @"
            akka {
              actor {
                provider = cluster
                serializers {
                  hyperion = ""Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion""
                }
                serialization-bindings {
                  ""System.Object"" = hyperion
                }
              }
              remote {
                dot-netty.tcp {
                  public-hostname = ""localhost""
                  hostname = ""localhost""
                  port = 0
                }
              }
              cluster {
                auto-down-unreachable-after = 5s
                sharding {
                  least-shard-allocation-strategy.rebalance-threshold = 3
                }
              }
              persistence {
                journal {
                  plugin = ""akka.persistence.journal.sqlite""
                  sqlite {
                    connection-string = ""Datasource=store.db""
                    auto-initialize = true
                  }
                }
                snapshot-store {
                  plugin = ""akka.persistence.snapshot-store.sqlite""
                  sqlite {
                    connection-string = ""Datasource=store.db""
                    auto-initialize = true
                  }
                }
              }
            }";

            using (var system = ActorSystem.Create("sharded-cluster-system", config.WithFallback(ClusterSingletonManager.DefaultConfig())))
            {
                var automaticCluster = new AutomaticCluster(system);
                try
                {
                    automaticCluster.Join();

                    RunExample(system);

                    Console.ReadLine();
                }
                finally
                {
                    //WARNING: you may need to remove SQLite database file from bin/Debug or bin/Release in case when unexpected crash happened
                    automaticCluster.Leave();
                }
            }
        }
Esempio n. 20
0
 /// <summary>
 /// Creates a cluster singleton actor given its <see cref="Props"/>. Singleton actor will
 /// exists only on one node in a cluster at a time. If this node goes down, it will be
 /// recreated on another one (usually it lives on the oldest node in the cluster).
 /// </summary>
 /// <param name="system"></param>
 /// <param name="props"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 public static IActorRef SingletonOf(this ActorSystem system, Props props, string name)
 {
     return(system.ActorOf(ClusterSingletonManager.Props(
                               singletonProps: props,
                               settings: ClusterSingletonManagerSettings.Create(system).WithRole(name)), name));
 }
 static ClusterShardingMessageSerializerSpec()
 {
     SpecConfig = ClusterSingletonManager.DefaultConfig().WithFallback(ClusterSharding.DefaultConfig());
 }
Esempio n. 22
0
        static void Main(string[] args)
        {
            using (var system = ActorSystem.Create("sharded-cluster-system", Cch2.Cfg.WithFallback(ClusterSingletonManager.DefaultConfig())))
            {
                var automaticCluster = new AutomaticCluster(system);
                try
                {
                    automaticCluster.Join();
                    CounterHelper.CounterActor = system.ActorOf(Props.Create(() => new CounterActor()));


                    RunExample(system);

                    Console.WriteLine("## Is started");
                    Console.ReadLine();
                }
                finally
                {
                    //WARNING: you may need to remove SQLite database file from bin/Debug or bin/Release in case when unexpected crash happened
                    automaticCluster.Leave();
                }
            }
        }
 public ClusterSingletonMessageSerializerSpec()
     : base(ConfigurationFactory.ParseString(@"akka.actor.provider = cluster
                                               akka.remote.dot-netty.tcp.port = 0").WithFallback(ClusterSingletonManager.DefaultConfig()))
 {
 }
Esempio n. 24
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);
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            using (var system = ActorSystem.Create("sharded-cluster-system", ConfigurationFactory.Load().WithFallback(ClusterSingletonManager.DefaultConfig())))
            {
                var automaticCluster = new AutomaticCluster(system);
                try
                {
                    automaticCluster.Join();

                    RunExample(system);

                    Console.ReadLine();
                }
                finally
                {
                    //WARNING: you may need to remove SQLite database file from bin/Debug or bin/Release in case when unexpected crash happened
                    automaticCluster.Leave();
                }
            }
        }
Esempio n. 26
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..");
        }
Esempio n. 27
0
        public ClusterShardingSpecConfig(/*string entityRecoveryStrategy*/)
        {
            Controller = Role("controller");
            First      = Role("first");
            Second     = Role("second");
            Third      = Role("third");
            Fourth     = Role("fourth");
            Fifth      = Role("fifth");
            Sixth      = Role("sixth");

            CommonConfig = DebugConfig(false)
                           .WithFallback(ConfigurationFactory.ParseString(@"
                    akka.actor {
                        serializers {
                            hyperion = ""Akka.Serialization.HyperionSerializer, Akka.Serialization.Hyperion""
                        }
                        serialization-bindings {
                            ""System.Object"" = hyperion
                        }
                    }

                    akka.cluster.auto-down-unreachable-after = 0s
                    akka.cluster.roles = [""backend""]
                    akka.cluster.sharding {
                        retry-interval = 1 s
                        handoff-timeout = 10 s
                        shard-start-timeout = 5s
                        entity-restart-backoff = 1s
                        rebalance-interval = 2 s
                        entity-recovery-strategy = ""all""
                        entity-recovery-constant-rate-strategy {
                            frequency = 1 ms
                            number-of-entities = 1
                        }
                        least-shard-allocation-strategy {
                            rebalance-threshold = 2
                            max-simultaneous-rebalance = 1
                        }
                    }

                    akka.testconductor.barrier-timeout = 70s


                    akka.persistence.snapshot-store.plugin = ""akka.persistence.snapshot-store.inmem""
                    akka.persistence.journal.plugin = ""akka.persistence.journal.memory-journal-shared""

                    akka.persistence.journal.MemoryJournal {
                        class = ""Akka.Persistence.Journal.MemoryJournal, Akka.Persistence""
                        plugin-dispatcher = ""akka.actor.default-dispatcher""
                    }

                    akka.persistence.journal.memory-journal-shared {
                        class = ""Akka.Cluster.Sharding.Tests.MemoryJournalShared, Akka.Cluster.Sharding.Tests.MultiNode""
                        plugin-dispatcher = ""akka.actor.default-dispatcher""
                        timeout = 5s
                    }
                "))
                           .WithFallback(Sharding.ClusterSharding.DefaultConfig())
                           .WithFallback(ClusterSingletonManager.DefaultConfig())
                           .WithFallback(MultiNodeClusterSpec.ClusterConfig());

            NodeConfig(new[] { Sixth }, new[] { ConfigurationFactory.ParseString(@"akka.cluster.roles = [""frontend""]") });
        }
Esempio n. 28
0
        internal static Config GetConfig(int port, string role)
        {
            var systemConfigString = SystemConfigString.Replace("PORT", port.ToString()).Replace("ROLE", role);

            return(ConfigurationFactory.ParseString(systemConfigString).WithFallback(ClusterSingletonManager.DefaultConfig()));
        }
        /// <summary>
        /// TBD
        /// </summary>
        public ClusterShardingGuardian()
        {
            Receive <Start>(start =>
            {
                try
                {
                    var settings = start.Settings;
                    var encName  = Uri.EscapeDataString(start.TypeName);
                    var coordinatorSingletonManagerName = CoordinatorSingletonManagerName(encName);
                    var coordinatorPath = CoordinatorPath(encName);
                    var shardRegion     = Context.Child(encName);
                    var replicator      = Replicator(settings);

                    if (Equals(shardRegion, ActorRefs.Nobody))
                    {
                        if (Equals(Context.Child(coordinatorSingletonManagerName), ActorRefs.Nobody))
                        {
                            var minBackoff       = settings.TunningParameters.CoordinatorFailureBackoff;
                            var maxBackoff       = new TimeSpan(minBackoff.Ticks * 5);
                            var coordinatorProps = settings.StateStoreMode == StateStoreMode.Persistence
                                ? PersistentShardCoordinator.Props(start.TypeName, settings, start.AllocationStrategy)
                                : DDataShardCoordinator.Props(start.TypeName, settings, start.AllocationStrategy, replicator, _majorityMinCap, settings.RememberEntities);

                            var singletonProps    = BackoffSupervisor.Props(coordinatorProps, "coordinator", minBackoff, maxBackoff, 0.2).WithDeploy(Deploy.Local);
                            var singletonSettings = settings.CoordinatorSingletonSettings.WithSingletonName("singleton").WithRole(settings.Role);
                            Context.ActorOf(ClusterSingletonManager.Props(singletonProps, PoisonPill.Instance, singletonSettings).WithDispatcher(Context.Props.Dispatcher), coordinatorSingletonManagerName);
                        }
                        shardRegion = Context.ActorOf(ShardRegion.Props(
                                                          typeName: start.TypeName,
                                                          entityProps: start.EntityProps,
                                                          settings: settings,
                                                          coordinatorPath: coordinatorPath,
                                                          extractEntityId: start.ExtractEntityId,
                                                          extractShardId: start.ExtractShardId,
                                                          handOffStopMessage: start.HandOffStopMessage,
                                                          replicator: replicator,
                                                          majorityMinCap: _majorityMinCap).WithDispatcher(Context.Props.Dispatcher), encName);
                    }

                    Sender.Tell(new Started(shardRegion));
                }
                catch (Exception ex)
                {
                    //TODO: JVM version matches NonFatal. Can / should we do something similar?
                    // don't restart
                    // could be invalid ReplicatorSettings, or InvalidActorNameException
                    // if it has already been started
                    Sender.Tell(new Status.Failure(ex));
                }
            });

            Receive <StartProxy>(startProxy =>
            {
                try
                {
                    var settings = startProxy.Settings;
                    var encName  = Uri.EscapeDataString(startProxy.TypeName);
                    var coordinatorSingletonManagerName = CoordinatorSingletonManagerName(encName);
                    var coordinatorPath = CoordinatorPath(encName);
                    var shardRegion     = Context.Child(encName);
                    var replicator      = Replicator(settings);

                    if (Equals(shardRegion, ActorRefs.Nobody))
                    {
                        shardRegion = Context.ActorOf(ShardRegion.ProxyProps(
                                                          typeName: startProxy.TypeName,
                                                          settings: settings,
                                                          coordinatorPath: coordinatorPath,
                                                          extractEntityId: startProxy.ExtractEntityId,
                                                          extractShardId: startProxy.ExtractShardId,
                                                          replicator: replicator,
                                                          majorityMinCap: _majorityMinCap).WithDispatcher(Context.Props.Dispatcher), encName);
                    }

                    Sender.Tell(new Started(shardRegion));
                }
                catch (Exception ex)
                {
                    //TODO: JVM version matches NonFatal. Can / should we do something similar?
                    // don't restart
                    // could be InvalidActorNameException if it has already been started
                    Sender.Tell(new Status.Failure(ex));
                }
            });
        }
Esempio n. 30
0
        /// <summary>
        /// Creates cluster singleton actor from config
        /// </summary>
        /// <param name="context">Current actor context (will create child actor)</param>
        /// <param name="actorConfig">Configuration to create from</param>
        /// <param name="currentPath">Parent (current) actor path</param>
        /// <param name="pathName">New actor's path name</param>
        protected virtual void CreateSingletonActor(
            IActorContext context,
            Config actorConfig,
            string currentPath,
            string pathName)
        {
            var childTypeName = actorConfig.GetString("type");

            if (string.IsNullOrWhiteSpace(childTypeName))
            {
                return;
            }

            var type = Type.GetType(childTypeName);

            if (type == null)
            {
                context.GetLogger()
                .Error(
                    "{Type}: {ClassTypeString} was not found for actor {NameSpaceName}/{PathString}",
                    typeof(NameSpaceActor).Name,
                    childTypeName,
                    currentPath,
                    pathName);
                return;
            }

            var singletonName = actorConfig.GetString("singleton-name");

            if (string.IsNullOrEmpty(singletonName))
            {
                context.GetLogger()
                .Error(
                    "{Type}: singleton-name was not defined for{NameSpaceName}/ {PathString}",
                    typeof(NameSpaceActor).Name,
                    currentPath,
                    pathName);
                return;
            }

            var role = actorConfig.GetString("singleton-node-role");

            if (string.IsNullOrEmpty(role))
            {
                context.GetLogger()
                .Error(
                    "{Type}: singleton-node-role was not defined for {NameSpaceName}/{PathString}",
                    typeof(NameSpaceActor).Name,
                    currentPath,
                    pathName);
                return;
            }

            context.GetLogger()
            .Info(
                "{Type}: {NameSpaceName} initializing singleton {SingletonName} of type {ActorType} on {PathString}",
                typeof(NameSpaceActor).Name,
                currentPath,
                singletonName,
                type.Name,
                pathName);

            context.ActorOf(
                ClusterSingletonManager.Props(
                    context.System.DI().Props(type),
                    new ClusterSingletonManagerSettings(
                        singletonName,
                        role,
                        actorConfig.GetTimeSpan("removal-margin", TimeSpan.FromSeconds(1), false),
                        actorConfig.GetTimeSpan("handover-retry-interval", TimeSpan.FromSeconds(5), false))),
                pathName);
        }