SessionLogReader.cs 8.1 KB

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