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

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