Statistics
| Branch: | Revision:

root / include / csimulation.h @ 2f5cc443

History | View | Annotate | Download (20.4 KB)

1
//==========================================================================
2
//   CSIMULATION.H  -  header for
3
//                     OMNeT++/OMNEST
4
//            Discrete System Simulation in C++
5
//
6
//
7
//  Declaration of the following classes:
8
//    cSimulation  : simulation management class; only one instance
9
//
10
//==========================================================================
11

    
12
/*--------------------------------------------------------------*
13
  Copyright (C) 1992-2008 Andras Varga
14
  Copyright (C) 2006-2008 OpenSim Ltd.
15

16
  This file is distributed WITHOUT ANY WARRANTY. See the file
17
  `license' for details on this and other legal matters.
18
*--------------------------------------------------------------*/
19

    
20
#ifndef __CSIMULATION_H
21
#define __CSIMULATION_H
22

    
23
#include "simkerneldefs.h"
24
#include "simtime_t.h"
25
#include "cmessageheap.h"
26
#include "cexception.h"
27

    
28
#include "clockedmsgheap.h"
29
#include "clock.h"
30
#include "cttaslock.h"
31

    
32
#include "cthreadpool.h"
33
#include "cstopwatch.h"
34
#include "cscheduler.h"
35
#include <list>
36

    
37
NAMESPACE_BEGIN
38

    
39
//=== classes mentioned:
40
class  cMessage;
41
class  cGate;
42
class  cModule;
43
class  cSimpleModule;
44
class  cCompoundModule;
45
class  cSimulation;
46
class  cException;
47
class  cScheduler;
48
class  cParsimPartition;
49
class  cNEDFileLoader;
50
class  cHasher;
51
class  cModuleType;
52
class  cEnvir;
53
class  cDefaultList;
54
class  cThreadPool;
55
class  cAsyncModule;
56
class  cStopWatch;
57

    
58
SIM_API extern cDefaultList defaultList; // also in globals.h
59

    
60
/**
61
 * The active simulation manager instance.
62
 *
63
 * @ingroup SimCore
64
 */
65
#define simulation  (*cSimulation::getActiveSimulation())
66

    
67

    
68
/**
69
 * Simulation manager class.  cSimulation is the central class in \opp.
70
 * It stores the active simulation model, and provides methods for setting up,
71
 * running and finalizing simulations.
72
 *
73
 * Most cSimulation methods are not of interest for simulation model code,
74
 * they are used internally (e.g. by the user interface libraries (Envir,
75
 * Cmdenv, Tkenv) to set up and run simulations).
76
 *
77
 * Some methods which can be of interest when programming simple modules:
78
 * getUniqueNumber(), getModuleByPath(), getModule(), snapshot().
79
 *
80
 * @ingroup SimCore
81
 * @ingroup Internals
82
 */
83
class SIM_API cSimulation : public cNamedObject, noncopyable
84
{
85
    friend class cSimpleModule;
86
    friend class cThreadPool;
87
    friend class cLockedThreadPool;
88
    friend class cSpinningThreadPool;
89

    
90
  private:
91
    // global variables
92
    static cSimulation *simPtr; // the active cSimulation instance
93
    static cEnvir *evPtr;       // the active cEnvir instance
94
    static cEnvir *staticEvPtr; // the environment to activate when simPtr becomes NULL
95

    
96
    // variables of the module vector
97
    int size;                 // size of vector
98
    int delta;                // if needed, grows by delta
99
    cModule **vect;           // vector of modules, vect[0] is not used
100
    int last_id;              // index of last used pos. in vect[]
101

    
102
    // simulation vars
103
    cEnvir *ownEvPtr;         // the environment that belongs to this simulation object
104
    cModule *systemmodp;      // pointer to system (root) module
105
    cSimpleModule *activitymodp; // the module currently executing activity() (NULL if handleMessage() or in main)
106
    //cComponent *contextmodp;  // component in context (or NULL)
107
    int contexttype;          // the innermost context type (one of CTX_BUILD, CTX_EVENT, CTX_INITIALIZE, CTX_FINISH)
108
    cModuleType *networktype; // network type
109
    cScheduler *schedulerp;   // event scheduler
110
    simtime_t warmup_period;  // warm-up period
111

    
112
    int simulationstage;      // simulation stage (one of CTX_NONE, CTX_BUILD, CTX_EVENT, CTX_INITIALIZE, CTX_FINISH or CTX_CLEANUP)
113
    //simtime_t sim_time;       // simulation time (time of current event)
114
    eventnumber_t event_num;  // sequence number of current event
115

    
116
    cMessage *msg_for_activity; // helper variable to pass the received message into activity()
117
    cException *exception;    // helper variable to get exceptions back from activity()
118

    
119
    cHasher *hasherp;         // used for fingerprint calculation
120

    
121
    bool threaded;              // use threads or not
122
    bool isrunning;             // flag indicating whether a simulation run is ongoing
123

    
124
    unsigned int eventsPerSimTimeInstance; // count how many event occur at the same sim time
125

    
126
    cStopWatch sequentialWatch;
127

    
128
  private:
129
    // internal
130
    void checkActive()  {if (getActiveSimulation()!=this) throw cRuntimeError(this, eWRONGSIM);}
131

    
132
  public:
133
    // internal: FES
134
#ifdef UNSAFE_FES
135
    cMessageHeap msgQueue;    // future messages (FES)
136
#else
137
    cLockedMessageHeap<cTTASLock> msgQueue;
138
#endif
139

    
140
    cMessageHeap& getMessageQueue() {return msgQueue;}  // accessor for sim_std.msg
141

    
142
    // Horizon thread pool
143
    cThreadPool* threadPool;
144

    
145
  private:
146
    /**
147
     * checks if the arrival module of this message is still alive. Return NULL
148
     * if not.
149
     */
150
    cSimpleModule* cleanDeadModule(cMessage* msg);
151

    
152
    /**
153
     * read configuration and setup the thread pool accordingly
154
     */
155
    void setupThreadPool();
156

    
157
    /*
158
     * setup the local Random Number Generators for each cAsyncmodule
159
     */
160
    void setupLocalRNGs();
161

    
162
  public:
163
    /** @name Constructor, destructor. */
164
    //@{
165
    /**
166
     * Constructor. The environment object will be associated with this simulation
167
     * object, and gets deleted in the simulation object's destructor.
168
     */
169
    cSimulation(const char *name, cEnvir *env);
170

    
171
    /**
172
     * Destructor.
173
     */
174
    virtual ~cSimulation();
175
    //@}
176

    
177
    /** @name Redefined cObject member functions. */
178
    //@{
179
    /**
180
     * Calls v->visit(this) for each contained object.
181
     * See cObject for more details.
182
     */
183
    virtual void forEachChild(cVisitor *v);
184

    
185
    /**
186
     * Redefined. (Reason: a C++ rule that overloaded virtual methods must be redefined together.)
187
     */
188
    virtual std::string getFullPath() const;
189
    //@}
190

    
191
    /** @name Accessing and switching the active simulation object */
192
    //@{
193
    /**
194
     * Returns the active simulation object. May be NULL.
195
     */
196
    static cSimulation *getActiveSimulation()  {return simPtr;}
197

    
198
    /**
199
     * Returns the environment object for the active simulation. Never returns NULL;
200
     * setActiveSimulation(NULL) will cause a static "do-nothing" instance to step in.
201
     */
202
    static cEnvir *getActiveEnvir()  {return evPtr;}
203

    
204
    /**
205
     * Activate the given simulation object, and its associated environment
206
     * object. NULL is also accepted; it will cause the static environment
207
     * object to step in (see getStaticEnvir()).
208
     */
209
    static void setActiveSimulation(cSimulation *sim);
210

    
211
    /**
212
     * Sets the environment object to use when there is no active simulation object.
213
     * The argument cannot be NULL.
214
     */
215
    static void setStaticEnvir(cEnvir *env);
216

    
217
    /**
218
     * Returns the environment object to use when there is no active simulation object.
219
     */
220
    static cEnvir *getStaticEnvir()  {return staticEvPtr;}
221

    
222
    /**
223
     * Returns the environment object associated with this simulation object.
224
     */
225
    cEnvir *getEnvir() const  {return ownEvPtr;}
226
    //@}
227

    
228
    /** @name Accessing modules. */
229
    //@{
230

    
231
    /**
232
     * Registers the module in cSimulation and assigns a module Id. It is called
233
     * internally during module creation. The Id of a deleted module is not
234
     * issued again to another module, because we want module Ids to be
235
     * unique during the whole simulation.
236
     */
237
    int registerModule(cModule *mod);
238

    
239
    /**
240
     * Deregisters the module from cSimulation. It is called internally from cModule
241
     * destructor.
242
     */
243
    void deregisterModule(cModule *mod);
244

    
245
    /**
246
     * Returns highest used module ID.
247
     */
248
    int getLastModuleId() const    {return last_id;}
249

    
250
    /**
251
     * Finds a module by its path. Inclusion of the name of the toplevel module
252
     * in the path is optional. Returns NULL if not found.
253
     */
254
    cModule *getModuleByPath(const char *modulepath) const;
255

    
256
    /**
257
     * Looks up a module by ID. If the module does not exist, returns NULL.
258
     */
259
    cModule *getModule(int id) const  {return id>=0 && id<size ? vect[id] : NULL;}
260

    
261
    /**
262
     * DEPRECATED because it might return null reference; use getModule(int) instead.
263
     *
264
     * Same as getModule(int), only this returns reference instead of pointer.
265
     */
266
    _OPPDEPRECATED cModule& operator[](int id) const  {return id>=0 && id<size ? *vect[id] : *(cModule *)NULL;}
267

    
268
    /**
269
     * Designates the system module, the top-level module in the model.
270
     */
271
    void setSystemModule(cModule *p);
272

    
273
    /**
274
     * Returns pointer to the system module, the top-level module in the model.
275
     */
276
    cModule *getSystemModule() const  {return systemmodp;}
277
    //@}
278

    
279
    /** @name Loading NED files.
280
     *
281
     * These functions delegate to the netbuilder part of the simulation kernel,
282
     * and they are present so that cEnvir and other libs outside the simkernel
283
     * do not need to directly depend on nedxml or netbuilder classes, and
284
     * conditional compilation (\#ifdef WITH_NETBUILDER) can be limited to the
285
     * simkernel.
286
     */
287
    //@{
288

    
289
    /**
290
     * Load all NED files from a NED source folder. This involves visiting
291
     * each subdirectory, and loading all "*.ned" files from there.
292
     * The given folder is assumed to be the root of the NED package hierarchy.
293
     * Returns the number of files loaded.
294
     *
295
     * Note: doneLoadingNedFiles() must be called after the last
296
     * loadNedSourceFolder()/loadNedFile()/loadNedText() call.
297
     */
298
    static int loadNedSourceFolder(const char *foldername);
299

    
300
    /**
301
     * Load a single NED file. If the expected package is given (non-NULL),
302
     * it should match the package declaration inside the NED file.
303
     *
304
     * Note: doneLoadingNedFiles() must be called after the last
305
     * loadNedSourceFolder()/loadNedFile()/loadNedText() call.
306
     */
307
    static void loadNedFile(const char *nedfname, const char *expectedPackage=NULL, bool isXML=false);
308

    
309
    /**
310
     * Parses and loads the NED source code passed in the nedtext argument.
311
     * The name argument will be used as filename in error messages, and
312
     * and should be unique among the files loaded. If the expected package
313
     * is given (non-NULL), it should match the package declaration inside
314
     * the NED file.
315
     *
316
     * Note: doneLoadingNedFiles() must be called after the last
317
     * loadNedSourceFolder()/loadNedFile()/loadNedText() call.
318
     */
319
    static void loadNedText(const char *name, const char *nedtext, const char *expectedPackage=NULL, bool isXML=false);
320

    
321
    /**
322
     * To be called after all NED folders / files have been loaded
323
     * (see loadNedSourceFolder()/loadNedFile()/loadNedText()).
324
     * Issues errors for components that could not be fully resolved
325
     * because of missing base types or interfaces.
326
     */
327
    static void doneLoadingNedFiles();
328

    
329
    /**
330
     * Returns the NED package that corresponds to the given folder. Returns ""
331
     * for the default package, and "-" if the folder is outside all NED folders.
332
     */
333
    static std::string getNedPackageForFolder(const char *folder);
334

    
335
    /**
336
     * Discards all information loaded from NED files. This method may only be
337
     * called immediately before exiting, because cModuleType/cChannelType
338
     * objects may depend on the corresponding NED declarations being loaded.
339
     */
340
    static void clearLoadedNedFiles();
341
    //@}
342

    
343
    /** @name Setting up and finishing a simulation run. */
344
    //@{
345

    
346
    /**
347
     * Installs a scheduler object. This may only be called when no
348
     * network is set up. The cSimulation object will be responsible
349
     * for deallocating the scheduler object.
350
     */
351
    void setScheduler(cScheduler *scheduler);
352

    
353
    /**
354
     * Returns the scheduler object.
355
     */
356
    cScheduler *getScheduler() const  {return schedulerp;}
357

    
358
    /**
359
     * Builds a new network.
360
     */
361
    void setupNetwork(cModuleType *networkType);
362

    
363
    /**
364
     * Should be called after setupNetwork(), but before the first
365
     * doOneEvent() call. Includes initialization of the modules,
366
     * that is, invokes callInitialize() on the system module.
367
     */
368
    void startRun();
369

    
370
    /**
371
     * Recursively calls finish() on the modules of the network.
372
     * This method simply invokes callfinish() on the system module.
373
     */
374
    void callFinish();
375

    
376
    /**
377
     * Should be called at the end of a simulation run.
378
     */
379
    void endRun();
380

    
381
    /**
382
     * Cleans up the network currently set up. This involves deleting
383
     * all modules and deleting the messages in the scheduled-event list.
384
     */
385
    void deleteNetwork();
386
    //@}
387

    
388
    /** @name Information about the current simulation run. */
389
    //@{
390
    /**
391
     * Returns the current simulation stage: network building (CTX_BUILD),
392
     * network initialization (CTX_INIT), simulation execution (CTX_EVENT),
393
     * simulation finalization (CTX_FINISH), network cleanup (CTX_CLEANUP),
394
     * or other (CTX_NONE).
395
     */
396
    int getSimulationStage() const  {return simulationstage;}
397

    
398
    /**
399
     * Returns the cModuleType object that was instantiated to set up
400
     * the current simulation model.
401
     */
402
    cModuleType *getNetworkType() const  {return networktype;}
403

    
404
    /**
405
     * INTERNAL USE ONLY. This method should NEVER be invoked from
406
     * simulation models, only from scheduler classes subclassed from
407
     * cScheduler.
408
     */
409
    void setSimTime(simtime_t time) {cThreadPool::setSimTime(time);}
410

    
411
    /**
412
     * Returns the current simulation time. (It is also available via the
413
     * global simTime() function.)
414
     */
415
    simtime_t getSimTime() const  {return cThreadPool::getSimTime();}
416

    
417
    /**
418
     * Returns the sequence number of current event.
419
     */
420
    eventnumber_t getEventNumber() const  {return event_num;}
421

    
422
    /**
423
     * Is the simulation currently running.
424
     */
425
    bool isRunning() const {
426
        return isrunning;
427
    }
428

    
429
    /**
430
     * Returns the length of the initial warm-up period from the configuration.
431
     * Modules that compute and record scalar results manually (via recordScalar(),
432
     * recordStatistic(), etc.) should be implemented in a way that they ignore
433
     * observations generated during the warm-up period. cOutVector objects,
434
     * and results recorded via the signals mechanism automatically obey
435
     * the warm-up period and need not be modified. The warm-up period is useful
436
     * for steady-state simulations.
437
     */
438
    simtime_t_cref getWarmupPeriod() const  {return warmup_period;}
439

    
440
    /**
441
     * INTERNAL USE ONLY. Sets the warm-up period.
442
     */
443
    void setWarmupPeriod(simtime_t t)  {warmup_period = t;}
444
    //@}
445

    
446
    /** @name Scheduling and context switching during simulation. */
447
    //@{
448

    
449
    /**
450
     * The scheduler function. Returns the module to which the
451
     * next event (lowest timestamp event in the FES) belongs.
452
     *
453
     * If there is no more event (FES is empty), it throws cTerminationException.
454
     *
455
     * A NULL return value means that there is no error but execution
456
     * was stopped by the user (e.g. with STOP button on the GUI)
457
     * while selectNextModule() --or rather, the installed cScheduler object--
458
     * was waiting for external synchronization.
459
     */
460
    cSimpleModule *selectNextModule();
461

    
462
    /**
463
     * To be called between events from the environment of the simulation
464
     * (e.g. from Tkenv), this function returns a pointer to the event
465
     * at the head of the FES. It is only guaranteed to be the next event
466
     * with sequential simulation; with parallel, distributed or real-time
467
     * simulation there might be another event coming from other processes
468
     * with a yet smaller timestamp.
469
     *
470
     * This method is careful not to change anything. It never throws
471
     * an exception, and especially, it does NOT invoke the scheduler
472
     * (see cScheduler) because e.g. its parallel simulation incarnations
473
     * might do subtle things to keep events synchronized in various
474
     * partitions of the parallel simulation.
475
     */
476
    cMessage *guessNextEvent();
477

    
478
    /**
479
     * To be called between events from the environment of the simulation
480
     * (e.g. from Tkenv), this function returns the module associated
481
     * with the event at the head of the FES. It returns NULL if the
482
     * FES is empty, there is no module associated with the event, or
483
     * the module has already finished.
484
     *
485
     * Based on guessNextEvent(); see further comments there.
486
     */
487
    cSimpleModule *guessNextModule();
488

    
489
    /**
490
     * To be called between events from the environment of the simulation
491
     * (e.g. Tkenv), this function returns the simulation time of the event
492
     * at the head of the FES. In contrast, simTime() returns the time of the
493
     * last executed (or currently executing) event. Returns a negative value
494
     * if the FES is empty.
495
     *
496
     * Based on guessNextEvent(); see further comments there.
497
     */
498
    simtime_t guessNextSimtime();
499

    
500
    /**
501
     * Executes one event. The argument should be the module
502
     * returned by selectNextModule(); that is, the module
503
     * to which the next event (lowest timestamp event in
504
     * the FES) belongs. Also increments the event number
505
     * (returned by getEventNumber()).
506
     */
507
    void doOneEvent(cMessage* msg);
508

    
509
    /**
510
     * Switches to simple module's coroutine. This method is invoked
511
     * from doOneEvent() for activity()-based modules.
512
     */
513
    void transferTo(cSimpleModule *p);
514

    
515
    /**
516
     * Switches to main coroutine.
517
     */
518
    void transferToMain();
519

    
520
    /**
521
     * Inserts the given message into the future events queue while assigning
522
     * the current event to its scheduling event. Used internally by
523
     * cSimpleModule::scheduleAt() and various other cSimpleModule methods.
524
     */
525
    void insertMsg(cMessage *msg);
526

    
527
    /**
528
     * Sets the component (module or channel) in context. Used internally.
529
     */
530
    void setContext(cComponent *p);
531

    
532
    /**
533
     * Sets the context type (see CTX_xxx constants). Used internally.
534
     */
535
    void setContextType(int ctxtype)  {contexttype = ctxtype;}
536

    
537
    /**
538
     * Sets global context. Used internally.
539
     */
540
    void setGlobalContext()  {
541
        cThreadPool::setContext(NULL);
542
        cThreadPool::setDefaultOwner(&defaultList);
543
    }
544
    /**
545
     * Returns the module whose activity() method is currently active.
546
     * Returns NULL if no module is running, or the current module uses
547
     * handleMessage().
548
     */
549
    cSimpleModule *getActivityModule() const {return activitymodp;}
550

    
551
    /**
552
     * Returns the component (module or channel) currently in context.
553
     */
554
    cComponent *getContext() const {return cThreadPool::getContext();}
555

    
556
    /**
557
     * Returns value only valid if getContextModule()!=NULL. Returns one of:
558
     * CTX_BUILD, CTX_INITIALIZE, CTX_EVENT, CTX_FINISH, depending on
559
     * what the module in context is doing. In case of nested contexts
560
     * (e.g. when a module is dynamically created, initialized or manually
561
     * finalized during simulation), the innermost context type is returned.
562
     */
563
    int getContextType() const {return contexttype;}
564

    
565
    /**
566
     * If the current context is a module, returns its pointer,
567
     * otherwise returns NULL.
568
     */
569
    cModule *getContextModule() const;
570

    
571
    /**
572
     * Returns the module currently in context as a simple module.
573
     * If the module in context is not a simple module, returns NULL.
574
     * This is a convenience function which simply calls getContextModule().
575
     */
576
    cSimpleModule *getContextSimpleModule() const;
577
    //@}
578

    
579
    /** @name Miscellaneous. */
580
    //@{
581
    /**
582
     * This function is guaranteed to return a different integer every time
583
     * it is called (usually 0, 1, 2, ...). This method works with parallel
584
     * simulation as well, so it is recommended over incrementing a global
585
     * variable. Useful for generating unique network addresses, etc.
586
     */
587
    unsigned long getUniqueNumber();
588

    
589
    /**
590
     * Writes a snapshot of the given object and its children to the
591
     * textual snapshot file.
592
     * This method is called internally from cSimpleModule's snapshot().
593
     */
594
    bool snapshot(cObject *obj, const char *label);
595

    
596
    /**
597
     * Returns the object used for fingerprint calculation. It returns NULL
598
     * if no fingerprint is being calculated during this simulation run.
599
     */
600
    cHasher *getHasher() {return hasherp;}
601

    
602
    /**
603
     * Installs a new hasher object, used for fingerprint calculation.
604
     */
605
    void setHasher(cHasher *hasher);
606

    
607
    /*
608
     * returns next execution order Id of given msg
609
     */
610
    unsigned int getNextExecutionOrderId(cMessage* msg);
611
    //@}
612

    
613

    
614
};
615

    
616
/**
617
 * Returns the current simulation time.
618
 */
619
inline simtime_t simTime() {return cSimulation::getActiveSimulation()->getSimTime();}
620

    
621

    
622
NAMESPACE_END
623

    
624

    
625
#endif
626