|
| 1 | +package org.meteordev.meteorbot; |
| 2 | + |
| 3 | +import com.sun.net.httpserver.HttpExchange; |
| 4 | +import com.sun.net.httpserver.HttpServer; |
| 5 | +import net.dv8tion.jda.api.JDA; |
| 6 | +import net.dv8tion.jda.api.entities.Guild; |
| 7 | +import net.dv8tion.jda.api.events.session.ReadyEvent; |
| 8 | +import net.dv8tion.jda.api.events.session.ShutdownEvent; |
| 9 | +import net.dv8tion.jda.api.hooks.ListenerAdapter; |
| 10 | + |
| 11 | +import java.io.IOException; |
| 12 | +import java.io.OutputStream; |
| 13 | +import java.net.InetSocketAddress; |
| 14 | +import java.nio.charset.StandardCharsets; |
| 15 | + |
| 16 | +public class Metrics extends ListenerAdapter { |
| 17 | + private Guild guild; |
| 18 | + private HttpServer server; |
| 19 | + |
| 20 | + @Override |
| 21 | + public void onReady(ReadyEvent event) { |
| 22 | + JDA bot = event.getJDA(); |
| 23 | + |
| 24 | + guild = bot.getGuildById(Env.GUILD_ID.value); |
| 25 | + if (guild == null) { |
| 26 | + MeteorBot.LOG.error("Couldn't find the specified server."); |
| 27 | + System.exit(1); |
| 28 | + } |
| 29 | + |
| 30 | + try { |
| 31 | + server = HttpServer.create(new InetSocketAddress(9400), 0); |
| 32 | + server.createContext("/metrics", this::onRequest); |
| 33 | + server.start(); |
| 34 | + } catch (IOException e) { |
| 35 | + throw new RuntimeException(e); |
| 36 | + } |
| 37 | + |
| 38 | + MeteorBot.LOG.info("Providing metrics on :9400/metrics"); |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public void onShutdown(ShutdownEvent event) { |
| 43 | + server.stop(1000); |
| 44 | + } |
| 45 | + |
| 46 | + private void onRequest(HttpExchange exchange) { |
| 47 | + byte[] response = String.format(""" |
| 48 | + # HELP meteor_discord_users_total Total number of Discord users in our server |
| 49 | + # TYPE meteor_discord_users_total gauge |
| 50 | + meteor_discord_users_total %d |
| 51 | + """, guild.getMemberCount()).getBytes(StandardCharsets.UTF_8); |
| 52 | + |
| 53 | + try { |
| 54 | + exchange.getResponseHeaders().set("Content-Type", "text/plain"); |
| 55 | + exchange.sendResponseHeaders(200, response.length); |
| 56 | + } catch (IOException e) { |
| 57 | + throw new RuntimeException(e); |
| 58 | + } |
| 59 | + |
| 60 | + OutputStream out = exchange.getResponseBody(); |
| 61 | + copy(response, out); |
| 62 | + } |
| 63 | + |
| 64 | + @SuppressWarnings("ThrowFromFinallyBlock") |
| 65 | + private static void copy(byte[] in, OutputStream out) { |
| 66 | + try { |
| 67 | + out.write(in); |
| 68 | + } catch (IOException e) { |
| 69 | + throw new RuntimeException(e); |
| 70 | + } finally { |
| 71 | + try { |
| 72 | + out.close(); |
| 73 | + } catch (IOException e) { |
| 74 | + throw new RuntimeException(e); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments