-
Notifications
You must be signed in to change notification settings - Fork 0
/
CheckMiddlewareHandler.cs
150 lines (139 loc) · 5.75 KB
/
CheckMiddlewareHandler.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
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace NetPro.Checker
{
public static class CheckMiddlewareHandler
{
private static readonly string DEFAULT_CONTENT_TYPE = "application/json";
/// <summary>
/// inclued: EnvCheck ;InfoCheck
/// </summary>
/// <param name="app"></param>
public static void UseCheck(this IApplicationBuilder app, string envPath = "/env", string infoPath = "/info")
{
app.UseEnvCheck(envPath);
app.UseInfoCheck(infoPath);
}
public static void UseEnvCheck(this IApplicationBuilder app, string path = "/env")
{
app.Map(path, s =>
{
s.Run(async context =>
{
var remoteIp = context.Connection.RemoteIpAddress;
if (!IPAddress.IsLoopback(remoteIp))
{
context.Response.StatusCode = 403;
context.Response.ContentType = "application/html";
await context.Response.WriteAsync("<font size=\"7\">403</font><br/>");
}
else
{
var env = AppEnvironment.GetAppEnvironment();
context.Response.ContentType = DEFAULT_CONTENT_TYPE;
await context.Response.WriteAsync(Serialize(env));
}
});
});
}
public static void UseInfoCheck(this IApplicationBuilder app, string path = "/info")
{
app.Map(path, s =>
{
s.Run(async context =>
{
var remoteIp = context.Connection.RemoteIpAddress;
if (!IPAddress.IsLoopback(remoteIp))
{
context.Response.StatusCode = 403;
context.Response.ContentType = "application/html";
await context.Response.WriteAsync("<font size=\"7\">403</font><br/>");
}
else
{
var configuration = app.ApplicationServices.GetService(typeof(IConfiguration)) as IConfiguration;
var info = AppInfo.GetAppInfo(configuration);
info.RequestHeaders = context.Request.Headers.ToDictionary(kv => kv.Key, kv => kv.Value.First());
//context.Response.Headers["Content-Type"] = "application/json";
context.Response.ContentType = DEFAULT_CONTENT_TYPE;
await context.Response.WriteAsync(Serialize(info));
}
});
});
}
[Obsolete("recommended to use IApplicationBuilder.UseCheck")]
public static void UseHealthCheck(this IApplicationBuilder app, string path = "/health")
{
app.Map(path, s =>
{
s.Run(async context =>
{
HealthCheckRegistry.HealthStatus status = await Task.Run(() => HealthCheckRegistry.GetStatus());
if (!status.IsHealthy)
{
// Return a service unavailable status code if any of the checks fail
context.Response.StatusCode = 503;
}
context.Response.ContentType = DEFAULT_CONTENT_TYPE;
await context.Response.WriteAsync(JsonConvert.SerializeObject(status));
});
});
}
public static async Task WriteHealthCheckUiResponse(HttpContext httpContext, HealthReport report)
{
httpContext.Response.ContentType = DEFAULT_CONTENT_TYPE;
if (report != null)
{
await httpContext.Response.WriteAsync(CreateFrom(report));
}
else
{
await httpContext.Response.WriteAsync(Serialize(new { Status = HealthStatus.Degraded.ToString() }));
}
}
private static string CreateFrom(HealthReport report)
{
if (report == null) return string.Empty;
var result = new Dictionary<string, CustomerHealthReport>();
foreach (var item in report.Entries)
{
var entry = new CustomerHealthReport
{
Data = item.Value.Data,
Description = item.Value.Description,
Duration = item.Value.Duration,
Status = item.Value.Status.ToString()
};
if (item.Value.Exception != null)
{
var message = item.Value.Exception?
.Message;
entry.Exception = message;
entry.Description = item.Value.Description ?? message;
}
result.Add(item.Key, entry);
}
return Serialize(new { Status = report.Status.ToString(), result });
}
private static string Serialize<T>(T obj)
{
return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { Formatting = Formatting.Indented });
}
}
public class CustomerHealthReport
{
public IReadOnlyDictionary<string, object> Data { get; set; }
public string Description { get; set; }
public TimeSpan Duration { get; set; }
public string Exception { get; set; }
public string Status { get; set; }
}
}