예제 #1
0
        public async Task CoordinatedShutdown_must_not_be_run_by_ActorSystem_Terminate_when_run_by_actor_system_terminate_is_off()
        {
            var sys = ActorSystem.Create(
                "name",
                ConfigurationFactory
                .ParseString(@"
                        akka.coordinated-shutdown.terminate-actor-system = on
                        akka.coordinated-shutdown.run-by-actor-system-terminate = off")
                .WithFallback(Sys.Settings.Config));
            var actor = CoordinatedShutdown.Get(sys);

            try
            {
                await sys.Terminate();

                sys.WhenTerminated.IsCompleted.Should().BeTrue();
                actor.ShutdownReason.ShouldBeEquivalentTo(null);
            }
            finally
            {
                Shutdown(sys);
            }
        }
예제 #2
0
        private static void EventListener_ActorSystemQuarantinedEvent(object sender, EventArgs e)
        {
            // write console log
            Console.WriteLine($"This Actor System quarantined by {e.ToString()} and will try to restart.");

            // unsubscribe from event stream
            _actorSystem.EventStream.Unsubscribe <ThisActorSystemQuarantinedEvent>(_listenerActor);

            // detach custom event of terminator

            // stop terminator actor
            _actorSystem.Stop(_listenerActor);


            // run coordinated shutdown to terminate actor system
            CoordinatedShutdown
            .Get(_actorSystem)
            .Run(CoordinatedShutdown.ClusterLeavingReason.Instance)
            .ContinueWith(t =>
            {
                StartActorSystem();
            });
        }
예제 #3
0
파일: Program.cs 프로젝트: fzf003/EventFly
        public static async Task Main(String[] args)
        {
            var actorSystem = ActorSystem.Create("print-job-system", Configuration.Config);

            var sp = new ServiceCollection()
                     .AddEventFly(actorSystem)
                     .WithContext <TestContext>()
                     .Services
                     .BuildServiceProvider();

            sp.UseEventFly();

            var scheduler = sp.GetService <EventFly.Jobs.IScheduler>();

            var firstJobId  = PrintJobId.New;
            var secondJobId = PrintJobId.New;
            var thirdJobId  = PrintJobId.New;

            var time = DateTime.UtcNow;

            await scheduler.Schedule <PrintJob, PrintJobId>(new PrintJob(firstJobId, "first"), TimeSpan.FromSeconds(5), time.AddSeconds(5));

            await scheduler.Schedule <PrintJob, PrintJobId>(new PrintJob(secondJobId, "second"), TimeSpan.FromSeconds(5), time.AddSeconds(6));

            await scheduler.Schedule <PrintJob, PrintJobId>(new PrintJob(thirdJobId, "THIRD"), time.AddSeconds(10));

            Console.ReadKey();

            await scheduler.Cancel <PrintJob, PrintJobId>(secondJobId);

            Console.ReadKey();

            Task shutdownTask = CoordinatedShutdown.Get(actorSystem)
                                .Run(CoordinatedShutdown.ClrExitReason.Instance);

            await shutdownTask;
        }
예제 #4
0
        protected override void OnReceive(object message)
        {
            switch (message)
            {
            case Run run:
                _startDateTime = DateTime.Now;
                _num           = run.Num - 1;

                var skynetActor = Context.ActorOf(SkynetActor.Props);
                var childStart  = new SkynetActor.Start(7, 0);

                skynetActor.Tell(childStart);

                break;

            case long l:
                var now      = DateTime.Now;
                var timeSpan = now - _startDateTime;

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"Result: {l} in {timeSpan.TotalMilliseconds} ms.");
                Console.ForegroundColor = ConsoleColor.White;

                if (_num == 0)
                {
                    CoordinatedShutdown.Get(Context.System).Run().Wait(5000);
                    Console.WriteLine("Actor System Terminated");
                }
                else
                {
                    Self.Tell(new Run(_num));
                }

                break;
            }
        }
예제 #5
0
        public void CoordinatedShutdown_must_only_run_once()
        {
            var phases = new Dictionary <string, Phase>()
            {
                { "a", EmptyPhase }
            };

            var co = new CoordinatedShutdown(ExtSys, phases);

            co.AddTask("a", "a1", () =>
            {
                TestActor.Tell("A");
                return(TaskEx.Completed);
            });

            co.ShutdownReason.Should().BeNull();
            co.Run(customReason).Wait(RemainingOrDefault);
            co.ShutdownReason.ShouldBeEquivalentTo(customReason);
            ExpectMsg("A");
            co.Run(CoordinatedShutdown.UnknownReason.Instance).Wait(RemainingOrDefault);
            TestActor.Tell("done");
            ExpectMsg("done"); // no additional A
            co.ShutdownReason.ShouldBeEquivalentTo(customReason);
        }
예제 #6
0
        private static async Task Main(string[] args)
        {
            var baseUri    = new Uri(args[0]);
            var outputSize = args.Length > 1
                ? int.Parse(args[1])
                : DefaultOutputSize;


            using var system = ActorSystem.Create("getlink-system");
            var supervisor = system.ActorOf(
                SupervisorActor.CreateProps(),
                "supervisor");


            supervisor.Tell(new GetSiteLinksRequest(baseUri, outputSize));


            Console.WriteLine("Press any key to exit application");
            Console.WriteLine();
            Console.Read();

            await CoordinatedShutdown.Get(system)
            .Run(CoordinatedShutdown.ClrExitReason.Instance);
        }
 public Task Stop()
 {
     return(CoordinatedShutdown.Get(ClusterSystem).Run());
 }
예제 #8
0
 public async Task StopAsync()
 {
     await CoordinatedShutdown.Get(_nodeSystem).Run(new ManualRequestReason());
 }
예제 #9
0
        public SimulationContext()
        {
            Receive <Command>(s => s == Command.Start, s =>
            {
                //Console.WriteLine("-- Starting Simulation -- !");
                Stash.UnstashAll();

                BecomeStacked(() =>
                {
                    Receive <Command>(c => c == Command.Done, c =>
                    {
                        //System.Diagnostics.Debug.WriteLine("-- Done");
                        _CurrentInstructions--;
                        Advance();
                    });

                    Receive <Command>(c => c == Command.Stop, c =>
                    {
                        // Console.WriteLine("-- Resume simulation -- !");
                        //System.Diagnostics.Debug.WriteLine("STOP");
                        Context.UnbecomeStacked();
                    });

                    Receive <Shutdown>(c =>
                    {
                        if (_CurrentInstructions == 0 && _FeaturedInstructions.Count() == 0)
                        {
                            //System.Diagnostics.Debug.WriteLine("Simulation Finished...");
                            CoordinatedShutdown.Get(Context.System).Run();
                        }
                    });

                    Receive <Schedule>(m =>
                    {
                        var sheduleAt = m.Delay + TimePeriod;
                        if (_FeaturedInstructions.TryGetValue(sheduleAt, out long value))
                        {
                            _FeaturedInstructions[sheduleAt] = _FeaturedInstructions[sheduleAt] + 1;
                        }
                        else
                        {
                            _FeaturedInstructions.Add(sheduleAt, 1);
                        }

                        m.Message.Target.Forward(m);
                    });

                    Receive <ISimulationMessage>(m =>
                    {
                        if (m.Target != null)
                        {
                            m.Target.Forward(m);
                        }
                        else if (m.TargetSelection != null)
                        {
                            m.TargetSelection.Tell(m);
                        }
                        else
                        {
                            Sender.Tell(m);
                        }

                        //System.Diagnostics.Debug.WriteLine("++" + m.GetType().ToString());
                        _CurrentInstructions++;
                    });

                    ReceiveAny(_ => Stash.Stash());
                });
            });

            ReceiveAny(_ => Stash.Stash());
        }
예제 #10
0
        static async Task Main(string[] args)
        {
            var myPort = int.Parse(args[0]);

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

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

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


            #region Echo singleton service example

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

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

            #endregion

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

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

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

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

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

            Console.WriteLine("End..");
        }
    public void Stop()
    {
        Task <Done> shutdownTask = CoordinatedShutdown.Get(actorSystem).Run(CoordinatedShutdown.ClrExitReason.Instance);

        shutdownTask.Wait();
    }
예제 #12
0
 public Task StopAsync(CancellationToken cancellationToken) => CoordinatedShutdown.Get(Sys).Run(CoordinatedShutdown.ClrExitReason.Instance);
예제 #13
0
 public async Task StopAsync(CancellationToken cancellationToken)
 {
     // theoretically, shouldn't even need this - will be invoked automatically via CLR exit hook
     // but it's good practice to actually terminate IHostedServices when ASP.NET asks you to
     await CoordinatedShutdown.Get(_actorSystem).Run(CoordinatedShutdown.ClrExitReason.Instance);
 }
예제 #14
0
        private void NormalMode()
        {
            Receive <Command>(s => s == Command.Start, s =>
            {
                if (_CurrentInstructions == 0)
                {
                    _IsRunning    = true;
                    _nextInterupt = _nextInterupt + _SimulationConfig.InteruptInterval;
                    _SimulationConfig.Inbox.Receiver.Tell(SimulationState.Started);
                    Advance();
                }
                else
                {
                    // Not Ready Yet, Try Again
                    Context.Self.Tell(s);
                }
            });

            // Determine when The Simulation is Done.
            Receive <Command>(s => s == Command.IsReady, s =>
            {
                //if (_InstructionStore.Count() == 0)
                if (_CurrentInstructions == 0)
                {
                    Sender.Tell(Command.IsReady, ActorRefs.NoSender);
                }
                else
                {
                    // Not Ready Yet, Try Again
                    Context.Self.Forward(s);
                }
            });

            // Determine when The Simulation is Done.
            Receive <SimulationState>(s => s == SimulationState.Finished, s =>
            {
                //if (_InstructionStore.Count() == 0)
                if (_CurrentInstructions == 0)
                {
                    _SimulationConfig.Inbox.Receiver.Tell(SimulationState.Finished);
                    _IsComplete = true;
                }
                else
                {
                    // Not Ready Yet, Try Again
                    Context.Self.Forward(s);
                }
            });

            Receive <Done>(c =>
            {
                //Console.WriteLine("--");
                _CurrentInstructions--;
                Advance();
            });

            Receive <Command>(c => c == Command.Stop, c =>
            {
                // Console.WriteLine("-- Resume simulation -- !");
                _IsRunning = false;
            });

            Receive <Shutdown>(c =>
            {
                if (_CurrentInstructions == 0 && _FeaturedInstructions.Count() == 0)
                {
                    CoordinatedShutdown.Get(Context.System).Run();
                }
            });

            Receive <Schedule>(m =>
            {
                LogInterceptor(m.Message);

                var sheduleAt = m.Delay + TimePeriod;

                if (_FeaturedInstructions.TryGetValue(sheduleAt, out long value))
                {
                    _FeaturedInstructions[sheduleAt] = _FeaturedInstructions[sheduleAt] + 1;
                }
                else
                {
                    _FeaturedInstructions.Add(sheduleAt, 1);
                }

                m.Message.Target.Forward(m);
            });

            Receive <ISimulationMessage>(m =>
            {
                LogInterceptor(m);

                if (m.Target != ActorRefs.NoSender)
                {
                    m.Target.Forward(m);
                }
                else if (m.TargetSelection != null)
                {
                    m.TargetSelection.Tell(m);
                }
                else
                {
                    Sender.Tell(m);
                }
                //Console.WriteLine("++");
                _CurrentInstructions++;
            });
        }
예제 #15
0
 private void StopApplication()
 {
     CoordinatedShutdown.Get(ActorSystem).Run().Wait(TimeSpan.FromSeconds(2));
 }
예제 #16
0
 public async Task StopAsync()
 {
     await CoordinatedShutdown.Get(_actorSystem).Run();
 }
예제 #17
0
 public Task StopAsync(CancellationToken cancellationToken)
 {
     return(CoordinatedShutdown.Get(GlobalActorSystem)
            .Run(CoordinatedShutdown.ClrExitReason.Instance));
 }
 public async Task StopAsync()
 {
     await CoordinatedShutdown
     .Get(LighthouseSystem)
     .Run(CoordinatedShutdown.ClrExitReason.Instance);
 }
예제 #19
0
        static void Main(string[] args)
        {
            var numArgs = 2;

            if (args.Length < numArgs)
            {
                Log.Fatal("Cluster Bootstrapper does not have the correct number of arguments. Expected at least {ExpectedArguments} but received {NumberOfArguments}", numArgs, args.Length);
                var count = 1;
                foreach (var arg in args)
                {
                    Log.Information("Arg[{ArgumentIndex}]:{Argument}", count, arg);
                    Log.CloseAndFlush();
                }
                return;
            }

            var loggerFactory = new ElasticSearchLoggerFactory(new Uri("http://*****:*****@{hostname}:4053";

            // Create the system and actors
            var cfg = CommonConfigs.BasicConfig()                         // Supress JSON warning
                      .WithFallback(ClusterNodeConstants.DefaultConfig()) // With default actor props factory
                      .WithFallback(
                ClusterConfigs.CreateClusterConfig(
                    new DefaultClusterConfig(
                        hostname, 0,
                        seedNodes: new[] { seedNode },
                        roles: roles.Select(x => (Key: x, Value: 0)).ToDictionary(x => x.Key, x => x.Value)
                        )
                    )
                )
                      .WithFallback(CommonConfigs.CreateLoggingConfig(new SerilogConfig())); // Serilog logging

            var system       = ActorSystem.Create(systemName, cfg);
            var configurator = system.ActorOf(Props.Create(() => new NodeConfigurator()), "configurator");

            Console.CancelKeyPress += async(sender, eventArgs) =>
            {
                Console.WriteLine("Stopping Cluster Worker...");
                await CoordinatedShutdown.Get(system).Run();
            };

            // Waits until service is terminated and then exits the program
            system.WhenTerminated.Wait();

            logger.Information("Cluster Worker stopped");

            Log.CloseAndFlush();
        }
예제 #20
0
 public async Task StopAsync()
 {
     await CoordinatedShutdown.Get(_lighthouseSystem).Run();
 }
 public async Task StopAsync(CancellationToken cancellationToken)
 {
     // strictly speaking this may not be necessary - terminating the ActorSystem would also work
     // but this call guarantees that the shutdown of the cluster is graceful regardless
     await CoordinatedShutdown.Get(_clusterSystem).Run(CoordinatedShutdown.ClrExitReason.Instance);
 }
예제 #22
0
 private static void LeaveCluster()
 {
     Console.WriteLine("Leaving cluster");
     CoordinatedShutdown.Get(_clusterSystem).Run().Wait(TimeSpan.FromSeconds(60));
 }
예제 #23
0
 public async Task StopAsync()
 {
     await CoordinatedShutdown.Get(SystemActors.ClusterSystem).Run();
 }
예제 #24
0
 public Task Shutdown()
 {
     return(CoordinatedShutdown
            .Get(_system)
            .Run(CoordinatedShutdown.ClrExitReason.Instance));
 }
예제 #25
0
        private void DebugMode()
        {
            Receive <Command>(s => s == Command.Start, s =>
            {
                if (_InstructionStore.Count() == 0)
                //if (_CurrentInstructions == 0)
                {
                    _IsRunning    = true;
                    _nextInterupt = _nextInterupt + _SimulationConfig.InteruptInterval;
                    _SimulationConfig.Inbox.Receiver.Tell(SimulationState.Started);

                    Advance_Debug();
                }
                else
                {
                    // Not Ready Yet, Try Again
                    Context.Self.Tell(s);
                }
            });

            // Determine when The initialisation is Done.
            Receive <Command>(s => s == Command.IsReady, s =>
            {
                if (_InstructionStore.Count() == 0)
                //if (_CurrentInstructions == 0)
                {
                    Sender.Tell(Command.IsReady, ActorRefs.NoSender);
                }
                else
                {
                    // Not Ready Yet, Try Again
                    Context.Self.Forward(s);
                }
            });

            // Determine when The Simulation is Done.
            Receive <SimulationState>(s => s == SimulationState.Finished, s =>
            {
                if (_InstructionStore.Count() == 0)
                {
                    _SimulationConfig.Inbox.Receiver.Tell(SimulationState.Finished);
                    _IsComplete = true;
                }
                else
                {
                    // Not Ready Yet, Try Again
                    Context.Self.Forward(s);
                }
            });

            Receive <Done>(c =>
            {
                if (!_InstructionStore.Remove(((ISimulationMessage)c.Message).Key))
                {
                    throw new Exception("Failed to remove message from Instruction store");
                }
                System.Diagnostics.Debug.WriteLine("-- Done(" + _InstructionStore.Count() + ") ", "AKKA");
                Advance_Debug();
            });

            Receive <Command>(c => c == Command.Stop, c =>
            {
                // Console.WriteLine("-- Resume simulation -- !");
                System.Diagnostics.Debug.WriteLine("STOP", "AKKA");
                _IsRunning = false;
            });

            Receive <Shutdown>(c =>
            {
                if (_InstructionStore.Count() == 0 && _FeatureStore.Count() == 0)
                //if (_CurrentInstructions == 0 && _FeaturedInstructions.Count() == 0)
                {
                    System.Diagnostics.Debug.WriteLine("Simulation Finished...", "AKKA");
                    CoordinatedShutdown.Get(Context.System).Run();
                }
            });

            Receive <Schedule>(m =>
            {
                LogInterceptor(m.Message);
                var sheduleAt = m.Delay + TimePeriod;
                if (_FeatureStore.TryGetValue(sheduleAt, out Dictionary <Guid, ISimulationMessage> value))
                {
                    value.Add(m.Message.Key, m.Message);
                }
                else
                {
                    _FeatureStore.Add(sheduleAt, new Dictionary <Guid, ISimulationMessage> {
                        { m.Message.Key, m.Message }
                    });
                }

                m.Message.Target.Forward(m);
            });

            Receive <ISimulationMessage>(m =>
            {
                LogInterceptor(m);
                if (m.Target != ActorRefs.NoSender)
                {
                    m.Target.Forward(m);
                }
                else if (m.TargetSelection != null)
                {
                    m.TargetSelection.Tell(m);
                }
                else
                {
                    // ping back
                    Sender.Tell(m);
                }
                //_CurrentInstructions++;
                _InstructionStore.Add(m.Key, m);
                System.Diagnostics.Debug.WriteLine(" DO ++ (" + _InstructionStore.Count() + ")" + m.GetType().ToString(), "AKKA");
            });
        }
예제 #26
0
 public void Stop()
 {
     Log.Information("Shutting down");
     CoordinatedShutdown.Get(_system).Run().Wait(TimeSpan.FromSeconds(2));
 }
예제 #27
0
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            cluster.Leave(cluster.SelfAddress);

            return(CoordinatedShutdown.Get(actorSystem).Run(CoordinatedShutdown.ClrExitReason.Instance));
        }
예제 #28
0
 private void StopAsync()
 {
     CoordinatedShutdown.Get(_system).Run(CoordinatedShutdown.ClrExitReason.Instance).Wait();
 }
예제 #29
0
 public Task Stop() => CoordinatedShutdown.Get(ClusterSystem).Run();
예제 #30
0
 public Task StopAsync(CancellationToken cancellationToken)
 {
     return(CoordinatedShutdown.Get(_actors.Sys).Run(CoordinatedShutdown.ClrExitReason.Instance));
 }