Statistics
| Branch: | Revision:

root / src / sim / csimulation.cc @ fbe00e73

History | View | Annotate | Download (29.8 KB)

1
//=========================================================================
2
//  CSIMULATION.CC - part of
3
//
4
//                  OMNeT++/OMNEST
5
//           Discrete System Simulation in C++
6
//
7
//   Definition of global object:
8
//    simulation
9
//
10
//   Member functions of
11
//    cSimulation  : holds modules and manages the simulation
12
//
13
//  Author: Andras Varga
14
//
15
//=========================================================================
16

    
17
/*--------------------------------------------------------------*
18
  Copyright (C) 1992-2008 Andras Varga
19
  Copyright (C) 2006-2008 OpenSim Ltd.
20

21
  This file is distributed WITHOUT ANY WARRANTY. See the file
22
  `license' for details on this and other legal matters.
23
*--------------------------------------------------------------*/
24

    
25
#include <string.h>
26
#include <stdio.h>
27
#include <algorithm>
28
#include "stringutil.h"
29
#include "cmodule.h"
30
#include "csimplemodule.h"
31
#include "cmessage.h"
32
#include "csimulation.h"
33
#include "cscheduler.h"
34
#include "cenvir.h"
35
#include "ccomponenttype.h"
36
#include "cstatistic.h"
37
#include "cexception.h"
38
#include "cparimpl.h"
39
#include "chasher.h"
40
#include "cconfiguration.h"
41
#include "ccoroutine.h"
42
#include "cthreadpool.h"
43
#include "cbarriermessage.h"
44
#include "cconfiguration.h"
45
#include "cconfigoption.h"
46
#include "clockedthreadpool.h"
47
#include "cspinningthreadpool.h"
48
#include "sysdep.h"
49

    
50

    
51

    
52
#ifdef WITH_PARSIM
53
#include "ccommbuffer.h"
54
#endif
55

    
56
#ifdef WITH_NETBUILDER
57
#include "netbuilder/cnedloader.h"
58
#endif
59

    
60
NAMESPACE_BEGIN
61

    
62
using std::ostream;
63

    
64
#ifdef DEVELOPER_DEBUG
65
#include <set>
66
extern std::set<cOwnedObject*> objectlist;
67
void printAllObjects();
68
#endif
69

    
70
Register_PerRunConfigOption(CFGID_USE_THREADPOOL, "use-thread-pool", CFG_BOOL, "false", "Use the threadpool");
71
Register_PerRunConfigOption(CFGID_THREADPOOL_CLASS, "thread-pool-class", CFG_STRING, "cSpinningThreadPool", "What class of threadpool to use");
72
Register_GlobalConfigOption(CFGID_THREADPOOL_CPU_ID_OFFSET, "cpu-id-offset", CFG_INT, "0", "Offset for Thread Affinity. (When running multiple instances of Horizon at once)");
73
Register_PerRunConfigOption(CFGID_SIMUL_THREADPOOL_SIZE, "thread-pool-size", CFG_STRING, "5", "Number of Threads in Threadpool");
74

    
75

    
76
cSimulation::cSimulation(const char *name, cEnvir *env) :
77
                cNamedObject(name, false), isrunning(false),
78
                endSimulation(false)
79
{
80
    ASSERT(cStaticFlag::isSet()); // cannot be instantiated as global variable
81

    
82
    ownEvPtr = env;
83

    
84
    activitymodp = NULL;
85
    cThreadPool::setContext(NULL);
86

    
87
    simulationstage = CTX_NONE;
88
    contexttype = CTX_NONE;
89

    
90
    systemmodp = NULL;
91
    schedulerp = NULL;
92
    threadPool = NULL;
93

    
94
    delta = 32;
95
    size = 0;
96
    last_id = 0; // vect[0] is not used for historical reasons
97
    vect = NULL;
98

    
99
    networktype = NULL;
100
    hasherp = NULL;
101

    
102
    //sim_time = SIMTIME_ZERO;
103
    cThreadPool::setSimTime(SIMTIME_ZERO);
104
    event_num = 0;
105

    
106
    msgQueue.setName("scheduled-events");
107
    take(&msgQueue);
108

    
109
    // install a default scheduler
110
    setScheduler(new cSequentialScheduler());
111

    
112
    eventsPerSimTimeInstance = 0;
113

    
114
    //calibrate stopwatch
115
    sequentialWatch.calibrateTSC();
116
}
117

    
118
cSimulation::~cSimulation()
119
{
120
    if (this==simPtr)
121
        throw cRuntimeError(this, "cannot delete the active simulation manager object");
122

    
123
    deleteNetwork();
124

    
125
    delete hasherp;
126
    delete schedulerp;
127
    delete ownEvPtr;
128
    drop(&msgQueue);
129
}
130

    
131
void cSimulation::setActiveSimulation(cSimulation *sim)
132
{
133
    simPtr = sim;
134
    evPtr = sim==NULL ? staticEvPtr : sim->ownEvPtr;
135
}
136

    
137
void cSimulation::setStaticEnvir(cEnvir *env)
138
{
139
    if (!env)
140
         throw cRuntimeError("cSimulation::setStaticEnvir(): argument cannot be NULL");
141
    staticEvPtr = env;
142
}
143

    
144
void cSimulation::forEachChild(cVisitor *v)
145
{
146
    if (systemmodp!=NULL)
147
        v->visit(systemmodp);
148
    v->visit(&msgQueue);
149
}
150

    
151
std::string cSimulation::getFullPath() const
152
{
153
    return getFullName();
154
}
155

    
156
static std::string xmlquote(const std::string& str)
157
{
158
    if (!strchr(str.c_str(), '<') && !strchr(str.c_str(), '>'))
159
        return str;
160

    
161
    std::stringstream out;
162
    for (const char *s=str.c_str(); *s; s++)
163
    {
164
        char c = *s;
165
        if (c=='<')
166
           out << "&lt;";
167
        else if (c=='>')
168
           out << "&gt;";
169
        else
170
           out << c;
171
    }
172
    return out.str();
173
}
174

    
175
class cSnapshotWriterVisitor : public cVisitor
176
{
177
  protected:
178
    ostream& os;
179
    int indentlevel;
180
  public:
181
    cSnapshotWriterVisitor(ostream& ostr) : os(ostr) {
182
        indentlevel = 0;
183
    }
184
    virtual void visit(cObject *obj) {
185
        std::string indent(2*indentlevel, ' ');
186
        os << indent << "<object class=\"" << obj->getClassName() << "\" fullpath=\"" << xmlquote(obj->getFullPath()) << "\">\n";
187
        os << indent << "  <info>" << xmlquote(obj->info()) << "</info>\n";
188
        std::string details = obj->detailedInfo();
189
        if (!details.empty())
190
            os << indent << "  <detailedinfo>" << xmlquote(details) << "</detailedinfo>\n";
191
        indentlevel++;
192
        obj->forEachChild(this);
193
        indentlevel--;
194
        os << indent << "</object>\n\n";
195

    
196
        if (os.fail()) throw EndTraversalException();
197
    }
198
};
199

    
200
bool cSimulation::snapshot(cObject *object, const char *label)
201
{
202
    if (!object)
203
        throw cRuntimeError("snapshot(): object pointer is NULL");
204

    
205
    ostream *osptr = ev.getStreamForSnapshot();
206
    if (!osptr)
207
        throw cRuntimeError("Could not create stream for snapshot");
208

    
209
    ostream& os = *osptr;
210

    
211
    os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
212
    os << "<snapshot\n";
213
    os << "    object=\"" << xmlquote(object->getFullPath()) << "\"\n";
214
    os << "    label=\"" << xmlquote(label?label:"") << "\"\n";
215
    os << "    simtime=\"" << xmlquote(SIMTIME_STR(simTime())) << "\"\n";
216
    os << "    network=\"" << xmlquote(networktype?networktype->getName():"") << "\"\n";
217
    os << "    >\n";
218

    
219
    cSnapshotWriterVisitor v(os);
220
    v.process(object);
221

    
222
    os << "</snapshot>\n";
223

    
224
    bool success = !os.fail();
225
    ev.releaseStreamForSnapshot(&os);
226

    
227
    if (!success)
228
        throw cRuntimeError("Could not write snapshot");
229
    return success;
230
}
231

    
232
void cSimulation::setScheduler(cScheduler *sch)
233
{
234
    if (systemmodp)
235
        throw cRuntimeError(this, "setScheduler(): cannot switch schedulers when a network is already set up");
236
    if (!sch)
237
        throw cRuntimeError(this, "setScheduler(): scheduler pointer is NULL");
238
    delete schedulerp;
239
    schedulerp = sch;
240
    schedulerp->setSimulation(this);
241
}
242

    
243
int cSimulation::loadNedSourceFolder(const char *folder)
244
{
245
#ifdef WITH_NETBUILDER
246
    return cNEDLoader::getInstance()->loadNedSourceFolder(folder);
247
#else
248
    throw cRuntimeError("cannot load NED files from `%s': simulation kernel was compiled without "
249
                        "support for dynamic loading of NED files (WITH_NETBUILDER=no)", folder);
250
#endif
251
}
252

    
253
void cSimulation::loadNedFile(const char *nedfile, const char *expectedPackage, bool isXML)
254
{
255
#ifdef WITH_NETBUILDER
256
    cNEDLoader::getInstance()->loadNedFile(nedfile, expectedPackage, isXML);
257
#else
258
    throw cRuntimeError("cannot load `%s': simulation kernel was compiled without "
259
                        "support for dynamic loading of NED files (WITH_NETBUILDER=no)", nedfile);
260
#endif
261
}
262

    
263
void cSimulation::loadNedText(const char *name, const char *nedtext, const char *expectedPackage, bool isXML)
264
{
265
#ifdef WITH_NETBUILDER
266
    cNEDLoader::getInstance()->loadNedText(name, nedtext, expectedPackage, isXML);
267
#else
268
    throw cRuntimeError("cannot source NED text: simulation kernel was compiled without "
269
                        "support for dynamic loading of NED files (WITH_NETBUILDER=no)");
270
#endif
271
}
272

    
273
void cSimulation::doneLoadingNedFiles()
274
{
275
#ifdef WITH_NETBUILDER
276
    cNEDLoader::getInstance()->doneLoadingNedFiles();
277
#endif
278
}
279

    
280
std::string cSimulation::getNedPackageForFolder(const char *folder)
281
{
282
#ifdef WITH_NETBUILDER
283
    return cNEDLoader::getInstance()->getNedPackageForFolder(folder);
284
#else
285
    return "-";
286
#endif
287
}
288

    
289
void cSimulation::clearLoadedNedFiles()
290
{
291
#ifdef WITH_NETBUILDER
292
    cNEDLoader::clear();
293
#endif
294
}
295

    
296
int cSimulation::registerModule(cModule *mod)
297
{
298
    // Insert module into the vector.
299
    // The module will get (last_id+1) as ID. We do not reuse "holes"
300
    // (empty slots) in the vector because we want the module ids to be
301
    // unique during the whole simulation.
302

    
303
    last_id++;
304

    
305
    if (last_id>=size)
306
    {
307
        // vector full, grow by delta
308
        cModule **v = new cModule *[size+delta];
309
        memcpy(v, vect, sizeof(cModule*)*size );
310
        for (int i=size; i<size+delta; i++) v[i]=NULL;
311
        delete [] vect;
312
        vect = v;
313
        size += delta;
314
    }
315
    vect[last_id] = mod;
316
    return last_id;
317
}
318

    
319
void cSimulation::deregisterModule(cModule *mod)
320
{
321
    int id = mod->getId();
322
    vect[id] = NULL;
323

    
324
    if (mod==systemmodp)
325
    {
326
        drop(systemmodp);
327
        systemmodp = NULL;
328
    }
329
}
330

    
331
void cSimulation::setSystemModule(cModule *p)
332
{
333
    systemmodp = p;
334
    take(p);
335
}
336

    
337
cModule *cSimulation::getModuleByPath(const char *path) const
338
{
339
    if (opp_isempty(path))
340
        return NULL;
341

    
342
    // start tokenizing the path
343
    opp_string pathbuf(path);
344
    char *s = strtok(pathbuf.buffer(),".");
345

    
346
    // search starts from system module
347
    cModule *modp = getSystemModule();
348
    if (!modp)
349
        return NULL;
350

    
351
    // 1st component in the path may be the system module, skip it then
352
    if (modp->isName(s))
353
        s = strtok(NULL,".");
354

    
355
    // match components of the path
356
    while (s && modp)
357
    {
358
        char *b;
359
        if ((b=strchr(s,'['))==NULL)
360
        {
361
            modp = modp->getSubmodule(s);  // no index given
362
        }
363
        else
364
        {
365
            if (s[strlen(s)-1]!=']')
366
                throw cRuntimeError("getModuleByPath(): syntax error in path `%s'", path);
367
            *b='\0';
368
            modp = modp->getSubmodule(s,atoi(b+1));
369
        }
370
        s = strtok(NULL,".");
371
    }
372

    
373
    return modp;  // NULL if not found
374
}
375

    
376
void cSimulation::setupNetwork(cModuleType *network)
377
{
378
#ifdef DEVELOPER_DEBUG
379
    printf("DEBUG: before setupNetwork: %d objects\n", cOwnedObject::getLiveObjectCount());
380
    objectlist.clear();
381
#endif
382

    
383
    checkActive();
384
    if (!network)
385
        throw cRuntimeError(eNONET);
386
    if (!network->isNetwork())
387
        throw cRuntimeError("setupNetwork: `%s' is not a network", network->getFullName());
388

    
389
    // set cNetworkType pointer
390
    networktype = network;
391

    
392
    // just to be sure
393
    msgQueue.clear();
394
    cComponent::clearSignalState();
395

    
396
    simulationstage = CTX_BUILD;
397

    
398
    try
399
    {
400
        // set up the network by instantiating the toplevel module
401
        cContextTypeSwitcher tmp(CTX_BUILD);
402
        cModule *mod = networktype->create(networktype->getName(), NULL);
403
        mod->finalizeParameters();
404
        mod->buildInside();
405
    }
406
    catch (std::exception& e)
407
    {
408
        // Note: no deleteNetwork() call here. We could call it here, but it's
409
        // dangerous: module destructors may try to delete uninitialized pointers
410
        // and crash. (Often pointers incorrectly get initialized in initialize()
411
        // and not in the constructor.)
412
        throw;
413
    }
414
    //catch (...) -- this is not a good idea because it would make debugging more difficult
415
    //{
416
    //    deleteNetwork();
417
    //    throw cRuntimeError("unknown exception occurred");
418
    //}
419

    
420
    //printf("setupNetwork finished, cParImpl objects in use: %ld\n", cParImpl::getLiveParImplObjectCount());
421
}
422

    
423
void cSimulation::startRun()
424
{
425
    checkActive();
426
    // read config and setup thread pool
427
    setupThreadPool();
428

    
429
    // setup local RNGs for each module according to config
430
    setupLocalRNGs();
431

    
432
    // reset counters. Note msgQueue.clear() was already called from setupNetwork()
433
    cThreadPool::setSimTime(0.0);
434
    //sim_time = 0;
435
    event_num = 0; // initialize() has event number 0
436
    cMessage::resetMessageCounters();
437

    
438
    simulationstage = CTX_INITIALIZE;
439

    
440
    // init the scheduler. Note this may insert events into the FES (see e.g. cNullMessageProtocol)
441
    getScheduler()->startRun();
442

    
443
    // prepare simple modules for simulation run:
444
    //    1. create starter message for all modules,
445
    //    2. then call initialize() for them (recursively)
446
    //  This order is important because initialize() functions might contain
447
    //  send() calls which could otherwise insert msgs BEFORE starter messages
448
    //  for the destination module and cause trouble in cSimpleMod's activate().
449
    if (systemmodp)
450
    {
451
        cContextSwitcher tmp(systemmodp);
452
        systemmodp->scheduleStart(0);
453
        systemmodp->callInitialize();
454
    }
455

    
456
    event_num = 1; // events are numbered from 1
457

    
458
    simulationstage = CTX_EVENT;
459
    isrunning = true;
460
}
461

    
462
void cSimulation::callFinish()
463
{
464
    checkActive();
465

    
466
    simulationstage = CTX_FINISH;
467

    
468
    if (threaded)
469
        threadPool->shutdown();
470

    
471
    // call user-defined finish() functions for all modules recursively
472
    if (systemmodp)
473
    {
474
        systemmodp->callFinish();
475
    }
476
    isrunning = false;
477
}
478

    
479
void cSimulation::endRun()
480
{
481
    checkActive();
482
    getScheduler()->endRun();
483

    
484
    // move to deleteNetwork later?
485
    if (threaded) {
486
        threadPool->shutdown();
487
        delete threadPool;
488
    }
489
}
490

    
491
void cSimulation::deleteNetwork()
492
{
493
    if (!systemmodp)
494
        return;  // network already deleted
495

    
496
    if (getContextModule()!=NULL)
497
        throw cRuntimeError("Attempt to delete network during simulation");
498

    
499
    simulationstage = CTX_CLEANUP;
500

    
501
    // delete all modules recursively
502
    systemmodp->deleteModule();
503

    
504
    // make sure it was successful
505
    for (int i=1; i<size; i++)
506
        ASSERT(vect[i]==NULL);
507

    
508
    // and clean up
509
    delete [] vect;
510
    vect = NULL;
511
    size = 0;
512
    last_id = 0;
513

    
514
    networktype = NULL;
515

    
516
    //FIXME todo delete cParImpl caches too (cParImplCache, cParImplCache2)
517
    cModule::clearNamePools();
518

    
519
    // clear remaining messages (module dtors may have cancelled & deleted some of them)
520
    msgQueue.clear();
521

    
522
    simulationstage = CTX_NONE;
523

    
524
#ifdef DEVELOPER_DEBUG
525
    printf("DEBUG: after deleteNetwork: %d objects\n", cOwnedObject::getLiveObjectCount());
526
    printAllObjects();
527
#endif
528

    
529
}
530

    
531
cSimpleModule *cSimulation::selectNextModule()
532
{
533
    assert(false); //Do not call the scheduler from here.
534
    // determine next event. Normally (with sequential simulation),
535
    // the scheduler just returns msgQueue->peekFirst().
536
    cMessage *msg = schedulerp->getNextEvent();
537
    if (!msg)
538
        return NULL; // scheduler got interrupted while waiting
539

    
540
    // check if destination module exists and is still running
541
    cSimpleModule *modp = (cSimpleModule *)vect[msg->getArrivalModuleId()];
542
    if (!modp || modp->isTerminated())
543
    {
544
        // Deleted/ended modules may have self-messages and sent messages
545
        // pending for them. Here we choose just to ignore them (delete them without
546
        // any error or warning). Rationale: if we thew an error here, it would
547
        // be very difficult to delete compound modules in which simple modules
548
        // send messages to one another -- each and every simple module
549
        // would have to be notified in advance that they're "shutting down",
550
        // and even then, deletion could progress only after waiting the maximum
551
        // propagation delay to elapse.
552
        delete msgQueue.removeFirst();
553
        return selectNextModule();
554
    }
555

    
556
    // advance simulation time
557
    //sim_time = msg->getArrivalTime();
558
    cThreadPool::setSimTime(msg->getArrivalTime());
559
    return modp;
560
}
561

    
562
cMessage *cSimulation::guessNextEvent()
563
{
564
    // determine the probable next event. No call to cSheduler!
565
    // TBD if this event is "not good" (no module or module ended),
566
    // we might look for another event, but this is not done right now.
567
    return msgQueue.peekFirst();
568
}
569

    
570
simtime_t cSimulation::guessNextSimtime()
571
{
572
    cMessage *msg = guessNextEvent();
573
    return msg==NULL ? -1 : msg->getArrivalTime();
574
}
575

    
576
cSimpleModule *cSimulation::guessNextModule()
577
{
578
    cMessage *msg = guessNextEvent();
579
    if (!msg)
580
        return NULL;
581

    
582
    // check if dest module exists and still running
583
    if (msg->getArrivalModuleId()==-1)
584
        return NULL;
585
    cSimpleModule *modp = (cSimpleModule *)vect[msg->getArrivalModuleId()];
586
    if (!modp || modp->isTerminated())
587
        return NULL;
588
    return modp;
589
}
590

    
591
void cSimulation::transferTo(cSimpleModule *modp)
592
{
593
    if (modp==NULL)
594
        throw cRuntimeError("transferTo(): attempt to transfer to NULL");
595

    
596
    // switch to activity() of the simple module
597
    exception = NULL;
598
    activitymodp = modp;
599
    cCoroutine::switchTo(modp->coroutine);
600

    
601
    if (modp->hasStackOverflow())
602
        throw cRuntimeError("Stack violation in module (%s)%s: module stack too small? "
603
                            "Try increasing it in the class' Module_Class_Members() or constructor",
604
                            modp->getClassName(), modp->getFullPath().c_str());
605

    
606
    // if exception occurred in activity(), re-throw it. This allows us to handle
607
    // handleMessage() and activity() in an uniform way in the upper layer.
608
    if (exception)
609
    {
610
        cException *e = exception;
611
        exception = NULL;
612

    
613
        // ok, so we have an exception *pointer*, but we have to throw further
614
        // by *value*, and possibly without leaking it. Hence the following magic...
615
        if (dynamic_cast<cDeleteModuleException *>(e))
616
        {
617
            cDeleteModuleException e2(*(cDeleteModuleException *)e);
618
            delete e;
619
            throw e2;
620
        }
621
        else if (dynamic_cast<cTerminationException *>(e))
622
        {
623
            cTerminationException e2(*(cTerminationException *)e);
624
            delete e;
625
            throw e2;
626
        }
627
        else if (dynamic_cast<cRuntimeError *>(e))
628
        {
629
            cRuntimeError e2(*(cRuntimeError *)e);
630
            delete e;
631
            throw e2;
632
        }
633
        else
634
        {
635
            cException e2(*(cException *)e);
636
            delete e;
637
            throw e2;
638
        }
639
    }
640
}
641

    
642
void cSimulation::doOneEvent(cMessage* msg)
643
{
644
    cSimpleModule* mod = NULL;
645

    
646
#ifndef NDEBUG
647
    checkActive();
648
#endif
649

    
650
    try
651
    {
652
        // a worker signaled to shutdown the simulation
653
        if(endSimulation)
654
            throw cTerminationException(eENDSIM);
655

    
656
        // update the number of events that occur at the same simtime
657
        simtime_t currentTime = cThreadPool::getSimTime();
658
        if (currentTime < msg->getArrivalTime())
659
            eventsPerSimTimeInstance = 0;
660
        else
661
            eventsPerSimTimeInstance++;
662

    
663
        // remember how many events at this simtime instance have already been executed
664
        msg->setExecutionOrderId(eventsPerSimTimeInstance);
665

    
666
        // finally, advance Simulation Time
667
        cThreadPool::setSimTime(msg->getArrivalTime());
668

    
669
        // Update mod pointer:
670
        mod = (cSimpleModule*) simulation.vect[msg->getArrivalModuleId()];
671
        // notify the environment about the event (writes eventlog, etc.)
672
        if (!mod) {
673
            throw cRuntimeError("Module was deleted during Simulation. This is not supported by Horizon.");
674
        }
675
        if (mod->usesActivity()) {
676
            throw cRuntimeError("Activity-Model not supported with Horizon.");
677
        }
678

    
679
                simtime_t duration = msg->getEventDuration();
680
                bool sequentialExecution = (duration == SimTime::simTimeSequentialExecution);
681

    
682
                if (sequentialExecution)
683
                        duration = SimTime::simTimeZero;
684

    
685
                if (duration < SimTime::simTimeZero)
686
                {
687
                        throw cRuntimeError("negative event duration not allowed.");
688
                }
689

    
690
                bool mayPar = mod->mayParallelize(msg, duration);
691
                // execute this event in parallel
692
                if (mayPar && threaded && !sequentialExecution)
693
                {
694
                        //printf("Offloading: %s\n",mod->getName());
695
                        threadPool->insertTask(msg, duration);
696
                        // the threadpool unsets the module busy after it finishes the event
697
                }
698
                else
699
                {
700
                        // set the context for sequential execution
701
                        setContext(mod);
702
                        setContextType(CTX_EVENT);
703

    
704
                        EVCB.simulationEvent(msg);
705

    
706
                        msg->setPreviousEventNumber(event_num);
707

    
708
                        sequentialWatch.reset();
709
                        sequentialWatch.startTicking();
710
                        // take ownership in callHandleMessage after concurrency check
711
                        mod->callHandleMessage(msg);
712
                        sequentialWatch.stopTicking();
713

    
714
                        //Store measured complexity and write to file
715
                        EVCB.simulationEventEnd(sequentialWatch.getTicksTime());
716

    
717
                        // take ownership in callHandleMessage after concurrency check
718
                        // unset busy to release module for further events
719
                        mod->unsetBusy();
720
                }
721

    
722
        //We have handled the Message, return
723
        setGlobalContext();
724
        event_num++;
725
        return;
726
    }
727
    catch (cDeleteModuleException& e)
728
    {
729
        assert(false); //not implemented
730
        setGlobalContext();
731
        mod->deleteModule();
732
    }
733
    catch (cException&)
734
    {
735
        // restore global context before throwing the exception further
736
        setGlobalContext();
737
        throw;
738
    }
739
    catch (std::exception& e)
740
    {
741
        // restore global context before throwing the exception further
742
        // but wrap into a cRuntimeError which captures the module before that
743
        cRuntimeError e2("%s: %s", opp_typename(typeid(e)), e.what());
744
        setGlobalContext();
745
        throw e2;
746
    }
747
}
748

    
749
void cSimulation::transferToMain()
750
{
751
    if (activitymodp!=NULL)
752
    {
753
        activitymodp = NULL;
754
        cCoroutine::switchToMain();     // stack switch
755
    }
756
}
757

    
758
void cSimulation::setContext(cComponent *p)
759
{
760
    cThreadPool::setContext(p);
761
    cThreadPool::setDefaultOwner(p);
762
}
763

    
764
cModule *cSimulation::getContextModule() const
765
{
766
    cComponent* ctxMod = cThreadPool::getContext();
767
    // cannot go inline (upward cast would require including cmodule.h in csimulation.h)
768
    if (!ctxMod || !ctxMod->isModule())
769
        return NULL;
770
    return (cModule *) ctxMod;
771
}
772

    
773
cSimpleModule *cSimulation::getContextSimpleModule() const
774
{
775
    cComponent* ctxMod = cThreadPool::getContext();
776
    // cannot go inline (upward cast would require including cmodule.h in csimulation.h)
777
    if (!ctxMod || !ctxMod->isModule() || !((cModule *) ctxMod)->isSimple())
778
        return NULL;
779
    return (cSimpleModule *) ctxMod;
780
}
781

    
782
unsigned long cSimulation::getUniqueNumber()
783
{
784
    return ev.getUniqueNumber();
785
}
786

    
787
void cSimulation::setHasher(cHasher *hasher)
788
{
789
    if (hasherp)
790
        delete hasherp;
791
    hasherp = hasher;
792
}
793

    
794
void cSimulation::insertMsg(cMessage *msg)
795
{
796
    msg->setPreviousEventNumber(event_num);
797
    simulation.msgQueue.insert(msg);
798
}
799

    
800
void cSimulation::setupThreadPool() {
801
    threaded = ev.getConfig()->getAsBool(CFGID_USE_THREADPOOL);
802

    
803
#ifdef ENABLE_OWNERSHIP
804
    if (threaded) {
805
        throw cRuntimeError(this, "Ownership Model is incompatible with threaded "
806
                "architecture of Horizon. Please disable threading or ownership");
807
    }
808
#endif
809

    
810
    if (threaded) {
811
        std::string threadPoolClass = ev.getConfig()->getAsString(
812
                CFGID_THREADPOOL_CLASS);
813
        if (threadPoolClass.compare("cLockedThreadPool") == 0) {
814
            threadPool = new cLockedThreadPool();
815
        } else if (threadPoolClass.compare("cSpinningThreadPool") == 0) {
816
            threadPool = new cSpinningThreadPool();
817
        } else {
818
            printf("WARNING: Threadpool class selected does not exist!\n");
819
            printf("Falling back to default (cSpinningThreadPool)\n");
820
            sleep(3);
821
            threadPool = new cSpinningThreadPool();
822
        }
823
        threadPool->activate();
824
    } else {
825
        //
826
        // set the cpu-id offset (used for demo reasons only)
827
        //
828
        unsigned cpuIdOffset = ev.getConfig()->getAsInt(
829
                CFGID_THREADPOOL_CPU_ID_OFFSET);
830
        unsigned cpuCount = (unsigned) sysconf(_SC_NPROCESSORS_ONLN);
831
        if (cpuIdOffset >= cpuCount) {
832
            throw cRuntimeError("Mis-configured CPU-id offset: exceeding number of"
833
                                " physical CPUs");
834
        }
835
        thread_set_affinity(pthread_self(), 0 + cpuIdOffset);
836
    }
837
}
838

    
839
unsigned int cSimulation::getNextExecutionOrderId(cMessage* msg) {
840
    simtime_t currentTime = cThreadPool::getSimTime();
841
    if (currentTime < msg->getArrivalTime())
842
        return 0;
843
    else
844
        return eventsPerSimTimeInstance + 1;
845
}
846

    
847
void cSimulation::setupLocalRNGs() {
848

    
849
    //
850
    // Walk through vect[] and setup RNGs for each cSimpleModule
851
    //
852
    // TODO: Better way to do this? What about dynamically created Modules?
853
    cSimpleModule* mod = NULL;
854
    for (int i = 1; i <= last_id; i++) {
855
        if (vect[i]) {
856
            mod = dynamic_cast<cSimpleModule*>(vect[i]);
857
            if (mod) {
858
                mod->initLocalRNGs();
859
            }
860
        }
861
    }
862
}
863

    
864
//----
865

    
866
/**
867
 * A dummy implementation of cEnvir, only provided so that one
868
 * can use simulation library classes outside simulations, that is,
869
 * in programs that only link with the simulation library (<i>sim_std</i>)
870
 * and not with the <i>envir</i>, <i>cmdenv</i>, <i>tkenv</i>,
871
 * etc. libraries.
872
 *
873
 * Many simulation library classes make calls to <i>ev</i> methods,
874
 * which would crash if <tt>evPtr</tt> was NULL; one example is
875
 * cObject's destructor which contains an <tt>ev.objectDeleted()</tt>.
876
 * The solution provided here is that <tt>evPtr</tt> is initialized
877
 * to point to a StaticEnv instance, thus enabling library classes to work.
878
 *
879
 * StaticEnv methods either do nothing, or throw an "unsupported method"
880
 * exception, so StaticEnv is only useful for the most basic usage scenarios.
881
 * For anything more complicated, <tt>evPtr</tt> must be set in <tt>main()</tt>
882
 * to point to a proper cEnvir implementation, like the Cmdenv or
883
 * Tkenv classes. (The <i>envir</i> library provides a <tt>main()</tt>
884
 * which does exactly that.)
885
 *
886
 * @ingroup Envir
887
 */
888
class StaticEnv : public cEnvir
889
{
890
  protected:
891
    void unsupported() const {throw opp_runtime_error("StaticEnv: unsupported method called");}
892

    
893
    virtual void sputn(const char *s, int n) {(void) ::fwrite(s,1,n,stdout);}
894
    virtual void putsmsg(const char *msg) {::printf("\n<!> %s\n\n", msg);}
895
    virtual bool askyesno(const char *msg)  {unsupported(); return false;}
896

    
897
  public:
898
    // constructor, destructor
899
    StaticEnv() {}
900
    virtual ~StaticEnv() {}
901

    
902
    // eventlog callback interface
903
    virtual void objectDeleted(cObject *object) {}
904
    virtual void simulationEvent(cMessage *msg)  {}
905
    virtual void simulationEventEnd(double complexity)  {}
906
    virtual void messageSent_OBSOLETE(cMessage *msg, cGate *directToGate=NULL)  {}
907
    virtual void messageScheduled(cMessage *msg)  {}
908
    virtual void messageCancelled(cMessage *msg)  {}
909
    virtual void beginSend(cMessage *msg)  {}
910
    virtual void messageSendDirect(cMessage *msg, cGate *toGate, simtime_t propagationDelay, simtime_t transmissionDelay)  {}
911
    virtual void messageSendHop(cMessage *msg, cGate *srcGate)  {}
912
    virtual void messageSendHop(cMessage *msg, cGate *srcGate, simtime_t propagationDelay, simtime_t transmissionDelay)  {}
913
    virtual void endSend(cMessage *msg)  {}
914
    virtual void messageDeleted(cMessage *msg)  {}
915
    virtual void moduleReparented(cModule *module, cModule *oldparent)  {}
916
    virtual void componentMethodBegin(cComponent *from, cComponent *to, const char *methodFmt, va_list va, bool silent)  {}
917
    virtual void componentMethodEnd()  {}
918
    virtual void moduleCreated(cModule *newmodule)  {}
919
    virtual void moduleDeleted(cModule *module)  {}
920
    virtual void gateCreated(cGate *newgate)  {}
921
    virtual void gateDeleted(cGate *gate)  {}
922
    virtual void connectionCreated(cGate *srcgate)  {}
923
    virtual void connectionDeleted(cGate *srcgate)  {}
924
    virtual void displayStringChanged(cComponent *component)  {}
925
    virtual void undisposedObject(cObject *obj);
926

    
927
     // configuration, model parameters
928
    virtual void configure(cComponent *component) {}
929
    virtual void readParameter(cPar *parameter)  {unsupported();}
930
    virtual bool isModuleLocal(cModule *parentmod, const char *modname, int index)  {return true;}
931
    virtual cXMLElement *getXMLDocument(const char *filename, const char *path=NULL)  {unsupported(); return NULL;}
932
    virtual void forgetXMLDocument(const char *filename) {}
933
    virtual void flushXMLDocumentCache() {}
934
    virtual unsigned getExtraStackForEnvir() const  {return 0;}
935
    virtual cConfiguration *getConfig()  {unsupported(); return NULL;}
936
    virtual bool isGUI() const  {return false;}
937

    
938
    // UI functions (see also protected ones)
939
    virtual void bubble(cComponent *component, const char *text)  {}
940
    virtual std::string gets(const char *prompt, const char *defaultreply=NULL)  {unsupported(); return "";}
941
    virtual cEnvir& flush()  {::fflush(stdout); return *this;}
942

    
943
    // RNGs
944
    virtual int getNumRNGs() const {return 0;}
945
    virtual cRNG *getRNG(int k)  {unsupported(); return NULL;}
946
    virtual void getRNGMappingFor(cComponent *component)  {component->setRNGMap(0,NULL);}
947

    
948
    // output vectors
949
    virtual void *registerOutputVector(const char *modulename, const char *vectorname)  {return NULL;}
950
    virtual void deregisterOutputVector(void *vechandle)  {}
951
    virtual void setVectorAttribute(void *vechandle, const char *name, const char *value)  {}
952
    virtual bool recordInOutputVector(void *vechandle, simtime_t t, double value)  {return false;}
953

    
954
    // output scalars
955
    virtual void recordScalar(cComponent *component, const char *name, double value, opp_string_map *attributes=NULL)  {}
956
    virtual void recordStatistic(cComponent *component, const char *name, cStatistic *statistic, opp_string_map *attributes=NULL)  {}
957

    
958
    // snapshot file
959
    virtual std::ostream *getStreamForSnapshot()  {unsupported(); return NULL;}
960
    virtual void releaseStreamForSnapshot(std::ostream *os)  {unsupported();}
961

    
962
    // misc
963
    virtual int getArgCount() const  {unsupported(); return 0;}
964
    virtual char **getArgVector() const  {unsupported(); return NULL;}
965
    virtual int getParsimProcId() const {return 0;}
966
    virtual int getParsimNumPartitions() const {return 1;}
967
    virtual unsigned long getUniqueNumber()  {unsupported(); return 0;}
968
    virtual bool idle()  {return false;}
969
};
970

    
971
void StaticEnv::undisposedObject(cObject *obj)
972
{
973
    if (!cStaticFlag::isSet())
974
    {
975
        ::printf("<!> WARNING: global object variable (DISCOURAGED) detected: "
976
                 "(%s)`%s' at %p\n", obj->getClassName(), obj->getFullPath().c_str(), obj);
977
    }
978
}
979

    
980
static StaticEnv staticEnv;
981

    
982
// cSimulation's global variables
983
cEnvir *cSimulation::evPtr = &staticEnv;
984
cEnvir *cSimulation::staticEvPtr = &staticEnv;
985

    
986
cSimulation *cSimulation::simPtr = NULL;
987

    
988

    
989
NAMESPACE_END
990