-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimulationController.cs
283 lines (227 loc) · 8.12 KB
/
SimulationController.cs
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
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text.Json;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
namespace SimulationApi;
[ApiController]
[Route("/")]
public class SimulationController : ControllerBase
{
private readonly IEnumerable<EndpointDataSource> _endpointSources;
public SimulationController(IEnumerable<EndpointDataSource> endpointSources
)
{
_endpointSources = endpointSources;
}
[HttpGet]
public IActionResult Get()
{
return Ok(GetSystemInfo());
}
[HttpGet("delay/{ms:int?}")]
public async Task<IActionResult> Delay(int ms = 3000)
{
await Task.Delay(ms);
return Ok(GetSystemInfo());
}
[HttpGet("delay/{msMin:int}/{msMax:int}")]
public async Task<IActionResult> DelayMinMax(int msMin = 1000, int msMax = 5000)
{
var ms = new Random().Next(msMin, msMax);
await Task.Delay(ms);
return Ok(GetSystemInfo());
}
[HttpGet("cpu/{seconds:int?}/{percentage:int?}")]
public IActionResult Cpu(int seconds = 10, int percentage = 100)
{
var timeControl = new Stopwatch();
timeControl.Start();
var tasks = new List<Task>();
for (var i = 0; i < Environment.ProcessorCount; i++)
{
tasks.Add(
Task.Factory.StartNew(() =>
{
var watch = new Stopwatch();
watch.Start();
while (true)
{
if (timeControl.Elapsed.Seconds > seconds)
break;
if (watch.ElapsedMilliseconds > percentage)
{
Thread.Sleep(100 - percentage);
watch.Reset();
watch.Start();
}
}
})
);
}
Task.WaitAll(tasks.ToArray());
return Ok(GetSystemInfo());
}
[HttpGet("memory/{seconds:int?}/{sizeInM:int?}")]
public async Task<IActionResult> Memory(int seconds = 10, int sizeInM = 1024)
{
var m = 1024 * 1024;
var bs = new byte[m];
var ps = new List<IntPtr>();
for (var i = 0; i < sizeInM; i++)
{
var p = Marshal.AllocHGlobal(m);
Marshal.Copy(bs, 0, p, bs.Length);
ps.Add(p);
}
await Task.Delay(seconds * 1000);
foreach (var ptr in ps)
Marshal.FreeHGlobal(ptr);
return Ok(GetSystemInfo());
}
[HttpGet("disk/{seconds:int?}/{sizeInM:int?}")]
public async Task<IActionResult> Disk(int seconds = 10, int sizeInM = 1024)
{
var tempFile = Path.Combine(Path.GetTempPath(), $"test_file_{Guid.NewGuid().ToString()}");
var data = new byte[8192];
var rng = new Random();
await using (var stream = System.IO.File.OpenWrite(tempFile))
{
for (var i = 0; i < sizeInM * 128; i++)
{
rng.NextBytes(data);
stream.Write(data, 0, data.Length);
}
}
await Task.Delay(seconds * 1000);
System.IO.File.Delete(tempFile);
return Ok(GetSystemInfo());
}
[HttpGet("{statusCode:int}")]
public IActionResult ReturnStatusCode(int statusCode)
{
return StatusCode(statusCode);
}
[HttpGet("exception")]
public IActionResult Exception()
{
throw new Exception("Exception simulation.");
}
[HttpGet("exception/{probability:int}")]
public IActionResult ExceptionRandom(int probability = 50)
{
var gen = new Random();
if (gen.Next(100) < probability)
throw new Exception($"Exception simulation by {probability}% chance.");
return Ok(GetSystemInfo());
}
[HttpGet("crash")]
public void Crash()
{
Environment.FailFast("Application crash simulation.");
}
[HttpGet("crash/{probability:int}")]
public IActionResult CrashRandom(int probability = 50)
{
var gen = new Random();
if (gen.Next(100) < probability)
Environment.FailFast($"Crash simulation by {probability}% chance.");
return Ok(GetSystemInfo());
}
[HttpGet("exit")]
public void Exit()
{
Environment.Exit(0);
}
#region Helper Methods
private dynamic GetSystemInfo()
{
var info = new
{
Hostname = Environment.MachineName,
OsPlatform = RuntimeInformation.OSDescription,
IpAddressV4 = GetIpAddressV4(),
IpAddressV6 = GetIpAddressV6(),
IpAddressesAll = GetAllIpAddresses(),
AppName = Environment.GetEnvironmentVariable("APP_NAME"),
DotNetCoreVersion = GetNetCoreVersion(),
AspNetCoreVersion = GetAspNetCoreVersion(),
AspNetCoreEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"),
Endpoints = GetEndpoints(),
RequestHeaders = GetRequestHeaders(),
RequestIp = GetRequestIp(),
RequestPath = Request.GetEncodedUrl(),
Now = DateTimeOffset.Now.ToString(),
};
return info;
}
private string GetNetCoreVersion()
{
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.Location.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
var netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];
return string.Empty;
}
private string? GetAspNetCoreVersion()
{
var env = Environment.GetEnvironmentVariable("ASPNETCORE_VERSION");
if (env != null) return env;
return Assembly
.GetEntryAssembly()?
.GetCustomAttribute<TargetFrameworkAttribute>()?
.FrameworkName;
}
private List<string> GetAllIpAddresses()
{
return Dns.GetHostAddresses(Dns.GetHostName()).Select(_ => _.ToString()).ToList();
}
private string? GetIpAddressV4()
{
return Dns.GetHostEntry(Dns.GetHostName()).AddressList
.FirstOrDefault(_ => _.AddressFamily == AddressFamily.InterNetwork)
?.ToString();
}
private string? GetIpAddressV6()
{
return Dns.GetHostEntry(Dns.GetHostName()).AddressList
.FirstOrDefault(_ => _.AddressFamily == AddressFamily.InterNetworkV6)
?.ToString();
}
private List<string> GetEndpoints()
{
var endpoints = _endpointSources
.SelectMany(es => es.Endpoints)
.OfType<RouteEndpoint>();
return endpoints.Select(e => $"/{e.RoutePattern.RawText?.TrimStart('/')}").ToList();
}
private Dictionary<string, string> GetRequestHeaders()
{
var requestHeaders = new Dictionary<string, string>();
foreach (var (key, value) in Request.Headers)
requestHeaders.Add(key, value);
return requestHeaders;
}
private dynamic GetRequestIp()
{
var xForwardedFor = Request.Headers["X-Forwarded-For"].ToString();
var xForwardedProto = Request.Headers["X-Forwarded-Proto"].ToString();
var xForwardedHost = Request.Headers["X-Forwarded-Host"].ToString();
var dotNetCoreIp = Request.HttpContext.Connection.RemoteIpAddress?.ToString();
var ips = new
{
xForwardedFor,
xForwardedProto,
xForwardedHost,
dotNetCoreIp
};
return ips;
}
#endregion
}