SessionLogReader.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Xml;
  5. using System.Text;
  6. using System.Threading;
  7. namespace WinSCP
  8. {
  9. internal class SessionLogReader : CustomLogReader
  10. {
  11. public SessionLogReader(Session session) :
  12. base(session)
  13. {
  14. _position = 0;
  15. }
  16. public override void Dispose()
  17. {
  18. using (Session.Logger.CreateCallstack())
  19. {
  20. LogContents();
  21. Cleanup();
  22. }
  23. base.Dispose();
  24. }
  25. private void Cleanup()
  26. {
  27. if (_stream != null)
  28. {
  29. Session.Logger.WriteLine("Closing log");
  30. _stream.Dispose();
  31. _stream = null;
  32. }
  33. if (_reader != null)
  34. {
  35. ((IDisposable)_reader).Dispose();
  36. _reader = null;
  37. }
  38. }
  39. public override bool Read(LogReadFlags flags)
  40. {
  41. using (Session.Logger.CreateCallstack())
  42. {
  43. bool result;
  44. bool retry;
  45. do
  46. {
  47. result = DoRead();
  48. retry = false;
  49. if (result &&
  50. IsNonEmptyElement("failure"))
  51. {
  52. SessionRemoteException e = SessionRemoteException.ReadFailure(this);
  53. Session.RaiseFailed(e);
  54. if ((flags & LogReadFlags.ThrowFailures) == 0)
  55. {
  56. retry = true;
  57. }
  58. else
  59. {
  60. throw Session.Logger.WriteException(e);
  61. }
  62. }
  63. }
  64. while (retry);
  65. return result;
  66. }
  67. }
  68. private bool DoRead()
  69. {
  70. int interval = 50;
  71. bool result;
  72. do
  73. {
  74. if (_reader == null)
  75. {
  76. OpenLog();
  77. }
  78. Debug.Assert(_reader != null);
  79. try
  80. {
  81. result = _reader.Read();
  82. if (result)
  83. {
  84. ++_position;
  85. Session.Logger.WriteLine("Read node {0}: {1} {2}{3}{4}",
  86. _position, _reader.NodeType, _reader.Name,
  87. (_reader.HasValue && !string.IsNullOrEmpty(_reader.Name) && !string.IsNullOrEmpty(_reader.Value) ? "=" : string.Empty),
  88. _reader.Value);
  89. Session.GotOutput();
  90. }
  91. else
  92. {
  93. Session.Logger.WriteLine("Cannot read");
  94. if (!_closed)
  95. {
  96. // this should not happen as when the log is not closed,
  97. // we should get XmlException on reaching the end
  98. _closed = true;
  99. Cleanup();
  100. }
  101. Session.CheckForTimeout();
  102. }
  103. }
  104. catch (XmlException e)
  105. {
  106. Cleanup();
  107. // check if the the root cause was session abort
  108. Session.CheckForTimeout();
  109. LogContents();
  110. string message = "Error parsing session log file";
  111. // This is possibly a race condition, as we may not have processed the event with the error yet
  112. // The ExeSessionProcess loops every 100ms
  113. Thread.Sleep(200);
  114. string s = Session.GetErrorOutputMessage();
  115. if (!string.IsNullOrEmpty(s))
  116. {
  117. message += " - " + s;
  118. }
  119. throw Session.Logger.WriteException(new SessionLocalException(Session, message, e));
  120. }
  121. if (!result && !_closed)
  122. {
  123. Session.Logger.WriteLine("Waiting for log update and dispatching events for {0}", interval);
  124. Session.DispatchEvents(interval);
  125. if (interval < 500)
  126. {
  127. interval *= 2;
  128. }
  129. }
  130. }
  131. while (!result && !_closed);
  132. if (result)
  133. {
  134. LogContents();
  135. }
  136. return result;
  137. }
  138. private void LogContents()
  139. {
  140. if (Session.Logger.Logging)
  141. {
  142. try
  143. {
  144. // alterative to File.ReadAllText with write-sharing
  145. // (note that the StreamReader disposes the Stream)
  146. using (StreamReader reader = new StreamReader(new FileStream(Session.XmlLogPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8))
  147. {
  148. string contents = reader.ReadToEnd();
  149. if ((_logged == null) || (_logged != contents))
  150. {
  151. Session.Logger.WriteLine("Log contents:\n{0}", contents);
  152. _logged = contents;
  153. }
  154. else
  155. {
  156. Session.Logger.WriteLine("Log contents has not changed");
  157. }
  158. }
  159. }
  160. catch (Exception e)
  161. {
  162. Session.Logger.WriteLine("Error logging log contents [{0}]", e.Message);
  163. }
  164. }
  165. }
  166. private void OpenLog()
  167. {
  168. if (_closed)
  169. {
  170. throw Session.Logger.WriteException(new InvalidOperationException("Log was closed already"));
  171. }
  172. try
  173. {
  174. Session.Logger.WriteLine("Opening log without write sharing");
  175. // First try to open file without write sharing.
  176. // This fails, if WinSCP is still writing to the log file.
  177. // This is done only as a way to detect that log file is not complete yet.
  178. _stream = new PatientFileStream(Session, Session.XmlLogPath, FileMode.Open, FileAccess.Read, FileShare.Read);
  179. _closed = true;
  180. LogContents();
  181. }
  182. catch (IOException)
  183. {
  184. Session.Logger.WriteLine("Opening log with write sharing");
  185. // If log file is still being written to, open it with write sharing
  186. _stream = new PatientFileStream(Session, Session.XmlLogPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  187. _closed = false;
  188. }
  189. Session.Logger.WriteLine("Log opened");
  190. // Allow control characters in log
  191. var settings = new XmlReaderSettings() { CheckCharacters = false };
  192. _reader = XmlReader.Create(_stream, settings);
  193. int skip = _position;
  194. Session.Logger.WriteLine("Skipping {0} nodes", skip);
  195. while (skip > 0)
  196. {
  197. if (!_reader.Read())
  198. {
  199. throw Session.Logger.WriteException(new SessionLocalException(Session, "Read less nodes than in previous log parsing"));
  200. }
  201. --skip;
  202. }
  203. }
  204. internal override XmlReader Reader
  205. {
  206. get
  207. {
  208. if (_reader == null)
  209. {
  210. throw Session.Logger.WriteException(new SessionLocalException(Session, "Reading has not commenced yet"));
  211. }
  212. return _reader;
  213. }
  214. }
  215. private int _position;
  216. private XmlReader _reader;
  217. private PatientFileStream _stream;
  218. private bool _closed;
  219. private string _logged;
  220. }
  221. }