created docker-prometheus compose file and edited the Prometheus yml file
This commit is contained in:
18
prom/web/blob/static/js/alerts.js
Normal file
18
prom/web/blob/static/js/alerts.js
Normal file
@ -0,0 +1,18 @@
|
||||
function init() {
|
||||
$(".alert_header").click(function() {
|
||||
var expanderIcon = $(this).find("i.icon-chevron-down");
|
||||
if (expanderIcon.length != 0) {
|
||||
expanderIcon.removeClass("icon-chevron-down").addClass("icon-chevron-up");
|
||||
} else {
|
||||
var collapserIcon = $(this).find("i.icon-chevron-up");
|
||||
collapserIcon.removeClass("icon-chevron-up").addClass("icon-chevron-down");
|
||||
}
|
||||
$(this).next().toggle();
|
||||
});
|
||||
|
||||
$(".silence_alert_link, .silence_children_link").click(function() {
|
||||
alert("Silencing is not yet supported.");
|
||||
});
|
||||
}
|
||||
|
||||
$(init);
|
679
prom/web/blob/static/js/graph.js
Normal file
679
prom/web/blob/static/js/graph.js
Normal file
@ -0,0 +1,679 @@
|
||||
var Prometheus = Prometheus || {};
|
||||
var graphs = [];
|
||||
var graphTemplate;
|
||||
|
||||
var SECOND = 1000;
|
||||
|
||||
Handlebars.registerHelper('pathPrefix', function() { return PATH_PREFIX; });
|
||||
|
||||
Prometheus.Graph = function(element, options) {
|
||||
this.el = element;
|
||||
this.options = options;
|
||||
this.changeHandler = null;
|
||||
this.rickshawGraph = null;
|
||||
this.data = [];
|
||||
|
||||
this.initialize();
|
||||
};
|
||||
|
||||
Prometheus.Graph.timeFactors = {
|
||||
"y": 60 * 60 * 24 * 365,
|
||||
"w": 60 * 60 * 24 * 7,
|
||||
"d": 60 * 60 * 24,
|
||||
"h": 60 * 60,
|
||||
"m": 60,
|
||||
"s": 1
|
||||
};
|
||||
|
||||
Prometheus.Graph.stepValues = [
|
||||
"1s", "10s", "1m", "5m", "15m", "30m", "1h", "2h", "6h", "12h", "1d", "2d",
|
||||
"1w", "2w", "4w", "8w", "1y", "2y"
|
||||
];
|
||||
|
||||
Prometheus.Graph.numGraphs = 0;
|
||||
|
||||
Prometheus.Graph.prototype.initialize = function() {
|
||||
var self = this;
|
||||
self.id = Prometheus.Graph.numGraphs++;
|
||||
|
||||
// Set default options.
|
||||
self.options["id"] = self.id;
|
||||
self.options["range_input"] = self.options["range_input"] || "1h";
|
||||
if (self.options["tab"] === undefined) {
|
||||
self.options["tab"] = 1;
|
||||
}
|
||||
|
||||
// Draw graph controls and container from Handlebars template.
|
||||
|
||||
var graphHtml = graphTemplate(self.options);
|
||||
self.el.append(graphHtml);
|
||||
|
||||
// Get references to all the interesting elements in the graph container and
|
||||
// bind event handlers.
|
||||
var graphWrapper = self.el.find("#graph_wrapper" + self.id);
|
||||
self.queryForm = graphWrapper.find(".query_form");
|
||||
|
||||
self.expr = graphWrapper.find("textarea[name=expr]");
|
||||
self.expr.keypress(function(e) {
|
||||
// Enter was pressed without the shift key.
|
||||
if (e.which == 13 && !e.shiftKey) {
|
||||
self.queryForm.submit();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
// Auto-resize the text area on input.
|
||||
var offset = this.offsetHeight - this.clientHeight;
|
||||
var resizeTextarea = function(el) {
|
||||
$(el).css('height', 'auto').css('height', el.scrollHeight + offset);
|
||||
};
|
||||
$(this).on('keyup input', function() { resizeTextarea(this); });
|
||||
});
|
||||
self.expr.change(storeGraphOptionsInURL);
|
||||
|
||||
self.rangeInput = self.queryForm.find("input[name=range_input]");
|
||||
self.stackedBtn = self.queryForm.find(".stacked_btn");
|
||||
self.stacked = self.queryForm.find("input[name=stacked]");
|
||||
self.insertMetric = self.queryForm.find("select[name=insert_metric]");
|
||||
self.refreshInterval = self.queryForm.find("select[name=refresh]");
|
||||
|
||||
self.consoleTab = graphWrapper.find(".console");
|
||||
self.graphTab = graphWrapper.find(".graph_container");
|
||||
|
||||
self.tabs = graphWrapper.find("a[data-toggle='tab']");
|
||||
self.tabs.eq(self.options["tab"]).tab("show");
|
||||
self.tabs.on("shown.bs.tab", function(e) {
|
||||
var target = $(e.target);
|
||||
self.options["tab"] = target.parent().index();
|
||||
storeGraphOptionsInURL();
|
||||
if ($("#" + target.attr("aria-controls")).hasClass("reload")) {
|
||||
self.submitQuery();
|
||||
}
|
||||
});
|
||||
|
||||
// Return moves focus back to expr instead of submitting.
|
||||
self.insertMetric.bind("keydown", "return", function(e) {
|
||||
self.expr.focus();
|
||||
self.expr.val(self.expr.val());
|
||||
|
||||
return e.preventDefault();
|
||||
})
|
||||
|
||||
self.error = graphWrapper.find(".error").hide();
|
||||
self.graphArea = graphWrapper.find(".graph_area");
|
||||
self.graph = self.graphArea.find(".graph");
|
||||
self.yAxis = self.graphArea.find(".y_axis");
|
||||
self.legend = graphWrapper.find(".legend");
|
||||
self.spinner = graphWrapper.find(".spinner");
|
||||
self.evalStats = graphWrapper.find(".eval_stats");
|
||||
|
||||
self.endDate = graphWrapper.find("input[name=end_input]");
|
||||
self.endDate.datetimepicker({
|
||||
language: 'en',
|
||||
pickSeconds: false,
|
||||
});
|
||||
if (self.options["end_input"]) {
|
||||
self.endDate.data('datetimepicker').setValue(self.options["end_input"]);
|
||||
}
|
||||
self.endDate.change(function() { self.submitQuery() });
|
||||
self.refreshInterval.change(function() { self.updateRefresh() });
|
||||
|
||||
self.isStacked = function() {
|
||||
return self.stacked.val() === '1';
|
||||
};
|
||||
|
||||
var styleStackBtn = function() {
|
||||
var icon = self.stackedBtn.find('.glyphicon');
|
||||
if (self.isStacked()) {
|
||||
self.stackedBtn.addClass("btn-primary");
|
||||
icon.addClass("glyphicon-check");
|
||||
icon.removeClass("glyphicon-unchecked");
|
||||
} else {
|
||||
self.stackedBtn.removeClass("btn-primary");
|
||||
icon.addClass("glyphicon-unchecked");
|
||||
icon.removeClass("glyphicon-check");
|
||||
}
|
||||
};
|
||||
styleStackBtn();
|
||||
|
||||
self.stackedBtn.click(function() {
|
||||
if (self.isStacked() && self.graphJSON) {
|
||||
// If the graph was stacked, the original series data got mutated
|
||||
// (scaled) and we need to reconstruct it from the original JSON data.
|
||||
self.data = self.transformData(self.graphJSON);
|
||||
}
|
||||
self.stacked.val(self.isStacked() ? '0' : '1');
|
||||
styleStackBtn();
|
||||
self.updateGraph();
|
||||
});
|
||||
|
||||
self.queryForm.submit(function() {
|
||||
self.consoleTab.addClass("reload");
|
||||
self.graphTab.addClass("reload");
|
||||
self.submitQuery();
|
||||
return false;
|
||||
});
|
||||
self.spinner.hide();
|
||||
|
||||
self.queryForm.find("button[name=inc_range]").click(function() { self.increaseRange(); });
|
||||
self.queryForm.find("button[name=dec_range]").click(function() { self.decreaseRange(); });
|
||||
|
||||
self.queryForm.find("button[name=inc_end]").click(function() { self.increaseEnd(); });
|
||||
self.queryForm.find("button[name=dec_end]").click(function() { self.decreaseEnd(); });
|
||||
|
||||
self.insertMetric.change(function() {
|
||||
self.expr.selection("replace", {text: self.insertMetric.val(), mode: "before"});
|
||||
self.expr.focus(); // refocusing
|
||||
});
|
||||
|
||||
self.populateInsertableMetrics();
|
||||
|
||||
if (self.expr.val()) {
|
||||
self.submitQuery();
|
||||
}
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.populateInsertableMetrics = function() {
|
||||
var self = this;
|
||||
$.ajax({
|
||||
method: "GET",
|
||||
url: PATH_PREFIX + "/api/v1/label/__name__/values",
|
||||
dataType: "json",
|
||||
success: function(json, textStatus) {
|
||||
if (json.status !== "success") {
|
||||
self.showError("Error loading available metrics!")
|
||||
return;
|
||||
}
|
||||
var metrics = json.data;
|
||||
for (var i = 0; i < metrics.length; i++) {
|
||||
self.insertMetric[0].options.add(new Option(metrics[i], metrics[i]));
|
||||
}
|
||||
self.expr.typeahead({
|
||||
source: metrics,
|
||||
items: "all"
|
||||
});
|
||||
// This needs to happen after attaching the typeahead plugin, as it
|
||||
// otherwise breaks the typeahead functionality.
|
||||
self.expr.focus();
|
||||
},
|
||||
error: function() {
|
||||
self.showError("Error loading available metrics!");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.onChange = function(handler) {
|
||||
this.changeHandler = handler;
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.getOptions = function() {
|
||||
var self = this;
|
||||
var options = {};
|
||||
|
||||
var optionInputs = [
|
||||
"range_input",
|
||||
"end_input",
|
||||
"step_input",
|
||||
"stacked"
|
||||
];
|
||||
|
||||
self.queryForm.find("input").each(function(index, element) {
|
||||
var name = element.name;
|
||||
if ($.inArray(name, optionInputs) >= 0) {
|
||||
options[name] = element.value;
|
||||
}
|
||||
});
|
||||
options["expr"] = self.expr.val();
|
||||
options["tab"] = self.options["tab"];
|
||||
return options;
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.parseDuration = function(rangeText) {
|
||||
var rangeRE = new RegExp("^([0-9]+)([ywdhms]+)$");
|
||||
var matches = rangeText.match(rangeRE);
|
||||
if (!matches) { return };
|
||||
if (matches.length != 3) {
|
||||
return 60;
|
||||
}
|
||||
var value = parseInt(matches[1]);
|
||||
var unit = matches[2];
|
||||
return value * Prometheus.Graph.timeFactors[unit];
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.increaseRange = function() {
|
||||
var self = this;
|
||||
var rangeSeconds = self.parseDuration(self.rangeInput.val());
|
||||
for (var i = 0; i < Prometheus.Graph.stepValues.length; i++) {
|
||||
if (rangeSeconds < self.parseDuration(Prometheus.Graph.stepValues[i])) {
|
||||
self.rangeInput.val(Prometheus.Graph.stepValues[i]);
|
||||
if (self.expr.val()) {
|
||||
self.submitQuery();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.decreaseRange = function() {
|
||||
var self = this;
|
||||
var rangeSeconds = self.parseDuration(self.rangeInput.val());
|
||||
for (var i = Prometheus.Graph.stepValues.length - 1; i >= 0; i--) {
|
||||
if (rangeSeconds > self.parseDuration(Prometheus.Graph.stepValues[i])) {
|
||||
self.rangeInput.val(Prometheus.Graph.stepValues[i]);
|
||||
if (self.expr.val()) {
|
||||
self.submitQuery();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.getEndDate = function() {
|
||||
var self = this;
|
||||
if (!self.endDate || !self.endDate.val()) {
|
||||
return new Date();
|
||||
}
|
||||
return self.endDate.data('datetimepicker').getDate().getTime();
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.getOrSetEndDate = function() {
|
||||
var self = this;
|
||||
var date = self.getEndDate();
|
||||
self.setEndDate(date);
|
||||
return date;
|
||||
}
|
||||
|
||||
Prometheus.Graph.prototype.setEndDate = function(date) {
|
||||
var self = this;
|
||||
self.endDate.data('datetimepicker').setValue(date);
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.increaseEnd = function() {
|
||||
var self = this;
|
||||
self.setEndDate(new Date(self.getOrSetEndDate() + self.parseDuration(self.rangeInput.val()) * 1000/2 )) // increase by 1/2 range & convert ms in s
|
||||
self.submitQuery();
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.decreaseEnd = function() {
|
||||
var self = this;
|
||||
self.setEndDate(new Date(self.getOrSetEndDate() - self.parseDuration(self.rangeInput.val()) * 1000/2 ))
|
||||
self.submitQuery();
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.submitQuery = function() {
|
||||
var self = this;
|
||||
self.clearError();
|
||||
if (!self.expr.val()) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.spinner.show();
|
||||
self.evalStats.empty();
|
||||
|
||||
var startTime = new Date().getTime();
|
||||
var rangeSeconds = self.parseDuration(self.rangeInput.val());
|
||||
var resolution = self.queryForm.find("input[name=step_input]").val() || Math.max(Math.floor(rangeSeconds / 250), 1);
|
||||
var endDate = self.getEndDate() / 1000;
|
||||
|
||||
if (self.queryXhr) {
|
||||
self.queryXhr.abort();
|
||||
}
|
||||
var url;
|
||||
var success;
|
||||
var params = {
|
||||
"query": self.expr.val()
|
||||
};
|
||||
if (self.options["tab"] === 0) {
|
||||
params['start'] = endDate - rangeSeconds;
|
||||
params['end'] = endDate;
|
||||
params['step'] = resolution;
|
||||
url = PATH_PREFIX + "/api/v1/query_range";
|
||||
success = function(json, textStatus) { self.handleGraphResponse(json, textStatus); };
|
||||
} else {
|
||||
params['time'] = startTime / 1000;
|
||||
url = PATH_PREFIX + "/api/v1/query";
|
||||
success = function(json, textStatus) { self.handleConsoleResponse(json, textStatus); };
|
||||
}
|
||||
|
||||
self.queryXhr = $.ajax({
|
||||
method: self.queryForm.attr("method"),
|
||||
url: url,
|
||||
dataType: "json",
|
||||
data: params,
|
||||
success: function(json, textStatus) {
|
||||
if (json.status !== "success") {
|
||||
self.showError(json.error);
|
||||
return;
|
||||
}
|
||||
success(json.data, textStatus);
|
||||
},
|
||||
error: function(xhr, resp) {
|
||||
if (resp != "abort") {
|
||||
var err;
|
||||
if (xhr.responseJSON !== undefined) {
|
||||
err = xhr.responseJSON.error;
|
||||
} else {
|
||||
err = xhr.statusText;
|
||||
}
|
||||
self.showError("Error executing query: " + err);
|
||||
}
|
||||
},
|
||||
complete: function() {
|
||||
var duration = new Date().getTime() - startTime;
|
||||
self.evalStats.html("Load time: " + duration + "ms <br /> Resolution: " + resolution + "s");
|
||||
self.spinner.hide();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.showError = function(msg) {
|
||||
var self = this;
|
||||
self.error.text(msg);
|
||||
self.error.show();
|
||||
}
|
||||
|
||||
Prometheus.Graph.prototype.clearError = function(msg) {
|
||||
var self = this;
|
||||
self.error.text('');
|
||||
self.error.hide();
|
||||
}
|
||||
|
||||
Prometheus.Graph.prototype.updateRefresh = function() {
|
||||
var self = this;
|
||||
|
||||
if (self.timeoutID) {
|
||||
window.clearTimeout(self.timeoutID);
|
||||
}
|
||||
|
||||
interval = self.parseDuration(self.refreshInterval.val());
|
||||
if (!interval) { return };
|
||||
|
||||
self.timeoutID = window.setTimeout(function() {
|
||||
self.submitQuery();
|
||||
self.updateRefresh();
|
||||
}, interval * SECOND);
|
||||
}
|
||||
|
||||
Prometheus.Graph.prototype.renderLabels = function(labels) {
|
||||
var labelStrings = [];
|
||||
for (label in labels) {
|
||||
if (label != "__name__") {
|
||||
labelStrings.push("<strong>" + label + "</strong>: " + escapeHTML(labels[label]));
|
||||
}
|
||||
}
|
||||
return labels = "<div class=\"labels\">" + labelStrings.join("<br>") + "</div>";
|
||||
}
|
||||
|
||||
Prometheus.Graph.prototype.metricToTsName = function(labels) {
|
||||
var tsName = (labels["__name__"] || '') + "{";
|
||||
var labelStrings = [];
|
||||
for (label in labels) {
|
||||
if (label != "__name__") {
|
||||
labelStrings.push(label + "=\"" + labels[label] + "\"");
|
||||
}
|
||||
}
|
||||
tsName += labelStrings.join(",") + "}";
|
||||
return tsName;
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.parseValue = function(value) {
|
||||
var val = parseFloat(value);
|
||||
if (isNaN(val)) {
|
||||
// "+Inf", "-Inf", "+Inf" will be parsed into NaN by parseFloat(). The
|
||||
// can't be graphed, so show them as gaps (null).
|
||||
return null
|
||||
}
|
||||
return val;
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.transformData = function(json) {
|
||||
var self = this;
|
||||
var palette = new Rickshaw.Color.Palette();
|
||||
if (json.resultType != "matrix") {
|
||||
self.showError("Result is not of matrix type! Please enter a correct expression.");
|
||||
return [];
|
||||
}
|
||||
var data = json.result.map(function(ts) {
|
||||
var name;
|
||||
var labels;
|
||||
if (ts.metric === null) {
|
||||
name = "scalar";
|
||||
labels = {};
|
||||
} else {
|
||||
name = escapeHTML(self.metricToTsName(ts.metric));
|
||||
labels = ts.metric;
|
||||
}
|
||||
return {
|
||||
name: name,
|
||||
labels: labels,
|
||||
data: ts.values.map(function(value) {
|
||||
return {
|
||||
x: value[0],
|
||||
y: self.parseValue(value[1])
|
||||
}
|
||||
}),
|
||||
color: palette.color()
|
||||
};
|
||||
});
|
||||
Rickshaw.Series.zeroFill(data);
|
||||
return data;
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.updateGraph = function() {
|
||||
var self = this;
|
||||
if (self.data.length == 0) { return; }
|
||||
|
||||
// Remove any traces of an existing graph.
|
||||
self.legend.empty();
|
||||
if (self.graphArea.children().length > 0) {
|
||||
self.graph.remove();
|
||||
self.yAxis.remove();
|
||||
}
|
||||
self.graph = $('<div class="graph"></div>');
|
||||
self.yAxis = $('<div class="y_axis"></div>');
|
||||
self.graphArea.append(self.graph);
|
||||
self.graphArea.append(self.yAxis);
|
||||
|
||||
var endTime = self.getEndDate() / 1000; // Convert to UNIX timestamp.
|
||||
var duration = self.parseDuration(self.rangeInput.val()) || 3600; // 1h default.
|
||||
var startTime = endTime - duration;
|
||||
self.data.forEach(function(s) {
|
||||
// Padding series with invisible "null" values at the configured x-axis boundaries ensures
|
||||
// that graphs are displayed with a fixed x-axis range instead of snapping to the available
|
||||
// time range in the data.
|
||||
if (s.data[0].x > startTime) {
|
||||
s.data.unshift({x: startTime, y: null});
|
||||
}
|
||||
if (s.data[s.data.length - 1].x < endTime) {
|
||||
s.data.push({x: endTime, y: null});
|
||||
}
|
||||
});
|
||||
|
||||
// Now create the new graph.
|
||||
self.rickshawGraph = new Rickshaw.Graph({
|
||||
element: self.graph[0],
|
||||
height: Math.max(self.graph.innerHeight(), 100),
|
||||
width: Math.max(self.graph.innerWidth() - 80, 200),
|
||||
renderer: (self.isStacked() ? "stack" : "line"),
|
||||
interpolation: "linear",
|
||||
series: self.data,
|
||||
min: "auto",
|
||||
});
|
||||
|
||||
var xAxis = new Rickshaw.Graph.Axis.Time({ graph: self.rickshawGraph });
|
||||
|
||||
var yAxis = new Rickshaw.Graph.Axis.Y({
|
||||
graph: self.rickshawGraph,
|
||||
orientation: "left",
|
||||
tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
|
||||
element: self.yAxis[0],
|
||||
});
|
||||
|
||||
self.rickshawGraph.render();
|
||||
|
||||
var hoverDetail = new Rickshaw.Graph.HoverDetail({
|
||||
graph: self.rickshawGraph,
|
||||
formatter: function(series, x, y) {
|
||||
var swatch = '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>';
|
||||
var content = swatch + (series.labels["__name__"] || 'value') + ": <strong>" + y + '</strong><br>';
|
||||
return content + self.renderLabels(series.labels);
|
||||
}
|
||||
});
|
||||
|
||||
var legend = new Rickshaw.Graph.Legend({
|
||||
element: self.legend[0],
|
||||
graph: self.rickshawGraph,
|
||||
});
|
||||
|
||||
var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight( {
|
||||
graph: self.rickshawGraph,
|
||||
legend: legend
|
||||
});
|
||||
|
||||
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
|
||||
graph: self.rickshawGraph,
|
||||
legend: legend
|
||||
});
|
||||
|
||||
self.changeHandler();
|
||||
};
|
||||
|
||||
Prometheus.Graph.prototype.resizeGraph = function() {
|
||||
var self = this;
|
||||
if (self.rickshawGraph != null) {
|
||||
self.rickshawGraph.configure({
|
||||
width: Math.max(self.graph.innerWidth() - 80, 200),
|
||||
});
|
||||
self.rickshawGraph.render();
|
||||
}
|
||||
}
|
||||
|
||||
Prometheus.Graph.prototype.handleGraphResponse = function(json, textStatus) {
|
||||
var self = this
|
||||
// Rickshaw mutates passed series data for stacked graphs, so we need to save
|
||||
// the original AJAX response in order to re-transform it into series data
|
||||
// when the user disables the stacking.
|
||||
self.graphJSON = json;
|
||||
self.data = self.transformData(json);
|
||||
if (self.data.length == 0) {
|
||||
self.showError("No datapoints found.");
|
||||
return;
|
||||
}
|
||||
self.graphTab.removeClass("reload");
|
||||
self.updateGraph();
|
||||
}
|
||||
|
||||
Prometheus.Graph.prototype.handleConsoleResponse = function(data, textStatus) {
|
||||
var self = this;
|
||||
self.consoleTab.removeClass("reload");
|
||||
self.graphJSON = null;
|
||||
|
||||
var tBody = self.consoleTab.find(".console_table tbody");
|
||||
tBody.empty();
|
||||
|
||||
switch(data.resultType) {
|
||||
case "vector":
|
||||
if (data.result.length === 0) {
|
||||
tBody.append("<tr><td colspan='2'><i>no data</i></td></tr>");
|
||||
return;
|
||||
}
|
||||
for (var i = 0; i < data.result.length; i++) {
|
||||
var s = data.result[i];
|
||||
var tsName = self.metricToTsName(s.metric);
|
||||
tBody.append("<tr><td>" + escapeHTML(tsName) + "</td><td>" + s.value[1] + "</td></tr>");
|
||||
}
|
||||
break;
|
||||
case "matrix":
|
||||
if (data.result.length === 0) {
|
||||
tBody.append("<tr><td colspan='2'><i>no data</i></td></tr>");
|
||||
return;
|
||||
}
|
||||
for (var i = 0; i < data.result.length; i++) {
|
||||
var v = data.result[i];
|
||||
var tsName = self.metricToTsName(v.metric);
|
||||
var valueText = "";
|
||||
for (var j = 0; j < v.values.length; j++) {
|
||||
valueText += v.values[j][1] + " @" + v.values[j][0] + "<br/>";
|
||||
}
|
||||
tBody.append("<tr><td>" + escapeHTML(tsName) + "</td><td>" + valueText + "</td></tr>")
|
||||
}
|
||||
break;
|
||||
case "scalar":
|
||||
tBody.append("<tr><td>scalar</td><td>" + data.result[1] + "</td></tr>");
|
||||
break;
|
||||
case "string":
|
||||
tBody.append("<tr><td>string</td><td>" + data.result[1] + "</td></tr>");
|
||||
break;
|
||||
default:
|
||||
self.showError("Unsupported value type!");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function parseGraphOptionsFromURL() {
|
||||
var hashOptions = window.location.hash.slice(1);
|
||||
if (!hashOptions) {
|
||||
return [];
|
||||
}
|
||||
var optionsJSON = decodeURIComponent(window.location.hash.slice(1));
|
||||
options = JSON.parse(optionsJSON);
|
||||
return options;
|
||||
}
|
||||
|
||||
// NOTE: This needs to be kept in sync with rules/helpers.go:GraphLinkForExpression!
|
||||
function storeGraphOptionsInURL() {
|
||||
var allGraphsOptions = [];
|
||||
for (var i = 0; i < graphs.length; i++) {
|
||||
allGraphsOptions.push(graphs[i].getOptions());
|
||||
}
|
||||
var optionsJSON = JSON.stringify(allGraphsOptions);
|
||||
window.location.hash = encodeURIComponent(optionsJSON);
|
||||
}
|
||||
|
||||
function addGraph(options) {
|
||||
var graph = new Prometheus.Graph($("#graph_container"), options);
|
||||
graphs.push(graph);
|
||||
graph.onChange(function() {
|
||||
storeGraphOptionsInURL();
|
||||
});
|
||||
$(window).resize(function() {
|
||||
graph.resizeGraph();
|
||||
});
|
||||
}
|
||||
|
||||
function escapeHTML(string) {
|
||||
var entityMap = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
"/": '/'
|
||||
};
|
||||
|
||||
return String(string).replace(/[&<>"'\/]/g, function (s) {
|
||||
return entityMap[s];
|
||||
});
|
||||
}
|
||||
|
||||
function init() {
|
||||
$.ajaxSetup({
|
||||
cache: false
|
||||
});
|
||||
|
||||
$.ajax({
|
||||
url: PATH_PREFIX + "/static/js/graph_template.handlebar",
|
||||
success: function(data) {
|
||||
graphTemplate = Handlebars.compile(data);
|
||||
var options = parseGraphOptionsFromURL();
|
||||
if (options.length == 0) {
|
||||
options.push({});
|
||||
}
|
||||
for (var i = 0; i < options.length; i++) {
|
||||
addGraph(options[i]);
|
||||
}
|
||||
$("#add_graph").click(function() { addGraph({}); });
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
$(init);
|
128
prom/web/blob/static/js/graph_template.handlebar
Normal file
128
prom/web/blob/static/js/graph_template.handlebar
Normal file
@ -0,0 +1,128 @@
|
||||
<div id="graph_wrapper{{id}}" class="graph_wrapper">
|
||||
<form class="query_form form-inline">
|
||||
<div class="row">
|
||||
<div class="col-lg-10">
|
||||
<textarea rows="1" placeholder="Expression (press Shift+Enter for newlines)" name="expr" id="expr{{id}}" class="form-control expression_input" data-provide="typeahead" autocomplete="off">{{expr}}</textarea>
|
||||
</div>
|
||||
<div class="col-lg-2">
|
||||
<div class="eval_stats pull-right"></div>
|
||||
<img src="{{ pathPrefix }}/static/img/ajax-loader.gif" class="spinner" alt="ajax_spinner">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-lg-10">
|
||||
<input class="btn btn-primary execute_btn" type="submit" value="Execute" name="submit">
|
||||
<select class="form-control expression_select" name="insert_metric">
|
||||
<option value="">- insert metric at cursor -</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-lg-12">
|
||||
<div class="error alert alert-danger"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!--
|
||||
TODO: Convert this to Bootstrap navbar. This requires Javascript
|
||||
refresh.
|
||||
-->
|
||||
<div class="row">
|
||||
<div class="col-lg-12">
|
||||
<div role="tabpanel">
|
||||
<ul class="nav nav-tabs" role="tablist">
|
||||
<li role="presentation"><a href="#graph{{id}}" aria-controls="graph{{id}}" role="tab" data-toggle="tab">Graph</a></li>
|
||||
<li role="presentation" class="active"><a href="#console{{id}}" aria-controls="console{{id}}" role="tab" data-toggle="tab">Console</a></li>
|
||||
</ul>
|
||||
<div class="tab-content">
|
||||
<div role="tabpanel" class="tab-pane graph_container reload" id="graph{{id}}">
|
||||
<div class="clearfix">
|
||||
<!-- Extracted to force grouped inputs. -->
|
||||
<div class="prometheus_input_group range_input pull-left">
|
||||
<button
|
||||
class="btn btn-default pull-left"
|
||||
type="button"
|
||||
name="dec_range"
|
||||
title="Shrink the time range.">
|
||||
<i class="glyphicon glyphicon-minus"></i>
|
||||
</button>
|
||||
<input
|
||||
class="pull-left input"
|
||||
id="range_input{{id}}"
|
||||
title="Time range of graph"
|
||||
type="text"
|
||||
name="range_input"
|
||||
size="3"
|
||||
value="{{range_input}}">
|
||||
<button
|
||||
class="btn btn-default pull-left"
|
||||
type="button"
|
||||
name="inc_range"
|
||||
title="Grow the time range.">
|
||||
<i class="glyphicon glyphicon-plus"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Extracted to force grouped inputs. -->
|
||||
<div class="prometheus_input_group pull-left">
|
||||
|
||||
<button
|
||||
class="btn btn-default pull-left"
|
||||
type="button"
|
||||
name="dec_end"
|
||||
title="Rewind the end time.">
|
||||
<i class="glyphicon glyphicon-backward"></i>
|
||||
</button>
|
||||
|
||||
<input
|
||||
class="pull-left date_input input"
|
||||
id="end{{id}}"
|
||||
title="End time of graph"
|
||||
placeholder="Until"
|
||||
data-format="yyyy-MM-dd"
|
||||
type="text"
|
||||
name="end_input"
|
||||
size="16"
|
||||
value="{{end}}">
|
||||
|
||||
<button
|
||||
class="btn btn-default pull-left"
|
||||
type="button"
|
||||
name="inc_end"
|
||||
title="Advance the end time.">
|
||||
<i class="glyphicon glyphicon-forward"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="prometheus_input_group pull-left">
|
||||
<input class="input" title="Resolution in seconds" placeholder="Res. (s)" type="text" name="step_input" id="step_input{{id}}" value="{{step_input}}" size="6">
|
||||
</div>
|
||||
|
||||
<div class="prometheus_input_group pull-left">
|
||||
<button type="button" class="btn btn-default stacked_btn">
|
||||
<i class="glyphicon"></i> stacked
|
||||
</button>
|
||||
<input type="hidden" name="stacked" value="{{stacked}}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="graph_area"></div>
|
||||
<div class="legend"></div>
|
||||
</div>
|
||||
<div role="tabpanel" class="tab-pane active console reload" id="console{{id}}">
|
||||
<table class="table table-condensed table-hover console_table">
|
||||
<thead>
|
||||
<th>Element</th>
|
||||
<th>Value</th>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td colspan="2"><i>no data</i></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
628
prom/web/blob/static/js/prom_console.js
Normal file
628
prom/web/blob/static/js/prom_console.js
Normal file
@ -0,0 +1,628 @@
|
||||
/*
|
||||
* Functions to make it easier to write prometheus consoles, such
|
||||
* as graphs.
|
||||
*
|
||||
*/
|
||||
|
||||
PromConsole = {};
|
||||
|
||||
PromConsole.NumberFormatter = {};
|
||||
PromConsole.NumberFormatter.prefixesBig = ["k", "M", "G", "T", "P", "E", "Z", "Y"];
|
||||
PromConsole.NumberFormatter.prefixesBig1024 = ["ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"];
|
||||
PromConsole.NumberFormatter.prefixesSmall = ["m", "u", "n", "p", "f", "a", "z", "y"];
|
||||
|
||||
PromConsole._stripTrailingZero = function(x) {
|
||||
if (x.indexOf("e") == -1) {
|
||||
// It's not safe to strip if it's scientific notation.
|
||||
return x.replace(/\.?0*$/, '');
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
// Humanize a number.
|
||||
PromConsole.NumberFormatter.humanize = function(x) {
|
||||
var ret = PromConsole.NumberFormatter._humanize(
|
||||
x, PromConsole.NumberFormatter.prefixesBig,
|
||||
PromConsole.NumberFormatter.prefixesSmall, 1000);
|
||||
x = ret[0];
|
||||
var prefix = ret[1];
|
||||
if (Math.abs(x) < 1) {
|
||||
return x.toExponential(3) + prefix;
|
||||
}
|
||||
return PromConsole._stripTrailingZero(x.toFixed(3)) + prefix;
|
||||
}
|
||||
|
||||
// Humanize a number, don't use milli/micro/etc. prefixes.
|
||||
PromConsole.NumberFormatter.humanizeNoSmallPrefix = function(x) {
|
||||
if (Math.abs(x) < 1) {
|
||||
return PromConsole._stripTrailingZero(x.toPrecision(3));
|
||||
}
|
||||
var ret = PromConsole.NumberFormatter._humanize(
|
||||
x, PromConsole.NumberFormatter.prefixesBig,
|
||||
[], 1000);
|
||||
x = ret[0];
|
||||
var prefix = ret[1];
|
||||
return PromConsole._stripTrailingZero(x.toFixed(3)) + prefix;
|
||||
}
|
||||
|
||||
// Humanize a number with 1024 as the base, rather than 1000.
|
||||
PromConsole.NumberFormatter.humanize1024 = function(x) {
|
||||
var ret = PromConsole.NumberFormatter._humanize(
|
||||
x, PromConsole.NumberFormatter.prefixesBig1024,
|
||||
[], 1024);
|
||||
x = ret[0];
|
||||
var prefix = ret[1];
|
||||
if (Math.abs(x) < 1) {
|
||||
return x.toExponential(3) + prefix;
|
||||
}
|
||||
return PromConsole._stripTrailingZero(x.toFixed(3)) + prefix;
|
||||
}
|
||||
|
||||
// Humanize a number, returning an exact representation.
|
||||
PromConsole.NumberFormatter.humanizeExact = function(x) {
|
||||
var ret = PromConsole.NumberFormatter._humanize(
|
||||
x, PromConsole.NumberFormatter.prefixesBig,
|
||||
PromConsole.NumberFormatter.prefixesSmall, 1000);
|
||||
return ret[0] + ret[1];
|
||||
}
|
||||
|
||||
PromConsole.NumberFormatter._humanize = function(x, prefixesBig, prefixesSmall, factor) {
|
||||
var prefix = ""
|
||||
if (x == 0) {
|
||||
/* Do nothing. */
|
||||
} else if (Math.abs(x) >= 1) {
|
||||
for (var i=0; i < prefixesBig.length && Math.abs(x) >= factor; ++i) {
|
||||
x /= factor;
|
||||
prefix = prefixesBig[i];
|
||||
}
|
||||
} else {
|
||||
for (var i=0; i < prefixesSmall.length && Math.abs(x) < 1; ++i) {
|
||||
x *= factor;
|
||||
prefix = prefixesSmall[i];
|
||||
}
|
||||
}
|
||||
return [x, prefix];
|
||||
};
|
||||
|
||||
|
||||
PromConsole.TimeControl = function() {
|
||||
document.getElementById("prom_graph_duration_shrink").onclick = this.decreaseDuration.bind(this);
|
||||
document.getElementById("prom_graph_duration_grow").onclick = this.increaseDuration.bind(this);
|
||||
document.getElementById("prom_graph_time_back").onclick = this.decreaseEnd.bind(this);
|
||||
document.getElementById("prom_graph_time_forward").onclick = this.increaseEnd.bind(this);
|
||||
document.getElementById("prom_graph_refresh_button").onclick = this.refresh.bind(this);
|
||||
this.durationElement = document.getElementById("prom_graph_duration");
|
||||
this.endElement = document.getElementById("prom_graph_time_end");
|
||||
this.durationElement.oninput = this.dispatch.bind(this);
|
||||
this.endElement.oninput = this.dispatch.bind(this);
|
||||
this.endElement.oninput = this.dispatch.bind(this);
|
||||
this.refreshValueElement = document.getElementById("prom_graph_refresh_button_value");
|
||||
|
||||
var refreshList = document.getElementById("prom_graph_refresh_intervals");
|
||||
var refreshIntervals = ["Off", "1m", "5m", "15m", "1h"];
|
||||
for (var i=0; i < refreshIntervals.length; ++i) {
|
||||
var li = document.createElement("li");
|
||||
li.onclick = this.setRefresh.bind(this, refreshIntervals[i]);
|
||||
li.textContent = refreshIntervals[i];
|
||||
refreshList.appendChild(li);
|
||||
}
|
||||
|
||||
this.durationElement.value = PromConsole.TimeControl.prototype.getHumanDuration(
|
||||
PromConsole.TimeControl._initialValues.duration);
|
||||
if (PromConsole.TimeControl._initialValues.endTimeNow === undefined) {
|
||||
this.endElement.value = PromConsole.TimeControl.prototype.getHumanDate(
|
||||
new Date(PromConsole.TimeControl._initialValues.endTime * 1000));
|
||||
}
|
||||
}
|
||||
|
||||
PromConsole.TimeControl.timeFactors = {
|
||||
"y": 60 * 60 * 24 * 365,
|
||||
"w": 60 * 60 * 24 * 7,
|
||||
"d": 60 * 60 * 24,
|
||||
"h": 60 * 60,
|
||||
"m": 60,
|
||||
"s": 1
|
||||
};
|
||||
|
||||
PromConsole.TimeControl.stepValues = [
|
||||
"10s", "1m", "5m", "15m", "30m", "1h", "2h", "6h", "12h", "1d", "2d",
|
||||
"1w", "2w", "4w", "8w", "1y", "2y"
|
||||
];
|
||||
|
||||
PromConsole.TimeControl.prototype._setHash = function() {
|
||||
var duration = this.parseDuration(this.durationElement.value);
|
||||
var endTime = this.getEndDate() / 1000;
|
||||
window.location.hash = "#pctc" + encodeURIComponent(JSON.stringify(
|
||||
{duration: duration, endTime: endTime}));
|
||||
}
|
||||
|
||||
PromConsole.TimeControl._initialValues = function() {
|
||||
var hash = window.location.hash;
|
||||
if (hash.indexOf('#pctc') == 0) {
|
||||
return JSON.parse(decodeURIComponent(hash.substring(5)));
|
||||
}
|
||||
return {duration: 3600, endTime: new Date().getTime() / 1000, endTimeNow: true};
|
||||
}();
|
||||
|
||||
PromConsole.TimeControl.prototype.parseDuration = function(durationText) {
|
||||
var durationRE = new RegExp("^([0-9]+)([ywdhms]?)$");
|
||||
var matches = durationText.match(durationRE);
|
||||
if (!matches) { return 3600; }
|
||||
var value = parseInt(matches[1]);
|
||||
var unit = matches[2] || 's';
|
||||
return value * PromConsole.TimeControl.timeFactors[unit];
|
||||
};
|
||||
|
||||
PromConsole.TimeControl.prototype.getHumanDuration = function(duration) {
|
||||
var units = [];
|
||||
for (var key in PromConsole.TimeControl.timeFactors) {
|
||||
units.push([PromConsole.TimeControl.timeFactors[key], key]);
|
||||
}
|
||||
units.sort(function(a, b) { return b[0] - a[0] });
|
||||
for (var i = 0; i < units.length; ++i) {
|
||||
if (duration % units[i][0] == 0) {
|
||||
return (duration / units[i][0]) + units[i][1];
|
||||
}
|
||||
}
|
||||
return duration;
|
||||
};
|
||||
|
||||
PromConsole.TimeControl.prototype.increaseDuration = function() {
|
||||
var durationSeconds = this.parseDuration(this.durationElement.value);
|
||||
for (var i = 0; i < PromConsole.TimeControl.stepValues.length; i++) {
|
||||
if (durationSeconds < this.parseDuration(PromConsole.TimeControl.stepValues[i])) {
|
||||
this.setDuration(PromConsole.TimeControl.stepValues[i]);
|
||||
this.dispatch();
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
PromConsole.TimeControl.prototype.decreaseDuration = function() {
|
||||
var durationSeconds = this.parseDuration(this.durationElement.value);
|
||||
for (var i = PromConsole.TimeControl.stepValues.length - 1; i >= 0; i--) {
|
||||
if (durationSeconds > this.parseDuration(PromConsole.TimeControl.stepValues[i])) {
|
||||
this.setDuration(PromConsole.TimeControl.stepValues[i]);
|
||||
this.dispatch();
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
PromConsole.TimeControl.prototype.setDuration = function(duration) {
|
||||
this.durationElement.value = duration;
|
||||
this._setHash();
|
||||
};
|
||||
|
||||
PromConsole.TimeControl.prototype.getEndDate = function() {
|
||||
if (this.endElement.value == '') {
|
||||
return null;
|
||||
}
|
||||
return new Date(this.endElement.value).getTime();
|
||||
};
|
||||
|
||||
PromConsole.TimeControl.prototype.getOrSetEndDate = function() {
|
||||
var date = this.getEndDate();
|
||||
if (date) {
|
||||
return date;
|
||||
}
|
||||
date = new Date();
|
||||
this.setEndDate(date);
|
||||
return date;
|
||||
}
|
||||
|
||||
PromConsole.TimeControl.prototype.getHumanDate = function(date) {
|
||||
var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
|
||||
var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
|
||||
return date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " " +
|
||||
hours + ":" + minutes;
|
||||
}
|
||||
|
||||
PromConsole.TimeControl.prototype.setEndDate = function(date) {
|
||||
this.setRefresh("Off");
|
||||
this.endElement.value = this.getHumanDate(date);
|
||||
this._setHash();
|
||||
};
|
||||
|
||||
|
||||
PromConsole.TimeControl.prototype.increaseEnd = function() {
|
||||
// Increase duration 25% range & convert ms to s.
|
||||
this.setEndDate(new Date(this.getOrSetEndDate() + this.parseDuration(this.durationElement.value) * 1000/4 ));
|
||||
this.dispatch();
|
||||
};
|
||||
|
||||
PromConsole.TimeControl.prototype.decreaseEnd = function() {
|
||||
this.setEndDate(new Date(this.getOrSetEndDate() - this.parseDuration(this.durationElement.value) * 1000/4 ));
|
||||
this.dispatch();
|
||||
};
|
||||
|
||||
PromConsole.TimeControl.prototype.refresh = function() {
|
||||
this.endElement.value = '';
|
||||
this._setHash();
|
||||
this.dispatch();
|
||||
}
|
||||
|
||||
PromConsole.TimeControl.prototype.dispatch = function() {
|
||||
var durationSeconds = this.parseDuration(this.durationElement.value);
|
||||
var end = this.getEndDate();
|
||||
if (end === null) {
|
||||
end = new Date().getTime();
|
||||
}
|
||||
for (var i = 0; i< PromConsole._graph_registry.length; i++) {
|
||||
var graph = PromConsole._graph_registry[i];
|
||||
graph.params.duration = durationSeconds;
|
||||
graph.params.endTime = end / 1000;
|
||||
graph.dispatch();
|
||||
}
|
||||
};
|
||||
|
||||
PromConsole.TimeControl.prototype._refreshInterval = null;
|
||||
|
||||
PromConsole.TimeControl.prototype.setRefresh = function(duration) {
|
||||
if (this._refreshInterval !== null) {
|
||||
window.clearInterval(this._refreshInterval);
|
||||
this._refreshInterval = null;
|
||||
}
|
||||
if (duration != "Off") {
|
||||
if (this.endElement.value != '') {
|
||||
this.refresh();
|
||||
}
|
||||
var durationSeconds = this.parseDuration(duration);
|
||||
this._refreshInterval = window.setInterval(this.dispatch.bind(this), durationSeconds * 1000);
|
||||
}
|
||||
this.refreshValueElement.textContent = duration;
|
||||
};
|
||||
|
||||
|
||||
|
||||
// List of all graphs, used by time controls.
|
||||
PromConsole._graph_registry = [];
|
||||
|
||||
PromConsole.graphDefaults = {
|
||||
expr: null, // Expression to graph. Can be a list of strings.
|
||||
node: null, // DOM node to place graph under.
|
||||
// How long the graph is over, in seconds.
|
||||
duration: PromConsole.TimeControl._initialValues.duration,
|
||||
// The unixtime the graph ends at.
|
||||
endTime: PromConsole.TimeControl._initialValues.endTime,
|
||||
width: null, // Height of the graph div, excluding titles and legends.
|
||||
// Defaults to auto-detection.
|
||||
height: 200, // Height of the graph div, excluding titles and legends.
|
||||
min: "auto", // Minimum Y-axis value, defaults to lowest data value.
|
||||
max: undefined, // Maximum Y-axis value, defaults to highest data value.
|
||||
renderer: 'line', // Type of graphs, options are 'line' and 'area'.
|
||||
name: null, // What to call plots, defaults to trying to do
|
||||
// something reasonable.
|
||||
// If a string, it'll use that. [[ label ]] will be substituted.
|
||||
// If a function it'll be called with a map of keys to values,
|
||||
// and should return the name to use.
|
||||
// Can be a list of strings/functions, each element
|
||||
// will be applied to the plots from the corresponding
|
||||
// element of the expr list.
|
||||
xTitle: "Time", // The title of the x axis.
|
||||
yUnits: "", // The units of the y axis.
|
||||
yTitle: "", // The title of the y axis.
|
||||
// Number formatter for y axis.
|
||||
yAxisFormatter: PromConsole.NumberFormatter.humanize,
|
||||
// Number formatter for y values hover detail.
|
||||
yHoverFormatter: PromConsole.NumberFormatter.humanizeExact,
|
||||
};
|
||||
|
||||
PromConsole.Graph = function(params) {
|
||||
for (var k in PromConsole.graphDefaults) {
|
||||
if (!(k in params)) {
|
||||
params[k] = PromConsole.graphDefaults[k];
|
||||
}
|
||||
}
|
||||
if (typeof params.expr == "string") {
|
||||
params.expr = [params.expr];
|
||||
}
|
||||
if (typeof params.name == "string" || typeof params.name == "function") {
|
||||
var name = [];
|
||||
for (var i = 0; i < params.expr.length; i++) {
|
||||
name.push(params.name)
|
||||
}
|
||||
params.name = name;
|
||||
}
|
||||
|
||||
this.params = params;
|
||||
this.rendered_data = null;
|
||||
PromConsole._graph_registry.push(this);
|
||||
|
||||
/*
|
||||
* Table layout:
|
||||
* | yTitle | Graph |
|
||||
* | | xTitle |
|
||||
* | /graph | Legend |
|
||||
*/
|
||||
var table = document.createElement("table");
|
||||
table.className = "prom_graph_table";
|
||||
params.node.appendChild(table);
|
||||
var tr = document.createElement("tr");
|
||||
table.appendChild(tr);
|
||||
var yTitleTd = document.createElement("td");
|
||||
tr.appendChild(yTitleTd);
|
||||
var yTitleDiv = document.createElement("td");
|
||||
yTitleTd.appendChild(yTitleDiv);
|
||||
yTitleDiv.className = "prom_graph_ytitle";
|
||||
yTitleDiv.textContent = params.yTitle + (params.yUnits ? " (" + params.yUnits.trim() + ")" : "");
|
||||
|
||||
this.graphTd = document.createElement("td");
|
||||
tr.appendChild(this.graphTd);
|
||||
this.graphTd.className = "rickshaw_graph";
|
||||
this.graphTd.width = params.width;
|
||||
this.graphTd.height = params.height;
|
||||
|
||||
tr = document.createElement("tr");
|
||||
table.appendChild(tr);
|
||||
tr.appendChild(document.createElement("td"));
|
||||
var xTitleTd = document.createElement("td");
|
||||
tr.appendChild(xTitleTd);
|
||||
xTitleTd.className = "prom_graph_xtitle";
|
||||
xTitleTd.textContent = params.xTitle;
|
||||
|
||||
tr = document.createElement("tr");
|
||||
table.appendChild(tr);
|
||||
var graphLinkTd = document.createElement("td");
|
||||
tr.appendChild(graphLinkTd);
|
||||
var graphLinkA = document.createElement("a");
|
||||
graphLinkTd.appendChild(graphLinkA);
|
||||
graphLinkA.className = "prom_graph_link";
|
||||
graphLinkA.textContent = "+";
|
||||
graphLinkA.href = PromConsole._graphsToSlashGraphURL(params.expr);
|
||||
var legendTd = document.createElement("td");
|
||||
tr.appendChild(legendTd);
|
||||
this.legendDiv = document.createElement("div");
|
||||
legendTd.width = params.width;
|
||||
legendTd.appendChild(this.legendDiv);
|
||||
|
||||
window.addEventListener('resize', function() {
|
||||
if(this.rendered_data !== null) {
|
||||
this._render(this.rendered_data);
|
||||
}
|
||||
}.bind(this))
|
||||
|
||||
this.dispatch();
|
||||
|
||||
};
|
||||
|
||||
PromConsole.Graph.prototype._parseValue = function(value) {
|
||||
var val = parseFloat(value);
|
||||
if (isNaN(val)) {
|
||||
// "+Inf", "-Inf", "+Inf" will be parsed into NaN by parseFloat(). The
|
||||
// can't be graphed, so show them as gaps (null).
|
||||
return null
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
PromConsole.Graph.prototype._escapeHTML = function(string) {
|
||||
var entityMap = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
"/": '/'
|
||||
};
|
||||
|
||||
return string.replace(/[&<>"'\/]/g, function (s) {
|
||||
return entityMap[s];
|
||||
});
|
||||
}
|
||||
|
||||
PromConsole.Graph.prototype._render = function(data) {
|
||||
var self = this;
|
||||
var palette = new Rickshaw.Color.Palette();
|
||||
var series = [];
|
||||
|
||||
// This will be used on resize.
|
||||
this.rendered_data = data;
|
||||
|
||||
|
||||
var nameFuncs = [];
|
||||
if (this.params.name === null) {
|
||||
var chooser = PromConsole._chooseNameFunction(data);
|
||||
for (var i = 0; i < this.params.expr.length; i++) {
|
||||
nameFuncs.push(chooser);
|
||||
}
|
||||
} else {
|
||||
for (var i = 0; i < this.params.name.length; i++) {
|
||||
if (typeof this.params.name[i] == "string") {
|
||||
nameFuncs.push(function(i, metric) {
|
||||
return PromConsole._interpolateName(this.params.name[i], metric);
|
||||
}.bind(this, i));
|
||||
} else {
|
||||
nameFuncs.push(this.params.name[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get the data into the right format.
|
||||
var seriesLen = 0;
|
||||
for (var e = 0; e < data.length; e++) {
|
||||
for (var i = 0; i < data[e].value.length; i++) {
|
||||
series[seriesLen++] = {
|
||||
data: data[e].value[i].values.map(function(s) {return {x: s[0], y: self._parseValue(s[1])} }),
|
||||
color: palette.color(),
|
||||
name: self._escapeHTML(nameFuncs[e](data[e].value[i].metric)),
|
||||
};
|
||||
}
|
||||
}
|
||||
this._clearGraph();
|
||||
if (!series.length) {
|
||||
var errorText = document.createElement("div");
|
||||
errorText.className = 'prom_graph_error';
|
||||
errorText.textContent = 'No timeseries returned';
|
||||
this.graphTd.appendChild(errorText);
|
||||
return;
|
||||
}
|
||||
// Render.
|
||||
var graph = new Rickshaw.Graph({
|
||||
interpolation: "linear",
|
||||
width: this.graphTd.offsetWidth,
|
||||
height: this.params.height,
|
||||
element: this.graphTd,
|
||||
renderer: this.params.renderer,
|
||||
max: this.params.max,
|
||||
min: this.params.min,
|
||||
series: series
|
||||
});
|
||||
var hoverDetail = new Rickshaw.Graph.HoverDetail({
|
||||
graph: graph,
|
||||
onRender: function() {
|
||||
var xLabel = this.element.getElementsByClassName("x_label")[0];
|
||||
var item = this.element.getElementsByClassName("item")[0];
|
||||
if (xLabel.offsetWidth + xLabel.offsetLeft + this.element.offsetLeft > graph.element.offsetWidth
|
||||
|| item.offsetWidth + item.offsetLeft + this.element.offsetLeft > graph.element.offsetWidth) {
|
||||
xLabel.classList.add("prom_graph_hover_flipped");
|
||||
item.classList.add("prom_graph_hover_flipped");
|
||||
} else {
|
||||
xLabel.classList.remove("prom_graph_hover_flipped");
|
||||
item.classList.remove("prom_graph_hover_flipped");
|
||||
}
|
||||
},
|
||||
yFormatter: function(y) {return this.params.yHoverFormatter(y) + this.params.yUnits}.bind(this)
|
||||
});
|
||||
var yAxis = new Rickshaw.Graph.Axis.Y({
|
||||
graph: graph,
|
||||
tickFormat: this.params.yAxisFormatter
|
||||
});
|
||||
var xAxis = new Rickshaw.Graph.Axis.Time({
|
||||
graph: graph,
|
||||
});
|
||||
var legend = new Rickshaw.Graph.Legend({
|
||||
graph: graph,
|
||||
element: this.legendDiv
|
||||
});
|
||||
xAxis.render();
|
||||
yAxis.render();
|
||||
graph.render();
|
||||
};
|
||||
|
||||
PromConsole.Graph.prototype._clearGraph = function() {
|
||||
while (this.graphTd.lastChild) {
|
||||
this.graphTd.removeChild(this.graphTd.lastChild);
|
||||
}
|
||||
while (this.legendDiv.lastChild) {
|
||||
this.legendDiv.removeChild(this.legendDiv.lastChild);
|
||||
}
|
||||
}
|
||||
|
||||
PromConsole.Graph.prototype._xhrs = []
|
||||
|
||||
PromConsole.Graph.prototype.dispatch = function() {
|
||||
for (var j = 0; j < this._xhrs.length; j++) {
|
||||
this._xhrs[j].abort();
|
||||
}
|
||||
var all_data = new Array(this.params.expr.length);
|
||||
this._xhrs = new Array(this.params.expr.length);
|
||||
var pending_requests = this.params.expr.length;
|
||||
for (var i = 0; i < this.params.expr.length; ++i) {
|
||||
var endTime = this.params.endTime;
|
||||
var url = PATH_PREFIX + "/api/query_range?expr=" + encodeURIComponent(this.params.expr[i])
|
||||
+ "&step=" + this.params.duration / this.graphTd.offsetWidth
|
||||
+ "&range=" + this.params.duration + "&end=" + endTime;
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('get', url, true);
|
||||
xhr.responseType = 'json';
|
||||
xhr.onerror = function(xhr, i) {
|
||||
this._clearGraph();
|
||||
var errorText = document.createElement("div");
|
||||
errorText.className = 'prom_graph_error';
|
||||
errorText.textContent = 'Error loading data';
|
||||
this.graphTd.appendChild(errorText);
|
||||
console.log('Error loading data for ' + this.params.expr[i]);
|
||||
pending_requests = 0;
|
||||
// onabort gets any aborts.
|
||||
for (var j = 0; j < pending_requests; j++) {
|
||||
this._xhrs[j].abort();
|
||||
}
|
||||
}.bind(this, xhr, i)
|
||||
xhr.onload = function(xhr, i) {
|
||||
if (pending_requests == 0) {
|
||||
// Got an error before this success.
|
||||
return;
|
||||
}
|
||||
var data = xhr.response;
|
||||
pending_requests -= 1;
|
||||
all_data[i] = data;
|
||||
if (pending_requests == 0) {
|
||||
this._xhrs = [];
|
||||
this._render(all_data);
|
||||
}
|
||||
}.bind(this, xhr, i)
|
||||
xhr.send();
|
||||
this._xhrs[i] = xhr;
|
||||
}
|
||||
|
||||
var loadingImg = document.createElement("img");
|
||||
loadingImg.src = PATH_PREFIX + '/static/img/ajax-loader.gif';
|
||||
loadingImg.alt = 'Loading...';
|
||||
loadingImg.className = 'prom_graph_loading';
|
||||
this.graphTd.appendChild(loadingImg);
|
||||
};
|
||||
|
||||
// Substitute the value of 'label' for [[ label ]].
|
||||
PromConsole._interpolateName = function(name, metric) {
|
||||
var re = /(.*?)\[\[\s*(\w+)+\s*\]\](.*?)/g;
|
||||
var result = '';
|
||||
while (match = re.exec(name)) {
|
||||
result = result + match[1] + metric[match[2]] + match[3]
|
||||
}
|
||||
if (!result) {
|
||||
return name;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Given the data returned by the API, return an appropriate function
|
||||
// to return plot names.
|
||||
PromConsole._chooseNameFunction = function(data) {
|
||||
// By default, use the full metric name.
|
||||
var nameFunc = function (metric) {
|
||||
name = metric.__name__ + "{";
|
||||
for (var label in metric) {
|
||||
if (label.substring(0,2) == "__") {
|
||||
continue;
|
||||
}
|
||||
name += label + "='" + metric[label] + "',";
|
||||
}
|
||||
return name + "}";
|
||||
}
|
||||
// If only one label varies, use that value.
|
||||
var labelValues = {};
|
||||
for (var e = 0; e < data.length; e++) {
|
||||
for (var i = 0; i < data[e].value.length; i++) {
|
||||
for (var label in data[e].value[i].metric) {
|
||||
if (!(label in labelValues)) {
|
||||
labelValues[label] = {};
|
||||
}
|
||||
labelValues[label][data[e].value[i].metric[label]] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
var multiValueLabels = [];
|
||||
for (var label in labelValues) {
|
||||
if (Object.keys(labelValues[label]).length > 1) {
|
||||
multiValueLabels.push(label);
|
||||
}
|
||||
}
|
||||
if (multiValueLabels.length == 1) {
|
||||
nameFunc = function(metric) {
|
||||
return metric[multiValueLabels[0]];
|
||||
}
|
||||
}
|
||||
return nameFunc;
|
||||
}
|
||||
|
||||
|
||||
// Given a list of expressions, produce the /graph url for them.
|
||||
PromConsole._graphsToSlashGraphURL = function(exprs) {
|
||||
var data = [];
|
||||
for (var i = 0; i < exprs.length; ++i) {
|
||||
data.push({'expr': exprs[i], 'tab': 0});
|
||||
}
|
||||
return PATH_PREFIX + '/graph#' + encodeURIComponent(JSON.stringify(data));
|
||||
|
||||
};
|
Reference in New Issue
Block a user