public void Send(PollNode sender, byte[] bytes, Direction dir) { PollNode next; if (dir == Direction.FromInitiator) { if (nodes.Find(sender) == null || nodes.Find(sender).Next == null) { return; } next = nodes.Find(sender).Next.Value; } else { if (nodes.Find(sender) == null || nodes.Find(sender).Previous == null) { return; } next = nodes.Find(sender).Previous.Value; } if (subscribers.ContainsKey(next)) { subscribers[next](bytes, dir); } else { } }
/// <summary> /// незалоченный путь /// /// </summary> public bool HasPathFreeForFinal(PollNode final, out string reason) { var path = paths.FirstOrDefault(p => p.LastOrDefault().Node == final); if (path == null) { reason = "путь обнулён"; return(false); } if (!path.Any()) { reason = "не найдены пути для финала"; return(false); } foreach (var node in path.Select(n => n.Node)) { if (node.IsLocked()) { reason = string.Format("нод [{0}] залочен", node.ToString()); return(false); } } reason = ""; return(true); }
public bool HasTaskForStarter(PollNode starter) { lock (initiators) { return(initiators.ContainsKey(starter) && initiators[starter].Count > 0); } }
public bool HasTaskForFinal(PollNode final) { lock (executers) { return(executers.ContainsKey(final) && executers[final].Count > 0); } }
public PollTask GetTaskForFinal(PollNode final) { IEnumerable <PollTask> tasks = null; lock (executers) { if (!executers.ContainsKey(final) || executers[final].Count == 0) { logger.Debug(string.Format("для {0} НЕ содержится задач", final)); return(null); } tasks = executers[final].ToArray(); } foreach (var task in tasks.OrderByDescending(p => p.Priority)) { string reason; if (!task.HasPathFreeForFinal(final, out reason)) { logger.Debug(string.Format("нет пути у таска для финала [{0}], причина: {1}", final, reason)); continue; } if (!task.Lock()) { logger.Debug("таск залочен"); continue; } logger.Debug(string.Format("для {0} есть таск {1}", final, task)); return(task); } return(null); }
private static NodeStatusViewModel GetNodeStatusViewModel(PollNode node, bool?includeData = false) { return(new NodeStatusViewModel { NodeType = node.NodeType, UniqueKey = node.UniqueKey, LastPoll = node.LastPoll, LastPollDuration = node.LastPollDuration, MinSecondsBetweenPolls = node.MinSecondsBetweenPolls, PollTaskStatus = node.PollTaskStatus, PollerCount = node.DataCaches.Count(), DataCaches = node.DataCaches.Select(dataCache => new NodeDataCacheViewModel { Name = dataCache.ParentMemberName, Type = dataCache.CachedDataType, UniqueId = dataCache.UniqueId, LastPoll = dataCache.LastRefresh, LastPollDuration = dataCache.LastRefreshDuration, LastPollStatus = dataCache.LastRefreshStatus, LastSuccess = dataCache.LastRefreshSuccess, NextPoll = dataCache.CacheExpiration, PollsSuccessful = dataCache.RefreshCountSuccessful, PollsTotal = dataCache.RefreshCountTotal, CacheFailureForSeconds = dataCache.CacheFailureForSeconds, CacheForSecond = dataCache.CacheForSeconds, CachedDataCount = dataCache.ContainsCachedData() ? (dataCache.CachedData is IList ? ((IList)dataCache.CachedData).Count : dataCache.CachedData != null ? 1 : 0) : 0, CachedData = includeData == true ? ToObjectArray(dataCache.ContainsCachedData(), dataCache.CachedData) : new object[0], //CachedTrendData = dataCache.CachedTrendData.Select(d => new //{ // DateTime = d.Item1, // Data = d.Item2, //}).ToList(), }).ToList(), }); }
public PollNode GetNext(PollNode node) { var next = nodes.Find(node).Next; if (next == null) { return(null); } return(next.Value); }
public void Subscribe(PollNode node, Action <byte[], Direction> callback) { if (subscribers.ContainsKey(node)) { subscribers[node] = callback; } else { subscribers.Add(node, callback); } }
public static bool TryRemove(PollNode node) { if (node == null) { return false; } lock (_addLock) { return AllPollNodes.Remove(node); } }
public bool Equals(PollNode other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(other.GetType() == GetType() && string.Equals(UniqueKey, other.UniqueKey)); }
/// <summary> /// Adds a node to the global polling list ONLY IF IT IS NEW /// If a node with the same unique key was already added, it will not be added again /// </summary> /// <param name="node">The node to add to the global polling list</param> /// <returns>Whether the node was added</returns> public static bool TryAdd(PollNode node) { lock (_addLock) { var added = AllPollNodes.Add(node); if (added) { Logger.InfoFormat("PollNode [{0} - {1}] added.", node.NodeType, node.UniqueKey); } return added; } }
//// метод реализуется теперь в самом таске //public bool BuildFromPath(IEnumerable<PollNodePathWrapper> path, PollTask initiator) //{ // var localPath = path.ToArray(); // var route = new Route(); // Func<bool, bool> cleanUp = (success) => // { // foreach (var n in localPath) // { // n.Node.Unlock(route); // } // //var finals = initiator.GetFinals(); // //if (finals != null) // //{ // // foreach (var final in finals) // // { // // final.Notify(); // // } // //} // initiator.LastActivityTime = DateTime.Now; // var final = localPath.LastOrDefault(); // if (final != null) final.Node.Notify(); // return success; // }; // route.SetPath(localPath); // foreach (var node in localPath) // { // if (!node.Node.Lock(route)) // { // return cleanUp(false); // } // } // foreach (var node in localPath.Reverse()) // { // if (!node.Node.Prepare(route, node.Left, initiator)) // { // foreach (var n in localPath.SkipWhile(nn => node != nn)) // { // n.Node.Release(route, n.Left); // } // return cleanUp(false); // } // } // foreach (var node in localPath) // { // node.Node.Release(route, node.Left); // } // return cleanUp(true); // //}); //} //public void AddTask(PollTask task, IEnumerable<PollNode> nodes) //{ // log.Debug(string.Format("добавляется таск для {0} нодов", nodes.Count())); // nodes.AsParallel().ForAll(t => // { // t.AddTask(task); // }); // log.Debug(string.Format("добавлен таск для {0} нодов", nodes.Count())); // //var finals = nodes.SelectMany(n => n.Paths.Where(p=>p.Any()).Select(p => p.Last())).Distinct().ToArray(); // //log.Debug(string.Format("уведомляются финальные ноды {0}", finals.Length)); // ////finals.AsParallel().ForAll(f => f.Notify()); // //foreach (var final in finals) // //{ // // final.Node.Notify(); // // //Task.Factory.StartNew(() => final.Notify()); // //} //} public void Destroy(PollNode start, Route route, int port) { if (start == null) { return; } log.Trace($"[{start}] уничтожение route={route}"); start.Release(route, port); start.Unlock(route); Destroy(route.GetNext(start), route, port); route.RemoveLast(start); }
public PollTask(string what, PollNode owner, dynamic arg, IEnumerable <IEnumerable <PollNodePathWrapper> > paths, int priority) { What = what; Owner = owner; Arg = arg; Repeats = 0; Priority = priority; isBusy = false; LastActivityTime = DateTime.Now; CreationDate = DateTime.Now; this.paths = GetActualPaths(paths, priority); }
public PollTask GetTaskForStarter(PollNode starter) { if (!HasTaskForStarter(starter)) { return(null); } lock (initiators) { var task = initiators[starter].OrderByDescending(p => p.Priority).FirstOrDefault(); if (task != null) { task.Lock(); } return(task); } }
/// <summary> /// запуск задачи, для финального узла /// </summary> /// <param name="final"></param> public void Begin(PollNode final) { var path = paths.Where(p => p.LastOrDefault() != null && p.LastOrDefault().Node == final).FirstOrDefault(); if (path == null) { return; } var code = ExecutePath(path); lock (busyLocker) { isBusy = false; } }
public static void AppendElement(this StringBuilder text, Dictionary <PollNode, List <PollTask> > elements) { int i = 1; foreach (KeyValuePair <PollNode, List <PollTask> > element in elements) { PollNode node = element.Key; List <PollTask> tasks = element.Value; text.AppendLine($"{i}) {node.GetId()} - {node.ToString()}"); foreach (PollTask task in tasks) { text.AppendLine($" {task.ToString()}"); } text.AppendLine(""); i++; } }
protected PollNodeDataCache(PollNode pollNode, int cacheForSeconds = 0, int? cacheFailureForSeconds = null, string description = "", [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { this.PollNode = pollNode; this.UniqueId = Guid.NewGuid(); this.CacheForSeconds = cacheForSeconds; this.CacheFailureForSeconds = cacheFailureForSeconds; this.Description = description; this.ParentMemberName = memberName; this.SourceFilePath = sourceFilePath; this.SourceLineNumber = sourceLineNumber; }
public void CancelTaskFor(PollNode initiator) { if (!HasTaskForStarter(initiator)) { Log("задачи отсутствуют", initiator.GetId()); return; } RemoveTaskFor(initiator); if (initiator.IsLocked()) { initiator.Cancel(); } else { Log("задачи отменены", initiator.GetId()); } }
public void RemoveTaskFor(PollNode initiator) { List <PollTask> tasks = new List <PollTask>(); lock (initiators) { if (initiators.ContainsKey(initiator)) { tasks = initiators[initiator]; } } if (!tasks.Any()) { return; } foreach (var task in tasks) { foreach (var executer in executers.Keys) { List <PollTask> taskscopy = null; lock (executers) { taskscopy = executers[executer]; } if (!taskscopy.Contains(task)) { continue; } lock (executers) { executers[executer].Remove(task); } } } lock (initiators) { initiators[initiator].Clear(); } }
private void RemoveBrokenPath(PollNode node) { var newpaths = paths.ToList(); foreach (var path in paths) { if (path.Any(n => n.Node == node)) { newpaths.Remove(path); } } if (!newpaths.Any()) { Destroy(); } else { paths = newpaths; } }
public bool Equals(PollNode other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other.GetType() == GetType() && string.Equals(UniqueKey, other.UniqueKey); }
public PollNodePathWrapper(PollNode node, int left = 1) { Node = node; Left = left; }
public void RemoveLast(PollNode node) { nodes.Remove(node); }
public void AddLast(PollNode node) { nodes.AddFirst(node); }
public PollNode GetPrevious(PollNode node) { return(nodes.Find(node).Previous.Value); }
// TODO: Copy constructor on // Microsoft.AspNetCore.Mvc.Rendering.TagBuilder public static IHtmlContent Now(PollNode n, Cache c = null) => new HtmlString($@"<a href=""#"" class=""pull-right hover-pulsate js-reload-link"" data-type=""{n.NodeType}"" data-uk=""{n.UniqueKey.HtmlEncode()}"" data-guid=""{c?.UniqueId.ToString().HtmlEncode()}"" title=""Updated {n.LastPoll?.ToZuluTime()}"">{Icon.Refresh} <span class=""js-text"">Poll Now</span></a>");
public static IHtmlContent Now(PollNode n, params Cache[] c) => new HtmlString($@"<a href=""#"" class=""pull-right hover-pulsate js-reload-link"" data-type=""{n.NodeType}"" data-uk=""{n.UniqueKey.HtmlEncode()}"" data-guid=""{JSON.Serialize(c.Select(i => i.UniqueId)).HtmlEncode()}"" title=""Updated {n.LastPoll?.ToZuluTime()}"">{Icon.Refresh} <span class=""js-text"">Poll Now</span></a>");
private static NodeStatusViewModel GetNodeStatusViewModel(PollNode node, bool? includeData = false) { return new NodeStatusViewModel { NodeType = node.NodeType, UniqueKey = node.UniqueKey, LastPoll = node.LastPoll, LastPollDuration = node.LastPollDuration, MinSecondsBetweenPolls = node.MinSecondsBetweenPolls, PollTaskStatus = node.PollTaskStatus, PollerCount = node.DataCaches.Count(), DataCaches = node.DataCaches.Select(dataCache => new NodeDataCacheViewModel { Name = dataCache.ParentMemberName, Type = dataCache.CachedDataType, UniqueId = dataCache.UniqueId, LastPoll = dataCache.LastRefresh, LastPollDuration = dataCache.LastRefreshDuration, LastPollStatus = dataCache.LastRefreshStatus, LastSuccess = dataCache.LastRefreshSuccess, NextPoll = dataCache.CacheExpiration, PollsSuccessful = dataCache.RefreshCountSuccessful, PollsTotal = dataCache.RefreshCountTotal, CacheFailureForSeconds = dataCache.CacheFailureForSeconds, CacheForSecond = dataCache.CacheForSeconds, CachedDataCount = dataCache.ContainsCachedData() ? (dataCache.CachedData is IList ? ((IList)dataCache.CachedData).Count : dataCache.CachedData != null ? 1 : 0) : 0, CachedData = includeData == true ? ToObjectArray(dataCache.ContainsCachedData(), dataCache.CachedData) : new object[0], //CachedTrendData = dataCache.CachedTrendData.Select(d => new //{ // DateTime = d.Item1, // Data = d.Item2, //}).ToList(), }).ToList(), }; }