Metrics.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. package com.gmail.nossr50;
  2. import org.bukkit.configuration.file.YamlConfiguration;
  3. import org.bukkit.plugin.Plugin;
  4. import org.bukkit.plugin.PluginDescriptionFile;
  5. import java.io.BufferedReader;
  6. import java.io.File;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. import java.io.OutputStreamWriter;
  10. import java.io.UnsupportedEncodingException;
  11. import java.net.Proxy;
  12. import java.net.URL;
  13. import java.net.URLConnection;
  14. import java.net.URLEncoder;
  15. import java.util.Collections;
  16. import java.util.HashMap;
  17. import java.util.HashSet;
  18. import java.util.Iterator;
  19. import java.util.LinkedHashSet;
  20. import java.util.Map;
  21. import java.util.Set;
  22. import java.util.UUID;
  23. public class Metrics {
  24. /**
  25. * The current revision number
  26. */
  27. private final static int REVISION = 5;
  28. /**
  29. * The base url of the metrics domain
  30. */
  31. private static final String BASE_URL = "http://metrics.griefcraft.com";
  32. /**
  33. * The url used to report a server's status
  34. */
  35. private static final String REPORT_URL = "/report/%s";
  36. /**
  37. * The file where guid and opt out is stored in
  38. */
  39. private static final String CONFIG_FILE = "plugins" + File.separator + "PluginMetrics" + File.separator + "config.yml";
  40. /**
  41. * The separator to use for custom data. This MUST NOT change unless you are hosting your own
  42. * version of metrics and want to change it.
  43. */
  44. private static final String CUSTOM_DATA_SEPARATOR = "~~";
  45. /**
  46. * Interval of time to ping (in minutes)
  47. */
  48. private final static int PING_INTERVAL = 10;
  49. /**
  50. * A map of all of the graphs for each plugin
  51. */
  52. private Map<Plugin, Set<Graph>> graphs = Collections.synchronizedMap(new HashMap<Plugin, Set<Graph>>());
  53. /**
  54. * A convenient map of the default Graph objects (used by addCustomData mainly)
  55. */
  56. private Map<Plugin, Graph> defaultGraphs = Collections.synchronizedMap(new HashMap<Plugin, Graph>());
  57. /**
  58. * The plugin configuration file
  59. */
  60. private final YamlConfiguration configuration;
  61. /**
  62. * Unique server id
  63. */
  64. private String guid;
  65. public Metrics() throws IOException {
  66. // load the config
  67. File file = new File(CONFIG_FILE);
  68. configuration = YamlConfiguration.loadConfiguration(file);
  69. // add some defaults
  70. configuration.addDefault("opt-out", false);
  71. configuration.addDefault("guid", UUID.randomUUID().toString());
  72. // Do we need to create the file?
  73. if (configuration.get("guid", null) == null) {
  74. configuration.options().header("http://metrics.griefcraft.com").copyDefaults(true);
  75. configuration.save(file);
  76. }
  77. // Load the guid then
  78. guid = configuration.getString("guid");
  79. }
  80. /**
  81. * Construct and create a Graph that can be used to separate specific plotters to their own graphs
  82. * on the metrics website. Plotters can be added to the graph object returned.
  83. *
  84. * @param plugin
  85. * @param type
  86. * @param name
  87. * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
  88. */
  89. public Graph createGraph(Plugin plugin, Graph.Type type, String name) {
  90. if (plugin == null || type == null || name == null) {
  91. throw new IllegalArgumentException("All arguments must not be null");
  92. }
  93. // Construct the graph object
  94. Graph graph = new Graph(type, name);
  95. // Get the graphs for the plugin
  96. Set<Graph> graphs = getOrCreateGraphs(plugin);
  97. // Now we can add our graph
  98. graphs.add(graph);
  99. // and return back
  100. return graph;
  101. }
  102. /**
  103. * Adds a custom data plotter for a given plugin
  104. *
  105. * @param plugin
  106. * @param plotter
  107. */
  108. public void addCustomData(Plugin plugin, Plotter plotter) {
  109. // The default graph for the plugin
  110. Graph graph = getOrCreateDefaultGraph(plugin);
  111. // Add the plotter to the graph o/
  112. graph.addPlotter(plotter);
  113. // Ensure the default graph is included in the submitted graphs
  114. getOrCreateGraphs(plugin).add(graph);
  115. }
  116. /**
  117. * Begin measuring a plugin
  118. *
  119. * @param plugin
  120. */
  121. public void beginMeasuringPlugin(final Plugin plugin) {
  122. // Did we opt out?
  123. if (configuration.getBoolean("opt-out", false)) {
  124. return;
  125. }
  126. // Begin hitting the server with glorious data
  127. plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() {
  128. private boolean firstPost = true;
  129. public void run() {
  130. try {
  131. // We use the inverse of firstPost because if it is the first time we are posting,
  132. // it is not a interval ping, so it evaluates to FALSE
  133. // Each time thereafter it will evaluate to TRUE, i.e PING!
  134. postPlugin(plugin, !firstPost);
  135. // After the first post we set firstPost to false
  136. // Each post thereafter will be a ping
  137. firstPost = false;
  138. } catch (IOException e) {
  139. System.out.println("[Metrics] " + e.getMessage());
  140. }
  141. }
  142. }, 0, PING_INTERVAL * 1200);
  143. }
  144. /**
  145. * Generic method that posts a plugin to the metrics website
  146. *
  147. * @param plugin
  148. */
  149. private void postPlugin(Plugin plugin, boolean isPing) throws IOException {
  150. // The plugin's description file containg all of the plugin data such as name, version, author, etc
  151. PluginDescriptionFile description = plugin.getDescription();
  152. // The author string, created with description.getAuthors()
  153. // Authors are separated by a comma
  154. String authors = "";
  155. // Add each author to the string
  156. for (String author : description.getAuthors()) {
  157. authors += author + ", ";
  158. }
  159. // If there were any authors at all, we need to remove the last 2 characters
  160. // the last 2 characters are the last comma and space
  161. if (!authors.isEmpty()) {
  162. authors = authors.substring(0, authors.length() - 2);
  163. }
  164. // Construct the post data
  165. String data = encode("guid") + '=' + encode(guid)
  166. + encodeDataPair("authors", authors)
  167. + encodeDataPair("version", description.getVersion())
  168. + encodeDataPair("server", plugin.getServer().getVersion())
  169. + encodeDataPair("players", Integer.toString(plugin.getServer().getOnlinePlayers().length))
  170. + encodeDataPair("revision", String.valueOf(REVISION));
  171. // If we're pinging, append it
  172. if (isPing) {
  173. data += encodeDataPair("ping", "true");
  174. }
  175. // Add any custom data available for the plugin
  176. Set<Graph> graphs = getOrCreateGraphs(plugin);
  177. // Acquire a lock on the graphs, which lets us make the assumption we also lock everything
  178. // inside of the graph (e.g plotters)
  179. synchronized(graphs) {
  180. Iterator<Graph> iter = graphs.iterator();
  181. while (iter.hasNext()) {
  182. Graph graph = iter.next();
  183. // Because we have a lock on the graphs set already, it is reasonable to assume
  184. // that our lock transcends down to the individual plotters in the graphs also.
  185. // Because our methods are private, no one but us can reasonably access this list
  186. // without reflection so this is a safe assumption without adding more code.
  187. for (Plotter plotter : graph.getPlotters()) {
  188. // The key name to send to the metrics server
  189. // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top
  190. // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME
  191. String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName());
  192. // The value to send, which for the foreseeable future is just the string
  193. // value of plotter.getValue()
  194. String value = Integer.toString(plotter.getValue());
  195. // Add it to the http post data :)
  196. data += encodeDataPair(key, value);
  197. }
  198. }
  199. }
  200. // Create the url
  201. URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName()));
  202. // Connect to the website
  203. URLConnection connection;
  204. // Mineshafter creates a socks proxy, so we can safely bypass it
  205. // It does not reroute POST requests so we need to go around it
  206. if (isMineshafterPresent()) {
  207. connection = url.openConnection(Proxy.NO_PROXY);
  208. } else {
  209. connection = url.openConnection();
  210. }
  211. connection.setDoOutput(true);
  212. // Write the data
  213. OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
  214. writer.write(data);
  215. writer.flush();
  216. // Now read the response
  217. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  218. String response = reader.readLine();
  219. // close resources
  220. writer.close();
  221. reader.close();
  222. if (response.startsWith("ERR")) {
  223. throw new IOException(response); //Throw the exception
  224. } else {
  225. // Is this the first update this hour?
  226. if (response.contains("OK This is your first update this hour")) {
  227. synchronized (graphs) {
  228. Iterator<Graph> iter = graphs.iterator();
  229. while (iter.hasNext()) {
  230. Graph graph = iter.next();
  231. for (Plotter plotter : graph.getPlotters()) {
  232. plotter.reset();
  233. }
  234. }
  235. }
  236. }
  237. }
  238. //if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right
  239. }
  240. /**
  241. * Get or create the Set of graphs for a specific plugin
  242. *
  243. * @param plugin
  244. * @return
  245. */
  246. private Set<Graph> getOrCreateGraphs(Plugin plugin) {
  247. Set<Graph> theGraphs = graphs.get(plugin);
  248. // Create the Set if it does not already exist
  249. if (theGraphs == null) {
  250. theGraphs = Collections.synchronizedSet(new HashSet<Graph>());
  251. graphs.put(plugin, theGraphs);
  252. }
  253. return theGraphs;
  254. }
  255. /**
  256. * Get the default graph for a plugin and if it does not exist, create one
  257. *
  258. * @param plugin
  259. * @return
  260. */
  261. private Graph getOrCreateDefaultGraph(Plugin plugin) {
  262. Graph graph = defaultGraphs.get(plugin);
  263. // Not yet created :(
  264. if (graph == null) {
  265. graph = new Graph(Graph.Type.Line, "Default");
  266. defaultGraphs.put(plugin, graph);
  267. }
  268. return graph;
  269. }
  270. /**
  271. * Check if mineshafter is present. If it is, we need to bypass it to send POST requests
  272. *
  273. * @return
  274. */
  275. private boolean isMineshafterPresent() {
  276. try {
  277. Class.forName("mineshafter.MineServer");
  278. return true;
  279. } catch (Exception e) {
  280. return false;
  281. }
  282. }
  283. /**
  284. * Encode a key/value data pair to be used in a HTTP post request. This INCLUDES a & so the first
  285. * key/value pair MUST be included manually, e.g:
  286. * <p>
  287. * String httpData = encode("guid") + "=" + encode("1234") + encodeDataPair("authors") + "..";
  288. * </p>
  289. *
  290. * @param key
  291. * @param value
  292. * @return
  293. */
  294. private static String encodeDataPair(String key, String value) throws UnsupportedEncodingException {
  295. return "&" + encode(key) + "=" + encode(value);
  296. }
  297. /**
  298. * Encode text as UTF-8
  299. *
  300. * @param text
  301. * @return
  302. */
  303. private static String encode(String text) throws UnsupportedEncodingException {
  304. return URLEncoder.encode(text, "UTF-8");
  305. }
  306. /**
  307. * Represents a custom graph on the website
  308. */
  309. public static class Graph {
  310. /**
  311. * The graph's type that will be visible on the website
  312. */
  313. public static enum Type {
  314. /**
  315. * A simple line graph which also includes a scrollable timeline viewer to view
  316. * as little or as much of the data as possible.
  317. */
  318. Line,
  319. /**
  320. * An area graph. This is the same as a line graph except the area under the curve is shaded
  321. */
  322. Area,
  323. /**
  324. * A column graph, which is a graph where the data is represented by columns on the vertical axis,
  325. * i.e they go up and down.
  326. */
  327. Column,
  328. /**
  329. * A pie graph. The graph is generated by taking the data for the last hour and summing it
  330. * together. Then the percentage for each plotter is calculated via round( (plot / total) * 100, 2 )
  331. */
  332. Pie
  333. }
  334. /**
  335. * What the graph should be plotted as
  336. */
  337. private final Type type;
  338. /**
  339. * The graph's name, alphanumeric and spaces only :)
  340. * If it does not comply to the above when submitted, it is rejected
  341. */
  342. private final String name;
  343. /**
  344. * The set of plotters that are contained within this graph
  345. */
  346. private final Set<Plotter> plotters = new LinkedHashSet<Plotter>();
  347. private Graph(Type type, String name) {
  348. this.type = type;
  349. this.name = name;
  350. }
  351. /**
  352. * Gets the graph's name
  353. *
  354. * @return
  355. */
  356. public String getName() {
  357. return name;
  358. }
  359. /**
  360. * Add a plotter to the graph, which will be used to plot entries
  361. *
  362. * @param plotter
  363. */
  364. public void addPlotter(Plotter plotter) {
  365. plotters.add(plotter);
  366. }
  367. /**
  368. * Remove a plotter from the graph
  369. *
  370. * @param plotter
  371. */
  372. public void removePlotter(Plotter plotter) {
  373. plotters.remove(plotter);
  374. }
  375. /**
  376. * Gets an <b>unmodifiable</b> set of the plotter objects in the graph
  377. * @return
  378. */
  379. public Set<Plotter> getPlotters() {
  380. return Collections.unmodifiableSet(plotters);
  381. }
  382. @Override
  383. public int hashCode() {
  384. return (type.hashCode() * 17) ^ name.hashCode();
  385. }
  386. @Override
  387. public boolean equals(Object object) {
  388. if (!(object instanceof Graph)) {
  389. return false;
  390. }
  391. Graph graph = (Graph) object;
  392. return graph.type == type && graph.name.equals(name);
  393. }
  394. }
  395. /**
  396. * Interface used to collect custom data for a plugin
  397. */
  398. public static abstract class Plotter {
  399. /**
  400. * The plot's name
  401. */
  402. private final String name;
  403. /**
  404. * Construct a plotter with the default plot name
  405. */
  406. public Plotter() {
  407. this("Default");
  408. }
  409. /**
  410. * Construct a plotter with a specific plot name
  411. *
  412. * @param name
  413. */
  414. public Plotter(String name) {
  415. this.name = name;
  416. }
  417. /**
  418. * Get the current value for the plotted point
  419. *
  420. * @return
  421. */
  422. public abstract int getValue();
  423. /**
  424. * Get the column name for the plotted point
  425. *
  426. * @return the plotted point's column name
  427. */
  428. public String getColumnName() {
  429. return name;
  430. }
  431. /**
  432. * Called after the website graphs have been updated
  433. */
  434. public void reset() {
  435. }
  436. @Override
  437. public int hashCode() {
  438. return getColumnName().hashCode() + getValue();
  439. }
  440. @Override
  441. public boolean equals(Object object) {
  442. if (!(object instanceof Plotter)) {
  443. return false;
  444. }
  445. Plotter plotter = (Plotter) object;
  446. return plotter.name.equals(name) && plotter.getValue() == getValue();
  447. }
  448. }
  449. }