NadekoBot/NadekoBot.Core/Services/ShardsCoordinator.cs

94 lines
3.0 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;
2017-07-05 15:38:38 +00:00
private readonly int _curProcessId;
2017-10-09 22:04:02 +00:00
public ShardsCoordinator(IDataCache cache)
{
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];
2017-10-09 22:04:02 +00:00
for (int i = 0; i < Statuses.Length; i++)
{
Statuses[i] = new ShardComMessage();
var s = Statuses[i];
s.ConnectionState = Discord.ConnectionState.Disconnected;
s.Guilds = 0;
s.ShardId = i;
s.Time = DateTime.Now - TimeSpan.FromMinutes(1);
}
_log = LogManager.GetCurrentClassLogger();
2017-10-09 22:04:02 +00:00
_comServer = new ShardComServer(cache);
_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,
2017-10-09 22:04:02 +00:00
Arguments = string.Format(_creds.ShardRunArguments, i, _curProcessId, "")
});
2017-10-09 22:04:02 +00:00
// last "" in format is for backwards compatibility
// because current startup commands have {2} in them probably
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 { }
}
}
}
}