allow Kekno to run with sv_running not returning anything :upside_down:

make sure script plugins output correct errors instead of being swallowed
prevent webfront error when webfront tab is left open on a server no longer being modified
This commit is contained in:
RaidMax 2020-02-01 12:27:14 -06:00
parent c6d6bebeab
commit 06cdaef8a4
9 changed files with 131 additions and 146 deletions

View File

@ -5,7 +5,7 @@
<TargetFramework>netcoreapp3.1</TargetFramework>
<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>
<PackageId>RaidMax.IW4MAdmin.Application</PackageId>
<Version>2.3.1.0</Version>
<Version>2.3.2.0</Version>
<Authors>RaidMax</Authors>
<Company>Forever None</Company>
<Product>IW4MAdmin</Product>

View File

@ -254,12 +254,28 @@ namespace IW4MAdmin.Application
try
{
if (plugin is ScriptPlugin scriptPlugin)
{
await scriptPlugin.Initialize(this);
scriptPlugin.Watcher.Changed += async (sender, e) =>
{
try
{
await scriptPlugin.Initialize(this);
}
catch (Exception ex)
{
Logger.WriteError(Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_ERROR"].FormatExt(scriptPlugin.Name));
Logger.WriteDebug(ex.Message);
}
};
}
else
{
await plugin.OnLoadAsync(this);
}
}
catch (Exception ex)
{

View File

@ -881,9 +881,9 @@ namespace IW4MAdmin
Version = RconParser.Version;
}
var svRunning = await this.GetDvarAsync<int>("sv_running");
var svRunning = await this.GetDvarAsync<string>("sv_running");
if (svRunning.Value == 0)
if (!string.IsNullOrEmpty(svRunning.Value) && svRunning.Value != "1")
{
throw new ServerException(loc["SERVER_ERROR_NOT_RUNNING"]);
}

View File

@ -8,6 +8,7 @@ using SharedLibraryCore.Exceptions;
using SharedLibraryCore.Helpers;
using SharedLibraryCore.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
@ -68,30 +69,9 @@ namespace IW4MAdmin.Application
try
{
var services = ConfigureServices();
using (var builder = services.BuildServiceProvider())
{
translationLookup = builder.GetRequiredService<ITranslationLookup>();
var importer = builder.GetRequiredService<IPluginImporter>();
importer.Load();
foreach (var type in importer.CommandTypes)
{
services.AddTransient(typeof(IManagerCommand), type);
}
foreach (var commandDefinition in typeof(SharedLibraryCore.Commands.QuitCommand).Assembly.GetTypes()
.Where(_command => _command.BaseType == typeof(Command)))
{
services.AddTransient(typeof(IManagerCommand), commandDefinition);
}
}
serviceProvider = services.BuildServiceProvider();
var pluginImporter = serviceProvider.GetRequiredService<IPluginImporter>();
pluginImporter.Load();
ServerManager = (ApplicationManager)serviceProvider.GetRequiredService<IManager>();
translationLookup = serviceProvider.GetRequiredService<ITranslationLookup>();
// do any needed housekeeping file/folder migrations
ConfigurationMigration.MoveConfigFolder10518(null);
@ -283,8 +263,8 @@ namespace IW4MAdmin.Application
/// </summary>
private static IServiceCollection ConfigureServices()
{
var serviceProvider = new ServiceCollection();
serviceProvider.AddSingleton<IManager, ApplicationManager>()
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IServiceCollection>(_serviceProvider => serviceCollection)
.AddSingleton(new BaseConfigurationHandler<ApplicationConfiguration>("IW4MAdminSettings") as IConfigurationHandler<ApplicationConfiguration>)
.AddSingleton(new BaseConfigurationHandler<CommandConfiguration>("CommandConfiguration") as IConfigurationHandler<CommandConfiguration>)
.AddSingleton(_serviceProvider => _serviceProvider.GetRequiredService<IConfigurationHandler<ApplicationConfiguration>>().Configuration())
@ -292,14 +272,27 @@ namespace IW4MAdmin.Application
.AddSingleton<ILogger>(_serviceProvider => new Logger("IW4MAdmin-Manager"))
.AddSingleton<IPluginImporter, PluginImporter>()
.AddSingleton<IMiddlewareActionHandler, MiddlewareActionHandler>()
.AddTransient(_serviceProvider =>
{
var importer = _serviceProvider.GetRequiredService<IPluginImporter>();
var config = _serviceProvider.GetRequiredService<CommandConfiguration>();
var layout = _serviceProvider.GetRequiredService<ITranslationLookup>();
// todo: this is disgusting, but I need it until I can figure out a way to dynamically load the plugins without creating an instance.
return importer.CommandTypes.
Union(typeof(SharedLibraryCore.Commands.QuitCommand).Assembly.GetTypes()
.Where(_command => _command.BaseType == typeof(Command)))
.Select(_cmdType => Activator.CreateInstance(_cmdType, config, layout) as IManagerCommand);
})
.AddSingleton(_serviceProvider =>
{
var config = _serviceProvider.GetRequiredService<IConfigurationHandler<ApplicationConfiguration>>().Configuration();
return Localization.Configure.Initialize(useLocalTranslation: config?.UseLocalTranslations ?? false,
customLocale: config?.EnableCustomLocale ?? false ? (config.CustomLocale ?? "en-US") : "en-US");
});
})
.AddSingleton<IManager, ApplicationManager>();
return serviceProvider;
return serviceCollection;
}
}
}

View File

@ -22,12 +22,14 @@ namespace IW4MAdmin.Application.Helpers
{
_logger = logger;
_translationLookup = translationLookup;
Load();
}
/// <summary>
/// Loads all the assembly and javascript plugins
/// </summary>
public void Load()
private void Load()
{
string pluginDir = $"{Utilities.OperatingDirectory}Plugins{Path.DirectorySeparatorChar}";
string[] dllFileNames = null;

View File

@ -1315,7 +1315,7 @@ namespace SharedLibraryCore.Commands
/// <summary>
/// Lists the loaded plugins
/// </summary>
public class ListPluginsCommand : Command
/*public class ListPluginsCommand : Command
{
private readonly IPluginImporter _pluginImporter;
public ListPluginsCommand(CommandConfiguration config, ITranslationLookup translationLookup, IPluginImporter pluginImporter) : base(config, translationLookup)
@ -1337,7 +1337,7 @@ namespace SharedLibraryCore.Commands
}
return Task.CompletedTask;
}
}
}*/
/// <summary>
/// Lists external IP

View File

@ -28,10 +28,5 @@ namespace SharedLibraryCore.Interfaces
/// All assemblies in the plugin folder
/// </summary>
IList<Assembly> Assemblies { get; }
/// <summary>
/// Loads in plugin assemblies and script plugins
/// </summary>
void Load();
}
}

View File

@ -18,63 +18,44 @@ namespace SharedLibraryCore
public string Author { get; set; }
public FileSystemWatcher Watcher { get; private set; }
private Engine ScriptEngine;
private readonly string FileName;
private IManager Manager;
private readonly FileSystemWatcher _watcher;
private readonly string _fileName;
private readonly SemaphoreSlim _fileChanging;
private bool successfullyLoaded;
public ScriptPlugin(string fileName)
public ScriptPlugin(string filename)
{
FileName = fileName;
_fileChanging = new SemaphoreSlim(1, 1);
_watcher = new FileSystemWatcher()
_fileName = filename;
Watcher = new FileSystemWatcher()
{
Path = $"{Utilities.OperatingDirectory}Plugins{Path.DirectorySeparatorChar}",
NotifyFilter = NotifyFilters.Size,
Filter = fileName.Split(Path.DirectorySeparatorChar).Last()
Filter = _fileName.Split(Path.DirectorySeparatorChar).Last()
};
_watcher.Changed += Watcher_Changed;
_watcher.EnableRaisingEvents = true;
Watcher.EnableRaisingEvents = true;
_fileChanging = new SemaphoreSlim(1, 1);
}
~ScriptPlugin()
{
_watcher.Dispose();
Watcher.Dispose();
_fileChanging.Dispose();
}
private async void Watcher_Changed(object sender, FileSystemEventArgs e)
{
try
public async Task Initialize(IManager manager)
{
await _fileChanging.WaitAsync();
await Initialize(Manager);
}
catch (Exception ex)
{
Manager.GetLogger(0).WriteError(Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_ERROR"].FormatExt(Name));
Manager.GetLogger(0).WriteDebug(ex.Message);
}
finally
{
if (_fileChanging.CurrentCount == 0)
{
_fileChanging.Release(1);
}
}
}
public async Task Initialize(IManager mgr)
try
{
// for some reason we get an event trigger when the file is not finished being modified.
// this must have been a change in .NET CORE 3.x
// so if the new file is empty we can't process it yet
if (new FileInfo(FileName).Length == 0L)
if (new FileInfo(_fileName).Length == 0L)
{
return;
}
@ -88,10 +69,9 @@ namespace SharedLibraryCore
}
successfullyLoaded = false;
Manager = mgr;
string script;
using (var stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var stream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var reader = new StreamReader(stream, Encoding.Default))
{
@ -119,13 +99,13 @@ namespace SharedLibraryCore
try
{
if(pluginObject.isParser)
if (pluginObject.isParser)
{
await OnLoadAsync(mgr);
await OnLoadAsync(manager);
IEventParser eventParser = (IEventParser)ScriptEngine.GetValue("eventParser").ToObject();
IRConParser rconParser = (IRConParser)ScriptEngine.GetValue("rconParser").ToObject();
Manager.AdditionalEventParsers.Add(eventParser);
Manager.AdditionalRConParsers.Add(rconParser);
manager.AdditionalEventParsers.Add(eventParser);
manager.AdditionalRConParsers.Add(rconParser);
}
}
catch { }
@ -133,27 +113,17 @@ namespace SharedLibraryCore
if (!firstRun)
{
await OnLoadAsync(mgr);
await OnLoadAsync(manager);
}
successfullyLoaded = true;
}
public async Task OnEventAsync(GameEvent E, Server S)
catch
{
if (successfullyLoaded)
{
try
{
await _fileChanging.WaitAsync();
ScriptEngine.SetValue("_gameEvent", E);
ScriptEngine.SetValue("_server", S);
ScriptEngine.SetValue("_IW4MAdminClient", Utilities.IW4MAdminClient(S));
ScriptEngine.Execute("plugin.onEventAsync(_gameEvent, _server)").GetCompletionValue();
throw;
}
catch { }
finally
{
if (_fileChanging.CurrentCount == 0)
@ -162,11 +132,21 @@ namespace SharedLibraryCore
}
}
}
public async Task OnEventAsync(GameEvent E, Server S)
{
if (successfullyLoaded)
{
ScriptEngine.SetValue("_gameEvent", E);
ScriptEngine.SetValue("_server", S);
ScriptEngine.SetValue("_IW4MAdminClient", Utilities.IW4MAdminClient(S));
await Task.FromResult(ScriptEngine.Execute("plugin.onEventAsync(_gameEvent, _server)").GetCompletionValue());
}
}
public Task OnLoadAsync(IManager manager)
{
Manager.GetLogger(0).WriteDebug($"OnLoad executing for {Name}");
manager.GetLogger(0).WriteDebug($"OnLoad executing for {Name}");
ScriptEngine.SetValue("_manager", manager);
return Task.FromResult(ScriptEngine.Execute("plugin.onLoadAsync(_manager)").GetCompletionValue());
}
@ -181,7 +161,6 @@ namespace SharedLibraryCore
{
if (successfullyLoaded)
{
Manager.GetLogger(0).WriteDebug($"OnUnLoad executing for {Name}");
await Task.FromResult(ScriptEngine.Execute("plugin.onUnloadAsync()").GetCompletionValue());
}
}

View File

@ -21,7 +21,7 @@ namespace WebfrontCore.Controllers
if (s == null)
{
return View("Error", "Invalid server!");
return NotFound();
}
var serverInfo = new ServerInfo()