private TestKitBase(TestKitAssertions assertions, ActorSystem system, Config config, string actorSystemName, string testActorName) { if(assertions == null) throw new ArgumentNullException("assertions"); if(system == null) { var configWithDefaultFallback = config.SafeWithFallback(_defaultConfig); system = ActorSystem.Create(actorSystemName ?? "test", configWithDefaultFallback); } _assertions = assertions; _system = system; system.RegisterExtension(new TestKitExtension()); system.RegisterExtension(new TestKitAssertionsExtension(assertions)); _testKitSettings = TestKitExtension.For(_system); _queue = new BlockingQueue<MessageEnvelope>(); _log = Logging.GetLogger(system, GetType()); _eventFilterFactory = new EventFilterFactory(this); if (string.IsNullOrEmpty(testActorName)) testActorName = "testActor" + _testActorId.IncrementAndGet(); var testActor = CreateTestActor(system, testActorName); //Wait for the testactor to start AwaitCondition(() => { var repRef = testActor as RepointableRef; return repRef == null || repRef.IsStarted; }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10)); if(!(this is NoImplicitSender)) { InternalCurrentActorCellKeeper.Current = (ActorCell)((ActorRefWithCell)testActor).Underlying; } _testActor = testActor; }
/// <summary> /// Performs configuration /// </summary> /// <param name="configuration">Previous configuration</param> /// <param name="config">Akka configuration</param> /// <returns>Updated configuration</returns> public LoggerConfiguration Configure(LoggerConfiguration configuration, Config config) { var minimumLevel = config.GetString("ClusterKit.Log.ElasticSearch.minimumLevel", "none")?.Trim(); LogEventLevel level; if (!Enum.TryParse(minimumLevel, true, out level)) { return configuration; } var nodes = config.GetStringList("ClusterKit.Log.ElasticSearch.nodes"); var indexFormat = config.GetString("ClusterKit.Log.ElasticSearch.indexFormat", "logstash-{0:yyyy.MM.dd}"); Log.Information( "{Type}: \n\tMinimum level: {MinimumLevel}\n\tIndex format: {IndexFormat}\n\tNodes:\n\t\t{NodeList}\n", this.GetType().FullName, minimumLevel, indexFormat, string.Join("\n\t\t", nodes)); SelfLog.Enable(Console.WriteLine); var options = new ElasticsearchSinkOptions(nodes.Select(s => new Uri(s))) { MinimumLogEventLevel = level, AutoRegisterTemplate = true, IndexFormat = indexFormat }; return configuration.WriteTo.Elasticsearch(options); }
public RemoteSettings(Config config) { Config = config; LogReceive = config.GetBoolean("akka.remote.log-received-messages"); LogSend = config.GetBoolean("akka.remote.log-sent-messages"); UntrustedMode = config.GetBoolean("akka.remote.untrusted-mode"); TrustedSelectionPaths = new HashSet<string>(config.GetStringList("akka.remote.trusted-selection-paths")); RemoteLifecycleEventsLogLevel = config.GetString("akka.remote.log-remote-lifecycle-events") ?? "DEBUG"; if (RemoteLifecycleEventsLogLevel.Equals("on")) RemoteLifecycleEventsLogLevel = "DEBUG"; FlushWait = config.GetMillisDuration("akka.remote.flush-wait-on-shutdown"); ShutdownTimeout = config.GetMillisDuration("akka.remote.shutdown-timeout"); TransportNames = config.GetStringList("akka.remote.enabled-transports"); Transports = (from transportName in TransportNames let transportConfig = TransportConfigFor(transportName) select new TransportSettings(transportConfig)).ToArray(); Adapters = ConfigToMap(config.GetConfig("akka.remote.adapters")); BackoffPeriod = config.GetMillisDuration("akka.remote.backoff-interval"); RetryGateClosedFor = config.GetMillisDuration("akka.remote.retry-gate-closed-for", TimeSpan.Zero); UsePassiveConnections = config.GetBoolean("akka.remote.use-passive-connections"); SysMsgBufferSize = config.GetInt("akka.remote.system-message-buffer-size"); SysResendTimeout = config.GetMillisDuration("akka.remote.resend-interval"); InitialSysMsgDeliveryTimeout = config.GetMillisDuration("akka.remote.initial-system-message-delivery-timeout"); SysMsgAckTimeout = config.GetMillisDuration("akka.remote.system-message-ack-piggyback-timeout"); QuarantineDuration = config.GetMillisDuration("akka.remote.prune-quarantine-marker-after"); StartupTimeout = config.GetMillisDuration("akka.remote.startup-timeout"); CommandAckTimeout = config.GetMillisDuration("akka.remote.command-ack-timeout"); }
public static void Main(string[] args) { Config fallbackConfig = ConfigurationFactory.ParseString(@" akka.suppress-json-serializer-warning=true akka.loglevel = DEBUG ").WithFallback(ConfigurationFactory.FromResource <ConsumerSettings <object, object> >("Akka.Streams.Kafka.reference.conf")); var system = ActorSystem.Create("TestKafka", fallbackConfig); var materializer = system.Materializer(); var consumerSettings = ConsumerSettings <Null, string> .Create(system, null, null) .WithBootstrapServers("localhost:29092") .WithGroupId("group1"); var subscription = Subscriptions.Topics("akka100"); KafkaConsumer.PlainSource(consumerSettings, subscription) .RunForeach(result => { Console.WriteLine($"Consumer: {result.Topic}/{result.Partition} {result.Offset}: {result.Value}"); }, materializer); Console.ReadLine(); }
protected JournalSpec(Config config = null, string actorSystemName = null, string testActorName = null) : base(config ?? Config, actorSystemName ?? "JournalSpec", testActorName) { _senderProbe = CreateTestProbe(); _receiverProbe = CreateTestProbe(); WriteMessages(1, 5, Pid, _senderProbe.Ref); }
private static ActorSystem CreateAndStartSystem(string name, Config withFallback, ActorSystemSetup setup) { var system = new ActorSystemImpl(name, withFallback, setup, Option <Props> .None); system.Start(); return(system); }
/// <summary> /// Performs configuration /// </summary> /// <param name="configuration">Previous configuration</param> /// <param name="config">Akka configuration</param> /// <returns>Updated configuration</returns> public LoggerConfiguration Configure(LoggerConfiguration configuration, Config config) { var templateName = config.GetString("ClusterKit.NodeManager.NodeTemplate"); return string.IsNullOrWhiteSpace(templateName) ? configuration : configuration.Enrich.WithProperty("nodeTemplate", templateName); }
static SqlServerJournalSpec() { var connectionString = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString.Replace(@"\", "\\"); var specString = @" akka.persistence { publish-plugin-commands = on journal { plugin = ""akka.persistence.journal.sql-server"" sql-server { class = ""Akka.Persistence.SqlServer.Journal.SqlServerJournal, Akka.Persistence.SqlServer"" plugin-dispatcher = ""akka.actor.default-dispatcher"" table-name = EventJournal schema-name = dbo auto-initialize = on connection-string = ""Data Source=localhost\\SQLEXPRESS;Database=akka_persistence_tests;User Id=akkadotnet;Password=akkadotnet;"" } } }"; SpecConfig = ConfigurationFactory.ParseString(specString); //need to make sure db is created before the tests start DbUtils.Initialize(); }
public JournalSettings(Config config) { if (config == null) throw new ArgumentNullException("config", "Table Storage journal settings cannot be initialized, because required HOCON section couldn't be found"); TableName = config.GetString("table-name"); ConnectionStrings = config.GetStringList("connection-strings"); _settings = new AzureStorageSettings(ConnectionStrings); }
private IAutoSubscription GetSubscription(Akka.Configuration.Config config) { var topicpattern = config.GetString("kafka.topic-pattern"); var topics = config.GetStringList("kafka.topics").ToArray(); return(topicpattern != null?Subscriptions.TopicPattern(topicpattern) : Subscriptions.Topics(topics)); }
private static ActorSystem CreateAndStartSystem(string name, Config withFallback) { var system = new ActorSystemImpl(name, withFallback); system.Start(); return(system); }
public SessionSettings(Config config) { if (config == null) throw new ArgumentNullException("config"); Builder = Cluster.Builder(); // Get IP and port configuration int port = config.GetInt("port", 9042); IPEndPoint[] contactPoints = ParseContactPoints(config.GetStringList("contact-points"), port); Builder.AddContactPoints(contactPoints); // Support user/pass authentication if (config.HasPath("credentials")) Builder.WithCredentials(config.GetString("credentials.username"), config.GetString("credentials.password")); // Support SSL if (config.GetBoolean("ssl")) Builder.WithSSL(); // Support compression string compressionTypeConfig = config.GetString("compression"); if (compressionTypeConfig != null) { var compressionType = (CompressionType) Enum.Parse(typeof (CompressionType), compressionTypeConfig, true); Builder.WithCompression(compressionType); } }
static OracleSnapshotStoreSpec() { var specString = @" akka.persistence { publish-plugin-commands = on snapshot-store { plugin = ""akka.persistence.snapshot-store.oracle-managed"" oracle-managed { class = ""Akka.Persistence.OracleManaged.Snapshot.OracleSnapshotStore, Akka.Persistence.OracleManaged"" plugin-dispatcher = ""akka.actor.default-dispatcher"" table-name = Spec-SnapshotStore schema-name = akka_persist_tests auto-initialize = on connection-string-name = ""TestDb"" } } }"; SpecConfig = ConfigurationFactory.ParseString(specString); //need to make sure db is created before the tests start //DbUtils.Initialize(); DbUtils.Clean("Spec-SnapshotStore"); }
private static void Main(string[] args) { var section = (AkkaConfigurationSection)ConfigurationManager.GetSection("akka"); _clusterConfig = section.AkkaConfig; LaunchBackend(new[] { "2551" }); LaunchBackend(new[] { "2552" }); LaunchBackend(new string[0]); string input; Console.WriteLine("Enter send to send the message bar or quit to exit."); while ((input = Console.ReadLine()) != null) { var cmd = input; switch (cmd) { case "quit": return; // Stop the run thread case "send": // Send to backend which will write to the console SendToBackend(); break; } } Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
public override Deploy ParseConfig(string key, Config config) { var deploy = base.ParseConfig(key, config); if (deploy == null) return null; if (deploy.Config.GetBoolean("cluster.enabled")) { if(deploy.Scope != Deploy.NoScopeGiven) throw new ConfigurationException(string.Format("Cluster deployment can't be combined with scope [{0}]", deploy.Scope)); //TODO: add handling for RemoteRouterConfig if (deploy.RouterConfig is Pool) { return deploy.Copy(scope: ClusterScope.Instance) .WithRouterConfig(new ClusterRouterPool(deploy.RouterConfig as Pool, ClusterRouterPoolSettings.FromConfig(deploy.Config))); } else if (deploy.RouterConfig is Group) { return deploy.Copy(scope: ClusterScope.Instance) .WithRouterConfig(new ClusterRouterGroup(deploy.RouterConfig as Group, ClusterRouterGroupSettings.FromConfig(deploy.Config))); } else { throw new ArgumentException(string.Format("Cluster-aware router can only wrap Pool or Group, got [{0}]", deploy.RouterConfig.GetType())); } } else { return deploy; } }
public Deployer(Settings settings) { _settings = settings; _deployment = settings.Config.GetConfig("akka.actor.deployment"); _default = _deployment.GetConfig("default"); Init(); }
private TestKitBase(TestKitAssertions assertions, ActorSystem system, Config config, string actorSystemName = null) { if(assertions == null) throw new ArgumentNullException("assertions"); if(system == null) { var configWithDefaultFallback = config.SafeWithFallback(_defaultConfig); system = ActorSystem.Create(actorSystemName ?? "test", configWithDefaultFallback); } _assertions = assertions; _system = system; system.RegisterExtension(new TestKitExtension()); system.RegisterExtension(new TestKitAssertionsExtension(assertions)); _testKitSettings = TestKitExtension.For(_system); _queue = new BlockingQueue<MessageEnvelope>(); _log = Logging.GetLogger(system, GetType()); var testActor = CreateTestActor(system, "testActor" + _testActorId.IncrementAndGet()); _testActor = testActor; //Wait for the testactor to start AwaitCondition(() => { var repRef = _testActor as RepointableRef; return repRef == null || repRef.IsStarted; }, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(10)); }
static PostgreSqlSnapshotStoreSpec() { var connectionString = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; var config = @" akka.persistence { publish-plugin-commands = on snapshot-store { plugin = ""akka.persistence.snapshot-store.postgresql"" postgresql { class = ""Akka.Persistence.PostgreSql.Snapshot.PostgreSqlSnapshotStore, Akka.Persistence.PostgreSql"" plugin-dispatcher = ""akka.actor.default-dispatcher"" table-name = snapshot_store schema-name = public auto-initialize = on connection-string = """ + connectionString + @""" } } }"; SpecConfig = ConfigurationFactory.ParseString(config); //need to make sure db is created before the tests start DbUtils.Initialize(); }
public StringPathEntry(bool valid, bool exists, Config config, string value) : this() { Config = config; Exists = exists; Valid = valid; Value = value; }
public Type GetMailboxType(Props props, Config dispatcherConfig) { if (!string.IsNullOrEmpty(props.Mailbox)) { return FromConfig(props.Mailbox); } var actortype = props.Type; var interfaces = actortype.GetInterfaces() .Where(i => i.IsGenericType) .Where(i => i.GetGenericTypeDefinition() == typeof (RequiresMessageQueue<>)) .Select(i => i.GetGenericArguments().First()) .ToList(); if (interfaces.Count > 0) { var config = _requirementsMapping[interfaces.First()]; var mailbox = config.GetString("mailbox-type"); var mailboxType = Type.GetType(mailbox); return mailboxType; } return FromConfig(DefaultMailboxId); }
/// <summary> /// Creates cluster publish subscribe settings from provided configuration with the same layout as `akka.cluster.pub-sub`. /// </summary> public static DistributedPubSubSettings Create(Config config) { RoutingLogic routingLogic = null; var routingLogicName = config.GetString("routing-logic"); switch (routingLogicName) { case "random": routingLogic = new RandomLogic(); break; case "round-robin": routingLogic = new RoundRobinRoutingLogic(); break; case "broadcast": routingLogic = new BroadcastRoutingLogic(); break; case "consistent-hashing": throw new ArgumentException("Consistent hashing routing logic cannot be used by the pub-sub mediator"); default: throw new ArgumentException("Unknown routing logic is tried to be applied to the pub-sub mediator: " + routingLogicName); } return new DistributedPubSubSettings( config.GetString("role"), routingLogic, config.GetTimeSpan("gossip-interval"), config.GetTimeSpan("removed-time-to-live"), config.GetInt("max-delta-elements")); }
static void Main(string[] args) { Config fallbackConfig = ConfigurationFactory.ParseString(@" akka.suppress-json-serializer-warning=true akka.loglevel = DEBUG ").WithFallback(ConfigurationFactory.FromResource <ConsumerSettings <object, object> >("Akka.Streams.Kafka.reference.conf")); var system = ActorSystem.Create("TestKafka", fallbackConfig); var throwEventActor = system.ActorOf(Props.Create <IntermediateMessageThrowEventActor>()); var sequenceFlowInput = new SequenceFlowInput { ProcessInstanceId = Guid.NewGuid(), Payload = new InputPayload { Status = "Exported", EventId = Guid.NewGuid().ToString(), } }; throwEventActor.Tell(sequenceFlowInput); Console.ReadLine(); }
public static void Main(string[] args) { Config fallbackConfig = ConfigurationFactory.ParseString(@" akka.suppress-json-serializer-warning=true akka.loglevel = DEBUG ").WithFallback(ConfigurationFactory.FromResource <ConsumerSettings <object, object> >("Akka.Streams.Kafka.reference.conf")); var system = ActorSystem.Create("TestKafka", fallbackConfig); var materializer = system.Materializer(); var producerSettings = ProducerSettings <Null, string> .Create(system, null, null) .WithBootstrapServers("localhost:29092"); Source .Cycle(() => Enumerable.Range(1, 100).GetEnumerator()) .Select(c => c.ToString()) .Select(elem => ProducerMessage.Single(new ProducerRecord <Null, string>("akka100", elem))) .Via(KafkaProducer.FlexiFlow <Null, string, NotUsed>(producerSettings)) .Select(result => { var response = result as Result <Null, string, NotUsed>; Console.WriteLine($"Producer: {response.Metadata.Topic}/{response.Metadata.Partition} {response.Metadata.Offset}: {response.Metadata.Value}"); return(result); }) .RunWith(Sink.Ignore <IResults <Null, string, NotUsed> >(), materializer); // TODO: producer as a Commitable Sink // TODO: Sharing KafkaProducer Console.ReadLine(); }
protected PersistenceSpec(Config config = null, ITestOutputHelper output = null) : base(config, output) { _name = NamePrefix + "-" + _counter.GetAndIncrement(); Clean = new Cleanup(this); Clean.Initialize(); }
internal static TimeSpan? GetSafeDeadlockTimeout(Config cfg) { var timespan = cfg.GetTimeSpan("deadlock-timeout", TimeSpan.FromSeconds(-1)); if (timespan.TotalSeconds < 0) return null; return timespan; }
public CurrentSynchronizationContextDispatcherConfigurator(Config config, IDispatcherPrerequisites prerequisites) : base(config, prerequisites) { _executorServiceConfigurator = new CurrentSynchronizationContextExecutorServiceFactory(config, prerequisites); // We don't bother trying to support any other type of exectuor here. PinnedDispatcher doesn't support them }
public MemoryEventAdaptersSpec() { var config = ConfigurationFactory.ParseString(@" akka.persistence.journal { plugin = ""akka.persistence.journal.inmem"" # adapters defined for all plugins common-event-adapter-bindings { } inmem { # showcases re-using and concating configuration of adapters event-adapters { example = """ + typeof (ExampleEventAdapter).FullName + @", Akka.Persistence.Tests"" marker = """ + typeof (MarkerInterfaceAdapter).FullName + @", Akka.Persistence.Tests"" precise = """ + typeof (PreciseAdapter).FullName + @", Akka.Persistence.Tests"" reader = """ + typeof (ReaderAdapter).FullName + @", Akka.Persistence.Tests"" writer = """ + typeof (WriterAdapter).FullName + @", Akka.Persistence.Tests"" } event-adapter-bindings = { """ + typeof (IEventMarkerInterface).FullName + @", Akka.Persistence.Tests"" = marker ""System.String"" = example """ + typeof (PreciseAdapterEvent).FullName + @", Akka.Persistence.Tests"" = precise """ + typeof (ReadMeEvent).FullName + @", Akka.Persistence.Tests"" = reader """ + typeof (WriteMeEvent).FullName + @", Akka.Persistence.Tests"" = writer } } }").WithFallback(ConfigurationFactory.Load()); _extendedActorySystem = (ExtendedActorSystem) Sys; _memoryConfig = config.GetConfig("akka.persistence.journal.inmem"); }
static SqlServerSnapshotStoreSpec() { var connectionString = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString.Replace(@"\", "\\"); var specString = @" akka.persistence { publish-plugin-commands = on snapshot-store { plugin = ""akka.persistence.snapshot-store.sql-server"" sql-server { class = ""Akka.Persistence.SqlServer.Snapshot.SqlServerSnapshotStore, Akka.Persistence.SqlServer"" plugin-dispatcher = ""akka.actor.default-dispatcher"" table-name = SnapshotStore schema-name = dbo auto-initialize = on connection-string-name = ""TestDb"" } } }"; SpecConfig = ConfigurationFactory.ParseString(specString); //need to make sure db is created before the tests start DbUtils.Initialize(); }
public PinnedDispatcherConfigurator(Config config, IDispatcherPrerequisites prerequisites) : base(config, prerequisites) { _executorServiceConfigurator = new ForkJoinExecutorServiceFactory(ForkJoinExecutorServiceFactory.SingleThreadDefault.WithFallback("id=" + config.GetString("id")), Prerequisites); // We don't bother trying to support any other type of exectuor here. PinnedDispatcher doesn't support them }
private static ActorSystem CreateClient(Config commonConfig) { var config = commonConfig.WithFallback("akka.remote.helios.tcp.port = 9002"); var system = ActorSystem.Create("Client", config); DeadRequestProcessingActor.Install(system); return system; }
/// <summary> /// Initializes a new instance of the <see cref="Settings" /> class. /// </summary> /// <param name="system">The system.</param> /// <param name="config">The configuration.</param> public Settings(ActorSystem system, Config config) { Config fallback = ConfigurationFactory.Default(); Config merged = config == null ? fallback : new Config(config, fallback); System = system; Config = merged; ConfigVersion = Config.GetString("akka.version"); ProviderClass = Config.GetString("akka.actor.provider"); SupervisorStrategyClass = Config.GetString("akka.actor.guardian-supervisor-strategy"); CreationTimeout = Config.GetMillisDuration("akka.actor.creation-timeout"); UnstartedPushTimeout = Config.GetMillisDuration("akka.actor.unstarted-push-timeout"); SerializeAllMessages = Config.GetBoolean("akka.actor.serialize-messages"); SerializeAllCreators = Config.GetBoolean("akka.actor.serialize-creators"); LogLevel = Config.GetString("akka.loglevel"); StdoutLogLevel = Config.GetString("akka.stdout-loglevel"); Loggers = Config.GetStringList("akka.loggers"); LoggerStartTimeout = Config.GetMillisDuration("akka.logger-startup-timeout"); //handled LogConfigOnStart = Config.GetBoolean("akka.log-config-on-start"); LogDeadLetters = 0; switch (Config.GetString("akka.log-dead-letters")) { case "on": case "true": LogDeadLetters = int.MaxValue; break; case "off": case "false": LogDeadLetters = 0; break; default: LogDeadLetters = Config.GetInt("akka.log-dead-letters"); break; } LogDeadLettersDuringShutdown = Config.GetBoolean("akka.log-dead-letters-during-shutdown"); AddLoggingReceive = Config.GetBoolean("akka.actor.debug.receive"); DebugAutoReceive = Config.GetBoolean("akka.actor.debug.autoreceive"); DebugLifecycle = Config.GetBoolean("akka.actor.debug.lifecycle"); DebugEventStream = Config.GetBoolean("akka.actor.debug.event-stream"); DebugUnhandledMessage = Config.GetBoolean("akka.actor.debug.unhandled"); DebugRouterMisConfiguration = Config.GetBoolean("akka.actor.debug.router-misConfiguration"); Home = Config.GetString("akka.home") ?? ""; //TODO: dunno.. we dont have FiniteStateMachines, dont know what the rest is /* final val FsmDebugEvent: Boolean = getBoolean("akka.actor.debug.fsm") final val SchedulerClass: String = getString("akka.scheduler.implementation") final val Daemonicity: Boolean = getBoolean("akka.daemonic") final val DefaultVirtualNodesFactor: Int = getInt("akka.actor.deployment.default.virtual-nodes-factor") */ }
private TestKitBase(ITestKitAssertions assertions, ActorSystem system, Config config, string actorSystemName, string testActorName) { if(assertions == null) throw new ArgumentNullException("assertions"); _assertions = assertions; InitializeTest(system, config, actorSystemName, testActorName); }
public Deploy(string path, Config config, RouterConfig routerConfig, Scope scope, string dispatcher) { Path = path; Config = config; RouterConfig = routerConfig; Scope = scope; Dispatcher = dispatcher; }
/// <summary> /// Initializes a new instance of the <see cref="Config"/> class. /// </summary> /// <param name="source">The configuration to use as the primary source.</param> /// <param name="fallback">The configuration to use as a secondary source.</param> /// <exception cref="ArgumentNullException">The source configuration cannot be null.</exception> public Config(Config source, Config fallback) { if (source == null) throw new ArgumentNullException("source"); Root = source.Root; Fallback = fallback; }
/// <summary> /// Creates cluster sharding proxy 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="windsorContainer">Dependency resolver</param> /// <param name="pathName">New actor's path name</param> protected virtual void CreateShardingProxyActor( IActorContext context, Config actorConfig, IWindsorContainer windsorContainer, string pathName) { context.ActorOf(Props.Create(() => new ShardingProxyWrappperActor(windsorContainer, actorConfig)), pathName); }
public static ClusterSingletonManagerSettings Create(Config config) { return new ClusterSingletonManagerSettings( singletonName: config.GetString("singleton-name"), role: RoleOption(config.GetString("role")), removalMargin: TimeSpan.Zero, // defaults to ClusterSettins.DownRemovalMargin handOverRetryInterval: config.GetTimeSpan("hand-over-retry-interval")); }
public AkkaSetting(IConfiguration configuration) { string akkaip = configuration.GetSection("akkaip").Value; string akkaport = configuration.GetSection("akkaport").Value; string akkaseed = configuration.GetSection("akkaseed").Value; string hconString = @" akka { remote { dot-netty.tcp { port = $akkaport hostname = ""$akkaip"" } } actor{ provider = cluster deployment { /scatter { router = scatter-gather-group # routing strategy routees.paths = [""/user/accountpool""] nr -of-instances = 10 # max number of total routees cluster { enabled = on allow-local-routees = off use-role = account max-nr-of-instances-per-node = 1 } } } } actor { serializers { json = ""Akka.Serialization.NewtonSoftJsonSerializer"" bytes = ""Akka.Serialization.ByteArraySerializer"" } serialization-bindings { ""System.Byte[]"" = bytes ""System.Object"" = json } } cluster { seed-nodes = [""akka.tcp://AccountClusterSystem@$akkaseed""] # address of seed node roles = [""account""] # roles this member is in } } " .Replace("$akkaport", akkaport) .Replace("$akkaip", akkaip) .Replace("$akkaseed", akkaseed); hConfig = ConfigurationFactory.ParseString(hconString); }
private static ActorSystem CreateAndStartSystem(string name, Config withFallback, ActorSystemSetup setup) { // allows the ThreadPool to scale up / down dynamically // by removing minimum thread count, which in our benchmarks // appears to negatively impact performance ThreadPool.SetMinThreads(0, 0); var system = new ActorSystemImpl(name, withFallback, setup, Option <Props> .None); system.Start(); return(system); }
public static async Task Main(string[] args) { Config fallbackConfig = ConfigurationFactory.ParseString(@" akka.suppress-json-serializer-warning=true akka.loglevel = DEBUG ").WithFallback(ConfigurationFactory.FromResource <ConsumerSettings <object, object> >("Akka.Streams.Kafka.reference.conf")); var system = ActorSystem.Create("TestKafka", fallbackConfig); var materializer = system.Materializer(); var consumerSettings = ConsumerSettings <Null, string> .Create(system, null, null) .WithBootstrapServers($"{EventHubNamespace}.servicebus.windows.net:9093") .WithGroupId(EventHubConsumerGroup) .WithProperties(new Dictionary <string, string> { { "security.protocol", "SASL_SSL" }, { "sasl.mechanism", "PLAIN" }, { "sasl.username", "$ConnectionString" }, { "sasl.password", EventHubConnectionString }, }); var subscription = Subscriptions.Topics(EventHubName); var committerDefaults = CommitterSettings.Create(system); // Comment for simple no-commit consumer DrainingControl <NotUsed> control = KafkaConsumer.CommittableSource(consumerSettings, subscription) .SelectAsync(1, msg => Business(msg.Record).ContinueWith(done => (ICommittable)msg.CommitableOffset)) .ToMaterialized( Committer.Sink(committerDefaults.WithMaxBatch(1)), DrainingControl <NotUsed> .Create) .Run(materializer); // Uncomment for simple no-commit consumer /* * await KafkaConsumer.PlainSource(consumerSettings, subscription) * .RunForeach(result => * { * Console.WriteLine($"Consumer: {result.Topic}/{result.Partition} {result.Offset}: {result.Value}"); * }, materializer); */ Console.WriteLine("Press any key to stop consumer."); Console.ReadKey(); // Comment for simple no-commit consumer await control.Stop(); await system.Terminate(); }
public static Akka.Configuration.Config WithPortFromEnvironmentVariable(this Akka.Configuration.Config clusterConfig) { var actualPort = -1; var envPort = Environment.GetEnvironmentVariable("CLUSTER_PORT")?.Trim(); if (!string.IsNullOrEmpty(envPort)) { int.TryParse(envPort, out actualPort); } if (actualPort != -1) { return(ConfigurationFactory.ParseString($"akka.remote.dot-netty.tcp.port = {actualPort}") .WithFallback(clusterConfig)); } return(clusterConfig); }
private void CreateNotifier(Akka.Configuration.Config config) { var uiNotificationWidth = config.GetInt("ui.notification.width"); var uiNotificationLifetime = config.GetTimeSpan("ui.notification.lifetime"); var uiNotificationMax = config.GetInt("ui.notification.maximum-count"); Notifier = new Notifier(cfg => { cfg.DisplayOptions.Width = uiNotificationWidth; cfg.PositionProvider = new PrimaryScreenPositionProvider(Corner.BottomRight, 0, 0); cfg.LifetimeSupervisor = new TimeAndCountBasedLifetimeSupervisor( notificationLifetime: uiNotificationLifetime, maximumNotificationCount: MaximumNotificationCount.FromCount(uiNotificationMax)); cfg.Dispatcher = Application.Current.Dispatcher; }); }
private void CreateTrayIcon(Akka.Configuration.Config config) { NotifyIcon = new System.Windows.Forms.NotifyIcon { Icon = BLUECATS.ToastNotifier.Properties.Resources.favicon, Text = "BLUE CATS Client" }; var menu = new System.Windows.Forms.ContextMenu(); NotifyIcon.ContextMenu = menu; NotifyIcon.Visible = true; var authority = AkkaHelper.ReadConfigurationFromHoconFile(Assembly.GetExecutingAssembly(), "conf") .WithFallback(ConfigurationFactory .FromResource <ConsumerSettings <object, object> >("Akka.Streams.Kafka.reference.conf")) .GetInt("ui.notification.authority-level"); menu.MenuItems.Add($"{_version} [{authority}]").Enabled = false; menu.MenuItems.Add(new System.Windows.Forms.MenuItem(@"&BLUE CATS", onClick: (_, __) => { var url = config.GetString("ui.server.url"); System.Diagnostics.Process.Start(url); })); menu.MenuItems.Add("-"); menu.MenuItems.Add(new System.Windows.Forms.MenuItem(@"&All Clear", onClick: (_, __) => { //notificationActor.Tell(new ClearAll()); Notifier.ClearMessages(new ClearAll()); })); menu.MenuItems.Add(new System.Windows.Forms.MenuItem(@"&Exit", onClick: (_, __) => { NotifyIcon.Visible = false; Shutdown(); })); }
static async Task Main(string[] args) { Config fallbackConfig = ConfigurationFactory.ParseString(@" akka.suppress-json-serializer-warning=true akka.loglevel = DEBUG ").WithFallback(ConfigurationFactory.FromResource <ConsumerSettings <object, object> >("Akka.Streams.Kafka.reference.conf")); var system = ActorSystem.Create("TestKafka", fallbackConfig); var materializer = system.Materializer(); var producerSettings = ProducerSettings <Null, string> .Create(system, null, null) .WithBootstrapServers($"{EventHubNamespace}.servicebus.windows.net:9093") .WithProperties(new Dictionary <string, string> { { "security.protocol", "SASL_SSL" }, { "sasl.mechanism", "PLAIN" }, { "sasl.username", "$ConnectionString" }, { "sasl.password", EventHubConnectionString }, }); await Source.From(Enumerable.Range(1, 100)) .Select(c => c.ToString()) .Select(elem => ProducerMessage.Single(new ProducerRecord <Null, string>(EventHubName, elem))) .Via(KafkaProducer.FlexiFlow <Null, string, NotUsed>(producerSettings)) .Select(result => { var response = result as Result <Null, string, NotUsed>; Console.WriteLine($"Producer: {response.Metadata.Topic}/{response.Metadata.Partition} {response.Metadata.Offset}: {response.Metadata.Value}"); return(result); }) .RunWith(Sink.Ignore <IResults <Null, string, NotUsed> >(), materializer); Console.ReadKey(); await system.Terminate(); }
private static AkkaConfig LoadConfig(string environment, string configFile, IConfiguration configuration) { string akkaip = configuration.GetSection("akkaip").Value ?? "127.0.0.1"; string akkaport = configuration.GetSection("akkaport").Value ?? "5100"; string akkaseed = configuration.GetSection("akkaseed").Value ?? "127.0.0.1:5100"; string roles = configuration.GetSection("roles").Value ?? "akkanet"; var configFilePath = string.Format(configFile, environment.ToLower() != "production" ? string.Concat(".", environment) : ""); if (File.Exists(configFilePath)) { string akkaseed_array; if (akkaseed.Split(",").Length > 1) { akkaseed_array = akkaseed.Split(",").Aggregate("[", (current, seed) => current + @"""" + seed + @""", "); akkaseed_array += "]"; } else { akkaseed_array = "[\"" + akkaseed + "\"]"; } string roles_array; if (roles.Split(",").Length > 1) { roles_array = roles.Split(",").Aggregate("[", (current, role) => current + @"""" + role + @""", "); roles_array += "]"; } else { roles_array = "[\"" + roles + "\"]"; } string customConfig = @" akka { remote { log-remote-lifecycle-events = debug dot-netty.tcp { port = $akkaport hostname = $akkaip } } cluster { seed-nodes = $akkaseed roles = $roles } } ".Replace("$akkaport", akkaport) .Replace("$akkaip", akkaip) .Replace("$akkaseed", akkaseed_array) .Replace("$roles", roles_array); AkkaConfig injectedClusterConfigString = customConfig; string configText = File.ReadAllText(configFilePath); var akkaConfig = ConfigurationFactory.ParseString(configText); var finalConfig = injectedClusterConfigString.WithFallback(akkaConfig); Console.WriteLine($"=== AkkaConfig:{configFilePath}\r\n{finalConfig}\r\n==="); return(finalConfig); } return(ConfigurationFactory.Empty); }
private static string GetBootStrapServers(Akka.Configuration.Config config) { return(config.GetStringList("kafka.bootstrap-servers") .Aggregate(new StringBuilder(), (builder, item) => builder.Append(builder.Length == 0 ? "" : ", ").Append(item)) .ToString()); }
/// <summary> /// Creates a new <see cref="ActorSystem"/> with the specified name and configuration. /// </summary> /// <param name="name">The name of the actor system to create. The name must be uri friendly. /// <remarks>Must contain only word characters (i.e. [a-zA-Z0-9] plus non-leading '-'</remarks> /// </param> /// <param name="config">The configuration used to create the actor system</param> /// <returns>A newly created actor system with the given name and configuration.</returns> public static ActorSystem Create(string name, Config config) { return(CreateAndStartSystem(name, config, ActorSystemSetup.Empty)); }
public BootstrapSetup WithConfigFallback(Config config) => Config.HasValue ? new BootstrapSetup(Config.Value.SafeWithFallback(config), ActorRefProvider) : WithConfig(config);
public BootstrapSetup WithConfig(Config config) { return(new BootstrapSetup(config, ActorRefProvider)); }
/// <summary> /// Creates a new <see cref="ActorSystem"/> with the specified name and configuration. /// </summary> /// <param name="name">The name of the actor system to create. The name must be uri friendly. /// <remarks>Must contain only word characters (i.e. [a-zA-Z0-9] plus non-leading '-'</remarks> /// </param> /// <param name="config">The configuration used to create the actor system</param> /// <returns>A newly created actor system with the given name and configuration.</returns> public static ActorSystem Create(string name, Config config) { // var withFallback = config.WithFallback(ConfigurationFactory.Default()); return(CreateAndStartSystem(name, config)); }
public SqlConnectionProvider(Akka.Configuration.Config config) { this.config = config; }
public static ActorSystem LaunchLighthouse(string ipAddress = null, int?specifiedPort = null, string systemName = null) { systemName = systemName ?? Environment.GetEnvironmentVariable("ACTORSYSTEM")?.Trim(); // Set environment variables for use inside Akka.Bootstrap.Docker // If overrides were provided to this method. //if (!string.IsNullOrEmpty(ipAddress)) Environment.SetEnvironmentVariable("CLUSTER_IP", ipAddress); //if (specifiedPort != null) // Environment.SetEnvironmentVariable("CLUSTER_PORT", specifiedPort.Value.ToString()); var useDocker = !(IsNullOrEmpty(Environment.GetEnvironmentVariable("CLUSTER_IP")?.Trim()) || IsNullOrEmpty(Environment.GetEnvironmentVariable("CLUSTER_SEEDS")?.Trim())); var clusterConfig = ConfigurationFactory.ParseString(File.ReadAllText("akka.hocon")); if (useDocker) { clusterConfig = clusterConfig.BootstrapFromDocker(); } var lighthouseConfig = clusterConfig.GetConfig("lighthouse"); if (lighthouseConfig != null && IsNullOrEmpty(systemName)) { systemName = lighthouseConfig.GetString("actorsystem", systemName); } ipAddress = clusterConfig.GetString("akka.remote.dot-netty.tcp.public-hostname", "127.0.0.1"); var port = clusterConfig.GetInt("akka.remote.dot-netty.tcp.port"); var sslEnabled = clusterConfig.GetBoolean("akka.remote.dot-netty.tcp.enable-ssl"); var selfAddress = sslEnabled ? new Address("akka.ssl.tcp", systemName, ipAddress.Trim(), port).ToString() : new Address("akka.tcp", systemName, ipAddress.Trim(), port).ToString(); /* * Sanity check */ Console.WriteLine($"[Lighthouse] ActorSystem: {systemName}; IP: {ipAddress}; PORT: {port}"); Console.WriteLine("[Lighthouse] Performing pre-boot sanity check. Should be able to parse address [{0}]", selfAddress); Console.WriteLine("[Lighthouse] Parse successful."); var seeds = clusterConfig.GetStringList("akka.cluster.seed-nodes").ToList(); AkkaConfig injectedClusterConfigString = null; if (!seeds.Contains(selfAddress)) { seeds.Add(selfAddress); if (seeds.Count > 1) { injectedClusterConfigString = seeds.Aggregate("akka.cluster.seed-nodes = [", (current, seed) => current + @"""" + seed + @""", "); injectedClusterConfigString += "]"; } else { injectedClusterConfigString = "akka.cluster.seed-nodes = [\"" + selfAddress + "\"]"; } } var finalConfig = injectedClusterConfigString != null ? injectedClusterConfigString .WithFallback(clusterConfig) : clusterConfig; return(ActorSystem.Create(systemName, finalConfig)); }
public static async Task Rubbish(Akka.Configuration.Config config) { var actorSystem = ActorSystem.Create("tessttt", config); var repositoryActor = actorSystem.ActorOf(Props.Create(() => new RepositoryActor <GiftCardProjection, GiftCardProjectionId>()), "repository-actor"); var projectorMap = new ProjectorMap <GiftCardProjection, GiftCardProjectionId, GiftCardProjectionContext> { Create = async(key, context, projector, shouldOverride) => { var projection = new GiftCardProjection() { Id = key }; await projector(projection); repositoryActor.Tell(new Create <GiftCardProjection, GiftCardProjectionId> { Projection = projection }); }, Update = async(key, context, projector, createIfMissing) => { var query = new Read <GiftCardProjectionId> { Key = key }; var projection = await repositoryActor.Ask <GiftCardProjection>(query); await projector(projection); repositoryActor.Tell(new Update <GiftCardProjection, GiftCardProjectionId> { Projection = projection }); }, Delete = (key, context) => { var command = new Delete <GiftCardProjectionId> { Key = key }; repositoryActor.Tell(command); return(Task.FromResult(true)); }, Custom = (context, projector) => projector() }; var eventMap = new EventMapBuilder <GiftCardProjection, GiftCardProjectionId, GiftCardProjectionContext>(); eventMap.Map <DomainEvent <GiftCard, GiftCardId, IssuedEvent> >() .AsCreateOf(x => IProjectionIdExtensions.From(x.AggregateIdentity)) .Using((projection, evt) => { projection.Credits = evt.AggregateEvent.Credits; projection.IsCancelled = false; projection.Issued = evt.Timestamp.UtcDateTime; }); eventMap.Map <DomainEvent <GiftCard, GiftCardId, RedeemedEvent> >() .AsUpdateOf(x => IProjectionIdExtensions.From(x.AggregateIdentity)) .Using((projection, evt) => { projection.Credits -= evt.AggregateEvent.Credits; }); eventMap.Map <DomainEvent <GiftCard, GiftCardId, CancelledEvent> >() .AsUpdateOf(x => IProjectionIdExtensions.From(x.AggregateIdentity)) .Using((projection, evt) => { projection.IsCancelled = false; }); var handler = eventMap.Build(projectorMap); var context2 = new GiftCardProjectionContext(); var mat = ActorMaterializer.Create(actorSystem); await PersistenceQuery .Get(actorSystem) .ReadJournalFor <SqlReadJournal>(SqlReadJournal.Identifier) .CurrentEventsByPersistenceId("giftcard-a8fd515e-d4fb-4bf6-9d7f-67abdd0fdeef", 0, 10) .RunForeach(async x => await handler.Handle(x.Event, context2), mat); }