/// <summary>Add the command async result for a command.
 /// </summary>
 /// <param name="commandId">The commandId.</param>
 /// <param name="commandAsyncResult">The command async result.</param>
 public void Add(Guid commandId, CommandAsyncResult commandAsyncResult)
 {
     if (!_commandAsyncResultDict.TryAdd(commandId, commandAsyncResult))
     {
         throw new Exception(string.Format("Command with id '{0}' is already exist.", commandId));
     }
 }
 /// <summary>Add the command async result for a command.
 /// </summary>
 /// <param name="commandId">The commandId.</param>
 /// <param name="commandAsyncResult">The command async result.</param>
 public void Add(Guid commandId, CommandAsyncResult commandAsyncResult)
 {
     if (!_commandAsyncResultDict.TryAdd(commandId, commandAsyncResult))
     {
         throw new Exception(string.Format("Command with id '{0}' is already exist.", commandId));
     }
 }
        public void BytesReceivedTest()
        {
            var target = new CommandAsyncResult();
            var expected = new Random().Next();

            target.BytesReceived = expected;

            Assert.AreEqual(expected, target.BytesReceived);
        }
        public void BytesSentTest()
        {
            var target = new CommandAsyncResult();
            int expected = new Random().Next();

            target.BytesSent = expected;

            Assert.AreEqual(expected, target.BytesSent);
        }
Beispiel #5
0
        public void BytesReceivedTest()
        {
            var target   = new CommandAsyncResult();
            var expected = new Random().Next();

            target.BytesReceived = expected;

            Assert.AreEqual(expected, target.BytesReceived);
        }
Beispiel #6
0
        public void BytesSentTest()
        {
            var target   = new CommandAsyncResult();
            int expected = new Random().Next();

            target.BytesSent = expected;

            Assert.AreEqual(expected, target.BytesSent);
        }
        private void SshCommandAsyncCallback(IAsyncResult r)
        {
            CommandAsyncResult car = r as CommandAsyncResult;
            KeyValuePair <SshCommand, Stopwatch> cas = (KeyValuePair <SshCommand, Stopwatch>)car.AsyncState;

            if (car.IsCompleted)
            {
                cas.Value.Stop();
                Debug("Completed execution of {0} with {1} bytes received in {2} ms.", cas.Key.CommandText, car.BytesReceived, cas.Value.ElapsedMilliseconds);
            }
        }
Beispiel #8
0
        public void BytesReceivedTest()
        {
            SshCommand         command = null;                            // TODO: Initialize to an appropriate value
            CommandAsyncResult target  = new CommandAsyncResult(command); // TODO: Initialize to an appropriate value
            int expected = 0;                                             // TODO: Initialize to an appropriate value
            int actual;

            target.BytesReceived = expected;
            actual = target.BytesReceived;
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
        public List <Tuple <string, ProcessExecuteStatus, string, string> > ExecuteMany(List <Tuple <string, string> > commands)
        {
            CallerInformation caller = this.Here();

            if (!this.IsConnected)
            {
                throw new InvalidOperationException("The SSH session is not connected.");
            }
            List <Tuple <string, ProcessExecuteStatus, string, string> > results = new List <Tuple <string, ProcessExecuteStatus, string, string> >(commands.Count);
            object    results_lock = new object();
            Stopwatch sw           = new Stopwatch();

            sw.Start();
            Parallel.ForEach(commands, new ParallelOptions()
            {
                MaxDegreeOfParallelism = 20
            }, (_c, state) =>
            {
                string process_output = string.Empty;
                string process_error  = string.Empty;
                SshCommand cmd        = this.SshClient.CreateCommand(_c.Item1 + " " + _c.Item2);
                Stopwatch cs          = new Stopwatch();
                cs.Start();
                CommandAsyncResult result = cmd.BeginExecute(new AsyncCallback(SshCommandAsyncCallback), new KeyValuePair <SshCommand, Stopwatch>(cmd, cs)) as CommandAsyncResult;
                cmd.EndExecute(result);
                KeyValuePair <SshCommand, Stopwatch> s = (KeyValuePair <SshCommand, Stopwatch>)result.AsyncState;
                process_output = s.Key.Result.Trim();
                process_error  = s.Key.Error.Trim();
                if (s.Value.IsRunning)
                {
                    s.Value.Stop();
                }
                if (process_output != string.Empty)
                {
                    lock (results_lock)
                    {
                        results.Add(new Tuple <string, ProcessExecuteStatus, string, string>(_c.Item1, ProcessExecuteStatus.Completed, process_output, process_error));
                    }
                    Debug(caller, "Execute {0} completed with {1} {2}.", s.Key.Result.Length, cmd.CommandText, process_output, process_error);
                }
                else
                {
                    lock (results_lock)
                    {
                        results.Add(new Tuple <string, ProcessExecuteStatus, string, string>(_c.Item1, ProcessExecuteStatus.Error, process_output, process_error));
                    }
                    Debug(caller, "Execute {0} did not complete successfully: {1} {2}.", s.Key.Result.Length, cmd.CommandText, process_output, process_error);
                }
            });
            return(results);
        }
Beispiel #10
0
        /// <summary>Send the given command to command queue, and block the current thread until the command was handled or timeout.
        /// </summary>
        /// <param name="command">The command to send.</param>
        /// <returns>The command execution result.</returns>
        /// <exception cref="ArgumentNullException">Throwed when the command is null.</exception>
        /// <exception cref="CommandQueueNotFoundException">Throwed when the command queue cannot be routed.</exception>
        /// <exception cref="CommandTimeoutException">Throwed when the command execution timeout.</exception>
        /// <exception cref="CommandExecutionException">Throwed when the command execution has any error.</exception>
        public CommandAsyncResult Execute(ICommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var commandQueue = _commandQueueRouter.Route(command);

            if (commandQueue == null)
            {
                throw new CommandQueueNotFoundException(command.GetType());
            }

            var waitHandle         = new ManualResetEvent(false);
            var commandAsyncResult = new CommandAsyncResult(waitHandle);

            _commandAsyncResultManager.Add(command.Id, commandAsyncResult);
            commandQueue.Enqueue(command);
            waitHandle.WaitOne(command.MillisecondsTimeout);
            _commandAsyncResultManager.Remove(command.Id);

            if (!commandAsyncResult.IsCompleted)
            {
                throw new CommandTimeoutException(command.Id, command.GetType());
            }
            if (commandAsyncResult.ErrorInfo == null)
            {
                return(commandAsyncResult);
            }

            var errorInfo = commandAsyncResult.ErrorInfo;

            if (errorInfo.ErrorMessage != null && errorInfo.Exception != null)
            {
                throw new CommandExecutionException(command.Id, command.GetType(), errorInfo.ErrorMessage, errorInfo.Exception);
            }
            if (errorInfo.ErrorMessage != null)
            {
                throw new CommandExecutionException(command.Id, command.GetType(), errorInfo.ErrorMessage);
            }
            if (errorInfo.Exception != null)
            {
                throw new CommandExecutionException(command.Id, command.GetType(), errorInfo.Exception);
            }

            return(commandAsyncResult);
        }
        /// <summary>Send the given command to command queue, and block the current thread until the command was handled or timeout.
        /// </summary>
        /// <param name="command">The command to send.</param>
        /// <returns>The command execution result.</returns>
        /// <exception cref="ArgumentNullException">Throwed when the command is null.</exception>
        /// <exception cref="CommandQueueNotFoundException">Throwed when the command queue cannot be routed.</exception>
        /// <exception cref="CommandTimeoutException">Throwed when the command execution timeout.</exception>
        /// <exception cref="CommandExecutionException">Throwed when the command execution has any error.</exception>
        public CommandAsyncResult Execute(ICommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var commandQueue = _commandQueueRouter.Route(command);
            if (commandQueue == null)
            {
                throw new CommandQueueNotFoundException(command.GetType());
            }

            var waitHandle = new ManualResetEvent(false);
            var commandAsyncResult = new CommandAsyncResult(waitHandle);

            _commandAsyncResultManager.Add(command.Id, commandAsyncResult);
            commandQueue.Enqueue(command);
            waitHandle.WaitOne(command.MillisecondsTimeout);
            _commandAsyncResultManager.Remove(command.Id);

            if (!commandAsyncResult.IsCompleted)
            {
                throw new CommandTimeoutException(command.Id, command.GetType());
            }
            if (commandAsyncResult.ErrorInfo == null)
            {
                return commandAsyncResult;
            }

            var errorInfo = commandAsyncResult.ErrorInfo;
            if (errorInfo.ErrorMessage != null && errorInfo.Exception != null)
            {
                throw new CommandExecutionException(command.Id, command.GetType(), errorInfo.ErrorMessage, errorInfo.Exception);
            }
            if (errorInfo.ErrorMessage != null)
            {
                throw new CommandExecutionException(command.Id, command.GetType(), errorInfo.ErrorMessage);
            }
            if (errorInfo.Exception != null)
            {
                throw new CommandExecutionException(command.Id, command.GetType(), errorInfo.Exception);
            }

            return commandAsyncResult;
        }
        IAsyncResult BeginExecuteCommand(string command, bool consumeStream, AsyncCallback callback = null, object state = null)
        {
            var data = Encoding.UTF8.GetBytes(command);

            if (data.Length > byte.MaxValue)
            {
                throw new ArgumentException("Command too long");
            }

            var buffer = new byte[data.Length + 1];

            buffer[0] = (byte)data.Length;
            Array.Copy(data, 0, buffer, 1, data.Length);

            var ar = new CommandAsyncResult(this, callback, state)
            {
                Buffer        = buffer,
                ConsumeStream = consumeStream,
            };

            //try to re-use an existing stream
            lock (lock_obj) {
                if (reusableStream != null)
                {
                    ar.Stream = reusableStream;
                    //if we're going to consume the stream, don't leave it around for others to re-use
                    if (consumeStream)
                    {
                        reusableStream = null;
                    }
                }
            }

            if (ar.Stream != null)
            {
                ExecuteCommand_BeginWriteCommand(ar);
            }
            else
            {
                BeginConnectStream(ExecuteCommand_ConnectedCommandStream, ar).AsyncWaitHandle.WaitOne(3000);
            }

            return(ar);
        }
        public override Dictionary <AuditFileInfo, string> ReadFilesAsText(List <AuditFileInfo> files)
        {
            CallerInformation here = this.Here();
            Dictionary <AuditFileInfo, string> results = new Dictionary <AuditFileInfo, string>(files.Count);
            object    results_lock = new object();
            Stopwatch sw           = new Stopwatch();

            sw.Start();
            Parallel.ForEach(files, new ParallelOptions()
            {
                MaxDegreeOfParallelism = 20
            }, (_f, state) =>
            {
                SshCommand cmd = this.SshClient.CreateCommand("cat " + _f.FullName);
                Stopwatch cs   = new Stopwatch();
                cs.Start();
                CommandAsyncResult result = cmd.BeginExecute(new AsyncCallback(SshCommandAsyncCallback), new KeyValuePair <SshCommand, Stopwatch> (cmd, cs)) as CommandAsyncResult;
                cmd.EndExecute(result);
                KeyValuePair <SshCommand, Stopwatch> s = (KeyValuePair <SshCommand, Stopwatch>)result.AsyncState;
                if (s.Key.Result != string.Empty)
                {
                    lock (results_lock)
                    {
                        results.Add(_f, s.Key.Result);
                    }
                    if (s.Value.IsRunning)
                    {
                        s.Value.Stop();
                    }
                    Debug(here, "Read {0} chars from {1}.", s.Key.Result.Length, _f.FullName);
                    Progress("Read environment files", files.Count, 3, s.Value.Elapsed);
                }
                else
                {
                    Error(here, "Could not read {0} as text. Command returned: {1}", _f.FullName, s.Key.Error);
                }
                s.Key.Dispose();
                cs = null;
            });
            sw.Stop();
            Success("Read text for {0} out of {1} files in {2} ms.", results.Count(r => r.Value.Length > 0), results.Count(), sw.ElapsedMilliseconds);
            return(results);
        }
 void ExecuteCommand_BeginWriteCommand(CommandAsyncResult r)
 {
     r.Stream.BeginWrite(r.Buffer, 0, r.Buffer.Length, ExecuteCommand_WroteCommand, r);
 }