-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHealthCheckServer.cs
More file actions
128 lines (115 loc) · 3.78 KB
/
HealthCheckServer.cs
File metadata and controls
128 lines (115 loc) · 3.78 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
#nullable enable
using System;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace InstDotNet;
/// <summary>
/// HTTP server for health check endpoint
/// </summary>
public static class HealthCheckServer
{
private static HttpListener? _listener;
private static Task? _serverTask;
private static CancellationTokenSource? _cts;
private static int _port = 8080;
/// <summary>
/// Start the health check HTTP server
/// </summary>
public static void Start(int port = 8080)
{
_port = port;
_cts = new CancellationTokenSource();
_listener = new HttpListener();
_listener.Prefixes.Add($"http://+:{port}/");
try
{
_listener.Start();
Console.WriteLine($"Health check server started on port {port}");
_serverTask = Task.Run(async () => await ListenAsync(_cts.Token), _cts.Token);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to start health check server on port {port}: {ex.Message}");
throw;
}
}
/// <summary>
/// Stop the health check server
/// </summary>
public static void Stop()
{
_cts?.Cancel();
_listener?.Stop();
_listener?.Close();
Console.WriteLine("Health check server stopped");
}
private static async Task ListenAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested && _listener != null && _listener.IsListening)
{
try
{
var context = await _listener.GetContextAsync().ConfigureAwait(false);
_ = Task.Run(() => HandleRequest(context), cancellationToken);
}
catch (ObjectDisposedException)
{
// Listener was closed, exit gracefully
break;
}
catch (HttpListenerException ex)
{
Console.WriteLine($"Health check server error: {ex.Message}");
if (!_listener.IsListening)
break;
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error in health check server: {ex.Message}");
}
}
}
private static void HandleRequest(HttpListenerContext context)
{
try
{
var request = context.Request;
var response = context.Response;
// Only handle GET requests to /health
if (request.HttpMethod == "GET" && request.Url?.AbsolutePath == "/health")
{
var status = HealthCheck.GetStatus();
var json = HealthCheck.GetStatusJson();
// Set status code based on health
response.StatusCode = status.Status == "healthy" ? 200 : 503;
response.ContentType = "application/json";
response.ContentEncoding = Encoding.UTF8;
var buffer = Encoding.UTF8.GetBytes(json);
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close();
}
else
{
// 404 for other paths
response.StatusCode = 404;
response.Close();
}
}
catch (Exception ex)
{
Console.WriteLine($"Error handling health check request: {ex.Message}");
try
{
context.Response.StatusCode = 500;
context.Response.Close();
}
catch
{
// Ignore errors when closing response
}
}
}
}