4

我正在使用SSH.NET库使用inotifywait命令在远程 linux 服务器上实现文件系统观察程序。本质上它是一个包装器:

ssh myhost "inotifywait -m -e close_write --format '%:e %f' /dropzone"

该命令将打印出来(到 STDOUT):

CLOSE_WRITE:CLOSE foo
CLOSE_WRITE:CLOSE bar
CLOSE_WRITE:CLOSE baz

这很简单,可以解析并转化为事件。无论如何,我的 C# 代码本质上是:

        var privateKeyFile = new PrivateKeyFile(identity);
        var client = new SshClient(hostname, username, privateKeyFile);

        SshCommand command = null;
        IAsyncResult result = null;
        try
        {
            client.Connect();
            command = client.CreateCommand("inotifywait -m -e close_write --format '%:e %f' " + dropZone);
            result = command.BeginExecute();

            Console.WriteLine("Watching for events");
            var reader = new StreamReader(command.OutputStream);
            string line = null;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
            Console.WriteLine("Reached end of stream");
        }
        finally
        {
            if (client != null)
            {
                Console.WriteLine("Close the connection");
                client.Dispose();
            }
        }

        Console.WriteLine("Press enter to quit");
        Console.ReadLine();

在写入单个文件后运行它会产生以下输出:

Watching for events
CLOSE_WRITE:CLOSE baz
Reached end of stream
Close the connection
Press enter to quit

立即出现Watching for events并等待第一个文件被写入(阻塞等待,正如我所期望的那样StreamReader)。但是,ReadLine即使命令仍在愉快地运行,下一个而不是另一个阻塞等待返回 null (表示流结束)。我知道我可以这样改变循环:

            while (!result.IsCompleted)
            {
                line = reader.ReadLine();
                if (line != null)
                {
                    Console.WriteLine(line);
                }
            }

结果是:

Watching for events
CLOSE_WRITE:CLOSE baz
CLOSE_WRITE:CLOSE bar
CLOSE_WRITE:CLOSE foo
...

根据需要,但它摆脱了对新输入的阻塞等待,这意味着循环不断旋转(显然是不希望的......)

你能解释一下这种行为吗?对另一种方法有什么建议吗?

- - 更新 - -

看起来该库正在迁移到 github 并进行更新。我已提交此问题以尝试解决此问题。

4

2 回答 2

2

观察到行为的原因是PipeStream类。它像字节队列一样工作。当您从 读取字节时PipeStream,实际上是在将它们出列,因此流长度会减少。当您读取所有字节时,流长度变为 0。这意味着在您读取第一“行”(实际上可以是多行,只是数据的第一部分)之后 - 流的长度为 0,因此有效结束。下一次读取将在没有阻塞的情况下返回,直到下一部分数据到达(如果有)。

不幸的是,这些流似乎不是为您的情况而设计的——它们旨在执行命令、接收一个结果并完成。如果您想读取连续的数据流(例如您的案例或例如“tail -f”结果 - 您唯一的选择似乎是回退到Thread.Sleep读取之间,至少在快速搜索之后我没有找到任何替代方案。

更新:仍然有一些反思,你可以达到你想要的结果。Undelying 通道具有 DataReceived 事件,您可以使用该事件在有新数据可用时获得通知。下面的代码应该可以解决问题(注意这是一个草图,所以要小心):

    static void Main(string[] args) {
        var privateKeyFile = new PrivateKeyFile(@"somefile");
        using (var client = new SshClient("somehost", "someuser", privateKeyFile)) {                
            client.Connect();
            var command = client.CreateCommand("tail -f /tmp/test.txt");

            var result = command.BeginExecute();
            var channelField = command.GetType().GetField("_channel", BindingFlags.Instance | BindingFlags.NonPublic);
            var channel = channelField.GetValue(command);
            var receivedEvent = channel.GetType().GetEvent("DataReceived", BindingFlags.Instance | BindingFlags.Public);
            Console.WriteLine("Watching for events");
            using (var handler = new ReceivedHandler()) {
                // add event handler here
                receivedEvent.AddEventHandler(channel, Delegate.CreateDelegate(receivedEvent.EventHandlerType, handler, handler.GetType().GetMethod("OnReceive")));
                while (true) {
                    // wait on both command completion and our custom wait handle. This is blocking call
                    WaitHandle.WaitAny(new[] {result.AsyncWaitHandle, handler.Signal});
                    // if done - break
                    if (result.IsCompleted)
                        break;
                    var line = handler.ReadLine();
                    Console.WriteLine(line);
                }
            }                                
            Console.WriteLine("Reached end of stream");                
            Console.ReadKey();
        }

    }

    public class ReceivedHandler : IDisposable {
        private readonly AutoResetEvent _signal;
        private readonly StringBuilder _buffer = new StringBuilder();
        public ReceivedHandler() {
            _signal = new AutoResetEvent(false);
        }

        public void OnReceive(object sender, EventArgs e) {
            var dataProp = e.GetType().GetProperty("Data", BindingFlags.Instance | BindingFlags.Public);
            var rawData = (byte[])dataProp.GetValue(e);
            var data = Encoding.ASCII.GetString(rawData);
            lock (_buffer) {
                // append to buffer for reader to consume
                _buffer.Append(data);
            }
            // notify reader
            Signal.Set();
        }

        public AutoResetEvent Signal => _signal;

        public string ReadLine() {
            lock (_buffer) {
                // cleanup buffer
                var result = _buffer.ToString();
                _buffer.Clear();
                return result;
            }
        }

        public void Dispose() {
            _signal.Dispose();
        }
    }

当然,最好联系这个库的开发者并解释问题,也许他们可以添加缺失的行为。

于 2016-05-05T21:10:18.963 回答
1

@Evk 的答案是正确的,这PipeStream是罪魁祸首。另一个问题PipeStream是,如果您尝试读取超过可用字节数,它将阻塞. 出于性能原因,阻塞应该PipeStream. 我使用 SSH.NET 来执行SshCommand和异步读取标准输出/错误。我解决这些问题的方法是写信给中介MemoryStream,然后使用标准机制,如StreamReader. 这是从以下内容中读取的更通用的答案PipeStream

public class SshCommandStreamReader : IDisposable
{
    private readonly Stream stream;
    private readonly MemoryStream intermediateStream;
    private readonly StreamReader reader;

    public SshCommandOutputReader(Stream stream)
    {
        this.stream = stream;
        this.intermediateStream = new MemoryStream();
        this.reader = new StreamReader(intermediateStream, Encoding.UTF8);
    }

    private int FlushToIntermediateStream()
    {
        var length = stream.Length;

        if (length == 0)
        {
            return 0;
        }

        // IMPORTANT: Do NOT read with a count higher than the stream length (which is typical of reading
        // from streams). The streams for SshCommand are implemented by PipeStream (an internal class to
        // SSH.NET). Reading more than the current length causes it to *block* until data is available.
        // If the stream is flushed when reading, it does not block. It is not reliable to flush and then
        // read because there is a possible race condition where a write might occur between flushing and
        // reading (writing resets the flag that it was flushed). The only reliable solution to prevent
        // blocking when reading is to always read the current length rather than an arbitrary buffer size.
        var intermediateOutputBuffer = new byte[length];
        var bytesRead = stream.Read(intermediateOutputBuffer, 0, intermediateOutputBuffer.Length);
        intermediateStream.Write(intermediateOutputBuffer, 0, bytesRead);
        return bytesRead;
    }

    public string Read()
    {
        var bytesFlushed = FlushToIntermediateStream();

        // Allow reading the newly flushed bytes.
        intermediateStream.Position -= bytesFlushed;

        // Minor optimization since this may be called in a tight loop.
        if (intermediateStream.Position == intermediateStream.Length)
        {
            return null;
        }
        else
        {
            var result = reader.ReadToEnd();
            return result;
        }
    }

    public void Dispose()
    {
        reader.Dispose();
        intermediateStream.Dispose();
    }
}

然后使用它:

using (var command = client.CreateCommand("your command text"))
{
    var cmdAsyncResult = command.BeginExecute();

    using (var standardOutputReader = new SshCommandStreamReader(command.OutputStream))
    {
        while (!cmdAsyncResult.IsCompleted)
        {
            var result = standardOutputReader.Read();
            if (!String.IsNullOrEmpty(result))
            {
                Console.Write(result);
            }

            // Or what ever mechanism you'd like to use to prevent CPU thrashing.
            Thread.Sleep(1);
        }

        // This must be done *after* the loop and *before* EndExecute() so that any extra output
        // is captured (e.g. the loop never ran because the command was so fast).
        var resultFinal = standardOutputReader.Read();
        if (!String.IsNullOrEmpty(resultFinal))
        {
            Console.Write(resultFinal);
        }
    }

    command.EndExecute(cmdAsyncResult);
}

您应该能够修改此示例以从标准错误中读取(通过ExtendedOutputStream)并将其更改为逐行读取,这是特定于您的应用程序的。

于 2017-10-18T14:45:52.857 回答