/
FtpHealthCheck.cs
82 lines (67 loc) · 2.85 KB
/
FtpHealthCheck.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
using System.Net;
using HealthChecks.Network.Extensions;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace HealthChecks.Network;
public class FtpHealthCheck : IHealthCheck
{
private readonly FtpHealthCheckOptions _options;
public FtpHealthCheck(FtpHealthCheckOptions options)
{
_options = options ?? throw new ArgumentException(nameof(options));
}
/// <inheritdoc />
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
List<string>? errorList = null;
foreach (var (host, createFile, credentials) in _options.Hosts.Values)
{
var ftpRequest = CreateFtpWebRequest(host, createFile, credentials);
#pragma warning disable IDISP004 // Don't ignore created IDisposable
using var ftpResponse = (FtpWebResponse)await ftpRequest.GetResponseAsync().WithCancellationTokenAsync(cancellationToken).ConfigureAwait(false);
#pragma warning restore IDISP004 // Don't ignore created IDisposable
if (ftpResponse.StatusCode != FtpStatusCode.PathnameCreated && ftpResponse.StatusCode != FtpStatusCode.ClosingData)
{
(errorList ??= new()).Add($"Error connecting to ftp host {host} with exit code {ftpResponse.StatusCode}");
if (!_options.CheckAllHosts)
{
break;
}
}
}
return errorList.GetHealthState(context);
}
catch (Exception ex)
{
return new HealthCheckResult(context.Registration.FailureStatus, exception: ex);
}
}
private WebRequest CreateFtpWebRequest(string host, bool createFile = false, NetworkCredential? credentials = null)
{
#pragma warning disable SYSLIB0014 // Type or member is obsolete, see https://github.com/dotnet/docs/issues/27028
FtpWebRequest ftpRequest;
if (createFile)
{
ftpRequest = (FtpWebRequest)WebRequest.Create($"{host}/beatpulse");
if (credentials != null)
{
ftpRequest.Credentials = credentials;
}
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
using var stream = ftpRequest.GetRequestStream();
stream.Write([0x0], 0, 1);
}
else
{
ftpRequest = (FtpWebRequest)WebRequest.Create(host);
if (credentials != null)
{
ftpRequest.Credentials = credentials;
}
ftpRequest.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
}
return ftpRequest;
#pragma warning restore SYSLIB0014 // Type or member is obsolete
}
}