csrd_data_dump.sp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /**
  2. * [CSRD] SRCDS Data Dumper
  3. *
  4. * Uses SourceMod dumping commands to dump useful information for plugin developers.
  5. */
  6. #pragma semicolon 1
  7. #include <sourcemod>
  8. #tryinclude <steamtools>
  9. #include <sdktools>
  10. #pragma newdecls required
  11. #include <stocksoup/log_server>
  12. #include <stocksoup/files>
  13. #include <stocksoup/version>
  14. #define PLUGIN_VERSION "1.5.0"
  15. public Plugin myinfo = {
  16. name = "[CSRD] SRCDS Automatic Data Dumper",
  17. author = "nosoop",
  18. description = "Automatically dumps useful engine data for plugin stuff.",
  19. #if defined _steamtools_included
  20. version = PLUGIN_VERSION,
  21. #else
  22. version = PLUGIN_VERSION ... "-no-steamtools",
  23. #endif
  24. url = "https://git.csrd.science/"
  25. }
  26. #define REDUMP_MARKER_FILE "data/.force-data-dump"
  27. #define REDUMP_OUTPUT_DIRECTORY "data/datadump"
  28. // Use a map with as few entities as possible to ensure enough free edicts
  29. #define LOW_ENTITY_MAP "itemtest"
  30. enum DumpAction {
  31. DumpAction_None = 0, // no checks are performed
  32. DumpAction_UpdateCheck, // check if dump indicator is present (TODO change method?)
  33. DumpAction_PendingDump // pending dump on current map
  34. };
  35. DumpAction g_DumpAction;
  36. StringMap g_ConCommandFlagCache;
  37. Handle g_SDKCallGetTFConditionName, g_SDKCallGetTFConditionNamePtr;
  38. public APLRes AskPluginLoad2(Handle hPluginSelf, bool bLateLoaded, char[] error, int err_max) {
  39. if (bLateLoaded) {
  40. // skip dump on late load because it's too late to cache flags for consistency
  41. g_DumpAction = DumpAction_None;
  42. } else {
  43. g_DumpAction = DumpAction_UpdateCheck;
  44. /**
  45. * cache flags early in case a plugin overrides flags
  46. * https://github.com/nosoop/SM-ConVarConfigs does this when all plugins are loaded
  47. */
  48. g_ConCommandFlagCache = new StringMap();
  49. char commandName[128];
  50. bool bIsCommand;
  51. int flags;
  52. Handle hConCommandIter = FindFirstConCommand(commandName, sizeof(commandName),
  53. bIsCommand, flags);
  54. do {
  55. g_ConCommandFlagCache.SetValue(commandName, flags);
  56. } while ( FindNextConCommand(hConCommandIter, commandName, sizeof(commandName),
  57. bIsCommand, flags) );
  58. delete hConCommandIter;
  59. }
  60. return APLRes_Success;
  61. }
  62. public void OnPluginStart() {
  63. Handle hGameConf = LoadGameConfigFile("csrd.data_dump");
  64. if (!hGameConf) {
  65. SetFailState("Failed to load gamedata (csrd.data_dump).");
  66. }
  67. // we call and fetch the pointer to work around alliedmodders/sourcemod#874
  68. // we could read the pointer directly, but ain't got time for that
  69. StartPrepSDKCall(SDKCall_Static);
  70. PrepSDKCall_SetFromConf(hGameConf, SDKConf_Signature, "GetTFConditionName()");
  71. PrepSDKCall_SetReturnInfo(SDKType_PlainOldData, SDKPass_Plain);
  72. PrepSDKCall_AddParameter(SDKType_PlainOldData, SDKPass_Plain);
  73. g_SDKCallGetTFConditionNamePtr = EndPrepSDKCall();
  74. StartPrepSDKCall(SDKCall_Static);
  75. PrepSDKCall_SetFromConf(hGameConf, SDKConf_Signature, "GetTFConditionName()");
  76. PrepSDKCall_SetReturnInfo(SDKType_String, SDKPass_Pointer, VDECODE_FLAG_ALLOWNULL);
  77. PrepSDKCall_AddParameter(SDKType_PlainOldData, SDKPass_Plain);
  78. g_SDKCallGetTFConditionName = EndPrepSDKCall();
  79. delete hGameConf;
  80. RegAdminCmd("csrd_force_data_dump", ForceDataDump, ADMFLAG_ROOT);
  81. }
  82. public void OnMapStart() {
  83. char path[PLATFORM_MAX_PATH];
  84. BuildPath(Path_SM, path, sizeof(path), "%s", REDUMP_MARKER_FILE);
  85. switch (g_DumpAction) {
  86. /**
  87. * Stage 1: Check if the marker file exists; change map if necessary.
  88. * This is performed on first map load.
  89. */
  90. case DumpAction_UpdateCheck: {
  91. if (FileExists(path) || IsNewServerVersion()) {
  92. g_DumpAction = DumpAction_PendingDump;
  93. ForceChangeLevel(LOW_ENTITY_MAP, "Starting server data dump");
  94. } else {
  95. g_DumpAction = DumpAction_None;
  96. // we're not dumping, so there's no point in keeping the cache
  97. delete g_ConCommandFlagCache;
  98. g_ConCommandFlagCache = null;
  99. }
  100. }
  101. /**
  102. * Stage 2: Validate map change and ensure dump is pending; start dumping if so.
  103. */
  104. case DumpAction_PendingDump: {
  105. char currentMap[PLATFORM_MAX_PATH];
  106. GetCurrentMap(currentMap, sizeof(currentMap));
  107. if (StrEqual(LOW_ENTITY_MAP, currentMap)
  108. && (FileExists(path) || IsNewServerVersion())) {
  109. DataPack pack = new DataPack();
  110. pack.WriteString(path);
  111. PerformDataDump(OnDataDumpFinished, pack);
  112. } else {
  113. LogError("Failed to change to map %s", LOW_ENTITY_MAP);
  114. }
  115. }
  116. }
  117. }
  118. bool IsNewServerVersion() {
  119. char updatePath[PLATFORM_MAX_PATH];
  120. BuildPath(Path_SM, updatePath, sizeof(updatePath), "%s/%s", REDUMP_OUTPUT_DIRECTORY,
  121. ".server-version");
  122. if (FileExists(updatePath)) {
  123. char versionString[64];
  124. File versionFile = OpenFile(updatePath, "r");
  125. versionFile.ReadLine(versionString, sizeof(versionString));
  126. delete versionFile;
  127. return GetNetworkPatchVersion() > StringToInt(versionString);
  128. }
  129. return true;
  130. }
  131. void PerformDataDump(RequestFrameCallback postDumpCallback = INVALID_FUNCTION, any data = 0) {
  132. char outputDirectory[PLATFORM_MAX_PATH];
  133. BuildPath(Path_SM, outputDirectory, sizeof(outputDirectory), REDUMP_OUTPUT_DIRECTORY);
  134. CreateDirectories(outputDirectory, 0b111101000); // u+rwx,g+rx
  135. int version = GetNetworkPatchVersion();
  136. // does not spawn entities
  137. ServerCommand("sm_dump_netprops %s/%d.netprops.txt", outputDirectory, version);
  138. DumpServerCommands("%s/%d.commands.txt", outputDirectory, version);
  139. DumpServerConVars("%s/%d.convars.txt", outputDirectory, version);
  140. DumpUserMessageNames("%s/%d.usermessages.txt", outputDirectory, version);
  141. DumpTFCondNames("%s/%d.tf_conds.txt", outputDirectory, version);
  142. /**
  143. * Spawns all entities, server will crash on map change -- make sure there are 700-ish
  144. * free edicts.
  145. * No more class dump; we'll just generate it with `grep -P '^\w+ - \w+$'` on datamaps.
  146. */
  147. ServerCommand("sm_dump_datamaps %s/%d.datamaps.txt", outputDirectory, version);
  148. ServerCommand("sm_dump_teprops %s/%d.tempents.txt", outputDirectory, version);
  149. // Defer the rest of the actions by a frame to ensure everything is finished processing.
  150. DataPack pack = new DataPack();
  151. pack.WriteFunction(postDumpCallback);
  152. pack.WriteCell(data);
  153. RequestFrame(PerformDataDump_NextFrame, pack);
  154. }
  155. public void PerformDataDump_NextFrame(DataPack pack) {
  156. // Create and update a .server-version file to notify incron of updates
  157. char updatePath[PLATFORM_MAX_PATH];
  158. BuildPath(Path_SM, updatePath, sizeof(updatePath), "%s/%s", REDUMP_OUTPUT_DIRECTORY,
  159. ".server-version");
  160. File versionFile = OpenFile(updatePath, "w");
  161. versionFile.WriteLine("%d", GetNetworkPatchVersion());
  162. delete versionFile;
  163. pack.Reset();
  164. Function postDumpCallback = pack.ReadFunction();
  165. any data = pack.ReadCell();
  166. delete pack;
  167. if (postDumpCallback != INVALID_FUNCTION) {
  168. Call_StartFunction(INVALID_HANDLE, postDumpCallback);
  169. Call_PushCell(data);
  170. Call_Finish();
  171. }
  172. }
  173. /**
  174. * User-defined call when the dumping process is finished.
  175. */
  176. public void OnDataDumpFinished(DataPack pack) {
  177. pack.Reset();
  178. char path[PLATFORM_MAX_PATH];
  179. pack.ReadString(path, sizeof(path));
  180. delete pack;
  181. if (FileExists(path)) {
  182. DeleteFile(path);
  183. }
  184. LogMessage("Dumped server data for network patchversion %d", GetNetworkPatchVersion());
  185. ServerCommand("quit");
  186. }
  187. #if defined _steamtools_included
  188. /**
  189. * Steam master server has requested a restart; game version probably updated.
  190. * Create the file indicating a data dump should be performed.
  191. */
  192. public Action Steam_RestartRequested() {
  193. PrepareRedump();
  194. return Plugin_Continue;
  195. }
  196. #endif
  197. public Action ForceDataDump(int client, int argc) {
  198. PrepareRedump();
  199. ReplyToCommand(client, "[SM] Prepared dump process. Restart server.");
  200. return Plugin_Continue;
  201. }
  202. /* Dump utilities */
  203. void DumpServerCommands(const char[] format, any ...) {
  204. char outputPath[PLATFORM_MAX_PATH];
  205. VFormat(outputPath, sizeof(outputPath), format, 2);
  206. File outputFile = OpenFile(outputPath, "w");
  207. char commandName[128], commandDescription[512];
  208. bool bIsCommand;
  209. int flags;
  210. outputFile.WriteLine("\"%s\",\"%s\",\"%s\"", "Names", "Flags", "Help Text");
  211. Handle hConCommandIter = FindFirstConCommand(commandName, sizeof(commandName), bIsCommand,
  212. flags, commandDescription, sizeof(commandDescription));
  213. do {
  214. if (bIsCommand) {
  215. if (g_ConCommandFlagCache) {
  216. g_ConCommandFlagCache.GetValue(commandName, flags);
  217. }
  218. ReplaceString(commandDescription, sizeof(commandDescription), "\"", "'");
  219. ReplaceString(commandDescription, sizeof(commandDescription), "\n", " / ");
  220. outputFile.WriteLine("\"%s\",\"%s\",\"%s\"", commandName,
  221. GetCommandFlagString(flags), commandDescription);
  222. }
  223. } while ( FindNextConCommand(hConCommandIter, commandName, sizeof(commandName),
  224. bIsCommand, flags, commandDescription, sizeof(commandDescription)) );
  225. delete hConCommandIter;
  226. delete outputFile;
  227. }
  228. void DumpServerConVars(const char[] format, any ...) {
  229. char outputPath[PLATFORM_MAX_PATH];
  230. VFormat(outputPath, sizeof(outputPath), format, 2);
  231. File outputFile = OpenFile(outputPath, "w");
  232. char commandName[128], commandDescription[512];
  233. bool bIsCommand;
  234. int flags;
  235. outputFile.WriteLine("\"%s\",\"%s\",\"%s\",\"%s\"", "Names", "Defaults", "Flags",
  236. "Help Text");
  237. Handle hConCommandIter = FindFirstConCommand(commandName, sizeof(commandName), bIsCommand,
  238. flags, commandDescription, sizeof(commandDescription));
  239. do {
  240. if (!bIsCommand) {
  241. if (g_ConCommandFlagCache) {
  242. g_ConCommandFlagCache.GetValue(commandName, flags);
  243. }
  244. char defaultValue[128];
  245. FindConVar(commandName).GetDefault(defaultValue, sizeof(defaultValue));
  246. ReplaceString(commandDescription, sizeof(commandDescription), "\"", "'");
  247. ReplaceString(commandDescription, sizeof(commandDescription), "\n", " / ");
  248. outputFile.WriteLine("\"%s\",\"%s\",\"%s\",\"%s\"", commandName,
  249. defaultValue, GetCommandFlagString(flags), commandDescription);
  250. }
  251. } while ( FindNextConCommand(hConCommandIter, commandName, sizeof(commandName),
  252. bIsCommand, flags, commandDescription, sizeof(commandDescription)) );
  253. delete hConCommandIter;
  254. delete outputFile;
  255. }
  256. /**
  257. * Dumps user message names to a path created by the format string.
  258. */
  259. void DumpUserMessageNames(const char[] format, any ...) {
  260. char outputPath[PLATFORM_MAX_PATH];
  261. VFormat(outputPath, sizeof(outputPath), format, 2);
  262. File outputFile = OpenFile(outputPath, "w");
  263. outputFile.WriteLine("\"%s\",\"%s\"", "Index", "Name");
  264. char umName[128];
  265. for (int um = 0; GetUserMessageName(view_as<UserMsg>(um), umName, sizeof(umName)); um++) {
  266. outputFile.WriteLine("\"%d\",\"%s\"", um, umName);
  267. }
  268. delete outputFile;
  269. }
  270. void DumpTFCondNames(const char[] format, any ...) {
  271. char outputPath[PLATFORM_MAX_PATH];
  272. VFormat(outputPath, sizeof(outputPath), format, 2);
  273. File outputFile = OpenFile(outputPath, "w");
  274. outputFile.WriteLine("\"%s\",\"%s\"", "Condition Index", "Name");
  275. char condName[64];
  276. int cond;
  277. while (SDKCall(g_SDKCallGetTFConditionNamePtr, cond)
  278. && SDKCall(g_SDKCallGetTFConditionName, condName, sizeof(condName), cond)) {
  279. outputFile.WriteLine("\"%d\",\"%s\"", cond, condName);
  280. cond++;
  281. }
  282. delete outputFile;
  283. }
  284. /**
  285. * Converts bitflags from a ConCommandBase to a space-separated list of flag descriptions.
  286. */
  287. char[] GetCommandFlagString(int flags) {
  288. // static array of flag descriptions, index mapped to corresponding bit
  289. static char s_flagStrings[][] = {
  290. "UNREGISTERED",
  291. "DEVELOPMENTONLY",
  292. "GAMEDLL",
  293. "CLIENTDLL",
  294. "HIDDEN",
  295. "PROTECTED",
  296. "SPONLY",
  297. "ARCHIVE",
  298. "NOTIFY",
  299. "USERINFO",
  300. "PRINTABLEONLY",
  301. "UNLOGGED",
  302. "NEVER_AS_STRING",
  303. "REPLICATED",
  304. "CHEAT",
  305. "SS", // split screen
  306. "DEMO",
  307. "DONTRECORD",
  308. "PLUGIN_OR_SS_ADDED", // split screen; same value as FCVAR_PLUGIN
  309. "RELEASE",
  310. "RELOAD_MATERIALS",
  311. "RELOAD_TEXTURES",
  312. "NOT_CONNECTED",
  313. "MATERIAL_SYSTEM_THREAD",
  314. "ARCHIVE_GAMECONSOLE",
  315. "ACCESSIBLE_FROM_THREADS",
  316. "SERVER_CAN_EXECUTE",
  317. "SERVER_CANNOT_QUERY",
  318. "CLIENTCMD_CAN_EXECUTE"
  319. };
  320. char buffer[512];
  321. for (int i = 0; i < sizeof(s_flagStrings); i++) {
  322. int flagbit = (1 << i);
  323. if (flags & flagbit) {
  324. if (strlen(buffer)) {
  325. StrCat(buffer, sizeof(buffer), " ");
  326. }
  327. StrCat(buffer, sizeof(buffer), s_flagStrings[i]);
  328. }
  329. }
  330. return buffer;
  331. }
  332. /* Dump marker functrions */
  333. void PrepareRedump() {
  334. char path[PLATFORM_MAX_PATH];
  335. BuildPath(Path_SM, path, sizeof(path), "%s", REDUMP_MARKER_FILE);
  336. TouchFile(path);
  337. }
  338. void TouchFile(const char[] file) {
  339. File f = OpenFile(file, "w");
  340. delete f;
  341. }