realtimescheduler.cc

Go to the documentation of this file.
00001 //
00002 // Copyright (C) 2006 Institut fuer Telematik, Universitaet Karlsruhe (TH)
00003 //
00004 // This program is free software; you can redistribute it and/or
00005 // modify it under the terms of the GNU General Public License
00006 // as published by the Free Software Foundation; either version 2
00007 // of the License, or (at your option) any later version.
00008 //
00009 // This program is distributed in the hope that it will be useful,
00010 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00011 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012 // GNU General Public License for more details.
00013 //
00014 // You should have received a copy of the GNU General Public License
00015 // along with this program; if not, write to the Free Software
00016 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
00017 //
00018 
00024 #include "realtimescheduler.h"
00025 
00026 Register_PerRunConfigOption(CFGID_EXTERNALAPP_CONNECTION_LIMIT, "externalapp-connection-limit", CFG_INT, NULL, "TODO some documentation");
00027 Register_PerRunConfigOption(CFGID_EXTERNALAPP_APP_PORT, "externalapp-app-port", CFG_INT, NULL, "TODO some documentation");
00028 
00029 inline std::ostream& operator<<(std::ostream& os, const timeval& tv)
00030 {
00031     return os << (unsigned long)tv.tv_sec << "s" << tv.tv_usec << "us";
00032 }
00033 
00034 RealtimeScheduler::RealtimeScheduler() : cScheduler()
00035 {
00036     FD_ZERO(&all_fds);
00037     maxfd = 0;
00038     netw_fd = INVALID_SOCKET;
00039     additional_fd = INVALID_SOCKET;
00040 }
00041 
00042 RealtimeScheduler::~RealtimeScheduler()
00043 { }
00044 
00045 void RealtimeScheduler::startRun()
00046 {
00047     if (initsocketlibonce()!=0)
00048         throw cRuntimeError("RealtimeScheduler: Cannot initialize socket library");
00049 
00050     gettimeofday(&baseTime, NULL);
00051 
00052     appModule = NULL;
00053     appNotificationMsg = NULL;
00054     module = NULL;
00055     notificationMsg = NULL;
00056 
00057     appConnectionLimit = ev.getConfig()->getAsInt(CFGID_EXTERNALAPP_CONNECTION_LIMIT, 0);
00058 
00059     if (initializeNetwork()) {
00060         opp_error("realtimeScheduler error: initializeNetwork failed\n");
00061     }
00062 }
00063 
00064 void RealtimeScheduler::endRun()
00065 {}
00066 
00067 void RealtimeScheduler::executionResumed()
00068 {
00069     gettimeofday(&baseTime, NULL);
00070     baseTime = timeval_substract(baseTime, SIMTIME_DBL(simTime()));
00071 }
00072 
00073 void RealtimeScheduler::setInterfaceModule(cModule *mod, cMessage *notifMsg,
00074                                            PacketBuffer* buffer, int mtu,
00075                                            bool isApp)
00076 {
00077     if (!mod || !notifMsg || !buffer) {
00078         throw cRuntimeError("RealtimeScheduler: setInterfaceModule(): "
00079                                 "arguments must be non-NULL");
00080     }
00081 
00082     if (!isApp) {
00083         if (module) {
00084             throw cRuntimeError("RealtimeScheduler: setInterfaceModule() "
00085                                     "already called");
00086         }
00087         module = mod;
00088         notificationMsg = notifMsg;
00089         packetBuffer = buffer;
00090         buffersize = mtu;
00091     } else {
00092         if (appModule) {
00093             throw cRuntimeError("RealtimeScheduler: setInterfaceModule() "
00094                                     "already called");
00095         }
00096         appModule = mod;
00097         appNotificationMsg = notifMsg;
00098         appPacketBuffer = buffer;
00099         appBuffersize = mtu;
00100     }
00101 }
00102 
00103 bool RealtimeScheduler::receiveWithTimeout(long usec)
00104 {
00105     bool newEvent = false;
00106     // prepare sets for select()
00107     fd_set readFD;
00108     readFD = all_fds;
00109 
00110     timeval timeout;
00111     timeout.tv_sec = 0;
00112     timeout.tv_usec = usec;
00113 
00114     if (select(FD_SETSIZE, &readFD, NULL, NULL, &timeout) > 0) {
00115         // Read on all sockets with data
00116         for (SOCKET fd = 0; fd <= maxfd; fd++) {
00117             if (FD_ISSET(fd, &readFD)) {
00118                 // Incoming data on netw_fd
00119                 if (fd == netw_fd) {
00120                     char* buf = new char[buffersize];
00121                     int nBytes;
00122 
00123                     // FIXME: Ugly. But we want to support IPv4 and IPv6 here, so we
00124                     // reserve enough space for the "bigger" address.
00125                     sockaddr* from = (sockaddr*) new sockaddr_in;
00126                     socklen_t addrlen = sizeof(sockaddr_in);
00127 
00128                     // FIXME: Ugly...
00129                     getsockname(netw_fd, from, &addrlen);
00130                     if ( from->sa_family != SOCK_DGRAM ) {
00131                         delete from;
00132                         from = 0;
00133                         addrlen = 0;
00134                         // use read() for TUN device
00135                         nBytes = read(netw_fd, buf, buffersize);
00136                     } else {
00137                         addrlen = sizeof(sockaddr_in);
00138                         nBytes = recvfrom(netw_fd, buf, buffersize, 0, from, &addrlen);
00139                     }
00140 
00141                     if (nBytes < 0) {
00142                         ev << "[RealtimeScheduler::receiveWithTimeout()]\n"
00143                             << "    Error reading from network: " << strerror(sock_errno())
00144                             << endl;
00145                         delete[] buf;
00146                         buf = NULL;
00147                         opp_error("Read from network device returned an error");
00148                     } else if (nBytes == 0) {
00149                         ev << "[RealtimeScheduler::receiveWithTimeout()]\n"
00150                            << "    Received 0 byte long UDP packet!" << endl;
00151                         delete[] buf;
00152                         buf = NULL;
00153                     } else {
00154                         // write data to buffer
00155                         ev << "[RealtimeScheduler::receiveWithTimeout()]\n"
00156                             << "    Received " << nBytes << " bytes"
00157                             << endl;
00158                         packetBuffer->push_back(PacketBufferEntry(buf, nBytes, from, addrlen));
00159                         // schedule notificationMsg for the interface module
00160                         sendNotificationMsg(notificationMsg, module);
00161                         newEvent = true;
00162                     }
00163                 } else if ( fd == additional_fd ) {
00164                     // Data on additional FD
00165                     additionalFD();
00166                     newEvent = true;
00167                 } else {
00168                     // Data on app FD
00169                     char* buf = new char[appBuffersize];
00170                     int nBytes = recv(fd, buf, appBuffersize, 0);
00171                     if (nBytes < 0) {
00172                         delete[] buf;
00173                         buf = NULL;
00174                         ev << "[RealtimeScheduler::receiveWithTimeout()]\n"
00175                             << "    Read error from application socket: "
00176                             << strerror(sock_errno()) << endl;
00177                         opp_error("Read from network device returned an error (App)");
00178                     } else if (nBytes == 0) {
00179                         // Application closed Socket
00180                         ev << "[RealtimeScheduler::receiveWithTimeout()]\n"
00181                             << "    Application closed socket"
00182                             << endl;
00183                         delete[] buf;
00184                         buf = NULL;
00185                         closeAppSocket(fd);
00186                         newEvent = true;
00187                     } else {
00188                         // write data to buffer
00189                         ev << "[RealtimeScheduler::receiveWithTimeout()]\n"
00190                             << "    Received " << nBytes << " bytes"
00191                             << endl;
00192                         appPacketBuffer->push_back(PacketBufferEntry(buf, nBytes, PacketBufferEntry::PACKET_DATA, fd));
00193                         // schedule notificationMsg for the interface module
00194                         sendNotificationMsg(appNotificationMsg, appModule);
00195                         newEvent = true;
00196                     }
00197                 }
00198             }
00199         }
00200     }
00201     return newEvent;
00202 }
00203 
00204 int RealtimeScheduler::receiveUntil(const timeval& targetTime)
00205 {
00206     // if there's more than 200ms to wait, wait in 100ms chunks
00207     // in order to keep UI responsiveness by invoking ev.idle()
00208     timeval curTime;
00209     gettimeofday(&curTime, NULL);
00210     while (targetTime.tv_sec-curTime.tv_sec >=2 ||
00211             timeval_diff_usec(targetTime, curTime) >= 200000) {
00212         if (receiveWithTimeout(100000)) { // 100ms
00213             if (ev.idle()) return -1;
00214             return 1;
00215         }
00216         if (ev.idle()) return -1;
00217         gettimeofday(&curTime, NULL);
00218     }
00219 
00220     // difference is now at most 100ms, do it at once
00221     long usec = timeval_diff_usec(targetTime, curTime);
00222     if (usec>0)
00223         if (receiveWithTimeout(usec)) {
00224             if (ev.idle()) return -1;
00225             return 1;
00226         }
00227     if (ev.idle()) return -1;
00228     return 0;
00229 }
00230 
00231 cMessage *RealtimeScheduler::getNextEvent()
00232 {
00233     // assert that we've been configured
00234     if (!module)
00235         throw cRuntimeError("RealtimeScheduler: setInterfaceModule() not called: it must be called from a module's initialize() function");
00236     // FIXME: reimplement sanity check
00237 //    if (app_fd >= 0 && !appModule)
00238 //        throw cRuntimeError("RealtimeScheduler: setInterfaceModule() not called from application: it must be called from a module's initialize() function");
00239 
00240     // calculate target time
00241     timeval targetTime;
00242     cMessage *msg = sim->msgQueue.peekFirst();
00243     if (!msg) {
00244         // if there are no events, wait until something comes from outside
00245         // TBD: obey simtimelimit, cpu-time-limit
00246         targetTime.tv_sec = LONG_MAX;
00247         targetTime.tv_usec = 0;
00248     } else {
00249         // use time of next event
00250         simtime_t eventSimtime = msg->getArrivalTime();
00251         targetTime = timeval_add(baseTime, SIMTIME_DBL(eventSimtime));
00252     }
00253 
00254     // if needed, wait until that time arrives
00255     timeval curTime;
00256     gettimeofday(&curTime, NULL);
00257     if (timeval_greater(targetTime, curTime)) {
00258         int status = receiveUntil(targetTime);
00259         if (status == -1) {
00260             printf("WARNING: receiveUntil returned -1 (user interrupt)\n");
00261             return NULL; // interrupted by user
00262         } else if (status == 1) {
00263             msg = sim->msgQueue.peekFirst(); // received something
00264         }
00265     } else {
00266         //    printf("WARNING: Lagging behind realtime!\n");
00267         // we're behind -- customized versions of this class may
00268         // alert if we're too much behind, whatever that means
00269     }
00270     // ok, return the message
00271     return msg;
00272 }
00273 
00274 void RealtimeScheduler::closeAppSocket(SOCKET fd)
00275 {
00276 #ifdef _WIN32
00277     closesocket(fd);
00278 #else
00279     close(fd);
00280 #endif
00281     FD_CLR(fd, &all_fds);
00282 
00283     appPacketBuffer->push_back(PacketBufferEntry(0, 0, PacketBufferEntry::PACKET_FD_CLOSE, fd));
00284     sendNotificationMsg(appNotificationMsg, appModule);
00285 }
00286 
00287 void RealtimeScheduler::sendNotificationMsg(cMessage* msg, cModule* mod)
00288 {
00289     if (msg->isScheduled()) return; // Notification already scheduled
00290     timeval curTime;
00291     gettimeofday(&curTime, NULL);
00292     curTime = timeval_substract(curTime, baseTime);
00293     simtime_t t = curTime.tv_sec + curTime.tv_usec*1e-6;
00294 
00295     // if t < simTime, clock would go backwards. this would be bad...
00296     // (this could happen as timeval has a lower number of digits that simtime_t)
00297     if (t < simTime()) t = simTime();
00298 
00299     msg->setSentFrom(mod, -1, simTime());
00300     msg->setArrival(mod,-1,t);
00301     simulation.msgQueue.insert(msg);
00302 }
00303 
00304 ssize_t RealtimeScheduler::sendBytes(const char *buf,
00305                                      size_t numBytes,
00306                                      sockaddr* addr,
00307                                      socklen_t addrlen,
00308                                      bool isApp,
00309                                      SOCKET fd)
00310 {
00311     if (!buf) {
00312         ev << "[RealtimeScheduler::sendBytes()]\n"
00313         << "    Error sending packet: buf = NULL"
00314         << endl;
00315         return -1;
00316     }
00317     if (!isApp) {
00318         if( numBytes > buffersize ) {
00319             ev << "[RealtimeScheduler::sendBytes()]\n"
00320             << "    Trying to send oversized packet: size " << numBytes << " mtu " << buffersize
00321             << endl;
00322             opp_error("Can't send packet: too large"); //FIXME: Throw exception instead
00323         }
00324 
00325         if ( netw_fd == INVALID_SOCKET ) {
00326             ev << "[RealtimeScheduler::sendBytes()]\n"
00327             << "    Can't send packet to network: no tun/udp socket"
00328             << endl;
00329             return 0;
00330         }
00331         int nBytes;
00332         if (addr) {
00333             nBytes =  sendto(netw_fd, buf, numBytes, 0, addr, addrlen);
00334         } else {
00335             // TUN
00336             nBytes =  write(netw_fd, buf, numBytes);
00337         }
00338         if (nBytes < 0) {
00339             ev << "[RealtimeScheduler::sendBytes()]\n"
00340             << "    Error sending data to network: " << strerror(sock_errno()) << "\n"
00341             << "    FD = " << netw_fd << ", numBytes = " << numBytes <<  ", addrlen = " << addrlen
00342             << endl;
00343         }
00344         return nBytes;
00345 
00346     } else {
00347         if (numBytes > appBuffersize) {
00348             ev << "[RealtimeScheduler::sendBytes()]\n"
00349             << "    Trying to send oversized packet: size " << numBytes << "\n"
00350             << "    mtu " << appBuffersize
00351             << endl;
00352             opp_error("Can't send packet: too large"); //FIXME: Throw exception instead
00353         }
00354         // If no fd is given, select a "random" one
00355         if (fd == INVALID_SOCKET) {
00356             for (fd = 0; fd <= maxfd; fd++) {
00357                 if (fd == netw_fd) continue;
00358                 if (fd == additional_fd) continue;
00359                 if (FD_ISSET(fd, &all_fds)) break;
00360             }
00361             if (fd > maxfd) {
00362                 throw cRuntimeError("Can't send packet to Application: no socket");
00363             }
00364         }
00365         return send(fd, buf, numBytes, 0);
00366     }
00367     // TBD check for errors
00368 }
00369 

Generated on Wed Mar 25 16:32:49 2009 for OverSim by  doxygen 1.5.5