Beispiel #1
0
        public async Task <string> Setup(IChatResponseToken icrt, GameServer gameServer)
        {
            try
            {
                _logger.LogInformation($"Setting up {gameServer.ServerName}...");

                var progression = new Progress <JSONMessage>();

                DockerContainer dcsu = new DockerContainer(_logger, icrt, gameServer);

                progression.ProgressChanged += dcsu.HandleUpdate;

                await _client.Images.CreateImageAsync(new ImagesCreateParameters
                {
                    FromImage = gameServer.ContainerName,
                    Tag       = gameServer.ContainerTag
                },
                                                      new AuthConfig(),
                                                      progression);

                _containerStore.TryAdd(dcsu.ID, dcsu);
                _logger.LogInformation($"Completed setup for {gameServer.ServerName}...");
                return(dcsu.ID);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error setting up docker container. {ex.Message}");
                throw;
            }
        }
Beispiel #2
0
        public DockerContainer(ILogger logger, IChatResponseToken icrt, GameServer gs)
        {
            _icrt      = icrt;
            _logger    = logger;
            GameServer = gs;

            var task = _icrt.Respond($"Current status is: Initialising...");

            _initialMessageID = task.Result;
        }
Beispiel #3
0
        private async Task <bool> VerifyUser(string serverId, string userId, IChatResponseToken icrt)
        {
            if (await _allowList.IsUserAllowed(serverId, userId))
            {
                return(true);
            }

            await icrt.Respond("I'm not allowed to talk to you, ask your server admin to allowlist you!");

            return(false);
        }
Beispiel #4
0
        public async Task Run(string serverId, IChatResponseToken icrt, string id)
        {
            try
            {
                _containerStore.TryGetValue(id, out DockerContainer gameServerContainer);
                if (gameServerContainer == null)
                {
                    _logger.LogWarning($"Couldn't find container with id {id}");
                    return;
                }

                var gameServer = gameServerContainer.GameServer;
                _logger.LogInformation($"{gameServer.ServerName} for ServerId:{serverId} starting run.");

                var mounts          = new List <Mount>();
                var portAssignments = await GeneratePortAssignments(gameServer);

                var environmentVariables = await GenerateEnvironmentVariables(gameServer);

                // Create basic server dirs if they don't exist already
                var gameFilesPath = await _fileStore.GetGameServerDirectoryOrCreateIt(serverId, gameServer);

                // Create all the mounts for the containers
                foreach (var bindData in gameServer.Binds ?? Enumerable.Empty <string>())
                {
                    mounts.Add(await CreateContainerMount(gameFilesPath, bindData));
                }

                var response = await _client.Containers.CreateContainerAsync(new CreateContainerParameters
                {
                    Image        = $"{gameServer.ContainerName}:{gameServer.ContainerTag}",
                    Name         = $"{serverId}-{gameServer.ServerName.Replace(" ", "")}",
                    ExposedPorts = portAssignments.Item2,
                    HostConfig   = new HostConfig
                    {
                        PortBindings    = portAssignments.Item1,
                        PublishAllPorts = false,
                        Mounts          = mounts
                    },
                    Env = environmentVariables,
                    Cmd = gameServer.Commands
                });

                await _client.Containers.StartContainerAsync(response.ID, null);

                _logger.LogInformation($"{gameServer.ServerName} for ServerId:{serverId} now running.");
                await icrt.UpdateLastInteractedWithMessage($"{gameServer.ServerName} available at: "
                                                           + $"{await _ipGetter.GetIp()} With Ports:\n {String.Join("\n", portAssignments.Item2.Select(x => x.Key))}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error running docker container. {ex.Message}");
            }
        }
Beispiel #5
0
        private async Task AttemptStop(string serverId, string input, IChatResponseToken responseToken)
        {
            // Time to do some work
            var serverName = ChatHelper.PreParseInputString(input.Replace("-stop ", ""));
            var gameServer = _serverStore.GetGameServerByName(serverName, GetContainerInterfaceType());

            if (gameServer == null)
            {
                await _containerInterface.StopById(serverId, responseToken, serverName);
            }
            else
            {
                await _containerInterface.Stop(serverId, responseToken, gameServer);
            }
        }
Beispiel #6
0
        public async Task StopById(string serverId, IChatResponseToken icrt, string containerId)
        {
            var messageId = await icrt.Respond($"Stopping game server {containerId}.");

            var success = await StopAndRemove(containerId);

            if (success)
            {
                await icrt.Update(messageId, $"Game server {containerId} removed.");
            }
            else
            {
                await icrt.Update(messageId, "No servers to stop found.");
            }
        }
Beispiel #7
0
        private async Task AttemptRun(string serverId, string input, IChatResponseToken responseToken)
        {
            // Time to do some work
            var serverName = ChatHelper.PreParseInputString(input.Replace("-run ", "").Replace("-start ", ""));
            var gameServer = _serverStore.GetGameServerByName(serverName, GetContainerInterfaceType());

            if (gameServer == null)
            {
                await responseToken.Respond("Image could not be found. Find all possible game servers with -possible");

                return;
            }
            var contId = await _containerInterface.Setup(responseToken, gameServer);

            await _containerInterface.Run(serverId, responseToken, contId);
        }
Beispiel #8
0
        public async Task Stop(string serverId, IChatResponseToken icrt, GameServer gameServer)
        {
            var allContainers = await GetAllContainersRanByServer(serverId);

            var gameContainers = allContainers.Where(x => x.Image.Contains(gameServer.ContainerName)).ToList();

            if (gameContainers.Any() == false)
            {
                await icrt.Respond("No servers to stop found.");

                return;
            }

            if (gameContainers.Count() == 1)
            {
                var messageId = await icrt.Respond($"Stopping game server {gameServer.ServerName}.");

                await StopAndRemove(gameContainers[0].ID);

                await icrt.Update(messageId, $"Game server {gameServer.ServerName} removed.");

                _logger.LogInformation($"{gameServer.ServerName} for ServerId:{serverId} stopped and removed.");
            }

            if (gameContainers.Count() > 1)
            {
                string runningContainerIds = "";

                foreach (var cont in gameContainers)
                {
                    runningContainerIds += $"{cont.ID} {cont.Image} {cont.Created} \n";
                }

                await icrt.Respond($"Which container would you like me to stop? `-stop *containerid*`\n Containers: {runningContainerIds}");
            }
        }
Beispiel #9
0
        public async Task ProcessMessage(string serverID, IChatResponseToken icrt, string senderID, string input)
        {
            // Make the initial command case insensitive
            var firstCommand = input.Split(" ")[0].ToLower();

            // Switch statement for all commands that are constant
            switch (firstCommand)
            {
            case "-help":
                await icrt.Respond(@"Command list:
                    `-ping` Will return if Sergen is alive.
                    `-ip` Will respond the ip of the main.
                    `-version` Will return 1.0.0 because I'm too lazy to fix the version.
                    `-running` Will return all the running game servers for this discord server.
                    `-possible` Will return all possible game servers.
                    `-run {Game Server}` Will start a game server of that type.
                    `-stop {Game Server}` Will stop a game server of that type.
                    `-allowlist` Will show you your current allowlist.
                    `-allowlist enable/disable` Will enable/disable the allowlist.
                    `-allowlist add @user` Will enable that user to control servers.
                    `-allowlist remove @user` Will stop that user from controlling servers.
                     ");

                break;

            case "-ping":
                var processingTime = DateTime.Now.Subtract(icrt.SendTime);
                await icrt.Respond(processingTime.Milliseconds + "ms");

                break;

            case "-ip":
                await icrt.Respond($"My IP Address is: {await _ipGetter.GetIp()}");

                break;

            case "-whoami":
                await icrt.Respond($"You are: {_context.GetUsername(senderID)}");

                break;

            case "-version":
                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
                string version = fvi.FileVersion;
                await icrt.Respond($"My version is: {version}");

                break;

            case "-running":
                var allcontainers = ObjectToString.Convert(await _containerInterface.GetRunningContainers(serverID));
                await icrt.Respond($"Running containers are: {allcontainers}");

                break;

            case "-possible":
                var servers          = _serverStore.GetAllServers(GetContainerInterfaceType());
                var serverNames      = servers.Select(s => s.ServerName).ToList();
                var serverStringList = ObjectToString.Convert(serverNames);
                await icrt.Respond($"Possible game servers are: {serverStringList}");

                break;
            }

            if (input.StartsWith("-run ") || input.StartsWith("-start "))
            {
                if (await VerifyUser(serverID, senderID, icrt))
                {
                    await AttemptRun(serverID, input, icrt);
                }
                return;
            }

            if (input.StartsWith("-stop "))
            {
                if (await VerifyUser(serverID, senderID, icrt))
                {
                    await AttemptStop(serverID, input, icrt);
                }
                return;
            }

            if (input.StartsWith("-allowlist"))
            {
                if (await _allowList.IsUserAllowedToManage(serverID, senderID))
                {
                    if (input.StartsWith("-allowlist add "))
                    {
                        await _allowList.AddUser(serverID, input.Replace("-allowlist add ", ""));

                        await icrt.Respond("User added.");

                        return;
                    }

                    if (input.StartsWith("-allowlist remove "))
                    {
                        await _allowList.RemoveUser(serverID, input.Replace("-allowlist remove ", ""));

                        await icrt.Respond("User removed.");

                        return;
                    }

                    if (input.StartsWith("-allowlist enable"))
                    {
                        await _allowList.SetAllowListStatus(serverID, true);

                        await icrt.Respond("Allow list enabled.");

                        return;
                    }

                    if (input.StartsWith("-allowlist disable"))
                    {
                        await _allowList.SetAllowListStatus(serverID, false);

                        await icrt.Respond("Allow list disabled.");

                        return;
                    }

                    var allowList = await _allowList.GetAllowList(serverID);

                    var rawAllowList = string.Join("\n", allowList.Select(x => x.ToString()).ToArray());
                    await icrt.Respond("Allow list:\n" + rawAllowList);

                    return;
                }

                await icrt.Respond("I'm not allowed to talk to you, ask your server admin to allowlist you!");
            }
        }