public ConfigurationDistributor(IActorRef manager) { _manager = manager; _logger = Context.WithIdentity(GetType().Name); Receive <RegisterNode>(msg => { var path = CreateConfiguratorPath(msg.Address); if (!_nodeRoles.ContainsKey(path)) { if (msg.Roles.Any(x => x == null)) { _logger.Error("Register message for {ActorPath} has roles that are null:{ClusterRoles}", path, msg.Roles); return; } _logger.Info("Node:{ActorPath} with roles:{ClusterRoles} has been registered.", path, msg.Roles); _nodeRoles.Add(path, msg.Roles.ToHashSet()); foreach (var role in msg.Roles) { if (_roleNodes.ContainsKey(role)) { _roleNodes[role].Add(path); } else { _roleNodes[role] = new HashSet <string> { path }; } } } else { _logger.Info("{ClassName} already contains a node registered with name:{ActorPath}", nameof(ConfigurationDistributor), path); } }); Receive <UnregisterNode>(msg => { var path = CreateConfiguratorPath(msg.Address); if (_nodeRoles.ContainsKey(path)) { _logger.Info("Node:{ActorPath} with roles :{ClusterRoles} has been un-registered.", path, _nodeRoles[path].ToArray()); _nodeRoles.Remove(path); foreach (var nameSets in _roleNodes.Values) { if (nameSets.Contains(path)) { nameSets.Remove(path); } } } else { _logger.Info("{ClassName} does not contain a registered node with name:{ActorPath}", nameof(ConfigurationDistributor), path); } }); Receive <NodeUp>(msg => { var path = CreateConfiguratorPath(msg.Address); if (!_nodeRoles.ContainsKey(path)) { if (msg.Roles.Any(x => x == null)) { _logger.Error("Update message for {ActorPath} has roles that are null:{ClusterRoles}", path, msg.Roles); return; } _logger.Info("Node:{ActorPath} has been updated with roles:{ClusterRoles}.", path, msg.Roles); _nodeRoles.Add(path, msg.Roles.ToHashSet()); foreach (var nameSets in _roleNodes.Where(x => !msg.Roles.Contains(x.Key)).Select(x => x.Value)) { if (nameSets.Contains(path)) { nameSets.Remove(path); } } } else { _logger.Info("{ClassName} does not contain a node registered with name:{ActorPath}", nameof(ConfigurationDistributor), path); } }); Receive <ConfigureRole>(msg => { _logger.Error("Role was null in Configure Role Message. Roles:{ClusterRoles}", msg.Roles); // Get all distinct nodes that need configuring - i.e. don't configure twice unnecessarily var nonNullRoles = msg.Roles.Where(x => x != null).ToHashSet(); var nodes = _nodeRoles.Where(kvp => kvp.Value.Intersect(nonNullRoles).Any()).Select(kvp => kvp.Key); foreach (var node in nodes) { // Get the actor selection for the given node. var selection = Context.ActorSelection(node); // Check it exists by touching it. This also gives the actor ref which is preferred. try { selection.Tell(msg.RoleConfiguration); } catch (Exception ex) { _logger.Error(ex, "Could not touch Configurator actor at {ActorPath}.", node); continue; } } }); Receive <IConfirmation <IRoleConfiguration> >(msg => { if (_nodeRoles.ContainsKey(Sender.Path.ToStringWithAddress())) { _nodeRefs[Sender.Path.ToStringWithAddress()] = Sender; } }); }
private void SendGossip(Address address, MetricsGossipEnvelope envelope) { Context.ActorSelection(Self.Path.ToStringWithAddress(address)).Tell(envelope); }
/// <summary> /// TBD /// </summary> /// <param name="singletonManagerPath">TBD</param> /// <param name="settings">TBD</param> public ClusterSingletonProxy(string singletonManagerPath, ClusterSingletonProxySettings settings) { _settings = settings; _singletonPath = (singletonManagerPath + "/" + settings.SingletonName).Split('/'); _identityId = CreateIdentifyId(_identityCounter); Receive <ClusterEvent.CurrentClusterState>(s => HandleInitial(s)); Receive <ClusterEvent.MemberUp>(m => Add(m.Member)); Receive <ClusterEvent.MemberExited>(m => Remove(m.Member)); Receive <ClusterEvent.MemberRemoved>(m => { if (m.Member.UniqueAddress.Equals(_cluster.SelfUniqueAddress)) { Context.Stop(Self); } else { Remove(m.Member); } }); Receive <ClusterEvent.IMemberEvent>(m => { /* do nothing */ }); Receive <ActorIdentity>(identity => { if (identity.Subject != null) { // if the new singleton is defined, deliver all buffered messages var subject = identity.Subject; Log.Info("Singleton identified at [{0}]", subject.Path); _singleton = subject; Context.Watch(subject); CancelTimer(); SendBuffered(); } }); Receive <TryToIdentifySingleton>(_ => { var oldest = _membersByAge.FirstOrDefault(); if (oldest != null && _identityTimer != null) { var singletonAddress = new RootActorPath(oldest.Address) / _singletonPath; Log.Debug("Trying to identify singleton at [{0}]", singletonAddress); Context.ActorSelection(singletonAddress).Tell(new Identify(_identityId)); } }); Receive <Terminated>(terminated => { if (Equals(_singleton, terminated.ActorRef)) { // buffering mode, identification of new will start when old node is removed _singleton = null; } }); ReceiveAny(msg => { if (_singleton != null) { if (Log.IsDebugEnabled) { Log.Debug("Forwarding message of type [{0}] to current singleton instance at [{1}]", msg.GetType(), _singleton.Path); } _singleton.Forward(msg); } else { Buffer(msg); } }); }
protected override bool Receive(object message) { Context.ActorSelection(string.Format("akka.tcp://[email protected]:{0}/user/remote", _port)) .Tell(message, ActorRefs.NoSender); return(true); }
protected override ActorSelection Replica(Address address) => Context.ActorSelection(_probes[address].Path);
private ActorSelection Peer(Address at) { return(Context.ActorSelection(Self.Path.ToStringWithAddress(at))); }
/// <summary> /// Looks up and returns the remote cluster heartbeat connection for the specific address. /// </summary> private ActorSelection HeartbeatReceiver(Address address) { return(Context.ActorSelection(new RootActorPath(address) / "system" / "cluster" / "heartbeatReceiver")); }
protected override void PreStart() { /* Request a download tracker instance from the downloads master */ Context.ActorSelection("/user/downloads").Tell(new DownloadsMaster.RequestDownloadTrackerFor(Job, Self)); }
public Reminder(ReminderSettings settings) { this.UpdateState = e => { switch (e) { case Scheduled scheduled: this.state = state.AddEntry(scheduled.Entry); break; case Completed completed: this.state = state.RemoveEntry(completed.TaskId); break; } }; this.settings = settings; PersistenceId = settings.PersistenceId; JournalPluginId = settings.JournalPluginId; SnapshotPluginId = settings.SnapshotPluginId; tickTask = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(settings.TickInterval, settings.TickInterval, Self, Tick.Instance, ActorRefs.NoSender); Command <Tick>(_ => { var now = Context.System.Scheduler.Now.UtcDateTime; foreach (var schedule in state.Entries.Values.Where(e => ShouldTrigger(e, now))) { Log.Info("Sending message [{0}] to recipient [{1}]", schedule.Message, schedule.Recipient); var selection = Context.ActorSelection(schedule.Recipient); selection.Tell(schedule.Message, ActorRefs.NoSender); Emit(new Completed(schedule.TaskId, now), UpdateState); var next = schedule.WithNextTriggerDate(now); if (next != null) { Emit(new Scheduled(next), UpdateState); } } }); Command <Schedule>(schedule => { var sender = Sender; try { Emit(new Scheduled(schedule.WithoutAck()), e => { UpdateState(e); //NOTE: use `schedule`, not `e` - latter contains a version with ACK explicitly erased to avoid storing ack in persistent memory if (schedule.Ack != null) { sender.Tell(schedule.Ack); } }); } catch (Exception error) { Log.Error(error, "Failed to schedule: [{0}]", schedule); if (schedule.Ack != null) { sender.Tell(new Status.Failure(error)); } } }); Command <GetState>(_ => { Sender.Tell(state); }); Command <Cancel>(cancel => { var sender = Sender; try { Emit(new Completed(cancel.TaskId, DateTime.UtcNow), e => { UpdateState(e); if (cancel.Ack != null) { sender.Tell(cancel.Ack); } }); } catch (Exception error) { Log.Error(error, "Failed to cancel task: [{0}]", cancel.TaskId); if (cancel.Ack != null) { sender.Tell(new Status.Failure(error)); } } }); Command <SaveSnapshotSuccess>(success => { Log.Debug("Successfully saved reminder snapshot. Removing all events before seqNr [{0}]", success.Metadata.SequenceNr); DeleteMessages(success.Metadata.SequenceNr - 1); }); Command <SaveSnapshotFailure>(failure => { Log.Error(failure.Cause, "Failed to save reminder snapshot"); }); Recover <Scheduled>(UpdateState); Recover <Completed>(UpdateState); Recover <SnapshotOffer>(offer => { if (offer.Snapshot is State state) { this.state = state; } }); }
public bool Run(TTimeout job) { Context.ActorSelection(Context.Parent.Path.Parent.Parent).Tell(job); return(true); }
public ReutersItemActor() { List <ReutersItem> items = new List <ReutersItem>(); // Step 1 Receive <processReutersItem>(i => { var id = Helpers.GeneralHelper.IdHelper(i.item.Element("guid").Value); if (!idsProcessed.Contains(id)) { idsProcessed.Add(id); var d = i.item.Element("description").Value; d = d.DeEscape(); if (d.IndexOf("<") > 0) { var item = new ReutersItem() { id = id, partionKey = "Reuters", link = i.item.Element("link").Value, pubDate = DateTimeOffset.Parse(i.item.Element("pubDate").Value), title = i.item.Element("title").Value.DeEscape(), description = d.Substring(0, d.IndexOf("<") - 1), origXML = i.item.ToString(), siteSection = i.item.Element("category").Value }; items.Add(item); Program.stopActor.Tell(new NLPHelper.StopwordRequest() { id = item.id, linesOfText = new List <string>() { item.title, item.description } }); } else { Context.Parent.Tell(new processedReuters()); } } else { Context.Parent.Tell(new processedReuters()); } }); // Step 2 Receive <NLPHelper.StopwordResponse>(r => { var item = items.First(z => z.id == r.id); item.swTitle = r.outputStrings[0]; item.swDescription = r.outputStrings[1]; var n = new SharedMessages.SentimentRequest() { id = r.id, feed = "Reuters", linesToProcess = new List <string>() { item.title, item.description } }; var remote2 = Context.ActorSelection("akka.tcp://nlp-system@localhost:8080/user/sent"); var req2 = JsonConvert.SerializeObject(n); remote2.Tell(req2); }); // step 3 || step 4 Receive <string>(r => { if (r.StartsWith("sent:")) { var sent = JsonConvert.DeserializeObject <SharedMessages.SentimentResponse>(r.Substring(5)); var item = items.First(z => z.id == sent.id); item.sentTitle = sent.results[0]; item.sentiDescription = sent.results[1]; var req = new StemmingRequest() { id = item.id, linesOfText = new List <string>() { item.swTitle, item.swDescription, } }; Program.stemActor.Tell(req); } else if (r.StartsWith("ner:")) { var sent = JsonConvert.DeserializeObject <SharedMessages.NERResponse>(r.Substring(4)); var item = items.First(z => z.id == sent.id); item.nerTitle = sent.results[0]; item.nerDescription = sent.results[1]; Program.nerCountActor.Tell(sent); Program.stemActor.Tell(new NLPHelper.StemmingRequest() { id = item.id, linesOfText = new List <string>() { item.title, item.description } }); } }); // step 5 Receive <NLPHelper.StemmingResponse>(r => { var item = items.First(z => z.id == r.id); item.stemmedTitle = r.lines[0]; item.stemmedDescription = r.lines[1]; Self.Tell(new processedReuters() { id = r.id }); }); Receive <processedReuters>(r => { var item = items.First(z => z.id == r.id); items.Remove(item); Program.cdb.UpsertDocument(item, "newsfeed").Wait(); Console.WriteLine("=========> Reuters saving " + item.siteSection); Program.wordCountActor.Tell(new NLPHelper.CountRequest() { Feed = "Reuters", Id = item.id, LineOFtext = item.stemmedDescription }); Program.nerActor.Tell(new SharedMessages.NERRequest() { id = item.id, feed = "Reuters", linesToProcess = new List <string>() { item.title, item.description } }); Context.Parent.Tell(new processedReuters()); }); }
private void GossipTo(Address address) { var sel = Context.ActorSelection(Self.Path.ToStringWithAddress(address)); sel.Tell(new Status(versions: OwnVersions, isReplyToStatus: false)); }
private void _init() { _log.Debug("初始化{0}SecuritiesActor", securities.Symbol); persistenceActor = Context.ActorSelection(String.Format("/user/{0}", ConstantsHelper.AKKA_PATH_PERSISTENCE)); }
/// <summary> /// Send a dummy trans /// </summary> private void SendTUDSessionInfo() { var pkt = new byte[0]; FLMsgType.AddUInt32(ref pkt, 0xC2); // dwPacketType FLMsgType.AddUInt32(ref pkt, 0); // dwReplyOffset FLMsgType.AddUInt32(ref pkt, 0); // dwReplySize FLMsgType.AddUInt32(ref pkt, 0x50); // dwApplicationDescSize FLMsgType.AddUInt32(ref pkt, 0x01); // dwFlags var resp = _globals.Ask <Globals.ServerInfo>("GetInfo"); resp.Wait(5); var result = resp.Result; FLMsgType.AddUInt32(ref pkt, result.MaxPlayers + 1); // dwMaxPlayers FLMsgType.AddUInt32(ref pkt, (uint)result.CurrentPlayers + 1); // dwCurrentPlayers FLMsgType.AddUInt32(ref pkt, 0x6C + 0x60); // dwSessionNameOffset FLMsgType.AddUInt32(ref pkt, (uint)result.ServerName.Length * 2); // dwSessionNameSize FLMsgType.AddUInt32(ref pkt, 0); // dwPasswordOffset FLMsgType.AddUInt32(ref pkt, 0); // dwPasswordSize FLMsgType.AddUInt32(ref pkt, 0); // dwReservedDataOffset FLMsgType.AddUInt32(ref pkt, 0); // dwReservedDataSize FLMsgType.AddUInt32(ref pkt, 0); // dwApplicationReservedDataOffset FLMsgType.AddUInt32(ref pkt, 0); // dwApplicationReservedDataSize FLMsgType.AddArray(ref pkt, result.InstanceGUID); FLMsgType.AddArray(ref pkt, result.AppGUID); FLMsgType.AddUInt32(ref pkt, _dPlayID); // dpnid FLMsgType.AddUInt32(ref pkt, _dPlayID); // dwVersion FLMsgType.AddUInt32(ref pkt, 0); // dwVersionNotUsed FLMsgType.AddUInt32(ref pkt, 2); // dwEntryCount FLMsgType.AddUInt32(ref pkt, 0); // dwMembershipCount // server name table entry FLMsgType.AddUInt32(ref pkt, 1); // dpnid FLMsgType.AddUInt32(ref pkt, 0); // dpnidOwner FLMsgType.AddUInt32(ref pkt, 0x000402); // dwFlags FLMsgType.AddUInt32(ref pkt, 2); // dwVersion FLMsgType.AddUInt32(ref pkt, 0); // dwVersionNotUsed FLMsgType.AddUInt32(ref pkt, 7); // dwDNETVersion FLMsgType.AddUInt32(ref pkt, 0); // dwNameOffset FLMsgType.AddUInt32(ref pkt, 0); // dwNameSize FLMsgType.AddUInt32(ref pkt, 0); // dwDataOffset FLMsgType.AddUInt32(ref pkt, 0); // dwDataSize FLMsgType.AddUInt32(ref pkt, 0); // dwURLOffset FLMsgType.AddUInt32(ref pkt, 0); // dwURLSize // connecting client name table entry FLMsgType.AddUInt32(ref pkt, _dPlayID); // dpnid FLMsgType.AddUInt32(ref pkt, 0); // dpnidOwner FLMsgType.AddUInt32(ref pkt, 0x020000); // dwFlags FLMsgType.AddUInt32(ref pkt, _dPlayID); // dwVersion FLMsgType.AddUInt32(ref pkt, 0); // dwVersionNotUsed FLMsgType.AddUInt32(ref pkt, 7); // dwDNETVersion FLMsgType.AddUInt32(ref pkt, 0); // dwNameOffset FLMsgType.AddUInt32(ref pkt, 0); // dwNameSize FLMsgType.AddUInt32(ref pkt, 0); // dwDataOffset FLMsgType.AddUInt32(ref pkt, 0); // dwDataSize FLMsgType.AddUInt32(ref pkt, 0); // dwURLOffset FLMsgType.AddUInt32(ref pkt, 0); // dwURLSize FLMsgType.AddUnicodeStringLen0(ref pkt, result.ServerName); Context.ActorSelection("../congestion").Tell(pkt); //UserData.AddLast(pkt); //SendDFrame(sess); }
private void DestroySession(DestroySession destroySession) { IActorRef sessionActor = Context.ActorSelection(SalesOrderActorRefs.SessionCollection).ResolveOne(TimeSpan.FromSeconds(10)).Result; sessionActor.Tell(destroySession); }
private ActorSelection ActorForAddress(Address address) { address = address.WithProtocol(_cluster.SelfAddress.Protocol); return(Context.ActorSelection($"{address}/user/{Self.Path.Name}")); }