Skip to content

Instantly share code, notes, and snippets.

@dornatsky
Created November 3, 2014 18:44
Show Gist options
  • Save dornatsky/dd9d8aac58f666042e07 to your computer and use it in GitHub Desktop.
Save dornatsky/dd9d8aac58f666042e07 to your computer and use it in GitHub Desktop.
(function(){
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
}
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function (str){
return this.slice(this.length - str.length, this.length) == str;
};
}
if (typeof String.prototype.capitalize != 'function') {
String.prototype.capitalize = function() {
if (this.indexOf('-') > 0 && this.indexOf('-') < 4 || this.length < 3) { //Maybe remove?
return this.substring(0, 3).toUpperCase() + this.slice(3);
} else {
return this.charAt(0).toUpperCase() + this.slice(1);
}
};
}
if (typeof Array.prototype.scan != 'function') {
Array.prototype.scan = function (fn) {
var value = true;
for (var i = 0; i < this.length; i++) {
value = value && fn(this[i]);
};
return value;
};
}
function toArray(obj) { return (typeof obj == "string" ? [ obj ] : obj) }
// Given the return value and user value should return widget to display it or null.
function expressRouter(property, location, instance){
var progressPattern = /^progress:(\d+)\/(\d+)\/(\d+)\/(\d+)$/
var urlPattern = /^http/
var ipPattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
var passPattern = /password|key|secret|credential/i
var testIp = function(ip) { return ipPattern.test(ip) }
var testHttp = function(url) { return urlPattern.test(url) }
var testPass = function(id) { return passPattern.test(id) }
var id = property.path[0];
var value = String(property.runtimeValue);
var raw = property.runtimeValue;
var isString = typeof raw == 'string';
var curName = _.last(property.path);
if(id.startsWith('frame.') && isString && value.startsWith('https') && location == 'instance') return Frame
else if(id.toLowerCase().startsWith('chart.') && isString && progressPattern.test(value.trim())) return Pie
else if(property.path[0].endsWith('-rpms-list')) return RPMList
//else if(Array.isArray(raw) && raw.scan(testIp)) return Compute
else if(isString && testIp(raw)) return Compute
else if(id.endsWith('-dns')) return Compute
else if(id.endsWith('-pdns')) return Compute
else if(isString && testHttp(value)) return Link
else if(passPattern.test(id) || passPattern.test(curName)) return HideThePassword
else if(id.endsWith('-pic') && raw.large && raw.small) return Picture
else if(_.isObject(raw) && !_.isArray(raw) && location == 'instance-dashboard') return HideValue
}
app.widgets.registerWidgetRouter(expressRouter);
// Hack. Replaced function
app.widgets.makeExpandable = function(type, cnt, $content) {
$content.find('tr').hide();
var $td = $('<td class="exp-show-link"><a style="cursor:pointer">[ +' + (cnt - 1) + ' more ]</a></td>');
$content.find('tr:first').show().append($td);
$content.find('td,th').css('border-bottom', 'none');
$td.find('a').on('click', function() {
$content.find('tr').show();
$content.find('td.exp-show-link').hide();
});
return $content;
}
function RPMList(property, location, instance) {
if (location == 'instance') {
var rpms = property.runtimeValue
var rpmPattern = /^(.+)\-(.+)\-(\d+)(?:\.(.+))?(?:\.(.+))?$/
var buff = []
buff.push("<div style='font-size: small' onclick='this.find('span.fa').toggleClass(\"fa-chevron-left fa-chevron-down\"); this.next().toggle()>" +
"Tracking " + rpms.length + " package(s)" +
"<span class='fa fa-chevron-down' style='font-size: x-small; float: right'> </span>" +
"</div><table style='display: none; font-size: small'><tr style='color: #999'><th>Name</th><th>Version</th><th>Release</th><th>Arch</th></tr>")
for(var i = 0; i < rpms.length; i++){
var rpm = rpms[i]
var groups = rpmPattern.exec(rpm)
console.log(groups)
if(groups)
buff.push(
"<tr><td>" + groups[1] + "</td><td>" + groups[2] + "</td><td>" + groups[3] + "</td><td>" + (groups[4] == undefined ? 'N/A' : groups[4]) + "</td></tr>"
)
else
buff.push("<tr><td colspan='4'>" + rpm + "</td></tr>")
}
buff.push("</table>")
$(this).html(buff.join(" "))
} else {
var rpms = property.runtimeValue
var retval = "Tracking " + rpms.length + " package(s)"
$(this).html(retval)
}
}
function Compute(property, location, instance) {
var icon = "cloud";
switch(property.path[0]) {
case "db-hosts": icon = "columns"; break;
case "app-hosts": icon = "th"; break;
case "lb-hosts": icon = "arrows-alt"; break;
}
var ips = toArray(property.runtimeValue);
if (location == 'instance') {
if(ips.length > 1) {
var table = $("<table class='property-table'><tr><td style='border-bottom:0'><i class='widget-compute fa fa-" + icon + "' style='color: #999;'></i>&nbsp;" + ips[0] + "&nbsp;</td></tr></table>");
for(var i = 1; i < ips.length; i++) {
table.append(
$("<tr style='display:none'><td style='border-bottom:0'><i class='widget-compute fa fa-" + icon + "' style='color: #999;'></i>&nbsp;" + ips[i] + "</td></tr>")
)
}
var link = $("<a>[ +" + (ips.length - 1) + " more ]</a>").css('cursor', 'pointer');
link.on('click', function() {
link.hide();
table.find('tr:hidden').show()
});
table.find('td:first').append(link);
$(this).empty().append(table);
}
else {
$(this).html(
"<i class='widget-compute fa fa-" + icon + "' style='color: #999;'></i> " + ips[0]
)
}
} else {
if (ips.length > 0) {
$(this).html(
"<i class='widget-compute fa fa-" + icon + "' style='float: right; color: #999;'></i>" +
(ips.length == 1 ? ips[0] : "[ " + ips.length + " IP's ]")
)
}
}
}
function Link(property, location, instance) {
var name = property.description || property.path.join('.');
if (location.indexOf('instance') >= 0) {
var $link = $('<a/>').attr({'href': property.runtimeValue, 'target': '_blank'}).text(name);
$(this).empty().html($link);
}
}
function size(table) {
var size = 0, key;
for (key in table) {
if (table.hasOwnProperty(key)) size++;
}
return size;
};
function StackChart(property, location, instance) {
if (location == 'instance') {
var progressList = property.runtimeValue || []
var rawData = [["Index", "Pass", "Ignore", "Fail", "Unknown"]]
for (var i=0; i<progressList.length; i++){
var text = progressList[i]
var all, green, progress, red, res, rest, urlPattern, yellow;
urlPattern = /^progress:(\d+)\/(\d+)\/(\d+)\/(\d+)$/;
progress = text.trim();
if (urlPattern.test(progress)) {
res = progress.match(urlPattern);
all = res[1] * 1;
green = res[2] * 1;
yellow = res[3] * 1;
red = res[4] * 1;
rest = all - (green + yellow + red);
if (all === 0) {
console.log("Sum is zero: " + progress);
continue;
} else if (all < green + yellow + red) {
console.log("Sum is zero: " + progress);
continue;
} else {
rawData.push([i.toString(), green, yellow, red, rest])
}
}
else {
console.log("Is not progress info: " + progress);
}
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawStackChart);
function drawStackChart() {
var data = google.visualization.arrayToDataTable(rawData)
var options = {
legend: 'none',
isStacked: true,
colors: ['green','yellow','red','blue'],
pointSize: 3
};
var chart = new google.visualization.AreaChart(document.getElementById('stackchart'+returnValue.id));
chart.draw(data, options);
}
$(this).attr('id', "stackchart" + returnValue.id);
} else {
$(this).empty(); //not rendered
}
}
function Frame(property, location, instance) {
//layout : 'block',
var url = property.runtimeValue;
$(this).empty().append("<iframe height='500' width='100%' src='"+url+"'><p>Your browser does not support iframes.</p></iframe>");
}
function Pie(property, location, instance) {
var all, green, progress, red, res, rest, yellow;
var returnValue = property.runtimeValue;
var urlPattern = /^progress:(\d+)\/(\d+)\/(\d+)\/(\d+)$/;
progress = property.runtimeValue.trim();
res = progress.match(urlPattern);
all = res[1] * 1;
green = res[2] * 1;
yellow = res[3] * 1;
red = res[4] * 1;
rest = all - (green + yellow + red);
if (all === 0) {
$(this).html("<span class=\"badge badge-important\">Sum is zero</span> " + progress);
} else if (all < green + yellow + red) {
$(this).html("<span class=\"badge badge-warning\">Sum is too small</span> " + progress);
} else {
$(this).html("<div style=\"white-space: normal\" class=\"progress\" data=\"" + progress + "\">\n<div class=\"bar bar-success\" style=\"width: " + (green / all * 100) + "%;\">" + green + "</div>\n<div class=\"bar bar-warning\" style=\"width: " + (yellow / all * 100) + "%;\">" + yellow + "</div>\n<div class=\"bar bar-danger\" style=\"width: " + (red / all * 100) + "%;\">" + red + "</div>\n<div class=\"bar bar-info\" style=\"width: " + (rest / all * 100) + "%;\">" + rest + "</div>\n</div>");
}
}
/*
chart: function(returnValue) {
var text = property.runtimeValue;
var all, green, progress, red, res, rest, urlPattern, yellow;
urlPattern = /^progress:(\d+)\/(\d+)\/(\d+)\/(\d+)$/;
progress = text.trim();
console.log("Progress: '" + progress + "'");
if (urlPattern.test(progress)) {
res = progress.match(urlPattern);
all = res[1] * 1;
green = res[2] * 1;
yellow = res[3] * 1;
red = res[4] * 1;
rest = all - (green + yellow + red);
if (all === 0) {
return "<span class=\"badge badge-important\">Sum is zero</span> " + progress;
} else if (all < green + yellow + red) {
return "<span class=\"badge badge-warning\">Sum is too small</span> " + progress;
} else {
//see https://developers.google.com/chart/interactive/docs/gallery/piechart
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Test Results', 'Tests count'],
['Pass', green],
['Ignore', yellow],
['Fail', red],
['Unknown', rest]
]);
var options = {
legend: 'none',
is3D: true,
colors: ['green','yellow','red','blue']
};
var gchart = new google.visualization.PieChart(document.getElementById('piechart_'+returnValue.id));
gchart.draw(data, options);
}
return "<div id=\"piechart_"+returnValue.id+"\" ></div>";
}
} else {
return text;
}
}
*/
function HideThePassword(property, location, instance) {
var pass = property.runtimeValue;
var span = $('<span style="display: inline-block; min-width: 85px; margin-right: 10px;"/>');
var checkbox = $('<label style="display:inline-block"><input type="checkbox"> show password</label>');
function updateValue(state) {
if (state) {
span.text(pass);
} else {
span.text('•••••••••••••••••'.substr(0, pass.length))
}
}
var state = $(this).data('currentState') || false
checkbox.find('input').prop('checked', state);
updateValue(state);
checkbox.on('click', 'input', function(e) {
$(this).data('currentState', this.checked);
updateValue(this.checked);
});
$(this).append(span).append(checkbox);
}
// Display properties like `*-pic: {"large": "url1", "small": "url2"}` as image
function Picture(property, location, instance) {
var src;
var img = $('<img alt="">');
if (location == 'instance') {
src = property.runtimeValue.large;
} else {
src = property.runtimeValue.small;
$(this).css('text-align', 'center');
img.attr('height', property.runtimeValue['small-height'] || 200);
}
$(this).empty().append(img.attr('src', src));
}
function HideValue(property, location, instance) {
// Nothing to display
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment