-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathHostsFileManager.cs
More file actions
211 lines (188 loc) · 7.91 KB
/
HostsFileManager.cs
File metadata and controls
211 lines (188 loc) · 7.91 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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Diagnostics;
using System.Threading;
namespace Microsoft.Hpc.Communicators.LinuxCommunicator.HostsFile
{
/// <summary>
/// This class abstracts a hosts file so that is can be managed by HPC.
/// </summary>
public class HostsFileManager : IDisposable
{
/// <summary>
/// The string placed in the comment field of an entry managed
/// by the cluster.
/// </summary>
public const string ManagedEntryKey = "HPC";
/// <summary>
/// The parameter name used to indicate whether the hosts file is HPC managed.
/// </summary>
public const string ManageFileParameter = "ManageFile";
/// <summary>
/// The interval to reload hosts file
/// </summary>
private const int ReloadInterval = 1000 * 60;
/// <summary>
/// Regular expression for a comment line in the text file
/// </summary>
private static readonly Regex Comment = new Regex(@"^#(?<1>.*)$");
/// <summary>
/// Regular expression for a parameter value in the comments section.
/// </summary>
private static readonly Regex CommentParameter = new Regex(@"^#\s*(?<parameter>[\w\p{Lm}\p{Nl}\p{Cf}\p{Mn}\p{Mc}\.]+)\s*=\s*(?<value>[\w\p{Lm}\p{Nl}\p{Cf}\p{Mn}\p{Mc}\.]+)");
/// <summary>
/// Regular expression for a ip entry in the text file.
/// </summary>
private static readonly Regex IpEntry = new Regex(@"^(?<ip>[0-9\.]+)\s+(?<dnsName>[^\s#]+)(\s+#(?<comment>.*))?");
/// <summary>
/// The path to the hosts file
/// </summary>
private string filepath;
/// <summary>
/// The timer to reload hosts file
/// </summary>
private Timer reloadTimer;
/// <summary>
/// The last modified date of the current loaded hosts file
/// </summary>
private DateTime lastModified = DateTime.MinValue;
/// <summary>
/// The unique update ID
/// </summary>
public Guid UpdateId
{
get;
private set;
}
/// <summary>
/// This constructor initializes the parser on a specific hosts file
/// </summary>
public HostsFileManager()
{
this.filepath = Path.Combine(Environment.SystemDirectory, @"drivers\etc\hosts");
this.ManagedEntries = new List<HostEntry>();
this.reloadTimer = new Timer(ReloadTimerEvent, null, 0, Timeout.Infinite);
}
/// <summary>
/// Gets the list of HPC managed entries in the host file.
/// </summary>
public List<HostEntry> ManagedEntries
{
get;
private set;
}
/// <summary>
/// Gets or sets a flag indicating whether the file is HPC managed
/// </summary>
public bool ManagedByHPC
{
get;
private set;
}
/// <summary>
/// Loads the contents of an existing host file. Will clear
/// the current configuration of this instance.
/// </summary>
/// <param name="path"></param>
public void ReloadTimerEvent(object param)
{
try
{
FileInfo fileInfo = new FileInfo(this.filepath);
if (!fileInfo.Exists)
{
LinuxCommunicator.Instance?.Tracer?.TraceInfo("[HostsFileManager] The hosts file doesn't exists: {0}", this.filepath);
return;
}
if (fileInfo.LastWriteTimeUtc <= this.lastModified)
{
LinuxCommunicator.Instance?.Tracer?.TraceInfo("[HostsFileManager] The hosts file isn't changed since last load");
return;
}
bool manageByHPC = false;
Dictionary<string, HostEntry> newEntries = new Dictionary<string, HostEntry>();
foreach (var line in File.ReadAllLines(this.filepath))
{
Match commentMatch = HostsFileManager.Comment.Match(line);
if (commentMatch.Success)
{
Match commentParameterMatch = HostsFileManager.CommentParameter.Match(line);
if (commentParameterMatch.Success && string.Equals(commentParameterMatch.Groups["parameter"].ToString(), ManageFileParameter, StringComparison.OrdinalIgnoreCase))
{
if (string.Equals(commentParameterMatch.Groups["value"].Value, "true", StringComparison.OrdinalIgnoreCase))
{
manageByHPC = true;
}
}
continue;
}
Match ipEntryMatch = HostsFileManager.IpEntry.Match(line);
HostEntry entry;
if (ipEntryMatch.Success &&
manageByHPC &&
!ipEntryMatch.Groups["ip"].Value.StartsWith(@"169.254") &&
ipEntryMatch.Groups["comment"].Value.Equals(HostsFileManager.ManagedEntryKey, StringComparison.OrdinalIgnoreCase) &&
HostEntry.TryCreate(ipEntryMatch.Groups["dnsName"].Value, ipEntryMatch.Groups["ip"].Value, out entry))
{
newEntries[entry.Name] = entry;
}
}
if (manageByHPC)
{
if (newEntries.Count != this.ManagedEntries.Count || !(new HashSet<HostEntry>(this.ManagedEntries)).SetEquals(new HashSet<HostEntry>(newEntries.Values)))
{
// Put the <NetworkType>.<NodeName> entries at the end of the list
var newHostList = newEntries.Values.Where(entry => !entry.Name.Contains('.')).ToList();
newHostList.AddRange(newEntries.Values.Where(entry => entry.Name.Contains('.')));
this.ManagedEntries = newHostList;
this.UpdateId = Guid.NewGuid();
LinuxCommunicator.Instance?.Tracer?.TraceInfo("[HostsFileManager] The managed host entries updated, current update Id is {0}", this.UpdateId);
}
else
{
LinuxCommunicator.Instance?.Tracer?.TraceInfo("[HostsFileManager] No update to HPC managed host entries, current update Id is {0}", this.UpdateId);
}
}
else
{
LinuxCommunicator.Instance?.Tracer?.TraceWarning("[HostsFileManager] Hosts file was not managed by HPC");
this.ManagedEntries.Clear();
}
this.ManagedByHPC = manageByHPC;
this.lastModified = fileInfo.LastWriteTimeUtc;
}
catch (Exception e)
{
LinuxCommunicator.Instance?.Tracer?.TraceWarning("[HostsFileManager] Failed to reload host file: {0}", e);
}
finally
{
try
{
this.reloadTimer.Change(ReloadInterval, Timeout.Infinite);
}
catch (Exception te)
{
LinuxCommunicator.Instance?.Tracer?.TraceWarning("[HostsFileManager] Failed to restart reload timer: {0}", te);
}
}
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool isDisposing)
{
if (isDisposing)
{
this.reloadTimer?.Dispose();
}
}
}
}