source: DCWoRMS/trunk/src/simulator/stats/implementation/WormsStatistics.java @ 477

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