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

Revision 687, 47.2 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 = execTask.getJobId() + "_" + execTask.getId();
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        private ResourceUsageStats gatherResourceLoadStats(ComputingResource resource, Map<String, List<ResStat>> basicStats) {
500                ResourceUsageStats usageStats = new ResourceUsageStats(resource.getName(), resource.getType(), "resourceLoadStats");
501                int cnt = 0;
502                for(String resName: basicStats.keySet()){
503                        try {
504                                if(resource.getDescendantByName(resName) != null || resource.getName().compareTo(resName) == 0){
505                                        createResourceLoadData(usageStats, basicStats.get(resName));
506                                        cnt++;
507                                }
508                        } catch (ResourceException e) {
509                                // TODO Auto-generated catch block
510                                e.printStackTrace();
511                        }
512                }
513                for(Long key: usageStats.getHistory().keySet()){
514                        Double value = usageStats.getHistory().get(key)/cnt;
515                        usageStats.getHistory().put(key, value);
516                }
517
518                return usageStats;
519        }
520       
521        private Map<Long, Double> createResourceLoadData(ResourceUsageStats usageStats, List<ResStat> resStats) {
522
523                TreeMap<Long, Double> ganttData = (TreeMap<Long, Double>)usageStats.getHistory();
524                for (ResStat resStat : resStats) {
525                       
526                        long start_time = resStat.getStartDate();
527                        long end_time = resStat.getEndDate();
528                        if (end_time > start_time) {
529                                Double end = ganttData.get(end_time);
530                                if (end == null) {
531                                        ganttData.put(end_time, 0.0);
532                                        Long left = getLeftKey(ganttData, end_time);
533                                        if (left != null) {
534                                                Double leftValue = ganttData.get(left);
535                                                ganttData.put(end_time, leftValue);
536                                        }
537                                }
538
539                                Double start = ganttData.get(start_time);
540                                if (start == null) {
541                                        ganttData.put(start_time, 0.0);
542                                        Long left = getLeftKey(ganttData, start_time);
543                                        if (left != null) {
544                                                Double leftValue = ganttData.get(left);
545                                                ganttData.put(start_time, leftValue);
546                                        }
547                                }
548
549                                SortedMap<Long, Double> sm = ganttData.subMap(start_time,
550                                                end_time);
551                                for (Long key : sm.keySet()) {
552                                        Double keyVal = ganttData.get(key);
553                                        ganttData.put(key, keyVal + 1);
554                                }
555                        }
556                }
557
558                return ganttData;
559        }
560
561        private Long getLeftKey(TreeMap<Long, Double> ganttData, Long toKey) {
562
563                SortedMap<Long, Double> sm = ganttData.headMap(toKey);
564                if (sm.isEmpty()) {
565                        return null;
566                }
567                return sm.lastKey();
568        }
569       
570       
571        private ResourcePowerStats gatherResourcePowerConsumptionStats(ComputingResource resource) {
572                double power = 0;
573                ResourcePowerStats resEnergyUsage = new ResourcePowerStats(resource.getName(), resource.getType(), "resourcePowerConsumptionStats");
574                Map<Long, Double> usage = resEnergyUsage.getHistory();
575               
576                ExtensionList extensionList = resource.getExtensionList();
577                if(extensionList != null){
578                        for (Extension extension : extensionList) {
579                                if (extension.getType() == ExtensionType.ENERGY_EXTENSION) {
580                                        EnergyExtension ee = (EnergyExtension)extension;
581                                        if(ee.getPowerProfile() == null)
582                                                break;
583                                        List<PowerUsage> powerUsage = ee.getPowerProfile().getPowerUsageHistory();
584                                        if(powerUsage.size() == 0)
585                                                break;
586                                        long lastTime = DateTimeUtilsExt.getOffsetTime().getTimeInMillis();
587                                        long endSimulationTime = DateTimeUtilsExt.currentTimeMillis();
588                                        double lastPower = 0;
589                                        powerUsage.add(new PowerUsage(endSimulationTime, ee.getPowerProfile().getPowerUsageHistory().get(ee.getPowerProfile().getPowerUsageHistory().size()-1).getValue()));
590                                        for(PowerUsage pu:powerUsage){
591                                                usage.put(pu.getTimestamp(), pu.getValue());
592                                               
593                                        ///     System.out.println(resource.getName() + ":"+new DateTime(pu.getTimestamp())+";"+pu.getValue());
594                                                power = power + (pu.getTimestamp() - lastTime) * lastPower/ (3600 * MILLI_SEC);
595                                                lastPower = pu.getValue();
596                                                lastTime = pu.getTimestamp();
597                                        }
598                                }
599                        }
600                }
601                //System.out.println(power);
602                return resEnergyUsage;
603        }
604       
605       
606        private ResourceAirFlowStats gatherResourceAirFlowStats(ComputingResource resource) {
607
608                ResourceAirFlowStats resAirFlow = new ResourceAirFlowStats(resource.getName(), resource.getType(), "resourceAirFlowStats");
609                Map<Long, Double> airFlow = resAirFlow.getHistory();
610               
611                ExtensionList extensionList = resource.getExtensionList();
612                if(extensionList != null){
613                        for (Extension extension : extensionList) {
614                                if (extension.getType() == ExtensionType.ENERGY_EXTENSION) {
615                                        EnergyExtension ee = (EnergyExtension)extension;
616                                        if(ee.getAirFlowProfile() == null)
617                                                break;
618                                        List<AirFlowValue> airFlowHistory = ee.getAirFlowProfile().getAirThroughputHistory();
619                                        if(airFlowHistory.size() == 0)
620                                                break;
621                                        long endSimulationTime = DateTimeUtilsExt.currentTimeMillis();
622                                        airFlowHistory.add(new AirFlowValue(endSimulationTime, ee.getAirFlowProfile().getAirThroughputHistory().get(ee.getAirFlowProfile().getAirThroughputHistory().size()-1).getValue()));
623                                        for(AirFlowValue af:airFlowHistory){
624                                                airFlow.put(af.getTimestamp(), af.getValue());
625                                        }
626                                }
627                        }
628                }
629                return resAirFlow;
630        }
631       
632        private void createResourceLoadDiagram(ResourceUsageStats resLoadStats) {
633
634                for(Long key: resLoadStats.getHistory().keySet()){
635                        Double value = resLoadStats.getHistory().get(key) * 100;
636                        resLoadStats.getHistory().put(key, value);
637                }
638
639                XYDataset dataset = createResourceChartDataSet(resLoadStats,
640                                startSimulationTime, endSimulationTime);
641
642                List<XYDataset> loadDiagram = resourceLoadDiagrams.get(resLoadStats.getResourceType());
643                if(loadDiagram == null){
644                        loadDiagram = new ArrayList<XYDataset>();
645                        loadDiagram.add(dataset);
646                        resourceLoadDiagrams.put(resLoadStats.getResourceType(), loadDiagram);
647                } else {
648                        loadDiagram.add(dataset);
649                }
650        }
651       
652        private void createResourceEnergyDiagramData(ResourceDynamicStats powerConsumptionStats) {
653
654                XYDataset dataset = createResourceChartDataSet(powerConsumptionStats,
655                                startSimulationTime, endSimulationTime);
656               
657                List<XYDataset> energyDiagramData = resourcePowerUsageDiagrams.get(powerConsumptionStats.getResourceType());
658                if(energyDiagramData == null){
659                        energyDiagramData = new ArrayList<XYDataset>();
660                        energyDiagramData.add(dataset);
661                        resourcePowerUsageDiagrams.put(powerConsumptionStats.getResourceType(), energyDiagramData);
662                } else {
663                        energyDiagramData.add(dataset);
664                }
665        }
666
667        private void createResourceAirFlowDiagramData(ResourceDynamicStats airFlowStats) {
668
669                XYDataset dataset = createResourceChartDataSet(airFlowStats,
670                                startSimulationTime, endSimulationTime);
671               
672                List<XYDataset> airFlowDiagramData = resourceAirFlowDiagrams.get(airFlowStats.getResourceType());
673                if(airFlowDiagramData == null){
674                        airFlowDiagramData = new ArrayList<XYDataset>();
675                        airFlowDiagramData.add(dataset);
676                        resourceAirFlowDiagrams.put(airFlowStats.getResourceType(), airFlowDiagramData);
677                } else {
678                        airFlowDiagramData.add(dataset);
679                }
680        }
681
682        private XYDataset createResourceChartDataSet(
683                        ResourceDynamicStats dynamicStats, long start, long end) {
684
685                Map<Long, Double> chartData = getResourceChartRawData(dynamicStats);
686                XYSeriesCollection dataset = new XYSeriesCollection();
687                XYSeries data = new XYSeries(dynamicStats.getResourceName(), false, true);
688                data.add(start, 0);
689                for (Long key : chartData.keySet()) {
690                        Double val = chartData.get(key);
691                        if(key >= startSimulationTime)
692                                data.add(key, val);
693                }
694                data.add(end, 0);
695                dataset.addSeries(data);
696                return dataset;
697        }
698
699        private Map<Long, Double> getResourceChartRawData(
700                        ResourceDynamicStats dynamicStats) {
701
702                Map<Long, Double> history = dynamicStats.getHistory();
703                Map<Long, Double> chartData = new TreeMap<Long, Double>();
704                for (Long key : history.keySet()) {
705                        chartData.put(key, history.get(key));
706                }
707                return chartData;
708        }
709
710        private boolean saveResourceGanttDiagrams() {
711
712                if (!generateDiagrams)
713                        return false;
714
715                String fileName = new File(outputFolderName, DIAGRAMS_FILE_NAME_PREFIX
716                                + simulationIdentifier + "_").getAbsolutePath();
717
718                String chartName = "Gantt diagram for "
719                                + DataCenterWorkloadSimulator.SIMULATOR_NAME;
720                String simulationTime = "Simulation time";
721                Title subtitle = new TextTitle("created for \"" + simulationIdentifier
722                                + "\" at " + Calendar.getInstance().getTime().toString());
723
724                JFreeChart peDiagram = null;
725                if (configuration.creatediagrams_gantt) {
726                        peDiagram = getPEGanttDiagram(chartName, subtitle,
727                                        simulationTime);
728                        if (!saveCategoryChart(peDiagram, fileName + "Gantt",
729                                        "{0}"))
730                                return false;
731                }
732                chartName = "Load diagram for "
733                        + DataCenterWorkloadSimulator.SIMULATOR_NAME;
734                JFreeChart resourceLoadDiagram = null;
735                if (configuration.creatediagrams_resutilization) {
736                        String axisName = "UTILIZATION [%]";
737                        for(ResourceType resType: resourceLoadDiagrams.keySet()){
738                                resourceLoadDiagram = getResourceDynamicDiagram(resourceLoadDiagrams.get(resType), simulationTime, chartName,
739                                                subtitle, axisName);
740                                if (!saveXYPlotChart(resourceLoadDiagram, fileName + "Resources Load - "+resType))
741                                        return false;
742                        }
743                }
744               
745                chartName = "Energy usage diagram for "
746                        + DataCenterWorkloadSimulator.SIMULATOR_NAME;
747                JFreeChart resourceEnergyDiagram = null;
748                if (configuration.creatediagrams_respowerusage) {
749                        String axisName = "POWER [W]";
750                        for(ResourceType resType: resourcePowerUsageDiagrams.keySet()){
751                                resourceEnergyDiagram = getResourceDynamicDiagram(resourcePowerUsageDiagrams.get(resType), simulationTime, chartName,
752                                                subtitle, axisName);
753                                if (!saveXYPlotChart(resourceEnergyDiagram, fileName + "Energy - "+resType))
754                                        return false;
755                        }
756                }
757               
758                chartName = "Air flow diagram for "
759                        + DataCenterWorkloadSimulator.SIMULATOR_NAME;
760                JFreeChart resourceAirFlowDiagram = null;
761                if (configuration.creatediagrams_resairflow) {
762                        String axisName = "AIR FLOW [m^3/min]";
763                        for(ResourceType resType: resourceAirFlowDiagrams.keySet()){
764                                resourceAirFlowDiagram = getResourceDynamicDiagram(resourceAirFlowDiagrams.get(resType), simulationTime, chartName,
765                                                subtitle, axisName);
766                                if (!saveXYPlotChart(resourceAirFlowDiagram, fileName + "AirThroughput - "+resType))
767                                        return false;
768                        }
769                }
770                return true;
771        }
772       
773        private JFreeChart getPEGanttDiagram(String chartName, Title subtitle,
774                        String simulationTime) {
775                String processors = "Processing Elements";
776                boolean tooltip = true;
777                boolean legend = true;
778                JFreeChart chart = TimetableChartFactory.createTimetableChart(
779                                chartName, processors, simulationTime,
780                                ganttDiagramTimetable, legend, tooltip);
781                chart.addSubtitle(subtitle);
782                TimetableRenderer rend = (TimetableRenderer) chart.getCategoryPlot()
783                                .getRenderer();
784                rend.setBackgroundBarPaint(null);
785                return chart;
786        }
787       
788        private JFreeChart getResourceDynamicDiagram(List<XYDataset> diagramData, String simulationTime, String chartName, Title subtitle,
789                        String axisName) {
790                boolean urls = false;
791                boolean tooltip = true;
792                boolean legend = true;
793                CombinedDomainXYPlot cPlot = new CombinedDomainXYPlot();
794                DateAxis xAxis = new DateAxis(simulationTime);
795                JFreeChart chart = null;
796
797                for (XYDataset dataset : diagramData) {
798                        JFreeChart tChart = ChartFactory.createXYStepAreaChart("", "",
799                                null, dataset, PlotOrientation.VERTICAL, legend, tooltip, urls);
800                        XYPlot tPlot = tChart.getXYPlot();
801                        NumberAxis yAxis = new NumberAxis(axisName);
802                        yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
803                        tPlot.setRangeAxis(yAxis);
804                        XYStepAreaRenderer rend = (XYStepAreaRenderer) tPlot.getRenderer();
805                        rend.setShapesVisible(false);
806                        cPlot.add(tPlot);
807                }
808                cPlot.setDomainAxis(xAxis);
809                cPlot.setDomainAxisLocation(AxisLocation.TOP_OR_LEFT);
810                chart = new JFreeChart(chartName, cPlot);
811                chart.addSubtitle(subtitle);
812                return chart;
813        }
814       
815        private boolean saveXYPlotChart(JFreeChart c, String fileName) {
816                c.setNotify(false);
817                c.setAntiAlias(true);
818                c.setTextAntiAlias(true);
819                c.setBorderVisible(false);
820
821                int height = 900;
822
823                CombinedDomainXYPlot cPlot = (CombinedDomainXYPlot) c.getPlot();
824                int nPlots = cPlot.getSubplots().size();
825
826                if (nPlots > 3) {
827                        height = nPlots * 300;
828                }
829                int width = GANTT_WIDTH;
830
831                if (configuration.creatediagrams_resources_scale != -1)
832                        width = (int) ((endSimulationTime - startSimulationTime) * configuration.creatediagrams_resources_scale);
833                ChartRenderingInfo info = new ChartRenderingInfo();
834                File f = new File(fileName + "." + ImageFormat.PNG);
835                final String dcwormsSubtitle = "Created by "
836                                + DataCenterWorkloadSimulator.SIMULATOR_NAME
837                                + " http://www.gssim.org/";
838                c.addSubtitle(new TextTitle(dcwormsSubtitle));
839                boolean encodeAlpha = false;
840                int compression = 9;// values 0-9
841                try {
842                        ChartUtilities.saveChartAsPNG(f, c, width, height, info,
843                                        encodeAlpha, compression);
844                } catch (IOException e) {
845                        e.printStackTrace();
846                        return false;
847                }
848                return true;
849        }
850       
851        private void createPEGanttDiagram(Map<String,List<ResStat>> basicResStats) {
852                for(String peName: basicResStats.keySet()){
853                        TimetableEventSource pe = new TimetableEventSource(peName);
854                        ganttDiagramTimetable.addEventSource(pe);
855                        peGanttMap.put(peName, pe);
856                        for(ResStat resStat: basicResStats.get(peName)){
857
858                                pe = peGanttMap.get(resStat.getPeName());
859                                if(pe == null){
860                                        //pe = new TimetableEventSource(resStat.getPeName());
861                                //      ganttDiagramPeTimetable.addEventSource(pe);
862                                //      peGanttMap.put(resStat.getPeName(), pe);
863                                }
864                                TimetableEventGroup task = taskGanttMap.get(resStat.getTaskID());
865                                long startDate = resStat.getStartDate();
866                                long endDate = resStat.getEndDate();
867                                if (task == null) {
868                                        task = new TimetableEventGroup(resStat.getTaskID());
869                                        taskGanttMap.put(resStat.getTaskID(), task);
870                                        ganttDiagramTimetable.addEventGroup(task);
871                                }
872                                ganttDiagramTimetable.addEvent(pe, task,
873                                                new FixedMillisecond(startDate), new FixedMillisecond(endDate));
874                        }
875                }
876        }
877
878
879        //TO DO
880        private void createAccumulatedResourceSimulationStatistic() {
881
882                List<ComputingResource> resources = resourceController.getComputingResources();
883                for(ComputingResource compRes: resources){
884                        //for(ComputingResource child :compRes.getChildren()){
885                       
886                                //ResourceUsageStats resourceUsage = gatherResourceLoadStats(compRes, basicResStats);
887                                //double load = calculateMeanValue(resourceUsage);
888                                double load = calculateResourceLoad(compRes, basicResLoad);
889                                accStats.meanTotalLoad.add(load);
890                                /*ResourceEnergyStats energyUsage = gatherResourceEnergyStats(compRes);
891                                energyUsage.setMeanUsage(calculateEnergyLoad(energyUsage));
892                                accStats.meanEnergyUsage.add(energyUsage.meanUsage);*/
893                        //}     
894                }
895        }
896
897        private Map<String, Double> calculatePELoad(Map<String, List<ResStat>> basicResStats){
898                Map<String, Double> peLoad = new HashMap<String, Double>();
899                for(String resName: basicResStats.keySet()){
900                        List<ResStat> resStats = basicResStats.get(resName);
901                        double sum = 0;
902                        for(ResStat resStat:resStats){
903                                sum += (resStat.endDate - resStat.startDate);
904                        }
905                        double load = sum / (endSimulationTime - startSimulationTime);
906                        peLoad.put(resName, load);
907                }
908                return peLoad;
909        }
910       
911        private  Double calculateResourceLoad(ComputingResource resource, Map<String, Double> peLoad ){
912                int peCnt = 0;
913                double sum = 0;
914                for(String resName: peLoad.keySet()){
915
916                        try {
917                                if(resource.getDescendantByName(resName) != null || resource.getName().compareTo(resName) == 0){
918                                        Double load = peLoad.get(resName);
919                                        sum += load;
920                                        peCnt++;
921                                }
922                        } catch (ResourceException e) {
923                                // TODO Auto-generated catch block
924                                e.printStackTrace();
925                        }
926                }
927               
928                return sum/peCnt;
929        }
930
931       
932        private double calculateMeanValue(ResourceDynamicStats resDynamicStats ){
933                double meanValue = 0;
934                long time = -1;
935                double value = 0;
936               
937                Map<Long, Double> history = resDynamicStats.getHistory();
938                for (Long key : history.keySet()) {
939                       
940                        if(key >= startSimulationTime){
941                                if (time != -1) {
942                                        meanValue += (value * (key - time)) / (endSimulationTime - startSimulationTime);
943                                        time = key;
944                                } else {
945                                        time = key;
946                                }       
947                        }
948                        value = history.get(key);
949                }
950                return meanValue;
951        }
952       
953       
954
955       
956       
957       
958       
959
960
961        /************* TASK STATISTICS SECTION **************/
962        public void gatherTaskStatistics() {
963
964                List<JobInterface<?>> jobs = users.getAllReceivedJobs();
965                Collections.sort(jobs, new JobIdComparator());
966
967                ganttDiagramTaskSeriesCollection = new TaskSeriesCollection();
968                ganttDiagramWaitingTimeSeriesCollection = new TaskSeriesCollection();
969
970                PrintStream taskStatsFile = null;
971                try {
972                        File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
973                                        + RAW_TASKS_STATISTICS_OUTPUT_FILE_NAME);
974                        taskStatsFile = new PrintStream(new FileOutputStream(file));
975                } catch (IOException e) {
976                        taskStatsFile = null;
977                }
978
979                PrintStream jobStatsFile = null;
980                if (configuration.createjobsstatistics) {
981                        try {
982                                File file = new File(outputFolderName + STATS_FILE_NAME_PREFIX + simulationIdentifier + "_"
983                                                + JOBS_STATISTICS_OUTPUT_FILE_NAME);
984                                jobStatsFile = new PrintStream(new FileOutputStream(file));
985                        } catch (IOException e) {
986                                jobStatsFile = null;
987                        }
988                }
989
990                for (int i = 0; i < jobs.size(); i++) {
991                        Job job = (Job) jobs.get(i);
992
993                        List<Executable> execList = jr.getExecutableTasks().getJobExecutables(job.getId());
994                        List<TaskStats> taskStatsList = new ArrayList<TaskStats>();
995
996                        this.serializer.setFieldSeparator(TASK_SEPARATOR);
997
998                        for (int j = 0; j < execList.size(); j++) {
999
1000                                Executable task = (Executable) execList.get(j);
1001
1002                                TaskStats taskStats = createTaskStats(task);
1003                                if (taskStats != null && taskStatsFile != null) {
1004                                        Object txt = taskStats.serialize(serializer);
1005                                        taskStatsFile.println(txt);
1006                                }
1007                                if (taskStats != null && taskStats.getExecFinishDate() != -1) {
1008                                        if (configuration.createsimulationstatistics) {
1009                                                createAccumulatedTaskSimulationStatistic(taskStats);
1010                                        }
1011                                        allTasksFinished &= task.isFinished();
1012                                        if (generateDiagrams) {
1013                                                if (configuration.creatediagrams_tasks)
1014                                                        createTaskDiagramData(task);
1015                                                if (configuration.creatediagrams_taskswaitingtime)
1016                                                        createTaskWaitingTimeDiagramData(task);
1017                                        }
1018                                        taskStatsList.add(taskStats);
1019                                }
1020                        }
1021                        if (configuration.createjobsstatistics && taskStatsList.size() > 0) {
1022
1023                                this.serializer.setFieldSeparator(JOB_SEPARATOR);
1024                                JobStats jobStats = createJobStats(taskStatsList);
1025                                if (jobStatsFile != null) {
1026                                        Object txt = jobStats.serialize(serializer);
1027                                        jobStatsFile.println(txt);
1028                                }
1029                        }
1030                }
1031
1032                if (configuration.createsimulationstatistics) {
1033                        accStats.makespan.add(maxCj);
1034                        accStats.delayedTasks.add(numOfdelayedTasks);
1035                        accStats.failedRequests.add(users.getAllSentTasks().size() - users.getFinishedTasksCount());
1036                        if(resourceController.getScheduler().getType().getName().equals("GS")){
1037                                for(Scheduler sched: resourceController.getScheduler().getChildren()){
1038                                        accStats.meanQueueLength.add(getSchedulerQueueStats(sched));
1039                                }
1040                        }
1041                        else {
1042                                accStats.meanQueueLength.add(getSchedulerQueueStats(resourceController.getScheduler()));
1043                        }
1044                }
1045
1046                saveTaskGanttDiagrams();
1047
1048                if (taskStatsFile != null) {
1049                        taskStatsFile.close();
1050                }
1051                if (jobStatsFile != null) {
1052                        jobStatsFile.close();
1053                }
1054        }
1055
1056        private double getSchedulerQueueStats(Scheduler scheduler) {
1057
1058                Sim_stat stats = scheduler.get_stat();
1059                List<Object[]> measures = stats.get_measures();
1060                for (Object[] info : measures) {
1061                        String measure = (String) info[0];
1062                        if (measure
1063                                        .startsWith(DCWormsConstants.TASKS_QUEUE_LENGTH_MEASURE_NAME)) {
1064                                return stats.average(measure);
1065                        }
1066                }
1067                return 0;
1068        }
1069       
1070        private TaskStats createTaskStats(Executable task) {
1071                TaskStats taskStats = new TaskStats(task, startSimulationTime);
1072                String uniqueTaskID = taskStats.getJobID() + "_" + taskStats.getTaskID();
1073                taskStats.setProcessorsName(task_processorsMap.get(uniqueTaskID));
1074                return taskStats;
1075        }
1076
1077        private JobStats createJobStats(List<TaskStats> tasksStats) {
1078
1079                String jobID = ((TaskStats) tasksStats.get(0)).getJobID();
1080                JobStats jobStats = new JobStats(jobID);
1081                double maxCj = 0;
1082
1083                for (int i = 0; i < tasksStats.size(); i++) {
1084
1085                        TaskStats task = (TaskStats) tasksStats.get(i);
1086                        jobStats.meanTaskStartTime.add(task.getStartTime());
1087                        jobStats.meanTaskCompletionTime.add(task.getCompletionTime());
1088                        maxCj = Math.max(maxCj, task.getCompletionTime());
1089                        jobStats.meanTaskExecutionTime.add(task.getExecutionTime());
1090                        jobStats.meanTaskWaitingTime.add(task.getWaitingTime());
1091                        jobStats.meanTaskFlowTime.add(task.getFlowTime());
1092                        jobStats.meanTaskGQ_WaitingTime.add(task.getGQ_WaitingTime());
1093                        jobStats.lateness.add(task.getLateness());
1094                        jobStats.tardiness.add(task.getTardiness());
1095                }
1096                jobStats.makespan.add(maxCj);
1097
1098                return jobStats;
1099        }
1100
1101        private void createAccumulatedTaskSimulationStatistic(TaskStats taskStats) {
1102                accStats.meanTaskFlowTime.add(taskStats.getFlowTime());
1103                accStats.meanTaskExecutionTime.add(taskStats.getExecutionTime());
1104                accStats.meanTaskCompletionTime.add(taskStats.getCompletionTime());
1105                accStats.meanTaskWaitingTime.add(taskStats.getWaitingTime());
1106                accStats.meanTaskStartTime.add(taskStats.getStartTime());
1107
1108                accStats.lateness.add(taskStats.getLateness());
1109                accStats.tardiness.add(taskStats.getTardiness());
1110
1111                if (taskStats.getExecFinishDate() == -1) {
1112                        numOfNotExecutedTasks++;
1113                }
1114                if (taskStats.getTardiness() > 0.0) {
1115                        numOfdelayedTasks++;
1116                }
1117
1118                maxCj = Math.max(maxCj, taskStats.getCompletionTime());
1119        }
1120
1121        private void createTaskDiagramData(Executable task) {
1122                String uniqueTaskID = task.getJobId() + "_" + task.getId();
1123
1124                String resID = task.getSchedulerName();
1125
1126                long execStartTime = Double.valueOf(task.getExecStartTime()).longValue() * MILLI_SEC;
1127                long execEndTime = Double.valueOf(task.getFinishTime()).longValue() * MILLI_SEC;
1128
1129                TaskSeries taskRes = ganttDiagramTaskSeriesCollection.getSeries(resID);
1130                if (taskRes == null) {
1131                        taskRes = new TaskSeries(resID);
1132                        ganttDiagramTaskSeriesCollection.add(taskRes);
1133                }
1134                org.jfree.data.gantt.Task ganttTask = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(execStartTime),
1135                                new Date(execEndTime));
1136                if (!task.isFinished()) {
1137                        ganttTask.setPercentComplete(1.0);
1138                }
1139                taskRes.add(ganttTask);
1140        }
1141
1142        private void createTaskWaitingTimeDiagramData(Executable task) {
1143                String uniqueTaskID = task.getJobId() + "_" + task.getId();
1144
1145                String resID = task.getSchedulerName();
1146
1147                long execStartTime = Double.valueOf(task.getExecStartTime()).longValue() * MILLI_SEC;
1148                long execEndTime = Double.valueOf(task.getFinishTime()).longValue() * MILLI_SEC;
1149
1150                TaskSeries waitRes = ganttDiagramWaitingTimeSeriesCollection.getSeries(resID);
1151                if (waitRes == null) {
1152                        waitRes = new TaskSeries(resID);
1153                        ganttDiagramWaitingTimeSeriesCollection.add(waitRes);
1154                }
1155
1156                long sub = Double.valueOf(task.getSubmissionTime()).longValue() * MILLI_SEC;
1157                org.jfree.data.gantt.Task wait_exec = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(sub), new Date(
1158                                execEndTime));
1159                org.jfree.data.gantt.Task exec = new org.jfree.data.gantt.Task(uniqueTaskID, new Date(execStartTime), new Date(
1160                                execEndTime));
1161                if (!task.isFinished()) {
1162                        exec.setPercentComplete(1.0);
1163                }
1164                wait_exec.addSubtask(wait_exec);
1165                wait_exec.addSubtask(exec);
1166                waitRes.add(wait_exec);
1167        }
1168
1169        private boolean saveTaskGanttDiagrams() {
1170
1171                JFreeChart taskDiagram = null;
1172                JFreeChart waitingTimeDiagram = null;
1173
1174                if (!generateDiagrams)
1175                        return false;
1176
1177                String fileName = new File(outputFolderName, DIAGRAMS_FILE_NAME_PREFIX + simulationIdentifier + "_")
1178                                .getAbsolutePath();
1179
1180                String chartName = "Task diagram for " + DataCenterWorkloadSimulator.SIMULATOR_NAME;
1181                String simulationTime = "Simulation time";
1182                Title subtitle = new TextTitle("created for \"" + simulationIdentifier + "\" at "
1183                                + Calendar.getInstance().getTime().toString());
1184
1185                if (configuration.creatediagrams_tasks) {
1186                        taskDiagram = getTaskDiagram(chartName, subtitle, simulationTime);
1187                        if (!saveCategoryChart(taskDiagram, fileName + "Tasks", null /* "{0}" */))
1188                                return false;
1189                }
1190
1191                chartName = "Task waiting times diagram for " + DataCenterWorkloadSimulator.SIMULATOR_NAME;
1192                if (configuration.creatediagrams_taskswaitingtime) {
1193                        waitingTimeDiagram = getWaitingTimeDiagram(chartName, subtitle, simulationTime);
1194                        if (!saveCategoryChart(waitingTimeDiagram, fileName + "Waiting_Time", null /* "Task {1} at {0}" */))
1195                                return false;
1196                }
1197
1198                return true;
1199        }
1200
1201        private JFreeChart getTaskDiagram(String chartName, Title subtitle, String simulationTime) {
1202                String tasks = "Tasks";
1203                boolean urls = false;
1204                boolean tooltip = true;
1205                boolean legend = true;
1206                JFreeChart chart = ChartFactory.createGanttChart(chartName, tasks, simulationTime,
1207                                ganttDiagramTaskSeriesCollection, legend, tooltip, urls);
1208                chart.addSubtitle(subtitle);
1209                GanttRenderer re = (GanttRenderer) chart.getCategoryPlot().getRenderer();
1210                re.setCompletePaint(Color.black);
1211                return chart;
1212        }
1213
1214        private JFreeChart getWaitingTimeDiagram(String chartName, Title subtitle, String simulationTime) {
1215                String tasks = "Tasks";
1216                boolean urls = false;
1217                boolean tooltip = true;
1218                boolean legend = true;
1219                JFreeChart chart = ChartFactory.createGanttChart(chartName, tasks, simulationTime,
1220                                ganttDiagramWaitingTimeSeriesCollection, legend, tooltip, urls);
1221                chart.addSubtitle(subtitle);
1222                chart.getPlot().setForegroundAlpha(ALPHA);
1223                GanttRenderer re = (GanttRenderer) chart.getCategoryPlot().getRenderer();
1224                re.setCompletePaint(Color.black);
1225                return chart;
1226        }
1227
1228        private boolean saveCategoryChart(JFreeChart c, String fileName, String labelFormat) {
1229                c.setNotify(false);
1230                c.setAntiAlias(true);
1231                c.setTextAntiAlias(true);
1232                c.setBorderVisible(false);
1233
1234                CategoryPlot categoryplot = (CategoryPlot) c.getPlot();
1235                categoryplot.setDomainGridlinesVisible(true);
1236
1237                if (labelFormat != null) {
1238                        CategoryItemRenderer rend = categoryplot.getRenderer();
1239                        rend.setBaseItemLabelsVisible(true);
1240                        ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER);
1241                        rend.setBasePositiveItemLabelPosition(position);
1242                        NumberFormat nf = NumberFormat.getInstance();
1243                        CategoryItemLabelGenerator gen = new StandardCategoryItemLabelGenerator(labelFormat, nf);
1244                        rend.setBaseItemLabelGenerator(gen);
1245                }
1246
1247                int rows = c.getCategoryPlot().getDataset().getColumnKeys().size();
1248
1249                int height = 900;
1250                if (rows > 45) {
1251                        height = rows * 20;
1252                }
1253                int width = calculateChartWidth(c);
1254                CategoryItemRenderer rend = c.getCategoryPlot().getRenderer();
1255
1256                for (int i = 0; i < c.getCategoryPlot().getDataset().getRowKeys().size(); i++) {
1257                        Paint collor = c.getCategoryPlot().getDrawingSupplier().getNextPaint();
1258                        rend.setSeriesOutlinePaint(i, collor);
1259                        rend.setSeriesPaint(i, collor);
1260                }
1261
1262                ChartRenderingInfo info = new ChartRenderingInfo();
1263                // info.setEntityCollection(null);
1264                File f = new File(fileName + "." + ImageFormat.PNG);
1265                final String dcwormsSubtitle = "Created by " + DataCenterWorkloadSimulator.SIMULATOR_NAME + " http://www.gssim.org/";
1266                c.addSubtitle(new TextTitle(dcwormsSubtitle));
1267                boolean encodeAlpha = false;
1268                int compression = 9;
1269                try {
1270                        ChartUtilities.saveChartAsPNG(f, c, width, height, info, encodeAlpha, compression);
1271
1272                } catch (IOException e) {
1273                        e.printStackTrace();
1274                        return false;
1275                } catch (Exception e) {
1276                        if (log.isErrorEnabled())
1277                                log.error("The png file (" + fileName
1278                                                + ")\nwill not be generated (It can be too large data size problem)", e);
1279                } catch (Throwable t) {
1280                        log.error("The png file (" + fileName + ")\nwill not be generated (It can be too large data size problem)",
1281                                        t);
1282                }
1283
1284                return true;
1285        }
1286
1287        private int calculateChartWidth(JFreeChart c) {
1288
1289                int ganttWidth = GANTT_WIDTH;
1290                int rows = c.getCategoryPlot().getDataset().getColumnKeys().size();
1291
1292                if (rows > 45) {
1293                        int height = rows * 20;
1294                        ganttWidth = Math.max((int) (height * 1.5), GANTT_WIDTH);
1295                }
1296                return ganttWidth;
1297        }
1298
1299        private static class JobIdComparator implements Comparator<JobInterface<?>> {
1300
1301                public int compare(JobInterface<?> o1, JobInterface<?> o2) {
1302                        Integer o1int;
1303                        Integer o2int;
1304                        try{
1305                                o1int = Integer.parseInt(o1.getId());
1306                                o2int = Integer.parseInt(o2.getId());
1307                                return o1int.compareTo(o2int);
1308                        } catch(NumberFormatException e){
1309                                return o1.getId().compareTo(o2.getId());
1310                        }
1311                }
1312        }
1313       
1314        private static class MapPEIdComparator implements Comparator<String> {
1315
1316                public int compare(String o1, String o2)  {
1317                        Integer o1int;
1318                        Integer o2int;
1319
1320                        o1int = Integer.parseInt(o1.substring(o1.indexOf("_")+1));
1321                        o2int = Integer.parseInt(o2.substring(o2.indexOf("_")+1));
1322                        return o1int.compareTo(o2int);
1323                }
1324        }
1325
1326        public GSSAccumulator getStats(String name) {
1327                return statsData.get(name);
1328        }
1329
1330        public boolean accumulatedStats() {
1331                return configuration.createsimulationstatistics;
1332        }
1333
1334}
1335
1336class ResStat{
1337       
1338        public long getStartDate() {
1339                return startDate;
1340        }
1341        public void setStartDate(long startDate) {
1342                this.startDate = startDate;
1343        }
1344        public long getEndDate() {
1345                return endDate;
1346        }
1347        public void setEndDate(long endDate) {
1348                this.endDate = endDate;
1349        }
1350        public String getTaskID() {
1351                return taskID;
1352        }
1353        public void setTaskID(String taskID) {
1354                this.taskID = taskID;
1355        }
1356
1357        public ResStat( String peName, long startDate, long endDate, String taskID) {
1358                super();
1359                this.startDate = startDate;
1360                this.endDate = endDate;
1361                this.taskID = taskID;
1362                this.peName = peName;
1363        }
1364        public String getPeName() {
1365                return peName;
1366        }
1367        public void setPeName(String peName) {
1368                this.peName = peName;
1369        }
1370        public ResStat(String peName, ResourceType resType, long startDate, long endDate, String taskID) {
1371                super();
1372                this.peName = peName;
1373                this.resType = resType;
1374                this.startDate = startDate;
1375                this.endDate = endDate;
1376                this.taskID = taskID;
1377        }
1378        String peName;
1379        ResourceType resType;
1380        long startDate;
1381        long endDate;
1382        String taskID;
1383
1384        public ResourceType getResType() {
1385                return resType;
1386        }
1387        public void setResType(ResourceType resType) {
1388                this.resType = resType;
1389        }
1390}
1391
1392enum Stats{
1393        textLoad,
1394        chartLoad,
1395        textEnergy,
1396        chartEnergy,
1397        textAirFlow,
1398        chartAirFlow;
1399}
Note: See TracBrowser for help on using the repository browser.