void TcpClient::runTcpClient() { logTrace(name_ + " TcpClient start"); while (continueRunning_) { try { boost::asio::io_service ioService; tcp::socket s(ioService); tcp::resolver resolver(ioService); boost::asio::connect(s, resolver.resolve(endpoint_)); try { while (continueRunning_) { this->update(s); boost::this_thread::sleep(boost::posix_time::milliseconds(1)); } } catch (const boost::system::system_error& e) { if (e.code() == boost::asio::error::eof) { logWarning("Connection closed"); break; } else { throw; } } catch (const std::exception& e) { logWarning(e.what()); } } catch (const std::exception& e) { if (!ignoreErrors_) { throw; } logWarning(e.what()); boost::this_thread::sleep(boost::posix_time::seconds(10)); } } logTrace(name_ + " TcpClient stop"); }
bool P4PUpdateManager::run() { if (!m_isp_mgr) return false; logTrace("Update manager started"); while (true) { /* Execute as many tasks as we can before we pause to sleep */ while (!m_stopped && !m_tasks.empty()) { p4p::detail::ScopedExclusiveLock lock(m_mutex); /* Look at the top task on the queue and check * if it is time to execute it. */ Task* task = m_tasks.top(); /* We're done for now if the first task should not * yet be executed. */ if (task->exectime > time(NULL)) break; /* Remove task from the queue and execute */ m_tasks.pop(); logTrace("Executing task (type=%d,time=%lu,isp=%lx)", (int)task->type, (unsigned long)task->exectime, task->isp); executeTask(*task); logTrace("Finished executing task"); /* Task has already been dequeued */ removeTask(task, false); } /* Quit if we're signalled to do so */ if (m_stopped) { logTrace("Update manager stopping by signal"); break; } /* Sleep for a small amount of time before * checking the next task again. */ #ifdef WIN32 Sleep(1000); #else sleep(1); #endif } logTrace("Update manager finished"); return true; }
// . this is called when we got a local RdbList // . we need to call it to call the original caller callback void gotListWrapper2 ( void *state , RdbList *list , Msg5 *msg5 ) { logTrace( g_conf.m_logTraceMsg0, "BEGIN" ); Msg0 *THIS = (Msg0 *) state; THIS->reset(); // delete m_msg5 THIS->m_callback ( THIS->m_state );//, THIS->m_list ); logTrace( g_conf.m_logTraceMsg0, "END. rdbId=%d", (int)THIS->m_rdbId ); }
/** * Loads data from configuration file. */ void Config::load(const std::string &filename) { CHECK_THROW(filename.size()); m_configFile = filename; setPath("/"); std::ifstream ifs(filename.c_str(), std::ios::in); if (!ifs) { logWarning( "No config file found, using default configuration " "values." ); return; } while (ifs.good()) { std::string line; std::getline(ifs, line); // Remove preceeding whitespace boost::algorithm::trim(line); if (line.length() < 2) { continue; } // Directories if ((*(line.begin()) == '[') && (*(--line.end()) == ']')) { std::string dir; dir += line.substr(1, line.length() - 2); setPath("/" + dir); logTrace(TRACE_CONFIG, boost::format("Reading: got path=%s") % dir ); continue; } // Values size_t pos = line.find('=', 0); if (pos != std::string::npos) { std::string name = line.substr(0, pos); std::string value = line.substr(pos + 1); m_values[m_curPath + name] = value; logTrace(TRACE_CONFIG, boost::format( "Reading: got key=%s " "value=%s curpath=%s" ) % name % value % m_curPath ); continue; } } setPath("/"); }
void *Mem::gbcalloc ( size_t size , const char *note ) { logTrace( g_conf.m_logTraceMem, "size=%zu note='%s'", size, note ); void *mem = gbmalloc ( size , note ); logTrace( g_conf.m_logTraceMem, "mem=%p size=%zu note='%s'", mem, size, note ); // init it if ( mem ) memset ( mem , 0, size ); return mem; }
char *Mem::dup ( const void *data , size_t dataSize , const char *note ) { logTrace( g_conf.m_logTraceMem, "data=%p dataSize=%zu note='%s'", data, dataSize, note ); // keep it simple char *mem = (char *)mmalloc ( dataSize , note ); logTrace( g_conf.m_logTraceMem, "mem=%p data=%p dataSize=%zu note='%s'", (void*)mem, data, dataSize, note ); if ( mem ) memcpy ( mem , data , dataSize ); return mem; }
// . returns false and sets g_errno on error // . we are responsible for freeing reply/replySize void Msg0::gotReply ( char *reply , int32_t replySize , int32_t replyMaxSize ) { logTrace( g_conf.m_logTraceMsg0, "BEGIN" ); // timing debug if ( g_conf.m_logTimingNet && m_rdbId==RDB_POSDB && m_startTime > 0 ) log(LOG_TIMING,"net: msg0: Got termlist, termId=%" PRIu64". " "Took %" PRId64" ms, replySize=%" PRId32" (niceness=%" PRId32").", g_posdb.getTermId ( m_startKey ) , gettimeofdayInMilliseconds()-m_startTime, replySize,m_niceness); // TODO: insert some seals for security, may have to alloc // separate space for the list then // set the list w/ the remaining data QUICKPOLL(m_niceness); m_list->set ( reply , replySize , reply , // alloc buf begins here, too replyMaxSize , m_startKey , m_endKey , m_fixedDataSize , true , // ownData? m_useHalfKeys , m_ks ); // return now if we don't add to cache //if ( ! m_addToCache ) return; // // add posdb list to termlist cache // //if ( m_rdbId != RDB_POSDB ) return; // add to LOCAL termlist cache //addToTermListCache(m_coll,m_startKey,m_endKey,m_list); // ignore any error adding to cache //g_errno = 0; // . NO! no more network caching, we got gigabit... save space // for our disk, no replication, man, mem is expensive // . throw the just the list into the net cache // . addToNetCache() will copy it for it's own // . our current copy should be freed by the user's callback somewhere // . grab our corresponding rdb's local cache // . we'll use it to store this list since there's no collision chance //RdbCache *cache = m_rdb->getCache (); // . add the list to this cache // . returns false and sets g_errno on error // . will not be added if cannot copy the data //cache->addList ( m_startKey , m_list ) ; // reset g_errno -- we don't care if cache coulnd't add it //g_errno = 0; logTrace( g_conf.m_logTraceMsg0, "END" ); }
void Mem::gbfree ( void *ptr , int size , const char *note ) { logTrace( g_conf.m_logTraceMem, "ptr=%p size=%d note='%s'", ptr, size, note ); // don't let electric fence zap us //if ( size == 0 && ptr==(void *)0x7fffffff) return; if ( size == 0 ) return; // huh? if ( ! ptr ) return; // . get how much it was from the mem table // . this is used for alloc/free wrappers for zlib because it does // not give us a size to free when it calls our mfree(), so we use -1 int32_t slot = g_mem.getMemSlot ( ptr ); if ( slot < 0 ) { log(LOG_LOGIC,"mem: could not find slot (note=%s)",note); //Do NOT abort here... Let it run, otherwise it dies during merges. abort(); //log(LOG_LOGIC,"mem: FIXME!!!"); // return for now so procog does not core all the time! return; //char *xx = NULL; *xx = 0; } bool isnew = s_isnew[slot]; // if this returns false it was an unbalanced free if ( ! rmMem ( ptr , size , note ) ) return; g_inMemFunction = true; if ( isnew ) sysfree ( (char *)ptr ); else sysfree ( (char *)ptr - UNDERPAD ); g_inMemFunction = false; }
void AbstractEARAClient::createNewRouteFrom(Packet* packet, NetworkInterface* interface) { float initialPheromoneValue = calculateInitialPheromoneValue(packet->getTTL()); float initialEnergyValue = calculateInitialEnergyValue(static_cast<EARAPacket*>(packet)); routingTable->update(packet->getSource(), packet->getSender(), interface, initialPheromoneValue, initialEnergyValue); //TODO log energy value (in percent) logTrace("Created new route to %s via %s (phi=%.2f)", packet->getSourceString().c_str(), packet->getSenderString().c_str(), initialPheromoneValue); }
bool HttpMime::getField(const char **field, size_t *fieldLen) { size_t currentLinePos = m_valueStartPos; const char *colonPos = (const char *)memchr(m_currentLine + currentLinePos, ':', m_currentLineLen); // no colon if (colonPos == NULL) { return false; } currentLinePos = colonPos - m_currentLine; m_valueStartPos = currentLinePos + 1; *field = m_currentLine; *fieldLen = currentLinePos; // strip ending whitespaces while (*fieldLen > 0 && is_wspace_a(m_currentLine[*fieldLen - 1])) { --(*fieldLen); } logTrace(g_conf.m_logTraceHttpMime, "field='%.*s'", static_cast<int>(*fieldLen), *field); return (*fieldLen > 0); }
void * operator new [] (size_t size) throw (std::bad_alloc) { logTrace( g_conf.m_logTraceMem, "size=%zu", size ); // don't let electric fence zap us if ( size == 0 ) return (void *)0x7fffffff; size_t max = g_conf.m_maxMem; // don't go over max if ( g_mem.getUsedMem() + size >= max && g_conf.m_maxMem > 1000000 ) { log(LOG_ERROR, "mem: new(%zu): Out of memory.", size ); throw std::bad_alloc(); //throw 1; } void *mem = sysmalloc ( size ); if ( ! mem && size > 0 ) { g_errno = errno; g_mem.incrementOOMCount(); log( LOG_WARN, "mem: new(%zu): %s", size, mstrerror(g_errno)); throw std::bad_alloc(); } g_mem.addMem ( (char*)mem , size, "TMPMEM" , 1 ); return mem; }
void Mem::gbfree ( void *ptr , const char *note, size_t size , bool checksize ) { if(!s_lock.working) return; logTrace( g_conf.m_logTraceMem, "ptr=%p size=%zu note='%s'", ptr, size, note ); if ((checksize && size == 0) || !ptr) { return; } // . get how much it was from the mem table // . this is used for alloc/free wrappers for zlib because it does // not give us a size to free when it calls our mfree(), so we use -1 int32_t slot = g_mem.getMemSlot ( ptr ); if ( slot < 0 ) { log(LOG_LOGIC,"mem: could not find slot (note=%s)",note); // do NOT abort here... Let it run, otherwise it dies during merges. abort(); // return for now so procog does not core all the time! return; } bool isnew = s_isnew[slot]; // if this returns false it was an unbalanced free if (!rmMem(ptr, size, note, checksize)) { return; } if ( isnew ) sysfree ( (char *)ptr ); else sysfree ( (char *)ptr - UNDERPAD ); }
Process::Process() { logTrace("Process::Process"); pid_ = -1; status_ = -1; privileged_ = -1; for (int i = 0; i < 256; i++) { parameters_[i] = NULL; environment_[i] = NULL; } nextEnvironment_ = 0; nextParameter_ = 0; function_ = NULL; in_ = -1; out_ = -1; err_ = -1; inStream_ = NULL; outStream_ = NULL; errStream_ = NULL; nullStream_ = NULL; }
void gotMulticastReplyWrapper0 ( void *state , void *state2 ) { logTrace( g_conf.m_logTraceMsg0, "BEGIN" ); Msg0 *THIS = (Msg0 *)state; if ( ! g_errno ) { int32_t replySize; int32_t replyMaxSize; bool freeit; char *reply = THIS->m_mcast.getBestReply (&replySize, &replyMaxSize, &freeit); THIS->gotReply( reply , replySize , replyMaxSize ) ; } THIS->m_callback ( THIS->m_state ); logTrace( g_conf.m_logTraceMsg0, "END" ); }
void Mem::delnew ( void *ptr , size_t size , const char *note ) { logTrace( g_conf.m_logTraceMem, "ptr=%p size=%zu note=%s", ptr, size, note ); // we don't need to use mdelete() if checking for leaks is enabled // because the size of the allocated mem is in the hash table under // s_sizes[]. and the delete() operator is overriden below to catch this. return; }
int Process::parseStatus(int result, int status) { logTrace("Process::parseStatus"); if (result > 0) { if (WIFSTOPPED(status)) { logTest("Process::parseStatus", "Child %d was stopped " "with signal %d", pid_, (WSTOPSIG(status))); } else { #ifdef TEST if (WIFEXITED(status)) { logTest("Process::parseStatus", "Child %d exited " "with status %d", pid_, (WEXITSTATUS(status))); } else if (WIFSIGNALED(status)) { logTest("Process::parseStatus", "Child %d died " "because of signal %d", pid_, (WTERMSIG(status))); } #endif status_ = status; return 1; } } else if (result < 0) { if (EGET() == ECHILD) { // // The process died but we missed to // call the waitpid() at the time. // logWarning("Process::parseStatus::waitpid", EGET()); return 1; } logError("Process::parseStatus::waitpid", EGET()); return -1; } return 0; }
P4PUpdateManager::~P4PUpdateManager() { logTrace("Update manager freeing %u tasks left in queue", (unsigned int)m_tasks.size()); /* Free all tasks still in the queue */ while (!m_tasks.empty()) { Task* task = m_tasks.top(); m_tasks.pop(); delete task; } }
static void clientSocketRead(void *subject, const char *event, void *data, va_list args) { LineServerClient *client = data; char *message = va_arg(args, char *); logTrace("Read message: %s", message); g_string_append(client->line_buffer, message); unsigned int added_lines = processClientBuffer(client); if (added_lines > 0) { LineServerCallback callback = client->server->callback; callback(client); } }
void TcpBase::receiveMessages(tcp::socket& s) { mutex::scoped_lock lock(mutex_); boost::system::error_code error; char data[MAX_LEN]; size_t length = s.read_some(asio::buffer(data), error); if (length == 0 && error == asio::error::would_block) { boost::this_thread::sleep(boost::posix_time::milliseconds(1)); return; } if (error) { throw boost::system::system_error(error); } data[length] = '\0'; logTrace(name_ + " TcpServer new message"); std::string messagesStr(data); std::vector<std::string> messages; split(messages, messagesStr, is_any_of("\r\n")); for_each(messages.begin(), messages.end(), [this](std::string& message) { logTrace("RX: " + message); inQueue_.push(message); }); }
void TcpBase::sendQueuedMessages(tcp::socket& s) { mutex::scoped_lock lock(mutex_); while (!outQueue_.empty()) { std::string message = outQueue_.front(); boost::system::error_code error; s.write_some(boost::asio::buffer(message.data(), message.size()), error); if (error) { throw boost::system::system_error(error); } logTrace("TX: " + message); outQueue_.pop(); } }
int Process::setCommand(const char *command) { logTrace("Process::setCommand"); if (setValue(parameters_[0], command) && setValue(parameters_[1], command)) { nextParameter_ = 2; return 1; } return -1; }
bool P4PUpdateManager::setISPManager(const ISPManager* isp_mgr) { if (m_isp_mgr) return false; m_isp_mgr = isp_mgr; /* Enqueue initial tasks for updating ISP Info. Once we update * the PID Map, a task will automatically be enqueued to update * the pDistance map. */ std::vector<ISP*> isps; m_isp_mgr->listISPs(isps); logTrace("Update manager initialized with %u ISPs", (unsigned int)isps.size()); for (unsigned int i = 0; i < isps.size(); ++i) { logTrace("Enqueuing update task for ISP %lx", isps[i]); enqueueTask(0, TYPE_PIDMAP, isps[i]); } return true; }
bool HttpMime::getNextLine() { // clear values m_currentLine = NULL; m_currentLineLen = 0; m_valueStartPos = 0; m_attributeStartPos = 0; size_t currentPos = m_nextLineStartPos; // don't cross limit if (currentPos == m_mimeLen) { return false; } m_currentLine = m_mime + currentPos; // cater for multiline header size_t linePos = currentPos; do { bool foundLineEnding = false; char currentChar = m_mime[currentPos]; while (currentPos < m_mimeLen) { if (!foundLineEnding) { if (currentChar == '\r' || currentChar == '\n') { foundLineEnding = true; m_currentLineLen = (currentPos - linePos); } } else { if (currentChar != '\r' && currentChar != '\n') { break; } } currentChar = m_mime[++currentPos]; } } while (m_currentLineLen && (m_mime[currentPos] == ' ' || m_mime[currentPos] == '\t')); if (m_currentLineLen == 0) { // set to end of mime m_currentLineLen = (m_mime + m_mimeLen) - m_currentLine; } // store next lineStartPos m_nextLineStartPos = currentPos; logTrace(g_conf.m_logTraceHttpMime, "line='%.*s'", static_cast<int>(m_currentLineLen), m_currentLine); return true; }
// Relabels memory in table. Returns true on success, false on failure. // Purpose is for times when UdpSlot's buffer is not owned and freed by someone // else. Now we can verify that passed memory is freed. bool Mem::lblMem( void *mem, size_t size, const char *note ) { logTrace( g_conf.m_logTraceMem, "mem=%p size=%zu note=%s", mem, size, note ); // seems to be a bad bug in this... return true; #if 0 bool val = false; // Make sure we're not relabeling a NULL or dummy memory address, // if so, error then exit if ( !mem ) { //log( "mem: lblMem: Mem addr (0x%08X) invalid/NULL, not " // "relabeling.", mem ); return val; } uint32_t u = ( PTRTYPE ) mem * ( PTRTYPE ) 0x4bf60ade; uint32_t h = u % ( uint32_t ) m_memtablesize; // chain to bucket while ( s_mptrs[ h ] ) { if ( s_mptrs[ h ] == mem ) { if ( s_sizes[ h ] != size ) { val = false; log( LOG_WARN, "mem: lblMem: Mem addr (0x%08" PTRFMT") exists, size is %" PRId32" off.", ( PTRTYPE ) mem, s_sizes[ h ] - size ); break; } int32_t len = strlen( note ); if ( len > 15 ) len = 15; char *here = &s_labels[ h * 16 ]; memcpy ( here, note, len ); // make sure NULL terminated here[ len ] = '\0'; val = true; break; } h++; if ( h == m_memtablesize ) h = 0; } if ( !val ) { log( "mem: lblMem: Mem addr (0x%08" PTRFMT") not found.", ( PTRTYPE ) mem ); } return val; #endif }
int Process::setPrivileged(int value) { logTrace("Process::setPrivileged"); if (pid_ != -1) { logError("Process::setPrivileged", ESET(EPERM)); return -1; } privileged_ = value; return 1; }
int Process::setDescriptor(int &std, int fd) { logTrace("Process::setDescriptor"); if (pid_ != -1) { logError("Process::setDescriptor", ESET(EPERM)); return -1; } std = fd; return 1; }
FILE *Process::setDescriptorStream(int &fd, FILE *&stream, char *mode) { logTrace("Process::setDescriptorStream"); if ((stream = fdopen(fd, mode)) == NULL) { logError("Process::setDescriptorStream::fdopen", EGET()); logTest("Process::setDescriptorStream", "Can't create " "stream for descriptor %d", fd); return getNullStream(); } return stream; }
int Process::kill(int signal) { logTrace("Process::kill"); logTest("Process::kill", "Sending signal %d to process %d", signal, pid_); if (::kill(pid_, signal) < 0 && EGET() != ESRCH) { logError("Process::kill::kill", EGET()); return -1; } return 1; }
int Process::wait(const T_timestamp timeout) { logTrace("Process::wait"); if (pid_ < 0) { logError("Process::wait", ESET(ECHILD)); return 1; } // // Wait for the process until the timeout. // int status; int options = WUNTRACED; setTimer(timeout); int result; if ((result = waitpid(pid_, &status, options)) == -1) { if (EGET() == EINTR) { logTest("Process::wait", "Timeout raised waiting " "for pid %d", pid_); return 0; } else { logError("Process::wait", EGET()); return -1; } } resetTimer(); result = parseStatus(result, status); return result; }
/** * Saves data into configuration file. */ void Config::save(const std::string &filename) const { CHECK_THROW(filename.size()); std::ofstream ofs(filename.c_str(), std::ios::out); if (!ofs) { logError( boost::format("Failed to open config file '%s'" " for writing.") % filename ); return; } // root dir values copied here and written separately std::vector<std::pair<std::string, std::string> > rootValues; std::string curpath = "/"; std::string wrpath = ""; for (CIter i = m_values.begin(); i != m_values.end(); ++i) { size_t pos = (*i).first.find_last_of('/'); if (pos == 0) { rootValues.push_back(*i); continue; } std::string key = (*i).first.substr(pos + 1); std::string path = (*i).first.substr(1, pos > 0 ? pos - 1 :pos); std::string value = (*i).second; logTrace(TRACE_CONFIG, boost::format("Writing: Key=%s Value=%s Path=%s") % key % value % path ); if (path != wrpath) { // Path not written yet ofs << "[" << path << "]\n"; wrpath = path; } ofs << key << "=" << value << std::endl; } // root keys are written in section [] ofs << "[]" << std::endl; while (rootValues.size()) { ofs << rootValues.back().first.substr(1) << "="; ofs << rootValues.back().second << std::endl; rootValues.pop_back(); } }