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

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