protected DiscoveryService(ClusterDiscoverySettings settings)
        {
            this.Cluster  = Cluster.Get(Context.System);
            this.Log      = Context.GetLogger();
            this.settings = settings;
            this.Entry    = new MemberEntry(Context.System.Name, Cluster.SelfAddress, Cluster.SelfRoles);

            var retries = settings.JoinRetries;

            ReceiveAsync <Join>(async _ =>
            {
                retries--;
                try
                {
                    var joined = await TryJoinAsync();
                    if (!joined)
                    {
                        SendJoinSignal();
                    }
                }
                catch (Exception cause)
                {
                    if (retries > 0)
                    {
                        SendJoinSignal();
                    }
                    else
                    {
                        Log.Error(cause, "Failed to obtain a distributed lock for actor system [{0}] after {1} retries. Closing.", Context.System.Name, retries);
                        Context.Stop(Self);
                    }
                }
            });
        }
Beispiel #2
0
 // Become State
 // When we start up we need to reset any jobs that this member was running.
 private void Startup()
 {
     ReceiveAny(task =>
     {
         _logger.Error(" [x] Oh Snap! Unhandled message: \r\n{0}", task);
     });
 }
            public ChaosDestination(IActorRef probe)
            {
                Probe               = probe;
                State               = new List <int>();
                _config             = Context.System.Settings.Config.GetConfig("akka.persistence.destination.chaos");
                _confirmFailureRate = _config.GetDouble("confirm-failure-rate");

                Receive <Msg>(m =>
                {
                    if (ChaosSupportExtensions.ShouldFail(_confirmFailureRate))
                    {
                        Log.Error(string.Format("[destination] confirm message failed (message = {0}, {1})", m.DeliveryId, m.I));
                    }
                    else if (State.Contains(m.I))
                    {
                        Log.Debug(string.Format("[destination] ignored duplicate (message = {0}, {1})", m.DeliveryId, m.I));
                        Sender.Tell(new Confirm(m.DeliveryId, m.I));
                    }
                    else
                    {
                        this.Add(m.I);
                        Sender.Tell(new Confirm(m.DeliveryId, m.I));
                        Log.Debug(string.Format("[destination] received and confirmed (message = {0}, {1})", m.DeliveryId, m.I));
                    }
                });
            }
        private void Clear()
        {
            try
            {
                MessageIdPartitionMap.Clear();
                foreach (var t in TimePartitions)
                {
                    t.Clear();
                }
            }

            catch (Exception ex)
            {
                _log.Error(ex.ToString());
            }
        }
        /// <summary>
        /// INTERNAL API
        ///
        /// Should only be called directly by the <see cref="AppDomain.ProcessExit"/> event
        /// in production.
        ///
        /// Safe to call multiple times, but hooks will only be run once.
        /// </summary>
        /// <returns>Returns a <see cref="Task"/> that will be completed once the process exits.</returns>
        private Task <Done> RunClrHooks()
        {
            if (_clrHooksStarted.CompareAndSet(false, true))
            {
                Task.WhenAll(_clrShutdownTasks.Select(hook =>
                {
                    try
                    {
                        var t = hook();
                        return(t);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Error occurred while executing CLR shutdown hook");
                        return(TaskEx.FromException <Done>(ex));
                    }
                })).ContinueWith(tr =>
                {
                    if (tr.IsFaulted || tr.IsCanceled)
                    {
                        _hooksRunPromise.SetException(tr.Exception.Flatten());
                    }
                    else
                    {
                        _hooksRunPromise.SetResult(Done.Instance);
                    }
                });
            }

            return(ClrShutdownTask);
        }
 protected override void PostRestart(Exception reason)
 {
     base.PostRestart(reason);
     ActorsSystem.Add(Alias, Self);
     logger.Error(string.Format("Actor PostRestart:{0} - {1}", reason.ToString(), GetType()));
     //ActorInitialize();
 }
Beispiel #7
0
        private void Handle(int info)
        {
            try
            {
                _log.Info($"{Context.Self.Path} Recieved {info}");
                if (info % 2 == 0)
                {
                    _log.Info("even");
                    Thread.Sleep(TimeSpan.FromSeconds(3));
                    _log.Info($"{Context.Self.Path} done");
                }
                else
                {
                    _log.Info("odd");
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    throw new Exception("Invalid data");
                }

                _log.Info("*************************************");
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                throw;
            }
        }
Beispiel #8
0
        protected override void LogTermination(Reason reason)
        {
            var failure = reason as Failure;

            if (failure != null)
            {
                failure.Cause.Match()
                .With <DisassociateInfo>(() => { })    //no logging
                .With <ForbiddenUidReason>(() => { })  //no logging
                .With <TimeoutReason>(timeoutReason => _log.Error(timeoutReason.ErrorMessage));
            }
            else
            {
                base.LogTermination(reason);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Default behaviour of the configurator
        ///
        /// Receives an <see cref="IRoleConfiguration"/> and creates children from the
        /// <see cref="IPluginConfiguration"/> list supplied
        /// </summary>
        private void DefaultBehaviour()
        {
            Receive <IRoleConfiguration>(msg =>
            {
                msg.Confirm(Sender);
                if (msg.Configs.Select(x => x.Name).Distinct().Count() != msg.Configs.Length)
                {
                    var ex = new ArgumentException("Configuration names are not distinct.");
                    _logger.Error(ex, "Configuration names are not distinct:{ConfigurationNames}", msg.Configs.Select(x => x.Name).ToArray());
                    throw ex;
                }

                foreach (var cfg in msg.Configs)
                {
                    var actor = CreateChildIfNotExist(cfg);
                    actor.Tell(cfg, Sender);
                }
            });

            Receive <INodeCommand>(msg =>
            {
                msg.Confirm(Sender);
                HandleCommand(msg);
            });

            Receive <IPluginCommand>(msg =>
            {
                msg.Confirm(Sender);
                HandlePluginCommand(msg);
            });

            Receive <IConfirmable>(msg => msg.Confirm(Sender));
        }
        private void WaitingToWork()
        {
            Receive <ProcessLine>(record =>
            {
                LogToEverything(Context, $"{record.UserName} : Privilege process is starting.");
                _currentRecord = record.UserName;
                Become(Working);

                ProcessIdentity();
            });

            ReceiveAny(task =>
            {
                _logger.Error(" [x] Oh Snap! Unhandled message: \r\n{0}", task);
            });
        }
Beispiel #11
0
        public void Ready()
        {
            Receive <DeadLetter>(ic =>
            {
                var message = ic.Message;

                if (message.GetType().Name == "DeathWatchNotification")
                {
                    Context.IncrementCounter("DeathWatchNotification");
                }
                else if (message.GetType().Name == "Terminate")
                {
                    Context.IncrementCounter("Terminate");
                }
                else
                {
                    Context.IncrementCounter("DeadLetter");
                    _logger.Warning("DeadLetter:{0}:{1}:{2}", ic.Message, ic.Sender?.Path.ToSerializationFormat(), ic.Recipient.Path.ToSerializationFormat());
                }
            });

            ReceiveAny(task =>
            {
                _logger.Error(" [x] Oh Snap! JobTasker.Ready.ReceiveAny: \r\n{0}", task);
            });
        }
Beispiel #12
0
        public DistributedActorTableContainer(string name, IActorRef clusterActorDiscovery,
                                              Type actorFactoryType, object[] actorFactoryInitalizeArgs,
                                              object downMessage = null)
        {
            _name = name;
            _clusterActorDiscovery = clusterActorDiscovery;
            _downMessage           = downMessage;
            _log = Context.GetLogger();

            if (actorFactoryType != null)
            {
                try
                {
                    _actorFactory = (IActorFactory)Activator.CreateInstance(actorFactoryType);
                    _actorFactory.Initialize(actorFactoryInitalizeArgs);
                }
                catch (Exception e)
                {
                    _log.Error(e, $"Exception in initializing ${actorFactoryType.FullName}");
                    _actorFactory = null;
                }
            }

            Receive <ClusterActorDiscoveryMessage.ActorUp>(m => Handle(m));
            Receive <ClusterActorDiscoveryMessage.ActorDown>(m => Handle(m));

            Receive <DistributedActorTableMessage <TKey> .Add>(m => Handle(m));
            Receive <DistributedActorTableMessage <TKey> .Remove>(m => Handle(m));

            Receive <DistributedActorTableMessage <TKey> .Internal.Create>(m => Handle(m));
            Receive <DistributedActorTableMessage <TKey> .Internal.AddReply>(m => Handle(m));
            Receive <DistributedActorTableMessage <TKey> .Internal.GracefulStop>(m => Handle(m));

            Receive <Terminated>(m => Handle(m));
        }
Beispiel #13
0
 protected override void OnRecoveryFailure(Exception reason, object message = null)
 {
     _log.Error(reason, "Failed to Recover");
     _probe.Tell(
         new AkkaPersistenceLivenessProbe.RecoveryStatus(_recoveredJournal, _recoveredSnapshotStore));
     throw new ApplicationException("Failed to recover", reason);
 }
        private async Task ReconcileClusterStateAsync()
        {
            ImmutableHashSet <Address> provided;

            try
            {
                provided = (await GetAliveNodesAsync()).ToImmutableHashSet();
            }
            catch (Exception e)
            {
                Log.Error(e, "Couldn't retrieve collection of nodes from external service. Is current node unreachable? Shutting down...");
                Cluster.Down(Cluster.SelfAddress);
                return;
            }

            var current = Cluster.State.Members.Union(Cluster.State.Unreachable).Select(m => m.Address).ToImmutableHashSet();

            if (!provided.SetEquals(current))
            {
                if (Log.IsInfoEnabled)
                {
                    Log.Info("Detected difference between set of nodes received from the discovery service [{0}] and the one provided by the cluster [{1}]",
                             string.Join(", ", provided), string.Join(", ", current));
                }

                // down all nodes not confirmed by service discovery provider
                foreach (var node in current.Except(provided))
                {
                    Cluster.Down(node);
                }
            }
        }
Beispiel #15
0
        protected override void PreRestart(Exception reason, object message)
        {
            UpdateCharacterMessage characterMessage = message as UpdateCharacterMessage;

            _logger.Error(reason, "Error processing character @CharacterID", characterMessage.CharacterID);
            base.PreRestart(reason, message);
        }
Beispiel #16
0
        public override async Task <Tuple <Address, TaskCompletionSource <IAssociationEventListener> > > Listen()
        {
            EndPoint  listenAddress;
            IPAddress ip;

            if (IPAddress.TryParse(Settings.Hostname, out ip))
            {
                listenAddress = new IPEndPoint(ip, Settings.Port);
            }
            else
            {
                listenAddress = new DnsEndPoint(Settings.Hostname, Settings.Port);
            }

            try
            {
                var newServerChannel = await NewServer(listenAddress).ConfigureAwait(false);

                // Block reads until a handler actor is registered
                // no incoming connections will be accepted until this value is reset
                // it's possible that the first incoming association might come in though
                newServerChannel.Configuration.AutoRead = false;
                ConnectionGroup.TryAdd(newServerChannel);
                ServerChannel = newServerChannel;

                var addr = MapSocketToAddress(
                    socketAddress: (IPEndPoint)newServerChannel.LocalAddress,
                    schemeIdentifier: SchemeIdentifier,
                    systemName: System.Name,
                    hostName: Settings.PublicHostname);

                if (addr == null)
                {
                    throw new ConfigurationException($"Unknown local address type {newServerChannel.LocalAddress}");
                }

                LocalAddress = addr;
                // resume accepting incoming connections
#pragma warning disable 4014 // we WANT this task to run without waiting
                AssociationListenerPromise.Task.ContinueWith(result => newServerChannel.Configuration.AutoRead = true,
                                                             TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion);
#pragma warning restore 4014


                return(Tuple.Create(addr, AssociationListenerPromise));
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to bind to {0}; shutting down DotNetty transport.", listenAddress);
                try
                {
                    await Shutdown().ConfigureAwait(false);
                }
                catch
                {
                    // ignore errors occurring during shutdown
                }
                throw;
            }
        }
Beispiel #17
0
        private async Task ReconcileClusterStateAsync()
        {
            ImmutableHashSet <Address> provided;

            try
            {
                // try to get all nodes during reconciliation. It's acceptable to get unhealthy nodes
                // if they didn't hit alive-timeout, as provdider service is expected to deregister
                // nodes past that threshold - they won't appear here
                provided = (await GetNodesAsync(onlyAlive: false)).ToImmutableHashSet();
            }
            catch (Exception e)
            {
                Log.Error(e, "Couldn't retrieve collection of nodes from external service. Is current node unreachable? Shutting down...");
                Cluster.Down(Cluster.SelfAddress);
                return;
            }

            var current = Cluster.State.Members.Union(Cluster.State.Unreachable).Select(m => m.Address).ToImmutableHashSet();

            if (!provided.SetEquals(current))
            {
                if (Log.IsWarningEnabled)
                {
                    Log.Warning("Detected difference between set of nodes received from the discovery service [{0}] and the one provided by the cluster [{1}]. Downing nodes not present in discovery service.",
                                string.Join(", ", provided), string.Join(", ", current));
                }

                // down all nodes not confirmed by service discovery provider
                foreach (var node in current.Except(provided))
                {
                    Cluster.Down(node);
                }
            }
        }
Beispiel #18
0
        protected override SupervisorStrategy SupervisorStrategy()
        {
            var decider = new LocalOnlyDecider(ex =>
            {
                switch (ex)
                {
                case AgentFailureException:
                case ActorInitializationException:
                    _logger.Info("Agent {0} with id {1} failed with exception {2}", _script.Name, _script.Id, ex);
                    Self.Tell(new AgentFailureState(ex));
                    return(Directive.Stop);

                case AgentMethodInvocationException:
                    _methodCallsFailureCounter.Increment();

                    if (!_methodCallsFailureCounter.Exceeded)
                    {
                        return(Directive.Resume);
                    }

                    Self.Tell(new AgentFailureState(ex));
                    return(Directive.Stop);

                default:
                    _logger.Error("Unhandled exception thrown thrown within game agent: {0}", ex);
                    return(Directive.Escalate);
                }
            });

            return(new AllForOneStrategy(-1, -1, decider, false));
        }
        public EventStoreJournal()
        {
            _log       = Context.GetLogger();
            _extension = EventStorePersistence.Instance.Apply(Context.System);

            _serializerSettings = new JsonSerializerSettings
            {
                TypeNameHandling       = TypeNameHandling.Objects,
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                Formatting             = Formatting.Indented,
                Converters             =
                {
                    new ActorRefConverter(Context)
                }
            };

            _connection = new Lazy <Task <IEventStoreConnection> >(async() =>
            {
                try
                {
                    IEventStoreConnection connection = EventStoreConnection.Create(_extension.EventStoreJournalSettings.ConnectionString, _extension.EventStoreJournalSettings.ConnectionName);
                    await connection.ConnectAsync();
                    return(connection);
                }
                catch (Exception exc)
                {
                    _log.Error(exc.ToString());
                    return(null);
                }
            });
        }
Beispiel #20
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="tcp">TBD</param>
        /// <param name="bindCommander">TBD</param>
        /// <param name="bind">TBD</param>
        public TcpListener(TcpExt tcp, IActorRef bindCommander,
                           Tcp.Bind bind)
        {
            _tcp           = tcp;
            _bindCommander = bindCommander;
            _bind          = bind;

            Context.Watch(bind.Handler);

            _socket = new Socket(_bind.LocalAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            {
                Blocking = false
            };

            _acceptLimit = bind.PullMode ? 0 : _tcp.Settings.BatchAcceptLimit;

            try
            {
                bind.Options.ForEach(x => x.BeforeServerSocketBind(_socket));
                _socket.Bind(bind.LocalAddress);
                _socket.Listen(bind.Backlog);
                _saeas = Accept(_acceptLimit).ToArray();
            }
            catch (Exception e)
            {
                _bindCommander.Tell(bind.FailureMessage);
                _log.Error(e, "Bind failed for TCP channel on endpoint [{0}]", bind.LocalAddress);
                Context.Stop(Self);
            }

            bindCommander.Tell(new Tcp.Bound(_socket.LocalEndPoint));
        }
Beispiel #21
0
        protected void _init()
        {
            _log.Info("加载{0}策略的仓位信息", Desc.Id);
            try {
                String path = String.Format("/user/{0}", ConstantsHelper.AKKA_PATH_PERSISTENCE);
                persistenceActor = Context.ActorSelection(path);
                PersistenceRequest req = new PersistenceRequest()
                {
                    Type = PersistenceType.FIND, Body = String.Format("from EStrategy where Id={0}", Desc.Id)
                };
                var ret = persistenceActor.Ask <EStrategy>(req, TimeSpan.FromSeconds(10));
                ret.Wait();
                Desc = ret.Result;
            } catch (Exception e)
            {
                _log.Error("发生异常 {0}", e.StackTrace);
                showLog(String.Format("必须重新启动,策略{0}加载超时", Desc.Id));
            }

            _log.Info("{0}策略连接交易接口", Desc.Id);
            if (Desc.Trader != null)
            {
                String tpath = String.Format("/user/{0}/{1}", ConstantsHelper.AKKA_PATH_TRADER, Desc.Trader.Id);
                tradeActor = Context.ActorSelection(tpath);
            }
            else
            {
                // 默认的trade actor is /user/trader/ths
                // tradeActor = Context.ActorSelection("/user/trader");
            }

            onInit();
        }
        public EventStoreJournal()
        {
            _log = Context.GetLogger();
            _extension = EventStorePersistence.Instance.Apply(Context.System);

            _serializerSettings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Objects,
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                Formatting = Formatting.Indented,
                Converters =
                {
                    new ActorRefConverter(Context)
                }
            };

            _connection = new Lazy<Task<IEventStoreConnection>>(async () =>
            {
                try
                {
                    IEventStoreConnection connection = EventStoreConnection.Create(_extension.EventStoreJournalSettings.ConnectionString, _extension.EventStoreJournalSettings.ConnectionName);
                    await connection.ConnectAsync();
                    return connection;
                }
                catch(Exception exc)
                {
                    _log.Error(exc.ToString());
                    return null;
                }
            });
        }
Beispiel #23
0
        protected override void OnReceive(object message)
        {
            log.Debug("Received message {0}", message);

            if (message is Progress)
            {
                var progress = (Progress)message;

                log.Info("Current progress: {0:N}%", progress.Percent);

                if (progress.Percent >= 100)
                {
                    log.Info("That's all, shutting down");
                    Context.System.Terminate();
                }
            }
            else if (message == ReceiveTimeout.Instance)
            {
                // No progress within 15 seconds, ServiceUnavailable
                log.Error("Shutting down due to unavailable service");
                Context.System.Terminate();
            }
            else
            {
                Unhandled(message);
            }
        }
Beispiel #24
0
        private SelectedSnapshot Load(ImmutableArray <SnapshotMetadata> metadata)
        {
            var last = metadata.LastOrDefault();

            if (last == null)
            {
                return(null);
            }
            else
            {
                try
                {
                    return(WithInputStream(last, stream =>
                    {
                        var snapshot = Deserialize(stream);

                        return new SelectedSnapshot(last, snapshot.Data);
                    }));
                }
                catch (Exception ex)
                {
                    var remaining = metadata.RemoveAt(metadata.Length - 1);
                    _log.Error(ex, $"Error loading snapshot [{last}], remaining attempts: [{remaining.Length}]");
                    if (remaining.IsEmpty)
                    {
                        throw;
                    }
                    else
                    {
                        return(Load(remaining));
                    }
                }
            }
        }
Beispiel #25
0
        /// <summary>
        /// By default, <see cref="Failure"/> is logged at error level and other
        /// reason types are not logged. It is possible to override this behavior.
        /// </summary>
        /// <param name="reason">TBD</param>
        protected virtual void LogTermination(Reason reason)
        {
            var failure = reason as Failure;

            if (failure != null)
            {
                if (failure.Cause is Exception)
                {
                    _log.Error(failure.Cause.AsInstanceOf <Exception>(), "terminating due to Failure");
                }
                else
                {
                    _log.Error(failure.Cause.ToString());
                }
            }
        }
Beispiel #26
0
 protected override void PostRestart(Exception reason)
 {
     base.PostRestart(reason);
     ActorsSystem.Add(Alias, Self);
     logger.Error($"Actor PostRestart:{reason} - {GetType()}");
     //ActorInitialize();
 }
Beispiel #27
0
        protected override void OnReceive(object message)
        {
            switch (message)
            {
            case RegisterDownloader registerMessage when StringComparer.OrdinalIgnoreCase.Equals(registerMessage.SystemId, SystemId):
                if (_downloaderActors.TryGetValue(registerMessage.DownloaderId, out var actor))
                {
                    _log.Info($"Downloader with id '{registerMessage.DownloaderId}' found.");
                }

                else
                {
                    _log.Info($"Downloader with id '{registerMessage.DownloaderId}' not found. Creating new actor...");
                    var deviceActor = Context.ActorOf(Downloader.Props(registerMessage.SystemId, registerMessage.DownloaderId), $"downloader-{registerMessage.DownloaderId}");
                    _downloaderActors.Add(registerMessage.DownloaderId, deviceActor);
                }
                break;

            case RegisterDownloader registerMessage:
                _log.Info($"Ignoring {nameof(RegisterDownloader)} message for system '{registerMessage.SystemId}' not found. This supervisor is responsible for {SystemId}.");
                break;

            case DownloadRun downloadMessage when StringComparer.OrdinalIgnoreCase.Equals(downloadMessage.SystemId, SystemId):
                // TODO: meaningful message routing...
                var downloaderId = _downloaderActors.Keys.FirstOrDefault();

                if (downloaderId != null)
                {
                    _log.Info($"Downloader with id '{downloaderId}' found. Forwarding download message...");
                    _downloaderActors
                    .GetValueOrDefault(downloaderId)
                    .Forward(downloadMessage);
                }
                else
                {
                    _log.Info($"Ignoring {nameof(DownloadRun)} message because no downloader instances have been registered for system {SystemId}.");
                }
                break;

            case DownloadRun downloadMessage:
                _log.Info($"Ignoring {nameof(DownloadRun)} message for system '{downloadMessage.SystemId}' not found. This supervisor is responsible for {SystemId}.");
                break;

            case DownloadResponse downloadResponse when StringComparer.OrdinalIgnoreCase.Equals(downloadResponse.SystemId, SystemId):
                if (downloadResponse.IsSuccessful)
                {
                    _log.Info($"Run {downloadResponse.RunId} successfully downloaded to system {downloadResponse.SystemId}.");
                }

                else
                {
                    _log.Error($"Failed to download run {downloadResponse.RunId} to system {downloadResponse.SystemId}.");
                }
                break;

            case DownloadResponse downloadResponse:
                _log.Info($"Ignoring {nameof(DownloadResponse)} message for system '{downloadResponse.SystemId}' not found. This supervisor is responsible for {SystemId}.");
                break;
            }
        }
Beispiel #28
0
        private void Ready()
        {
            Receive <StartProcessCommand>(cmd =>
            {
                logger.Info($"Creating process with Id: {cmd.Id}.");
                if (processes.ContainsKey(cmd.Id))
                {
                    logger.Error($"Process exists with Id: {cmd.Id}.");
                    return;
                }

                var process = processFactory.Create(Context, Akka.Actor.SupervisorStrategy.StoppingStrategy);
                Context.Watch(process);
                processes.Add(cmd.Id, process);
                logger.Info($"Created process with Id: {cmd.Id}.");
                process.Forward(cmd);
            });

            Receive <DomainEvent>(evnt =>
            {
                if (!processes.ContainsKey(evnt.Id))
                {
                    logger.Error($"Could not delagate event to process with Id: {evnt.Id}.");
                    return;
                }
                logger.Info($"Delegating event to process with Id: {evnt.Id}.");
                processes[evnt.Id].Tell(evnt);
            });

            Receive <Terminated>(msg =>
            {
                logger.Info("Removing process.");

                Guid key = (from actorRef in processes
                            where Equals(actorRef.Value, msg.ActorRef)
                            select actorRef.Key).DefaultIfEmpty(Guid.Empty).FirstOrDefault();

                if (key == Guid.Empty)
                {
                    logger.Warning("Could not remove process.");
                    return;
                }

                logger.Info($"Removing process with Id: {key}.");
                processes.Remove(key);
            });
        }
Beispiel #29
0
        private void Registering()
        {
            _logger.Info("Is registering.");
            _logger.Info("Waiting for Registry Supervisor.");

            Receive <SupervisorRegistryReady>(e => {
                _SupervisorRegistry = e.RegistrySupervisorActorRef;
                AttemptSupervisorRegistrationHelper(); // now that we have the Supervisor Registry IActorRef
            });

            // If supervisor registered successfully...
            Receive <SupervisorRegistrationEvent>(e =>
            {
                if (e.Registered)
                {
                    // Once all client actors have been instantiated and we have registered with the supervisor register we are good to go
                    _logger.Info("Registered");
                    Become(Initializing);
                }
                else
                {
                    _logger.Error("Supervisor '{0}' failed to register. Something went really wrong - killing supervisor.", Self.Path.ToStringWithAddress());
                    // Retry the registration again
                    AttemptSupervisorRegistrationHelper();
                }
            });

            // If the registration process failed...
            Receive <RegisterSupervisorTimeout>(e => {
                // Try it again _RegistrationRetryTimes then give up
                if ((_RegistrationRetryTimes--) == 0)
                {
                    _logger.Error("Supervisor '{0}' registration took too long timing out. {1} retries left - killing supervisor.", Self.Path.ToStringWithAddress(), _RegistrationRetryTimes);
                    Context.Stop(Self);
                }
                _logger.Warning("Supervisor '{0}' registration took too long timing out. {1} retries left", Self.Path.ToStringWithAddress(), _RegistrationRetryTimes);

                AttemptSupervisorRegistrationHelper();
            });

            // This catch all will log if there are any weird unhandled messages.
            Receive <object>(o =>
            {
                Stash?.Stash();
                _logger.Debug("Received unhandled message from:{0} Unhandled Message:{1} - Stashing.", Sender.Path.ToStringWithAddress(), o.GetType().Name);
            });
        }
 public AccountBusinessRulesMapper()
 {
     Receive <BootUp>(cmd => DoBootUp(cmd));
     Receive <FetchAccountBusinessRules>(cmd => GetAccountBusinessRulesForCommand(cmd));
     Receive <GetCommandsToBusinesRules>(cmd => GetCommandsToBusinesRules());
     Receive <UpdateAccountBusinessRules>(cmd => UpdateAccountBusinessRules(cmd.UpdatedRules));
     ReceiveAny(msg =>
                _logger.Error($"[ReceiveAny]: Unhandled message in {Self.Path.Name}. Message:{msg.ToString()}"));
 }
        private void Ready()
        {
            Receive <WorkerCoordinator.GetJobData>(process =>
            {
                var self = Self; // closure

                Task.Run(() =>
                {
                    // ... work
                    _logger.Info("Get Items");

                    List <Item> items = new List <Item>();

                    try
                    {
                        var rnd = new Random().Next(-250, 250);
                        for (int i = 0; i < rnd; i++)
                        {
                            items.Add(new Item(i));
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(ex, "GetItems");
                    }

                    return(items);
                }, _cancel.Token).ContinueWith(x =>
                {
                    if (x.IsCanceled || x.IsFaulted)
                    {
                        return(new Finished(null, x.Exception));
                    }

                    return(new Finished(x.Result, null));
                }, TaskContinuationOptions.AttachedToParent & TaskContinuationOptions.ExecuteSynchronously)
                .PipeTo(self);

                // switch behavior
                Become(Working);
            });

            ReceiveAny(task =>
            {
                _logger.Error(" [x] Oh Snap! GetItemData.Ready.ReceiveAny: \r\n{0}", task);
            });
        }