forked from MichaCo/DnsClient.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomCommand.cs
More file actions
212 lines (179 loc) · 8.03 KB
/
RandomCommand.cs
File metadata and controls
212 lines (179 loc) · 8.03 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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DnsClient;
using McMaster.Extensions.CommandLineUtils;
namespace DigApp
{
public class RandomCommand : DnsCommand
{
private static readonly Random s_randmom = new Random();
private readonly ConcurrentDictionary<string, int> _errorsPerCode = new ConcurrentDictionary<string, int>();
private readonly ConcurrentDictionary<NameServer, int> _successByServer = new ConcurrentDictionary<NameServer, int>();
private readonly ConcurrentDictionary<NameServer, int> _failByServer = new ConcurrentDictionary<NameServer, int>();
private ConcurrentQueue<string> _domainNames;
private int _clients;
private int _runtime;
private long _reportExcecutions = 0;
private long _allExcecutions = 0;
private bool _running;
private LookupClientOptions _settings;
private LookupClient _lookup;
private int _errors;
private int _success;
private Spiner _spinner;
private bool _runSync;
public CommandOption ClientsArg { get; private set; }
public CommandOption RuntimeArg { get; private set; }
public CommandOption SyncArg { get; private set; }
public RandomCommand(CommandLineApplication app, string[] originalArgs) : base(app, originalArgs)
{
}
public string NextDomainName()
{
while (true)
{
if (_domainNames.TryDequeue(out string result))
{
_domainNames.Enqueue(result);
return result;
}
}
}
protected override void Configure()
{
ClientsArg = App.Option("-c | --clients", "Number of clients to run", CommandOptionType.SingleValue);
RuntimeArg = App.Option("-r | --run", "Time in seconds to run", CommandOptionType.SingleValue);
SyncArg = App.Option("--sync", "Run synchronous api", CommandOptionType.NoValue);
base.Configure();
}
protected override async Task<int> Execute()
{
var lines = File.ReadAllLines("names.txt");
_domainNames = new ConcurrentQueue<string>(lines.Select(p => p.Substring(p.IndexOf(',', StringComparison.Ordinal) + 1)).OrderBy(x => s_randmom.Next(0, lines.Length * 2)));
_clients = ClientsArg.HasValue() ? int.Parse(ClientsArg.Value()) : 10;
_runtime = RuntimeArg.HasValue() ? int.Parse(RuntimeArg.Value()) <= 1 ? 5 : int.Parse(RuntimeArg.Value()) : 5;
_runSync = SyncArg.HasValue();
_settings = GetLookupSettings();
_settings.EnableAuditTrail = false;
_settings.ThrowDnsErrors = false;
_settings.ContinueOnDnsError = false;
_lookup = GetDnsLookup(_settings);
_running = true;
Console.WriteLine($"; <<>> Starting random run with {_clients} clients running for {_runtime} seconds <<>>");
Console.WriteLine($"; ({_settings.NameServers.Count} Servers, caching:{_settings.UseCache}, minttl:{_settings.MinimumCacheTimeout?.TotalMilliseconds})");
_spinner = new Spiner();
_spinner.Start();
var sw = Stopwatch.StartNew();
var timeoutTask = Task.Delay(_runtime * 1000).ContinueWith((t) =>
{
_running = false;
});
var tasks = new List<Task>
{
timeoutTask
};
for (var clientIndex = 0; clientIndex < _clients; clientIndex++)
{
tasks.Add(ExcecuteRun());
}
tasks.Add(CollectPrint());
try
{
await Task.WhenAny(tasks.ToArray()).ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
double elapsedSeconds = sw.ElapsedMilliseconds / 1000d;
// results
_spinner.Stop();
Console.WriteLine(string.Join("-", Enumerable.Repeat("-", 50)));
Console.WriteLine($";; results:\t\t");
Console.WriteLine(string.Join("-", Enumerable.Repeat("-", 50)));
Console.WriteLine($";; run for {elapsedSeconds}sec {_clients} clients.");
//var successPercent = _errors == 0 ? 100 : _success == 0 ? 0 : (100 - (double)_success / (_errors * (double)_success));
var successPercent = _errors == 0 ? 100 : _success == 0 ? 0 : (100 - ((double)_errors / (_success) * 100));
Console.WriteLine($";; {_errors:N0} errors {_success:N0} ok {successPercent:N2}% success.");
foreach (var code in _errorsPerCode.Keys)
{
Console.WriteLine($"{code,30}:\t {_errorsPerCode[code]}");
}
var execPerSec = _allExcecutions / elapsedSeconds;
Console.WriteLine($";; {execPerSec:N2} queries per second.");
return 0;
}
private async Task CollectPrint()
{
var waitCount = 0;
while (_running && waitCount < _runtime)
{
waitCount++;
await Task.Delay(1000).ConfigureAwait(false);
var serverUpdate = from good in _successByServer
join fail in _failByServer on good.Key equals fail.Key into all
from row in all.DefaultIfEmpty()
select new
{
good.Key,
Fails = row.Value,
Success = good.Value
};
var updateString = string.Join(" | ", serverUpdate.Select((p, i) => $"Server{i}: +{p.Success} -{p.Fails}"));
_spinner.Status = $"{_reportExcecutions:N2} req/sec {_allExcecutions:N0} total - [{updateString}]";
Interlocked.Exchange(ref _reportExcecutions, 0);
}
_running = false;
}
private async Task ExcecuteRun()
{
//var swatch = Stopwatch.StartNew();
while (_running)
{
var query = NextDomainName();
try
{
IDnsQueryResponse response = null;
_spinner.Message = query;
if (!_runSync)
{
response = await _lookup.QueryAsync(query, QueryType.A).ConfigureAwait(false);
}
else
{
response = await Task.Run(() => _lookup.Query(query, QueryType.A)).ConfigureAwait(false);
}
Interlocked.Increment(ref _allExcecutions);
Interlocked.Increment(ref _reportExcecutions);
if (response.HasError)
{
_errorsPerCode.AddOrUpdate(response.Header.ResponseCode.ToString(), 1, (c, v) => v + 1);
_failByServer.AddOrUpdate(response.NameServer, 1, (n, v) => v + 1);
Interlocked.Increment(ref _errors);
}
else
{
_successByServer.AddOrUpdate(response.NameServer, 1, (n, v) => v + 1);
Interlocked.Increment(ref _success);
}
}
catch (DnsResponseException ex)
{
_errorsPerCode.AddOrUpdate(ex.Code.ToString(), 1, (c, v) => v + 1);
Interlocked.Increment(ref _errors);
}
catch (Exception ex)
{
_errorsPerCode.AddOrUpdate(ex.GetType().Name, 1, (c, v) => v + 1);
Interlocked.Increment(ref _errors);
}
}
}
}
}