Statistics
| Branch: | Revision:

root / include / csimulation.h @ master

History | View | Annotate | Download (20.7 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  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
    bool endSimulation;     // used to signal shutdown from threaded context
129

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
230
    /** @name Accessing modules. */
231
    //@{
232

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
345
    /** @name Setting up and finishing a simulation run. */
346
    //@{
347

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

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

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

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

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

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

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

    
389
    /**
390
     * signal shutdown from thread
391
     */
392
    void signalShutdown()  { endSimulation = true; }
393
    //@}
394

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
620

    
621
};
622

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

    
628

    
629
NAMESPACE_END
630

    
631

    
632
#endif
633