SessionLogReader.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. result = false;
  117. }
  118. else
  119. #endif
  120. {
  121. // check if the the root cause was session abort
  122. Session.CheckForTimeout();
  123. LogContents();
  124. string message = "Error parsing session log file";
  125. // This is possibly a race condition, as we may not have processed the event with the error yet
  126. // The ExeSessionProcess loops every 100ms
  127. Thread.Sleep(200);
  128. string s = Session.GetErrorOutputMessage();
  129. if (!string.IsNullOrEmpty(s))
  130. {
  131. message += " - " + s;
  132. }
  133. throw Session.Logger.WriteException(new SessionLocalException(Session, message, e));
  134. }
  135. }
  136. if (!result && !_closed)
  137. {
  138. Session.Logger.WriteLine("Waiting for log update and dispatching events for {0}", interval);
  139. Session.DispatchEvents(interval);
  140. if (interval < 500)
  141. {
  142. interval *= 2;
  143. }
  144. }
  145. }
  146. while (!result && !_closed);
  147. if (result)
  148. {
  149. LogContents();
  150. }
  151. return result;
  152. }
  153. private void LogContents()
  154. {
  155. if (Session.Logger.Logging)
  156. {
  157. try
  158. {
  159. // alterative to File.ReadAllText with write-sharing
  160. // (note that the StreamReader disposes the Stream)
  161. using (StreamReader reader = new StreamReader(new FileStream(Session.XmlLogPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8))
  162. {
  163. string contents = reader.ReadToEnd();
  164. if ((_logged == null) || (_logged != contents))
  165. {
  166. Session.Logger.WriteLine("Log contents:\n{0}", contents);
  167. _logged = contents;
  168. }
  169. else
  170. {
  171. Session.Logger.WriteLine("Log contents has not changed");
  172. }
  173. }
  174. }
  175. catch (Exception e)
  176. {
  177. Session.Logger.WriteLine("Error logging log contents [{0}]", e.Message);
  178. }
  179. }
  180. }
  181. private void OpenLog()
  182. {
  183. if (_closed)
  184. {
  185. throw Session.Logger.WriteException(new InvalidOperationException("Log was closed already"));
  186. }
  187. try
  188. {
  189. Session.Logger.WriteLine("Opening log without write sharing");
  190. // First try to open file without write sharing.
  191. // This fails, if WinSCP is still writing to the log file.
  192. // This is done only as a way to detect that log file is not complete yet.
  193. _stream = new PatientFileStream(Session, Session.XmlLogPath, FileMode.Open, FileAccess.Read, FileShare.Read);
  194. _closed = true;
  195. LogContents();
  196. }
  197. catch (IOException)
  198. {
  199. Session.Logger.WriteLine("Opening log with write sharing");
  200. // If log file is still being written to, open it with write sharing
  201. _stream = new PatientFileStream(Session, Session.XmlLogPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  202. _closed = false;
  203. }
  204. Session.Logger.WriteLine("Log opened");
  205. _reader = XmlReader.Create(_stream);
  206. int skip = _position;
  207. Session.Logger.WriteLine("Skipping {0} nodes", skip);
  208. while (skip > 0)
  209. {
  210. if (!_reader.Read())
  211. {
  212. throw Session.Logger.WriteException(new SessionLocalException(Session, "Read less nodes than in previous log parsing"));
  213. }
  214. --skip;
  215. }
  216. }
  217. internal override XmlReader Reader
  218. {
  219. get
  220. {
  221. if (_reader == null)
  222. {
  223. throw Session.Logger.WriteException(new SessionLocalException(Session, "Reading has not commenced yet"));
  224. }
  225. return _reader;
  226. }
  227. }
  228. private int _position;
  229. private XmlReader _reader;
  230. private PatientFileStream _stream;
  231. private bool _closed;
  232. private string _logged;
  233. }
  234. }