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

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