Initial code

This commit is contained in:
pizzaboxer 2022-10-06 07:54:18 +01:00
commit eddfd8fb5a
17 changed files with 1143 additions and 0 deletions

350
.gitignore vendored Normal file
View File

@ -0,0 +1,350 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 pizzaboxer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

25
PolygonGSArbiter.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30114.105
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PolygonGSArbiter", "PolygonGSArbiter\PolygonGSArbiter.csproj", "{E317FEAE-B541-493C-8DB3-F6662B66FA92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E317FEAE-B541-493C-8DB3-F6662B66FA92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E317FEAE-B541-493C-8DB3-F6662B66FA92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E317FEAE-B541-493C-8DB3-F6662B66FA92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E317FEAE-B541-493C-8DB3-F6662B66FA92}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D2EEBC59-B040-4497-9B16-49274FD675F1}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<add key="GameserverID" value="1" />
<add key="MachineAddress" value="127.0.0.1" />
<add key="BaseUrl" value="https://polygondev.pizzaboxer.xyz/api/polygongs" />
<add key="BaseUrlHTTP" value="http://polygondev.pizzaboxer.xyz/api/polygongs" />
<add key="AccessKey" value="" />
<add key="ServicePort" value="64989" />
<add key="InternalBasePort" value="53640" />
<add key="ExternalPortOffset" value="0" />
<add key="MaximumJobs" value="5" />
</appSettings>
</configuration>

View File

@ -0,0 +1,119 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace PolygonGSArbiter
{
class ArbiterService
{
private static TcpListener Service = new TcpListener(IPAddress.Any, Config.ServicePort);
public static int Start()
{
Service.Start();
Task.Run(() => ListenForConnections());
return Config.ServicePort;
}
public static void Stop()
{
Service.Stop();
}
private static void ListenForConnections()
{
while (true)
{
TcpClient Client = Service.AcceptTcpClient();
string ClientAddress = GetClientAddress(Client);
//ConsoleEx.WriteLine($"[ArbiterService] Service received a new connection from '{ClientAddress}'", ConsoleColor.Blue);
Task.Run(() => HandleConnection(Client, ClientAddress));
}
}
private static void HandleConnection(TcpClient Client, string ClientAddress)
{
NetworkStream Stream = Client.GetStream();
StreamReader Reader = new StreamReader(Stream);
try
{
while (Client.Connected)
{
string IncomingCommand = Reader.ReadLine();
if (IncomingCommand == null)
{
//ConsoleEx.WriteLine($"[ArbiterService/{ClientAddress}] Client disconnected", ConsoleColor.Blue);
Stream.Close();
Client.Close();
}
else
{
//ConsoleEx.WriteLine($"[ArbiterService/{ClientAddress}] Received command '{IncomingCommand}'", ConsoleColor.Blue);
ProcessCommand(Stream, ClientAddress, IncomingCommand);
}
}
}
catch (IOException)
{
//ConsoleEx.WriteLine($"$[ArbiterService/{ClientAddress}] Client disconnected", ConsoleColor.Blue);
}
}
private static void WriteToClient(NetworkStream Stream, string ClientAddress, string Response)
{
//ConsoleEx.WriteLine($"[ArbiterService/{ClientAddress}] Writing to client with '{Response}'", ConsoleColor.Blue);
StreamWriter Writer = new StreamWriter(Stream);
Writer.WriteLine(Response);
Writer.Flush();
}
private static void ProcessCommand(NetworkStream Stream, string ClientAddress, string Message)
{
PolygonGSP Request = JsonConvert.DeserializeObject<PolygonGSP>(Message);
switch (Request.Operation)
{
case "OpenJob":
if (JobManager.GetJobFromID(Request.JobID) != null)
{
WriteToClient(Stream, ClientAddress, "{\"Operation\":\"CloseJob\", \"Status\":\"Error\", \"Message\":\"Job already exists\"}");
}
else
{
Task.Run(() => JobManager.OpenJob(Request.JobID, Request.Version, Request.PlaceID));
WriteToClient(Stream, ClientAddress, "{\"Operation\":\"OpenJob\", \"Status\":\"OK\"}");
}
break;
case "CloseJob":
if (JobManager.GetJobFromID(Request.JobID) == null)
{
WriteToClient(Stream, ClientAddress, "{\"Operation\":\"CloseJob\", \"Status\":\"Error\", \"Message\":\"Job does not exist\"}");
}
else
{
Task.Run(() => JobManager.CloseJob(Request.JobID));
WriteToClient(Stream, ClientAddress, "{\"Operation\":\"CloseJob\", \"Status\":\"OK\"}");
}
break;
default:
ConsoleEx.WriteLine($"[ArbiterService/{ClientAddress}] Invalid command received", ConsoleColor.Blue);
break;
}
}
private static string GetClientAddress(TcpClient Client)
{
return Client.Client.RemoteEndPoint.ToString();
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Configuration;
namespace PolygonGSArbiter
{
class Config
{
public static int GameserverID = Int32.Parse(ConfigurationManager.AppSettings.Get("GameserverID"));
public static string MachineAddress = ConfigurationManager.AppSettings.Get("MachineAddress");
public static string BaseUrl = ConfigurationManager.AppSettings.Get("BaseUrl");
public static string BaseUrlHTTP = ConfigurationManager.AppSettings.Get("BaseUrlHTTP");
public static string AccessKey = ConfigurationManager.AppSettings.Get("AccessKey");
public static int ServicePort = Int32.Parse(ConfigurationManager.AppSettings.Get("ServicePort"));
public static int InternalBasePort = Int32.Parse(ConfigurationManager.AppSettings.Get("InternalBasePort"));
public static int ExternalPortOffset = Int32.Parse(ConfigurationManager.AppSettings.Get("ExternalPortOffset"));
public static int MaximumJobs = Int32.Parse(ConfigurationManager.AppSettings.Get("MaximumJobs"));
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PolygonGSArbiter
{
public static class ConsoleEx
{
// would race conditions be an issue here?
public static void Write(string Message, ConsoleColor Color = ConsoleColor.Gray)
{
Console.ForegroundColor = Color;
Console.Write(Message);
Console.ForegroundColor = ConsoleColor.Gray;
}
public static void WriteLine(string Message, ConsoleColor Color = ConsoleColor.Gray)
{
Console.ForegroundColor = Color;
Console.WriteLine(Message);
Console.ForegroundColor = ConsoleColor.Gray;
}
public static void Error(string Message)
{
ConsoleEx.WriteLine(Message, ConsoleColor.Red);
Console.ReadLine();
Environment.Exit(0);
}
}
}

95
PolygonGSArbiter/Job.cs Normal file
View File

@ -0,0 +1,95 @@
using System;
using System.Diagnostics;
namespace PolygonGSArbiter
{
public enum JobStatus
{
Pending = 0,
Started = 1,
Monitored = 2,
Closed = 3,
Crashed = 4,
}
public class Job
{
public string ID { get; set; }
public int Version { get; set; }
public int PlaceID { get; set; }
public int Port { get; set; }
public JobStatus Status { get; set; }
public int TimeCreated { get; set; }
public int TimeStarted { get; set; }
public bool HasShutdown { get; set; }
public Process Process { get; set; }
public Job(string JobID, int Version, int PlaceID, int Port)
{
this.ID = JobID;
this.Version = Version;
this.PlaceID = PlaceID;
this.Port = Port;
this.Status = JobStatus.Pending;
this.HasShutdown = false;
this.TimeCreated = UnixTime.GetTimestamp();
}
internal void Start()
{
ConsoleEx.WriteLine($"[Job] Starting '{ID}' on port {Port}...", ConsoleColor.Yellow);
// ExternalPortOffset is used for the connection port that is declared in the joinscript
// the internal port is the port networkserver should listen on
WebManager.UpdateJob(ID, "Loading", Port + Config.ExternalPortOffset);
string GameserverScript = WebManager.GetGameserverScript(ID, PlaceID, Port);
string[] CommandLine = JobManager.GetCommandLine(ID, Version, GameserverScript);
Process = new Process();
Process.StartInfo.FileName = CommandLine[0];
Process.StartInfo.Arguments = CommandLine[1];
Process.Start();
Process.WaitForInputIdle();
Status = JobStatus.Started;
this.TimeStarted = UnixTime.GetTimestamp();
ConsoleEx.WriteLine($"[Job] Started '{ID}'!", ConsoleColor.Green);
}
internal void Close()
{
try
{
if (HasShutdown || Process.HasExited)
{
if (HasShutdown) Process.CloseMainWindow();
Process.Close();
ConsoleEx.WriteLine($"[Job] Closed '{ID}'! (Job closed by game:Shutdown())", ConsoleColor.Green);
WebManager.UpdateJob(ID, "Closed");
}
else if (Status == JobStatus.Crashed || !Process.Responding)
{
Process.Kill();
Process.Close();
ConsoleEx.WriteLine($"[Job] Closed '{ID}'! (Job encountered a soft crash)", ConsoleColor.Red);
WebManager.UpdateJob(ID, "Crashed");
}
else
{
Process.CloseMainWindow();
Process.Close();
ConsoleEx.WriteLine($"[Job] Closed '{ID}'! (Job closed by request)", ConsoleColor.Green);
WebManager.UpdateJob(ID, "Closed");
}
}
catch (InvalidOperationException)
{
ConsoleEx.WriteLine($"[Job] Closed '{ID}'! (Job encountered a hard crash)", ConsoleColor.Red);
WebManager.UpdateJob(ID, "Crashed");
}
}
}
}

View File

@ -0,0 +1,173 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace PolygonGSArbiter
{
class JobManager
{
public static List<Job> OpenJobs = new List<Job>();
[DllImport("User32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("User32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
[DllImport("User32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("User32.dll")]
static extern int GetWindowTextLength(IntPtr hWnd);
public static string GetWindowTitle(IntPtr hWnd)
{
var length = GetWindowTextLength(hWnd) + 1;
var title = new StringBuilder(length);
GetWindowText(hWnd, title, length);
return title.ToString();
}
public static string[] GetCommandLine(string jobId, int Version, string ScriptUrl)
{
switch (Version)
{
case 2010:
return new string[] { "Gameservers\\2010\\PolygonServer.exe", $"-a https://polygon.pizzaboxer.xyz/Login/Negotiate.ashx -t 0 -j {ScriptUrl} -jobId {jobId}" };
case 2011:
return new string[] { "Gameservers\\2011\\PolygonServer.exe", $"-a https://polygon.pizzaboxer.xyz/Login/Negotiate.ashx -t 0 -j {ScriptUrl} -jobId {jobId}" };
case 2012:
return new string[] { "Gameservers\\2012\\PolygonServer.exe", $"-a https://polygon.pizzaboxer.xyz/Login/Negotiate.ashx -t 0 -j {ScriptUrl} -jobId {jobId}" };
default:
return new string[] { };
}
}
public static int GetAvailablePort()
{
int Port = Config.InternalBasePort;
for (int i = 0; i < Config.MaximumJobs; i++)
{
if (OpenJobs.Find(Job => Job.Port == Port) == null)
break;
else
Port++;
}
return Port;
}
public static Job OpenJob(string JobID, int Version, int PlaceID)
{
ConsoleEx.WriteLine($"[JobManager] Opening Job for '{JobID}' ({Version})", ConsoleColor.Blue);
Job NewJob = new Job(JobID, Version, PlaceID, GetAvailablePort());
OpenJobs.Add(NewJob);
NewJob.Start();
return NewJob;
}
public static void CloseJob(string JobID)
{
Job JobToClose = GetJobFromID(JobID);
if (JobToClose == null) return;
JobToClose.Close();
OpenJobs.Remove(JobToClose);
}
public static Job GetJobFromID(string JobID)
{
return OpenJobs.Find(Job => Job.ID == JobID);
}
public static bool CheckIfJobExists(string JobID)
{
foreach (Job OpenJob in OpenJobs)
{
if (OpenJob.ID == JobID)
return true;
}
return false;
}
public static void MonitorUnresponsiveJobs()
{
while (true)
{
try
{
foreach (Job OpenJob in OpenJobs)
{
if (OpenJob.Status == JobStatus.Pending || OpenJob.Status == JobStatus.Monitored) continue;
if (OpenJob.HasShutdown || OpenJob.Process.HasExited)
{
OpenJob.Close();
OpenJobs.Remove(OpenJob);
continue;
}
if (OpenJob.Process.Responding) continue;
Task.Run(() => MonitorUnresponsiveJob(OpenJob));
}
}
catch (InvalidOperationException)
{
}
Thread.Sleep(5000);
}
}
public static void CloseAllJobs()
{
foreach (Job OpenJob in OpenJobs)
{
OpenJob.Close();
}
OpenJobs.Clear();
}
public static void MonitorUnresponsiveJob(Job UnresponsiveJob)
{
ConsoleEx.WriteLine($"[JobManager] '{UnresponsiveJob.ID}' is not responding! Monitoring...", ConsoleColor.Yellow);
UnresponsiveJob.Status = JobStatus.Monitored;
for (int i = 1; i <= 30; i++)
{
Thread.Sleep(1000);
if (UnresponsiveJob.Process.Responding)
{
ConsoleEx.WriteLine($"[JobManager] '{UnresponsiveJob.ID}' has recovered from its unresponsive status!", ConsoleColor.Green);
UnresponsiveJob.Status = JobStatus.Started;
break;
}
else if (i == 30)
{
ConsoleEx.WriteLine($"[JobManager] '{UnresponsiveJob.ID}' has been unresponsive for over 30 seconds. Closing Job...", ConsoleColor.Yellow);
UnresponsiveJob.Status = JobStatus.Crashed;
UnresponsiveJob.Close();
OpenJobs.Remove(UnresponsiveJob);
break;
}
}
return;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

View File

@ -0,0 +1,99 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{E317FEAE-B541-493C-8DB3-F6662B66FA92}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>PolygonGSArbiter</RootNamespace>
<AssemblyName>PolygonGSArbiter</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>PlayerBetaServer.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Management" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ArbiterService.cs" />
<Compile Include="Config.cs" />
<Compile Include="ConsoleEx.cs" />
<Compile Include="Job.cs" />
<Compile Include="JobManager.cs" />
<Compile Include="PolygonGSP.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="WebManager.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.7.2">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.7.2 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<Content Include="PlayerBetaServer.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PolygonGSArbiter
{
public class PolygonGSP
{
public string Operation { get; set; }
public string JobID { get; set; }
public int Version { get; set; }
public int PlaceID { get; set; }
public string Status { get; set; }
public string Message { get; set; }
}
}

View File

@ -0,0 +1,51 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace PolygonGSArbiter
{
class Program
{
static void Main(string[] args)
{
ConsoleEx.WriteLine($"Access Key read: {Config.AccessKey}");
ConsoleEx.WriteLine($"Current Access key: {Config.AccessKey}");
ConsoleEx.WriteLine("Service starting...");
Task.Run(() => JobManager.MonitorUnresponsiveJobs());
Task.Run(() => WebManager.StartResourceReporter());
WebManager.SetMarker(true);
ConsoleEx.WriteLine("Initializing Project Polygon Arbiter Service");
int ServicePort = ArbiterService.Start();
ConsoleEx.WriteLine($"Service Started on port {ServicePort}");
Console.CancelKeyPress += delegate
{
Console.WriteLine("Service shutting down...");
ArbiterService.Stop();
WebManager.SetMarker(false);
JobManager.CloseAllJobs();
// wait for web requests to finish
Thread.Sleep(10000);
};
while (true)
{
Thread.Sleep(1000);
}
}
}
public class UnixTime
{
public static int GetTimestamp()
{
return (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PolygonGSArbiter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PolygonGSArbiter")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e317feae-b541-493c-8db3-f6662b66fa92")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Net.Http;
namespace PolygonGSArbiter
{
class WebManager
{
private static readonly HttpClient WebClient = new HttpClient();
public static string GetGameserverScript(string JobID, int PlaceID, int Port)
{
return $"{Config.BaseUrlHTTP}/gameserver?jobId={JobID}&placeId={PlaceID}&port={Port}&maxPlayers=10&{Config.AccessKey}";
}
static int GetAvailableMemory()
{
PerformanceCounter performance = new PerformanceCounter("Memory", "Available MBytes");
return (int)performance.NextValue();
}
static int GetCpuUsage()
{
PerformanceCounter performance = new PerformanceCounter("Processor", "% Processor Time", "_Total");
performance.NextValue(); // this is always gonna be zero
Thread.Sleep(500);
return (int)Math.Round(performance.NextValue());
}
public static void SetMarker(bool Online)
{
int OnlineInt = Online ? 1 : 0;
WebClient.GetAsync($"{Config.BaseUrl}/set-marker?{Config.AccessKey}&GameserverID={Config.GameserverID}&Online={OnlineInt}");
}
public static void StartResourceReporter()
{
while (true)
{
string AvailableMemory = GetAvailableMemory().ToString();
string CpuUsage = GetCpuUsage().ToString();
Dictionary<string, string> FormData = new Dictionary<string, string>
{
{ "GameserverID", Config.GameserverID.ToString() },
{ "CpuUsage", CpuUsage },
{ "AvailableMemory", AvailableMemory },
};
FormUrlEncodedContent FormContent = new FormUrlEncodedContent(FormData);
WebClient.PostAsync($"{Config.BaseUrl}/report-gameserver-resources?{Config.AccessKey}", FormContent);
Thread.Sleep(60000);
}
}
public static void UpdateJob(string JobID, string Status, int Port = 0)
{
if (Port == 0)
{
WebClient.GetAsync($"{Config.BaseUrl}/update-job?{Config.AccessKey}&JobID={JobID}&Status={Status}");
}
else
{
WebClient.GetAsync($"{Config.BaseUrl}/update-job?{Config.AccessKey}&JobID={JobID}&Status={Status}&MachineAddress={Config.MachineAddress}&ServerPort={Port}");
}
}
}
}

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net472" />
</packages>

10
README.md Normal file
View File

@ -0,0 +1,10 @@
# polygon-arbiter
Manages gameserver requests sent from the Project Polygon website
This is the backend service that was used to handle the launching and shutdown of dedicated gameservers on Project Polygon, with development having started in December 2021 and subsequently used in production in February 2022.
While developing the gameserver system, I recorded a few demo videos of the arbiter in action, which I've linked below:
- [Proof of concept demo](https://youtu.be/bszlNpBIRTo)
- [Website integration demo](https://youtu.be/XF-MD0K5IOA)
I've published this here purely for archival purposes, however I've had to omit the commit history from this release due to sensitive info being contained in the configs. I don't recommend that you use this in your work, but I won't stop you.