Example #1
0
        public async Task <Object> Report(Int32 id, String token)
        {
            var node = DecodeToken(token, Setting.Current.TokenSecret);

            if (node == null)
            {
                throw new ApiException(402, "节点未登录");
            }

            var cmd = NodeCommand.FindByID(id);

            if (cmd != null && cmd.NodeID == node.ID)
            {
                var ms = Request.Body;
                if (Request.ContentLength > 0)
                {
                    var rs = cmd.Command switch
                    {
                        "截屏" => await SaveFileAsync(cmd, ms, "png"),
                        "抓日志" => await SaveFileAsync(cmd, ms, "log"),
                        _ => await SaveFileAsync(cmd, ms, "bin"),
                    };
                    if (!rs.IsNullOrEmpty())
                    {
                        cmd.Status = CommandStatus.已完成;
                        cmd.Result = rs;
                        cmd.Save();

                        WriteHistory(node, cmd.Command, true, rs);
                    }
                }
            }

            return(null);
        }
        public override bool VisitNodeCommand(NodeCommand command)
        {
            NodeStore nodeStore = _neoStores.NodeStore;

            Track(nodeStore, command);
            Track(nodeStore.DynamicLabelStore, command.After.DynamicLabelRecords);
            return(false);
        }
Example #3
0
        public Task <Byte[]> Send(byte nodeID, Command command, byte responseCommandID)
        {
            if (nodeID == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(nodeID), nodeID, "nodeID can not be 0");
            }
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            return(Exchange(async() =>
            {
                var completionSource = new TaskCompletionSource <Command>();

                EventHandler <NodeEventArgs> onNodeEventReceived = (_, e) =>
                {
                    if (e.NodeID == nodeID && e.Command.ClassID == command.ClassID && e.Command.CommandID == responseCommandID)
                    {
                        // BugFix:
                        // http://stackoverflow.com/questions/19481964/calling-taskcompletionsource-setresult-in-a-non-blocking-manner
                        Task.Run(() => completionSource.TrySetResult(e.Command));
                    }
                };

                var request = new NodeCommand(nodeID, command);
                _transmitQueue.Add(request);

                NodeEventReceived += onNodeEventReceived;
                try
                {
                    await WaitForResponse((message) =>
                    {
                        return (message is NodeCommandCompleted && ((NodeCommandCompleted)message).CallbackID == request.CallbackID);
                    }).ConfigureAwait(false);

                    try
                    {
                        using (var cancellationTokenSource = new CancellationTokenSource())
                        {
                            cancellationTokenSource.CancelAfter(ResponseTimeout);
                            cancellationTokenSource.Token.Register(() => completionSource.TrySetCanceled(), useSynchronizationContext: false);

                            var response = await completionSource.Task.ConfigureAwait(false);
                            return response.Payload;
                        }
                    }
                    catch (TaskCanceledException)
                    {
                        throw new TimeoutException();
                    }
                }
                finally
                {
                    NodeEventReceived -= onNodeEventReceived;
                }
            }, $"NodeID:{nodeID:D3}, Command:[{command}], Reponse:{responseCommandID}"));
        }
Example #4
0
    public async Async.Task SendMessage(Node node, NodeCommand message)
    {
        var r = await _context.NodeMessageOperations.Replace(new NodeMessage(node.MachineId, message));

        if (!r.IsOk)
        {
            _logTracer.WithHttpStatus(r.ErrorV).Error($"failed to replace NodeMessge record for machine_id: {node.MachineId}");
        }
    }
Example #5
0
        /// <summary>
        /// Attempts to add or remove a node from the addnode list.
        ///Or try a connection to a node once.
        ///Nodes added using addnode (or -connect) are protected from DoS disconnection and are not required to be
        ///full nodes/support SegWit as other outbound peers are(though such peers will not be synced from).
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="command">'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once.</param>
        /// <returns></returns>
        public async Task <string> AddNode(string node, NodeCommand command)
        {
            AddNode addNode = new AddNode()
            {
                Node = node, NodeCommand = command
            };
            string response = await httpRequest.SendReq(MethodName.addnode, addNode);

            return(response);
        }
Example #6
0
        public Int32 SendCommand(CommandInModel model, String token)
        {
            if (model.NodeCode.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(model.NodeCode), "必须指定节点");
            }
            if (model.Command.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(model.Command));
            }

            var node = Node.FindByCode(model.NodeCode);

            if (node == null)
            {
                throw new ArgumentOutOfRangeException(nameof(model.NodeCode), "无效节点");
            }

            var app = _tokenService.DecodeToken(token, Setting.Current);

            if (app == null || app.AllowControlNodes.IsNullOrEmpty())
            {
                throw new InvalidOperationException("无权操作!");
            }

            if (app.AllowControlNodes != "*" && !node.Code.EqualIgnoreCase(app.AllowControlNodes.Split(",")))
            {
                throw new InvalidOperationException($"[{app}]无权操作节点[{node}]!");
            }

            var cmd = new NodeCommand
            {
                NodeID   = node.ID,
                Command  = model.Command,
                Argument = model.Argument,
                //Expire = model.Expire,
                Times = 1,

                CreateUser = app.Name,
            };

            if (model.Expire > 0)
            {
                cmd.Expire = DateTime.Now.AddSeconds(model.Expire);
            }
            cmd.Insert();

            var queue = _queue.GetQueue <String>($"cmd:{node.Code}");

            queue.Add(cmd.ToModel().ToJson());

            return(cmd.ID);
        }
Example #7
0
        private async Task <String> SaveFileAsync(NodeCommand cmd, Stream ms, String ext)
        {
            var file = $"../{cmd.Command}/{DateTime.Today:yyyyMMdd}/{cmd.NodeID}_{cmd.ID}.{ext}";

            file.EnsureDirectory(true);

            using var fs = file.AsFile().OpenWrite();
            await ms.CopyToAsync(fs);

            await ms.FlushAsync();

            return(file);
        }
Example #8
0
        public PingResponse Ping(PingInfo inf)
        {
            var rs = new PingResponse
            {
                Time       = inf.Time,
                ServerTime = DateTime.UtcNow,
            };

            var node = Session["Node"] as Node;

            if (node != null)
            {
                var code = node.Code;
                FixArea(node);
                node.SaveAsync();

                var olt = GetOnline(code, node);
                if (olt == null)
                {
                    olt = CreateOnline(code, node);
                }
                Fill(olt, inf);

                olt.Token = Token;
                olt.PingCount++;
                olt.SaveAsync();

                // 拉取命令
                var cmds = NodeCommand.AcquireCommands(node.ID, 100);
                if (cmds != null)
                {
                    rs.Commands = cmds.Select(e => new CommandModel
                    {
                        Id       = e.ID,
                        Command  = e.Command,
                        Argument = e.Argument,
                    }).ToArray();

                    foreach (var item in cmds)
                    {
                        item.Finished   = true;
                        item.UpdateTime = DateTime.Now;
                    }
                    cmds.Update(true);
                }
            }

            return(rs);
        }
Example #9
0
        public async Task <Object> Report(Int32 id)
        {
            var node = Session["Node"] as Node;

            if (node == null)
            {
                throw new ApiException(402, "节点未登录");
            }

            var cmd = NodeCommand.FindByID(id);

            if (cmd != null && cmd.NodeID == node.ID)
            {
                var ms = Request.Body;
                if (Request.ContentLength > 0)
                {
                    var rs = "";
                    switch (cmd.Command)
                    {
                    case "截屏":
                        rs = await SaveFileAsync(cmd, ms, "png");

                        break;

                    case "抓日志":
                        rs = await SaveFileAsync(cmd, ms, "log");

                        break;

                    default:
                        rs = await SaveFileAsync(cmd, ms, "bin");

                        break;
                    }

                    if (!rs.IsNullOrEmpty())
                    {
                        cmd.Result = rs;
                        cmd.Save();

                        WriteHistory(node, cmd.Command, true, rs);
                    }
                }
            }

            return(null);
        }
Example #10
0
        private static CommandModel[] AcquireCommands(Int32 nodeId)
        {
            // 缓存最近1000个未执行命令,用于快速过滤,避免大量节点在线时频繁查询命令表
            if (_nextTime < DateTime.Now)
            {
                _commands = NodeCommand.AcquireCommands(-1, 1000);
                _nextTime = DateTime.Now.AddMinutes(1);
            }

            // 是否有本节点
            if (!_commands.Any(e => e.NodeID == nodeId))
            {
                return(null);
            }

            var cmds = NodeCommand.AcquireCommands(nodeId, 100);

            if (cmds == null)
            {
                return(null);
            }

            var rs = new List <CommandModel>();

            foreach (var item in cmds)
            {
                if (item.Times > 10 || item.Expire.Year > 2000 && item.Expire < DateTime.Now)
                {
                    item.Status = CommandStatus.取消;
                }
                else
                {
                    if (item.Status == CommandStatus.处理中 && item.UpdateTime.AddMinutes(10) < DateTime.Now)
                    {
                        continue;
                    }

                    item.Times++;
                    item.Status = CommandStatus.处理中;
                    rs.Add(item.ToModel());
                }
                item.UpdateTime = DateTime.Now;
            }
            cmds.Update(false);

            return(rs.ToArray());
        }
Example #11
0
        private static CommandModel[] AcquireCommands(Int32 nodeId)
        {
            // 缓存最近1000个未执行命令,用于快速过滤,避免大量节点在线时频繁查询命令表
            if (_nextTime < DateTime.Now)
            {
                _commands = NodeCommand.AcquireCommands(-1, 1000);
                _nextTime = DateTime.Now.AddMinutes(1);
            }

            // 是否有本节点
            if (!_commands.Any(e => e.NodeID == nodeId))
            {
                return(null);
            }

            var cmds = NodeCommand.AcquireCommands(nodeId, 100);

            if (cmds == null)
            {
                return(null);
            }

            var rs = cmds.Select(e => new CommandModel
            {
                Id       = e.ID,
                Command  = e.Command,
                Argument = e.Argument,
                Expire   = e.Expire,
            }).ToArray();

            foreach (var item in cmds)
            {
                item.Finished   = true;
                item.UpdateTime = DateTime.Now;
            }
            cmds.Update(false);

            return(rs);
        }
Example #12
0
        public Task Send(byte nodeID, Command command, CancellationToken cancellationToken)
        {
            if (nodeID == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(nodeID), nodeID, "nodeID can not be 0");
            }
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            return(Exchange(async() =>
            {
                var request = new NodeCommand(nodeID, command);
                _transmitQueue.Add(request);

                await WaitForResponse((message) =>
                {
                    return (message is NodeCommandCompleted && ((NodeCommandCompleted)message).CallbackID == request.CallbackID);
                }, cancellationToken).ConfigureAwait(false);

                return null;
            }, $"NodeID:{nodeID:D3}, Command:{command}", cancellationToken));
        }
Example #13
0
 public async Async.Task SendMessage(Guid machineId, NodeCommand message, string?messageId = null)
 {
     messageId = messageId ?? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
     await Insert(new NodeMessage(machineId, messageId, message));
 }
Example #14
0
 public bool NodeCommand(NodeCommand e)
 {
     return(Test(e));
 }
 private double GetSuccess(NodeCommand command)
 {
     int success;
     if (_successCounter.TryGetValue(command.Description, out success))
     {
         return success;
     }
     return _random.NextDouble();
 }