Statistics
| Branch: | Revision:

root / include / csimulation.h @ b781545c

History | View | Annotate | Download (20.6 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 "cttaslock.h"
30
#include "cnolock.h"
31
#include "cpthreadlock.h"
32

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

    
38
NAMESPACE_BEGIN
39

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

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

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

    
68

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

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

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

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

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

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

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

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

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

    
127
    cStopWatch sequentialWatch;
128

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

    
133
  public:
134
    // internal: FES
135
#ifdef UNSAFE_FES
136
    cMessageHeap msgQueue;    // future messages (FES)
137
#else
138
    //
139
    // choose on of the following locks
140
    //
141
    // cLockedMessageHeap<cNoLock> msgQueue;
142
    // cLockedMessageHeap<cPThreadLock> msgQueue;
143
    cLockedMessageHeap<cTTASLock> msgQueue;
144
#endif
145

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

    
148
    // Horizon thread pool
149
    cThreadPool* threadPool;
150

    
151
  private:
152
    /**
153
     * checks if the arrival module of this message is still alive. Return NULL
154
     * if not.
155
     */
156
    cSimpleModule* cleanDeadModule(cMessage* msg);
157

    
158
    /**
159
     * read configuration and setup the thread pool accordingly
160
     */
161
    void setupThreadPool();
162

    
163
    /*
164
     * setup the local Random Number Generators for each cAsyncmodule
165
     */
166
    void setupLocalRNGs();
167

    
168
  public:
169
    /** @name Constructor, destructor. */
170
    //@{
171
    /**
172
     * Constructor. The environment object will be associated with this simulation
173
     * object, and gets deleted in the simulation object's destructor.
174
     */
175
    cSimulation(const char *name, cEnvir *env);
176

    
177
    /**
178
     * Destructor.
179
     */
180
    virtual ~cSimulation();
181
    //@}
182

    
183
    /** @name Redefined cObject member functions. */
184
    //@{
185
    /**
186
     * Calls v->visit(this) for each contained object.
187
     * See cObject for more details.
188
     */
189
    virtual void forEachChild(cVisitor *v);
190

    
191
    /**
192
     * Redefined. (Reason: a C++ rule that overloaded virtual methods must be redefined together.)
193
     */
194
    virtual std::string getFullPath() const;
195
    //@}
196

    
197
    /** @name Accessing and switching the active simulation object */
198
    //@{
199
    /**
200
     * Returns the active simulation object. May be NULL.
201
     */
202
    static cSimulation *getActiveSimulation()  {return simPtr;}
203

    
204
    /**
205
     * Returns the environment object for the active simulation. Never returns NULL;
206
     * setActiveSimulation(NULL) will cause a static "do-nothing" instance to step in.
207
     */
208
    static cEnvir *getActiveEnvir()  {return evPtr;}
209

    
210
    /**
211
     * Activate the given simulation object, and its associated environment
212
     * object. NULL is also accepted; it will cause the static environment
213
     * object to step in (see getStaticEnvir()).
214
     */
215
    static void setActiveSimulation(cSimulation *sim);
216

    
217
    /**
218
     * Sets the environment object to use when there is no active simulation object.
219
     * The argument cannot be NULL.
220
     */
221
    static void setStaticEnvir(cEnvir *env);
222

    
223
    /**
224
     * Returns the environment object to use when there is no active simulation object.
225
     */
226
    static cEnvir *getStaticEnvir()  {return staticEvPtr;}
227

    
228
    /**
229
     * Returns the environment object associated with this simulation object.
230
     */
231
    cEnvir *getEnvir() const  {return ownEvPtr;}
232
    //@}
233

    
234
    /** @name Accessing modules. */
235
    //@{
236

    
237
    /**
238
     * Registers the module in cSimulation and assigns a module Id. It is called
239
     * internally during module creation. The Id of a deleted module is not
240
     * issued again to another module, because we want module Ids to be
241
     * unique during the whole simulation.
242
     */
243
    int registerModule(cModule *mod);
244

    
245
    /**
246
     * Deregisters the module from cSimulation. It is called internally from cModule
247
     * destructor.
248
     */
249
    void deregisterModule(cModule *mod);
250

    
251
    /**
252
     * Returns highest used module ID.
253
     */
254
    int getLastModuleId() const    {return last_id;}
255

    
256
    /**
257
     * Finds a module by its path. Inclusion of the name of the toplevel module
258
     * in the path is optional. Returns NULL if not found.
259
     */
260
    cModule *getModuleByPath(const char *modulepath) const;
261

    
262
    /**
263
     * Looks up a module by ID. If the module does not exist, returns NULL.
264
     */
265
    cModule *getModule(int id) const  {return id>=0 && id<size ? vect[id] : NULL;}
266

    
267
    /**
268
     * DEPRECATED because it might return null reference; use getModule(int) instead.
269
     *
270
     * Same as getModule(int), only this returns reference instead of pointer.
271
     */
272
    _OPPDEPRECATED cModule& operator[](int id) const  {return id>=0 && id<size ? *vect[id] : *(cModule *)NULL;}
273

    
274
    /**
275
     * Designates the system module, the top-level module in the model.
276
     */
277
    void setSystemModule(cModule *p);
278

    
279
    /**
280
     * Returns pointer to the system module, the top-level module in the model.
281
     */
282
    cModule *getSystemModule() const  {return systemmodp;}
283
    //@}
284

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

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

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

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

    
327
    /**
328
     * To be called after all NED folders / files have been loaded
329
     * (see loadNedSourceFolder()/loadNedFile()/loadNedText()).
330
     * Issues errors for components that could not be fully resolved
331
     * because of missing base types or interfaces.
332
     */
333
    static void doneLoadingNedFiles();
334

    
335
    /**
336
     * Returns the NED package that corresponds to the given folder. Returns ""
337
     * for the default package, and "-" if the folder is outside all NED folders.
338
     */
339
    static std::string getNedPackageForFolder(const char *folder);
340

    
341
    /**
342
     * Discards all information loaded from NED files. This method may only be
343
     * called immediately before exiting, because cModuleType/cChannelType
344
     * objects may depend on the corresponding NED declarations being loaded.
345
     */
346
    static void clearLoadedNedFiles();
347
    //@}
348

    
349
    /** @name Setting up and finishing a simulation run. */
350
    //@{
351

    
352
    /**
353
     * Installs a scheduler object. This may only be called when no
354
     * network is set up. The cSimulation object will be responsible
355
     * for deallocating the scheduler object.
356
     */
357
    void setScheduler(cScheduler *scheduler);
358

    
359
    /**
360
     * Returns the scheduler object.
361
     */
362
    cScheduler *getScheduler() const  {return schedulerp;}
363

    
364
    /**
365
     * Builds a new network.
366
     */
367
    void setupNetwork(cModuleType *networkType);
368

    
369
    /**
370
     * Should be called after setupNetwork(), but before the first
371
     * doOneEvent() call. Includes initialization of the modules,
372
     * that is, invokes callInitialize() on the system module.
373
     */
374
    void startRun();
375

    
376
    /**
377
     * Recursively calls finish() on the modules of the network.
378
     * This method simply invokes callfinish() on the system module.
379
     */
380
    void callFinish();
381

    
382
    /**
383
     * Should be called at the end of a simulation run.
384
     */
385
    void endRun();
386

    
387
    /**
388
     * Cleans up the network currently set up. This involves deleting
389
     * all modules and deleting the messages in the scheduled-event list.
390
     */
391
    void deleteNetwork();
392
    //@}
393

    
394
    /** @name Information about the current simulation run. */
395
    //@{
396
    /**
397
     * Returns the current simulation stage: network building (CTX_BUILD),
398
     * network initialization (CTX_INIT), simulation execution (CTX_EVENT),
399
     * simulation finalization (CTX_FINISH), network cleanup (CTX_CLEANUP),
400
     * or other (CTX_NONE).
401
     */
402
    int getSimulationStage() const  {return simulationstage;}
403

    
404
    /**
405
     * Returns the cModuleType object that was instantiated to set up
406
     * the current simulation model.
407
     */
408
    cModuleType *getNetworkType() const  {return networktype;}
409

    
410
    /**
411
     * INTERNAL USE ONLY. This method should NEVER be invoked from
412
     * simulation models, only from scheduler classes subclassed from
413
     * cScheduler.
414
     */
415
    void setSimTime(simtime_t time) {cThreadPool::setSimTime(time);}
416

    
417
    /**
418
     * Returns the current simulation time. (It is also available via the
419
     * global simTime() function.)
420
     */
421
    simtime_t getSimTime() const  {return cThreadPool::getSimTime();}
422

    
423
    /**
424
     * Returns the sequence number of current event.
425
     */
426
    eventnumber_t getEventNumber() const  {return event_num;}
427

    
428
    /**
429
     * Is the simulation currently running.
430
     */
431
    bool isRunning() const {
432
        return isrunning;
433
    }
434

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

    
446
    /**
447
     * INTERNAL USE ONLY. Sets the warm-up period.
448
     */
449
    void setWarmupPeriod(simtime_t t)  {warmup_period = t;}
450
    //@}
451

    
452
    /** @name Scheduling and context switching during simulation. */
453
    //@{
454

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

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

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

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

    
506
    /**
507
     * Executes one event. The argument should be the module
508
     * returned by selectNextModule(); that is, the module
509
     * to which the next event (lowest timestamp event in
510
     * the FES) belongs. Also increments the event number
511
     * (returned by getEventNumber()).
512
     */
513
    void doOneEvent(cMessage* msg);
514

    
515
    /**
516
     * Switches to simple module's coroutine. This method is invoked
517
     * from doOneEvent() for activity()-based modules.
518
     */
519
    void transferTo(cSimpleModule *p);
520

    
521
    /**
522
     * Switches to main coroutine.
523
     */
524
    void transferToMain();
525

    
526
    /**
527
     * Inserts the given message into the future events queue while assigning
528
     * the current event to its scheduling event. Used internally by
529
     * cSimpleModule::scheduleAt() and various other cSimpleModule methods.
530
     */
531
    void insertMsg(cMessage *msg);
532

    
533
    /**
534
     * Sets the component (module or channel) in context. Used internally.
535
     */
536
    void setContext(cComponent *p);
537

    
538
    /**
539
     * Sets the context type (see CTX_xxx constants). Used internally.
540
     */
541
    void setContextType(int ctxtype)  {contexttype = ctxtype;}
542

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

    
557
    /**
558
     * Returns the component (module or channel) currently in context.
559
     */
560
    cComponent *getContext() const {return cThreadPool::getContext();}
561

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

    
571
    /**
572
     * If the current context is a module, returns its pointer,
573
     * otherwise returns NULL.
574
     */
575
    cModule *getContextModule() const;
576

    
577
    /**
578
     * Returns the module currently in context as a simple module.
579
     * If the module in context is not a simple module, returns NULL.
580
     * This is a convenience function which simply calls getContextModule().
581
     */
582
    cSimpleModule *getContextSimpleModule() const;
583
    //@}
584

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

    
595
    /**
596
     * Writes a snapshot of the given object and its children to the
597
     * textual snapshot file.
598
     * This method is called internally from cSimpleModule's snapshot().
599
     */
600
    bool snapshot(cObject *obj, const char *label);
601

    
602
    /**
603
     * Returns the object used for fingerprint calculation. It returns NULL
604
     * if no fingerprint is being calculated during this simulation run.
605
     */
606
    cHasher *getHasher() {return hasherp;}
607

    
608
    /**
609
     * Installs a new hasher object, used for fingerprint calculation.
610
     */
611
    void setHasher(cHasher *hasher);
612

    
613
    /*
614
     * returns next execution order Id of given msg
615
     */
616
    unsigned int getNextExecutionOrderId(cMessage* msg);
617
    //@}
618

    
619

    
620
};
621

    
622
/**
623
 * Returns the current simulation time.
624
 */
625
inline simtime_t simTime() {return cSimulation::getActiveSimulation()->getSimTime();}
626

    
627

    
628
NAMESPACE_END
629

    
630

    
631
#endif
632