2020-05-01 23:52:52 +00:00
|
|
|
using Autofac;
|
|
|
|
|
|
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
using Myriad.Gateway;
|
2022-04-10 14:41:26 +00:00
|
|
|
using Myriad.Types;
|
2020-12-22 12:15:26 +00:00
|
|
|
using Myriad.Rest;
|
|
|
|
|
2020-05-01 23:52:52 +00:00
|
|
|
using PluralKit.Core;
|
|
|
|
|
2021-11-07 08:09:45 +00:00
|
|
|
using Sentry;
|
|
|
|
|
2020-05-01 23:52:52 +00:00
|
|
|
using Serilog;
|
2020-05-05 16:12:34 +00:00
|
|
|
using Serilog.Core;
|
2020-05-01 23:52:52 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
namespace PluralKit.Bot;
|
|
|
|
|
|
|
|
public class Init
|
2020-05-01 23:52:52 +00:00
|
|
|
{
|
2022-01-24 13:13:59 +00:00
|
|
|
private static async Task Main(string[] args)
|
2020-05-01 23:52:52 +00:00
|
|
|
{
|
2021-11-27 02:10:56 +00:00
|
|
|
// Load configuration and run global init stuff
|
|
|
|
var config = InitUtils.BuildConfiguration(args).Build();
|
|
|
|
InitUtils.InitStatic();
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2022-01-24 13:13:59 +00:00
|
|
|
// init version service
|
|
|
|
await BuildInfoService.LoadVersion();
|
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// Set up DI container and modules
|
|
|
|
var services = BuildContainer(config);
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2022-01-24 13:13:59 +00:00
|
|
|
await RunWrapper(services, async ct =>
|
2020-05-01 23:52:52 +00:00
|
|
|
{
|
|
|
|
var logger = services.Resolve<ILogger>().ForContext<Init>();
|
2020-05-05 16:12:34 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// Initialize Sentry SDK, and make sure it gets dropped at the end
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
using var _ = SentrySdk.Init(opts =>
|
2020-05-05 16:12:34 +00:00
|
|
|
{
|
2021-11-27 02:10:56 +00:00
|
|
|
opts.Dsn = services.Resolve<CoreConfig>().SentryUrl;
|
|
|
|
opts.Release = BuildInfoService.FullVersion;
|
|
|
|
opts.AutoSessionTracking = true;
|
|
|
|
opts.DisableTaskUnobservedTaskExceptionCapture();
|
|
|
|
});
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2022-02-04 19:53:56 +00:00
|
|
|
var config = services.Resolve<BotConfig>();
|
2022-01-13 17:26:25 +00:00
|
|
|
var coreConfig = services.Resolve<CoreConfig>();
|
2022-02-04 19:53:56 +00:00
|
|
|
|
|
|
|
// initialize Redis
|
2022-01-13 17:26:25 +00:00
|
|
|
var redis = services.Resolve<RedisService>();
|
2022-02-04 19:53:56 +00:00
|
|
|
if (config.UseRedisRatelimiter)
|
|
|
|
await redis.InitAsync(coreConfig);
|
2022-01-13 17:26:25 +00:00
|
|
|
|
2022-01-07 19:26:41 +00:00
|
|
|
if (config.Cluster == null)
|
|
|
|
{
|
|
|
|
// "Connect to the database" (ie. set off database migrations and ensure state)
|
|
|
|
logger.Information("Connecting to database");
|
|
|
|
await services.Resolve<IDatabase>().ApplyMigrations();
|
|
|
|
|
2022-01-22 08:52:52 +00:00
|
|
|
// Clear shard status from Redis
|
2022-02-04 19:53:56 +00:00
|
|
|
if (redis.Connection != null)
|
|
|
|
await redis.Connection.GetDatabase().KeyDeleteAsync("pluralkit:shardstatus");
|
2022-01-07 19:26:41 +00:00
|
|
|
}
|
2021-11-27 02:10:56 +00:00
|
|
|
|
|
|
|
logger.Information("Initializing bot");
|
|
|
|
var bot = services.Resolve<Bot>();
|
2020-05-05 16:12:34 +00:00
|
|
|
|
2022-03-31 00:42:57 +00:00
|
|
|
// Get bot status message from Redis
|
|
|
|
if (redis.Connection != null)
|
|
|
|
bot.CustomStatusMessage = await redis.Connection.GetDatabase().StringGetAsync("pluralkit:botstatus");
|
|
|
|
|
|
|
|
// Init the bot instance itself, register handlers and such to the client before beginning to connect
|
|
|
|
bot.Init();
|
2021-11-29 01:50:13 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// Start the Discord shards themselves (handlers already set up)
|
|
|
|
logger.Information("Connecting to Discord");
|
|
|
|
await StartCluster(services);
|
|
|
|
logger.Information("Connected! All is good (probably).");
|
2020-05-01 23:52:52 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// Lastly, we just... wait. Everything else is handled in the DiscordClient event loop
|
2020-05-01 23:52:52 +00:00
|
|
|
try
|
|
|
|
{
|
2021-11-27 02:10:56 +00:00
|
|
|
await Task.Delay(-1, ct);
|
2020-05-01 23:52:52 +00:00
|
|
|
}
|
2021-11-27 02:10:56 +00:00
|
|
|
catch (TaskCanceledException)
|
2020-05-01 23:52:52 +00:00
|
|
|
{
|
2021-11-27 02:10:56 +00:00
|
|
|
// Once the CancellationToken fires, we need to shut stuff down
|
|
|
|
// (generally happens given a SIGINT/SIGKILL/Ctrl-C, see calling wrapper)
|
|
|
|
await bot.Shutdown();
|
2020-05-01 23:52:52 +00:00
|
|
|
}
|
2021-11-27 02:10:56 +00:00
|
|
|
});
|
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
private static async Task RunWrapper(IContainer services, Func<CancellationToken, Task> taskFunc)
|
|
|
|
{
|
|
|
|
// This function does a couple things:
|
|
|
|
// - Creates a CancellationToken that'll cancel tasks once needed
|
|
|
|
// - Wraps the given function in an exception handler that properly logs errors
|
|
|
|
// - Adds a SIGINT (Ctrl-C) listener through Console.CancelKeyPress to gracefully shut down
|
|
|
|
// - Adds a SIGTERM (kill, systemctl stop, docker stop) listener through AppDomain.ProcessExit (same as above)
|
|
|
|
var logger = services.Resolve<ILogger>().ForContext<Init>();
|
2020-05-01 23:52:52 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
var shutdown = new TaskCompletionSource<object>();
|
|
|
|
var gracefulShutdownCts = new CancellationTokenSource();
|
|
|
|
|
|
|
|
Console.CancelKeyPress += delegate
|
2020-05-01 23:52:52 +00:00
|
|
|
{
|
2021-11-27 02:10:56 +00:00
|
|
|
// ReSharper disable once AccessToDisposedClosure (will only be hit before the below disposal)
|
|
|
|
logger.Information("Received SIGINT/Ctrl-C, attempting graceful shutdown...");
|
|
|
|
gracefulShutdownCts.Cancel();
|
|
|
|
};
|
|
|
|
|
|
|
|
AppDomain.CurrentDomain.ProcessExit += (_, __) =>
|
|
|
|
{
|
|
|
|
// This callback is fired on a SIGKILL is sent.
|
|
|
|
// The runtime will kill the program as soon as this callback is finished, so we have to
|
|
|
|
// block on the shutdown task's completion to ensure everything is sorted by the time this returns.
|
|
|
|
|
|
|
|
// ReSharper disable once AccessToDisposedClosure (it's only disposed after the block)
|
|
|
|
logger.Information("Received SIGKILL event, attempting graceful shutdown...");
|
|
|
|
gracefulShutdownCts.Cancel();
|
|
|
|
var ___ = shutdown.Task.Result; // Blocking! This is the only time it's justified...
|
|
|
|
};
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
await taskFunc(gracefulShutdownCts.Token);
|
|
|
|
logger.Information("Shutdown complete. Have a nice day~");
|
|
|
|
}
|
|
|
|
catch (Exception e)
|
|
|
|
{
|
|
|
|
logger.Fatal(e, "Error while running bot");
|
2020-05-01 23:52:52 +00:00
|
|
|
}
|
2021-06-09 12:49:12 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// Allow the log buffer to flush properly before exiting
|
|
|
|
((Logger)logger).Dispose();
|
|
|
|
await Task.Delay(500);
|
|
|
|
shutdown.SetResult(null);
|
|
|
|
}
|
|
|
|
|
|
|
|
private static IContainer BuildContainer(IConfiguration config)
|
|
|
|
{
|
|
|
|
var builder = new ContainerBuilder();
|
|
|
|
builder.RegisterInstance(config);
|
|
|
|
builder.RegisterModule(new ConfigModule<BotConfig>("Bot"));
|
2021-11-27 03:02:58 +00:00
|
|
|
builder.RegisterModule(new LoggingModule("bot"));
|
2021-11-27 02:10:56 +00:00
|
|
|
builder.RegisterModule(new MetricsModule());
|
|
|
|
builder.RegisterModule<DataStoreModule>();
|
|
|
|
builder.RegisterModule<BotModule>();
|
|
|
|
return builder.Build();
|
|
|
|
}
|
2021-06-09 12:49:12 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
private static async Task StartCluster(IComponentContext services)
|
|
|
|
{
|
2022-01-13 17:26:25 +00:00
|
|
|
var redis = services.Resolve<RedisService>();
|
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
var cluster = services.Resolve<Cluster>();
|
|
|
|
var config = services.Resolve<BotConfig>();
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
if (config.Cluster != null)
|
|
|
|
{
|
2022-04-10 14:41:26 +00:00
|
|
|
var info = new GatewayInfo.Bot()
|
|
|
|
{
|
|
|
|
SessionStartLimit = new()
|
|
|
|
{
|
|
|
|
MaxConcurrency = config.MaxShardConcurrency ?? 1,
|
|
|
|
},
|
|
|
|
Shards = config.Cluster.TotalShards,
|
|
|
|
Url = "wss://gateway.discord.gg",
|
|
|
|
};
|
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// For multi-instance deployments, calculate the "span" of shards this node is responsible for
|
|
|
|
var totalNodes = config.Cluster.TotalNodes;
|
|
|
|
var totalShards = config.Cluster.TotalShards;
|
2022-01-07 19:25:08 +00:00
|
|
|
var nodeIndex = config.Cluster.NodeIndex;
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2021-11-27 02:10:56 +00:00
|
|
|
// Should evenly distribute shards even with an uneven amount of nodes
|
|
|
|
var shardMin = (int)Math.Round(totalShards * (float)nodeIndex / totalNodes);
|
|
|
|
var shardMax = (int)Math.Round(totalShards * (float)(nodeIndex + 1) / totalNodes) - 1;
|
2021-06-09 12:49:12 +00:00
|
|
|
|
2022-01-13 17:26:25 +00:00
|
|
|
await cluster.Start(info.Url, shardMin, shardMax, totalShards, info.SessionStartLimit.MaxConcurrency, redis.Connection);
|
2021-11-27 02:10:56 +00:00
|
|
|
}
|
|
|
|
else
|
2021-06-09 12:49:12 +00:00
|
|
|
{
|
2022-04-10 14:41:26 +00:00
|
|
|
var info = await services.Resolve<DiscordApiClient>().GetGatewayBot();
|
2022-01-13 17:26:25 +00:00
|
|
|
await cluster.Start(info, redis.Connection);
|
2021-06-09 12:49:12 +00:00
|
|
|
}
|
2020-05-01 23:52:52 +00:00
|
|
|
}
|
|
|
|
}
|