feat(server): docker container log stream

This commit is contained in:
CyberL1 2024-05-29 18:34:13 +02:00
parent 21635d53c2
commit 6ff9faf741
3 changed files with 57 additions and 3 deletions

View File

@ -2,6 +2,7 @@
using Minecraft_Realms_Emulator.Attributes;
using Minecraft_Realms_Emulator.Data;
using Minecraft_Realms_Emulator.Entities;
using Minecraft_Realms_Emulator.Modes.Realms.Helpers;
namespace Minecraft_Realms_Emulator.Controllers.Admin
{
@ -31,5 +32,30 @@ namespace Minecraft_Realms_Emulator.Controllers.Admin
return Ok(world);
}
[HttpGet("{wId}/logs")]
public async Task<ActionResult> GetLogs(int wId)
{
Response.ContentType = "text/event-stream";
Response.Headers.Add("Cache-Control", "no-cache");
Response.Headers.Add("X-Accel-Buffering", "no");
var world = _context.Worlds.ToList().Find(w => w.Id == wId);
if (world == null) return BadRequest("World not found");
await new DockerHelper(world).GetServerLogsStreamAsync(async log =>
{
if (!HttpContext.Response.Body.CanWrite)
{
return;
}
await HttpContext.Response.WriteAsync($"data: {log}\n\n");
await HttpContext.Response.Body.FlushAsync();
});
return new EmptyResult();
}
}
}

View File

@ -10,7 +10,6 @@ using Minecraft_Realms_Emulator.Requests;
using Minecraft_Realms_Emulator.Responses;
using Newtonsoft.Json;
using Semver;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

View File

@ -29,7 +29,8 @@ namespace Minecraft_Realms_Emulator.Modes.Realms.Helpers
serverProcess.Start();
}
public void StopServer() {
public void StopServer()
{
ProcessStartInfo serverProcessInfo = new();
serverProcessInfo.FileName = "docker";
@ -51,5 +52,33 @@ namespace Minecraft_Realms_Emulator.Modes.Realms.Helpers
serverProcess.StartInfo = serverProcessInfo;
serverProcess.Start();
}
public async Task GetServerLogsStreamAsync(Action<string> handler)
{
ProcessStartInfo serverProcessInfo = new();
serverProcessInfo.FileName = "docker";
serverProcessInfo.Arguments = $"container logs -f realm-server-{world.Id} --tail 100";
serverProcessInfo.RedirectStandardOutput = true;
Process serverProcess = new();
serverProcess.StartInfo = serverProcessInfo;
serverProcess.Start();
List<string> logs = [];
await Task.Run(() =>
{
while (!serverProcess.StandardOutput.EndOfStream)
{
string line = serverProcess.StandardOutput.ReadLine();
if (line != null)
{
handler(line);
}
}
});
}
}
}
}