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

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