Review logging

This commit is contained in:
Jöran Malek 2024-01-14 01:11:41 +01:00
parent 6a334352be
commit 76ebb55ab7
7 changed files with 71 additions and 39 deletions

View file

@ -206,7 +206,7 @@ public sealed class KeaDhcpLeaseWatcher : IHostedService
} }
else else
{ {
await waitHandle.WaitOneAsync(stoppingToken).ConfigureAwait(continueOnCapturedContext: false); await waitHandle.WaitOneAsync(stoppingToken).ConfigureAwait(false);
} }
} }
} }

View file

@ -49,6 +49,6 @@ public class KeaService : IHostedService
var waitTask = Task.WhenAll(tasks); var waitTask = Task.WhenAll(tasks);
TaskCompletionSource taskCompletionSource = new(); TaskCompletionSource taskCompletionSource = new();
using var registration = cancellationToken.Register(s => ((TaskCompletionSource)s!).SetCanceled(), taskCompletionSource); using var registration = cancellationToken.Register(s => ((TaskCompletionSource)s!).SetCanceled(), taskCompletionSource);
await Task.WhenAny(waitTask, taskCompletionSource.Task).ConfigureAwait(continueOnCapturedContext: false); await Task.WhenAny(waitTask, taskCompletionSource.Task).ConfigureAwait(false);
} }
} }

View file

@ -4,7 +4,7 @@ public interface IMethod;
public record MethodBase(string Method); public record MethodBase(string Method);
public abstract record Method<TParam>(string Method, TParam Parameters) : MethodBase(Method) public record Method<TParam>(string Method, TParam Parameters) : MethodBase(Method)
where TParam : MethodParameters; where TParam : MethodParameters;
public record InitializeMethod(InitializeParameters Parameters) : Method<InitializeParameters>("initialize", Parameters), IMethod; public record InitializeMethod(InitializeParameters Parameters) : Method<InitializeParameters>("initialize", Parameters), IMethod;

View file

@ -1,16 +1,43 @@
using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace pdns_dhcp.PowerDns; namespace pdns_dhcp.PowerDns;
[JsonDerivedType(typeof(InitializeParameters))]
[JsonDerivedType(typeof(LookupParameters))]
public record class Parameters; public record class Parameters;
[JsonDerivedType(typeof(InitializeParameters))]
[JsonDerivedType(typeof(LookupParameters))]
public record class MethodParameters : Parameters public record class MethodParameters : Parameters
{ {
[JsonExtensionData] [JsonExtensionData]
public Dictionary<string, JsonElement> AdditionalProperties { get; set; } = []; public Dictionary<string, JsonElement> AdditionalProperties { get; set; } = [];
protected override bool PrintMembers(StringBuilder builder)
{
if (base.PrintMembers(builder))
{
builder.Append(", ");
}
builder.Append("AdditionalProperties = [");
bool append = false;
foreach (var kv in AdditionalProperties)
{
if (append)
{
builder.Append(", ");
}
append = true;
builder.Append(kv.Key);
builder.Append(" = ");
builder.Append(kv.Value);
}
builder.Append(']');
return true;
}
} }
public record class InitializeParameters( public record class InitializeParameters(

View file

@ -72,39 +72,44 @@ public class PowerDnsHandler : ConnectionHandler
continue; continue;
} }
MethodBase method;
try
{
using var jsonDocument = JsonDocument.Parse(json.WrittenMemory);
var root = jsonDocument.RootElement;
if (!root.TryGetProperty("method", out var methodElement))
{
_logger.LogWarning("Json Document missing required property method: {document}", jsonDocument);
continue;
}
if (Parse(methodElement, root.GetProperty("parameters")) is not { } methodLocal)
{
continue;
}
method = methodLocal;
}
finally
{
json.Clear();
state = default;
}
Reply reply = BoolReply.False; Reply reply = BoolReply.False;
try try
{ {
MethodBase method;
try
{
using var jsonDocument = JsonDocument.Parse(json.WrittenMemory);
var root = jsonDocument.RootElement;
if (!root.TryGetProperty("method", out var methodElement))
{
_logger.LogWarning("Json Document missing required property method: {document}", jsonDocument);
continue;
}
if (Parse(methodElement, root.GetProperty("parameters")) is not { } methodLocal)
{
continue;
}
method = methodLocal;
}
finally
{
json.Clear();
state = default;
}
reply = await Handle(method, connection.ConnectionClosed).ConfigureAwait(false); reply = await Handle(method, connection.ConnectionClosed).ConfigureAwait(false);
} }
catch (Exception e) { } catch (Exception e)
{
await JsonSerializer.SerializeAsync(writer, reply, PowerDnsSerializerContext.Default.Reply, connection.ConnectionClosed) _logger.LogError(e, "Error");
.ConfigureAwait(continueOnCapturedContext: false); }
finally
{
await JsonSerializer.SerializeAsync(writer, reply, PowerDnsSerializerContext.Default.Reply, connection.ConnectionClosed)
.ConfigureAwait(false);
}
} }
input.AdvanceTo(read.Buffer.End); input.AdvanceTo(read.Buffer.End);
@ -166,7 +171,7 @@ public class PowerDnsHandler : ConnectionHandler
return element.GetString() switch return element.GetString() switch
{ {
null => null, null => null,
{ } methodName when !Converters.TryGetValue(methodName, out converter) => new MethodBase(methodName), { } methodName when !Converters.TryGetValue(methodName, out converter) => new Method<MethodParameters>(methodName, parameters.Deserialize(PowerDnsSerializerContext.Default.MethodParameters)!),
_ => converter(parameters) _ => converter(parameters)
}; };
} }
@ -184,7 +189,7 @@ public class PowerDnsHandler : ConnectionHandler
static ValueTask<Reply> LogUnhandled(ILogger logger, MethodBase method) static ValueTask<Reply> LogUnhandled(ILogger logger, MethodBase method)
{ {
logger.LogWarning("Unhandled Method {Method}", method); logger.LogWarning("Unhandled {Method}", method);
return ValueTask.FromResult<Reply>(BoolReply.False); return ValueTask.FromResult<Reply>(BoolReply.False);
} }
} }
@ -193,7 +198,7 @@ public class PowerDnsHandler : ConnectionHandler
{ {
if (_logger.IsEnabled(LogLevel.Information)) if (_logger.IsEnabled(LogLevel.Information))
{ {
_logger.LogInformation("Handling Initialize {parameters}", parameters); _logger.LogInformation("Handling {parameters}", parameters);
} }
return ValueTask.FromResult<Reply>(BoolReply.True); return ValueTask.FromResult<Reply>(BoolReply.True);
@ -217,7 +222,7 @@ public class PowerDnsHandler : ConnectionHandler
if (_logger.IsEnabled(LogLevel.Information)) if (_logger.IsEnabled(LogLevel.Information))
{ {
_logger.LogInformation("Searching for {key} in {family}", parameters.Qname, parameters.Qtype); _logger.LogInformation("Lookup {key} in {family}", parameters.Qname, parameters.Qtype);
} }
return FindByName(((AddressFamily)qtype, parameters.Qname.AsMemory()), _repository, _logger); return FindByName(((AddressFamily)qtype, parameters.Qname.AsMemory()), _repository, _logger);

View file

@ -3,7 +3,7 @@ using System.Text.Json.Serialization;
namespace pdns_dhcp.PowerDns; namespace pdns_dhcp.PowerDns;
[JsonSerializable(typeof(Reply))] [JsonSerializable(typeof(Reply))]
[JsonSerializable(typeof(Parameters))] [JsonSerializable(typeof(MethodParameters))]
[JsonSourceGenerationOptions( [JsonSourceGenerationOptions(
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
NumberHandling = JsonNumberHandling.AllowReadingFromString, NumberHandling = JsonNumberHandling.AllowReadingFromString,

View file

@ -45,6 +45,6 @@ public class DhcpWatcher : IHostedService
var waitTask = Task.WhenAll(tasks); var waitTask = Task.WhenAll(tasks);
TaskCompletionSource taskCompletionSource = new(); TaskCompletionSource taskCompletionSource = new();
using var registration = cancellationToken.Register(s => ((TaskCompletionSource)s!).SetCanceled(), taskCompletionSource); using var registration = cancellationToken.Register(s => ((TaskCompletionSource)s!).SetCanceled(), taskCompletionSource);
await Task.WhenAny(waitTask, taskCompletionSource.Task).ConfigureAwait(continueOnCapturedContext: false); await Task.WhenAny(waitTask, taskCompletionSource.Task).ConfigureAwait(false);
} }
} }