From f377dfd9b629e3203b8a498d9108ed9d310d22ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn?= Date: Wed, 30 Apr 2014 10:50:07 +0200 Subject: [PATCH 01/18] Feature #1607: New methods to get raw accounting data in sunstone --- src/sunstone/models/SunstoneServer.rb | 24 ++++++++++++++++++++ src/sunstone/public/js/opennebula.js | 32 +++++++++++++++++++++++++-- src/sunstone/sunstone-server.rb | 11 ++++++++- 3 files changed, 64 insertions(+), 3 deletions(-) diff --git a/src/sunstone/models/SunstoneServer.rb b/src/sunstone/models/SunstoneServer.rb index 35f2fb58d1..7f58338377 100644 --- a/src/sunstone/models/SunstoneServer.rb +++ b/src/sunstone/models/SunstoneServer.rb @@ -368,6 +368,30 @@ class SunstoneServer < CloudServer return [200, {:monitoring => result}.to_json] end + def get_vm_accounting(options) + pool = VirtualMachinePool.new(@client) + + filter_flag = options[:userfilter] ? options[:userfilter].to_i : VirtualMachinePool::INFO_ALL + start_time = options[:start_time] ? options[:start_time].to_i : -1 + end_time = options[:end_time] ? options[:end_time].to_i : -1 + + acct_options = { + :start_time => start_time, + :end_time => end_time, + :group => options[:group] + } + + rc = pool.accounting(filter_flag, acct_options) + + if OpenNebula.is_error?(rc) + error = Error.new(rc.message) + return [500, error.to_json] + end + + return [200, rc.to_json] + end + + private ############################################################################ diff --git a/src/sunstone/public/js/opennebula.js b/src/sunstone/public/js/opennebula.js index 1bbacca82d..b23ea72645 100644 --- a/src/sunstone/public/js/opennebula.js +++ b/src/sunstone/public/js/opennebula.js @@ -595,7 +595,32 @@ var OpenNebula = { callback_error(request, OpenNebula.Error(response)) : null; } }); - } + }, + + "accounting": function(params, resource, path){ + var callback = params.success; + var callback_error = params.error; + var data = params.data; + + var method = "accounting"; + var request = OpenNebula.Helper.request(resource,method, data); + + var url = path ? path : resource.toLowerCase() + "/accounting"; + + $.ajax({ + url: url, + type: "GET", + data: data, + dataType: "json", + success: function(response){ + return callback ? callback(request, response) : null; + }, + error: function(response){ + return callback_error ? + callback_error(request, OpenNebula.Error(response)) : null; + } + }); + }, }, "Auth": { @@ -984,7 +1009,10 @@ var OpenNebula = { "recover" : function(params){ var action_obj = {"with": params.data.extra_param}; OpenNebula.Action.simple_action(params,OpenNebula.VM.resource,"recover",action_obj); - } + }, + "accounting": function(params){ + OpenNebula.Action.accounting(params,OpenNebula.VM.resource); + }, }, "Group": { diff --git a/src/sunstone/sunstone-server.rb b/src/sunstone/sunstone-server.rb index 0fb6c07e8e..b4a54af27f 100755 --- a/src/sunstone/sunstone-server.rb +++ b/src/sunstone/sunstone-server.rb @@ -374,7 +374,7 @@ get '/vm/:id/log' do end ############################################################################## -# Accounting & Monitoring +# Monitoring ############################################################################## get '/:resource/monitor' do @@ -399,6 +399,15 @@ get '/:resource/:id/monitor' do params[:monitor_resources]) end +############################################################################## +# Accounting +############################################################################## + +get '/vm/accounting' do + @SunstoneServer.get_vm_accounting(params) +end + + ############################################################################## # Marketplace ############################################################################## From 2487c4f1eabf9e8c517ee365462ca74991943ab8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn?= Date: Wed, 30 Apr 2014 16:02:19 +0200 Subject: [PATCH 02/18] Feature #1607: Add accounting tab to user and group resources --- install.sh | 1 + src/sunstone/public/js/plugins/groups-tab.js | 12 + src/sunstone/public/js/plugins/users-tab.js | 13 + src/sunstone/public/js/sunstone.js | 475 ++++++++++++++++++ .../vendor/flot/jquery.flot.tooltip.min.js | 12 + src/sunstone/views/index.erb | 1 + 6 files changed, 514 insertions(+) create mode 100644 src/sunstone/public/vendor/flot/jquery.flot.tooltip.min.js diff --git a/install.sh b/install.sh index 681c236228..6fbec3466f 100755 --- a/install.sh +++ b/install.sh @@ -1497,6 +1497,7 @@ src/sunstone/public/vendor/flot/jquery.flot.navigate.min.js \ src/sunstone/public/vendor/flot/jquery.flot.pie.min.js \ src/sunstone/public/vendor/flot/jquery.flot.resize.min.js \ src/sunstone/public/vendor/flot/jquery.flot.stack.min.js \ +src/sunstone/public/vendor/flot/jquery.flot.tooltip.min.js \ src/sunstone/public/vendor/flot/LICENSE.txt \ src/sunstone/public/vendor/flot/NOTICE" diff --git a/src/sunstone/public/js/plugins/groups-tab.js b/src/sunstone/public/js/plugins/groups-tab.js index 9c35733922..b35598601f 100644 --- a/src/sunstone/public/js/plugins/groups-tab.js +++ b/src/sunstone/public/js/plugins/groups-tab.js @@ -703,9 +703,16 @@ function updateGroupInfo(request,group){ ' }; + var accounting_tab = { + title: tr("Accounting"), + icon: "fa-bar-chart-o", + content: '
' + }; + Sunstone.updateInfoPanelTab("group_info_panel","group_info_tab",info_tab); Sunstone.updateInfoPanelTab("group_info_panel","group_quotas_tab",quotas_tab); Sunstone.updateInfoPanelTab("group_info_panel","group_providers_tab",providers_tab); + Sunstone.updateInfoPanelTab("group_info_panel","group_accouning_tab",accounting_tab); Sunstone.popUpInfoPanel("group_info_panel", 'groups-tab'); $("#add_rp_button", $("#group_info_panel")).click(function(){ @@ -715,6 +722,11 @@ function updateGroupInfo(request,group){ return false; }); + + accountingGraphs( + $("#group_accounting","#group_info_panel"), + { fixed_group: info.ID, + init_group_by: "user" }); } function setup_group_resource_tab_content(zone_id, zone_section, str_zone_tab_id, str_datatable_id, selected_group_clusters, group) { diff --git a/src/sunstone/public/js/plugins/users-tab.js b/src/sunstone/public/js/plugins/users-tab.js index 98c98aeebe..f835e49dcb 100644 --- a/src/sunstone/public/js/plugins/users-tab.js +++ b/src/sunstone/public/js/plugins/users-tab.js @@ -715,10 +715,23 @@ function updateUserInfo(request,user){ content : quotas_html }; + var accounting_tab = { + title: tr("Accounting"), + icon: "fa-bar-chart-o", + content: '
' + }; + Sunstone.updateInfoPanelTab("user_info_panel","user_info_tab",info_tab); Sunstone.updateInfoPanelTab("user_info_panel","user_quotas_tab",quotas_tab); + Sunstone.updateInfoPanelTab("user_info_panel","user_accouning_tab",accounting_tab); //Sunstone.updateInfoPanelTab("user_info_panel","user_acct_tab",acct_tab); Sunstone.popUpInfoPanel("user_info_panel", 'users-tab'); + + accountingGraphs( + $("#user_accounting","#user_info_panel"), + { fixed_user: info.ID, + init_group_by: "vm" }); + }; // Used also from groups-tabs.js diff --git a/src/sunstone/public/js/sunstone.js b/src/sunstone/public/js/sunstone.js index 21790d112e..f3104c4575 100644 --- a/src/sunstone/public/js/sunstone.js +++ b/src/sunstone/public/js/sunstone.js @@ -3902,3 +3902,478 @@ $(document).ready(function(){ } }) }); + +// div is a jQuery selector +// The following options can be set: +// fixed_user fix an owner user ID +// fixed_group fix an owner group ID +// init_group_by "user", "group", "vm". init the group-by selector +function accountingGraphs(div, opt){ + div.append( + '
\ +
\ + '+tr("Time range")+'\ +
\ +
\ + \ +
\ +
\ + \ +
\ +
\ +
\ +
\ + \ + \ + \ +
\ +
\ +
\ +
\ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ + \ +
\ +
\ +
\ +

'+tr("CPU hours")+'

\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +

'+tr("Memory GB hours")+'

\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
'); + + if (opt == undefined){ + opt = {}; + } + + //-------------------------------------------------------------------------- + // Init start time to 1st of last month + //-------------------------------------------------------------------------- + var d = new Date(); + + d.setDate(1); + d.setMonth(d.getMonth() - 1); + + $("#acct_start_time", div).val(d.getFullYear() + '/' + (d.getMonth()+1) + '/' + d.getDate()); + + $("#acct_start_time", div).jdPicker(); + $("#acct_end_time", div).jdPicker(); + + //-------------------------------------------------------------------------- + // VM owner: all, group, user + //-------------------------------------------------------------------------- + + if (opt.fixed_user != undefined || opt.fixed_group != undefined){ + $("input[name='acct_owner']", div).attr("disabled", "disabled"); + + $("#acct_owner_select", div).show(); + + if(opt.fixed_user != undefined){ + var text = tr("User") +" " + opt.fixed_user; + $("input[value='acct_owner_user']", div).attr("checked", "checked"); + } else { + var text = tr("Group") + " " + opt.fixed_group; + $("input[value='acct_owner_group']", div).attr("checked", "checked"); + } + + $("#acct_owner_select", div).text(text); + } else { + $("input[name='acct_owner']", div).change(function(){ + var value = $(this).val(); + + switch (value){ + case "acct_owner_all": + $("#acct_owner_select", div).hide(); + break; + + case "acct_owner_group": + $("#acct_owner_select", div).show(); + insertSelectOptions("#acct_owner_select", div, "Group"); + break; + + case "acct_owner_user": + $("#acct_owner_select", div).show(); + insertSelectOptions("#acct_owner_select", div, "User", -1, false, + ''); + break; + } + }); + } + + //-------------------------------------------------------------------------- + // Init group by select + //-------------------------------------------------------------------------- + + if(opt.init_group_by != undefined){ + $("#acct_group_by", div).val(opt.init_group_by); + } + + //-------------------------------------------------------------------------- + // Submit request + //-------------------------------------------------------------------------- + + // TODO: make start_time mandatory + + $("#acct_submit", div).on("click", function(){ + var start_time = -1; + var end_time = -1; + + var v = $("#acct_start_time", div).val(); + if (v != ""){ + start_time = new Date(v).getTime() / 1000; + } + + var v = $("#acct_end_time", div).val(); + if (v != ""){ + end_time = new Date(v).getTime() / 1000; + } + + var options = { + "start_time": start_time, + "end_time": end_time + }; + + if (opt.fixed_user != undefined){ + options.userfilter = opt.fixed_user; + } else if (opt.fixed_group != undefined){ + options.group = opt.fixed_group; + } else { + var select_val = $("#acct_owner_select .resource_list_select", div).val(); + + switch ($("input[name='acct_owner']:checked", div).val()){ + case "acct_owner_all": + break; + + case "acct_owner_group": + if(select_val != ""){ + options.group = select_val; + } + break; + + case "acct_owner_user": + if(select_val != ""){ + options.userfilter = select_val; + } + break; + } + } + + OpenNebula.VM.accounting({ + // timeout: true, + success: function(req, response){ + fillAccounting(div, req, response); + }, + error: onError, + data: options + }); + }); +} + +function fillAccounting(div, req, response) { +/* + console.log(req); + console.log(response); +*/ + + +/* +TODO More options: + +Granularity: month, day, hour +Time range +Group by: user, group, vm, [flow] +Filter by: user, group, vm, [flow] + +Download csv +*/ + + var options = req.request.data[0]; + + //-------------------------------------------------------------------------- + // Time slots + //-------------------------------------------------------------------------- + + // start_time is mandatory + var start = new Date(options.start_time * 1000); + + var end = new Date(); + + if(options.end_time != undefined && options.end_time != -1){ + var end = new Date(options.end_time * 1000) + } + + // granularity of 1 day + var times = []; + + var tmp_time = start; + + // End time is the start of the last time slot. We use <=, to + // add one extra time step + while (tmp_time <= end) { + times.push(tmp_time.getTime()); + + // day += 1 + tmp_time.setDate( tmp_time.getDate() + 1 ); + } + + //-------------------------------------------------------------------------- + // Flot options + //-------------------------------------------------------------------------- + + var options = { +// colors: [ "#2ba6cb", "#707D85", "#AC5A62" ], + + xaxis : { + mode: "time", + timeformat: "%y/%m/%d", + min: times[0], + max: end.getTime(), + color: "#999", + size: 8 + }, + yaxis : { labelWidth: 50, + min: 0, + color: "#999", + size: 8 + }, + series: { + bars: { + show: true, + lineWidth: 1, + fill: true, + barWidth: 24*60*60*1000 * 0.8, + align: "center" + }, + stack: true + }, + legend : { + show : true, + noColumns: 6, + container: $("#acct_legend", div) + }, + grid: { + borderWidth: 1, + borderColor: "#cfcfcf", + hoverable: true + }, + tooltip: true, + tooltipOpts: { + content: "%x | %s | %y" //"%s | X: %x | Y: %y" +/* + xDateFormat: string //null + yDateFormat: string //null + monthNames: string // null + dayNames: string // null + shifts: { + x: int //10 + y: int //20 + }, + defaultTheme: boolean //true + onHover: function(flotItem, $tooltipEl) +*/ + } + }; + + //-------------------------------------------------------------------------- + // Group by + //-------------------------------------------------------------------------- + + // TODO: Allow to change group by dynamically, instead of calling oned again + + switch ($("#acct_group_by", div).val()){ + case "user": + var group_by_fn = function(history){ + return history.VM.UID; + } + + var group_by_prefix = tr("User")+" "; + + break; + + case "group": + var group_by_fn = function(history){ + return history.VM.GID; + } + + var group_by_prefix = tr("Group")+" "; + + break; + + case "vm": + var group_by_fn = function(history){ + return history.OID; + } + + var group_by_prefix = tr("VM")+" "; + + break; + } + + //-------------------------------------------------------------------------- + // Filter history entries + //-------------------------------------------------------------------------- + + // TODO filter + // True to proccess, false to discard + var filter_by_fn = function(history){ +// return history.OID == 3605 || history.OID == 2673; + return true; + } + + //-------------------------------------------------------------------------- + // Process data series for flot + //-------------------------------------------------------------------------- + + var series = {}; + series.CPU_HOURS = {}; + series.MEM_HOURS = {}; + + // TODO: response can be an empty object + + $.each(response.HISTORY_RECORDS.HISTORY, function(index, history){ + + if(!filter_by_fn(history)){ + return true; //continue + } + + var group_by = group_by_fn(history); + + if (series.CPU_HOURS[group_by] == undefined){ + series.CPU_HOURS[group_by] = {}; + } + + if (series.MEM_HOURS[group_by] == undefined){ + series.MEM_HOURS[group_by] = {}; + } + +// TODO Optimize getting here? +// var serie = series.CPU_HOURS[history.VM.UID]; + + for (var i = 0; i t || history.ETIME == 0) && + (history.STIME != 0 && history.STIME*1000 <= t_next) ) { + + var stime = t; + if(history.STIME != 0){ + stime = Math.max(t, history.STIME*1000); + } + + var etime = t_next; + if(history.ETIME != 0){ + etime = Math.min(t_next, history.ETIME*1000); + } + + var n_hours = (etime - stime) / 1000 / 60 / 60; + + // --- cpu --- + + // TODO cpu may not exist + var val = parseFloat(history.VM.TEMPLATE.CPU) * n_hours; + + var serie = series.CPU_HOURS[group_by]; + + if(serie[t] == undefined){ + serie[t] = 0; + } + + serie[t] += val; + + // --- mem --- + + // TODO memory may not exist. In GB + var val = parseInt(history.VM.TEMPLATE.MEMORY)/1024 * n_hours; + + var serie = series.MEM_HOURS[group_by]; + + if(serie[t] == undefined){ + serie[t] = 0; + } + + serie[t] += val; + } + } + }); + +// console.log(series); + + //-------------------------------------------------------------------------- + // Create series, draw plots + //-------------------------------------------------------------------------- + + // --- cpu --- + + var plot_series = []; + + $.each(series.CPU_HOURS, function(key, val){ + var data = []; + + $.each(val, function(time,num){ + data.push([parseInt(time),num]); + }); + + plot_series.push( + { + label: group_by_prefix+key, + data: data + }); + }); + + $.plot($("#acct_cpu_graph", div), plot_series, options); + + // --- mem --- + + var plot_series = []; + + $.each(series.MEM_HOURS, function(key, val){ + var data = []; + + $.each(val, function(time,num){ + data.push([parseInt(time),num]); + }); + + plot_series.push( + { + label: group_by_prefix+key, + data: data + }); + }); + + $.plot($("#acct_mem_graph", div), plot_series, options); +} \ No newline at end of file diff --git a/src/sunstone/public/vendor/flot/jquery.flot.tooltip.min.js b/src/sunstone/public/vendor/flot/jquery.flot.tooltip.min.js new file mode 100644 index 0000000000..8fdce4e4cb --- /dev/null +++ b/src/sunstone/public/vendor/flot/jquery.flot.tooltip.min.js @@ -0,0 +1,12 @@ +/* + * jquery.flot.tooltip + * + * description: easy-to-use tooltips for Flot charts + * version: 0.6.7 + * author: Krzysztof Urbas @krzysu [myviews.pl] + * website: https://github.com/krzysu/flot.tooltip + * + * build on 2014-03-26 + * released under MIT License, 2012 +*/ +Array.prototype.indexOf||(Array.prototype.indexOf=function(t,i){if(void 0===this||null===this)throw new TypeError('"this" is null or not defined');var e=this.length>>>0;for(i=+i||0,1/0===Math.abs(i)&&(i=0),0>i&&(i+=e,0>i&&(i=0));e>i;i++)if(this[i]===t)return i;return-1}),function(t){var i={tooltip:!1,tooltipOpts:{content:"%s | X: %x | Y: %y",xDateFormat:null,yDateFormat:null,monthNames:null,dayNames:null,shifts:{x:10,y:20},defaultTheme:!0,onHover:function(){}}},e=function(t){this.tipPosition={x:0,y:0},this.init(t)};e.prototype.init=function(i){function e(t){var i={};i.x=t.pageX,i.y=t.pageY,s.updateTooltipPosition(i)}function o(t,i,e){var o=s.getDomElement();if(e){var n;n=s.stringFormat(s.tooltipOptions.content,e),o.html(n),s.updateTooltipPosition({x:i.pageX,y:i.pageY}),o.css({left:s.tipPosition.x+s.tooltipOptions.shifts.x,top:s.tipPosition.y+s.tooltipOptions.shifts.y}).show(),"function"==typeof s.tooltipOptions.onHover&&s.tooltipOptions.onHover(e,o)}else o.hide().html("")}var s=this,n=t.plot.plugins.length;if(this.plotPlugins=[],n)for(var r=0;n>r;r++)this.plotPlugins.push(t.plot.plugins[r].name);i.hooks.bindEvents.push(function(i,n){s.plotOptions=i.getOptions(),s.plotOptions.tooltip!==!1&&void 0!==s.plotOptions.tooltip&&(s.tooltipOptions=s.plotOptions.tooltipOpts,s.getDomElement(),t(i.getPlaceholder()).bind("plothover",o),t(n).bind("mousemove",e))}),i.hooks.shutdown.push(function(i,s){t(i.getPlaceholder()).unbind("plothover",o),t(s).unbind("mousemove",e)})},e.prototype.getDomElement=function(){var i;return t("#flotTip").length>0?i=t("#flotTip"):(i=t("
").attr("id","flotTip"),i.appendTo("body").hide().css({position:"absolute"}),this.tooltipOptions.defaultTheme&&i.css({background:"#fff","z-index":"1040",padding:"0.4em 0.6em","border-radius":"0.5em","font-size":"0.8em",border:"1px solid #111",display:"none","white-space":"nowrap"})),i},e.prototype.updateTooltipPosition=function(i){var e=t("#flotTip").outerWidth()+this.tooltipOptions.shifts.x,o=t("#flotTip").outerHeight()+this.tooltipOptions.shifts.y;i.x-t(window).scrollLeft()>t(window).innerWidth()-e&&(i.x-=e),i.y-t(window).scrollTop()>t(window).innerHeight()-o&&(i.y-=o),this.tipPosition.x=i.x,this.tipPosition.y=i.y},e.prototype.stringFormat=function(t,i){var e,o,s=/%p\.{0,1}(\d{0,})/,n=/%s/,r=/%lx/,a=/%ly/,p=/%x\.{0,1}(\d{0,})/,l=/%y\.{0,1}(\d{0,})/,d="%x",h="%y";if(i.series.threshold!==void 0?(e=i.datapoint[0],o=i.datapoint[1]):(e=i.series.data[i.dataIndex][0],o=i.series.data[i.dataIndex][1]),null===i.series.label&&i.series.originSeries&&(i.series.label=i.series.originSeries.label),"function"==typeof t&&(t=t(i.series.label,e,o,i)),i.series.percent!==void 0&&(t=this.adjustValPrecision(s,t,i.series.percent)),t=i.series.label!==void 0?t.replace(n,i.series.label):t.replace(n,""),t=this.hasAxisLabel("xaxis",i)?t.replace(r,i.series.xaxis.options.axisLabel):t.replace(r,""),t=this.hasAxisLabel("yaxis",i)?t.replace(a,i.series.yaxis.options.axisLabel):t.replace(a,""),this.isTimeMode("xaxis",i)&&this.isXDateFormat(i)&&(t=t.replace(p,this.timestampToDate(e,this.tooltipOptions.xDateFormat))),this.isTimeMode("yaxis",i)&&this.isYDateFormat(i)&&(t=t.replace(l,this.timestampToDate(o,this.tooltipOptions.yDateFormat))),"number"==typeof e&&(t=this.adjustValPrecision(p,t,e)),"number"==typeof o&&(t=this.adjustValPrecision(l,t,o)),i.series.xaxis.ticks!==void 0){var u;u=this.hasRotatedXAxisTicks(i)?"rotatedTicks":"ticks";var x=i.dataIndex+i.seriesIndex;i.series.xaxis[u].length>x&&!this.isTimeMode("xaxis",i)&&(t=t.replace(p,i.series.xaxis[u][x].label))}if(i.series.yaxis.ticks!==void 0)for(var c in i.series.yaxis.ticks)if(i.series.yaxis.ticks.hasOwnProperty(c)){var m=this.isCategoriesMode("yaxis",i)?i.series.yaxis.ticks[c].label:i.series.yaxis.ticks[c].v;m===o&&(t=t.replace(l,i.series.yaxis.ticks[c].label))}return i.series.xaxis.tickFormatter!==void 0&&(t=t.replace(d,i.series.xaxis.tickFormatter(e,i.series.xaxis).replace(/\$/g,"$$"))),i.series.yaxis.tickFormatter!==void 0&&(t=t.replace(h,i.series.yaxis.tickFormatter(o,i.series.yaxis).replace(/\$/g,"$$"))),t},e.prototype.isTimeMode=function(t,i){return i.series[t].options.mode!==void 0&&"time"===i.series[t].options.mode},e.prototype.isXDateFormat=function(){return this.tooltipOptions.xDateFormat!==void 0&&null!==this.tooltipOptions.xDateFormat},e.prototype.isYDateFormat=function(){return this.tooltipOptions.yDateFormat!==void 0&&null!==this.tooltipOptions.yDateFormat},e.prototype.isCategoriesMode=function(t,i){return i.series[t].options.mode!==void 0&&"categories"===i.series[t].options.mode},e.prototype.timestampToDate=function(i,e){var o=new Date(1*i);return t.plot.formatDate(o,e,this.tooltipOptions.monthNames,this.tooltipOptions.dayNames)},e.prototype.adjustValPrecision=function(t,i,e){var o,s=i.match(t);return null!==s&&""!==RegExp.$1&&(o=RegExp.$1,e=e.toFixed(o),i=i.replace(t,e)),i},e.prototype.hasAxisLabel=function(t,i){return-1!==this.plotPlugins.indexOf("axisLabels")&&i.series[t].options.axisLabel!==void 0&&i.series[t].options.axisLabel.length>0},e.prototype.hasRotatedXAxisTicks=function(i){return 1===t.grep(t.plot.plugins,function(t){return"tickRotor"===t.name}).length&&i.series.xaxis.rotatedTicks!==void 0};var o=function(t){new e(t)};t.plot.plugins.push({init:o,options:i,name:"tooltip",version:"0.6.7"})}(jQuery); \ No newline at end of file diff --git a/src/sunstone/views/index.erb b/src/sunstone/views/index.erb index 315026cf98..6f084a53bf 100644 --- a/src/sunstone/views/index.erb +++ b/src/sunstone/views/index.erb @@ -13,6 +13,7 @@ + From b4809b327914f0944b564cd9e7eea33b3e21adb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn?= Date: Wed, 30 Apr 2014 16:49:28 +0200 Subject: [PATCH 03/18] Feature #1607: better x axis min, max --- src/sunstone/public/js/sunstone.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/sunstone/public/js/sunstone.js b/src/sunstone/public/js/sunstone.js index f3104c4575..04a1d78aab 100644 --- a/src/sunstone/public/js/sunstone.js +++ b/src/sunstone/public/js/sunstone.js @@ -4159,8 +4159,6 @@ Download csv xaxis : { mode: "time", timeformat: "%y/%m/%d", - min: times[0], - max: end.getTime(), color: "#999", size: 8 }, @@ -4273,10 +4271,16 @@ Download csv if (series.CPU_HOURS[group_by] == undefined){ series.CPU_HOURS[group_by] = {}; + + series.CPU_HOURS[group_by][times[0]] = 0; + series.CPU_HOURS[group_by][times[times.length-2]] = 0; } if (series.MEM_HOURS[group_by] == undefined){ series.MEM_HOURS[group_by] = {}; + + series.MEM_HOURS[group_by][times[0]] = 0; + series.MEM_HOURS[group_by][times[times.length-2]] = 0; } // TODO Optimize getting here? From 0d28333456dc177ba78cfa3d6d8a6e303f897aae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn?= Date: Mon, 5 May 2014 17:18:44 +0200 Subject: [PATCH 04/18] Feature #1607: Add activity gantt chart --- install.sh | 2 + src/sunstone/public/js/sunstone.js | 107 +++- .../public/vendor/flot/jquery.flot.JUMlib.js | 520 ++++++++++++++++++ .../public/vendor/flot/jquery.flot.gantt.js | 201 +++++++ src/sunstone/views/index.erb | 2 + 5 files changed, 831 insertions(+), 1 deletion(-) create mode 100644 src/sunstone/public/vendor/flot/jquery.flot.JUMlib.js create mode 100644 src/sunstone/public/vendor/flot/jquery.flot.gantt.js diff --git a/install.sh b/install.sh index 6fbec3466f..1bdb5464c0 100755 --- a/install.sh +++ b/install.sh @@ -1498,6 +1498,8 @@ src/sunstone/public/vendor/flot/jquery.flot.pie.min.js \ src/sunstone/public/vendor/flot/jquery.flot.resize.min.js \ src/sunstone/public/vendor/flot/jquery.flot.stack.min.js \ src/sunstone/public/vendor/flot/jquery.flot.tooltip.min.js \ +src/sunstone/public/vendor/flot/jquery.flot.JUMlib.min.js \ +src/sunstone/public/vendor/flot/jquery.flot.gantt.min.js \ src/sunstone/public/vendor/flot/LICENSE.txt \ src/sunstone/public/vendor/flot/NOTICE" diff --git a/src/sunstone/public/js/sunstone.js b/src/sunstone/public/js/sunstone.js index 04a1d78aab..1ee7926d6a 100644 --- a/src/sunstone/public/js/sunstone.js +++ b/src/sunstone/public/js/sunstone.js @@ -3944,6 +3944,19 @@ function accountingGraphs(div, opt){
\ \
\ +
\ +
\ +

'+tr("Activity")+'

\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\
\
\

'+tr("CPU hours")+'

\ @@ -4379,5 +4392,97 @@ Download csv }); }); - $.plot($("#acct_mem_graph", div), plot_series, options); + var mem_plot = $.plot($("#acct_mem_graph", div), plot_series, options); + + // --- activity --- + + // TODO: refactor inefficient code + + series.GANTT = {}; + + var group_by_index = {}; + var group_by_rev_index = {}; + + var index = 0; + + $.each(response.HISTORY_RECORDS.HISTORY, function(index, history){ + + if(!filter_by_fn(history)){ + return true; //continue + } + + if(history.STIME == 0){ + return true; + } + + var group_by = group_by_fn(history); + + if(group_by_index[group_by] == undefined){ + group_by_index[group_by] = index; + group_by_rev_index[index] = group_by; + index++; + } + + var group_by_i = group_by_index[group_by]; + + if (series.GANTT[group_by_i] == undefined){ + series.GANTT[group_by_i] = []; + } + + var gantt_start = parseInt(history.STIME)*1000; + if(gantt_start < times[0]){ + gantt_start = times[0]; + } + + var gantt_end = parseInt(history.ETIME)*1000; + if(gantt_end == 0){ + gantt_end = times[times.length - 2]; + } + + var serie = series.GANTT[group_by_i]; + serie.push([ + gantt_start, // Start of Step + group_by_i, // number of resource + gantt_end, // End of step + "" // Name for step (used for tooltip) + ]); + }); + + + var plot_series = []; + var ticks = []; + + $.each(series.GANTT, function(key, val){ + data = val; + + var name = group_by_prefix+group_by_rev_index[key]; + + plot_series.push( + { + label: name, + data: data, + }); + + ticks.push([parseInt(key), name]); + }); + + options.series = { + gantt : { + active : true, + show : true, + barHeight : 1.0 + } + }; + + options.yaxis.ticks = ticks; + options.yaxis.min = -0.5; + options.yaxis.max = plot_series.length - 0.5; + + var plot_data = mem_plot.getData(); + if(plot_data.length != 0){ + options.xaxis.min = plot_data[0].xaxis.min; + options.xaxis.max = plot_data[0].xaxis.max; + } + + $.plot($("#acct_activity_graph", div), plot_series, options); } \ No newline at end of file diff --git a/src/sunstone/public/vendor/flot/jquery.flot.JUMlib.js b/src/sunstone/public/vendor/flot/jquery.flot.JUMlib.js new file mode 100644 index 0000000000..4c619d6950 --- /dev/null +++ b/src/sunstone/public/vendor/flot/jquery.flot.JUMlib.js @@ -0,0 +1,520 @@ +/* + * The MIT License + +Copyright (c) 2012, 2013 by Juergen Marsch + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +(function ($) { + "use strict"; + var pluginName = "JUMlib", pluginVersion = "0.5"; + function between(v,limit1,limit2){ + if(limit2 > limit1){ return (v >= limit1 && v <= limit2); } + else{ return(v >=limit2 && v <= limit1); } + } + function getMinMax(data,dataIndex){ + var mn,mx,df,dI; + if(dataIndex){ dI = dataIndex} else{ dI = 1;} + mn = Number.POSITIVE_INFINITY; + mx = Number.NEGATIVE_INFINITY; + for(var i = 0; i < data.length; i++){ + mn = Math.min(mn, data[i][dI]); + mx = Math.max(mx, data[i][dI]); + } + df = mx - mn; + return {min: mn, max: mx, diff: df}; + } + function showHover(event,pos,item,showAlways,createText){ + var txt; + if (item) { + var data = item.series.data[item.dataIndex]; + if(createText){ txt = createText(data);} + else { + txt = "X:" + data[0] + "
Y:" + data[1]; + if(data.length > 2) { for(var i = 2; i < data.length; i++){ txt += "
" + data[i]; } } + } + showTooltip(pos.pageX, pos.pageY,txt); + } + else { + if(showAlways === true){ + txt = pos.x1 + " / " + pos.y1; + showTooltip(pos.pageX,pos.pageY,txt); + } + else {$("#FLOTtooltip").remove();} + } + } + function showTooltip(x, y, contents){ + $("#FLOTtooltip").remove(); + $('
' + contents + '
').css( + { position: 'absolute',display: 'none',top: y + 5,left: x + 5, + border: '1px solid #fdd',padding: '2px','background-color': '#fee',opacity: 0.80 + }).appendTo("body").fadeIn(200); + } + function loadScripts(scripts,maxWait,callback){ + var loadedScripts = {},defs = []; + for(var i = 0; i < scripts.length; i++){ defs.push(loadScript(scripts[i].path,scripts[i].name)); } + $.when.apply(null,defs).then(function(){callback(loadedScripts);}); + function loadScript(path,name){ + var dfd = $.Deferred(),t; + t = setInterval(function(){clearInterval(t);dfd.reject();},maxWait); + $.getScript(path).done(loaded).fail(errorFound); + return dfd.promise(); + function loaded(){ loadedScripts[name] = true;dfd.resolve();} + function errorFound(e,f,g){console.log(path,e); loadedScripts[name] = false;dfd.reject();} + } + } + function loadJSON(scripts,maxWait,callback){ + var loadedJSON = {},defs = []; + for(var i = 0;i < scripts.length; i++){ defs.push(loadJSON(scripts[i].path,scripts[i].name)); } + $.when.apply(null,defs).then(function(){ callback(loadedJSON);}); + function loadJSON(path,name){ + var dfd = $.Deferred(),t; + t = setInterval(function(){clearInterval(t);dfd.reject();},maxWait); + $.getJSON(path,function(data){ + loadedJSON[name] = {data:data,name:name,loaded:true}; + }).done(loaded).fail(errorFound); + return dfd.promise(); + function loaded(){ dfd.resolve(); } + function errorFound(e,f,g){ loadedJSON[name] = {name:name,loaded:false};dfd.reject();} + } + } + + function createQuartile(data, index, indexName){ + var q0 = [], q1 = [],q2 = [],q3 = [],q4 = [], v = [], i1, i2, i3, i4, p; + i1 = (0.25 * data.length).toFixed(0); i2 = (0.5 * data.length).toFixed(0); + i3 = (0.75 * data.length).toFixed(0); i4 = data.length - 1; + for (var j = 0; j < data[0].length; j++){ + p = []; + for (var i = 0; i < data.length; i++) { p.push(data[i][j]); } + p.sort(function(a,b){return a - b;} ); + q1.push([j,p[i1]]); q2.push([j,p[i2]]); q3.push([j,p[i3]]); q4.push([j,p[i4]]); + q0.push([j,p[0]]); v.push([j,data[index][j]]); + } + var r = [ { data: q4}, { data: q3}, { data: q2}, { data: q1}, {data: q0, color: "#ffffff" }, + {label: indexName, points: {show:true}, lines: { fill: null, steps: false}, data: v}]; + return r; + } + function createPercentile(data, index, indexName, percentiles){ + var percentile = [], val = [], indexes = [], p,j,i; + if(percentiles.length){ + indexes.push([0]); + percentile.push([]); + for(j = 0;j < percentiles.length;j++){ + indexes.push(parseInt(data.length * percentiles[j],0)); + percentile.push([]); + } + indexes.push(data.length - 1); + } + else{ + for(j = 0;j < percentiles; j++){ + indexes.push(parseInt(data.length / percentiles * j,0)); + percentile.push([]); + } + indexes.push(data.length - 1); + } + percentile.push([]); + for(j = 0; j < data[0].length; j++){ + p = []; + for(i = 0; i < data.length; i++){ p.push(data[i][j]); } + p.sort(function(a,b){return a-b;}); + for(i = 0; i < percentile.length; i++ ) { percentile[i].push([j,p[indexes[i]]]); } + val.push([j,data[index][j]]); + } + var r = []; + for(j = percentile.length - 1; j > 0 ; j--){ r.push({ data: percentile[j] });} + r.push({data: percentile[0], color:"#ffffff"}); + r.push({label: indexName, points: {show: true}, lines: { fill: null, steps: false}, data:val}); + return r; + } + function createSimiliarity(data1, data2, mode){ + var r = []; + var d1 = normalize(data1); + var d2 = normalize(data2); + var d; + for (var i = 0; i < d1.length; i++){ + switch (mode){ + case "diff": + d = d1[i][1] - d2[i][1]; + break; + case "abs": + d = Math.abs(d1[i][1] - d2[i][1]); + break; + default: + d = 0; + } + r.push([d1[i][0],d]); + } + return r; + } + function createWaterfall(data, colors){ //convert waterfalldata to 4 Bars, d1 for fixed bars, d2 for invisible bar + var d1 = [], d2 = [], d3 = [], d4 = [], p = 0, mn = Number.POSITIVE_INFINITY,i; // d3 for negative bars and d4 for positive bars + var dx = data; + for(i = 0; i < dx.length; i++) { + if(dx[i][2]){ + if(typeof dx[i][1] === "undefined") { d1.push([i,p]); } + else { d1.push([i,dx[i][1]]); p = dx[i][1]; } + } + else{ + if(dx[i][1] > 0) { d4.push([i,- dx[i][1]]);p = p + dx[i][1];d2.push([i,p]);d3.push([i,0]);} + else {d3.push([i,- dx[i][1]]);p = p + dx[i][1];d2.push([i,p]);} + } + mn = Math.min(mn,p); + } + var ticks = []; + for(i = 0; i < data.length; i++){ ticks.push([i,data[i][0]]);} + var dr = { + data: [ + { data: d1, color: colors.fixed }, + { data: d2, bars: { show: false }, lines: { show: false } }, + { data: d3, color: colors.negative }, + { data: d4, color: colors.positive} + ], + ticks: ticks, + yaxismin: mn + }; + return dr; + } + function avg(data,range){ + var r = [],rd = [],i1,s; + for(var i = 0; i < data.length; i++){ + if(i < range){ i1 = 0;} else{ i1 = i - range + 1;} + rd = []; + rd.push(data[i][0]); + for(var k = 1; k < data[i].length; k++){ + s = 0; + for(var j = i1; j <= i; j++){ s += data[j][k];} + rd.push(s / (i - i1 + 1)); + } + r.push(rd); + } + return r; + } + function max(data,range){ + var r = [], rd = [], i1, mx; + for(var i = 0; i < data.length; i++){ + if(i < range) {i1 = 0;} else {i1 = i - range + 1;} + rd = []; + rd.push(data[i][0]); + for(var k = 1; k < data[i].length; k++){ + mx = - Number.MAX_VALUE; + for(var j = i1; j <= i; j++){ if(data[j][k] > mx){ mx = data[j][k]; } } + rd.push(mx); + } + r.push(rd); + } + return r; + } + function min(data,range){ + var r = [], rd = [], i1, mn; + for(var i = 0; i < data.length; i++){ + if(i < range){ i1 = 0;} else{ i1 = i - range + 1;} + rd = []; + rd.push(data[i][0]); + for(var k = 1; k < data[i].length; k++){ + mn = Number.MAX_VALUE; + for(var j = i1; j <= i; j++){ if(data[j][k] < mn){ mn = data[j][k]; } } + rd.push(mn); + } + r.push(rd); + } + return r; + } + function sort(data,sortOrder,sortfnc){ + var d = []; + for(var i = 0; i < data.length; i++){ d.push(data[i]);} + if(sortfnc){ d.sort(sortfnc); } + else{ + if (sortOrder === "a"){ d.sort(mysorta); } else { d.sort(mysortd); } + } + return d; + function mysorta(a,b){ return a[1] - b[1]; } + function mysortd(a,b){ return b[1] - a[1]; } + } + function sortTicks(data,sortOrder,sortfnc){ + var d = sort(data,sortOrder,sortfnc); + for(var i = 0; i < d.length; i++){d[i][0] = i; } + return { data:d, ticks:getTicks(d) }; + } + function pareto(data,otherLabel,showOthers,topN,topPercent){ + var d = [],othersLabel="Others",showothers = true,i,dn = []; + d = sort(data,"d"); + if(otherLabel.length > 0){ othersLabel = otherLabel;} + showothers = showOthers; + if(topN){ + var s; + for(i = 0;i < topN; i++){ dn.push(d[i]); } + s = 0; + for(i = topN;i < d.length; i++){ s+=d[i][1]; } + if(showothers){ dn.push([topN, s,othersLabel]);} + d = dn; + } + else if(topPercent){ + var datasum = 0, datar = 0, datao = 0,j; + for(i = 0; i < d.length;i++){ datasum += d[i][1];} + datasum = datasum * topPercent / 100; + for(i = 0; i < d.length; i++){ + if (datar < datasum) { + dn.push(d[i]); + datar += d[i][1]; + j = i; + } + else{ datao += d[i][1]; } + } + j++; + if(showothers){ dn.push([j,datao,othersLabel]);} + d = dn; + } + for(i = 0; i < d.length; i++){d[i][0] = i; } + return { data:d, ticks:getTicks(d) }; + } + function getTicks(d){ + var t = []; + for(var i = 0; i < d.length; i++){ + if(d[i][2]){ t.push([d[i][0], d[i][2]]);} else{ t.push(d[i][0], d[i][0]);} + } + return t; + } + function normalize(data){ + var minmax, d;var r = []; + minmax = getMinMax(data); + for(var i = 0; i < data.length; i++){ + d = (data[i][1] - minmax.min) / minmax.diff * 100; + r.push([data[i][0],d]); + } + return r; + } + function combineData(data,ticks){ + var r = []; + for(var i = 0; i < data.length; i++){ + var s = []; + for(var j = 0; j < data[i].length; j++){ + var d = [ ticks[j], data[i][j] ]; + s.push(d); + } + r.push(s); + } + return r; + } + + function createFont(placeholder){ + var f = { + style: placeholder.css("font-style"), + size: Math.round(0.8 * (+placeholder.css("font-size").replace("px", "") || 13)), + variant: placeholder.css("font-variant"), + weight: placeholder.css("font-weight"), + family: placeholder.css("font-family") + }; + return f; + } + function createColors(options,neededColors){ + // this is copied code from jquery.flot.js in fillInSeriesOptions + var c, colors = [], colorPool = options.colors, + colorPoolSize = colorPool.length, variation = 0; + for(var i = 0; i < colorPoolSize; i++){ colors[i] = colorPool[i]; } + if(colorPoolSize < neededColors){ + for (i = colorPoolSize; i < neededColors; i++) { + c = $.color.parse(colorPool[i % colorPoolSize] || "#666"); + if (i % colorPoolSize === 0 && i) { + if (variation >= 0) { + if (variation < 0.5) { variation = -variation - 0.2; } else{ variation = 0;} + } + else {variation = -variation;} + } + colors[i] = c.scale('rgb', 1 + variation).toString(); + } + } + return colors; + } + function getColor(colorData){ //based on a patch from Martin Thorsen Ranang from Nov 2012 + var c; + if(typeof colorData === "object"){ + if(typeof colorData.dataIndex !== "undefined"){ + if(typeof colorData.serie.data[colorData.dataIndex].color !== "undefined"){ + c = getColorL(colorData.serie.data[colorData.dataIndex].color); + } + else{ c = colorData.colors[colorData.dataIndex]; } + } + else{ + if(typeof colorData.serieIndex !== "undefined"){ + if(typeof colorData.serie.color !== "undefined"){ c = getColorL(colorData.serie.color);} + else{ c = colorData.colors[colorData.serieIndex];} + } + else{ + if(typeof colorData.color !== "undefined"){c = getColorL(colorData.color);} + else {c = "darkgreen"; } + } + } + } + else{ c = getColorL(colorData); } + return c; + function getColorL(color){ + var c; + if(typeof color === "object"){ + if(typeof color.image !== "undefined"){ + c = colorData.ctx.createPattern(color.image,color.repeat); + } + else{ + if(colorData.radius){ + c = colorData.ctx.createRadialGradient(colorData.left,colorData.top,0, + colorData.left,colorData.top,colorData.radius); + } + else { c = colorData.ctx.createLinearGradient(0,0,colorData.width,colorData.height);} + for(var i = 0; i < color.colors.length; i++){ + var cl = color.colors[i]; + if(typeof cl !== "string"){ + var co = $.color.parse(colorData.defaultColor); + if(color.brightness !== null){ cl = co.scale("rgb",color.brightness);} + if(color.opacity !== null){ co *= color.opacity;} + cl = co.toString(); + } + c.addColorStop(i / (color.colors.length - 1),cl); + } + } + } + else{ if(typeof color === "string"){ c = color; } else { c = colorData.colors[color]; } } + return c; + } + } + function loadImages(images,maxWait,callback){ + var loadedImg = {},defs = []; + for(var i = 0; i < images.length; i++){ defs.push(loadImage(images[i])); } + $.when.apply(null,defs).then(function(){callback(loadedImg);}); + function loadImage(img){ + var dfd = $.Deferred(),t,url; + url = img.path + img.name + "." + img.type; + t = setInterval(function(){clearInterval(t);dfd.reject();},maxWait); + $('').attr('src',url).load(loaded).error(errorFound); + return dfd.promise(); + function loaded(){ loadedImg[img.name] = this;dfd.resolve();} + function errorFound(e,f,g){console.log(url,e); loadedImg[img.name] = null;dfd.reject();} + } + } + function getCanvases(placeholder){ + var canvases = { + background:$(placeholder).children(".flot-background"), + base:$(placeholder).children(".flot-base"), + overlay:$(placeholder).children(".flot-overlay") + }; + return canvases; + } + function extendEmpty(org,ext){ + for(var i in ext){ + if(!org[i]){ org[i] = ext[i];} + else{ + if(typeof ext[i] === "object"){ + extendEmpty(org[i],ext[i]); + } + } + } + } + + function drawLines(plot,lines){ + var offset,series,ctx; + offset = plot.getPlotOffset(); + series = plot.getData(); + ctx = plot.getCanvas().getContext("2d"); + ctx.translate(offset.left,offset.top); + for(var i = 0; i < lines.length; i++){ + var from = series[lines[i].from.seriesIndex], to = series[lines[i].to.seriesIndex]; + var fl = lines[i].from, tl = lines[i].to; + if(!fl.dataFieldX){ fl.dataFieldX = 0;} + if(!fl.dataFieldY){ fl.dataFieldY = 1;} + if(!tl.dataFieldX){ tl.dataFieldX = 0;} + if(!tl.dataFieldY){ tl.dataFieldY = 1;} + var fromPos = {xaxis:from.xaxis, yaxis:from.yaxis, x:from.data[fl.dataIndex][fl.dataFieldX], y:from.data[fl.dataIndex][fl.dataFieldY]}, + toPos = {xaxis:to.xaxis, yaxis:to.yaxis, x:to.data[tl.dataIndex][tl.dataFieldX], y:to.data[tl.dataIndex][tl.dataFieldY]}, + lineStyle = {strokeStyle:"red", lineWidth:5}; + drawLine(plot,ctx,fromPos,toPos,lineStyle); + } + } + function drawLine(plot,ctx,fromPos,toPos,lineStyle){ + var xf,yf,xt,yt; + xf = fromPos.xaxis.p2c(fromPos.x); + yf = fromPos.yaxis.p2c(fromPos.y); + xt = toPos.xaxis.p2c(toPos.x); + yt = toPos.yaxis.p2c(toPos.y); + ctx.beginPath(); + ctx.strokeStyle = lineStyle.strokeStyle; + ctx.lineWidth = lineStyle.lineWidth; + ctx.moveTo(xf,yf); + ctx.lineTo(xt,yt); + ctx.stroke(); + } + function drawRect(plot,ctx,xaxis,yaxis,boxDim,boxStyle){ + var boxC = {x: xaxis.p2c(boxDim.x),y: yaxis.p2c(boxDim.y), + width: xaxis.p2c((boxDim.x + boxDim.width)) - xaxis.p2c(boxDim.x), + height: yaxis.p2c(boxDim.y + boxDim.height) - yaxis.p2c(boxDim.y)}; + switch(boxStyle.mode){ + case "image": drawImage(plot,ctx,boxC,boxStyle); break; + case "color": drawColor(plot,ctx,boxC,boxStyle); break; + case "userdefined": boxStyle.boxDraw(plot,ctx,boxC,boxStyle); break; + default: drawColor(plot,ctx,boxC,boxStyle); + } + function drawImage(plot,ctx,boxC,boxStyle){ + var image = boxStyle.image; + if(typeof image !== "undefined"){ctx.drawImage(image,boxC.x,boxC.y,boxC.width(),boxC.height());} + } + function drawColor(plot,ctx,boxC,boxStyle){ + color = getColor({ctx:ctx,color:boxStyle.color,left:boxC.x,top:boxC.y,height:boxC.height,width:boxC.width}); + ctx.fillStyle = color; + ctx.fillRect(boxC.x,boxC.y,boxC.width,boxC.height); + } + } + function drawCircle(plot,ctx,xaxis,yaxis,circle,circleStyle){ + var circleC = {x: xaxis.p2c(boxDim.x),y: yaxis.p2c(boxDim.y)} + } + $.plot.JUMlib = {}; + $.plot.JUMlib.library = {}; + $.plot.JUMlib.library.between = between; + $.plot.JUMlib.library.getMinMax = getMinMax; + $.plot.JUMlib.library.showHover = showHover; + $.plot.JUMlib.library.showTooltip = showTooltip; + $.plot.JUMlib.library.loadScripts = loadScripts; + $.plot.JUMlib.library.loadJSON = loadJSON; + $.plot.JUMlib.prepareData = {}; + $.plot.JUMlib.prepareData.createQuartile = createQuartile; + $.plot.JUMlib.prepareData.createPercentile = createPercentile; + $.plot.JUMlib.prepareData.createSimiliarity = createSimiliarity; + $.plot.JUMlib.prepareData.createWaterfall = createWaterfall; + $.plot.JUMlib.prepareData.avg = avg; + $.plot.JUMlib.prepareData.max = max; + $.plot.JUMlib.prepareData.min = min; + $.plot.JUMlib.prepareData.sort = sort; + $.plot.JUMlib.prepareData.sortTicks = sortTicks; + $.plot.JUMlib.prepareData.pareto = pareto; + $.plot.JUMlib.prepareData.normalize = normalize; + $.plot.JUMlib.prepareData.combineData = combineData; + $.plot.JUMlib.data = {}; + $.plot.JUMlib.data.createFont = createFont; + $.plot.JUMlib.data.createColors = createColors; + $.plot.JUMlib.data.getColor = getColor; + $.plot.JUMlib.data.loadImages = loadImages; + $.plot.JUMlib.data.getCanvases = getCanvases; + $.plot.JUMlib.data.extendEmpty = extendEmpty; + $.plot.JUMlib.drawing = {}; + $.plot.JUMlib.drawing.drawLine = drawLine; + $.plot.JUMlib.drawing.drawRect = drawRect; + $.plot.JUMlib.drawing.drawLines = drawLines; + $.plot.plugins.push({ + init: function(){}, + options: { }, + name: pluginName, + version: pluginVersion + }); +})(jQuery); \ No newline at end of file diff --git a/src/sunstone/public/vendor/flot/jquery.flot.gantt.js b/src/sunstone/public/vendor/flot/jquery.flot.gantt.js new file mode 100644 index 0000000000..16edaabf60 --- /dev/null +++ b/src/sunstone/public/vendor/flot/jquery.flot.gantt.js @@ -0,0 +1,201 @@ +/* + * The MIT License + +Copyright (c) 2010, 2011, 2012, 2013 by Juergen Marsch + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +(function ($) { + "use strict"; + var pluginName = "gantt", pluginVersion = "0.3"; + var options = { + series: { + gantt: { + active: false, + show: false, + connectSteps: { show: false, lineWidth:2, color:"rgb(0,0,0)" }, + barHeight: 0.6, + highlight: { opacity: 0.5 }, + drawstep: drawStepDefault + } + } + }; + var replaceOptions = { series:{ lines: { show:false } } }; + var defaultOptions = { + series:{ + editMode: 'y', //could be none, x, y, xy, v + nearBy:{ + distance: 6, + findItem: null, + findMode: "circle", + drawHover: null + } + } + }; + function drawStepDefault(ctx,series,data,x,y,x2,color, isHighlight){ + if(isHighlight === false){ + ctx.beginPath(); + ctx.lineWidth = series.gantt.barheight; + ctx.strokeStyle = "rgb(0,0,0)"; + ctx.moveTo(x, y); + ctx.lineTo(x2, y); + ctx.stroke(); + } + ctx.beginPath(); + ctx.strokeStyle = color; + ctx.lineWidth = series.gantt.barheight - 2; + ctx.lineCap = "butt"; + ctx.moveTo(x + 1, y); + ctx.lineTo(x2 - 1, y); + ctx.stroke(); + } + function init(plot) { + var offset = null, opt = null, series = null,canvas,target,axes,data; + plot.hooks.processOptions.push(processOptions); + function processOptions(plot,options){ + if (options.series.gantt.active){ + $.extend(true,options,replaceOptions); + $.plot.JUMlib.data.extendEmpty(options,defaultOptions); + opt = options; + plot.hooks.processRawData.push(processRawData); + plot.hooks.draw.push(draw); + } + } + function processRawData(plot,s,data,datapoints){ + if(s.gantt.show === true){ + s.nearBy.findItem = findNearbyItemGantt; + s.nearBy.drawHover = drawHoverGantt; + } + } + function draw(plot, ctx){ + var serie; + canvas = plot.getCanvas(); + target = $(canvas).parent(); + axes = plot.getAxes(); + offset = plot.getPlotOffset(); + data = plot.getData(); + for (var i = 0; i < data.length; i++){ + serie = data[i]; + serie.gantt.barheight = axes.yaxis.p2c(1) / (axes.yaxis.max - axes.yaxis.min) * serie.gantt.barHeight; + if (serie.gantt.show) { + series = serie; + for (var j = 0; j < serie.data.length; j++){drawData(ctx,serie, serie.data[j], serie.color,false); } + if(serie.gantt.connectSteps.show){ drawConnections(ctx,serie); } + } + } + } + function drawData(ctx,series,data,color,isHighlight){ + var x,y,x2; + x = offset.left + axes.xaxis.p2c(data[0]); + x = Math.min(Math.max(offset.left,x),offset.left + plot.width()); + y = offset.top + axes.yaxis.p2c(data[1]); + x2 = offset.left + axes.xaxis.p2c(data[2]); + x2 = Math.min(Math.max(x2,offset.left),offset.left + plot.width()); + if(x2 > offset.left || x > offset.left){ + if (x < (offset.left + plot.width()) || x2 < (offset.left + plot.width())){ + if (data.length === 4) {drawStepDefault(ctx, series, data, x, y, x2, color, isHighlight);} + else{ series.gantt.drawstep(ctx,series,data,x,y,x2,color,isHighlight);} + } + } + } + function drawConnections(ctx,series){ + for(var i = 0; i < series.data.length; i++){ + for(var j = 0; j < series.data.length; j++){ + if(series.data[i][2] == series.data[j][0]){ + var x = offset.left + axes.xaxis.p2c(series.data[i][2]), + y = offset.top + axes.yaxis.p2c(series.data[i][1]), + y2 = offset.top + axes.yaxis.p2c(series.data[j][1]); + drawConnection(ctx,x,y,y2,series.gantt.connectSteps.lineWidth,series.gantt.connectSteps.color); + } + } + } + } + function drawConnection(ctx,x,y,y2,lineWidth,color){ + ctx.beginPath(); + ctx.lineWidth = lineWidth; + ctx.strokeStyle = color; + ctx.moveTo(x, y); + ctx.lineTo(x, y2); + ctx.stroke(); + } + function findNearbyItemGantt(mouseX, mouseY,i,serie){ + var item = null; + if(opt.series.justEditing){ + if(opt.series.justEditing[1].seriesIndex === i){item = findNearbyItemEdit(mouseX,mouseY,i,serie);} + } + else{ + if(opt.grid.editable){ item = findNearbyItemForEdit(mouseX,mouseY,i,serie);} + else{ item = findNearbyItem(mouseX,mouseY,i,serie);} + } + return item; + function findNearbyItem(mouseX,mouseY,i,serie){ + var item = null; + if(serie.gantt.show){ + for(var j = 0; j < serie.data.length; j++){ + var dataitem = serie.data[j]; + var dx = serie.xaxis.p2c(dataitem[0]),dx2 = serie.xaxis.p2c(dataitem[2]), + dy = Math.abs(serie.yaxis.p2c(dataitem[1]) - mouseY); + if(dy <= serie.gantt.barheight / 2){ if(between(mouseX,dx,dx2)){ item = [i,j]; } } + } + } + return item; + } + function findNearbyItemForEdit(mouseX,mouseY,i,serie){ + var item = null; + if(serie.gantt.show){ + for(var j = 0; j < serie.data.length; j++){ + var dataitem = serie.data[j]; + var dx = serie.xaxis.p2c(dataitem[0]),dx2 = serie.xaxis.p2c(dataitem[2]), + dy = Math.abs(serie.yaxis.p2c(dataitem[1]) - mouseY); + if(dy <= serie.gantt.barheight / 2){ + if(between(mouseX,dx,dx2)){ item = [i,j]; serie.editMode = 'y'; serie.nearBy.findMode = 'vertical';serie.nearBy.width = dataitem[2]-dataitem[0];} + if(between(mouseX,dx,dx + serie.nearBy.distance)) { item = [i,[j,1]];serie.editMode = 'x'; serie.nearBy.findMode = 'horizontal'; } + if(between(mouseX,dx2,dx2 + serie.nearBy.distance)) { item = [i,[j,2]];serie.editMode = 'x'; serie.nearBy.findMode = 'horizontal'; } + } + } + } + return item; + } + function findNearbyItemEdit(mouseX,mouseY,i,serie){ + var item = null; + var j = opt.series.justEditing[1].dataIndex; + var dataitem = serie.data[j]; + if(j.length){item = [i,j];}else{item = [i,j];} + return item; + } + } + function drawHoverGantt(octx,serie,dataIndex){ + var data; + octx.save(); + octx.translate(-offset.left,-offset.top); + var c = "rgba(255,255,255, " + serie.gantt.highlight.opacity + ")"; + if(dataIndex.length){ data = serie.data[dataIndex[0]];} else{ data = serie.data[dataIndex];} + drawData(octx,serie,data,c,true); + octx.restore(); + } + } + var between = $.plot.JUMlib.library.between; + $.plot.plugins.push({ + init: init, + options: options, + name: pluginName, + version: pluginVersion + }); +})(jQuery); diff --git a/src/sunstone/views/index.erb b/src/sunstone/views/index.erb index 6f084a53bf..058be2aa60 100644 --- a/src/sunstone/views/index.erb +++ b/src/sunstone/views/index.erb @@ -13,6 +13,8 @@ + + From 8c03a253f6a06b2d8a418d74a750902a8260bd65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn?= Date: Tue, 6 May 2014 17:30:24 +0200 Subject: [PATCH 05/18] Feature #1607: Add accounting tables --- src/sunstone/public/js/sunstone.js | 127 ++++++++++++++++++++++++++++- 1 file changed, 126 insertions(+), 1 deletion(-) diff --git a/src/sunstone/public/js/sunstone.js b/src/sunstone/public/js/sunstone.js index 1ee7926d6a..85a14cef1e 100644 --- a/src/sunstone/public/js/sunstone.js +++ b/src/sunstone/public/js/sunstone.js @@ -3986,6 +3986,34 @@ function accountingGraphs(div, opt){
\
\
\ +
\ +
\ +
\ +

'+tr("CPU hours")+'

\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ +
'+tr("Date")+'
\ +
\ +
\ +
\ +

'+tr("Memory GB hours")+'

\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ +
'+tr("Date")+'
\
'); if (opt == undefined){ @@ -4133,6 +4161,8 @@ Filter by: user, group, vm, [flow] Download csv */ + // TODO: Uniform time format (yy/mm/dd?) and define the time zone (utc, local?) + var options = req.request.data[0]; //-------------------------------------------------------------------------- @@ -4372,7 +4402,7 @@ Download csv }); }); - $.plot($("#acct_cpu_graph", div), plot_series, options); + var cpu_plot = $.plot($("#acct_cpu_graph", div), plot_series, options); // --- mem --- @@ -4485,4 +4515,99 @@ Download csv } $.plot($("#acct_activity_graph", div), plot_series, options); + + //-------------------------------------------------------------------------- + // Init dataTables + //-------------------------------------------------------------------------- + + $("#acct_cpu_datatable",div).dataTable().fnClearTable(); + $("#acct_cpu_datatable",div).dataTable().fnDestroy(); + + $("#acct_cpu_datatable thead",div).remove(); + + + $("#acct_mem_datatable",div).dataTable().fnClearTable(); + $("#acct_mem_datatable",div).dataTable().fnDestroy(); + + $("#acct_mem_datatable thead",div).remove(); + + + cpu_plot_data = cpu_plot.getData(); + mem_plot_data = mem_plot.getData(); + + var thead = ''+tr("Date")+''; + + $.each(series.CPU_HOURS, function(key, val){ + thead += ''+group_by_prefix+key+''; + }); + + thead += ''; + + $("#acct_cpu_datatable",div).append(thead); + + thead = ''+tr("Date")+''; + + $.each(series.MEM_HOURS, function(key, val){ + thead += ''+group_by_prefix+key+''; + }); + + thead += ''; + + $("#acct_mem_datatable",div).append(thead); + + + var cpu_dataTable_data = []; + var mem_dataTable_data = []; + + for (var i = 0; i Date: Tue, 6 May 2014 18:11:10 +0200 Subject: [PATCH 06/18] Feature #1607: Add accounting to cloud view --- .../public/js/plugins/provision-tab.js | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/sunstone/public/js/plugins/provision-tab.js b/src/sunstone/public/js/plugins/provision-tab.js index 5b5656c894..d9b89f5d5e 100644 --- a/src/sunstone/public/js/plugins/provision-tab.js +++ b/src/sunstone/public/js/plugins/provision-tab.js @@ -212,9 +212,10 @@ var provision_user_info = '