source: xssim/trunk/src/simulator/GridSchedulingSimulator.java @ 159

Revision 159, 40.7 KB checked in by wojtekp, 13 years ago (diff)
  • Property svn:mime-type set to text/plain
Line 
1package simulator;
2
3//import eduni.cloudsim.GSSIM;
4import eduni.simjava.Sim_system;
5import gridsim.GridSim;
6import gridsim.gssim.GssimConstants;
7import gridsim.gssim.network.ExtendedGridSim;
8import gridsim.gssim.network.ExtendedGridSimCore;
9import gridsim.gssim.network.ExtendedGridSimTags;
10import gridsim.gssim.resource.AbstractComputingResource;
11import gssim.schedframe.scheduling.plugin.grid.network.manager.Topology;
12import gssim.schedframe.scheduling.plugin.grid.network.utils.GSSIMNetworkReader;
13
14import java.io.File;
15import java.io.FileInputStream;
16import java.io.FileNotFoundException;
17import java.io.FileOutputStream;
18import java.io.FileReader;
19import java.io.FileWriter;
20import java.io.FilenameFilter;
21import java.io.IOException;
22import java.io.PrintStream;
23import java.security.InvalidParameterException;
24import java.text.NumberFormat;
25import java.util.ArrayList;
26import java.util.Calendar;
27import java.util.Date;
28
29import javax.swing.JFileChooser;
30import javax.swing.filechooser.FileFilter;
31
32import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
33import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
34import org.apache.commons.logging.Log;
35import org.apache.commons.logging.LogFactory;
36import org.joda.time.DateTimeUtilsExt;
37import org.qcg.broker.schemas.jobdesc.QcgJob;
38
39import simulator.stats.AccumulatedStatistics;
40import simulator.stats.implementation.GSSimStatistics;
41import simulator.utils.LogErrStream;
42import simulator.workload.WorkloadLoader;
43import simulator.workload.reader.archive.AbstractWAReader;
44import simulator.workload.reader.archive.WAReader;
45import simulator.workload.reader.xmlJob.Grms3XmlJobReader;
46import simulator.workload.reader.xmlJob.XMLJobReader;
47import test.rewolucja.GSSimUsersNew;
48import test.rewolucja.resources.physical.base.ComputingResource;
49import test.rewolucja.resources.physical.implementation.DataCenter;
50import test.rewolucja.resources.reader.TempResourceReader;
51import test.rewolucja.resources.utils.ResourceController;
52import cern.jet.random.Uniform;
53import cern.jet.random.engine.MersenneTwister64;
54
55/**
56 * The main class of the Grid Scheduling Simulator. It has the
57 * {@link #main(String[])} method used to invoke the program. This class also
58 * provides second possibility to start the simulator, namely one may use the
59 * {@link #performSimulation(ConfigurationOptions, GSSimStatisticsOld)} method.
60 * In this case, the input parameter, describing the simulation options, must be
61 * earlier prepared. The results of the simulation can be acquired using the
62 * {@link #getAccumulatedStatistics()} method.
63 *
64 * @author Stanislaw Szczepanowski
65 */
66public class GridSchedulingSimulator {
67
68        /**
69         * The name of the simulator application
70         */
71        public static final String SIMULATOR_NAME = "Grid Scheduling Simulator";
72
73        /**
74         * GridSim statistics output filename
75         */
76        public static final String GridSim_stat = "GridSim_stat.txt";
77
78        /**
79         * SimJava2 report filename
80         */
81        public static final String sim_report = "sim_report";
82
83        /**
84         * SimJava2 trace filename
85         */
86        public static final String sim_trace = "sim_trace";
87
88        /**
89         * The name of the file with the statistics for the whole run of the
90         * experiment
91         */
92        public static final String globalStatisticsFileName = "Statistics.txt";
93
94        /**
95         * Stores the statistical data of last run of the simulator (it may consist
96         * of several runs of simulations)
97         */
98        protected static AccumulatedStatistics accumulatedStatistics;
99
100        /**
101         * Determines the maximum fraction digits when printing floating point
102         * values
103         */
104        public static int MAXIMUM_FRACTION_DIGITS = 3;
105
106        /**
107         * The format of the numbers that will be printed
108         */
109        public static NumberFormat DFAULT_NUMBER_FORMAT = NumberFormat
110                        .getInstance();
111        static {
112                DFAULT_NUMBER_FORMAT.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); // 0,001
113        }
114
115        protected static int MAXIMUM_NETWORK_FRACTION_DIGITS = 6;
116        // protected static NumberFormat DFAULT_NUMBER_FORMAT =
117        // NumberFormat.getInstance();
118        public static NumberFormat NETWORK_NUMBER_FORMAT = NumberFormat
119                        .getInstance();
120        static {
121                // DFAULT_NUMBER_FORMAT.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS);
122                NETWORK_NUMBER_FORMAT
123                                .setMaximumFractionDigits(MAXIMUM_NETWORK_FRACTION_DIGITS);
124        }
125
126        private Log log = LogFactory.getLog(GridSchedulingSimulator.class);
127
128        protected ArrayList<GSSimUsers> wl_ = new ArrayList<GSSimUsers>();
129        protected ArrayList<GridBroker> brokerInterface_ = new ArrayList<GridBroker>();
130        // protected ArrayList<String>statsOutputPath_ = new ArrayList<String>();
131        protected AbstractComputingResource resources_[];
132        protected String statsOutputPath;
133        protected static int simulationRunNumber = 0;
134
135        /**
136         * Default empty constructor
137         */
138        public GridSchedulingSimulator() {
139        }
140
141        /**
142         * The main method to start the simulation the accepted arguments are:
143         * args[0] - the name of the resource bundle file with the configuration
144         * args[1] (optional) - the number of simulations that are to be performed
145         * (the default value is 1)
146         *
147         * @param args
148         *            the arguments passed to the application
149         */
150        public static void main(String[] args) {
151                GridSchedulingSimulator gssim = new GridSchedulingSimulator();
152                gssim.run(args);
153        }
154
155        public void run(String args[]) {
156                System.setErr(new PrintStream(new LogErrStream(log)));
157
158                String propertiesFileName = null;
159                if (args.length == 0) {
160                        JFileChooser ch = new JFileChooser(".");
161                        FileFilter filter = new FileFilter() {
162                                @Override
163                                public boolean accept(File f) {
164                                        return f.getName().endsWith(".properties")
165                                                        || f.isDirectory();
166                                }
167
168                                @Override
169                                public String getDescription() {
170                                        return "GSSim experiment file";
171                                }
172                        };
173                        ch.setFileFilter(filter);
174                        ch.setDialogTitle("Choose the GSSim simulation experiment file");
175                        int result = ch.showOpenDialog(ch);
176                        if (result == JFileChooser.APPROVE_OPTION) {
177                                propertiesFileName = ch.getSelectedFile().getAbsolutePath();
178                        } else {
179                                if (log.isFatalEnabled())
180                                        log.fatal("Resource bundle file name was not provided.");
181                                return;
182                        }
183                } else if (args.length == 2 && "-multiuser".equals(args[0])) {
184                        runMultiuser(args[1], this);
185                        return;
186                } else {
187                        propertiesFileName = args[0];
188                }
189
190                ConfigurationOptions configurationOptions = ConfigurationOptions
191                                .getConfiguration(propertiesFileName);
192                int noOfSimulations = 1; // default value is one
193
194                if(configurationOptions.getNumberOfSimulations() > 1)
195                        noOfSimulations = configurationOptions.getNumberOfSimulations();
196                else if (args.length == 2) {// second parameter is given
197                        noOfSimulations = Integer.parseInt(args[1]);
198                        if (noOfSimulations < 1) {
199                                throw new InvalidParameterException(
200                                                "Number of simulations cannot be less than 1");
201                        }
202                }
203
204                if (log.isInfoEnabled())
205                        log.info(":: Starting " + SIMULATOR_NAME + ". " + noOfSimulations
206                                        + " simulation runs will be performed. ::");
207
208                accumulatedStatistics = new AccumulatedStatistics(noOfSimulations);
209
210                File outputDir = null;
211
212                try {
213                        outputDir = prepareDirecotry(configurationOptions);
214                } catch (Exception e) {
215                        if (log.isErrorEnabled())
216                                log.error("FAILED to create the output path", e);
217                        return;
218                }
219
220                File outputPropertiesFile = new File(outputDir, "experiment.properties");
221
222                for (int i = 0; i < noOfSimulations; ++i) {
223                        simulationRunNumber++;
224                        String simulationIdentifier = "Simulation " + (i + 1);
225                        try {
226                                // GSSimStatisticsNew simulationStatistics = new
227                                // GSSimStatisticsNew(simulationIdentifier,
228                                // configurationOptions);
229                                // accumulatedStatistics.add(simulationStatistics);
230
231                                if (configurationOptions.networkTopologyFileName != null)
232                                        performNetworkSimulation(simulationIdentifier,
233                                                        configurationOptions); // run the simulation using
234                                // network extension
235                                else
236                                        performSimulation(simulationIdentifier,
237                                                        configurationOptions); // run the simulation
238
239                        } catch (Exception e) {
240                                if (log.isErrorEnabled())
241                                        log.error("ERROR in simulation run \""
242                                                        + simulationIdentifier + "\":", e);
243                                break;
244                        }
245                }
246                /*
247                 * String outputPath; String outputFile = globalStatisticsFileName; if
248                 * (configurationOptions.createScenario) { outputPath =
249                 * configurationOptions.outputFolder +
250                 * configurationOptions.statsOutputSubfolderNameCreate + File.separator;
251                 * } else { String prefix = null; if(configurationOptions.inputFolder !=
252                 * null) { prefix = configurationOptions.inputFolder; } else
253                 * if(configurationOptions.inputWorkloadFileName != null){ prefix = new
254                 * File(configurationOptions.inputWorkloadFileName).getParent(); } else
255                 * { prefix = System.getProperty("user.dir"); }
256                 *
257                 *
258                 * outputPath = prefix +"/"+
259                 * configurationOptions.statsOutputSubfolderNameRerad + File.separator;
260                 * }
261                 *
262                 * if(log.isInfoEnabled()) log.info(":: Creating statistics ... ");
263                 *
264                 * //clean all gantts /*File file = new File(outputPath); File
265                 * fileList[] = file.listFiles(); for(int i = 0; i < fileList.length;
266                 * i++){ File tmpFile = fileList[i]; String name = tmpFile.getName();
267                 * if(name.length() > 4){ String subName = name.substring(0, 5);
268                 * if(subName.compareTo("Gantt") == 0){ tmpFile.delete(); } } }
269                 */
270                //accumulatedStatistics.saveStatistics();
271
272                if (log.isInfoEnabled())
273                        log.info("Done :: " + SIMULATOR_NAME + " has finished "
274                                        + noOfSimulations + " simulation runs ::");
275
276                // fixed name with z in front to be last file in alphabetical order
277
278                System.out.flush();
279                System.err.flush();
280
281                try {
282                        copyFile(new File(propertiesFileName), outputPropertiesFile);
283                } catch (IOException e) {
284                        log
285                                        .error("IO exception occured during copying properties file to output path");
286                }
287
288                FilenameFilter fileFilter = new FilenameFilter() {
289                        public boolean accept(File dir, String name) {
290                                return (!name.endsWith(".sjg") && !name.endsWith(".png"));
291                        }
292                };
293
294                File tarArchive = new File(outputDir, "results.tar");
295
296                File networkTopologyFile = (configurationOptions.networkTopologyFileName == null) ? null
297                                : new File(configurationOptions.networkTopologyFileName);
298
299                try {
300                        createResultsTar(tarArchive, outputDir.listFiles(fileFilter),
301                                        networkTopologyFile);
302                } catch (IOException e) {
303                        log.error("IOException occured while creating archive file", e);
304                }
305        }
306
307        public void runMultiuser(String rootDirPath, GridSchedulingSimulator gssim) {
308                /*
309                 * System.out.println("************ Runing in multiuser mode ************"
310                 * ); File mainDirectory = null; mainDirectory = new File(rootDirPath);
311                 * if(!mainDirectory.exists() || !mainDirectory.isDirectory()) throw new
312                 * RuntimeException("Second argument must be a root directory name.");
313                 *
314                 * java.io.FileFilter dirFilter = new WorkloadDirectoryFilter();
315                 * java.io.FileFilter propertiesFilter = new PropertiesFileFilter();
316                 *
317                 * File workloadDirs[] = mainDirectory.listFiles(dirFilter); File
318                 * propertiesFile[] = null; File dir;
319                 *
320                 * File localResProperiesFiles[] =
321                 * mainDirectory.listFiles(propertiesFilter); ConfigurationOptions
322                 * configurationOptions =
323                 * ConfigurationOptions.getConfiguration(localResProperiesFiles
324                 * [0].getAbsolutePath());
325                 *
326                 * //BEGIN: Initializing the GridSim:
327                 *
328                 * // use simulation start time from one, specific swf file String
329                 * fileName = configurationOptions.inputWorkloadFileName; Date date =
330                 * null; try { date = AbstractSWFJobReader.getStartTime(fileName); }
331                 * catch (IOException e1) { date = new Date(0l); } catch
332                 * (NoSuchCommentException e1) { date = new Date(0l); }
333                 *
334                 * Calendar calendar = Calendar.getInstance(); calendar.setTime(date);
335                 *
336                 * boolean traceFlag = true; // means: trace GridSim events/activities
337                 *
338                 * String[] excludeFromFile = {""}, excludeFromProcessing = {""}; String
339                 * reportFileName = GssConstants.BrokerInterfaceEntityName+"_0"; //FIXME
340                 * solve this issue more elegant - this is a result of many brokers in
341                 * simulation
342                 *
343                 * GridSim.init(workloadDirs.length, calendar, traceFlag,
344                 * excludeFromFile, excludeFromProcessing, reportFileName);
345                 *
346                 * //END: Initializing the GridSim:
347                 *
348                 * VirtualClock vClock = VirtualClock.initialize();
349                 *
350                 * //Startup of the random number generators must be set up with a
351                 * random seed that is greater than zero //if seed is not given then all
352                 * consecutive simulations are the same //if seed < 0 then the random
353                 * numbers are equal to zero Uniform uniform = new Uniform(new
354                 * MersenneTwister64(new Date())); //seed should be > 0 and fits to int
355                 * size (which is also important) long seed = uniform.nextLongFromTo(1,
356                 * Integer.MAX_VALUE); assert seed > 0 && seed <= Integer.MAX_VALUE :
357                 * "Initial seed is <= 0, what is improper"; Sim_system.set_seed(seed);
358                 *
359                 * accumulatedStatistics = new AccumulatedStatistics(); try {
360                 *
361                 * // wczytanie i zbudowanie opisu swiata
362                 *
363                 * ResourceGeneratorInterface hostDescGenerator = new ResourceGenerator(
364                 * configurationOptions.forecastFinishTimePluginName,
365                 * configurationOptions.localAllocPolicyPluginName);
366                 * hostDescGenerator_.add(hostDescGenerator);
367                 * hostDescGenerator.readConfigurationHostsDescriptionXMLFile(
368                 * configurationOptions.resdescFileName);
369                 *
370                 * hostDescGenerator.createResources(vClock); resources_ =
371                 * hostDescGenerator.getCreatedResources();
372                 * System.out.println("localResources: "
373                 * +localResProperiesFiles[0].getAbsolutePath());
374                 *
375                 * // wczytanie i przygotowanie opisu zadan for(int i = 0; i <
376                 * workloadDirs.length; i++){ dir = workloadDirs[i]; propertiesFile =
377                 * dir.listFiles(propertiesFilter); if(propertiesFile.length == 0) throw
378                 * new RuntimeException("No properties file in "+dir.getPath());
379                 * if(propertiesFile.length > 1) throw new
380                 * RuntimeException("Leave only one properties file in "+dir.getPath());
381                 *
382                 * System.out.println(propertiesFile[0].getAbsolutePath());
383                 * configurationOptions =
384                 * ConfigurationOptions.getConfiguration(propertiesFile
385                 * [0].getAbsolutePath()); GSSimStatistics simulationStatistics = new
386                 * GSSimStatistics("stats_for_"+propertiesFile[0].getName());
387                 * simulationStatistics_.add(simulationStatistics);
388                 * accumulatedStatistics.add(simulationStatistics);
389                 * gssim.prepareSimulation(configurationOptions, simulationStatistics,
390                 * vClock);
391                 *
392                 * }
393                 *
394                 *
395                 * gssim.runMultiuserSimulation();
396                 *
397                 * } catch (Exception e) { e.printStackTrace(); }
398                 */
399        }
400
401        public void prepareSimulation(ConfigurationOptions options,
402                        GSSimStatistics simulationStatistics/* , VirtualClock vClock */)
403                        throws Exception {
404
405                /*
406                 * System.out.println("\n:: " +
407                 * simulationStatistics.getSimulationIdentifier() + "\" ::");
408                 * System.out.print(":: In the the mode of "); String statsOutputPath =
409                 * null; if (options.createScenario) { File outputFolderFile = new
410                 * File(options.outputFolder); if (! outputFolderFile.exists()) { if (!
411                 * outputFolderFile.mkdirs()) throw new
412                 * IOException("Cannot create the output path: "
413                 * +statsOutputPath+". Cause: "); }
414                 *
415                 * System.out.println("CREATING SCENARIO ::"); statsOutputPath =
416                 * options.outputFolder + STATS_OUTPUT_SUBFOLDER_NAME_CREATE; } else {
417                 * System.out.println("READING SCENARIO ::"); statsOutputPath =
418                 * options.inputFolder + STATS_OUTPUT_SUBFOLDER_NAME_READ; }
419                 * statsOutputPath += File.separator;
420                 * statsOutputPath_.add(statsOutputPath);
421                 *
422                 * System.out.println();
423                 *
424                 * Sim_system.set_trace_detail(true, true, true);
425                 * Sim_system.generate_graphs(statsOutputPath +
426                 * GssConstants.GraphsFileName);
427                 * Sim_system.set_trace_level(Integer.MAX_VALUE);
428                 *
429                 * // reseting the gridlet numbering //
430                 * GssConstants.resetGridletIDSequencer();
431                 *
432                 * JobGenerator <QcgJob>jobDescGenerator = new JobGenerator_GRMS3(); if
433                 * (options.createScenario) {
434                 * jobDescGenerator.generateWorkload(options.workloadDescFileName,
435                 * options.outputFolder, options.overwriteFiles,
436                 * options.outputWorkloadFileName);
437                 * jobDescGenerator.performPostprocessing(options.resdescFileName,
438                 * options.outputFolder, options.outputWorkloadFileName);
439                 * options.inputFolder = options.outputFolder;
440                 * options.inputWorkloadFileName = options.outputWorkloadFileName; }
441                 *
442                 * if(options.createXMLSupplement){
443                 * jobDescGenerator.generateXMLSupplement(options.workloadDescFileName,
444                 * options.inputWorkloadFileName, options.outputFolder,
445                 * options.overwriteFiles); }
446                 *
447                 * jobDescGenerator.loadWorkload(options.inputFolder,
448                 * options.inputWorkloadFileName);
449                 *
450                 *
451                 * if (!jobDescGenerator.isReady()) { System.err.println(
452                 * "Error: xml job genereator is not fully initialized. The simulation will terminate."
453                 * ); System.exit(1); }
454                 *
455                 *
456                 * //creating the broker interface entity GridScheduler brokerInterface
457                 * = new GridScheduler(GssConstants.BrokerInterfaceEntityName + "_" +
458                 * brokerInterface_.size(), options, jobDescGenerator.getJobCount(),
459                 * jobDescGenerator.getTaskCount());
460                 *
461                 * GSSimUsers<JobGridlet> wl = new
462                 * GSSimUsers<JobGridlet>("GridUsers"+wl_.size(),
463                 * GssConstants.BrokerInterfaceEntityName + "_" +
464                 * brokerInterface_.size(), jobDescGenerator);
465                 *
466                 * for(int i = 0; i < resources_.length; i++){
467                 * brokerInterface.addToResourceSubset(resources_[i].get_id()); }
468                 *
469                 * wl_.add(wl); brokerInterface_.add(brokerInterface);
470                 *
471                 * //create the output folder File statsOutputPathFile = new
472                 * File(statsOutputPath); if (! statsOutputPathFile.exists()) { if (!
473                 * statsOutputPathFile.mkdirs()) throw new
474                 * IOException("Cannot create the output (stats) path: "
475                 * +statsOutputPath+". Cause: "); }
476                 */
477
478        }
479
480        /**
481         * Starts a single simulation run.
482         *
483         * @param options
484         *            the configuration options according to which the simulation is
485         *            to be performed
486         * @param simulationStatistics
487         *            the statistics object that is to be filled after the
488         *            simulation run
489         * @throws Exception
490         *             any exception that may occur
491         */
492        public void performSimulation(String simulationIdentifier,
493                        ConfigurationOptions options) throws Exception {
494                // Startup of the random number generators must be set up with a random
495                // seed that is greater than zero
496                // if seed is not given then all consecutive simulations are the same
497                // if seed < 0 then the random numbers are equal to zero
498                Uniform uniform = new Uniform(new MersenneTwister64(new Date()));
499                // seed should be > 0 and fits to int size (which is also important)
500                long seed = uniform.nextLongFromTo(1, Integer.MAX_VALUE);
501                if (log.isDebugEnabled())
502                        log.debug("Shuffled initial seed: " + seed);
503
504                assert seed > 0 && seed <= Integer.MAX_VALUE : "Initial seed is <= 0, what is improper";
505                Sim_system.set_seed(seed);
506
507                long startSimulation = System.currentTimeMillis();
508                if (log.isInfoEnabled()) {
509                        log.info(":: Starting simulation run: \"" + simulationIdentifier
510                                        + "\" ::");
511                        log.info(":: In the the mode of ");
512                }
513                /*
514                 * String statsOutputPath = null; if (options.createScenario) { File
515                 * outputFolderFile = new File(options.outputFolder); if (!
516                 * outputFolderFile.exists()) { if (! outputFolderFile.mkdirs()) throw
517                 * new
518                 * IOException("Cannot create the output path: "+statsOutputPath+". Cause: "
519                 * ); }
520                 *
521                 * if(log.isInfoEnabled()) log.info("CREATING SCENARIO ::");
522                 * statsOutputPath = options.outputFolder +
523                 * options.statsOutputSubfolderNameCreate; } else {
524                 * if(log.isInfoEnabled()) log.info("READING SCENARIO ::"); String
525                 * prefix = null; if(options.inputFolder != null){ prefix =
526                 * options.inputFolder; }else if(options.inputWorkloadFileName != null){
527                 * prefix = new File(options.inputWorkloadFileName).getParent(); }else{
528                 * prefix = System.getProperty("user.dir"); } statsOutputPath = prefix +
529                 * "/" + options.statsOutputSubfolderNameRerad; } statsOutputPath +=
530                 * File.separator;
531                 */
532
533                Sim_system.set_trace_detail(true, true, true);
534                Sim_system.generate_graphs(statsOutputPath
535                                + GssimConstants.GraphsFileName);
536                Sim_system.set_trace_level(Integer.MAX_VALUE);
537
538                XMLJobReader<QcgJob> xmlJobReader = null;
539                WAReader<QcgJob> swfReader = null;
540
541                String wlFileName = options.inputWorkloadFileName;
542
543                if (options.inputFolder != null) {
544                        File f = null;
545                        if (options.inputTar != null) {
546                                f = new File(options.inputFolder + File.separator
547                                                + options.inputTar);
548                        } else {
549                                f = new File(options.inputFolder);
550                        }
551
552                        xmlJobReader = new Grms3XmlJobReader(f);
553
554                        wlFileName = options.inputFolder + File.separator
555                                        + options.inputWorkloadFileName;
556                }
557
558                swfReader = AbstractWAReader.getInstace(wlFileName);
559
560                WorkloadLoader workload = new WorkloadLoader(xmlJobReader, swfReader);
561                workload.load();
562
563                /*
564                 * if (options.createScenario) {
565                 * jobDescGenerator.generateWorkload(options.workloadDescFileName,
566                 * options.outputFolder, options.overwriteFiles,
567                 * options.outputWorkloadFileName);
568                 * jobDescGenerator.performPostprocessing(options.resdescFileName,
569                 * options.outputFolder, options.outputWorkloadFileName);
570                 * options.inputFolder = options.outputFolder;
571                 * options.inputWorkloadFileName = options.outputWorkloadFileName; }
572                 *
573                 * if(options.createXMLSupplement){
574                 * jobDescGenerator.generateXMLSupplement(options.workloadDescFileName,
575                 * options.inputWorkloadFileName, options.outputFolder,
576                 * options.overwriteFiles); }
577                 *
578                 * jobDescGenerator.loadWorkload(options.inputFolder,
579                 * options.inputWorkloadFileName);
580                 *
581                 *
582                 * if (!jobDescGenerator.isReady()) { System.err.println(
583                 * "Error: xml job genereator is not fully initialized. The simulation will terminate."
584                 * ); System.exit(1); }
585                 */
586                // BEGIN: Initializing the GridSim:
587                int numUser = 1; // the number of users in the experiment simulation
588                // (default 1)
589                // Date date = jobDescGenerator.getSimulationStartTime();
590                Date date = workload.getSimulationStartTime();
591                Calendar calendar = Calendar.getInstance();
592                if (date == null)
593                        calendar.setTimeInMillis(0L);
594                else
595                        calendar.setTime(date);
596
597                boolean traceFlag = true; // means: trace GridSim events/activities
598
599                String[] excludeFromFile = { "" }, excludeFromProcessing = { "" };
600                String reportFileName = GssimConstants.BrokerInterfaceEntityName;
601               
602                //GSSIM.init(numUser, calendar, traceFlag);
603                GridSim.init(numUser, calendar, traceFlag, excludeFromFile,
604                                excludeFromProcessing, "COMPUTING_GRID_0");
605                // END: Initializing the GridSim:
606
607                DateTimeUtilsExt.initVirtualTimeAccess(calendar);
608
609                // creating the broker interface entity
610                /*GridBroker brokerInterface = new GridBroker(
611                                GssimConstants.BrokerInterfaceEntityName, options, workload
612                                                .getJobCount(), workload.getTaskCount());*/
613
614                // creating the resources only after GridSim had been initialized
615                //AbstractComputingResource resources[] = null;
616                TempResourceReader resourceReader = new TempResourceReader(
617                                options);
618
619                //resources = new AbstractComputingResource[resourceReader
620                //              .getNoOfResources()];
621                //AbstractComputingResource resource = null;
622                //int i = 0;
623                //while ((resource = resourceReader.read()) != null
624                //              && i < resources.length) {
625                //      resources[i++] = resource;
626                //}
627
628                ResourceController rc = resourceReader.read();
629
630                GSSimUsersNew wl = new GSSimUsersNew("GridUsers",
631                                rc.getResources().getName(), workload);
632
633                // create the output folder
634                /*
635                 * File statsOutputPathFile = new File(statsOutputPath); if (!
636                 * statsOutputPathFile.exists()) { if (! statsOutputPathFile.mkdirs())
637                 * throw new
638                 * IOException("Cannot create the output (stats) path: "+statsOutputPath
639                 * +". Cause: "); }
640                 */
641
642                GridSim.startGridSimulation();
643                //GSSIM.startSimulation();
644                long stopSimulation = System.currentTimeMillis();
645
646                GSSimStatistics stats = new GSSimStatistics(simulationIdentifier,
647                                options, wl, statsOutputPath, rc);
648                accumulatedStatistics.add(stats);
649                if (log.isInfoEnabled())
650                        log.info("Generating statistics...");
651                stats.generateStatistics();
652
653                // Fill the statistical data
654                // simulationStatistics.setGenPEdiagram(false);
655                // simulationStatistics.gatherStatistics(wl, brokerInterface,
656                // resources);
657
658                // Print history
659                /*
660                 * simulationStatistics.printTasksInformation(new PrintStream( new
661                 * FileOutputStream( new File(statsOutputPath,
662                 * GssimConstants.tasksStatisitcsOutputFileName))),
663                 * options.printHistory);
664                 * simulationStatistics.printResourcesInformation(new PrintStream( new
665                 * FileOutputStream( new File(statsOutputPath,
666                 * GssimConstants.resourceStatisticsOutputFileName))));
667                 */
668
669                long duration = (stopSimulation - startSimulation) / 1000;
670                if (log.isInfoEnabled())
671                        log.info("The simulation run took " + duration + " seconds");
672
673                // Move output files to the output directory
674                String name = GridSim_stat;
675                String fileName = statsOutputPath + name;
676                if (!moveFile(name, fileName))
677                        if (log.isErrorEnabled())
678                                log.error("Error moving file " + fileName);
679
680                name = "sim_report";
681                fileName = statsOutputPath + name;
682                if (!moveFile(name, fileName))
683                        if (log.isErrorEnabled())
684                                log.error("Error moving file " + fileName);
685
686                name = "sim_trace";
687                fileName = statsOutputPath + name;
688                if (!moveFile(name, fileName))
689                        if (log.isErrorEnabled())
690                                log.error("Error moving file " + fileName);
691
692                // if necessary generate gifs from sjvg - need to rewrite the SJVG
693                // classes for public methods
694                if (log.isInfoEnabled())
695                        log.info(":: Finished simulation run: \"" + simulationIdentifier
696                                        + "\" ::");
697
698                System.out.flush();
699                System.err.flush();
700        }
701
702        /**
703         * Starts a single network simulation run.
704         *
705         * @param options
706         *            the configuration options according to which the simulation is
707         *            to be performed
708         * @param simulationStatistics
709         *            the statistics object that is to be filled after the
710         *            simulation run
711         * @throws Exception
712         *             any exception that may occur
713         */
714        public void performNetworkSimulation(String simulationIdentifier,
715                        ConfigurationOptions options) throws Exception {
716                // Startup of the random number generators must be set up with a random
717                // seed that is greater than zero
718                // if seed is not given then all consecutive simulations are the same
719                // if seed < 0 then the random numbers are equal to zero
720                Uniform uniform = new Uniform(new MersenneTwister64(new Date()));
721                // seed should be > 0 and fits to int size (which is also important)
722                long seed = uniform.nextLongFromTo(1, Integer.MAX_VALUE);
723                if (log.isDebugEnabled())
724                        log.debug("Shuffled initial seed: " + seed);
725
726                assert seed > 0 && seed <= Integer.MAX_VALUE : "Initial seed is <= 0, what is improper";
727                Sim_system.set_seed(seed);
728
729                long startSimulation = System.currentTimeMillis();
730                if (log.isInfoEnabled()) {
731                        log.info(":: Starting simulation run: \"" + simulationIdentifier
732                                        + "\" ::");
733                        log.info(":: In the the mode of ");
734                }
735                /*
736                 * String statsOutputPath = null; if (options.createScenario) { File
737                 * outputFolderFile = new File(options.outputFolder); if (!
738                 * outputFolderFile.exists()) { if (! outputFolderFile.mkdirs()) throw
739                 * new
740                 * IOException("Cannot create the output path: "+statsOutputPath+". Cause: "
741                 * ); }
742                 *
743                 * if(log.isInfoEnabled()) log.info("CREATING SCENARIO ::");
744                 * statsOutputPath = options.outputFolder +
745                 * options.statsOutputSubfolderNameCreate; } else {
746                 * if(log.isInfoEnabled()) log.info("READING SCENARIO ::"); String
747                 * prefix = null; if(options.inputFolder != null){ prefix =
748                 * options.inputFolder; }else if(options.inputWorkloadFileName != null){
749                 * prefix = new File(options.inputWorkloadFileName).getParent(); }else{
750                 * prefix = System.getProperty("user.dir"); } statsOutputPath = prefix +
751                 * "/" + options.statsOutputSubfolderNameRerad; } statsOutputPath +=
752                 * File.separator;
753                 */
754
755                Sim_system.set_trace_detail(true, true, true);
756                Sim_system.generate_graphs(statsOutputPath
757                                + GssimConstants.GraphsFileName);
758                Sim_system.set_trace_level(Integer.MAX_VALUE);
759
760                XMLJobReader<QcgJob> xmlJobReader = null;
761                WAReader<QcgJob> swfReader = null;
762                String wlFileName = options.inputWorkloadFileName;
763
764                if (options.inputFolder != null) {
765                        File f = new File(options.inputFolder);
766                        xmlJobReader = new Grms3XmlJobReader(f);
767                        if (f.isDirectory()) {
768                                wlFileName = options.inputFolder + File.separator
769                                                + options.inputWorkloadFileName;
770                        }
771                }
772
773                swfReader = AbstractWAReader.getInstace(wlFileName);
774
775                WorkloadLoader workload = new WorkloadLoader(xmlJobReader, swfReader);
776                workload.load();
777
778                /*
779                 * if (options.createScenario) {
780                 * jobDescGenerator.generateWorkload(options.workloadDescFileName,
781                 * options.outputFolder, options.overwriteFiles,
782                 * options.outputWorkloadFileName);
783                 * jobDescGenerator.performPostprocessing(options.resdescFileName,
784                 * options.outputFolder, options.outputWorkloadFileName);
785                 * options.inputFolder = options.outputFolder;
786                 * options.inputWorkloadFileName = options.outputWorkloadFileName; }
787                 *
788                 * if(options.createXMLSupplement){
789                 * jobDescGenerator.generateXMLSupplement(options.workloadDescFileName,
790                 * options.inputWorkloadFileName, options.outputFolder,
791                 * options.overwriteFiles); }
792                 *
793                 * jobDescGenerator.loadWorkload(options.inputFolder,
794                 * options.inputWorkloadFileName);
795                 *
796                 *
797                 * if (!jobDescGenerator.isReady()) { System.err.println(
798                 * "Error: xml job genereator is not fully initialized. The simulation will terminate."
799                 * ); System.exit(1); }
800                 */
801                // BEGIN: Initializing the GridSim:
802                int numUser = 1; // the number of users in the experiment simulation
803                // (default 1)
804                // Date date = jobDescGenerator.getSimulationStartTime();
805                Date date = workload.getSimulationStartTime();
806                Calendar calendar = Calendar.getInstance();
807                if (date == null)
808                        calendar.setTimeInMillis(0L);
809                else
810                        calendar.setTime(date);
811
812                boolean traceFlag = true; // means: trace GridSim events/activities
813
814                String[] excludeFromFile = { "" }, excludeFromProcessing = { "" };
815                String reportFileName = GssimConstants.BrokerInterfaceEntityName;
816
817                ExtendedGridSim
818                                .initNetworkType(ExtendedGridSimTags.RESERVATION_NET_FLOW_LEVEL);
819                ExtendedGridSimCore
820                                .initNetworkType(ExtendedGridSimTags.RESERVATION_NET_FLOW_LEVEL);
821                //ExtendedGridSim.init(numUser, calendar, traceFlag, excludeFromFile,
822                //              excludeFromProcessing, reportFileName);
823               
824                ExtendedGridSim.init(numUser, calendar, traceFlag, excludeFromFile,
825                                excludeFromProcessing, "COMPUTING_GRID_0");
826                // END: Initializing the GridSim:
827
828                DateTimeUtilsExt.initVirtualTimeAccess(calendar);
829
830                // creating the network broker interface entity
831                /*
832                 * NetworkGridBroker brokerInterface = new
833                 * NetworkGridBroker(GssimConstants.BrokerInterfaceEntityName, new
834                 * GSSIMFlowLink(GssimConstants.BrokerInterfaceEntityName + "_link",
835                 * Double .parseDouble("1")* 1000000, Double.parseDouble("300"),
836                 * Integer.parseInt("100000")), options, workload.getJobCount(),
837                 * workload.getTaskCount());
838                 */
839
840                // creating networktopology
841                Topology topology = GSSIMNetworkReader
842                                .createNetworkTopology(options.networkTopologyFileName);
843
844                // creating the network broker interface entity
845                /*NetworkGridBroker brokerInterface = new NetworkGridBroker(
846                                GssimConstants.BrokerInterfaceEntityName,
847                                ((GSSIMFlowLink) GSSIMNetworkReader.getBrokerLinkMapping().get(
848                                                GssimConstants.BrokerInterfaceEntityName)), topology,
849                                options, workload.getJobCount(), workload.getTaskCount());
850*/
851                AbstractComputingResource resources[] = null;
852        /*      ResourceReader resourceReader = new ResourceReader(
853                                options);
854
855                resources = new AbstractComputingResource[resourceReader
856                                .getNoOfResources()];
857                AbstractComputingResource resource = null;
858                int i = 0;
859                //while ((resource = resourceReader.read()) != null
860                //              && i < resources.length) {
861                //      resources[i++] = resource;
862                //}
863
864                AbstractResource res = resourceReader.close();
865
866                GSSimUsersNew wl = new GSSimUsersNew("GridUsers",
867                                res.getResourceName(), workload);
868
869*/
870                GSSIMNetworkReader.createResourceConnections();
871                /*
872                 * brokerInterface.networkManager.getTopology().printLinks();
873                 * brokerInterface.networkManager.getTopology().printResourcesNames();
874                 * brokerInterface.networkManager.getTopology().printRouters();
875                 * brokerInterface.networkManager.getTopology().printUsers();
876                 * List<DataLink> list=
877                 * brokerInterface.networkManager.getAbstractTopology().getLinks();
878                 * Iterator it=list.iterator(); while(it.hasNext()){ DataLink l =
879                 * (DataLink)it.next();
880                 * System.out.println(l.getId()+";"+l.getEndpoint1()
881                 * .getId()+";"+l.getEndpoint2().getId()); } List<Node> list2=
882                 * brokerInterface.networkManager.getAbstractTopology().getNodes();
883                 * Iterator it2=list2.iterator(); while(it2.hasNext()){ Node n =
884                 * (Node)it2.next();
885                 * System.out.println(n.getId()+";"+n.getType().toString()); }
886                 */
887
888
889                // create the output folder
890                /*
891                 * File statsOutputPathFile = new File(statsOutputPath); if (!
892                 * statsOutputPathFile.exists()) { if (! statsOutputPathFile.mkdirs())
893                 * throw new
894                 * IOException("Cannot create the output (stats) path: "+statsOutputPath
895                 * +". Cause: "); }
896                 */
897
898                ExtendedGridSim.startGridSimulation();
899                long stopSimulation = System.currentTimeMillis();
900
901                /*GSSimStatistics stats = new GSSimStatistics(simulationIdentifier,
902                                options, wl, null, resources, null, statsOutputPath);
903                accumulatedStatistics.add(stats);
904                if (log.isInfoEnabled())
905                        log.info("Generating statistics...");
906                stats.generateStatistics();*/
907
908                // Fill the statistical data
909                // GSSimStatistics simulationStatistics = new GSSimStatistics("old",
910                // options);
911                // simulationStatistics.setGenPEdiagram(false);
912                // simulationStatistics.gatherStatistics(wl, brokerInterface,
913                // resources);
914
915                // Print history
916                /*
917                 * simulationStatistics.printTasksInformation(new PrintStream( new
918                 * FileOutputStream( new File(statsOutputPath,
919                 * GssimConstants.tasksStatisitcsOutputFileName))),
920                 * options.printHistory);
921                 * simulationStatistics.printResourcesInformation(new PrintStream( new
922                 * FileOutputStream( new File(statsOutputPath,
923                 * GssimConstants.resourceStatisticsOutputFileName))));
924                 */
925
926                long duration = (stopSimulation - startSimulation) / 1000;
927                if (log.isInfoEnabled())
928                        log.info("The simulation run took " + duration + " seconds");
929
930                // Move output files to the output directory
931                String name = GridSim_stat;
932                String fileName = statsOutputPath + name;
933                if (!moveFile(name, fileName))
934                        if (log.isErrorEnabled())
935                                log.error("Error moving file " + fileName);
936
937                name = "sim_report";
938                fileName = statsOutputPath + name;
939                if (!moveFile(name, fileName))
940                        if (log.isErrorEnabled())
941                                log.error("Error moving file " + fileName);
942
943                name = "sim_trace";
944                fileName = statsOutputPath + name;
945                if (!moveFile(name, fileName))
946                        if (log.isErrorEnabled())
947                                log.error("Error moving file " + fileName);
948
949                // if necessary generate gifs from sjvg - need to rewrite the SJVG
950                // classes for public methods
951                if (log.isInfoEnabled())
952                        log.info(":: Finished simulation run: \"" + simulationIdentifier
953                                        + "\" ::");
954
955                System.out.flush();
956                System.err.flush();
957        }
958
959        /**
960         * Static method to move a file from given "from" location to "to" location
961         *
962         * @param from
963         *            from location
964         * @param to
965         *            to location
966         * @return true if the operation succeeded, false otherwise
967         */
968        public static boolean moveFile(String from, String to) {
969                File fromFile = new File(from);
970                File toFile = new File(to);
971                if (toFile.exists()) {
972                        if (!toFile.delete())
973                                return false;
974                }
975                if (!fromFile.renameTo(toFile)) {
976                        return false;
977                }
978                return true;
979        }
980
981        /**
982         * Removes the given directory no matter if it is empty or non empty. If the
983         * given parameter represents a file, it is not deleted. See the description
984         * of the return statement.
985         *
986         * @param dirPath
987         *            the file representing the directory to be deleted.
988         * @return true, if the given directory with all its contents have been
989         *         remove; false if deletion of any of files ended with error (all
990         *         other files are possibly also deleted)
991         */
992        public static boolean deleteDirectory(File dirPath) {
993                if (dirPath.exists() && dirPath.isDirectory()) {
994                        boolean result = true;
995                        File[] files = dirPath.listFiles();
996                        for (File file : files) {
997                                if (file.isFile())
998                                        result |= file.delete();
999                                else
1000                                        result |= deleteDirectory(file);
1001                        }
1002                        result |= dirPath.delete();
1003                        return result;
1004                }
1005                return false; // it is not a directory
1006        }
1007
1008        /**
1009         * Returns the accumulated simulation statistics from the last run of the
1010         * simulator
1011         *
1012         * @return the accumulated simulation statistics from the last run of the
1013         *         simulator
1014         */
1015        public static AccumulatedStatistics getAccumulatedStatistics() {
1016                return accumulatedStatistics;
1017        }
1018
1019        protected class WorkloadDirectoryFilter implements java.io.FileFilter {
1020
1021                public boolean accept(File file) {
1022                        if (file.isDirectory() && file.getName().startsWith("workload"))
1023                                return true;
1024                        else
1025                                return false;
1026                }
1027
1028        }
1029
1030        protected class PropertiesFileFilter implements java.io.FileFilter {
1031
1032                public boolean accept(File file) {
1033                        if (file.isFile() && file.getName().endsWith(".properties"))
1034                                return true;
1035                        else
1036                                return false;
1037                }
1038
1039        }
1040
1041        public File prepareDirecotry(ConfigurationOptions options) throws Exception {
1042                // String statsOutputPath = null;
1043                if (options.createScenario) {
1044                        File outputFolderFile = new File(options.outputFolder);
1045                        if (!outputFolderFile.exists()) {
1046                                if (!outputFolderFile.mkdirs())
1047                                        throw new IOException("Cannot create the output path: "
1048                                                        + statsOutputPath + ". Cause: ");
1049                        }
1050
1051                        if (log.isInfoEnabled())
1052                                log.info("CREATING SCENARIO ::");
1053                        statsOutputPath = options.outputFolder
1054                                        + options.statsOutputSubfolderNameCreate;
1055                } else {
1056                        if (log.isInfoEnabled())
1057                                log.info("READING SCENARIO ::");
1058                        String prefix = null;
1059                        if (options.inputFolder != null) {
1060                                prefix = options.inputFolder;
1061                        } else if (options.inputWorkloadFileName != null) {
1062                                prefix = new File(options.inputWorkloadFileName).getParent();
1063                        } else {
1064                                prefix = System.getProperty("user.dir");
1065                        }
1066                        statsOutputPath = prefix + File.separator
1067                                        + options.statsOutputSubfolderNameRerad;
1068                }
1069                statsOutputPath += File.separator;
1070
1071                // create the output folder
1072                File statsOutputPathFile = new File(statsOutputPath);
1073                if (!statsOutputPathFile.exists()) {
1074                        if (!statsOutputPathFile.mkdirs())
1075                                throw new IOException("Cannot create the output (stats) path: "
1076                                                + statsOutputPath + ". Cause: ");
1077                }
1078
1079                File folder = new File(statsOutputPath);
1080                File fileList[] = folder.listFiles();
1081                for (int i = 0; i < fileList.length; i++) {
1082                        File tmpFile = fileList[i];
1083                        String name = tmpFile.getName();
1084                        if (name.length() > 4) {
1085                                String subName = name.substring(0, 5);
1086                                if (subName.compareTo("Chart") == 0
1087                                                || subName.compareTo("Stats") == 0) {
1088                                        tmpFile.delete();
1089                                }
1090                        }
1091                }
1092
1093                return statsOutputPathFile;
1094        }
1095
1096        public void createResultsTar(File outputTar, File[] files, File networkFile)
1097                        throws IOException {
1098
1099                if (!outputTar.exists())
1100                        outputTar.createNewFile();
1101                TarArchiveOutputStream tos = null;
1102                try {
1103                        tos = new TarArchiveOutputStream(new FileOutputStream(outputTar));
1104                        for (File file : files) {
1105                                if (file.exists())
1106                                        addEntryToArchive(tos, file);
1107                                else
1108                                        log.warn("File " + file.getName() + " does not exist");
1109                        }
1110                        if (networkFile != null)
1111                                addEntryWithParentsToArchive(tos, networkFile);
1112                } catch (FileNotFoundException e1) {
1113                        log.error("Archive output file was not found", e1);
1114                } finally {
1115                        if (tos != null)
1116                                try {
1117                                        tos.close();
1118                                } catch (IOException e) {
1119                                        log.error("IOException occured while "
1120                                                        + "closing tar archive", e);
1121                                }
1122                }
1123
1124        }
1125
1126        private void addEntryWithParentsToArchive(TarArchiveOutputStream tos,
1127                        File file) {
1128                File parent = file.getParentFile();
1129                if (parent != null)
1130                        addEntryWithParentsToArchive(tos, parent);
1131                String filePath = file.isDirectory() ? file.getPath() + File.separator
1132                                : file.getPath();
1133                addEntryToArchive(tos, file, filePath);
1134        }
1135
1136        private void addEntryToArchive(TarArchiveOutputStream tos, File file) {
1137                addEntryToArchive(tos, file, file.getName());
1138        }
1139
1140        private void addEntryToArchive(TarArchiveOutputStream tos, File file,
1141                        String name) {
1142                FileInputStream fis = null;
1143                TarArchiveEntry in = new TarArchiveEntry(name);
1144                in.setModTime(file.lastModified());
1145                if (!file.isDirectory())
1146                        in.setSize(file.length());
1147
1148                try {
1149                        tos.putArchiveEntry(in);
1150                        if (!file.isDirectory()) {
1151                                byte[] b = new byte[(int) file.length()];
1152                                fis = new FileInputStream(file);
1153                                while (fis.read(b) > 0) {
1154                                        tos.write(b);
1155                                }
1156                        }
1157                } catch (FileNotFoundException e) {
1158                        log.error("File " + file.getName() + " was not found", e);
1159                } catch (IOException e) {
1160                        log.error("IOException occured while adding file " + file.getName()
1161                                        + " to archive");
1162
1163                } finally {
1164                        try {
1165                                if (fis != null)
1166                                        fis.close();
1167                                tos.closeArchiveEntry();
1168                        } catch (IOException e) {
1169                                log.error("IOException occured while closing "
1170                                                + "archive input stream or entry", e);
1171                        }
1172
1173                }
1174
1175        }
1176
1177        public void copyFile(File inputFile, File outputFile) throws IOException {
1178
1179                FileReader in = new FileReader(inputFile);
1180                FileWriter out = new FileWriter(outputFile);
1181                int c;
1182
1183                while ((c = in.read()) != -1)
1184                        out.write(c);
1185
1186                in.close();
1187                out.close();
1188        }
1189       
1190        public static int getSimulationRunNumber(){
1191                return simulationRunNumber;
1192        }
1193}
Note: See TracBrowser for help on using the repository browser.