source: DCWoRMS/trunk/src/simulator/stats/implementation/DCWormsStatistics.java @ 481

Revision 481, 48.6 KB checked in by wojtekp, 13 years ago (diff)
  • Property svn:mime-type set to text/plain
Line 
1package simulator.stats.implementation;
2
3import java.awt.Color;
4import java.awt.Paint;
5import java.io.File;
6import java.io.FileOutputStream;
7import java.io.IOException;
8import java.io.PrintStream;
9import java.text.NumberFormat;
10import java.util.ArrayList;
11import java.util.Calendar;
12import java.util.Collections;
13import java.util.Comparator;
14import java.util.Date;
15import java.util.HashMap;
16import java.util.List;
17import java.util.Map;
18import java.util.SortedMap;
19import java.util.TreeMap;
20
21import org.apache.commons.logging.Log;
22import org.apache.commons.logging.LogFactory;
23import org.jfree.chart.ChartFactory;
24import org.jfree.chart.ChartRenderingInfo;
25import org.jfree.chart.ChartUtilities;
26import org.jfree.chart.JFreeChart;
27import org.jfree.chart.axis.AxisLocation;
28import org.jfree.chart.axis.DateAxis;
29import org.jfree.chart.axis.NumberAxis;
30import org.jfree.chart.encoders.ImageFormat;
31import org.jfree.chart.labels.CategoryItemLabelGenerator;
32import org.jfree.chart.labels.ItemLabelAnchor;
33import org.jfree.chart.labels.ItemLabelPosition;
34import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
35import org.jfree.chart.plot.CategoryPlot;
36import org.jfree.chart.plot.CombinedDomainXYPlot;
37import org.jfree.chart.plot.PlotOrientation;
38import org.jfree.chart.plot.XYPlot;
39import org.jfree.chart.renderer.category.CategoryItemRenderer;
40import org.jfree.chart.renderer.category.GanttRenderer;
41import org.jfree.chart.renderer.xy.XYStepAreaRenderer;
42import org.jfree.chart.title.TextTitle;
43import org.jfree.chart.title.Title;
44import org.jfree.data.gantt.TaskSeries;
45import org.jfree.data.gantt.TaskSeriesCollection;
46import org.jfree.data.time.FixedMillisecond;
47import org.jfree.data.xy.XYDataset;
48import org.jfree.data.xy.XYSeries;
49import org.jfree.data.xy.XYSeriesCollection;
50import org.jfree.ui.TextAnchor;
51import org.joda.time.DateTimeUtilsExt;
52
53import schedframe.ExecutablesList;
54import schedframe.ResourceController;
55import schedframe.exceptions.ResourceException;
56import schedframe.resources.ResourceType;
57import schedframe.resources.StandardResourceType;
58import schedframe.resources.computing.ComputingResource;
59import schedframe.resources.computing.extensions.Extension;
60import schedframe.resources.computing.extensions.ExtensionList;
61import schedframe.resources.computing.extensions.ExtensionType;
62import schedframe.resources.computing.profiles.energy.EnergyExtension;
63import schedframe.resources.computing.profiles.energy.power.PowerUsage;
64import schedframe.resources.units.PEUnit;
65import schedframe.resources.units.ProcessingElements;
66import schedframe.resources.units.ResourceUnit;
67import schedframe.resources.units.ResourceUnitName;
68import schedframe.resources.units.StandardResourceUnitName;
69import schedframe.scheduling.ResourceHistoryItem;
70import schedframe.scheduling.Scheduler;
71import schedframe.scheduling.manager.tasks.JobRegistry;
72import schedframe.scheduling.manager.tasks.JobRegistryImpl;
73import schedframe.scheduling.tasks.Job;
74import schedframe.scheduling.tasks.JobInterface;
75import simulator.ConfigurationOptions;
76import simulator.DCWormsConstants;
77import simulator.DataCenterWorkloadSimulator;
78import simulator.GenericUser;
79import simulator.stats.GSSAccumulator;
80import simulator.stats.SimulationStatistics;
81import simulator.stats.implementation.out.AbstractStringSerializer;
82import simulator.stats.implementation.out.FormatedStringSerializer;
83import simulator.stats.implementation.out.StringSerializer;
84import csiro.mit.utils.jfreechart.timetablechart.TimetableChartFactory;
85import csiro.mit.utils.jfreechart.timetablechart.data.Timetable;
86import csiro.mit.utils.jfreechart.timetablechart.data.TimetableEventGroup;
87import csiro.mit.utils.jfreechart.timetablechart.data.TimetableEventSource;
88import csiro.mit.utils.jfreechart.timetablechart.renderer.TimetableRenderer;
89import eduni.simjava.Sim_stat;
90import gssim.schedframe.scheduling.ExecTask;
91import gssim.schedframe.scheduling.Executable;
92
93public class DCWormsStatistics implements SimulationStatistics {
94
95        private Log log = LogFactory.getLog(DCWormsStatistics.class);
96
97        protected static float ALPHA = 0.5f;
98        protected static int GANTT_WIDTH = 1200;
99
100        //protected static final int BITS = 8;
101        protected static final int MILLI_SEC = 1000;
102
103        protected static final String RAW_TASKS_STATISTICS_OUTPUT_FILE_NAME = "Tasks.txt";
104        protected static final String JOBS_STATISTICS_OUTPUT_FILE_NAME = "Jobs.txt";
105
106        protected static final String SIMULATION_STATISTICS_OUTPUT_FILE_NAME = "Simulation.txt";
107        protected static final String ENERGYUSAGE_STATISTICS_OUTPUT_FILE_NAME = "Energy.txt";
108        protected static final String RESOURCEUSAGE_STATISTICS_OUTPUT_FILE_NAME = "ResourceUtilization.txt";
109
110        protected static final String DIAGRAMS_FILE_NAME_PREFIX = "Chart_";
111        protected static final String STATS_FILE_NAME_PREFIX = "Stats_";
112
113        protected static final String TASK_SEPARATOR = ";";
114        protected static final String JOB_SEPARATOR = ";";
115
116        protected String outputFolderName;
117
118        protected String simulationIdentifier;
119        protected ConfigurationOptions configuration;
120
121        protected GSSAccumulatorsStats accStats;
122        protected Map<String, GSSAccumulator> statsData;
123       
124        private GenericUser users;
125        protected ResourceController resourceController;
126        protected boolean generateDiagrams = true;
127        protected AbstractStringSerializer serializer;
128        protected long startSimulationTime;
129        protected long endSimulationTime;
130       
131        //RESOURCES
132        protected Timetable ganttDiagramPeTimetable;
133        protected Map<ResourceType, List<XYDataset>> resourceEnergyDiagrams;
134        protected Map<ResourceType, List<XYDataset>> resourceLoadDiagrams;
135        protected Map<String,List<ResStat>> basicResStats;
136        protected HashMap<String, Double> basicResLoad;
137       
138        protected Map<String, TimetableEventSource> peGanttMap;
139        protected Map<String, TimetableEventGroup> taskGanttMap;
140       
141        //TASKS
142        protected int numOfdelayedTasks = 0;
143        protected int numOfNotExecutedTasks = 0;
144        protected double maxCj = 0;
145
146        protected boolean allTasksFinished;
147        protected TaskSeriesCollection ganttDiagramTaskSeriesCollection;
148        protected TaskSeriesCollection ganttDiagramWaitingTimeSeriesCollection;
149        protected HashMap<String, List<String>> task_processorsMap;
150
151        protected JobRegistryImpl jr;
152
153       
154        public DCWormsStatistics(String simulationIdentifier, ConfigurationOptions co, GenericUser users,
155                        String outputFolderName, ResourceController resourceController) {
156                this.simulationIdentifier = simulationIdentifier;
157                this.configuration = co;
158                this.users = users;
159
160                this.outputFolderName = outputFolderName;
161
162                if (this.configuration.formatstatisticsoutput)
163                        this.serializer = new FormatedStringSerializer();
164                else
165                        this.serializer = new StringSerializer();
166
167                this.serializer.setDefaultNumberFormat(DataCenterWorkloadSimulator.DFAULT_NUMBER_FORMAT);
168
169                this.resourceController = resourceController;
170                 jr = new JobRegistryImpl("COMPUTING_GRID_0#BROKER");
171                init();
172        }
173
174        public void generateStatistics() {
175
176                this.startSimulationTime = DateTimeUtilsExt.getOffsetTime().getTimeInMillis();
177
178                this.endSimulationTime = DateTimeUtilsExt.currentTimeMillis();
179
180                long s = 0;
181                long e = 0;
182
183                log.info("gatherResourceStatistics");
184                s = System.currentTimeMillis();
185                gatherResourceStatistics();
186                e = System.currentTimeMillis();
187                log.info("time in sec: " + ((e - s) / MILLI_SEC));
188               
189                log.info("gatherTaskStatistics");
190                s = System.currentTimeMillis();
191                gatherTaskStatistics();
192                e = System.currentTimeMillis();
193                log.info("time in sec: " + ((e - s) / MILLI_SEC));
194
195                log.info("saveSimulationStatistics");
196                s = System.currentTimeMillis();
197                saveSimulationStatistics();
198                e = System.currentTimeMillis();
199                log.info("time in sec: " + ((e - s) / MILLI_SEC));
200        }
201
202
203        public String getOutputFolderName() {
204                return outputFolderName;
205        }
206
207        private void init() {
208
209                task_processorsMap = new HashMap<String, List<String>>();
210                accStats = new GSSAccumulatorsStats();
211                statsData = new HashMap<String, GSSAccumulator>();
212        }
213
214        public void saveSimulationStatistics() {
215                PrintStream simulationStatsFile = null;
216                if (configuration.createsimulationstatistics) {
217                        try {
218                                File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
219                                                + SIMULATION_STATISTICS_OUTPUT_FILE_NAME);
220                                simulationStatsFile = new PrintStream(new FileOutputStream(file));
221                        } catch (IOException e) {
222                                e.printStackTrace();
223                        }
224                }
225                if (simulationStatsFile != null) {
226                        Object txt = accStats.serialize(this.serializer);
227                        simulationStatsFile.println(txt);
228                }
229
230                if (simulationStatsFile != null) {
231                        simulationStatsFile.close();
232                }
233
234        }
235
236
237
238        /************* RESOURCE STATISTICS SECTION **************/
239        private void gatherResourceStatistics() {
240               
241               
242                //TEMPORARY CONFIGURATION SECTION
243                StandardResourceType [] resForAnalyze = {StandardResourceType.DataCenter, StandardResourceType.ComputingNode, StandardResourceType.Processor};
244                HashMap<StandardResourceType, List<Stats>> type_stats = new HashMap<StandardResourceType, List<Stats>>();
245               
246                List<Stats> crStats = new ArrayList<Stats>();
247                crStats.add(Stats.textLoad);
248                crStats.add(Stats.chartLoad);
249                crStats.add(Stats.textEnergy);
250                crStats.add(Stats.chartEnergy);
251                type_stats.put(StandardResourceType.DataCenter, crStats);
252               
253                List<Stats> cnStats = new ArrayList<Stats>();
254                cnStats.add(Stats.textLoad);
255                cnStats.add(Stats.chartLoad);
256                cnStats.add(Stats.textEnergy);
257                cnStats.add(Stats.chartEnergy);
258                type_stats.put(StandardResourceType.ComputingNode, cnStats);
259               
260                List<Stats> cpuStats = new ArrayList<Stats>();
261                cpuStats.add(Stats.textLoad);
262                cpuStats.add(Stats.chartLoad);
263                cpuStats.add(Stats.textEnergy);
264                //cpuStats.add(Stats.chartEnergy);
265                type_stats.put(StandardResourceType.Processor, cpuStats);
266               
267               
268               
269                peGanttMap = new HashMap<String, TimetableEventSource>();
270                taskGanttMap = new HashMap<String, TimetableEventGroup>();
271               
272               
273                resourceLoadDiagrams = new HashMap<ResourceType, List<XYDataset>>();
274                resourceEnergyDiagrams = new HashMap<ResourceType, List<XYDataset>>();
275               
276                ganttDiagramPeTimetable = new Timetable(new FixedMillisecond(
277                                startSimulationTime), new FixedMillisecond(endSimulationTime));
278               
279                PrintStream resourceLoadStatsFile = null;
280                try {
281                        File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX
282                                        + simulationIdentifier + "_"
283                                        + RESOURCEUSAGE_STATISTICS_OUTPUT_FILE_NAME);
284                        resourceLoadStatsFile = new PrintStream(new FileOutputStream(file));
285                } catch (IOException e) {
286                        resourceLoadStatsFile = null;
287                }
288               
289                PrintStream energyStatsFile = null;
290                try {
291                        File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX
292                                        + simulationIdentifier + "_"
293                                        + ENERGYUSAGE_STATISTICS_OUTPUT_FILE_NAME);
294                        energyStatsFile = new PrintStream(new FileOutputStream(file));
295                } catch (IOException e) {
296                        energyStatsFile = null;
297                }
298                JobRegistry jr = new JobRegistryImpl("stats");
299                basicResStats = gatherPEStats(jr.getExecutableTasks());
300                peStatsPostProcessing(basicResStats);
301                basicResLoad = calculatePELoad( basicResStats);
302
303                if (configuration.creatediagrams_processors) {
304                        createPEGanttDiagram(basicResStats);
305                }
306               
307                for(StandardResourceType resType: resForAnalyze){
308                        List<ComputingResource> resources = null;
309                        try {
310                                resources = new ArrayList<ComputingResource>();
311                                for(ComputingResource compRes: resourceController.getComputingResources() ){
312                                        resources.addAll(compRes.getDescendantsByType(resType));
313                                }
314                                /*if(resourceController.getComputingResources().get(0).getType().equals(resType))
315                                        resources.addAll(resourceController.getComputingResources());*/
316                        } catch (Exception e) {
317                                continue;
318                        }
319                        if(type_stats.containsKey(resType)){
320                                Map<String, GSSAccumulator> energyCategoryStats = new TreeMap<String, GSSAccumulator>();
321                                Map<String, GSSAccumulator> loadCategoryStats = new TreeMap<String, GSSAccumulator>();
322                                for(ComputingResource resource: resources){
323                                        ResourceUsageStats resourceUsage = null;
324                                        ResourceEnergyStats energyUsage = null;
325                                        if(type_stats.get(resType).contains(Stats.textLoad)){
326                                                resourceUsage = gatherResourceLoadStats(resource, basicResStats);
327                                                resourceUsage.setMeanUsage(calculateResourceLoad(resource, basicResLoad));
328                                                if (resourceLoadStatsFile != null) {
329                                                        Object txt = resourceUsage.serialize(serializer);
330                                                        resourceLoadStatsFile.println(txt);
331                                                }
332                                        }
333                                        if(type_stats.get(resType).contains(Stats.chartLoad)){
334                                                if (configuration.creatediagrams_resources) {
335                                                        createResourceLoadDiagram(resourceUsage);
336                                                }
337                                        }
338                                        if(type_stats.get(resType).contains(Stats.textEnergy)){
339                                                energyUsage = gatherResourceEnergyStats(resource);
340                                                energyUsage.setMeanUsage(calculateEnergyLoad(energyUsage));
341                                                energyUsage.setSumUsage(energyUsage.getMeanUsage() * (endSimulationTime - startSimulationTime) / (3600 * MILLI_SEC));
342                                               
343                                                EnergyExtension een = (EnergyExtension )(resource.getExtensionList().getExtension(ExtensionType.ENERGY_EXTENSION));
344                                                if(resourceController.getComputingResources().contains(resource)) {
345                                                        if( een != null /*&& een.getPp() != null*/ ){
346                                                                accStats.meanEnergyUsage.add(energyUsage.meanUsage);
347                                                        }
348
349                                                } else if( een != null && een.getPowerProfile() != null ){
350                                                        ComputingResource parent = resource.getParent();
351                                                        een = (EnergyExtension )(parent.getExtensionList().getExtension(ExtensionType.ENERGY_EXTENSION));
352                                                        boolean top = true;
353                                                        while(parent != null){
354                                                                if(een != null &&  een.getPowerProfile() != null)
355                                                                {
356                                                                        top = false;
357                                                                        break;
358                                                                }
359                                                                parent = parent.getParent();
360                                                        }
361                                                        if(top == true){
362                                                                accStats.meanEnergyUsage.add(energyUsage.meanUsage);
363                                                        }
364                                                }
365                                                if (energyStatsFile != null) {
366                                                        Object txt = energyUsage.serialize(serializer);
367                                                        energyStatsFile.println(txt);
368                                                }
369                                        }
370                                        if(type_stats.get(resType).contains(Stats.chartEnergy)){
371
372                                                if (configuration.creatediagrams_energyusage) {
373                                                        createResourceEnergyGanttDiagram(energyUsage);
374                                                }
375                                        }
376                                       
377                                        /*if(resType == ResourceType.ComputingNode){
378                                                ComputingNode compNode = (ComputingNode) resource;
379                                                if(energyCategoryStats.containsKey(resType+"#"+compNode.getCategory().getName())){
380                                                        GSSAccumulator acc = energyCategoryStats.get(resType+"#"+compNode.getCategory().getName());
381                                                        acc.add(energyUsage.meanUsage);
382                                                        energyCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
383                                                } else{
384                                                        GSSAccumulator acc = new GSSAccumulator();
385                                                        acc.add(energyUsage.meanUsage);
386                                                        energyCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
387                                                }
388                                               
389                                                if(loadCategoryStats.containsKey(resType+"#"+compNode.getCategory().getName())){
390                                                        GSSAccumulator acc = loadCategoryStats.get(resType+"#"+compNode.getCategory().getName());
391                                                        acc.add(resourceUsage.meanUsage);
392                                                        loadCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
393                                                } else{
394                                                        GSSAccumulator acc = new GSSAccumulator();
395                                                        acc.add(resourceUsage.meanUsage);
396                                                        loadCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
397                                                }
398                                        } else if(resType == ResourceType.Processor){
399                                                Processor proc = (Processor)resource;
400                                                if(energyCategoryStats.containsKey(resType+"#"+proc.getComputingNode().getCategory().getName())){
401                                                        GSSAccumulator acc = energyCategoryStats.get(resType+"#"+proc.getComputingNode().getCategory().getName());
402                                                        acc.add(energyUsage.meanUsage);
403                                                        energyCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
404                                                } else{
405                                                        GSSAccumulator acc = new GSSAccumulator();
406                                                        acc.add(energyUsage.meanUsage);
407                                                        energyCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
408                                                }
409                                               
410                                                if(loadCategoryStats.containsKey(resType+"#"+proc.getComputingNode().getCategory().getName())){
411                                                        GSSAccumulator acc = loadCategoryStats.get(resType+"#"+proc.getComputingNode().getCategory().getName());
412                                                        acc.add(resourceUsage.meanUsage);
413                                                        loadCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
414                                                } else{
415                                                        GSSAccumulator acc = new GSSAccumulator();
416                                                        acc.add(resourceUsage.meanUsage);
417                                                        loadCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
418                                                }
419                                        }*/
420                                }
421                               
422                                if(energyCategoryStats.size() > 0)
423                                {
424                                        energyStatsFile.println("\n=========BY CATEGORY===========");
425                                        for(String key: energyCategoryStats.keySet()){
426                                                GSSAccumulator acc = energyCategoryStats.get(key);
427                                                energyStatsFile.println(key + "- mean: "  + acc.getMean()+ " sum: " +acc.getMean() * (endSimulationTime-startSimulationTime) / (3600 * MILLI_SEC) * acc.getCount());
428                                        }
429                                        energyStatsFile.println("\n\n");
430                                }
431                               
432                                if(loadCategoryStats.size() > 0)
433                                {
434                                        resourceLoadStatsFile.println("\n=========BY CATEGORY===========");
435                                        for(String key: loadCategoryStats.keySet()){
436                                                GSSAccumulator acc = loadCategoryStats.get(key);
437                                                resourceLoadStatsFile.println(key + "- mean: "  + acc.getMean());
438                                        }
439                                        resourceLoadStatsFile.println("\n\n");
440                                }
441                        }
442                }
443               
444                saveResourceGanttDiagrams();
445                createAccumulatedResourceSimulationStatistic();
446                if (energyStatsFile != null) {
447                        energyStatsFile.close();
448                }
449                if (resourceLoadStatsFile != null) {
450                        resourceLoadStatsFile.close();
451                }
452        }
453       
454        private double getSchedulerQueueStats(Scheduler scheduler) {
455
456                Sim_stat stats = scheduler.get_stat();
457                List<Object[]> measures = stats.get_measures();
458                for (Object[] info : measures) {
459                        String measure = (String) info[0];
460                        if (measure
461                                        .startsWith(DCWormsConstants.TASKS_QUEUE_LENGTH_MEASURE_NAME)) {
462                                return stats.average(measure);
463                        }
464                }
465                return 0;
466        }
467       
468        private void peStatsPostProcessing(Map<String, List<ResStat>> basicResStats){
469                ResourceType resType = null;
470
471                for(String key: basicResStats.keySet()){
472                        List<ResStat> resStats = basicResStats.get(key);
473                        resType = resStats.get(0).getResType();
474                        break;
475                }
476                List<ComputingResource> resources = null;
477                try {
478                        resources = new ArrayList<ComputingResource>();
479                        for(ComputingResource compRes: resourceController.getComputingResources() ){
480                                resources.addAll(compRes.getDescendantsByType(resType));
481                        }
482                } catch (Exception e) {
483                        return;
484                }
485                for(ComputingResource resource: resources){
486                        if(!basicResStats.containsKey(resource.getName())){
487                                basicResStats.put(resource.getName(), new ArrayList<ResStat>());
488                        }
489                }
490        }
491        private Map<String, List<ResStat>> gatherPEStats( ExecutablesList executables) {
492
493               
494                Map<String, List<ResStat>> basicResStats = new TreeMap<String, List<ResStat>>(new MapPEIdComparator());
495                //Map<Integer, Map<String, Object>> history
496               
497                for (ExecTask execTask:executables) {
498                        Executable exec = (Executable) execTask;
499
500                        List<ResourceHistoryItem> resHistItemList = exec.getUsedResources();
501                        Map<ResourceUnitName, ResourceUnit> res = resHistItemList.get(resHistItemList.size() - 1).getResourceUnits();
502                        ResourceUnit resUnit = res.get(StandardResourceUnitName.PE);
503                        //ProcessingElements pes = (ProcessingElements) resUnit ;
504                        if(resUnit instanceof ProcessingElements ){
505                                ProcessingElements pes = (ProcessingElements) resUnit;
506                                for(ComputingResource pe: pes){
507                                        String peName = pe.getName();
508                                        long startDate = Double.valueOf(exec.getExecStartTime()).longValue() * MILLI_SEC;
509                                        long endDate = Double.valueOf(exec.getFinishTime()).longValue() * MILLI_SEC;
510
511
512                                        String uniqueTaskID = execTask.getJobId() + "_" + execTask.getId();
513                                       
514                                        ResStat resStat = new ResStat(peName, pe.getType(), startDate, endDate, uniqueTaskID);
515                                       
516                                        List<ResStat> resStats = basicResStats.get(peName);
517                                        if (resStats == null) {
518                                                resStats = new ArrayList<ResStat>();
519                                                resStats.add(resStat);
520                                                basicResStats.put(peName, resStats);
521                                        } else {
522                                                resStats.add(resStat);
523                                        }
524
525                                        List<String> peNames = task_processorsMap.get(uniqueTaskID);
526                                        if (peNames == null) {
527                                                peNames = new ArrayList<String>();
528                                                peNames.add(peName);
529                                                task_processorsMap.put(uniqueTaskID, peNames);
530                                        } else {
531                                                peNames.add(peName);
532                                        }
533                                }
534                        } else if (resUnit instanceof PEUnit){
535                                PEUnit peUnit = (PEUnit) resUnit ;
536                        }
537
538                }
539                return basicResStats;
540        }
541       
542        private ResourceUsageStats gatherResourceLoadStats(ComputingResource resource, Map<String,List<ResStat>> basicStats) {
543                ResourceUsageStats usageStats = new ResourceUsageStats(resource.getName(), resource.getType(), "resourceLoadStats");
544                for(String resName: basicStats.keySet()){
545                        try {
546                                if(resource.getDescendantByName(resName) != null || resource.getName().compareTo(resName) == 0){
547                                        createResourceLoadData(usageStats, basicStats.get(resName));
548                                }
549                        } catch (ResourceException e) {
550                                // TODO Auto-generated catch block
551                                e.printStackTrace();
552                        }
553                }
554                return usageStats;
555        }
556       
557        private TreeMap<Long, Integer> createResourceLoadData(ResourceUsageStats usageStats, List<ResStat> resStats) {
558
559                TreeMap<Long, Integer> ganttData = (TreeMap)usageStats.getUsage();
560                for (ResStat resStat : resStats) {
561                       
562                        long start_time = resStat.getStartDate();
563                        long end_time = resStat.getEndDate();
564                        if (end_time > start_time) {
565                                Integer end = ganttData.get(end_time);
566                                if (end == null) {
567                                        ganttData.put(end_time, 0);
568                                        Long left = getLeftKey(ganttData, end_time);
569                                        if (left != null) {
570                                                Integer leftValue = ganttData.get(left);
571                                                ganttData.put(end_time, leftValue);
572                                        }
573                                }
574
575                                Integer start = ganttData.get(start_time);
576                                if (start == null) {
577                                        ganttData.put(start_time, 0);
578                                        Long left = getLeftKey(ganttData, start_time);
579                                        if (left != null) {
580                                                Integer leftValue = ganttData.get(left);
581                                                ganttData.put(start_time, leftValue);
582                                        }
583                                }
584
585                                SortedMap<Long, Integer> sm = ganttData.subMap(start_time,
586                                                end_time);
587                                for (Long key : sm.keySet()) {
588                                        Integer keyVal = ganttData.get(key);
589                                        ganttData.put(key, keyVal + 1);
590                                }
591                        }
592                }
593                return ganttData;
594        }
595
596        private Long getLeftKey(TreeMap<Long, Integer> ganttData, Long toKey) {
597
598                SortedMap<Long, Integer> sm = ganttData.headMap(toKey);
599                if (sm.isEmpty()) {
600                        return null;
601                }
602                return sm.lastKey();
603        }
604       
605       
606        private ResourceEnergyStats gatherResourceEnergyStats(ComputingResource resource) {
607                double power = 0;
608                ResourceEnergyStats resEnergyUsage = new ResourceEnergyStats(resource.getName(), resource.getType(), "resourceEnergyStats");
609                Map<Long, Double> usage = resEnergyUsage.getEnergy();
610               
611                ExtensionList extensionList = resource.getExtensionList();
612                if(extensionList != null){
613                        for (Extension extension : extensionList) {
614                                if (extension.getType() == ExtensionType.ENERGY_EXTENSION) {
615                                        EnergyExtension ee = (EnergyExtension)extension;
616                                        if(ee.getPowerProfile() == null)
617                                                break;
618                                        List<PowerUsage> powerUsage = ee.getPowerProfile().getPowerUsageHistory();
619                                        if(powerUsage.size() == 0)
620                                                break;
621                                        long lastTime = DateTimeUtilsExt.getOffsetTime().getTimeInMillis();
622                                        long endSimulationTime = DateTimeUtilsExt.currentTimeMillis();
623                                        double lastPower = 0;
624                                        powerUsage.add(new PowerUsage(endSimulationTime, ee.getPowerProfile().getPowerUsageHistory().get(ee.getPowerProfile().getPowerUsageHistory().size()-1).getValue()));
625                                        for(PowerUsage pu:powerUsage){
626                                                usage.put(pu.getTimestamp(), pu.getValue());
627                                               
628                                        ///     System.out.println(resource.getName() + ":"+new DateTime(pu.getTimestamp())+";"+pu.getValue());
629                                                power = power + (pu.getTimestamp() - lastTime) * lastPower/ (3600 * MILLI_SEC);
630                                                lastPower = pu.getValue();
631                                                lastTime = pu.getTimestamp();
632                                        }
633                                }
634                        }
635                }
636                //System.out.println(power);
637                return resEnergyUsage;
638        }
639       
640        private void createResourceEnergyGanttDiagram(ResourceEnergyStats energyUsage) {
641
642                XYDataset dataset = createResourceEnergyGanttDataSet(energyUsage,
643                                startSimulationTime, endSimulationTime);
644               
645                List<XYDataset> energyDiagram = resourceEnergyDiagrams.get(energyUsage.getResourceType());
646                if(energyDiagram == null){
647                        energyDiagram = new ArrayList<XYDataset>();
648                        energyDiagram.add(dataset);
649                        resourceEnergyDiagrams.put(energyUsage.getResourceType(), energyDiagram);
650                } else {
651                        energyDiagram.add(dataset);
652                }
653
654        }
655
656        private XYDataset createResourceEnergyGanttDataSet(
657                        ResourceEnergyStats energyUsage, long start, long end) {
658
659                TreeMap<Long, Double> ganttdata = createResourceEnergyGanttData(energyUsage);
660                XYSeriesCollection dataset = new XYSeriesCollection();
661                XYSeries data = new XYSeries(energyUsage.getResourceName(), false, true);
662                //data.add(start, 0);
663                for (Long key : ganttdata.keySet()) {
664                        Double val = ganttdata.get(key);
665                        data.add(key, val);
666                }
667                data.add(end, 0);
668                dataset.addSeries(data);
669                return dataset;
670        }
671
672        private TreeMap<Long, Double> createResourceEnergyGanttData(
673                        ResourceEnergyStats energyUsage) {
674
675                Map<Long, Double> energy = energyUsage.getEnergy();
676                TreeMap<Long, Double> ganttData = new TreeMap<Long, Double>();
677                for (Long euKey : energy.keySet()) {
678
679                        ganttData.put(euKey, energy.get(euKey));
680                }
681                return ganttData;
682        }
683
684
685        private boolean saveResourceGanttDiagrams() {
686                JFreeChart resourceDiagram = null;
687                JFreeChart peDiagram = null;
688                JFreeChart resourceEnergyDiagram = null;
689                if (!generateDiagrams)
690                        return false;
691
692                String fileName = new File(outputFolderName, DIAGRAMS_FILE_NAME_PREFIX
693                                + simulationIdentifier + "_").getAbsolutePath();
694
695                String chartName = "Gantt diagram for "
696                                + DataCenterWorkloadSimulator.SIMULATOR_NAME;
697                String simulationTime = "Simulation time";
698                Title subtitle = new TextTitle("created for \"" + simulationIdentifier
699                                + "\" at " + Calendar.getInstance().getTime().toString());
700
701               
702                if (configuration.creatediagrams_processors) {
703                        peDiagram = getPeGanttDiagram(chartName, subtitle,
704                                        simulationTime);
705                        if (!saveCategoryChart(peDiagram, fileName + "Gantt",
706                                        "{0}"))
707                                return false;
708                }
709
710                if (configuration.creatediagrams_resources) {
711                        for(ResourceType resType: resourceLoadDiagrams.keySet()){
712                                resourceDiagram = getResourcesLoadDiagram(resType, chartName, subtitle,
713                                                simulationTime);
714                                if (!saveXYPlotChart(resourceDiagram, fileName + "Resources Load - "+resType))
715                                        return false;
716                        }
717
718                }
719                if (configuration.creatediagrams_energyusage) {
720                        for(ResourceType resType: resourceEnergyDiagrams.keySet()){
721                                resourceEnergyDiagram = getResourcesEnergyDiagram(resType, chartName,
722                                                subtitle, simulationTime);
723                                if (!saveXYPlotChart(resourceEnergyDiagram, fileName + "Energy - "+resType))
724                                        return false;
725                        }
726                }
727                return true;
728        }
729       
730        private JFreeChart getResourcesLoadDiagram(ResourceType resType, String chartName, Title subtitle,
731                        String simulationTime) {
732                String cpu = "CPU";
733                boolean urls = false;
734                boolean tooltip = true;
735                boolean legend = true;
736                CombinedDomainXYPlot cPlot = new CombinedDomainXYPlot();
737                DateAxis xAxis = new DateAxis(simulationTime);
738                JFreeChart chart = null;
739
740                List<XYDataset> loadDiagram = resourceLoadDiagrams.get(resType);
741                for (XYDataset dataset : loadDiagram) {
742                        JFreeChart tChart = ChartFactory.createXYStepAreaChart("", "",
743                                null, dataset, PlotOrientation.VERTICAL, legend, tooltip,
744                                urls);
745                        XYPlot tPlot = tChart.getXYPlot();
746                        NumberAxis yAxis = new NumberAxis(cpu);
747                        yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
748                        tPlot.setRangeAxis(yAxis);
749                        XYStepAreaRenderer rend = (XYStepAreaRenderer) tPlot.getRenderer();
750                        rend.setShapesVisible(false);
751                        cPlot.add(tPlot);
752                }
753                cPlot.setDomainAxis(xAxis);
754                cPlot.setDomainAxisLocation(AxisLocation.TOP_OR_LEFT);
755                chart = new JFreeChart(chartName, cPlot);
756                chart.addSubtitle(subtitle);
757                return chart;
758        }
759
760        private JFreeChart getResourcesEnergyDiagram(ResourceType resType, String chartName,
761                        Title subtitle, String simulationTime) {
762                String energy = "ENERGY [W]";
763                boolean urls = false;
764                boolean tooltip = true;
765                boolean legend = true;
766                CombinedDomainXYPlot cPlot = new CombinedDomainXYPlot();
767                DateAxis xAxis = new DateAxis(simulationTime);
768
769                List<XYDataset> energyDiagram = resourceEnergyDiagrams.get(resType);
770                for (XYDataset dataset : energyDiagram) {
771
772                        JFreeChart tChart = ChartFactory.createXYStepAreaChart("", "",
773                                        null, dataset, PlotOrientation.VERTICAL, legend, tooltip,
774                                        urls);
775
776                        XYPlot tPlot = tChart.getXYPlot();
777                        NumberAxis yAxis = new NumberAxis(energy);
778                        yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
779                        tPlot.setRangeAxis(yAxis);
780                        XYStepAreaRenderer rend = (XYStepAreaRenderer) tPlot.getRenderer();
781                        rend.setShapesVisible(false);
782                        cPlot.add(tPlot);
783                }
784                cPlot.setDomainAxis(xAxis);
785                cPlot.setDomainAxisLocation(AxisLocation.TOP_OR_LEFT);
786                JFreeChart chart = new JFreeChart(chartName, cPlot);
787                chart.addSubtitle(subtitle);
788                return chart;
789        }
790       
791       
792        private JFreeChart getPeGanttDiagram(String chartName, Title subtitle,
793                        String simulationTime) {
794                String processors = "Processing Elements";
795                boolean tooltip = true;
796                boolean legend = true;
797                JFreeChart chart = TimetableChartFactory.createTimetableChart(
798                                chartName, processors, simulationTime,
799                                ganttDiagramPeTimetable, legend, tooltip);
800                chart.addSubtitle(subtitle);
801                TimetableRenderer rend = (TimetableRenderer) chart.getCategoryPlot()
802                                .getRenderer();
803                rend.setBackgroundBarPaint(null);
804                return chart;
805        }
806       
807       
808        private boolean saveXYPlotChart(JFreeChart c, String fileName) {
809                c.setNotify(false);
810                c.setAntiAlias(true);
811                c.setTextAntiAlias(true);
812                c.setBorderVisible(false);
813
814                int height = 900;
815
816                CombinedDomainXYPlot cPlot = (CombinedDomainXYPlot) c.getPlot();
817                int nPlots = cPlot.getSubplots().size();
818
819                if (nPlots > 3) {
820                        height = nPlots * 300;
821                }
822                int width = GANTT_WIDTH;
823
824                if (configuration.creatediagrams_resources_scale != -1)
825                        width = (int) ((endSimulationTime - startSimulationTime) * configuration.creatediagrams_resources_scale);
826                ChartRenderingInfo info = new ChartRenderingInfo();
827                File f = new File(fileName + "." + ImageFormat.PNG);
828                final String gssimSubtitle = "Created by "
829                                + DataCenterWorkloadSimulator.SIMULATOR_NAME
830                                + " http://www.gssim.org/";
831                c.addSubtitle(new TextTitle(gssimSubtitle));
832                boolean encodeAlpha = false;
833                int compression = 9;// values 0-9
834                try {
835                        ChartUtilities.saveChartAsPNG(f, c, width, height, info,
836                                        encodeAlpha, compression);
837                } catch (IOException e) {
838                        e.printStackTrace();
839                        return false;
840                }
841                return true;
842        }
843       
844        private void createPEGanttDiagram(Map<String,List<ResStat>> basicResStats) {
845                for(String peName: basicResStats.keySet()){
846                        TimetableEventSource pe = new TimetableEventSource(peName);
847                        ganttDiagramPeTimetable.addEventSource(pe);
848                        peGanttMap.put(peName, pe);
849                        for(ResStat resStat: basicResStats.get(peName)){
850
851                                pe = peGanttMap.get(resStat.getPeName());
852                                if(pe == null){
853                                        //pe = new TimetableEventSource(resStat.getPeName());
854                                //      ganttDiagramPeTimetable.addEventSource(pe);
855                                //      peGanttMap.put(resStat.getPeName(), pe);
856                                }
857                                TimetableEventGroup task = taskGanttMap.get(resStat.getTaskID());
858                                long startDate = resStat.getStartDate();
859                                long endDate = resStat.getEndDate();
860                                if (task == null) {
861                                        task = new TimetableEventGroup(resStat.getTaskID());
862                                        taskGanttMap.put(resStat.getTaskID(), task);
863                                        ganttDiagramPeTimetable.addEventGroup(task);
864                                }
865                                ganttDiagramPeTimetable.addEvent(pe, task,
866                                                new FixedMillisecond(startDate), new FixedMillisecond(endDate));
867                        }
868                }
869        }
870
871        private void createResourceLoadDiagram(ResourceUsageStats resStats) {
872
873                XYDataset dataset = createResourceLoadDataSet(resStats);
874
875                List<XYDataset> loadDiagram = resourceLoadDiagrams.get(resStats.getResourceType());
876                if(loadDiagram == null){
877                        loadDiagram = new ArrayList<XYDataset>();
878                        loadDiagram.add(dataset);
879                        resourceLoadDiagrams.put(resStats.getResourceType(), loadDiagram);
880                } else {
881                        loadDiagram.add(dataset);
882                }
883        }
884
885        private XYDataset createResourceLoadDataSet(ResourceUsageStats resStats) {
886
887                XYSeriesCollection dataset = new XYSeriesCollection();
888                XYSeries data = new XYSeries(resStats.resourceName, false, true);
889                Map<Long, Integer> usage = resStats.getUsage();
890               
891                for (Long key : usage.keySet()) {
892                        Integer val = usage.get(key);
893                        double newv =100*val/basicResStats.size();
894                        int newinv = (int)newv;
895                        data.add(key, new Integer(newinv));
896                }
897                dataset.addSeries(data);
898                return dataset;
899        }
900
901        private void createAccumulatedResourceSimulationStatistic() {
902
903                List<ComputingResource> resources = resourceController.getComputingResources();
904                for(ComputingResource compRes: resources){
905                        //for(ComputingResource child :compRes.getChildren()){
906                                double load = calculateResourceLoad(compRes, basicResLoad);
907                                accStats.meanTotalLoad.add(load);
908                                /*ResourceEnergyStats energyUsage = gatherResourceEnergyStats(compRes);
909                                energyUsage.setMeanUsage(calculateEnergyLoad(energyUsage));
910                                accStats.meanEnergyUsage.add(energyUsage.meanUsage);*/
911                        //}     
912                }
913        }
914
915        private HashMap<String, Double> calculatePELoad(Map<String,List<ResStat>> basicResStats){
916                HashMap<String, Double> peLoad = new HashMap<String, Double>();
917                for(String resName: basicResStats.keySet()){
918                        List<ResStat> resStats = basicResStats.get(resName);
919                        double sum = 0;
920                        for(ResStat resStat:resStats){
921                                sum += (resStat.endDate - resStat.startDate);
922                        }
923                        double load = sum / (endSimulationTime - startSimulationTime);
924                        peLoad.put(resName, load);
925                }
926                return peLoad;
927        }
928       
929        private  Double calculateResourceLoad(ComputingResource resource, HashMap<String, Double> peLoad ){
930                int peCnt = 0;
931                double sum = 0;
932                for(String resName: peLoad.keySet()){
933
934                        try {
935                                if(resource.getDescendantByName(resName) != null || resource.getName().compareTo(resName) == 0){
936                                        Double load = peLoad.get(resName);
937                                        sum += load;
938                                        peCnt++;
939                                }
940                        } catch (ResourceException e) {
941                                // TODO Auto-generated catch block
942                                e.printStackTrace();
943                        }
944                }
945               
946                return sum/peCnt;
947        }
948       
949        private double calculateEnergyLoad(ResourceEnergyStats resEnergyStats ){
950                double meanEnergyUsage = 0;
951                long time = 0;
952                double usage = 0;
953                Map<Long, Double> enUsage = resEnergyStats.getEnergy();
954                for (Long key : enUsage.keySet()) {
955                       
956                        if (time != 0) {
957                                meanEnergyUsage += (usage * (key - time))
958                                                / (endSimulationTime - startSimulationTime);
959
960                                time = key;
961                        } else {
962                                time = key;
963                        }
964                        usage = (double) enUsage.get(key);
965                }
966                return meanEnergyUsage;
967        }
968       
969        /*private void createPEGanttDiagram(String peName,
970                        String uniqueTaskID, Map<String, Object> historyItem) {
971                TimetableEventSource pe = peGanttMap.get(peName);
972                if(pe == null){
973                        pe = new TimetableEventSource(peName);
974                        ganttDiagramPETimetable.addEventSource(pe);
975                        peGanttMap.put(peName, pe);
976                }
977                TimetableEventGroup task = taskGanttMap.get(uniqueTaskID);
978                long startDate = ((DateTime) historyItem.get(GssimConstants.START_TIME))
979                                .getMillis();
980                long endDate = ((DateTime) historyItem.get(GssimConstants.END_TIME))
981                                .getMillis();
982                if (task == null) {
983                        task = new TimetableEventGroup(uniqueTaskID);
984                        taskGanttMap.put(uniqueTaskID, task);
985                        ganttDiagramPETimetable.addEventGroup(task);
986                }
987                ganttDiagramPETimetable.addEvent(pe, task,
988                                new FixedMillisecond(startDate), new FixedMillisecond(endDate));
989        }*/
990       
991
992
993        /************* TASK STATISTICS SECTION **************/
994        public void gatherTaskStatistics() {
995
996                List<JobInterface<?>> jobs = users.getAllReceivedJobs();
997                Collections.sort(jobs, new JobIdComparator());
998
999                ganttDiagramTaskSeriesCollection = new TaskSeriesCollection();
1000                ganttDiagramWaitingTimeSeriesCollection = new TaskSeriesCollection();
1001
1002                PrintStream taskStatsFile = null;
1003                try {
1004                        File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
1005                                        + RAW_TASKS_STATISTICS_OUTPUT_FILE_NAME);
1006                        taskStatsFile = new PrintStream(new FileOutputStream(file));
1007                } catch (IOException e) {
1008                        taskStatsFile = null;
1009                }
1010
1011                PrintStream jobStatsFile = null;
1012                if (configuration.createjobsstatistics) {
1013                        try {
1014                                File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
1015                                                + JOBS_STATISTICS_OUTPUT_FILE_NAME);
1016                                jobStatsFile = new PrintStream(new FileOutputStream(file));
1017                        } catch (IOException e) {
1018                                jobStatsFile = null;
1019                        }
1020                }
1021
1022                for (int i = 0; i < jobs.size(); i++) {
1023                        Job job = (Job) jobs.get(i);
1024
1025                        //List<TaskInterface> execList = JobRegistry.getInstance("COMPUTING_GRID_0#BROKER").getAllSubmittedTasks();
1026                        List<Executable> execList = jr.getExecutableTasks().getJobExecutables(job.getId());
1027                        List<TaskStats> taskStatsList = new ArrayList<TaskStats>();
1028
1029                        this.serializer.setFieldSeparator(TASK_SEPARATOR);
1030
1031                        for (int j = 0; j < execList.size(); j++) {
1032
1033                                Executable task = (Executable) execList.get(j);
1034
1035                                TaskStats taskStats = createTaskStats(task);
1036                                if (taskStats != null && taskStatsFile != null) {
1037                                        Object txt = taskStats.serialize(serializer);
1038                                        taskStatsFile.println(txt);
1039                                }
1040                                if (taskStats != null && taskStats.getExecFinishDate() != -1) {
1041                                        if (configuration.createsimulationstatistics) {
1042                                                createAccumulatedTaskSimulationStatistic(taskStats);
1043                                        }
1044                                        allTasksFinished &= task.isFinished();
1045                                        if (generateDiagrams) {
1046                                                if (configuration.creatediagrams_tasks)
1047                                                        createTaskDiagramData(task);
1048                                                if (configuration.creatediagrams_taskswaitingtime)
1049                                                        createTaskWaitingTimeDiagramData(task);
1050                                        }
1051                                        taskStatsList.add(taskStats);
1052                                }
1053                        }
1054                        if (configuration.createjobsstatistics && taskStatsList.size() > 0) {
1055
1056                                this.serializer.setFieldSeparator(JOB_SEPARATOR);
1057                                JobStats jobStats = createJobStats(taskStatsList);
1058                                if (jobStatsFile != null) {
1059                                        Object txt = jobStats.serialize(serializer);
1060                                        jobStatsFile.println(txt);
1061                                }
1062                        }
1063                }
1064
1065                if (configuration.createsimulationstatistics) {
1066                        accStats.makespan.add(maxCj);
1067                        accStats.delayedTasks.add(numOfdelayedTasks);
1068                        accStats.failedRequests.add(users.getAllSentTasks().size() - users.getFinishedTasksCount());
1069                        if(resourceController.getScheduler().getType().getName().equals("GS")){
1070                                for(Scheduler sched: resourceController.getScheduler().getChildren()){
1071                                        accStats.meanQueueLength.add(getSchedulerQueueStats(sched));
1072                                }
1073                        }
1074                        else {
1075                                accStats.meanQueueLength.add(getSchedulerQueueStats(resourceController.getScheduler()));
1076                        }
1077                }
1078
1079                saveTaskGanttDiagrams();
1080
1081                if (taskStatsFile != null) {
1082                        taskStatsFile.close();
1083                }
1084                if (jobStatsFile != null) {
1085                        jobStatsFile.close();
1086                }
1087        }
1088
1089        private TaskStats createTaskStats(Executable task) {
1090                TaskStats taskStats = new TaskStats(task, startSimulationTime);
1091                String uniqueTaskID = taskStats.getJobID() + "_" + taskStats.getTaskID();
1092                taskStats.setProcessorsName(task_processorsMap.get(uniqueTaskID));
1093                return taskStats;
1094        }
1095
1096        private JobStats createJobStats(List<TaskStats> tasksStats) {
1097
1098                String jobID = ((TaskStats) tasksStats.get(0)).getJobID();
1099                JobStats jobStats = new JobStats(jobID);
1100                double maxCj = 0;
1101
1102                for (int i = 0; i < tasksStats.size(); i++) {
1103
1104                        TaskStats task = (TaskStats) tasksStats.get(i);
1105                        jobStats.meanTaskStartTime.add(task.getStartTime());
1106                        jobStats.meanTaskCompletionTime.add(task.getCompletionTime());
1107                        maxCj = Math.max(maxCj, task.getCompletionTime());
1108                        jobStats.meanTaskExecutionTime.add(task.getExecutionTime());
1109                        jobStats.meanTaskWaitingTime.add(task.getWaitingTime());
1110                        jobStats.meanTaskFlowTime.add(task.getFlowTime());
1111                        jobStats.meanTaskGQ_WaitingTime.add(task.getGQ_WaitingTime());
1112                        jobStats.lateness.add(task.getLateness());
1113                        jobStats.tardiness.add(task.getTardiness());
1114                }
1115                jobStats.makespan.add(maxCj);
1116
1117                return jobStats;
1118        }
1119
1120        private void createAccumulatedTaskSimulationStatistic(TaskStats taskStats) {
1121                accStats.meanTaskFlowTime.add(taskStats.getFlowTime());
1122                accStats.meanTaskExecutionTime.add(taskStats.getExecutionTime());
1123                accStats.meanTaskCompletionTime.add(taskStats.getCompletionTime());
1124                accStats.meanTaskWaitingTime.add(taskStats.getWaitingTime());
1125                accStats.meanTaskStartTime.add(taskStats.getStartTime());
1126
1127                accStats.lateness.add(taskStats.getLateness());
1128                accStats.tardiness.add(taskStats.getTardiness());
1129
1130                if (taskStats.getExecFinishDate() == -1) {
1131                        numOfNotExecutedTasks++;
1132                }
1133                if (taskStats.getTardiness() > 0.0) {
1134                        numOfdelayedTasks++;
1135                }
1136
1137                maxCj = Math.max(maxCj, taskStats.getCompletionTime());
1138        }
1139
1140        private void createTaskDiagramData(Executable task) {
1141                String uniqueTaskID = task.getJobId() + "_" + task.getId();
1142
1143                String resID = task.getSchedulerName();
1144
1145                long execStartTime = Double.valueOf(task.getExecStartTime()).longValue() * MILLI_SEC;
1146                long execEndTime = Double.valueOf(task.getFinishTime()).longValue() * MILLI_SEC;
1147
1148                TaskSeries taskRes = ganttDiagramTaskSeriesCollection.getSeries(resID);
1149                if (taskRes == null) {
1150                        taskRes = new TaskSeries(resID);
1151                        ganttDiagramTaskSeriesCollection.add(taskRes);
1152                }
1153                org.jfree.data.gantt.Task ganttTask = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(execStartTime),
1154                                new Date(execEndTime));
1155                if (!task.isFinished()) {
1156                        ganttTask.setPercentComplete(1.0);
1157                }
1158                taskRes.add(ganttTask);
1159        }
1160
1161        private void createTaskWaitingTimeDiagramData(Executable task) {
1162                String uniqueTaskID = task.getJobId() + "_" + task.getId();
1163
1164                String resID = task.getSchedulerName();
1165
1166                long execStartTime = Double.valueOf(task.getExecStartTime()).longValue() * MILLI_SEC;
1167                long execEndTime = Double.valueOf(task.getFinishTime()).longValue() * MILLI_SEC;
1168
1169                TaskSeries waitRes = ganttDiagramWaitingTimeSeriesCollection.getSeries(resID);
1170                if (waitRes == null) {
1171                        waitRes = new TaskSeries(resID);
1172                        ganttDiagramWaitingTimeSeriesCollection.add(waitRes);
1173                }
1174
1175                long sub = Double.valueOf(task.getSubmissionTime()).longValue() * MILLI_SEC;
1176                org.jfree.data.gantt.Task wait_exec = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(sub), new Date(
1177                                execEndTime));
1178                org.jfree.data.gantt.Task exec = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(execStartTime), new Date(
1179                                execEndTime));
1180                if (!task.isFinished()) {
1181                        exec.setPercentComplete(1.0);
1182                }
1183                wait_exec.addSubtask(wait_exec);
1184                wait_exec.addSubtask(exec);
1185                waitRes.add(wait_exec);
1186        }
1187
1188        private boolean saveTaskGanttDiagrams() {
1189
1190                JFreeChart taskDiagram = null;
1191                JFreeChart waitingTimeDiagram = null;
1192
1193                if (!generateDiagrams)
1194                        return false;
1195
1196                String fileName = new File(outputFolderName, DIAGRAMS_FILE_NAME_PREFIX + simulationIdentifier + "_")
1197                                .getAbsolutePath();
1198
1199                String chartName = "Gantt diagram for " + DataCenterWorkloadSimulator.SIMULATOR_NAME;
1200                String simulationTime = "Simulation time";
1201                Title subtitle = new TextTitle("created for \"" + simulationIdentifier + "\" at "
1202                                + Calendar.getInstance().getTime().toString());
1203
1204                if (configuration.creatediagrams_tasks) {
1205                        taskDiagram = getTaskDiagram(chartName, subtitle, simulationTime);
1206                        if (!saveCategoryChart(taskDiagram, fileName + "Tasks", null /* "{0}" */))
1207                                return false;
1208                }
1209
1210                if (configuration.creatediagrams_taskswaitingtime) {
1211                        waitingTimeDiagram = getWaitingTimeDiagram(chartName, subtitle, simulationTime);
1212                        if (!saveCategoryChart(waitingTimeDiagram, fileName + "Waiting_Time", null /* "Task {1} at {0}" */))
1213                                return false;
1214                }
1215
1216                return true;
1217        }
1218
1219        private JFreeChart getTaskDiagram(String chartName, Title subtitle, String simulationTime) {
1220                String tasks = "Tasks";
1221                boolean urls = false;
1222                boolean tooltip = true;
1223                boolean legend = true;
1224                JFreeChart chart = ChartFactory.createGanttChart(chartName, tasks, simulationTime,
1225                                ganttDiagramTaskSeriesCollection, legend, tooltip, urls);
1226                chart.addSubtitle(subtitle);
1227                GanttRenderer re = (GanttRenderer) chart.getCategoryPlot().getRenderer();
1228                re.setCompletePaint(Color.black);
1229                return chart;
1230        }
1231
1232        private JFreeChart getWaitingTimeDiagram(String chartName, Title subtitle, String simulationTime) {
1233                String tasks = "Tasks";
1234                boolean urls = false;
1235                boolean tooltip = true;
1236                boolean legend = true;
1237                JFreeChart chart = ChartFactory.createGanttChart(chartName, tasks, simulationTime,
1238                                ganttDiagramWaitingTimeSeriesCollection, legend, tooltip, urls);
1239                chart.addSubtitle(subtitle);
1240                chart.getPlot().setForegroundAlpha(ALPHA);
1241                GanttRenderer re = (GanttRenderer) chart.getCategoryPlot().getRenderer();
1242                re.setCompletePaint(Color.black);
1243                return chart;
1244        }
1245
1246        private boolean saveCategoryChart(JFreeChart c, String fileName, String labelFormat) {
1247                c.setNotify(false);
1248                c.setAntiAlias(true);
1249                c.setTextAntiAlias(true);
1250                c.setBorderVisible(false);
1251
1252                CategoryPlot categoryplot = (CategoryPlot) c.getPlot();
1253                categoryplot.setDomainGridlinesVisible(true);
1254
1255                if (labelFormat != null) {
1256                        CategoryItemRenderer rend = categoryplot.getRenderer();
1257                        rend.setBaseItemLabelsVisible(true);
1258                        ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER);
1259                        rend.setBasePositiveItemLabelPosition(position);
1260                        NumberFormat nf = NumberFormat.getInstance();
1261                        CategoryItemLabelGenerator gen = new StandardCategoryItemLabelGenerator(labelFormat, nf);
1262                        rend.setBaseItemLabelGenerator(gen);
1263                }
1264
1265                int rows = c.getCategoryPlot().getDataset().getColumnKeys().size();
1266
1267                int height = 900;
1268                if (rows > 45) {
1269                        height = rows * 20;
1270                }
1271                int width = calculateChartWidth(c);
1272                CategoryItemRenderer rend = c.getCategoryPlot().getRenderer();
1273
1274                for (int i = 0; i < c.getCategoryPlot().getDataset().getRowKeys().size(); i++) {
1275                        Paint collor = c.getCategoryPlot().getDrawingSupplier().getNextPaint();
1276                        rend.setSeriesOutlinePaint(i, collor);
1277                        rend.setSeriesPaint(i, collor);
1278                }
1279
1280                ChartRenderingInfo info = new ChartRenderingInfo();
1281                // info.setEntityCollection(null);
1282                File f = new File(fileName + "." + ImageFormat.PNG);
1283                final String gssimSubtitle = "Created by " + DataCenterWorkloadSimulator.SIMULATOR_NAME + " http://www.gssim.org/";
1284                c.addSubtitle(new TextTitle(gssimSubtitle));
1285                boolean encodeAlpha = false;
1286                int compression = 9;
1287                try {
1288                        ChartUtilities.saveChartAsPNG(f, c, width, height, info, encodeAlpha, compression);
1289
1290                } catch (IOException e) {
1291                        e.printStackTrace();
1292                        return false;
1293                } catch (Exception e) {
1294                        if (log.isErrorEnabled())
1295                                log.error("The png file (" + fileName
1296                                                + ")\nwill not be generated (It can be too large data size problem)", e);
1297                } catch (Throwable t) {
1298                        log.error("The png file (" + fileName + ")\nwill not be generated (It can be too large data size problem)",
1299                                        t);
1300                }
1301
1302                return true;
1303        }
1304
1305        private int calculateChartWidth(JFreeChart c) {
1306
1307                int ganttWidth = GANTT_WIDTH;
1308                int rows = c.getCategoryPlot().getDataset().getColumnKeys().size();
1309
1310                if (rows > 45) {
1311                        int height = rows * 20;
1312                        ganttWidth = Math.max((int) (height * 1.5), GANTT_WIDTH);
1313                }
1314                return ganttWidth;
1315        }
1316
1317        private static class JobIdComparator implements Comparator<JobInterface<?>> {
1318
1319                public int compare(JobInterface<?> o1, JobInterface<?> o2) {
1320
1321                        Integer o1int;
1322                        Integer o2int;
1323                        try{
1324                                o1int = Integer.parseInt(o1.getId());
1325                                o2int = Integer.parseInt(o2.getId());
1326                                return o1int.compareTo(o2int);
1327                        } catch(NumberFormatException e){
1328                                return o1.getId().compareTo(o2.getId());
1329                        }
1330
1331                }
1332        }
1333       
1334        private static class MapPEIdComparator implements Comparator<String> {
1335
1336                public int compare(String o1, String o2)  {
1337                        Integer o1int;
1338                        Integer o2int;
1339
1340                        o1int = Integer.parseInt(o1.substring(o1.indexOf("_")+1));
1341                        o2int = Integer.parseInt(o2.substring(o2.indexOf("_")+1));
1342                        return o1int.compareTo(o2int);
1343                }
1344        }
1345
1346        public GSSAccumulator getStats(String name) {
1347                return statsData.get(name);
1348        }
1349       
1350        private void createStatsData() {
1351                statsData.put(MAKESPAN, accStats.makespan);
1352                statsData.put(TASK_COMPLETION_TIME, accStats.meanTaskCompletionTime);
1353                statsData.put(TASK_EXECUTION_TIME, accStats.meanTaskExecutionTime);
1354                statsData.put(TASK_START_TIME, accStats.meanTaskStartTime);
1355                statsData.put(TASK_FLOW_TIME, accStats.meanTaskFlowTime);
1356                statsData.put(TASK_WAITING_TIME, accStats.meanTaskWaitingTime);
1357                statsData.put(TASK_LATENESS, accStats.lateness);
1358                statsData.put(TASK_TARDINESS, accStats.tardiness);
1359                statsData.put(DELAYED_TASKS, accStats.delayedTasks);
1360                statsData.put(FAILED_REQUESTS, accStats.failedRequests);
1361                statsData.put(RESOURCES_TOTAL_LOAD, accStats.meanTotalLoad);
1362                statsData.put(RESOURCES_RESERVATION_LOAD, accStats.meanReservationLoad);
1363                statsData.put(RESOURCES_RESERVATION_LOAD, accStats.meanEnergyUsage);
1364                statsData.put(RESOURCES_QUEUE_LENGTH, accStats.meanQueueLength);
1365
1366        }
1367
1368
1369        public boolean accumulatedStats() {
1370                return configuration.createsimulationstatistics;
1371        }
1372
1373}
1374
1375class ResStat{
1376       
1377       
1378        public long getStartDate() {
1379                return startDate;
1380        }
1381        public void setStartDate(long startDate) {
1382                this.startDate = startDate;
1383        }
1384        public long getEndDate() {
1385                return endDate;
1386        }
1387        public void setEndDate(long endDate) {
1388                this.endDate = endDate;
1389        }
1390        public String getTaskID() {
1391                return taskID;
1392        }
1393        public void setTaskID(String taskID) {
1394                this.taskID = taskID;
1395        }
1396
1397        public ResStat( String peName, long startDate, long endDate, String taskID) {
1398                super();
1399                this.startDate = startDate;
1400                this.endDate = endDate;
1401                this.taskID = taskID;
1402                this.peName = peName;
1403        }
1404        public String getPeName() {
1405                return peName;
1406        }
1407        public void setPeName(String peName) {
1408                this.peName = peName;
1409        }
1410        public ResStat(String peName, ResourceType resType, long startDate, long endDate, String taskID) {
1411                super();
1412                this.peName = peName;
1413                this.resType = resType;
1414                this.startDate = startDate;
1415                this.endDate = endDate;
1416                this.taskID = taskID;
1417        }
1418        String peName;
1419        ResourceType resType;
1420        long startDate;
1421        long endDate;
1422        String taskID;
1423
1424        public ResourceType getResType() {
1425                return resType;
1426        }
1427        public void setResType(ResourceType resType) {
1428                this.resType = resType;
1429        }
1430}
1431
1432enum Stats{
1433        textLoad,
1434        chartLoad,
1435        textEnergy,
1436        chartEnergy;
1437}
Note: See TracBrowser for help on using the repository browser.