AdminLog.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include <stdarg.h> // for String_vprintf()
  16. #include "admin/Admin.h"
  17. #include "admin/AdminLog.h"
  18. #include "benc/Dict.h"
  19. #include "benc/List.h"
  20. #include "benc/String.h"
  21. #include "crypto/random/Random.h"
  22. #include "util/log/Log.h"
  23. #include "util/log/Log_impl.h"
  24. #include "util/Hex.h"
  25. #include "util/Identity.h"
  26. #include "util/events/Time.h"
  27. #include "util/events/Timeout.h"
  28. #define MAX_SUBSCRIPTIONS 64
  29. #define FILE_NAME_COUNT 32
  30. struct Subscription
  31. {
  32. /** The log level to match against, all higher levels will also be matched. */
  33. enum Log_Level logLevel;
  34. /** The line number within the file or 0 to match all lines. */
  35. int lineNum;
  36. /** The name of the file to match against or null to match any file. */
  37. const char* file;
  38. /** True if file can be compared with pointer comparison instead of strcmp. */
  39. bool internalFile;
  40. /**
  41. * Dropped messages because they are being sent too fast for UDP interface to handle.
  42. * Reset when the pipes unclog an a message is sent reporting the number of dropped messages.
  43. */
  44. int dropped;
  45. /** The transaction ID of the message which solicited this stream of logs. */
  46. String* txid;
  47. /** A hopefully unique (random) number identifying this stream. */
  48. String* streamId;
  49. /** An allocator which will live during the lifecycle of the Subscription */
  50. struct Allocator* alloc;
  51. };
  52. struct AdminLog
  53. {
  54. struct Log pub;
  55. struct Subscription subscriptions[MAX_SUBSCRIPTIONS];
  56. int subscriptionCount;
  57. /** non-zero if we are logging at this very moment (reentrent logging is not allowed!) */
  58. int logging;
  59. struct Timeout* unpause;
  60. struct Admin* admin;
  61. struct Allocator* alloc;
  62. struct Random* rand;
  63. EventBase_t* base;
  64. Identity
  65. };
  66. static inline bool isMatch(struct Subscription* subscription,
  67. struct AdminLog* logger,
  68. enum Log_Level logLevel,
  69. const char* file,
  70. int line)
  71. {
  72. if (subscription->file) {
  73. if (subscription->file == file) {
  74. // fall through
  75. } else if (!subscription->internalFile && !CString_strcmp(file, subscription->file)) {
  76. // It's the same name but so we'll swap the name for the internal name and then
  77. // it can be compared quickly with a pointer comparison.
  78. subscription->file = file;
  79. subscription->internalFile = true;
  80. } else {
  81. return false;
  82. }
  83. }
  84. if (logLevel < subscription->logLevel) {
  85. return false;
  86. }
  87. if (subscription->lineNum && line != subscription->lineNum) {
  88. return false;
  89. }
  90. return true;
  91. }
  92. static String* STREAM_ID = String_CONST_SO("streamId");
  93. static String* TIME = String_CONST_SO("time");
  94. static String* LEVEL = String_CONST_SO("level");
  95. static String* STR_FILE = String_CONST_SO("file");
  96. static String* LINE = String_CONST_SO("line");
  97. static String* MESSAGE = String_CONST_SO("message");
  98. static Dict* makeLogMessage(struct Subscription* subscription,
  99. struct AdminLog* logger,
  100. enum Log_Level logLevel,
  101. const char* file,
  102. uint32_t line,
  103. String* message,
  104. struct Allocator* alloc)
  105. {
  106. int64_t now = (int64_t) Time_currentTimeSeconds();
  107. Dict* out = Dict_new(alloc);
  108. Dict_putString(out, STREAM_ID, subscription->streamId, alloc);
  109. Dict_putInt(out, TIME, now, alloc);
  110. Dict_putString(out, LEVEL, String_new(Log_nameForLevel(logLevel), alloc), alloc);
  111. Dict_putString(out, STR_FILE, String_new(file, alloc), alloc);
  112. Dict_putInt(out, LINE, line, alloc);
  113. Dict_putString(out, MESSAGE, message, alloc);
  114. return out;
  115. }
  116. static void removeSubscription(struct AdminLog* log, struct Subscription* sub)
  117. {
  118. Allocator_free(sub->alloc);
  119. log->subscriptionCount--;
  120. if (log->subscriptionCount == 0 || sub == &log->subscriptions[log->subscriptionCount]) {
  121. return;
  122. }
  123. Bits_memcpy(sub,
  124. &log->subscriptions[log->subscriptionCount],
  125. sizeof(struct Subscription));
  126. }
  127. static void unpause(void* vAdminLog)
  128. {
  129. struct AdminLog* log = Identity_check((struct AdminLog*) vAdminLog);
  130. // dirty reentrence.
  131. Assert_true(!log->logging);
  132. bool noneDropped = true;
  133. for (int i = log->subscriptionCount - 1; i >= 0; i--) {
  134. int dropped = log->subscriptions[i].dropped;
  135. if (!dropped) { continue; }
  136. noneDropped = false;
  137. log->subscriptions[i].dropped = 0;
  138. Log_warn((struct Log*) log,
  139. "UDPInterface cannot handle the logging, [%d] messages dropped", dropped);
  140. if (log->subscriptions[i].dropped) {
  141. // oh well, we'll try again later.
  142. log->subscriptions[i].dropped += dropped;
  143. }
  144. }
  145. if (noneDropped && false) {
  146. Timeout_clearTimeout(log->unpause);
  147. log->unpause = NULL;
  148. }
  149. }
  150. static void doLog(struct Log* genericLog,
  151. enum Log_Level logLevel,
  152. const char* fullFilePath,
  153. int line,
  154. const char* format,
  155. va_list args)
  156. {
  157. struct AdminLog* log = Identity_check((struct AdminLog*) genericLog);
  158. String* message = NULL;
  159. struct Allocator* logLineAlloc = NULL;
  160. if (log->logging) { return; }
  161. log->logging++;
  162. for (int i = log->subscriptionCount - 1; i >= 0; i--) {
  163. if (!isMatch(&log->subscriptions[i], log, logLevel, fullFilePath, line)) { continue; }
  164. if (log->subscriptions[i].dropped) {
  165. log->subscriptions[i].dropped++;
  166. continue;
  167. }
  168. if (!message) {
  169. logLineAlloc = Allocator_child(log->alloc);
  170. message = String_vprintf(logLineAlloc, format, args);
  171. // Strip all of the annoying \n marks in the log entries.
  172. if (message->len > 0 && message->bytes[message->len - 1] == '\n') {
  173. message->len--;
  174. }
  175. }
  176. Dict* d = makeLogMessage(&log->subscriptions[i],
  177. log,
  178. logLevel,
  179. fullFilePath,
  180. line,
  181. message,
  182. logLineAlloc);
  183. int ret = Admin_sendMessage(d, log->subscriptions[i].txid, log->admin);
  184. if (ret == Admin_sendMessage_CHANNEL_CLOSED) {
  185. removeSubscription(log, &log->subscriptions[i]);
  186. } else if (ret) {
  187. log->subscriptions[i].dropped++;
  188. if (!log->unpause) {
  189. log->unpause = Timeout_setInterval(unpause, log, 10, log->base, log->alloc);
  190. }
  191. }
  192. }
  193. if (logLineAlloc) {
  194. Allocator_free(logLineAlloc);
  195. }
  196. Assert_true(!--log->logging);
  197. }
  198. static void subscribe(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  199. {
  200. struct AdminLog* log = Identity_check((struct AdminLog*) vcontext);
  201. String* levelName = Dict_getStringC(args, "level");
  202. enum Log_Level level = (levelName) ? Log_levelForName(levelName->bytes) : Log_Level_DEBUG;
  203. int64_t* lineNumPtr = Dict_getIntC(args, "line");
  204. String* fileStr = Dict_getStringC(args, "file");
  205. if (fileStr && !fileStr->len) { fileStr = NULL; }
  206. char* error = "2+2=5";
  207. if (level == Log_Level_INVALID) {
  208. level = Log_Level_KEYS;
  209. }
  210. if (lineNumPtr && *lineNumPtr < 0) {
  211. error = "Invalid line number, must be positive or 0 to signify any line is acceptable.";
  212. } else if (log->subscriptionCount >= MAX_SUBSCRIPTIONS) {
  213. error = "Max subscription count reached.";
  214. } else {
  215. struct Subscription* sub = &log->subscriptions[log->subscriptionCount];
  216. Bits_memset(sub, 0, sizeof(struct Subscription));
  217. sub->logLevel = level;
  218. sub->alloc = Allocator_child(log->alloc);
  219. String* fileStrCpy = String_clone(fileStr, sub->alloc);
  220. sub->file = (fileStrCpy) ? fileStrCpy->bytes : NULL;
  221. sub->lineNum = (lineNumPtr) ? *lineNumPtr : 0;
  222. sub->txid = String_clone(txid, sub->alloc);
  223. uint8_t streamId[8];
  224. Random_bytes(log->rand, streamId, 8);
  225. uint8_t streamIdHex[20];
  226. Hex_encode(streamIdHex, 20, streamId, 8);
  227. sub->streamId = String_new(streamIdHex, sub->alloc);
  228. Dict response = Dict_CONST(
  229. String_CONST("error"), String_OBJ(String_CONST("none")), Dict_CONST(
  230. String_CONST("streamId"), String_OBJ(sub->streamId), NULL
  231. ));
  232. Admin_sendMessage(&response, txid, log->admin);
  233. log->subscriptionCount++;
  234. return;
  235. }
  236. Dict response = Dict_CONST(
  237. String_CONST("error"), String_OBJ(String_CONST(error)), NULL
  238. );
  239. Admin_sendMessage(&response, txid, log->admin);
  240. }
  241. static void unsubscribe(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  242. {
  243. struct AdminLog* log = Identity_check((struct AdminLog*) vcontext);
  244. String* streamIdHex = Dict_getStringC(args, "streamId");
  245. uint8_t streamId[8];
  246. char* error = NULL;
  247. if (streamIdHex->len != 16 || Hex_decode(streamId, 8, (uint8_t*)streamIdHex->bytes, 16) != 8) {
  248. error = "Invalid streamId.";
  249. } else {
  250. error = "No such subscription.";
  251. for (int i = 0; i < (int)log->subscriptionCount; i++) {
  252. if (String_equals(streamIdHex, log->subscriptions[i].streamId)) {
  253. removeSubscription(log, &log->subscriptions[i]);
  254. error = "none";
  255. break;
  256. }
  257. }
  258. }
  259. Dict response = Dict_CONST(
  260. String_CONST("error"), String_OBJ(String_CONST(error)), NULL
  261. );
  262. Admin_sendMessage(&response, txid, log->admin);
  263. }
  264. static void logMany(Dict* args, void* vcontext, String* txid, struct Allocator* alloc)
  265. {
  266. struct AdminLog* log = Identity_check((struct AdminLog*) vcontext);
  267. int64_t* countPtr = Dict_getIntC(args, "count");
  268. uint32_t count = *countPtr;
  269. for (uint32_t i = 0; i < count; i++) {
  270. Log_debug((struct Log*)log, "This is message number [%d] of total [%d]", i, count);
  271. }
  272. Dict response = Dict_CONST(
  273. String_CONST("error"), String_OBJ(String_CONST("none")), NULL
  274. );
  275. Admin_sendMessage(&response, txid, log->admin);
  276. }
  277. static void subscriptions(Dict* args, void* vcontext, String* txid, struct Allocator* alloc)
  278. {
  279. struct AdminLog* log = Identity_check((struct AdminLog*) vcontext);
  280. Dict* msg = Dict_new(alloc);
  281. List* entries = List_new(alloc);
  282. Dict_putListC(msg, "entries", entries, alloc);
  283. for (int i = 0; i < (int)log->subscriptionCount; i++) {
  284. Dict* entry = Dict_new(alloc);
  285. struct Subscription* sub = &log->subscriptions[i];
  286. Dict_putString(entry, LEVEL, String_new(Log_nameForLevel(sub->logLevel), alloc), alloc);
  287. if (sub->file) {
  288. Dict_putString(entry, STR_FILE, String_new(sub->file, alloc), alloc);
  289. }
  290. Dict_putInt(entry, LINE, sub->lineNum, alloc);
  291. Dict_putIntC(entry, "dropped", sub->dropped, alloc);
  292. Dict_putIntC(entry, "internalFile", sub->internalFile, alloc);
  293. Dict_putStringC(entry, "streamId", sub->streamId, alloc);
  294. List_addDict(entries, entry, alloc);
  295. }
  296. Admin_sendMessage(msg, txid, log->admin);
  297. }
  298. struct Log* AdminLog_registerNew(struct Admin* admin,
  299. struct Allocator* alloc,
  300. struct Random* rand,
  301. EventBase_t* base)
  302. {
  303. struct AdminLog* log = Allocator_clone(alloc, (&(struct AdminLog) {
  304. .pub = {
  305. .print = doLog
  306. },
  307. .admin = admin,
  308. .alloc = alloc,
  309. .rand = rand,
  310. .base = base
  311. }));
  312. Identity_set(log);
  313. Admin_registerFunction("AdminLog_subscribe", subscribe, log, true,
  314. ((struct Admin_FunctionArg[]) {
  315. { .name = "level", .required = 0, .type = "String" },
  316. { .name = "line", .required = 0, .type = "Int" },
  317. { .name = "file", .required = 0, .type = "String" }
  318. }), admin);
  319. Admin_registerFunction("AdminLog_unsubscribe", unsubscribe, log, true,
  320. ((struct Admin_FunctionArg[]) {
  321. { .name = "streamId", .required = 1, .type = "String" }
  322. }), admin);
  323. Admin_registerFunction("AdminLog_subscriptions", subscriptions, log, true, NULL, admin);
  324. Admin_registerFunction("AdminLog_logMany", logMany, log, true,
  325. ((struct Admin_FunctionArg[]) {
  326. { .name = "count", .required = 1, .type = "Int" }
  327. }), admin);
  328. return &log->pub;
  329. }