SftpFileReader.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. using Renci.SshNet.Abstractions;
  2. using Renci.SshNet.Common;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. namespace Renci.SshNet.Sftp
  7. {
  8. internal class SftpFileReader : IDisposable
  9. {
  10. private readonly byte[] _handle;
  11. private readonly ISftpSession _sftpSession;
  12. private uint _chunkLength;
  13. private ulong _offset;
  14. private ulong _fileSize;
  15. private readonly IDictionary<int, BufferedRead> _queue;
  16. private int _readAheadChunkIndex;
  17. private ulong _readAheadOffset;
  18. private ManualResetEvent _readAheadCompleted;
  19. private int _nextChunkIndex;
  20. private bool _isEndOfFile;
  21. private SemaphoreLight _semaphore;
  22. private readonly object _readLock;
  23. private Exception _exception;
  24. private bool _disposed;
  25. /// <summary>
  26. /// Initializes a new <see cref="SftpFileReader"/> instance with the specified handle,
  27. /// <see cref="ISftpSession"/> and the maximum number of pending reads.
  28. /// </summary>
  29. /// <param name="handle"></param>
  30. /// <param name="sftpSession"></param>
  31. /// <param name="maxReadHead">The maximum number of pending reads.</param>
  32. public SftpFileReader(byte[] handle, ISftpSession sftpSession, int maxReadHead)
  33. {
  34. _handle = handle;
  35. _sftpSession = sftpSession;
  36. _chunkLength = 32 * 1024 - 13; // TODO !
  37. _semaphore = new SemaphoreLight(maxReadHead);
  38. _queue = new Dictionary<int, BufferedRead>(maxReadHead);
  39. _readLock = new object();
  40. _readAheadCompleted = new ManualResetEvent(false);
  41. _fileSize = (ulong)_sftpSession.RequestFStat(_handle).Size;
  42. StartReadAhead();
  43. }
  44. public byte[] Read()
  45. {
  46. if (_exception != null || _disposed)
  47. throw new ObjectDisposedException(GetType().FullName);
  48. if (_isEndOfFile)
  49. throw new SshException("Attempting to read beyond the end of the file.");
  50. lock (_readLock)
  51. {
  52. BufferedRead nextChunk;
  53. // TODO: break when we've reached file size and still haven't received an EOF ?
  54. // wait until either the next chunk is avalable or an exception has occurred
  55. while (!_queue.TryGetValue(_nextChunkIndex, out nextChunk) && _exception == null)
  56. {
  57. Monitor.Wait(_readLock);
  58. }
  59. if (_exception != null)
  60. throw _exception;
  61. if (nextChunk.Offset == _offset)
  62. {
  63. var data = nextChunk.Data;
  64. _offset += (ulong) data.Length;
  65. // remove processed chunk
  66. _queue.Remove(_nextChunkIndex);
  67. // move to next chunk
  68. _nextChunkIndex++;
  69. // have we reached EOF?
  70. if (data.Length == 0)
  71. {
  72. _isEndOfFile = true;
  73. }
  74. // unblock wait in read-ahead
  75. _semaphore.Release();
  76. return data;
  77. }
  78. // when we received an EOF for the next chunk, then we only complete the current
  79. // chunk if we haven't already read up to the file size
  80. if (nextChunk.Data.Length == 0 && _offset == _fileSize)
  81. {
  82. _isEndOfFile = true;
  83. // unblock wait in read-ahead
  84. _semaphore.Release();
  85. // signal EOF to caller
  86. return nextChunk.Data;
  87. }
  88. // when the server returned less bytes than requested (for the previous chunk)
  89. // we'll synchronously request the remaining data
  90. var bytesToCatchUp = nextChunk.Offset - _offset;
  91. // TODO: break loop and interrupt blocking wait in case of exception
  92. var read = _sftpSession.RequestRead(_handle, _offset, (uint) bytesToCatchUp);
  93. if (read.Length == 0)
  94. {
  95. // move reader to error state
  96. _exception = new SshException("Unexpectedly reached end of file.");
  97. // unblock wait in read-ahead
  98. _semaphore.Release();
  99. // notify caller of error
  100. throw _exception;
  101. }
  102. _offset += (uint) read.Length;
  103. return read;
  104. }
  105. }
  106. public void Dispose()
  107. {
  108. Dispose(true);
  109. GC.SuppressFinalize(this);
  110. }
  111. protected void Dispose(bool disposing)
  112. {
  113. if (disposing)
  114. {
  115. var readAheadCompleted = _readAheadCompleted;
  116. if (readAheadCompleted != null)
  117. {
  118. _readAheadCompleted = null;
  119. if (!readAheadCompleted.WaitOne(TimeSpan.FromSeconds(1)))
  120. {
  121. DiagnosticAbstraction.Log("Read-ahead thread did not complete within time-out.");
  122. }
  123. readAheadCompleted.Dispose();
  124. }
  125. _disposed = true;
  126. }
  127. }
  128. private void StartReadAhead()
  129. {
  130. ThreadAbstraction.ExecuteThread(() =>
  131. {
  132. while (_exception == null)
  133. {
  134. // TODO implement cancellation!?
  135. // TODO implement IDisposable to cancel the Wait in case the client never completes reading to EOF
  136. // TODO check if the BCL Semaphore unblocks wait on dispose (and mimick same behavior in our SemaphoreLight ?)
  137. _semaphore.Wait();
  138. // don't bother reading any more chunks if we reached EOF, or an exception has occurred
  139. // while processing a chunk
  140. if (_isEndOfFile || _exception != null)
  141. break;
  142. // start reading next chunk
  143. try
  144. {
  145. _sftpSession.BeginRead(_handle, _readAheadOffset, _chunkLength, ReadCompleted,
  146. new BufferedRead(_readAheadChunkIndex, _readAheadOffset));
  147. }
  148. catch (Exception ex)
  149. {
  150. HandleFailure(ex);
  151. break;
  152. }
  153. if (_readAheadOffset >= _fileSize)
  154. {
  155. // read one chunk beyond the chunk in which we read "file size" bytes
  156. // to get an EOF
  157. break;
  158. }
  159. // advance read-ahead offset
  160. _readAheadOffset += _chunkLength;
  161. _readAheadChunkIndex++;
  162. }
  163. _readAheadCompleted.Set();
  164. });
  165. }
  166. private void ReadCompleted(IAsyncResult result)
  167. {
  168. var readAsyncResult = result as SftpReadAsyncResult;
  169. if (readAsyncResult == null)
  170. return;
  171. byte[] data = null;
  172. try
  173. {
  174. data = readAsyncResult.EndInvoke();
  175. }
  176. catch (Exception ex)
  177. {
  178. HandleFailure(ex);
  179. return;
  180. }
  181. // a read that completes with a zero-byte result signals EOF
  182. // but there may be pending reads before that read
  183. var bufferedRead = (BufferedRead)readAsyncResult.AsyncState;
  184. bufferedRead.Complete(data);
  185. _queue.Add(bufferedRead.ChunkIndex, bufferedRead);
  186. // signal that a chunk has been read or EOF has been reached;
  187. // in both cases, we want to unblock the "read-ahead" thread
  188. lock (_readLock)
  189. {
  190. Monitor.PulseAll(_readLock);
  191. }
  192. }
  193. private void HandleFailure(Exception cause)
  194. {
  195. _exception = cause;
  196. // unblock read-ahead
  197. _semaphore.Release();
  198. // unblock Read()
  199. lock (_readLock)
  200. {
  201. Monitor.PulseAll(_readLock);
  202. }
  203. }
  204. internal class BufferedRead
  205. {
  206. public int ChunkIndex { get; private set; }
  207. public byte[] Data { get; private set; }
  208. public ulong Offset { get; private set; }
  209. public BufferedRead(int chunkIndex, ulong offset)
  210. {
  211. ChunkIndex = chunkIndex;
  212. Offset = offset;
  213. }
  214. public void Complete(byte[] data)
  215. {
  216. Data = data;
  217. }
  218. }
  219. }
  220. }