forked from sbozzie/test-intel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntelChannel.cs
More file actions
923 lines (857 loc) · 36 KB
/
Copy pathIntelChannel.cs
File metadata and controls
923 lines (857 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
using PleaseIgnore.IntelMap.Properties;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
namespace PleaseIgnore.IntelMap {
/// <summary>
/// Monitors the log directory for new log entries to a specific
/// channel.
/// </summary>
/// <threadsafety static="true" instance="true"/>
/// <remarks>
/// <para>When running, <see cref="IntelChannel"/> makes use of the
/// <see cref="ThreadPool"/> to perform background operations. The
/// following sequence of events are processed:</para>
/// <list type="number">
/// <item>
/// <term><see cref="OnStart"/></term>
/// <description>Called after the initial call to
/// <see cref="Start()"/>. Responsible for initializing the
/// internal operations and searching the log directory for
/// possible active logs. Will not be called by subsequent
/// calls to <see cref="Start()"/> unless an intervening call
/// to <see cref="Stop()"/> has been made.</description>
/// </item>
/// <item>
/// <term><see cref="OnFileCreated"/></term>
/// <description>Generated by an internal instance of
/// <see cref="FileSystemWatcher"/> to notify us of new files
/// being created within the log directory, allowing us to
/// switch to newer log files.</description>
/// </item>
/// <item>
/// <term><see cref="OnFileChanged"/></term>
/// <description>Generated by an internal instance of
/// <see cref="FileSystemWatcher"/> to notify us of changes
/// to files in the log directory, allowing us to rescan and
/// reopen log files appropriately. Unfortunately, due to
/// performance optimizations in Windows, change notifications
/// are often sent when the file is <em>closed</em>, not when
/// new data has been written to the file.</description>
/// </item>
/// <item>
/// <term><see cref="OnTick"/></term>
/// <description>Generated periodically by the
/// <see cref="ThreadPool"/> to allow us to rescan the log
/// files. Has primary responsibility for generating
/// <see cref="IntelReported"/> events.</description>
/// </item>
/// <item>
/// <term><see cref="OnStop"/></term>
/// <description>Called after the initial call to
/// <see cref="Stop()"/>. Destroys all internal tracking
/// structures. Will be not be called by subsequent calls
/// to <see cref="Stop()"/> unless an intervening call to
/// <see cref="Start()"/> has been made.</description>
/// </item>
/// </list>
/// <note>Internal <see langword="protected"/> and <see langword="virtual"/>
/// members are provided for the benefit of user testing. Redefinition may
/// lead to behavior defects or loss of thread safety.</note>
/// </remarks>
[DefaultEvent("IntelReported"), DefaultProperty("Name")]
public class IntelChannel : Component {
// Internal members should not be referenced by any other class within
// PleaseIgnore.IntelMap. They are made internal purely for the
// benefit of implementing unit tests.
/// <summary>
/// Regular Expression used to break apart each entry in the log file.
/// </summary>
private static readonly Regex Parser = new Regex(
"^\uFEFF?" + @"\[\s*(\d{4})\.(\d{2})\.(\d{2})\s+(\d{2}):(\d{2}):(\d{2})\s*\](.*)$",
RegexOptions.CultureInvariant);
/// <summary>
/// Regular Expression used to extract the timestamp from the filename.
/// </summary>
private static readonly Regex FilenameParser = new Regex(
@"_(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})\.txt$",
RegexOptions.CultureInvariant);
/// <summary>
/// Default directory to find EVE logs
/// </summary>
private static readonly string defaultLogDirectory = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"EVE",
"logs",
"Chatlogs");
/// <summary>
/// The timer period to use when scheduling the timer
/// </summary>
private const int timerPeriod = 5000;
/// <summary>
/// The default value for expireLog
/// </summary>
private const string defaultExpireLog = "00:30:00";
/// <summary>
/// Synchronization primitive
/// </summary>
internal readonly object syncRoot = new object();
/// <summary>
/// Raises the periodic timer for log scanning
/// </summary>
private readonly Timer logTimer;
/// <summary>
/// The local file system watcher object
/// </summary>
private FileSystemWatcher watcher;
/// <summary>
/// The channel file name stub
/// </summary>
[ContractPublicPropertyName("Name")]
private string channelFileName;
/// <summary>
/// The path to search for EVE chat logs
/// </summary>
[ContractPublicPropertyName("Path")]
private string logDirectory = defaultLogDirectory;
/// <summary>
/// The current component status
/// </summary>
[ContractPublicPropertyName("Status")]
private IntelStatus status;
/// <summary>
/// The <see cref="TextReader"/> being used to parse the log file.
/// </summary>
private StreamReader reader;
/// <summary>
/// The log file currently being monitored.
/// </summary>
[ContractPublicPropertyName("LogFile")]
private FileInfo logFile;
/// <summary>
/// The last time we parsed a log entry from the current log
/// </summary>
private DateTime lastEntry;
/// <summary>
/// The time to wait before calling a log file "dead"
/// </summary>
[ContractPublicPropertyName("LogExpiration")]
private TimeSpan expireLog = TimeSpan.Parse(
defaultExpireLog,
CultureInfo.InvariantCulture);
/// <summary>
/// "User" that sends the channel MOTD (and should be ignored).
/// </summary>
private const string MotdPrefix = " EVE System >";
/// <summary>
/// Initializes a new instance of the <see cref="IntelChannel" /> class.
/// </summary>
public IntelChannel() : this(null, null) {
}
/// <summary>
/// Initializes a new instance of the <see cref="IntelChannel" /> class
/// with the specified <see cref="Name" />.
/// </summary>
/// <param name="name">The initial value for <see cref="Name" />.</param>
public IntelChannel(string name)
: this(name, null) {
}
/// <summary>
/// Initializes a new instance of the <see cref="IntelChannel" /> class
/// with the specified <see cref="Container" />.
/// </summary>
/// <param name="container">Optional parent <see cref="Container" />.</param>
public IntelChannel(IContainer container)
: this(null, container) {
}
/// <summary>
/// Initializes a new instance of the <see cref="IntelChannel" /> class
/// with the specified <see cref="Name" /> and <see cref="Container" />.
/// </summary>
/// <param name="name">The initial value for <see cref="Name" />.</param>
/// <param name="container">Optional parent <see cref="Container" />.</param>
public IntelChannel(string name, IContainer container) {
this.channelFileName = name;
this.logTimer = new Timer(this.timer_Callback);
if (container != null) {
container.Add(this);
}
}
/// <summary>
/// Occurs when a new log entry has been read from the chat logs.
/// </summary>
public event EventHandler<IntelEventArgs> IntelReported;
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets the default directory to search for EVE chat logs.
/// </summary>
/// <value>
/// The default directory to search for EVE chat logs, constructed
/// from the user's profile directory and other information.
/// </value>
public static string DefaultPath {
get {
Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
return defaultLogDirectory;
}
}
/// <summary>
/// Gets or sets the directory to search for log files.
/// </summary>
/// <value>
/// The directory to search for log files. If this directory does not
/// exist, <see cref="Status" /> will be set to
/// <see cref="IntelStatus.InvalidPath" /> and <see cref="IntelChannel" />
/// will periodically check if the directory exists.
/// </value>
public string Path {
get {
Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
return this.logDirectory;
}
set {
Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value));
lock (this.syncRoot) {
if (value != this.logDirectory) {
this.logDirectory = value;
if (this.watcher != null) {
try {
this.watcher.Path = value;
this.ScanFiles();
} catch (ArgumentException) {
this.watcher.Dispose();
this.watcher = null;
this.Status = IntelStatus.InvalidPath;
}
}
this.OnPropertyChanged("Path");
}
}
}
}
/// <summary>
/// Gets or sets the channel name of this <see cref="IntelChannel" />.
/// </summary>
/// <value>
/// The channel name of this <see cref="IntelChannel" />, used as the
/// basename when searching for log files.
/// </value>
/// <exception cref="InvalidOperationException">
/// Attempt to modify <see cref="Name"/> while <see cref="IsRunning"/>
/// is <see langword="true"/>.
/// </exception>
[DefaultValue((string)null)]
public string Name {
get {
Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>())
|| !this.IsRunning);
var channelName = this.channelFileName;
var site = this.Site;
if (!String.IsNullOrEmpty(channelName)) {
return channelName;
} else if (site != null) {
return site.Name;
} else {
return null;
}
}
set {
lock (this.syncRoot) {
if (this.IsRunning) {
throw new InvalidOperationException();
}
this.channelFileName = value;
}
}
}
/// <summary>
/// Gets the number of reports that have been made by this
/// <see cref="IntelChannel" />.
/// </summary>
/// <value>
/// The number of times <see cref="IntelReported"/> has been
/// raised.
/// </value>
public int IntelCount { get; private set; }
/// <summary>
/// Gets the log file currently being observed for new intel.
/// </summary>
/// <value>
/// An instance of <see cref="FileInfo"/> describing the log file
/// being monitoring.
/// </value>
public FileInfo LogFile {
get { return this.logFile; }
private set {
Contract.Ensures(this.LogFile == value);
if (this.logFile != value) {
this.logFile = value;
this.OnPropertyChanged("LogFile");
}
}
}
/// <summary>
/// Gets the current operational status of the <see cref="IntelChannel"/>
/// component.
/// </summary>
/// <value>
/// A value from the <see cref="IntelStatus"/> enumeration describing
/// the current operational status of the <see cref="IntelChannel"/>.
/// </value>
public virtual IntelStatus Status {
get {
return this.status;
}
private set {
Contract.Ensures(Status == value);
if (this.status != value) {
this.status = value;
var period = ((value == IntelStatus.Active)
|| (value == IntelStatus.InvalidPath))
? timerPeriod : Timeout.Infinite;
this.logTimer.Change(period, period);
this.OnPropertyChanged("Status");
}
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="IntelChannel" />
/// is currently running and watching for log entries.
/// </summary>
/// <value>
/// <see langword="true"/> if this instance is running; otherwise,
/// <see langword="false" />.
/// </value>
public bool IsRunning { get { return this.Status.IsRunning(); } }
/// <summary>
/// Gets or sets the expiration time on a log file.
/// </summary>
/// <value>
/// A <see cref="TimeSpan"/> representing the maximum time since the
/// most recent log entry before the log is deemed inactive and closed.
/// </value>
[DefaultValue(typeof(TimeSpan), defaultExpireLog)]
public TimeSpan LogExpiration {
get {
Contract.Ensures(Contract.Result<TimeSpan>() > TimeSpan.Zero);
return this.expireLog;
}
set {
Contract.Requires<ArgumentOutOfRangeException>(
value > TimeSpan.Zero,
"value");
Contract.Ensures(LogExpiration == value);
lock (this.syncRoot) {
if (this.expireLog != value) {
this.expireLog = value;
this.OnPropertyChanged("LogExpiration");
}
}
}
}
/// <summary>
/// Initiate the acquisition of log entries from the EVE chat logs. This
/// method enables <see cref="IntelReported"/> events.
/// </summary>
/// <seealso cref="Stop"/>
public virtual void Start() {
Contract.Requires<ObjectDisposedException>(
Status != IntelStatus.Disposed,
null);
Contract.Requires<InvalidOperationException>(
!String.IsNullOrEmpty(Name));
Contract.Ensures(Status != IntelStatus.Stopped);
Contract.Ensures(IsRunning);
lock (this.syncRoot) {
try {
if (this.status == IntelStatus.Stopped) {
this.Status = IntelStatus.Starting;
this.channelFileName = this.Name;
this.OnStart();
if (this.status == IntelStatus.Starting) {
this.Status = IntelStatus.Waiting;
}
}
} catch {
this.Status = IntelStatus.FatalError;
throw;
}
}
}
/// <summary>
/// Stops the <see cref="IntelChannel"/> from monitoring for new log
/// entries.
/// </summary>
/// <seealso cref="Start"/>
public virtual void Stop() {
Contract.Ensures((Status == IntelStatus.Stopped)
|| (Status == IntelStatus.Disposed));
Contract.Ensures(!IsRunning);
lock (this.syncRoot) {
if ((this.status != IntelStatus.Stopped)
&& (this.status != IntelStatus.Disposed)) {
try {
this.Status = IntelStatus.Stopping;
this.OnStop();
this.Status = IntelStatus.Stopped;
} catch {
this.status = IntelStatus.FatalError;
throw;
}
}
}
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="IntelChannel"/>
/// and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">
/// <see langword="true"/> to release both managed and unmanaged
/// resources; <see langword="false"/> to release only unmanaged
/// resources.
/// </param>
protected override void Dispose(bool disposing) {
Contract.Ensures(Status == IntelStatus.Disposed);
try {
if (disposing) {
lock (this.syncRoot) {
if (this.status != IntelStatus.Disposed) {
// Normal shutdown
var isRunning = this.IsRunning;
this.Status = IntelStatus.Disposing;
if (isRunning) {
this.OnStop();
}
// Dispose child objects
this.logTimer.Dispose();
// Clear any lingering object references
this.IntelReported = null;
this.PropertyChanged = null;
}
}
}
} finally {
this.status = IntelStatus.Disposed;
}
base.Dispose(disposing);
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this
/// instance of <see cref="IntelChannel" />.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance
/// of <see cref="IntelChannel" />.
/// </returns>
public override string ToString() {
return String.Format(
CultureInfo.CurrentCulture,
Resources.IntelChannel_ToString,
this.GetType().Name,
this.Name ?? Resources.IntelChannel_NoName,
this.Status);
}
/// <summary>
/// Creates the instance of <see cref="FileSystemWatcher" /> used
/// to monitor the file system.
/// </summary>
/// <returns>
/// An instance of <see cref="FileSystemWatcher" /> that will be
/// used to monitor the directory for the creation/modification
/// of log files.
/// </returns>
/// <remarks>
/// <see cref="CreateFileSystemWatcher" /> will be called from within
/// a synchronized context so derived classes should not attempt to
/// perform any additional synchronization themselves.
/// </remarks>
protected virtual FileSystemWatcher CreateFileSystemWatcher() {
Contract.Ensures(Contract.Result<FileSystemWatcher>() != null);
var watcher = new FileSystemWatcher();
watcher.BeginInit();
watcher.Changed += this.watcher_Changed;
watcher.Created += this.watcher_Created;
watcher.EnableRaisingEvents = true;
watcher.Filter = this.Name + "_*.txt";
watcher.IncludeSubdirectories = false;
watcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.LastWrite
| NotifyFilters.DirectoryName | NotifyFilters.FileName;
watcher.Path = this.Path;
watcher.EndInit();
return watcher;
}
/// <summary>
/// Raises the <see cref="IntelReported" /> event.
/// </summary>
/// <param name="e">Arguments for the event being raised.</param>
/// <remarks>
/// <see cref="OnIntelReported" /> will be called from within
/// a synchronized context so derived classes should not attempt to
/// perform any additional synchronization themselves.
/// </remarks>
internal protected void OnIntelReported(IntelEventArgs e) {
Contract.Requires<ArgumentNullException>(e != null, "e");
ThreadPool.QueueUserWorkItem(delegate(object state) {
Contract.Requires(state is IntelEventArgs);
var handler = this.IntelReported;
if (handler != null) {
handler(this, (IntelEventArgs)state);
}
}, e);
this.lastEntry = DateTime.UtcNow;
++this.IntelCount;
this.OnPropertyChanged("IntelCount");
}
/// <summary>
/// Raises the <see cref="PropertyChanged" /> event.
/// </summary>
/// <param name="e">Arguments for the event being raised.</param>
/// <remarks>
/// <see cref="OnPropertyChanged(PropertyChangedEventArgs)" />
/// will be called from within a synchronized context so derived
/// classes should not attempt to perform any additional
/// synchronization themselves.
/// </remarks>
internal protected void OnPropertyChanged(PropertyChangedEventArgs e) {
Contract.Requires<ArgumentNullException>(e != null, "e");
Debug.Assert(String.IsNullOrEmpty(e.PropertyName)
|| (GetType().GetProperty(e.PropertyName) != null));
ThreadPool.QueueUserWorkItem(delegate(object state) {
Contract.Requires(state is PropertyChangedEventArgs);
var handler = this.PropertyChanged;
if (handler != null) {
handler(this, (PropertyChangedEventArgs)state);
}
}, e);
}
/// <summary>
/// Raises the <see cref="PropertyChanged" /> event.
/// </summary>
/// <param name="propertyName">Name of the property that has
/// changed</param>
private void OnPropertyChanged(string propertyName) {
Contract.Requires(propertyName != null);
this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Called after <see cref="Start" /> has been called.
/// </summary>
/// <remarks>
/// <see cref="OnStart" /> will be called from within a synchronized
/// context so derived classes should not attempt to perform any
/// additional synchronization themselves.
/// </remarks>
protected virtual void OnStart() {
Contract.Requires<InvalidOperationException>(
Status == IntelStatus.Starting);
Contract.Ensures((Status == IntelStatus.Active)
|| (Status == IntelStatus.Waiting)
|| (Status == IntelStatus.InvalidPath));
// Create the file system watcher object
try {
this.watcher = this.CreateFileSystemWatcher();
} catch(ArgumentException) {
this.Status = IntelStatus.InvalidPath;
}
// Open the log file with the latest timestamp in its filename
this.ScanFiles();
}
/// <summary>
/// Called when a new log file is created for the channel we
/// are monitoring.
/// </summary>
/// <param name="e">
/// Instance of <see cref="FileSystemEventArgs" /> describing the
/// new file.
/// </param>
/// <remarks>
/// <see cref="OnFileCreated" /> will be called from within a
/// synchronized context so derived classes should not attempt to
/// perform any additional synchronization themselves.
/// </remarks>
protected virtual void OnFileCreated(FileSystemEventArgs e) {
Contract.Requires<ArgumentNullException>(e != null, "e");
// Assume it's going to be a better file....for now
if (e.FullPath != null) {
OpenFile(new FileInfo(e.FullPath));
}
}
/// <summary>
/// Called when a log file associated with the channel we are
/// monitoring has been modified.
/// </summary>
/// <param name="e">Instance of <see cref="FileSystemEventArgs" />
/// describing the modified file.
/// </param>
/// <remarks>
/// <see cref="OnFileChanged" /> will be called from within a
/// synchronized context so derived classes should not attempt to
/// perform any additional synchronization themselves.
/// </remarks>
protected virtual void OnFileChanged(FileSystemEventArgs e) {
Contract.Requires<ArgumentNullException>(e != null, "e");
// Only process this message if we have nothing else to go on
if (this.reader == null) {
this.OpenFile(new FileInfo(e.FullPath));
}
}
/// <summary>
/// Called every couple of seconds to sweep the log file for
/// new entries.
/// </summary>
/// <remarks>
/// <see cref="OnTick" /> will be called from within a synchronized
/// context so derived classes should not attempt to perform any
/// additional synchronization themselves.
/// </remarks>
protected virtual void OnTick() {
if (this.watcher == null) {
// Try (again) to create the watcher object
try {
this.watcher = this.CreateFileSystemWatcher();
this.Status = IntelStatus.Waiting;
this.ScanFiles();
} catch (ArgumentException) {
// Still doesn't seem to exist
}
}
if (this.reader != null) {
// Read new log entries from the current log
try {
string line;
while ((line = reader.ReadLine()) != null) {
Trace.WriteLine("R " + line, IntelExtensions.WebTraceCategory);
var match = Parser.Match(line);
if (match.Success && !match.Groups[7].Value.StartsWith(MotdPrefix)) {
var e = new IntelEventArgs(
this.Name,
new DateTime(
match.Groups[1].ToInt32(),
match.Groups[2].ToInt32(),
match.Groups[3].ToInt32(),
match.Groups[4].ToInt32(),
match.Groups[5].ToInt32(),
match.Groups[6].ToInt32(),
DateTimeKind.Utc),
match.Groups[7].Value);
this.OnIntelReported(e);
}
}
} catch (IOException) {
this.CloseFile();
}
// Close the log if it has been idle for too long
if (this.lastEntry + this.expireLog < DateTime.UtcNow) {
this.CloseFile();
}
}
}
/// <summary>
/// Called after <see cref="Stop" /> has been called.
/// </summary>
/// <remarks>
/// <see cref="OnStop" /> will be called from within a synchronized
/// context so derived classes should not attempt to perform any
/// additional synchronization themselves.
/// </remarks>
protected virtual void OnStop() {
Contract.Requires((Status == IntelStatus.Stopping)
|| (Status == IntelStatus.Disposing));
if (this.reader != null) {
this.reader.Close();
this.reader = null;
}
this.LogFile = null;
}
/// <summary>
/// Rescans the active directory looking for valid log files
/// </summary>
/// <returns>
/// <see langword="true" /> if we were able to open a log file;
/// otherwise, <see langword="false" />.
/// </returns>
protected bool ScanFiles() {
Contract.Requires<InvalidOperationException>(this.IsRunning);
Contract.Ensures((this.Status == IntelStatus.Waiting)
|| (this.Status == IntelStatus.Active)
|| (this.Status == IntelStatus.InvalidPath));
try {
var files = new DirectoryInfo(this.Path)
.GetFiles(this.Name + "_*.txt", SearchOption.TopDirectoryOnly);
Contract.Assert(files != null);
var downtime = IntelExtensions.LastDowntime;
var file = files
.Select(x => new {
File = x,
Match = FilenameParser.Match(x.Name)
})
.Where(x => x.Match.Success)
.Select(x => new {
File = x.File,
Timestamp = new DateTime(
x.Match.Groups[1].ToInt32(),
x.Match.Groups[2].ToInt32(),
x.Match.Groups[3].ToInt32(),
x.Match.Groups[4].ToInt32(),
x.Match.Groups[5].ToInt32(),
x.Match.Groups[6].ToInt32(),
DateTimeKind.Utc)
})
.Where(x => x.Timestamp > downtime)
.OrderByDescending(x => x.Timestamp)
.FirstOrDefault(x => this.OpenFile(x.File));
if (file == null) {
this.CloseFile();
}
return file != null;
} catch (IOException) {
return false;
}
}
/// <summary>
/// Closes the existing log file and opens a new log file.
/// </summary>
/// <param name="fileInfo">The new log file to track.</param>
/// <returns>
/// <see langword="true" /> if we were able to open the file;
/// otherwise, <see langword="false" />.
/// </returns>
internal protected bool OpenFile(FileInfo fileInfo) {
Contract.Requires<ArgumentNullException>(fileInfo != null, "fileInfo");
// Defer raising PropertyChanged until final decision is made
var status = this.status;
FileInfo logFile = null;
try {
// Close the existing file (if any)
if (this.reader != null) {
try {
this.reader.Close();
} catch (IOException) {
} finally {
this.reader = null;
}
}
// Clear the status
status = (this.watcher != null)
? IntelStatus.Waiting
: IntelStatus.InvalidPath;
// Try to open the file stream
FileStream stream = null;
try {
stream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
stream.Seek(0, SeekOrigin.End);
// XXX: We rely upon StreamReader's BOM detection. EVE seems
// to generate Little Endian UTF-16 log files. We could hard
// code that, but we don't know if that would cause other
// problems.
this.reader = new StreamReader(stream, true);
status = IntelStatus.Active;
logFile = fileInfo;
this.lastEntry = DateTime.UtcNow;
} catch (IOException) {
// Don't leak FileStream references
if (stream != null) {
try {
stream.Close();
} catch (IOException) {
}
}
}
} catch {
// Unexpected failure
status = IntelStatus.FatalError;
throw;
} finally {
// Raise any deferred PropertyChanged events
this.Status = status;
this.LogFile = logFile;
}
// Success if we opened a reader
return (this.reader != null);
}
/// <summary>
/// Closes the log file we are currently monitoring (if any).
/// </summary>
protected void CloseFile() {
Contract.Ensures((Status == IntelStatus.Waiting)
|| (Status == IntelStatus.InvalidPath));
if (this.reader != null) {
try {
this.reader.Close();
} catch (IOException) {
} finally {
this.reader = null;
}
}
this.LogFile = null;
this.Status = (this.watcher != null)
? IntelStatus.Waiting
: IntelStatus.InvalidPath;
}
/// <summary>
/// Handler for <see cref="FileSystemWatcher.Created" /> event.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="FileSystemEventArgs"/> instance
/// containing the event data.</param>
private void watcher_Created(object sender, FileSystemEventArgs e) {
Contract.Requires(e != null);
ThreadPool.QueueUserWorkItem(delegate(object state) {
Contract.Requires(state is FileSystemEventArgs);
lock (this.syncRoot) {
if (this.IsRunning) {
this.OnFileCreated((FileSystemEventArgs)e);
}
}
}, e);
}
/// <summary>
/// Handler for <see cref="FileSystemWatcher.Created" /> event.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="FileSystemEventArgs"/> instance
/// containing the event data.</param>
private void watcher_Changed(object sender, FileSystemEventArgs e) {
Contract.Requires(e != null);
ThreadPool.QueueUserWorkItem(delegate(object state) {
Contract.Requires(state is FileSystemEventArgs);
lock (this.syncRoot) {
if (this.IsRunning) {
this.OnFileChanged((FileSystemEventArgs)e);
}
}
}, e);
}
/// <summary>
/// Callback for <see cref="logTimer"/>.
/// </summary>
/// <param name="state">Ignored</param>
private void timer_Callback(object state) {
lock (this.syncRoot) {
if (this.IsRunning) {
this.OnTick();
}
}
}
/// <summary>Invariant method for Code Contracts.</summary>
[ContractInvariantMethod]
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
private void ObjectInvariant() {
Contract.Invariant(!String.IsNullOrEmpty(this.channelFileName)
|| !this.IsRunning);
Contract.Invariant(!String.IsNullOrEmpty(this.logDirectory));
Contract.Invariant(this.IntelCount >= 0);
}
}
}