Merge pull request #17 from Moonlight-Panel/CleanupSystem
Cleanup System
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
using Moonlight.App.Database.Entities;
|
||||
using Moonlight.App.Database.Entities.LogsEntries;
|
||||
using Moonlight.App.Database.Entities.Notification;
|
||||
using Moonlight.App.Models.Misc;
|
||||
using Moonlight.App.Services;
|
||||
|
||||
namespace Moonlight.App.Database;
|
||||
|
||||
@@ -20,4 +20,5 @@ public class Server
|
||||
public NodeAllocation MainAllocation { get; set; } = null!;
|
||||
public Node Node { get; set; } = null!;
|
||||
public User Owner { get; set; } = null!;
|
||||
public bool IsCleanupException { get; set; } = false;
|
||||
}
|
||||
1082
Moonlight/App/Database/Migrations/20230402204329_AddCleanupExceptionsTable.Designer.cs
generated
Normal file
1082
Moonlight/App/Database/Migrations/20230402204329_AddCleanupExceptionsTable.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,170 @@
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Moonlight.App.Database.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddCleanupExceptionsTable : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "State",
|
||||
table: "Users",
|
||||
type: "varchar(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "longtext")
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "LastName",
|
||||
table: "Users",
|
||||
type: "varchar(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "longtext")
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "FirstName",
|
||||
table: "Users",
|
||||
type: "varchar(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "longtext")
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Country",
|
||||
table: "Users",
|
||||
type: "varchar(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "longtext")
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "City",
|
||||
table: "Users",
|
||||
type: "varchar(128)",
|
||||
maxLength: 128,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "longtext")
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Address",
|
||||
table: "Users",
|
||||
type: "varchar(128)",
|
||||
maxLength: 128,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "longtext")
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "CleanupExceptions",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false)
|
||||
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
|
||||
ServerId = table.Column<int>(type: "int", nullable: false),
|
||||
Note = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_CleanupExceptions", x => x.Id);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "CleanupExceptions");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "State",
|
||||
table: "Users",
|
||||
type: "longtext",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "varchar(64)",
|
||||
oldMaxLength: 64)
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "LastName",
|
||||
table: "Users",
|
||||
type: "longtext",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "varchar(64)",
|
||||
oldMaxLength: 64)
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "FirstName",
|
||||
table: "Users",
|
||||
type: "longtext",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "varchar(64)",
|
||||
oldMaxLength: 64)
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Country",
|
||||
table: "Users",
|
||||
type: "longtext",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "varchar(64)",
|
||||
oldMaxLength: 64)
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "City",
|
||||
table: "Users",
|
||||
type: "longtext",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "varchar(128)",
|
||||
oldMaxLength: 128)
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Address",
|
||||
table: "Users",
|
||||
type: "longtext",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "varchar(128)",
|
||||
oldMaxLength: 128)
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
.OldAnnotation("MySql:CharSet", "utf8mb4");
|
||||
}
|
||||
}
|
||||
}
|
||||
1098
Moonlight/App/Database/Migrations/20230402215155_ChengedCleanupExceptionModel.Designer.cs
generated
Normal file
1098
Moonlight/App/Database/Migrations/20230402215155_ChengedCleanupExceptionModel.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Moonlight.App.Database.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class ChengedCleanupExceptionModel : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTime>(
|
||||
name: "CreatedAt",
|
||||
table: "CleanupExceptions",
|
||||
type: "datetime(6)",
|
||||
nullable: false,
|
||||
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_CleanupExceptions_ServerId",
|
||||
table: "CleanupExceptions",
|
||||
column: "ServerId");
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_CleanupExceptions_Servers_ServerId",
|
||||
table: "CleanupExceptions",
|
||||
column: "ServerId",
|
||||
principalTable: "Servers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_CleanupExceptions_Servers_ServerId",
|
||||
table: "CleanupExceptions");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_CleanupExceptions_ServerId",
|
||||
table: "CleanupExceptions");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CreatedAt",
|
||||
table: "CleanupExceptions");
|
||||
}
|
||||
}
|
||||
}
|
||||
1067
Moonlight/App/Database/Migrations/20230402220651_RemovedCleanupExceptionChangedServerModel.Designer.cs
generated
Normal file
1067
Moonlight/App/Database/Migrations/20230402220651_RemovedCleanupExceptionChangedServerModel.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Moonlight.App.Database.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class RemovedCleanupExceptionChangedServerModel : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "CleanupExceptions");
|
||||
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "IsCleanupException",
|
||||
table: "Servers",
|
||||
type: "tinyint(1)",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "IsCleanupException",
|
||||
table: "Servers");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "CleanupExceptions",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false)
|
||||
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
|
||||
ServerId = table.Column<int>(type: "int", nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
Note = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_CleanupExceptions", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_CleanupExceptions_Servers_ServerId",
|
||||
column: x => x.ServerId,
|
||||
principalTable: "Servers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_CleanupExceptions_ServerId",
|
||||
table: "CleanupExceptions",
|
||||
column: "ServerId");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -482,6 +482,9 @@ namespace Moonlight.App.Database.Migrations
|
||||
b.Property<bool>("Installing")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<bool>("IsCleanupException")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<int>("MainAllocationId")
|
||||
.HasColumnType("int");
|
||||
|
||||
@@ -707,18 +710,21 @@ namespace Moonlight.App.Database.Migrations
|
||||
|
||||
b.Property<string>("Address")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("varchar(128)");
|
||||
|
||||
b.Property<bool>("Admin")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("City")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("varchar(128)");
|
||||
|
||||
b.Property<string>("Country")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("varchar(64)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
@@ -732,11 +738,13 @@ namespace Moonlight.App.Database.Migrations
|
||||
|
||||
b.Property<string>("FirstName")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("varchar(64)");
|
||||
|
||||
b.Property<string>("LastName")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("varchar(64)");
|
||||
|
||||
b.Property<string>("Password")
|
||||
.IsRequired()
|
||||
@@ -744,7 +752,8 @@ namespace Moonlight.App.Database.Migrations
|
||||
|
||||
b.Property<string>("State")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("varchar(64)");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("int");
|
||||
|
||||
@@ -19,5 +19,8 @@ public enum AuditLogType
|
||||
AddDomainRecord,
|
||||
UpdateDomainRecord,
|
||||
DeleteDomainRecord,
|
||||
PasswordReset
|
||||
PasswordReset,
|
||||
CleanupEnabled,
|
||||
CleanupDisabled,
|
||||
CleanupTriggered,
|
||||
}
|
||||
365
Moonlight/App/Services/CleanupService.cs
Normal file
365
Moonlight/App/Services/CleanupService.cs
Normal file
@@ -0,0 +1,365 @@
|
||||
using System.Diagnostics;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MineStatLib;
|
||||
using Moonlight.App.Database.Entities;
|
||||
using Moonlight.App.Models.Daemon.Resources;
|
||||
using Moonlight.App.Models.Wings;
|
||||
using Moonlight.App.Repositories;
|
||||
using Moonlight.App.Repositories.Servers;
|
||||
using Logging.Net;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Moonlight.App.Services;
|
||||
|
||||
public class CleanupService
|
||||
{
|
||||
public DateTime StartedAt { get; private set; }
|
||||
public DateTime CompletedAt { get; private set; }
|
||||
public int ServersCleaned { get; private set; }
|
||||
public int CleanupsPerformed { get; private set; }
|
||||
public int ServersRunning { get; private set; }
|
||||
public bool IsRunning { get; private set; }
|
||||
public bool Activated { get; set; }
|
||||
public int PercentProgress { get; private set; } = 100;
|
||||
public string Status { get; private set; } = "N/A";
|
||||
|
||||
private Task PerformTask;
|
||||
private readonly ConfigService ConfigService;
|
||||
private readonly IServiceScopeFactory ServiceScopeFactory;
|
||||
|
||||
private int RequiredCpu;
|
||||
private long RequiredMemory;
|
||||
private int WaitTime;
|
||||
|
||||
public EventHandler OnUpdated;
|
||||
|
||||
public CleanupService(ConfigService configService, IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
ServiceScopeFactory = serviceScopeFactory;
|
||||
ConfigService = configService;
|
||||
|
||||
var config = configService.GetSection("Moonlight").GetSection("Cleanup");
|
||||
|
||||
RequiredCpu = config.GetValue<int>("Cpu");
|
||||
RequiredMemory = config.GetValue<long>("Memory");
|
||||
WaitTime = config.GetValue<int>("Wait");
|
||||
|
||||
if (!ConfigService.DebugMode)
|
||||
Task.Run(Start);
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
StartedAt = DateTime.Now;
|
||||
CompletedAt = DateTime.Now;
|
||||
IsRunning = false;
|
||||
Activated = true;
|
||||
|
||||
DoWaiting();
|
||||
}
|
||||
|
||||
private async void DoWaiting()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
if (Activated)
|
||||
await Perform();
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay((int) TimeSpan.FromMinutes(WaitTime).TotalMilliseconds);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task TriggerPerform()
|
||||
{
|
||||
if (IsRunning)
|
||||
return;
|
||||
|
||||
PerformTask = new Task(async () => await Perform());
|
||||
PerformTask.Start();
|
||||
}
|
||||
|
||||
private async Task Perform()
|
||||
{
|
||||
if (IsRunning)
|
||||
return;
|
||||
|
||||
IsRunning = true;
|
||||
StartedAt = DateTime.Now;
|
||||
ServersRunning = 0;
|
||||
|
||||
OnUpdated?.Invoke(this, null);
|
||||
|
||||
using (var scope = ServiceScopeFactory.CreateScope())
|
||||
{
|
||||
// Setup time measure
|
||||
var watch = new Stopwatch();
|
||||
watch.Start();
|
||||
|
||||
// Get repos from dependency injection
|
||||
var serverRepository = scope.ServiceProvider.GetRequiredService<ServerRepository>();
|
||||
var nodeRepository = scope.ServiceProvider.GetRequiredService<NodeRepository>();
|
||||
var nodeService = scope.ServiceProvider.GetRequiredService<NodeService>();
|
||||
var imageRepo = scope.ServiceProvider.GetRequiredService<ImageRepository>();
|
||||
var serverService = scope.ServiceProvider.GetRequiredService<ServerService>();
|
||||
|
||||
// Fetching data from mysql
|
||||
var servers = serverRepository.Get()
|
||||
.Include(x => x.Image)
|
||||
.ToArray();
|
||||
var nodes = nodeRepository.Get().ToArray();
|
||||
var exceptions = servers.Where(x => x.IsCleanupException);
|
||||
var images = imageRepo.Get().ToArray();
|
||||
|
||||
var nodeCount = nodes.Count();
|
||||
|
||||
// We use this counter for the foreach loops
|
||||
int counter = 0;
|
||||
PercentProgress = 0;
|
||||
|
||||
// Fetching data from nodes so we know what nodes to scan
|
||||
var nodeContainers = new Dictionary<Node, ContainerStats.Container[]>();
|
||||
|
||||
Status = "Checking Nodes";
|
||||
counter = 0;
|
||||
PercentProgress = 0;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
try
|
||||
{
|
||||
var cpu = await nodeService.GetCpuStats(node);
|
||||
var freeMemory = await nodeService.GetMemoryStats(node);
|
||||
|
||||
if (cpu.Usage > RequiredCpu || freeMemory.Free < RequiredMemory)
|
||||
{
|
||||
var c = await nodeService.GetContainerStats(node);
|
||||
var containers = c.Containers;
|
||||
nodeContainers.Add(node, containers.ToArray());
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error($"Error fetching cleanup data from node {node.Id}");
|
||||
Logger.Error(e);
|
||||
}
|
||||
|
||||
counter++;
|
||||
CalculateAndUpdateProgress(counter, nodeCount);
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
|
||||
// Searching for servers we can actually stop because they have the cleanup tag
|
||||
// and determine which servers we have to check for an illegal mc server
|
||||
var serversToCheck = new List<Server>();
|
||||
var serversToCheckForMc = new List<Server>();
|
||||
|
||||
Status = "Checking found servers";
|
||||
counter = 0;
|
||||
PercentProgress = 0;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
|
||||
// Count every container for progress calculation
|
||||
var allContainers = 0;
|
||||
foreach (var array in nodeContainers)
|
||||
{
|
||||
allContainers += array.Value.Length;
|
||||
}
|
||||
|
||||
foreach (var nodeContainer in nodeContainers)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var container in nodeContainer.Value)
|
||||
{
|
||||
var server = servers.First(x => x.Uuid.ToString() == container.Name);
|
||||
var tagsJson = imageRepo
|
||||
.Get()
|
||||
.First(x => x.Id == server.Image.Id).TagsJson;
|
||||
|
||||
var tags = JsonConvert.DeserializeObject<string[]>(tagsJson) ?? Array.Empty<string>();
|
||||
|
||||
if (tags.FirstOrDefault(x => x == "cleanup") != null)
|
||||
{
|
||||
serversToCheck.Add(server);
|
||||
}
|
||||
|
||||
if (tags.FirstOrDefault(x => x == "illegalmc") != null)
|
||||
{
|
||||
serversToCheckForMc.Add(server);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error($"Error processing cleanup data from node {nodeContainer.Key.Id}");
|
||||
Logger.Error(e);
|
||||
}
|
||||
|
||||
counter++;
|
||||
CalculateAndUpdateProgress(counter, allContainers);
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
|
||||
// Now we gonna scan every tagged server
|
||||
Status = "Scanning servers";
|
||||
counter = 0;
|
||||
PercentProgress = 0;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
|
||||
foreach (var server in serversToCheck)
|
||||
{
|
||||
try
|
||||
{
|
||||
var serverData = serverRepository
|
||||
.Get()
|
||||
.Include(x => x.MainAllocation)
|
||||
.Include(x => x.Node)
|
||||
.Include(x => x.Variables)
|
||||
.First(x => x.Id == server.Id);
|
||||
|
||||
var players = GetPlayers(serverData.Node, serverData.MainAllocation);
|
||||
var stats = await serverService.GetDetails(server);
|
||||
|
||||
var exception = exceptions.FirstOrDefault(x => x.Id == server.Id) != null;
|
||||
|
||||
if (stats != null)
|
||||
{
|
||||
if (exception)
|
||||
{
|
||||
if (players == 0 && stats.Utilization.Uptime > TimeSpan.FromHours(6).TotalMilliseconds)
|
||||
{
|
||||
await serverService.SetPowerState(server, PowerSignal.Restart);
|
||||
ServersCleaned++;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
ServersRunning++;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (players == 0 && stats.Utilization.Uptime > TimeSpan.FromMinutes(10).TotalMilliseconds)
|
||||
{
|
||||
var cleanupVar = serverData.Variables.FirstOrDefault(x => x.Key == "J2S");
|
||||
|
||||
if (cleanupVar == null)
|
||||
{
|
||||
await serverService.SetPowerState(server, PowerSignal.Stop);
|
||||
ServersCleaned++;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (cleanupVar.Value == "1")
|
||||
{
|
||||
await serverService.SetPowerState(server, PowerSignal.Restart);
|
||||
ServersCleaned++;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
await serverService.SetPowerState(server, PowerSignal.Stop);
|
||||
ServersCleaned++;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ServersRunning++;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error($"Error scanning {server.Name}");
|
||||
Logger.Error(e);
|
||||
}
|
||||
|
||||
counter++;
|
||||
CalculateAndUpdateProgress(counter, serversToCheck.Count);
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
|
||||
// Finally we have to check all code container allocations
|
||||
// for illegal hosted mc servers
|
||||
|
||||
Status = "Scanning code containers";
|
||||
counter = 0;
|
||||
PercentProgress = 0;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
|
||||
foreach (var server in serversToCheckForMc)
|
||||
{
|
||||
try
|
||||
{
|
||||
var serverData = serverRepository
|
||||
.Get()
|
||||
.Include(x => x.Allocations)
|
||||
.Include(x => x.Node)
|
||||
.First(x => x.Id == server.Id);
|
||||
|
||||
foreach (var allocation in serverData.Allocations)
|
||||
{
|
||||
if (GetPlayers(server.Node, allocation) != -1)
|
||||
{
|
||||
// TODO: Suspend server
|
||||
Logger.Warn("Found CC running mc: https://moonlight.endelon-hosting.de/server/" +
|
||||
server.Uuid + "/");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error($"Error scanning (cc) {server.Name}");
|
||||
Logger.Error(e);
|
||||
}
|
||||
|
||||
counter++;
|
||||
CalculateAndUpdateProgress(counter, serversToCheckForMc.Count);
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
|
||||
watch.Stop();
|
||||
|
||||
Status = $"Cleanup finished. Duration: {Math.Round(TimeSpan.FromMilliseconds(watch.ElapsedMilliseconds).TotalMinutes, 2)} Minutes";
|
||||
PercentProgress = 100;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
|
||||
IsRunning = false;
|
||||
CompletedAt = DateTime.Now;
|
||||
CleanupsPerformed++;
|
||||
OnUpdated?.Invoke(this, null);
|
||||
}
|
||||
|
||||
private int GetPlayers(Node node, NodeAllocation allocation)
|
||||
{
|
||||
var ms = new MineStat(node.Fqdn, (ushort)allocation.Port);
|
||||
|
||||
if (ms.ServerUp)
|
||||
{
|
||||
return ms.CurrentPlayersInt;
|
||||
}
|
||||
else
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private void CalculateAndUpdateProgress(int now, int all)
|
||||
{
|
||||
PercentProgress = (int)Math.Round((now / (double)all) * 100);
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,8 @@
|
||||
<_ContentIncludedByDefault Remove="wwwroot\css\site.css" />
|
||||
<_ContentIncludedByDefault Remove="Shared\Components\Tables\Column.razor" />
|
||||
<_ContentIncludedByDefault Remove="Shared\Components\Tables\Table.razor" />
|
||||
<_ContentIncludedByDefault Remove="Shared\Views\Admin\Servers\Cleanup\Exceptions\Add.razor" />
|
||||
<_ContentIncludedByDefault Remove="Shared\Views\Admin\Servers\Cleanup\Exceptions\Edit.razor" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -98,6 +98,8 @@ namespace Moonlight
|
||||
builder.Services.AddScoped<GoogleOAuth2Service>();
|
||||
builder.Services.AddScoped<DiscordOAuth2Service>();
|
||||
|
||||
builder.Services.AddSingleton<CleanupService>();
|
||||
|
||||
// Loggers
|
||||
builder.Services.AddScoped<SecurityLogService>();
|
||||
builder.Services.AddScoped<AuditLogService>();
|
||||
@@ -154,6 +156,9 @@ namespace Moonlight
|
||||
// Support service
|
||||
var supportServerService = app.Services.GetRequiredService<SupportServerService>();
|
||||
|
||||
// cleanup service
|
||||
_ = app.Services.GetRequiredService<CleanupService>();
|
||||
|
||||
// Discord bot service
|
||||
//var discordBotService = app.Services.GetRequiredService<DiscordBotService>();
|
||||
|
||||
|
||||
200
Moonlight/Shared/Views/Admin/Servers/Cleanup/Index.razor
Normal file
200
Moonlight/Shared/Views/Admin/Servers/Cleanup/Index.razor
Normal file
@@ -0,0 +1,200 @@
|
||||
@page "/admin/servers/cleanup"
|
||||
|
||||
@using Moonlight.App.Services
|
||||
@using Logging.Net
|
||||
@using Moonlight.App.Models.Misc
|
||||
@using Moonlight.App.Services.LogServices
|
||||
|
||||
@inject CleanupService CleanupService
|
||||
@inject AuditLogService AuditLogService
|
||||
|
||||
@implements IDisposable
|
||||
|
||||
<PageTitle>
|
||||
<TL>Cleanup</TL>
|
||||
</PageTitle>
|
||||
|
||||
<IsAdmin>
|
||||
<div class="row g-5 g-xl-10 mb-5 mb-xl-10">
|
||||
<div class="col-xl-3">
|
||||
<div class="card card-flush bgi-no-repeat bgi-size-contain bgi-position-x-end h-xl-100" style="background-color: #170049;">
|
||||
<div class="card-header pt-5 mb-3">
|
||||
<div class="d-flex flex-center rounded-circle h-80px w-80px" style="border: 1px rgba(255, 255, 255, 0.4);background-color: #7239EA">
|
||||
<i class="text-white bx bxs-skull bx-lg"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body d-flex align-items-end mb-3">
|
||||
<div class="d-flex align-items-center">
|
||||
<span class="fs-4hx text-white fw-bold me-6">@(CleanupService.ServersCleaned)</span>
|
||||
<div class="fw-bold fs-6 text-white">
|
||||
<span class="d-block">
|
||||
<TL>Servers</TL>
|
||||
</span>
|
||||
<span>
|
||||
<TL>stopped</TL>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-xl-3">
|
||||
<div class="card card-flush bgi-no-repeat bgi-size-contain bgi-position-x-end h-xl-100" style="background-color: #170049;">
|
||||
<div class="card-header pt-5 mb-3">
|
||||
<div class="d-flex flex-center rounded-circle h-80px w-80px" style="border: 1px rgba(255, 255, 255, 0.4);background-color: #7239EA">
|
||||
<i class="text-white bx bx-transfer bx-lg"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body d-flex align-items-end mb-3">
|
||||
<div class="d-flex align-items-center">
|
||||
<span class="fs-4hx text-white fw-bold me-6">@(CleanupService.CleanupsPerformed)</span>
|
||||
<div class="fw-bold fs-6 text-white">
|
||||
<span class="d-block">
|
||||
<TL>Cleanups</TL>
|
||||
</span>
|
||||
<span>
|
||||
<TL>executed</TL>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-xl-3">
|
||||
<div class="card card-flush bgi-no-repeat bgi-size-contain bgi-position-x-end h-xl-100" style="background-color: #170049;">
|
||||
<div class="card-header pt-5 mb-3">
|
||||
<div class="d-flex flex-center rounded-circle h-80px w-80px" style="border: 1px rgba(255, 255, 255, 0.4);background-color: #7239EA">
|
||||
<i class="text-white bx bx-rocket bx-lg"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body d-flex align-items-end mb-3">
|
||||
<div class="d-flex align-items-center">
|
||||
<span class="fs-4hx text-white fw-bold me-6">@(CleanupService.ServersRunning)</span>
|
||||
<div class="fw-bold fs-6 text-white">
|
||||
<span class="d-block">
|
||||
<TL>Used clanup</TL>
|
||||
</span>
|
||||
<span>
|
||||
<TL>Servers</TL>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-xl-3">
|
||||
<div class="card card-flush bgi-no-repeat bgi-size-contain bgi-position-x-end h-xl-100" style="background-color: #170049;">
|
||||
<div class="card-body d-flex align-items-end mb-3">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="mb-3">
|
||||
<label class="form-label"><TL>Status</TL>: @(CleanupService.Status)</label>
|
||||
<div class="progress">
|
||||
<div class="progress-bar progress-bar-striped progress-bar-animated bg-primary" role="progressbar" aria-valuenow="@(CleanupService.PercentProgress)" aria-valuemin="0" aria-valuemax="100" style="width: @(CleanupService.PercentProgress)%"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-xl-3">
|
||||
<div class="card card-flush bgi-no-repeat bgi-size-contain bgi-position-x-end">
|
||||
<div class="card-body mb-3">
|
||||
<div class="align-items-top">
|
||||
<div class="fw-bold fs-6 text-white">
|
||||
<div class="row mb-3">
|
||||
@if (CleanupService.IsRunning)
|
||||
{
|
||||
<button class="btn btn-primary disabled" disabled="">
|
||||
<TL>Start</TL>
|
||||
</button>
|
||||
}
|
||||
else
|
||||
{
|
||||
<button @onclick="Trigger" class="btn btn-primary">
|
||||
<TL>Start</TL>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
@if (CleanupService.Activated)
|
||||
{
|
||||
<button class="btn btn-success disabled" disabled="">
|
||||
<TL>Enable</TL>
|
||||
</button>
|
||||
}
|
||||
else
|
||||
{
|
||||
<button @onclick="Enable" class="btn btn-success">
|
||||
<TL>Enable</TL>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
<div class="row">
|
||||
@if (CleanupService.Activated)
|
||||
{
|
||||
<button @onclick="Disabled" class="btn btn-danger">
|
||||
<TL>Disabble</TL>
|
||||
</button>
|
||||
}
|
||||
else
|
||||
{
|
||||
<button class="btn btn-danger disabled" disabled="">
|
||||
<TL>Disable</TL>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</IsAdmin>
|
||||
<NonAdmin>
|
||||
<UnauthorizedAlert></UnauthorizedAlert>
|
||||
</NonAdmin>
|
||||
|
||||
@code
|
||||
{
|
||||
|
||||
protected async override Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (firstRender)
|
||||
{
|
||||
CleanupService.OnUpdated += OnUpdated;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnUpdated(object? sender, EventArgs e)
|
||||
{
|
||||
Logger.Debug(CleanupService.PercentProgress);
|
||||
|
||||
InvokeAsync(StateHasChanged);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
CleanupService.OnUpdated -= OnUpdated;
|
||||
}
|
||||
|
||||
private void Enable()
|
||||
{
|
||||
CleanupService.Activated = true;
|
||||
AuditLogService.Log(AuditLogType.CleanupEnabled, "The automatic cleanup has been activated");
|
||||
InvokeAsync(StateHasChanged);
|
||||
}
|
||||
|
||||
private void Disabled()
|
||||
{
|
||||
CleanupService.Activated = false;
|
||||
AuditLogService.Log(AuditLogType.CleanupDisabled, "The automatic cleanup has been disabled");
|
||||
InvokeAsync(StateHasChanged);
|
||||
}
|
||||
|
||||
private async void Trigger()
|
||||
{
|
||||
await CleanupService.TriggerPerform();
|
||||
await AuditLogService.Log(AuditLogType.CleanupTriggered, "The automatic cleanup has been manually triggered");
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
}
|
||||
@@ -111,6 +111,10 @@
|
||||
<option value="@(DockerImages.IndexOf(image))">@(image.Name)</option>
|
||||
}
|
||||
</select>
|
||||
<label class="form-label">
|
||||
<TL>Cleanup exception</TL>
|
||||
</label>
|
||||
<input @bind="Server.IsCleanupException" class="form-control" type="checkbox" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mb-5">
|
||||
|
||||
@@ -406,29 +406,4 @@ The City field is required.;The City field is required.
|
||||
The State field is required.;The State field is required.
|
||||
The Country field is required.;The Country field is required.
|
||||
Street and house number requered;Street and house number requered
|
||||
Max lenght reached;Max lenght reached
|
||||
Server not found;Server not found
|
||||
A server with that id cannot be found or you have no access for this server;A server with that id cannot be found or you have no access for this server
|
||||
Addons;Addons
|
||||
Go up;Go up
|
||||
Uploading files;Uploading files
|
||||
complete;complete
|
||||
Upload complete;Upload complete
|
||||
Moving;Moving
|
||||
selected;selected
|
||||
Select folder to move the file(s) to;Select folder to move the file(s) to
|
||||
Submit;Submit
|
||||
Processing;Processing
|
||||
Error from daemon;Error from daemon
|
||||
Enter a new name;Enter a new name
|
||||
The uploaded file should not be bigger than 100MB;The uploaded file should not be bigger than 100MB
|
||||
Compress;Compress
|
||||
Compressing;Compressing
|
||||
Decompress;Decompress
|
||||
Paper version;Paper version
|
||||
Error creating server on wings;Error creating server on wings
|
||||
Javascript version;Javascript version
|
||||
Javascript file;Javascript file
|
||||
Select javascript file to execute on start;Select javascript file to execute on start
|
||||
Javascript Version;Javascript Version
|
||||
Join2Start;Join2Start
|
||||
Max lenght reached;Max lenght reached
|
||||
Reference in New Issue
Block a user