NadekoBot/NadekoBot.Core/Services/ShardsCoordinator.cs

83 lines
2.5 KiB
C#
Raw Normal View History

2017-09-29 22:46:33 +00:00
using NadekoBot.Services.Impl;
using NLog;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
2017-07-17 19:42:36 +00:00
using NadekoBot.Common.ShardCom;
2017-09-29 22:46:33 +00:00
namespace NadekoBot.Services
{
public class ShardsCoordinator
{
2017-07-17 19:42:36 +00:00
private readonly BotCredentials _creds;
private readonly Process[] _shardProcesses;
public ShardComMessage[] Statuses { get; }
public int GuildCount => Statuses.ToArray()
.Where(x => x != null)
.Sum(x => x.Guilds);
private readonly Logger _log;
private readonly ShardComServer _comServer;
private readonly int _port;
2017-07-05 15:38:38 +00:00
private readonly int _curProcessId;
public ShardsCoordinator(int port)
{
LogSetup.SetupLogger();
2017-07-17 19:42:36 +00:00
_creds = new BotCredentials();
_shardProcesses = new Process[_creds.TotalShards];
2017-07-17 19:42:36 +00:00
Statuses = new ShardComMessage[_creds.TotalShards];
_log = LogManager.GetCurrentClassLogger();
_port = port;
_comServer = new ShardComServer(port);
_comServer.Start();
_comServer.OnDataReceived += _comServer_OnDataReceived;
2017-07-05 15:38:38 +00:00
_curProcessId = Process.GetCurrentProcess().Id;
}
private Task _comServer_OnDataReceived(ShardComMessage msg)
{
Statuses[msg.ShardId] = msg;
if (msg.ConnectionState == Discord.ConnectionState.Disconnected || msg.ConnectionState == Discord.ConnectionState.Disconnecting)
_log.Error("!!! SHARD {0} IS IN {1} STATE", msg.ShardId, msg.ConnectionState.ToString());
return Task.CompletedTask;
}
2017-06-20 02:23:11 +00:00
public async Task RunAsync()
{
2017-07-17 19:42:36 +00:00
for (int i = 1; i < _creds.TotalShards; i++)
{
var p = Process.Start(new ProcessStartInfo()
{
2017-07-17 19:42:36 +00:00
FileName = _creds.ShardRunCommand,
Arguments = string.Format(_creds.ShardRunArguments, i, _curProcessId, _port)
});
await Task.Delay(5000);
}
}
2017-06-20 02:23:11 +00:00
public async Task RunAndBlockAsync()
{
try
{
2017-06-20 02:23:11 +00:00
await RunAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_log.Error(ex);
}
2017-07-06 17:30:22 +00:00
await Task.Delay(-1);
foreach (var p in _shardProcesses)
{
try { p.Kill(); } catch { }
try { p.Dispose(); } catch { }
}
}
}
}