public void ClusterSharding_should_support_proxy_only_mode()
        {
            ClusterSharding_should_support_passivation_and_activation_of_entities();

            Within(TimeSpan.FromSeconds(10), () =>
            {
                RunOn(() =>
                {
                    var cfg = ConfigurationFactory.ParseString(@"
                        retry-interval = 1s
                        buffer-size = 1000")
                              .WithFallback(Sys.Settings.Config.GetConfig("akka.cluster.sharding"));

                    var settings = ClusterShardingSettings.Create(cfg, Sys.Settings.Config.GetConfig("akka.cluster.singleton"));
                    var proxy    = Sys.ActorOf(ShardRegion.ProxyProps(
                                                   typeName: "counter",
                                                   settings: settings,
                                                   coordinatorPath: "/user/counterCoordinator/singleton/coordinator",
                                                   extractEntityId: Counter.ExtractEntityId,
                                                   extractShardId: Counter.ExtractShardId));

                    proxy.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance));
                    proxy.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance));
                    proxy.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance));
                    proxy.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance));
                    proxy.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance));
                    proxy.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance));

                    proxy.Tell(new Counter.Get(1));
                    ExpectMsg(2);
                    proxy.Tell(new Counter.Get(2));
                    ExpectMsg(4);
                }, _second);
                EnterBarrier("after-5");
            });
        }
Beispiel #2
0
        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("AkkaTrader", conf.BootstrapFromDocker());

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

                var shardRegion = sharding.Start("orderBook", s => OrderBookActor.PropsFor(s), ClusterShardingSettings.Create(actorSystem),
                                                 new StockShardMsgRouter());
            });

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

            pbm.RegisterCommandPalette(ClusterCommands.Instance);
            pbm.RegisterCommandPalette(ClusterShardingCommands.Instance);
            pbm.RegisterCommandPalette(RemoteCommands.Instance);
            pbm.Start();

            actorSystem.WhenTerminated.Wait();
            return(0);
        }
        public void ClusterSharding_should_be_easy_to_use_with_extensions()
        {
            Within(TimeSpan.FromSeconds(50), () =>
            {
                RunOn(() =>
                {
                    //#counter-start
                    ClusterSharding.Get(Sys).Start(
                        typeName: "Counter",
                        entityProps: Props.Create <Counter>(),
                        settings: ClusterShardingSettings.Create(Sys),
                        extractEntityId: Counter.ExtractEntityId,
                        extractShardId: Counter.ExtractShardId);

                    //#counter-start
                    ClusterSharding.Get(Sys).Start(
                        typeName: "AnotherCounter",
                        entityProps: Props.Create <AnotherCounter>(),
                        settings: ClusterShardingSettings.Create(Sys),
                        extractEntityId: Counter.ExtractEntityId,
                        extractShardId: Counter.ExtractShardId);

                    //#counter-supervisor-start
                    ClusterSharding.Get(Sys).Start(
                        typeName: "SupervisedCounter",
                        entityProps: Props.Create <CounterSupervisor>(),
                        settings: ClusterShardingSettings.Create(Sys),
                        extractEntityId: Counter.ExtractEntityId,
                        extractShardId: Counter.ExtractShardId);
                }, _config.Third, _config.Fourth, _config.Fifth, _config.Sixth);
                EnterBarrier("extension-started");

                RunOn(() =>
                {
                    //#counter-usage
                    var counterRegion = ClusterSharding.Get(Sys).ShardRegion("Counter");
                    counterRegion.Tell(new Counter.Get(123));
                    ExpectMsg(0);

                    counterRegion.Tell(new Counter.EntityEnvelope(123, Counter.Increment.Instance));
                    counterRegion.Tell(new Counter.Get(123));
                    ExpectMsg(1);
                    //#counter-usage

                    var anotherCounterRegion = ClusterSharding.Get(Sys).ShardRegion("AnotherCounter");
                    anotherCounterRegion.Tell(new Counter.EntityEnvelope(123, Counter.Decrement.Instance));
                    anotherCounterRegion.Tell(new Counter.Get(123));
                    ExpectMsg(-1);
                }, _config.Fifth);
                EnterBarrier("extension-used");

                // sixth is a frontend node, i.e. proxy only
                RunOn(() =>
                {
                    for (int i = 1000; i <= 1010; i++)
                    {
                        ClusterSharding.Get(Sys).ShardRegion("Counter").Tell(new Counter.EntityEnvelope(i, Counter.Increment.Instance));
                        ClusterSharding.Get(Sys).ShardRegion("Counter").Tell(new Counter.Get(i));
                        ExpectMsg(1);
                        LastSender.Path.Address.Should().NotBe(Cluster.SelfAddress);
                    }
                }, _config.Sixth);
                EnterBarrier("after-10");
            });
        }
        static void Main(string[] args)
        {
            var hostname = Dns.GetHostName();

            Console.WriteLine($"Hostname: {hostname}");

            var hostIp = GetHostIPAddress(hostname);

            Console.WriteLine($"HostIP: {hostIp}");

            var hcon = @"akka {                                
                                actor {
                                    provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"" 
                                }

                                remote {
                                    log-remote-lifecycle-events = DEBUG
                                    dot-netty.tcp {
                                        port = 0
                                        hostname = {hostIP}
                                    }
                                }
                                
                                cluster {
                                    allow-weakly-up-members = off
                                    seed-nodes = [""{clusterAddresses}""]
                                    roles = [server,sharding]

                                    sharding {
                                        role = sharding
                                        remember-entities = false
                                    }
                                }
                            }";

            hcon = hcon.Replace("{hostIP}", hostIp);
            hcon = hcon.Replace("{clusterAddresses}", $"akka.tcp://testsystem@{hostIp}:4053");

            Console.WriteLine($"Seed Address:{hostIp}");

            _clusterSystem = ActorSystem.Create("testsystem", ConfigurationFactory.ParseString(hcon));

            var clusterSharding = ClusterSharding.Get(_clusterSystem);

            clusterSharding.Start(
                typeName: "testregion",
                entityProps: Props.Create <TestEntity>(),
                settings: ClusterShardingSettings.Create(_clusterSystem),
                messageExtractor: new MessageExtractor());

            AssemblyLoadContext.Default.Unloading += (obj) =>
            {
                LeaveCluster();
            };

            Console.CancelKeyPress += (s, ev) =>
            {
                LeaveCluster();
            };

            new AutoResetEvent(false).WaitOne();
        }
Beispiel #5
0
 public void ClusterShardingSettingsSpec_should_disable_passivation_if_RememberEntities_is_the_default_and_PassivateIdleEntityAfter_is_0_or_off()
 {
     ClusterShardingSettings.Create(Sys).WithPassivateIdleAfter(TimeSpan.Zero).ShouldPassivateIdleEntities.ShouldBe(false);
 }
Beispiel #6
0
 public void ClusterShardingSettingsSpec_should_disable_passivation_if_RememberEntities_is_enabled()
 {
     ClusterShardingSettings.Create(Sys)
     .WithRememberEntities(true)
     .ShouldPassivateIdleEntities.ShouldBe(false);
 }
Beispiel #7
0
 public void ClusterShardingSettingsSpec_must_passivate_idle_entities_if_RememberEntities_and_PassivateIdleEntityAfter_are_the_defaults()
 {
     ClusterShardingSettings.Create(Sys).ShouldPassivateIdleEntities.ShouldBe(true);
 }
Beispiel #8
0
        internal bool Start()
        {
            var logger = new LoggerConfiguration()
                         .WriteTo.ColoredConsole()
                         .MinimumLevel.Information()
                         .CreateLogger();

            Serilog.Log.Logger = logger;

            ActorSystem = ActorSystem.Create("BankSystem", @"akka
{
    loglevel=INFO,
    loggers=[""Akka.Logger.Serilog.SerilogLogger, Akka.Logger.Serilog""]

    remote {
        helios.tcp {
            port = 8081
            hostname = localhost
        }
    }

    cluster {
        seed-nodes = [""akka.tcp://BankSystem@localhost:8081""]
        auto-down-unreachable-after = 5s
        sharding {
            least-shard-allocation-strategy.rebalance-threshold = 3
        }
    }

    actor {
        provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
        serializers {
                wire = ""Akka.Serialization.WireSerializer, Akka.Serialization.Wire""
        }
        serialization-bindings {
                ""System.Object"" = wire
        }
        persistence {
            journal {
                plugin = ""akka.persistence.journal.inmem""
                inmem {
                    class=""Akka.Persistence.Journal.MemoryJournal, Akka.Persistence""
                    plugin-dispatcher = ""akka.actor.default-dispatcher""
                }
            }
            snapshot-store {
                plugin = ""akka.persistence.snapshot - store.local""
                local {
                    class = ""Akka.Persistence.Snapshot.LocalSnapshotStore, Akka.Persistence""
                    plugin-dispatcher = ""akka.persistence.dispatchers.default-plugin-dispatcher""
                    stream-dispatcher = ""akka.persistence.dispatchers.default-stream-dispatcher""
                    dir = ""snapshots""
                }
            }
        }
    }
}");

            var sharding = ClusterSharding.Get(ActorSystem);
            var settings = ClusterShardingSettings.Create(ActorSystem);

            sharding.Start(
                typeName: "AccountsBoundedContextActor",
                entityProps: Props.Create <AccountsBoundedContextActor>(),
                settings: settings,
                idExtractor: x => Tuple.Create(x.ToString(), x), //FAKE
                shardResolver: x => x.ToString());               //FAKE

            Domain = ActorSystem.ActorOf(DomainActor.Props(), "domains");

            Application = ActorSystem.ActorOf(SupervisorActor.Props(), "Application");
            ActorSystem.ActorOf(SupervisorActor.Props(), "Input");
            ActorSystem.ActorOf(SupervisorActor.Props(), "Output");
            ActorSystem.ActorOf(SupervisorActor.Props(), "Repositories");

            System.Console.WriteLine($"Domain @ {Domain.Path}");

            Thread.Sleep(2000);

            // Simulates user interactions
            {
                var command = new CreateAccountCommand("AC001", 100);
                Application.Tell(command);
            }


            System.Threading.Thread.Sleep(1000);

            {
                var command = new TransferBetweenAccountsCommand("AC001", "AC002", 50);
                Application.Tell(command);
            }

            System.Threading.Thread.Sleep(4000);

            {
                var command = new CreateAccountCommand("AC002", 100);
                Application.Tell(command);
            }


            return(true);
        }
        public void ShardedDaemonProcess_must_not_run_if_the_role_does_not_match_node_role()
        {
            Cluster.Get(Sys).Join(Cluster.Get(Sys).SelfAddress);

            var probe    = CreateTestProbe();
            var settings = ShardedDaemonProcessSettings.Create(Sys).WithShardingSettings(ClusterShardingSettings.Create(Sys).WithRole("workers"));

            ShardedDaemonProcess.Get(Sys).Init("roles", 3, id => MyActor.Props(id, probe.Ref), settings);

            probe.ExpectNoMsg();
        }
        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);
        }
Beispiel #11
0
        static int Main(string[] args)
        {
            var config = File.ReadAllText("app.conf");
            var conf   = ConfigurationFactory.ParseString(config).BoostrapApplication(new AppBootstrapConfig(true, true));

            var actorSystem = ActorSystem.Create("AkkaTrader", conf);

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

                var shardRegion = sharding.Start("orderBook", s => OrderBookActor.PropsFor(s), ClusterShardingSettings.Create(actorSystem),
                                                 new StockShardMsgRouter());
            });

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

            pbm.RegisterCommandPalette(ClusterCommands.Instance);
            pbm.RegisterCommandPalette(ClusterShardingCommands.Instance);
            pbm.RegisterCommandPalette(RemoteCommands.Instance);
            pbm.Start();

            actorSystem.WhenTerminated.Wait();
            return(0);
        }
 public static void Start(ActorSystem system, Props actor)
 => ClusterSharding.Get(system).Start(nameof(ExpressionApi), actor, ClusterShardingSettings.Create(system), new ExpressionMessageExtractor());
        /// <summary>
        /// Initializes a new instance of the <see cref="ShardingWrappperActor"/> class.
        /// </summary>
        /// <param name="container">
        /// The dependency resolver.
        /// </param>
        /// <param name="shardingConfig">
        /// The sharding config.
        /// </param>
        public ShardingWrappperActor(IComponentContext container, Config shardingConfig)
        {
            var shardingTypeName = shardingConfig.GetString("type-name");

            if (string.IsNullOrWhiteSpace(shardingTypeName))
            {
                Context.GetLogger()
                .Error(
                    "{Type}: type-name was not defined for actor {PathString}",
                    this.GetType().Name,
                    this.Self.Path.ToString());
                return;
            }

            var role = shardingConfig.GetString("role");

            if (string.IsNullOrWhiteSpace(role))
            {
                Context.GetLogger()
                .Error(
                    "{Type}: role was not defined for actor {PathString}",
                    this.GetType().Name,
                    this.Self.Path.ToString());
                return;
            }

            var childTypeName = shardingConfig.GetString("type");

            if (string.IsNullOrWhiteSpace(childTypeName))
            {
                Context.GetLogger()
                .Error(
                    "{Type}: Type was not defined for actor {PathString}",
                    this.GetType().Name,
                    this.Self.Path.ToString());
                return;
            }

            var type = Type.GetType(childTypeName);

            if (type == null)
            {
                Context.GetLogger()
                .Error(
                    "{Type}: {ClassTypeString} was not found for actor{PathString}",
                    this.GetType().Name,
                    childTypeName,
                    this.Self.Path.ToString());
                return;
            }

            var messageExtractorTypeName = shardingConfig.GetString("message-extractor");

            if (string.IsNullOrWhiteSpace(messageExtractorTypeName))
            {
                Context.GetLogger()
                .Error(
                    "{Type}: message-extractor was not defined for actor {PathString}",
                    this.GetType().Name,
                    this.Self.Path.ToString());
                return;
            }

            var messageExtractorType = Type.GetType(messageExtractorTypeName);

            if (messageExtractorType == null)
            {
                Context.GetLogger()
                .Error(
                    "{Type}: {ClassTypeString} was not found for actor {PathString}",
                    this.GetType().Name,
                    messageExtractorTypeName,
                    this.Self.Path.ToString());
                return;
            }

            if (messageExtractorType.GetInterfaces().All(t => t != typeof(IMessageExtractor)))
            {
                Context.GetLogger()
                .Error(
                    "{Type}: {ClassTypeString} defined in {PathString} does not implements IMessageExtractor",
                    this.GetType().Name,
                    messageExtractorTypeName,
                    this.Self.Path.ToString());
                return;
            }

            Context.GetLogger()
            .Info(
                "{Type}: initializing Sharding manager on {PathString}",
                typeof(NameSpaceActor).Name,
                this.Self.Path.ToString());

            var shardingRegion = ClusterSharding.Get(Context.System)
                                 .Start(
                shardingTypeName,
                Context.System.DI().Props(type),
                ClusterShardingSettings.Create(Context.System).WithRole(role),
                (IMessageExtractor)container.Resolve(messageExtractorType));

            this.Receive <object>(m => shardingRegion.Tell(m, this.Sender));
        }
Beispiel #14
0
 public MetricsActorSpec() :
     base(CLUSTERSHARDCONFIG)
 {
     cluster        = Cluster.Get(Sys);
     clusterMetrics = ClusterMetrics.Get(Sys);
     ClusterSharding.Get(Sys).Start(typeName: ShardRegions.OBJECTREGION, entityProps: Props.Create(() => new ObjectActor(null)), settings: ClusterShardingSettings.Create(Sys), messageExtractor: new ObjectRegionMessageExtractor(10));
     ClusterSharding.Get(Sys).Start(typeName: ShardRegions.AREAREGION, entityProps: Props.Create(() => new ObjectActor(null)), settings: ClusterShardingSettings.Create(Sys), messageExtractor: new AreaRegionMessageExtractor(10));
 }
Beispiel #15
0
 private void InitializeShardRegions(ActorSystem system)
 {
     this.shardRegionResolver = new DefaultShardRegionResolver(ClusterSharding.Get(system));
     this.shardRegionObject   = ClusterSharding.Get(system).Start(typeName: ShardRegions.OBJECTREGION, entityProps: Props.Create(() => new ObjectActor(this.shardRegionResolver)), settings: ClusterShardingSettings.Create(system), messageExtractor: new ObjectRegionMessageExtractor(this.state.ShardCountObject));
     this.shardRegionArea     = ClusterSharding.Get(system).Start(typeName: ShardRegions.AREAREGION, entityProps: Props.Create(() => new AreaActor(this.shardRegionResolver)), settings: ClusterShardingSettings.Create(system), messageExtractor: new AreaRegionMessageExtractor(this.state.ShardCountArea));
 }