SessionLogReader.cs 9.1 KB

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