source: DCWoRMS/trunk/build/classes/simulator/stats/implementation/GSSimStatistics.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 GSSimStatistics implements SimulationStatistics {
93
94        private Log log = LogFactory.getLog(GSSimStatistics.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 GSSimStatistics(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                        } catch (Exception e) {
318                                continue;
319                        }
320                        if(type_stats.containsKey(resType)){
321                                Map<String, GSSAccumulator> energyCategoryStats = new TreeMap<String, GSSAccumulator>();
322                                Map<String, GSSAccumulator> loadCategoryStats = new TreeMap<String, GSSAccumulator>();
323                                for(ComputingResource resource: resources){
324                                        ResourceUsageStats resourceUsage = null;
325                                        ResourceEnergyStats energyUsage = null;
326                                        if(type_stats.get(resType).contains(Stats.textLoad)){
327                                                resourceUsage = gatherResourceLoadStats(resource, basicResStats);
328                                                resourceUsage.setMeanUsage(calculateResourceLoad(resource, basicResLoad));
329                                                if (resourceLoadStatsFile != null) {
330                                                        Object txt = resourceUsage.serialize(serializer);
331                                                        resourceLoadStatsFile.println(txt);
332                                                }
333                                        }
334                                        if(type_stats.get(resType).contains(Stats.chartLoad)){
335                                                if (configuration.creatediagrams_resources) {
336                                                        createResourceLoadDiagram(resourceUsage);
337                                                }
338                                        }
339                                        if(type_stats.get(resType).contains(Stats.textEnergy)){
340                                                energyUsage = gatherResourceEnergyStats(resource);
341                                                energyUsage.setMeanUsage(calculateEnergyLoad(energyUsage));
342                                                energyUsage.setSumUsage(energyUsage.getMeanUsage() * (endSimulationTime - startSimulationTime) / (3600 * 1000));
343                                               
344                                                EnergyExtension een = (EnergyExtension )(resource.getExtensionList().getExtension(ExtensionType.ENERGY_EXTENSION));
345                                                if(resourceController.getComputingResources().contains(resource)) {
346                                                        if( een != null /*&& een.getPp() != null*/ ){
347                                                                accStats.meanEnergyUsage.add(energyUsage.meanUsage);
348                                                        }
349
350                                                } else if( een != null && een.getPowerProfile() != null ){
351                                                        ComputingResource parent = resource.getParent();
352                                                        een = (EnergyExtension )(parent.getExtensionList().getExtension(ExtensionType.ENERGY_EXTENSION));
353                                                        boolean top = true;
354                                                        while(parent != null){
355                                                                if(een != null &&  een.getPowerProfile() != null)
356                                                                {
357                                                                        top = false;
358                                                                        break;
359                                                                }
360                                                                parent = parent.getParent();
361                                                        }
362                                                        if(top == true){
363                                                                accStats.meanEnergyUsage.add(energyUsage.meanUsage);
364                                                        }
365                                                }
366                                                if (energyStatsFile != null) {
367                                                        Object txt = energyUsage.serialize(serializer);
368                                                        energyStatsFile.println(txt);
369                                                }
370                                        }
371                                        if(type_stats.get(resType).contains(Stats.chartEnergy)){
372
373                                                if (configuration.creatediagrams_energyusage) {
374                                                        createResourceEnergyGanttDiagram(energyUsage);
375                                                }
376                                        }
377                                       
378                                        /*if(resType == ResourceType.ComputingNode){
379                                                ComputingNode compNode = (ComputingNode) resource;
380                                                if(energyCategoryStats.containsKey(resType+"#"+compNode.getCategory().getName())){
381                                                        GSSAccumulator acc = energyCategoryStats.get(resType+"#"+compNode.getCategory().getName());
382                                                        acc.add(energyUsage.meanUsage);
383                                                        energyCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
384                                                } else{
385                                                        GSSAccumulator acc = new GSSAccumulator();
386                                                        acc.add(energyUsage.meanUsage);
387                                                        energyCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
388                                                }
389                                               
390                                                if(loadCategoryStats.containsKey(resType+"#"+compNode.getCategory().getName())){
391                                                        GSSAccumulator acc = loadCategoryStats.get(resType+"#"+compNode.getCategory().getName());
392                                                        acc.add(resourceUsage.meanUsage);
393                                                        loadCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
394                                                } else{
395                                                        GSSAccumulator acc = new GSSAccumulator();
396                                                        acc.add(resourceUsage.meanUsage);
397                                                        loadCategoryStats.put(resType+"#"+compNode.getCategory().getName(), acc);
398                                                }
399                                        } else if(resType == ResourceType.Processor){
400                                                Processor proc = (Processor)resource;
401                                                if(energyCategoryStats.containsKey(resType+"#"+proc.getComputingNode().getCategory().getName())){
402                                                        GSSAccumulator acc = energyCategoryStats.get(resType+"#"+proc.getComputingNode().getCategory().getName());
403                                                        acc.add(energyUsage.meanUsage);
404                                                        energyCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
405                                                } else{
406                                                        GSSAccumulator acc = new GSSAccumulator();
407                                                        acc.add(energyUsage.meanUsage);
408                                                        energyCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
409                                                }
410                                               
411                                                if(loadCategoryStats.containsKey(resType+"#"+proc.getComputingNode().getCategory().getName())){
412                                                        GSSAccumulator acc = loadCategoryStats.get(resType+"#"+proc.getComputingNode().getCategory().getName());
413                                                        acc.add(resourceUsage.meanUsage);
414                                                        loadCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
415                                                } else{
416                                                        GSSAccumulator acc = new GSSAccumulator();
417                                                        acc.add(resourceUsage.meanUsage);
418                                                        loadCategoryStats.put(resType+"#"+proc.getComputingNode().getCategory().getName(), acc);
419                                                }
420                                        }*/
421                                }
422                               
423                                if(energyCategoryStats.size() > 0)
424                                {
425                                        energyStatsFile.println("\n=========BY CATEGORY===========");
426                                        for(String key: energyCategoryStats.keySet()){
427                                                GSSAccumulator acc = energyCategoryStats.get(key);
428                                                energyStatsFile.println(key + "- mean: "  + acc.getMean()+ " sum: " +acc.getMean() * (endSimulationTime-startSimulationTime) / (3600 * 1000) * acc.getCount());
429                                        }
430                                        energyStatsFile.println("\n\n");
431                                }
432                               
433                                if(loadCategoryStats.size() > 0)
434                                {
435                                        resourceLoadStatsFile.println("\n=========BY CATEGORY===========");
436                                        for(String key: loadCategoryStats.keySet()){
437                                                GSSAccumulator acc = loadCategoryStats.get(key);
438                                                resourceLoadStatsFile.println(key + "- mean: "  + acc.getMean());
439                                        }
440                                        resourceLoadStatsFile.println("\n\n");
441                                }
442                        }
443                }
444               
445                saveResourceGanttDiagrams();
446                createAccumulatedResourceSimulationStatistic();
447                if (energyStatsFile != null) {
448                        energyStatsFile.close();
449                }
450                if (resourceLoadStatsFile != null) {
451                        resourceLoadStatsFile.close();
452                }
453        }
454       
455        private double getSchedulerQueueStats(Scheduler scheduler) {
456
457                Sim_stat stats = scheduler.get_stat();
458                List<Object[]> measures = stats.get_measures();
459                for (Object[] info : measures) {
460                        String measure = (String) info[0];
461                        if (measure
462                                        .startsWith(WormsConstants.TASKS_QUEUE_LENGTH_MEASURE_NAME)) {
463                                return stats.average(measure);
464                        }
465                }
466                return 0;
467        }
468       
469        private void peStatsPostProcessing(Map<String, List<ResStat>> basicResStats){
470                ResourceType resType = null;
471
472                for(String key: basicResStats.keySet()){
473                        List<ResStat> resStats = basicResStats.get(key);
474                        resType = resStats.get(0).getResType();
475                        break;
476                }
477                List<ComputingResource> resources = null;
478                try {
479                        resources = new ArrayList<ComputingResource>();
480                        for(ComputingResource compRes: resourceController.getComputingResources() ){
481                                resources.addAll(compRes.getDescendantsByType(resType));
482                        }
483                } catch (Exception e) {
484                        return;
485                }
486                for(ComputingResource resource: resources){
487                        if(!basicResStats.containsKey(resource.getName())){
488                                basicResStats.put(resource.getName(), new ArrayList<ResStat>());
489                        }
490                }
491        }
492        private Map<String, List<ResStat>> gatherPEStats(Map<Integer, Map<String, Object>> history) {
493
494                Map<String, List<ResStat>> basicResStats = new TreeMap<String, List<ResStat>>(new MapPEIdComparator());
495               
496                for (Integer executableId : history.keySet()) {
497
498                        Map<String, Object> historyItem = (Map<String, Object>) history.get(executableId);
499                        List<ResourceHistoryItem> resHistItemList = (List<ResourceHistoryItem>) historyItem.get(WormsConstants.RESOURCES);
500                        Map<ResourceUnitName, ResourceUnit> res = resHistItemList.get(resHistItemList.size() - 1).getResourceUnits();
501                        ResourceUnit resUnit = res.get(StandardResourceUnitName.PE);
502                        //ProcessingElements pes = (ProcessingElements) resUnit ;
503                        if(resUnit instanceof ProcessingElements ){
504                                ProcessingElements pes = (ProcessingElements) resUnit;
505                                for(ComputingResource pe: pes){
506                                        String peName = pe.getName();
507                                        long startDate = ((DateTime) historyItem.get(WormsConstants.START_TIME)).getMillis();
508                                        long endDate = ((DateTime) historyItem.get(WormsConstants.END_TIME)).getMillis();
509                                        JobRegistryImpl jr = new JobRegistryImpl("stats");
510                                        ExecTask execTask = jr.getTaskExecutable(executableId);
511                                        String uniqueTaskID = execTask.getJobId() + "_" + execTask.getId();
512                                       
513                                        ResStat resStat = new ResStat(peName, pe.getType(), startDate, endDate, uniqueTaskID);
514                                       
515                                        List<ResStat> resStats = basicResStats.get(peName);
516                                        if (resStats == null) {
517                                                resStats = new ArrayList<ResStat>();
518                                                resStats.add(resStat);
519                                                basicResStats.put(peName, resStats);
520                                        } else {
521                                                resStats.add(resStat);
522                                        }
523
524                                        List<String> peNames = task_processorsMap.get(uniqueTaskID);
525                                        if (peNames == null) {
526                                                peNames = new ArrayList<String>();
527                                                peNames.add(peName);
528                                                task_processorsMap.put(uniqueTaskID, peNames);
529                                        } else {
530                                                peNames.add(peName);
531                                        }
532                                }
533                        } else if (resUnit instanceof PEUnit){
534                                PEUnit peUnit = (PEUnit) resUnit ;
535                       
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 * 1000);
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 + "Processing_Elements",
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.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 resIDlist[] = task.getAllResourceName();
1144                String resID = resIDlist[resIDlist.length - 1];
1145
1146                long execStartTime = Double.valueOf(task.getExecStartTime()).longValue() * 1000;
1147                long execEndTime = Double.valueOf(task.getFinishTime()).longValue() * 1000;
1148
1149                TaskSeries taskRes = ganttDiagramTaskSeriesCollection.getSeries(resID);
1150                if (taskRes == null) {
1151                        taskRes = new TaskSeries(resID);
1152                        ganttDiagramTaskSeriesCollection.add(taskRes);
1153                }
1154                org.jfree.data.gantt.Task ganttTask = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(execStartTime),
1155                                new Date(execEndTime));
1156                if (!task.isFinished()) {
1157                        ganttTask.setPercentComplete(1.0);
1158                }
1159                taskRes.add(ganttTask);
1160        }
1161
1162        private void createTaskWaitingTimeDiagramData(Executable task) {
1163                String uniqueTaskID = task.getJobId() + "_" + task.getId();
1164
1165                String resIDlist[] = task.getAllResourceName();
1166                String resID = resIDlist[resIDlist.length - 1];
1167
1168                long execStartTime = Double.valueOf(task.getExecStartTime()).longValue() * 1000;
1169                long execEndTime = Double.valueOf(task.getFinishTime()).longValue() * 1000;
1170
1171                TaskSeries waitRes = ganttDiagramWaitingTimeSeriesCollection.getSeries(resID);
1172                if (waitRes == null) {
1173                        waitRes = new TaskSeries(resID);
1174                        ganttDiagramWaitingTimeSeriesCollection.add(waitRes);
1175                }
1176
1177                long sub = Double.valueOf(task.getSubmissionTime()).longValue() * 1000;
1178                org.jfree.data.gantt.Task wait_exec = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(sub), new Date(
1179                                execEndTime));
1180                org.jfree.data.gantt.Task exec = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(execStartTime), new Date(
1181                                execEndTime));
1182                if (!task.isFinished()) {
1183                        exec.setPercentComplete(1.0);
1184                }
1185                wait_exec.addSubtask(wait_exec);
1186                wait_exec.addSubtask(exec);
1187                waitRes.add(wait_exec);
1188        }
1189
1190        private boolean saveTaskGanttDiagrams() {
1191
1192                JFreeChart taskDiagram = null;
1193                JFreeChart waitingTimeDiagram = null;
1194
1195                if (!generateDiagrams)
1196                        return false;
1197
1198                String fileName = new File(outputFolderName, DIAGRAMS_FILE_NAME_PREFIX + simulationIdentifier + "_")
1199                                .getAbsolutePath();
1200
1201                String chartName = "Gantt diagram for " + DataCenterWorkloadSimulator.SIMULATOR_NAME;
1202                String simulationTime = "Simulation time";
1203                Title subtitle = new TextTitle("created for \"" + simulationIdentifier + "\" at "
1204                                + Calendar.getInstance().getTime().toString());
1205
1206                if (configuration.creatediagrams_tasks) {
1207                        taskDiagram = getTaskDiagram(chartName, subtitle, simulationTime);
1208                        if (!saveCategoryChart(taskDiagram, fileName + "Tasks", null /* "{0}" */))
1209                                return false;
1210                }
1211
1212                if (configuration.creatediagrams_taskswaitingtime) {
1213                        waitingTimeDiagram = getWaitingTimeDiagram(chartName, subtitle, simulationTime);
1214                        if (!saveCategoryChart(waitingTimeDiagram, fileName + "Waiting_Time", null /* "Task {1} at {0}" */))
1215                                return false;
1216                }
1217
1218                return true;
1219        }
1220
1221        private JFreeChart getTaskDiagram(String chartName, Title subtitle, String simulationTime) {
1222                String tasks = "Tasks";
1223                boolean urls = false;
1224                boolean tooltip = true;
1225                boolean legend = true;
1226                JFreeChart chart = ChartFactory.createGanttChart(chartName, tasks, simulationTime,
1227                                ganttDiagramTaskSeriesCollection, legend, tooltip, urls);
1228                chart.addSubtitle(subtitle);
1229                GanttRenderer re = (GanttRenderer) chart.getCategoryPlot().getRenderer();
1230                re.setCompletePaint(Color.black);
1231                return chart;
1232        }
1233
1234        private JFreeChart getWaitingTimeDiagram(String chartName, Title subtitle, String simulationTime) {
1235                String tasks = "Tasks";
1236                boolean urls = false;
1237                boolean tooltip = true;
1238                boolean legend = true;
1239                JFreeChart chart = ChartFactory.createGanttChart(chartName, tasks, simulationTime,
1240                                ganttDiagramWaitingTimeSeriesCollection, legend, tooltip, urls);
1241                chart.addSubtitle(subtitle);
1242                chart.getPlot().setForegroundAlpha(ALPHA);
1243                GanttRenderer re = (GanttRenderer) chart.getCategoryPlot().getRenderer();
1244                re.setCompletePaint(Color.black);
1245                return chart;
1246        }
1247
1248        private boolean saveCategoryChart(JFreeChart c, String fileName, String labelFormat) {
1249                c.setNotify(false);
1250                c.setAntiAlias(true);
1251                c.setTextAntiAlias(true);
1252                c.setBorderVisible(false);
1253
1254                CategoryPlot categoryplot = (CategoryPlot) c.getPlot();
1255                categoryplot.setDomainGridlinesVisible(true);
1256
1257                if (labelFormat != null) {
1258                        CategoryItemRenderer rend = categoryplot.getRenderer();
1259                        rend.setBaseItemLabelsVisible(true);
1260                        ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER);
1261                        rend.setBasePositiveItemLabelPosition(position);
1262                        NumberFormat nf = NumberFormat.getInstance();
1263                        CategoryItemLabelGenerator gen = new StandardCategoryItemLabelGenerator(labelFormat, nf);
1264                        rend.setBaseItemLabelGenerator(gen);
1265                }
1266
1267                int rows = c.getCategoryPlot().getDataset().getColumnKeys().size();
1268
1269                int height = 900;
1270                if (rows > 45) {
1271                        height = rows * 20;
1272                }
1273                int width = calculateChartWidth(c);
1274                CategoryItemRenderer rend = c.getCategoryPlot().getRenderer();
1275
1276                for (int i = 0; i < c.getCategoryPlot().getDataset().getRowKeys().size(); i++) {
1277                        Paint collor = c.getCategoryPlot().getDrawingSupplier().getNextPaint();
1278                        rend.setSeriesOutlinePaint(i, collor);
1279                        rend.setSeriesPaint(i, collor);
1280                }
1281
1282                ChartRenderingInfo info = new ChartRenderingInfo();
1283                // info.setEntityCollection(null);
1284                File f = new File(fileName + "." + ImageFormat.PNG);
1285                final String gssimSubtitle = "Created by " + DataCenterWorkloadSimulator.SIMULATOR_NAME + " http://www.gssim.org/";
1286                c.addSubtitle(new TextTitle(gssimSubtitle));
1287                boolean encodeAlpha = false;
1288                int compression = 9;
1289                try {
1290                        ChartUtilities.saveChartAsPNG(f, c, width, height, info, encodeAlpha, compression);
1291
1292                } catch (IOException e) {
1293                        e.printStackTrace();
1294                        return false;
1295                } catch (Exception e) {
1296                        if (log.isErrorEnabled())
1297                                log.error("The png file (" + fileName
1298                                                + ")\nwill not be generated (It can be too large data size problem)", e);
1299                } catch (Throwable t) {
1300                        log.error("The png file (" + fileName + ")\nwill not be generated (It can be too large data size problem)",
1301                                        t);
1302                }
1303
1304                return true;
1305        }
1306
1307        private int calculateChartWidth(JFreeChart c) {
1308
1309                int ganttWidth = GANTT_WIDTH;
1310                int rows = c.getCategoryPlot().getDataset().getColumnKeys().size();
1311
1312                if (rows > 45) {
1313                        int height = rows * 20;
1314                        ganttWidth = Math.max((int) (height * 1.5), GANTT_WIDTH);
1315                }
1316                return ganttWidth;
1317        }
1318
1319        private static class JobIdComparator implements Comparator<JobInterface<?>> {
1320
1321                public int compare(JobInterface<?> o1, JobInterface<?> o2) {
1322                        try {
1323                                Integer o1int;
1324                                Integer o2int;
1325                                try{
1326                                        o1int = Integer.parseInt(o1.getId());
1327                                        o2int = Integer.parseInt(o2.getId());
1328                                        return o1int.compareTo(o2int);
1329                                } catch(NumberFormatException e){
1330                                        return o1.getId().compareTo(o2.getId());
1331                                }
1332
1333                        } catch (NoSuchFieldException e) {
1334                                e.printStackTrace();
1335                        }
1336                        return -1;
1337                }
1338        }
1339       
1340        private static class MapPEIdComparator implements Comparator<String> {
1341
1342                public int compare(String o1, String o2)  {
1343                        Integer o1int;
1344                        Integer o2int;
1345
1346                        o1int = Integer.parseInt(o1.substring(o1.indexOf("_")+1));
1347                        o2int = Integer.parseInt(o2.substring(o2.indexOf("_")+1));
1348                        return o1int.compareTo(o2int);
1349                }
1350        }
1351
1352        public GSSAccumulator getStats(String name) {
1353                return statsData.get(name);
1354        }
1355       
1356        private void createStatsData() {
1357                statsData.put(MAKESPAN, accStats.makespan);
1358                statsData.put(TASK_COMPLETION_TIME, accStats.meanTaskCompletionTime);
1359                statsData.put(TASK_EXECUTION_TIME, accStats.meanTaskExecutionTime);
1360                statsData.put(TASK_START_TIME, accStats.meanTaskStartTime);
1361                statsData.put(TASK_FLOW_TIME, accStats.meanTaskFlowTime);
1362                statsData.put(TASK_WAITING_TIME, accStats.meanTaskWaitingTime);
1363                statsData.put(TASK_LATENESS, accStats.lateness);
1364                statsData.put(TASK_TARDINESS, accStats.tardiness);
1365                statsData.put(DELAYED_TASKS, accStats.delayedTasks);
1366                statsData.put(FAILED_REQUESTS, accStats.failedRequests);
1367                statsData.put(RESOURCES_TOTAL_LOAD, accStats.meanTotalLoad);
1368                statsData.put(RESOURCES_RESERVATION_LOAD, accStats.meanReservationLoad);
1369                statsData.put(RESOURCES_RESERVATION_LOAD, accStats.meanEnergyUsage);
1370                statsData.put(RESOURCES_QUEUE_LENGTH, accStats.meanQueueLength);
1371
1372        }
1373
1374
1375        public boolean accumulatedStats() {
1376                return configuration.createsimulationstatistics;
1377        }
1378
1379}
1380
1381class ResStat{
1382       
1383       
1384        public long getStartDate() {
1385                return startDate;
1386        }
1387        public void setStartDate(long startDate) {
1388                this.startDate = startDate;
1389        }
1390        public long getEndDate() {
1391                return endDate;
1392        }
1393        public void setEndDate(long endDate) {
1394                this.endDate = endDate;
1395        }
1396        public String getTaskID() {
1397                return taskID;
1398        }
1399        public void setTaskID(String taskID) {
1400                this.taskID = taskID;
1401        }
1402
1403        public ResStat( String peName, long startDate, long endDate, String taskID) {
1404                super();
1405                this.startDate = startDate;
1406                this.endDate = endDate;
1407                this.taskID = taskID;
1408                this.peName = peName;
1409        }
1410        public String getPeName() {
1411                return peName;
1412        }
1413        public void setPeName(String peName) {
1414                this.peName = peName;
1415        }
1416        public ResStat(String peName, ResourceType resType, long startDate, long endDate, String taskID) {
1417                super();
1418                this.peName = peName;
1419                this.resType = resType;
1420                this.startDate = startDate;
1421                this.endDate = endDate;
1422                this.taskID = taskID;
1423        }
1424        String peName;
1425        ResourceType resType;
1426        long startDate;
1427        long endDate;
1428        String taskID;
1429
1430        public ResourceType getResType() {
1431                return resType;
1432        }
1433        public void setResType(ResourceType resType) {
1434                this.resType = resType;
1435        }
1436}
1437
1438enum Stats{
1439        textLoad,
1440        chartLoad,
1441        textEnergy,
1442        chartEnergy;
1443}
Note: See TracBrowser for help on using the repository browser.