Files
tbd-station-14/Content.Server.Database/ModelSqlite.cs
Javier Guardia Fernández 319aec109d Admin logs (#5419)
* Add admin logging, models, migrations

* Add logging damage changes

* Add Log admin flag, LogFilter, Logs admin menu tab, message
Refactor admin logging API

* Change admin log get method names

* Fix the name again

* Minute amount of reorganization

* Reset Postgres db snapshot

* Reset Sqlite db snapshot

* Make AdminLog have a composite primary key of round, id

* Minute cleanup

* Change admin system to do a type check instead of index check

* Make admin logs use C# 10 interpolated string handlers

* Implement UI on its own window
Custom controls
Searching
Add admin log converters

* Implement limits into the query

* Change logs to be put into an OutputPanel instead for text wrapping

* Add log <-> player m2m relationship back

* UI improvements, make text wrap, add separators

* Remove entity prefix from damaged log

* Add explicit m2m model, fix any players filter

* Add debug command to test bulk adding logs

* Admin logs now just kinda go

* Add histogram for database update time

* Make admin log system update run every 5 seconds

* Add a cap to the log queue and a metric for how many times it has been reached

* Add metric for logs sent in a round

* Make cvars out of admin logs queue send delay and cap

* Merge fixes

* Reset some changes

* Add test for adding and getting a single log

* Add tests for bulk adding logs

* Add test for querying logs

* Add CallerArgumentExpression to LogStringHandler methods and test

* Improve UI, fix SQLite, add searching by round

* Add entities to admin logs

* Move distinct after orderby

* Add migrations

* ef core eat my ass

* Add cvar for client logs batch size

* Sort logs from newest to oldest by default

* Merge fixes

* Reorganize tests and add one for date ordering

* Add note to log types to not change their numeric values

* Add impacts to logs, better UI filtering

* Make log add callable from shared for convenience

* Get current round id directly from game ticker

* Revert namespace change for DamageableSystem
2021-11-22 18:49:26 +01:00

154 lines
4.9 KiB
C#

using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Content.Server.Database
{
public sealed class SqliteServerDbContext : ServerDbContext
{
public DbSet<SqliteServerBan> Ban { get; set; } = default!;
public DbSet<SqliteServerUnban> Unban { get; set; } = default!;
public DbSet<SqliteConnectionLog> ConnectionLog { get; set; } = default!;
public SqliteServerDbContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (!InitializedWithOptions)
options.UseSqlite("dummy connection string");
((IDbContextOptionsBuilderInfrastructure) options).AddOrUpdateExtension(new SnakeCaseExtension());
options.ConfigureWarnings(x =>
{
x.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning);
});
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Player>()
.HasIndex(p => p.LastSeenUserName);
var ipConverter = new ValueConverter<IPAddress, string>(
v => v.ToString(),
v => IPAddress.Parse(v));
modelBuilder.Entity<Player>()
.Property(p => p.LastSeenAddress)
.HasConversion(ipConverter);
var ipMaskConverter = new ValueConverter<(IPAddress address, int mask), string>(
v => InetToString(v.address, v.mask),
v => StringToInet(v)
);
modelBuilder
.Entity<SqliteServerBan>()
.Property(e => e.Address)
.HasColumnType("TEXT")
.HasConversion(ipMaskConverter);
var jsonConverter = new ValueConverter<JsonDocument, string>(
v => JsonDocumentToString(v),
v => StringToJsonDocument(v));
modelBuilder.Entity<AdminLog>()
.Property(log => log.Json)
.HasConversion(jsonConverter);
}
public SqliteServerDbContext(DbContextOptions<ServerDbContext> options) : base(options)
{
}
private static string InetToString(IPAddress address, int mask) {
if (address.IsIPv4MappedToIPv6)
{
// Fix IPv6-mapped IPv4 addresses
// So that IPv4 addresses are consistent between separate-socket and dual-stack socket modes.
address = address.MapToIPv4();
mask -= 96;
}
return $"{address}/{mask}";
}
private static (IPAddress, int) StringToInet(string inet) {
var idx = inet.IndexOf('/', StringComparison.Ordinal);
return (
IPAddress.Parse(inet.AsSpan(0, idx)),
int.Parse(inet.AsSpan(idx + 1), provider: CultureInfo.InvariantCulture)
);
}
private static string JsonDocumentToString(JsonDocument document)
{
using var stream = new MemoryStream();
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions {Indented = false});
document.WriteTo(writer);
writer.Flush();
return Encoding.UTF8.GetString(stream.ToArray());
}
private static JsonDocument StringToJsonDocument(string str)
{
return JsonDocument.Parse(str);
}
}
[Table("ban")]
public class SqliteServerBan
{
public int Id { get; set; }
public Guid? UserId { get; set; }
public (IPAddress address, int mask)? Address { get; set; }
public byte[]? HWId { get; set; }
public DateTime BanTime { get; set; }
public DateTime? ExpirationTime { get; set; }
public string Reason { get; set; } = null!;
public Guid? BanningAdmin { get; set; }
public SqliteServerUnban? Unban { get; set; }
}
[Table("unban")]
public class SqliteServerUnban
{
[Column("unban_id")] public int Id { get; set; }
public int BanId { get; set; }
public SqliteServerBan Ban { get; set; } = null!;
public Guid? UnbanningAdmin { get; set; }
public DateTime UnbanTime { get; set; }
}
[Table("connection_log")]
public class SqliteConnectionLog
{
public int Id { get; set; }
public Guid UserId { get; set; }
public string UserName { get; set; } = null!;
public DateTime Time { get; set; }
public string Address { get; set; } = null!;
public byte[]? HWId { get; set; }
}
}