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

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