-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathKepwareApiClient.cs
More file actions
277 lines (247 loc) · 13 KB
/
KepwareApiClient.cs
File metadata and controls
277 lines (247 loc) · 13 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
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
using Kepware.Api.ClientHandler;
using Kepware.Api.Model;
using Kepware.Api.Serializer;
using Kepware.Api.Util;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Reflection.Metadata;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace Kepware.Api
{
/// <summary>
/// Client for interacting with the Kepware server Configuration API. Using the <see cref="KepwareApiClient"/> class
/// provides the ability to create, read, update and delete configuration of a Kepware server instance.
///
/// All handlers are defined in the <see cref="Kepware.Api.ClientHandler"/> namespace.
/// </summary>
public partial class KepwareApiClient : IKepwareDefaultValueProvider
{
/// <summary>
/// The value for an unknown client or hostname.
/// </summary>
public const string UNKNOWN = "Unknown";
private const string ENDPOINT_STATUS = "/config/v1/status";
private const string ENDPOINT_DOC = "/config/v1/doc";
private const string ENDPOINT_ABOUT = "/config/v1/about";
private readonly ILogger<KepwareApiClient> m_logger;
private readonly HttpClient m_httpClient;
private bool? m_isConnected = null;
private bool? m_hasValidCredentials = null;
/// <summary>
/// Gets the name of the client instance.
/// </summary>
public string ClientName { get; }
/// <summary>
/// Gets the hostname of the Kepware server the client is connecting to.
/// </summary>
public string ClientHostName => m_httpClient.BaseAddress?.Host ?? UNKNOWN;
/// <summary>
/// Gets the client options for the Kepware server connection.
/// </summary>
public KepwareApiClientOptions ClientOptions { get; init; }
/// <summary>
/// Gets the generic configuration handlers.
/// </summary>
/// <remarks> See <see cref="Kepware.Api.ClientHandler.GenericApiHandler"/> for method references.</remarks>
public GenericApiHandler GenericConfig { get; init; }
/// <summary>
/// Gets the project handlers.
/// </summary>
/// <remarks> See <see cref="Kepware.Api.ClientHandler.ProjectApiHandler"/> for method references.</remarks>
public ProjectApiHandler Project { get; init; }
/// <summary>
/// Gets the admin handlers.
/// </summary>
/// <remarks> See <see cref="Kepware.Api.ClientHandler.AdminApiHandler"/> for method references.</remarks>
public AdminApiHandler Admin { get; init; }
/// <summary>
/// Gets the services handlers.
/// </summary>
/// <remarks> See <see cref="Kepware.Api.ClientHandler.ServicesApiHandler"/> for method references.</remarks>
public ServicesApiHandler ApiServices { get; init; }
internal HttpClient HttpClient { get { return m_httpClient; } }
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="KepwareApiClient"/> class. This class
/// represents a connection to an instance of Kepware. An instance of this is
/// used in all configuration calls done.
/// </summary>
/// <param name="options">The client options as <see cref="KepwareApiClientOptions"/>.</param>
/// <param name="loggerFactory">The loggerFactory instance.</param>
/// <param name="httpClient">The <see cref="HttpClient"/> instance for the connection.</param>
public KepwareApiClient(KepwareApiClientOptions options, ILoggerFactory loggerFactory, HttpClient httpClient)
: this(UNKNOWN, options, loggerFactory, httpClient)
{
m_logger.LogInformation("Created KepwareApiClient instance with name {ClientName} at {BaseAddress}", ClientName, m_httpClient.BaseAddress);
m_logger.LogInformation("KepwareApiClient instance created successfully.");
}
internal KepwareApiClient(string name, KepwareApiClientOptions options, ILoggerFactory loggerFactory, HttpClient httpClient)
{
ArgumentNullException.ThrowIfNull(loggerFactory);
ArgumentNullException.ThrowIfNull(httpClient);
m_logger = loggerFactory.CreateLogger<KepwareApiClient>();
m_httpClient = httpClient;
ClientName = name;
ClientOptions = options;
GenericConfig = new GenericApiHandler(this, loggerFactory.CreateLogger<GenericApiHandler>());
var channelsApiHandler = new ChannelApiHandler(this, loggerFactory.CreateLogger<ChannelApiHandler>());
var devicesApiHandler = new DeviceApiHandler(this, loggerFactory.CreateLogger<DeviceApiHandler>());
Project = new ProjectApiHandler(this, channelsApiHandler, devicesApiHandler, loggerFactory.CreateLogger<ProjectApiHandler>());
Admin = new AdminApiHandler(this, loggerFactory.CreateLogger<AdminApiHandler>());
ApiServices = new ServicesApiHandler(this, loggerFactory.CreateLogger<ServicesApiHandler>());
}
#endregion
#region connection test & product info
/// <summary>
/// Tests the connection to the Kepware server and checks if the server runtime is healthy. Uses the
/// /config/v1/status endpoint for health verification.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains a boolean indicating whether the connection was successful.</returns>
public async Task<bool> TestConnectionAsync(CancellationToken cancellationToken = default)
{
bool blnIsConnected = false;
try
{
if (m_isConnected == null) // first time after connection change
{
m_logger.LogInformation("Connecting to {ClientName}-client at {BaseAddress}...", ClientName, m_httpClient.BaseAddress);
}
var response = await m_httpClient.GetAsync(ENDPOINT_STATUS, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var status = await JsonSerializer.DeserializeAsync(
await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false),
KepJsonContext.Default.ListApiStatus, cancellationToken)
.ConfigureAwait(false);
if (status?.FirstOrDefault()?.Healthy == true)
{
blnIsConnected = true;
}
}
if (m_isConnected == null || (m_isConnected != null && m_isConnected != blnIsConnected)) // first time after connection change or when connection is lost
{
if (!blnIsConnected)
{
m_logger.LogWarning("Failed to connect to {ClientName}-client at {BaseAddress}, Reason: {ReasonPhrase}", ClientName, m_httpClient.BaseAddress, response.ReasonPhrase);
}
else
{
var prodInfo = await GetProductInfoAsync(cancellationToken).ConfigureAwait(false);
m_logger.LogInformation("Successfully connected to {ClientName}-client: {ProductName} {ProductVersion} on {BaseAddress}", ClientName, prodInfo?.ProductName, prodInfo?.ProductVersion, m_httpClient.BaseAddress);
m_hasValidCredentials = await TestCredentialsAsync(cancellationToken).ConfigureAwait(false);
}
}
}
catch (HttpRequestException httpEx)
{
if (m_isConnected == null || m_isConnected == true) // first time after connection change or when connection is lost
m_logger.LogWarning("Failed to connect to {ClientName}-client at {BaseAddress}, Reason: {Message}", ClientName, m_httpClient.BaseAddress, httpEx.Message);
}
m_isConnected = blnIsConnected;
return blnIsConnected && m_hasValidCredentials == true;
}
/// <summary>
/// Gets the product information from the Kepware server which includes product name and version information.
/// Uses the /config/v1/about endpoint
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the product information.</returns>
public async Task<ProductInfo?> GetProductInfoAsync(CancellationToken cancellationToken = default)
{
try
{
var response = await m_httpClient.GetAsync(ENDPOINT_ABOUT, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
var prodInfo = JsonSerializer.Deserialize(content, KepJsonContext.Default.ProductInfo);
m_isConnected = true;
return prodInfo;
}
else
{
m_logger.LogWarning("Failed to get product info from endpoint {Endpoint}, Reason: {ReasonPhrase}", "/config/v1/about", response.ReasonPhrase);
}
}
catch (HttpRequestException httpEx)
{
m_logger.LogWarning(httpEx, "Failed to connect to {ClientName}-client at {BaseAddress}: {Message}", ClientName, m_httpClient.BaseAddress, httpEx.Message);
m_isConnected = null;
}
catch (JsonException jsonEx)
{
m_logger.LogWarning(jsonEx, "Failed to parse ProductInfo from {BaseAddress}", m_httpClient.BaseAddress);
}
return null;
}
private async Task<bool> TestCredentialsAsync(CancellationToken cancellationToken = default)
{
bool hasValidCredentials = false;
try
{
var response = await m_httpClient.GetAsync(ENDPOINT_DOC, cancellationToken).ConfigureAwait(false);
hasValidCredentials = response.IsSuccessStatusCode;
if (hasValidCredentials)
{
// credentials are valid
}
else
{
// log a warning, that we don't have valid credentials
m_logger.LogWarning("Failed to connect to {ClientName}-client at {BaseAddress} with valid credentials, Reason: {ReasonPhrase}",
ClientName, m_httpClient.BaseAddress, response.ReasonPhrase);
}
}
catch (HttpRequestException httpEx)
{
m_logger.LogWarning(httpEx, "Failed to connect to {ClientName}-client at {BaseAddress}", ClientName, m_httpClient.BaseAddress);
}
return hasValidCredentials;
}
#endregion
#region IKepwareDefaultValueProvider
private readonly ConcurrentDictionary<string, ReadOnlyDictionary<string, JsonElement>> m_driverDefaultValues = [];
async Task<ReadOnlyDictionary<string, JsonElement>> IKepwareDefaultValueProvider.GetDefaultValuesAsync(string driverName, string entityName, CancellationToken cancellationToken)
{
var key = $"{driverName}/{entityName}";
if (m_driverDefaultValues.TryGetValue(key, out var deviceDefaults))
{
return deviceDefaults;
}
else
{
Docs.CollectionDefinition collectionDefinition = entityName switch
{
nameof(Channel) => await GenericConfig.GetChannelPropertiesAsync(driverName, cancellationToken),
nameof(Device) => await GenericConfig.GetDevicePropertiesAsync(driverName, cancellationToken),
_ => Docs.CollectionDefinition.Empty,
};
var defaults = collectionDefinition?.PropertyDefinitions?
.Where(p => !string.IsNullOrEmpty(p.SymbolicName) && p.SymbolicName != Properties.Channel.DeviceDriver)
.ToDictionary(p => p.SymbolicName!, p => p.GetDefaultValue()) ?? [];
return m_driverDefaultValues[key] = new ReadOnlyDictionary<string, JsonElement>(defaults);
}
}
#endregion
#region internal
/// <summary>
/// Invoked by Handler, when they receice a http request exception
/// </summary>
/// <param name="httpEx"></param>
internal void OnHttpRequestException(HttpRequestException httpEx)
{
m_isConnected = null;
}
#endregion
}
}