Example #1
0
        public static void DelTask(string taskType, int hash, int delay = 60)
        {
            ThreadManager.AddSingleTask(info =>
            {
                if (!Tasks.ContainsKey($"{taskType}_{hash}"))
                {
                    return;
                }

                var bcmTask = Tasks[$"{taskType}_{hash}"];

                bcmTask.Status     = BCMTaskStatus.Complete;
                bcmTask.Completion = DateTime.UtcNow;
                bcmTask.Duration   = bcmTask.Completion - bcmTask.Timestamp;

                Thread.Sleep(delay * 1000);
                if (!Tasks.ContainsKey($"{taskType}_{hash}"))
                {
                    return;
                }

                Tasks.Remove($"{taskType}_{hash}");
                SendOutput($"Task complete {hash}");
            }
                                        );
        }
Example #2
0
        public static void DoProcess(World world, BCMCmdArea command, BCCommandAbstract cmdRef)
        {
            if (command.Opts.ContainsKey("forcesync"))
            {
                BCCommandAbstract.SendOutput("Processing Command synchronously...");
                ProcessCommand(world, command, cmdRef);

                return;
            }

            if (BCCommandAbstract.SenderInfo.NetworkConnection != null && !(BCCommandAbstract.SenderInfo.NetworkConnection is TelnetConnection))
            {
                BCCommandAbstract.SendOutput("Processing Async Command... Sending output to log");
            }
            else
            {
                BCCommandAbstract.SendOutput("Processing Async Command...");
            }

            BCTask.AddTask(
                command.CmdType,
                ThreadManager.AddSingleTask(
                    info => ProcessCommand(world, command, cmdRef),
                    null,
                    (info, e) => BCTask.DelTask(command.CmdType, info.GetHashCode()))
                .GetHashCode(),
                command);
        }
Example #3
0
        public override void Execute(List <string> parameters, CommandSenderInfo senderInfo)
        {
            TelemetryTools.CollectEvent("command", "execute", GetCommands()[0]);
            try
            {
                var world      = GameManager.Instance.World ?? throw new FriendlyMessageException(Resources.ErrorWorldNotReady);
                var chunkCache = world.ChunkCache ?? throw new FriendlyMessageException(Resources.ErrorChunkCacheNotReady);

                (var pos1, var pos2) = ParseParams(parameters, senderInfo);
                WorldTools.OrderAreaBounds(ref pos1, ref pos2);

                // Check if all needed chunks are in cache
                foreach (var chunkKey in GetChunksForArea(pos1, pos2, +1))
                {
                    if (!chunkCache.ContainsChunkSync(chunkKey))
                    {
                        throw new FriendlyMessageException(Resources.ErrorAreaTooFarAway);
                    }
                }

                ThreadManager.AddSingleTask(info => RegenerateChunks(pos1, pos2, senderInfo));
            }
            catch (Exception ex)
            {
                CommandTools.HandleCommandException(ex);
            }
        }
Example #4
0
        public override void Execute(List <string> parameters, CommandSenderInfo senderInfo)
        {
            TelemetryTools.CollectEvent("command", "execute", GetCommands()[0]);
            try
            {
                ParseParams(parameters, out var tasks, out bool simulate, out bool auto, out int?timerInterval);
                timerInterval = timerInterval ?? 60 * 10; // every 10 minutes by default

                if (auto)
                {
                    if (!PersistentData.Instance.RepairAuto)
                    {
                        PersistentData.Instance.RepairAuto     = true;
                        PersistentData.Instance.RepairTasks    = tasks;
                        PersistentData.Instance.RepairSimulate = simulate;
                        PersistentData.Instance.RepairInterval = timerInterval.Value; // every 10 minutes by default;
                        PersistentData.Instance.Save();
                        RepairEngine.AutoOn();
                    }
                    else
                    {
                        RepairEngine.AutoOff();
                        PersistentData.Instance.RepairAuto    = false;
                        PersistentData.Instance.RepairCounter = 0;
                        PersistentData.Instance.Save();
                    }
                }
                else
                {
                    ThreadManager.AddSingleTask(delegate
                    {
                        try
                        {
                            var repairEngine = new RepairEngine(tasks, simulate, senderInfo);
                            repairEngine.Start();
                        }
                        catch (Exception ex)
                        {
                            Log.Exception(ex);
                            SdtdConsole.Instance.OutputAsync(senderInfo, string.Format(Resources.ErrorDuringCommand, ex.Message));
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                CommandTools.HandleCommandException(ex);
            }
        }
        /// <summary>
        /// Must be called at ServerRegistered event or later because only then it got the external ip address
        /// </summary>
        private static void Collect(NameValueCollection payload)
        {
            ServicePointManager.ServerCertificateValidationCallback += ServerCertificateValidationHandler;
            var gameInfo = Steam.Masterserver.Server.LocalGameInfo;

            payload["v"]   = "1";                                                                              // version
            payload["tid"] = "UA-110885986-1";                                                                 // trackingId
            payload["cid"] = ClientId;                                                                         // clientId
            payload["an"]  = Constants.ModName;                                                                // applicationName
            payload["aid"] = Constants.ModId;                                                                  // applicationId;
            payload["av"]  = ModVersion;                                                                       // applicationVersion
            payload["cd1"] = gameInfo.GetValue(GameInfoString.GameHost);                                       // ServerName
            payload["cd3"] = gameInfo.GetValue(GameInfoString.IP) + ":" + gameInfo.GetValue(GameInfoInt.Port); // IPPort
            payload["cd5"] = global::Constants.cVersion + " " + global::Constants.cVersionBuild;               // GameVersion
            payload["cd6"] = ClientId;                                                                         // clientId

            // Execute asynchronously to avoid blocking the main thread
            ThreadManager.AddSingleTask(CollectCallback, payload, null, false);
        }
Example #6
0
        public static void ChunkObserver(BCMCmdArea command, World world, int timeoutSec)
        {
            var pos           = command.HasPos ? command.Position.ToV3() : command.ChunkBounds.ToV3();
            var viewDim       = !command.Opts.ContainsKey("r") ? command.Radius : command.ChunkBounds.GetRadius();
            var chunkObserver = world.m_ChunkManager.AddChunkObserver(pos, false, viewDim, -1);

            var timerSec = 60;

            if (command.Opts.ContainsKey("ts") && command.Opts["ts"] != null)
            {
                int.TryParse(command.Opts["ts"], out timerSec);
            }
            timerSec += timeoutSec;
            BCTask.AddTask(
                command.CmdType,
                ThreadManager.AddSingleTask(
                    info => DoCleanup(world, chunkObserver, command.CmdType, timerSec, info),
                    null,
                    (info, e) => BCTask.DelTask(command.CmdType, info.GetHashCode(), 120)
                    ).GetHashCode(),
                command);
        }
        private static void LogMessageReceived(string condition, string stackTrace, LogType type)
        {
            // Scan not more than every 5 seconds while log is spammed with error messages
            if (_lastLogMessageTriggeredScan.AddSeconds(5) > DateTime.Now)
            {
                return;
            }

            _lastLogMessageTriggeredScan = DateTime.Now;

            // Check if this is the exception we are looking for
            if (type == LogType.Exception &&
                condition == "NullReferenceException: Object reference not set to an instance of an object" &&
                stackTrace != null && stackTrace.StartsWith("TileEntityPoweredTrigger.write"))
            {
                // Doing it in background task so that NRE appears before our output in log
                ThreadManager.AddSingleTask(info => RepairPowerBlocks());
            }
            else
            {
                Log.Debug($"Intercepted unknown log message:\r\ncondition={condition ?? "<null>"}\r\ntype={type}\r\nstackTrace={stackTrace ?? "<null>"}");
            }
        }
Example #8
0
        private static void ScriptsChanged(object sender, FileSystemEventArgs args)
        {
            // Allow only one simultaneous event and skip all others
            lock (_scriptsChangedLock)
            {
                if (_scriptsChangedRunning)
                {
                    return;
                }
                _scriptsChangedRunning = true;
            }

            ThreadManager.AddSingleTask(info =>
            {
                try
                {
                    Log.Out("Changes in scripts folder detected. Reloading commands ...");

                    // Let all other associated events pass by
                    Thread.Sleep(500);

                    // Reload commands
                    UnloadCommands();
                    InitScripts();
                    PatchTools.ApplyPatches();
                }
                catch (Exception ex)
                {
                    Log.Error("Error occured while changes in script folder were processed: " + ex);
                }
                finally
                {
                    _scriptsChangedRunning = false;
                }
            });
        }