Merge pull request #336 from prometheus/fix/ui-cleanups

JSON-based tabular view and minor UI cleanups
This commit is contained in:
juliusv 2013-07-24 03:30:12 -07:00
commit f52baf02ab
5 changed files with 88 additions and 62 deletions

View file

@ -24,7 +24,7 @@ import (
type MetricsService struct { type MetricsService struct {
gorest.RestService `root:"/api/" consumes:"application/json" produces:"application/json"` gorest.RestService `root:"/api/" consumes:"application/json" produces:"application/json"`
query gorest.EndPoint `method:"GET" path:"/query?{expr:string}&{json:string}" output:"string"` query gorest.EndPoint `method:"GET" path:"/query?{expr:string}&{as_text:string}" output:"string"`
queryRange gorest.EndPoint `method:"GET" path:"/query_range?{expr:string}&{end:int64}&{range:int64}&{step:int64}" output:"string"` queryRange gorest.EndPoint `method:"GET" path:"/query_range?{expr:string}&{end:int64}&{range:int64}&{step:int64}" output:"string"`
metrics gorest.EndPoint `method:"GET" path:"/metrics" output:"string"` metrics gorest.EndPoint `method:"GET" path:"/metrics" output:"string"`

View file

@ -37,7 +37,7 @@ func (serv MetricsService) setAccessControlHeaders(rb *gorest.ResponseBuilder) {
rb.AddHeader("Access-Control-Expose-Headers", "Date") rb.AddHeader("Access-Control-Expose-Headers", "Date")
} }
func (serv MetricsService) Query(expr string, formatJson string) string { func (serv MetricsService) Query(expr string, asText string) string {
exprNode, err := rules.LoadExprFromString(expr) exprNode, err := rules.LoadExprFromString(expr)
if err != nil { if err != nil {
return ast.ErrorToJSON(err) return ast.ErrorToJSON(err)
@ -48,7 +48,8 @@ func (serv MetricsService) Query(expr string, formatJson string) string {
rb := serv.ResponseBuilder() rb := serv.ResponseBuilder()
serv.setAccessControlHeaders(rb) serv.setAccessControlHeaders(rb)
var format ast.OutputFormat var format ast.OutputFormat
if formatJson != "" { // BUG(julius): Use Content-Type negotiation.
if asText == "" {
format = ast.JSON format = ast.JSON
rb.SetContentType(gorest.Application_Json) rb.SetContentType(gorest.Application_Json)
} else { } else {

View file

@ -107,9 +107,8 @@ input[title=*]:hover:after {
display: inline; display: inline;
} }
.console { .console_table {
white-space: pre; margin-top: 5px;
overflow: scroll;
} }
.ui-widget { .ui-widget {

View file

@ -55,10 +55,10 @@ Prometheus.Graph.prototype.initialize = function() {
self.id = Prometheus.Graph.numGraphs++; self.id = Prometheus.Graph.numGraphs++;
// Set default options. // Set default options.
self.options['id'] = self.id; self.options["id"] = self.id;
self.options['range_input'] = self.options['range_input'] || "1h"; self.options["range_input"] = self.options["range_input"] || "1h";
self.options['stacked_checked'] = self.options['stacked'] ? "checked" : ""; self.options["stacked_checked"] = self.options["stacked"] ? "checked" : "";
self.options['tab'] = self.options['tab'] || 0; self.options["tab"] = self.options["tab"] || 0;
// Draw graph controls and container from Handlebars template. // Draw graph controls and container from Handlebars template.
@ -77,22 +77,22 @@ Prometheus.Graph.prototype.initialize = function() {
self.consoleTab = graphWrapper.find(".console"); self.consoleTab = graphWrapper.find(".console");
self.graphTab = graphWrapper.find(".graph_container"); self.graphTab = graphWrapper.find(".graph_container");
self.tabs = graphWrapper.find(".tabs");; self.tabs = graphWrapper.find(".tabs");
self.tab = $(self.tabs.find("> div")[self.options['tab']]); // active tab self.tab = $(self.tabs.find("> div")[self.options["tab"]]); // active tab
self.tabs.tabs({ self.tabs.tabs({
active: self.options['tab'], active: self.options["tab"],
activate: function(e, ui) { activate: function(e, ui) {
storeGraphOptionsInUrl(); storeGraphOptionsInUrl();
self.tab = ui.newPanel self.tab = ui.newPanel
if (self.tab.hasClass('reload')) { // reload if flagged with class 'reload' if (self.tab.hasClass("reload")) { // reload if flagged with class "reload"
self.submitQuery(); self.submitQuery();
} }
} }
}); });
// Return moves focus back to expr instead of submitting. // Return moves focus back to expr instead of submitting.
self.insertMetric.bind('keydown', 'return', function(e) { self.insertMetric.bind("keydown", "return", function(e) {
self.expr.focus(); self.expr.focus();
self.expr.val(self.expr.val()); self.expr.val(self.expr.val());
@ -113,12 +113,12 @@ Prometheus.Graph.prototype.initialize = function() {
self.endDate.val(""); self.endDate.val("");
} }
self.endDate.change(function() { self.submitQuery() }); self.endDate.change(function() { self.submitQuery() });
self.refreshInterval.change(function() { self.updateRefresh() }) self.refreshInterval.change(function() { self.updateRefresh() });
self.stacked.change(function() { self.updateGraph(); }); self.stacked.change(function() { self.updateGraph(); });
self.queryForm.submit(function() { self.queryForm.submit(function() {
self.consoleTab.addClass('reload'); self.consoleTab.addClass("reload");
self.graphTab.addClass('reload'); self.graphTab.addClass("reload");
self.submitQuery(); self.submitQuery();
return false; return false;
}); });
@ -131,10 +131,10 @@ Prometheus.Graph.prototype.initialize = function() {
self.queryForm.find("button[name=dec_end]").click(function() { self.decreaseEnd(); }); self.queryForm.find("button[name=dec_end]").click(function() { self.decreaseEnd(); });
self.insertMetric.change(function() { self.insertMetric.change(function() {
self.expr.selection('replace', {text: self.insertMetric.val(), mode: 'before'}) self.expr.selection("replace", {text: self.insertMetric.val(), mode: "before"});
self.insertMetric.focus(); // refocusing self.insertMetric.focus(); // refocusing
}); });
self.insertMetric.click(function() { self.expr.focus() }) self.insertMetric.click(function() { self.expr.focus() });
self.expr.focus(); // TODO: move to external Graph method. self.expr.focus(); // TODO: move to external Graph method.
@ -152,12 +152,12 @@ Prometheus.Graph.prototype.populateInsertableMetrics = function() {
url: "/api/metrics", url: "/api/metrics",
dataType: "json", dataType: "json",
success: function(json, textStatus) { success: function(json, textStatus) {
var availableMetrics = [] var availableMetrics = [];
for (var i = 0; i < json.length; i++) { for (var i = 0; i < json.length; i++) {
self.insertMetric[0].options.add(new Option(json[i], json[i])); self.insertMetric[0].options.add(new Option(json[i], json[i]));
availableMetrics.push(json[i]) availableMetrics.push(json[i]);
} }
self.expr.autocomplete({source: availableMetrics}) self.expr.autocomplete({source: availableMetrics});
}, },
error: function() { error: function() {
alert("Error loading available metrics!"); alert("Error loading available metrics!");
@ -191,7 +191,7 @@ Prometheus.Graph.prototype.getOptions = function() {
} }
} }
}); });
options['tab'] = self.tabs.tabs("option", "active"); options["tab"] = self.tabs.tabs("option", "active");
return options; return options;
}; };
@ -256,8 +256,8 @@ Prometheus.Graph.prototype.getOrSetEndDate = function() {
Prometheus.Graph.prototype.setEndDate = function(date) { Prometheus.Graph.prototype.setEndDate = function(date) {
var self = this; var self = this;
dateString = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate() + ' ' + dateString = date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " " +
date.getHours() + ':' + date.getMinutes(); date.getHours() + ":" + date.getMinutes();
self.endDate.val(""); self.endDate.val("");
self.endDate.appendDtpicker({"current": dateString}); self.endDate.appendDtpicker({"current": dateString});
}; };
@ -277,7 +277,7 @@ Prometheus.Graph.prototype.decreaseEnd = function() {
Prometheus.Graph.prototype.submitQuery = function() { Prometheus.Graph.prototype.submitQuery = function() {
var self = this; var self = this;
if (!self.expr.val()) { if (!self.expr.val()) {
return return;
} }
self.spinner.show(); self.spinner.show();
@ -293,26 +293,22 @@ Prometheus.Graph.prototype.submitQuery = function() {
self.queryForm.find("input[name=end]").val(endDate); self.queryForm.find("input[name=end]").val(endDate);
if (self.queryXhr) { if (self.queryXhr) {
self.queryXhr.abort() self.queryXhr.abort();
} }
var url var url;
var data var success;
if (self.tab[0] == self.graphTab[0]) { if (self.tab[0] == self.graphTab[0]) {
url = self.queryForm.attr("action") url = self.queryForm.attr("action");
data = self.queryForm.serialize() success = function(json, textStatus) { self.handleGraphResponse(json, textStatus); };
dataType = "json"
success = function(json, textStatus) { self.handleGraphResponse(json, textStatus) }
} else { } else {
url = '/api/query' url = "/api/query";
data = self.expr.serialize() success = function(text, textStatus) { self.handleConsoleResponse(text, textStatus); };
dataType = "text"
success = function(text, textStatus) { self.handleConsoleResponse(text, textStatus) }
} }
self.queryXhr = $.ajax({ self.queryXhr = $.ajax({
method: self.queryForm.attr("method"), method: self.queryForm.attr("method"),
url: url, url: url,
dataType: dataType, dataType: "json",
data: self.queryForm.serialize(), data: self.queryForm.serialize(),
success: success, success: success,
error: function(xhr, resp) { error: function(xhr, resp) {
@ -330,16 +326,16 @@ Prometheus.Graph.prototype.updateRefresh = function() {
var self = this; var self = this;
if (self.timeoutID) { if (self.timeoutID) {
window.clearTimeout(self.timeoutID) window.clearTimeout(self.timeoutID);
} }
interval = self.parseDuration(self.refreshInterval.val()); interval = self.parseDuration(self.refreshInterval.val());
if (!interval) { return }; if (!interval) { return };
self.timeoutID = window.setTimeout(function() { self.timeoutID = window.setTimeout(function() {
self.submitQuery() self.submitQuery();
self.updateRefresh() self.updateRefresh();
}, interval * SECOND) }, interval * SECOND);
} }
Prometheus.Graph.prototype.renderLabels = function(labels) { Prometheus.Graph.prototype.renderLabels = function(labels) {
@ -349,7 +345,7 @@ Prometheus.Graph.prototype.renderLabels = function(labels) {
labelStrings.push("<strong>" + label + "</strong>: " + labels[label]); labelStrings.push("<strong>" + label + "</strong>: " + labels[label]);
} }
} }
return labels = "<div class='labels'>" + labelStrings.join("<br>") + "</div>"; return labels = "<div class=\"labels\">" + labelStrings.join("<br>") + "</div>";
} }
Prometheus.Graph.prototype.metricToTsName = function(labels) { Prometheus.Graph.prototype.metricToTsName = function(labels) {
@ -357,7 +353,7 @@ Prometheus.Graph.prototype.metricToTsName = function(labels) {
var labelStrings = []; var labelStrings = [];
for (label in labels) { for (label in labels) {
if (label != "name") { if (label != "name") {
labelStrings.push(label + "='" + labels[label] + "'"); labelStrings.push(label + "=\"" + labels[label] + "\"");
} }
} }
tsName += labelStrings.join(",") + "}"; tsName += labelStrings.join(",") + "}";
@ -486,10 +482,12 @@ Prometheus.Graph.prototype.updateGraph = function(reloadGraph) {
Prometheus.Graph.prototype.resizeGraph = function() { Prometheus.Graph.prototype.resizeGraph = function() {
var self = this; var self = this;
self.rickshawGraph.configure({ if (self.rickshawGraph != null) {
width: Math.max(self.graph.innerWidth() - 80, 200), self.rickshawGraph.configure({
}); width: Math.max(self.graph.innerWidth() - 80, 200),
self.rickshawGraph.render(); });
self.rickshawGraph.render();
}
} }
Prometheus.Graph.prototype.handleGraphResponse = function(json, textStatus) { Prometheus.Graph.prototype.handleGraphResponse = function(json, textStatus) {
@ -503,24 +501,43 @@ Prometheus.Graph.prototype.handleGraphResponse = function(json, textStatus) {
alert("No datapoints found."); alert("No datapoints found.");
return; return;
} }
self.graphTab.removeClass('reload'); self.graphTab.removeClass("reload");
self.updateGraph(true); self.updateGraph(true);
} }
Prometheus.Graph.prototype.handleConsoleResponse = function(text, textStatus) { Prometheus.Graph.prototype.handleConsoleResponse = function(data, textStatus) {
var self = this; var self = this;
var body = "<table class=\"table-striped console_table\"></table>"; self.consoleTab.removeClass("reload");
self.consoleTab.removeClass('reload');
self.consoleTab.html(body);
var elements = text.split("\n"); var tBody = self.consoleTab.find(".console_table tbody");
var table = $("#console_table"); tBody.empty();
table.find("tr:gt(0)").remove();
for (var i = 0; i < elements.length; i++) { switch(data.Type) {
var e = "<tr><td>" + elements[i] + "</td></tr>"; case "vector":
table.append(e); for (var i = 0; i < data.Value.length; i++) {
var v = data.Value[i];
var tsName = self.metricToTsName(v.Metric);
tBody.append("<tr><td>" + tsName + "</td><td>" + v.Value + "</td></tr>")
}
break;
case "matrix":
for (var i = 0; i < data.Value.length; i++) {
var v = data.Value[i];
var tsName = self.metricToTsName(v.Metric);
var valueText = "";
for (var j = 0; j < v.Values.length; j++) {
valueText += v.Values[j].Value + " @" + v.Values[j].Timestamp + "<br/>";
}
tBody.append("<tr><td>" + tsName + "</td><td>" + valueText + "</td></tr>")
}
break;
case "scalar":
tBody.append("<tr><td>scalar</td><td>" + data.Value + "</td></tr>");
break;
default:
alert("Unsupported value type!");
break;
} }
console.log(table);
} }
function parseGraphOptionsFromUrl() { function parseGraphOptionsFromUrl() {

View file

@ -104,7 +104,16 @@
</div> </div>
<div class="legend"></div> <div class="legend"></div>
</div> </div>
<div id="console{{id}}" class="console reload"></div> <div id="console{{id}}" class="console reload">
<table class="table table-condensed table-bordered table-hover console_table">
<thead>
<th>Element</th>
<th>Value</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div> </div>
</form> </form>
</div> </div>