IW4M-Admin/Application/IO/NetworkGameLogReader.cs

158 lines
5.2 KiB
C#
Raw Normal View History

using SharedLibraryCore;
using SharedLibraryCore.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
2022-02-13 15:53:01 -05:00
using System.Threading;
using System.Threading.Tasks;
2022-02-13 15:53:01 -05:00
using Integrations.Cod;
using Microsoft.Extensions.Logging;
2022-02-13 15:53:01 -05:00
using Serilog.Context;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace IW4MAdmin.Application.IO
{
/// <summary>
2022-02-13 15:53:01 -05:00
/// provides capability of reading log files over udp
/// </summary>
class NetworkGameLogReader : IGameLogReader
{
private readonly IEventParser _eventParser;
private readonly ILogger _logger;
2022-02-13 15:53:01 -05:00
private readonly Uri _uri;
private static readonly NetworkLogState State = new();
private bool _stateRegistered;
private CancellationToken _token;
2022-02-13 15:53:01 -05:00
public NetworkGameLogReader(IReadOnlyList<Uri> uris, IEventParser parser, ILogger<NetworkGameLogReader> logger)
{
_eventParser = parser;
2022-02-13 15:53:01 -05:00
_uri = uris[0];
_logger = logger;
}
public long Length => -1;
2022-02-13 15:53:01 -05:00
public int UpdateInterval => 150;
2022-02-13 15:53:01 -05:00
public Task<IEnumerable<GameEvent>> ReadEventsFromLog(long fileSizeDiff, long startPosition,
Server server = null)
{
2022-02-13 15:53:01 -05:00
// todo: other games might support this
var serverEndpoint = (server?.RemoteConnection as CodRConConnection)?.Endpoint;
2022-02-13 15:53:01 -05:00
if (serverEndpoint is null)
{
2022-02-13 15:53:01 -05:00
return Task.FromResult(Enumerable.Empty<GameEvent>());
}
2022-02-13 15:53:01 -05:00
if (!_stateRegistered && !State.EndPointExists(serverEndpoint))
{
2022-02-13 15:53:01 -05:00
try
{
var client = State.RegisterEndpoint(serverEndpoint, BuildLocalEndpoint()).Client;
_stateRegistered = true;
_token = server.Manager.CancellationToken;
if (client == null)
{
using (LogContext.PushProperty("Server", server.ToString()))
{
_logger.LogInformation("Not registering {Name} socket because it is already bound",
nameof(NetworkGameLogReader));
}
return Task.FromResult(Enumerable.Empty<GameEvent>());
}
new Thread(() => ReadNetworkData(client)).Start();
}
catch (Exception ex)
{
_logger.LogError(ex, "Could not register {Name} endpoint {Endpoint}",
nameof(NetworkGameLogReader), _uri);
throw;
}
}
2022-02-13 15:53:01 -05:00
var events = new List<GameEvent>();
2022-02-13 15:53:01 -05:00
foreach (var logData in State.GetServerLogData(serverEndpoint)
.Select(log => Utilities.EncodingType.GetString(log)))
{
2022-02-13 15:53:01 -05:00
if (string.IsNullOrWhiteSpace(logData))
{
return Task.FromResult(Enumerable.Empty<GameEvent>());
}
var lines = logData
.Split('\n')
.Where(line => line.Length > 0);
foreach (var eventLine in lines)
{
try
{
// this trim end should hopefully fix the nasty runaway regex
var gameEvent = _eventParser.GenerateGameEvent(eventLine.TrimEnd('\r'));
events.Add(gameEvent);
}
catch (Exception ex)
{
_logger.LogError(ex, "Could not properly parse event line from http {EventLine}",
eventLine);
}
}
}
2022-02-13 15:53:01 -05:00
return Task.FromResult((IEnumerable<GameEvent>)events);
}
2022-02-13 15:53:01 -05:00
private void ReadNetworkData(UdpClient client)
{
while (!_token.IsCancellationRequested)
{
2022-02-13 15:53:01 -05:00
// get more data
IPEndPoint remoteEndpoint = null;
byte[] bufferedData = null;
if (client == null)
{
2022-02-13 15:53:01 -05:00
// we already have a socket listening on this port for data, so we don't need to run another thread
break;
}
2022-02-13 15:53:01 -05:00
try
{
bufferedData = client.Receive(ref remoteEndpoint);
}
catch (Exception ex)
{
2022-02-13 15:53:01 -05:00
_logger.LogError(ex, "Could not receive lines for {LogReader}", nameof(NetworkGameLogReader));
}
if (bufferedData != null)
{
State.QueueServerLogData(remoteEndpoint, bufferedData);
}
}
2022-02-13 15:53:01 -05:00
}
2022-02-13 15:53:01 -05:00
private IPEndPoint BuildLocalEndpoint()
{
try
{
return new IPEndPoint(Dns.GetHostAddresses(_uri.Host).First(), _uri.Port);
}
catch (Exception ex)
{
_logger.LogError(ex, "Could not setup {LogReader} endpoint", nameof(NetworkGameLogReader));
throw;
}
}
}
}