// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- bool MXAFILEREADER_CLASS_NAME::initReader() { #if defined (WINDOWS_LARGE_FILE_SUPPORT) _instream = CreateFile(TEXT(this->_filename.c_str()), // file to open GENERIC_READ, // open for reading FILE_SHARE_READ, // share for reading NULL, // default security OPEN_EXISTING, // existing file only FILE_FLAG_SEQUENTIAL_SCAN, // normal file NULL); // no attr. template if (_instream == INVALID_HANDLE_VALUE) { std::cout << logTime() << "Error: Failed to open file: " + std::string(this->_filename) << " Error code:(" << GetLastError() << ")" << std::endl; return false; } #else // Open a stream with a large buffer. _buffer.resize(BUFF_SIZE, 0); _instream.rdbuf()->pubsetbuf ( &(_buffer.front()), BUFF_SIZE ); _instream.open ( _filename.c_str(), std::ifstream::in | std::ifstream::binary ); if ( !_instream.is_open() ) { std::cout << logTime() << "Error: Failed to open file: " + _filename << std::endl; return false; } #endif return true; }
/** * for the first few seconds after start up, we run a lamp test * * @param force run test even if it has already run * @return true if we are still in the lamp test */ bool SensorManager::lampTest(bool force) { static bool done; static unsigned long startTime; static int numTests = 8; // power on self-test static ledState test[] = { led_off, led_red, led_green, led_yellow, }; if (force && done) { done = false; startTime = 0; numTests = 60; // one minute of tests } else if (done) return( false ); // figure out when the tests started (checking for timer wrap) unsigned long now = millis(); if (startTime == 0 || now < startTime) { startTime = now; #ifdef DEBUG_EVT if (debug > 1) { // excuse: strings take up data space logTime(now); putchar('T'); putchar('E'); putchar('S'); putchar('T'); putchar('\n'); } #endif } // see if we're done with the tests yet int second = (now - startTime)/1000; if (second > numTests) { done = true; #ifdef DEBUG_EVT if (debug > 1) { // excuse: strings take up data space logTime(now); putchar('R'); putchar('U'); putchar('N'); putchar('\n'); } #endif return false; } // set all the LEDs according to the test phase for ( int i = 0; i < cfg->sensors->num_sensors; i++ ) { setLed(i, test[second%4], led_none ); } return( true ); }
void onBlock(int rank, ADIOS_FILE* f, ADIOS_VARINFO* v, int i, int j, int blockCounter, FastBitDataType ft) { char bmsVarName[100]; char keyVarName[100]; char offsetName[100]; int64_t var_ids_bms[v->nblocks[i]]; int64_t var_ids_key[v->nblocks[i]]; int64_t var_ids_offset[v->nblocks[i]]; sprintf(bmsVarName, "bms-%d-%d-%d", v->varid, i, j); sprintf(keyVarName, "key-%d-%d-%d", v->varid, i, j); sprintf(offsetName, "offset-%d-%d-%d", v->varid, i, j); uint64_t blockSize = fastbit_adios_util_getBlockSize(v, i, j); uint64_t blockDataByteSize = adios_type_size (v->type, v->value) * blockSize; char notes[100]; logTime(NULL); logTimeMillis(NULL); sprintf(notes, " reading data from adios on varid=%d, time=%d, block: %d, size=%ld bytes=%ld", v->varid, i, j, blockSize, blockDataByteSize); logTime(notes); logTimeMillis(notes); localtime(&indexRefresh); //printf(" %d th block / (%d), size= %" PRIu64 " bytes=%" PRIu64, j, blockSize, blockCounter, blockDataByteSize); void* data = malloc (blockDataByteSize); ADIOS_SELECTION* blockSel = adios_selection_writeblock(j); //adios_selcton_writeblock(num), 0 <= num < nblocks[timestep] //ADIOS_SELECTION* blockSel = adios_selection_writeblock(blockCounter); int err = adios_schedule_read_byid(f, blockSel, v->varid, i, 1, data); if (!err) { err = adios_perform_reads(f, 1); } else { printf("Unable to read block %d at timestep: %d \n", j, i); return; //break; } //fastbit_adios_util_printData(data, v->type, blockSize); char selName[20]; sprintf(selName, "block-%d", j); processData(data, blockSize, rank, i, selName, ft, v); //processData(void* data, uint64_t dataCount, int rank, int timestep, char* selName, FastBitDataType ft, ADIOS_VARINFO* v) adios_selection_delete(blockSel); verifyData(f, v, blockCounter, i); } // onblock
void *copyThread(void *voidcmr){ struct CopyMessageRequest *cmr = (struct CopyMessageRequest*)voidcmr; char targeturl[128], sourceurl[128]; logTime("startCopyMessage"); sprintf(targeturl, "%s:%u", cmr->targetip, cmr->targetport); sprintf(sourceurl, "%s:%u", cmr->sourceip, cmr->sourceport); QpidClient qpidclient((std::string)sourceurl, (std::string)targeturl); qpidclient.receiveSend(cmr->sourcename, cmr->targetname); logTime("finishCopyMessage"); delete cmr; return NULL; }
/* * 现在squid.conf中可以配置的debug_level等级只有连个 * 0:显示关键的信息 * 1:显示所有信息 * */ int addInfoLog(int type, const char* str) { time_t t; t = time(NULL); char timeStr[128]; snprintf(timeStr, sizeof(timeStr), "%s", logTime(t)); str_rtrim(timeStr, "\n"); log_open(); if(0 == type ) { file_size += fprintf(fp, "[%s]:%s\n", timeStr, str); } else if(1 == type && 1 == conf.debug_level) { file_size += fprintf(fp, "[%s]:%s\n", timeStr, str); } else if (2 == type) { file_size += fprintf(fp, "Error[%s]:%s\n", timeStr, str); } fflush(fp); if(file_size > LOG_ROTATE_SIZE) log_rotate(); // fclose(fp); return 1; }
OsStatus LogNotifier::handleAlarm( const OsTime alarmTime, const UtlString& callingHost, const cAlarmData* alarmData, const UtlString& alarmMsg) { OsStatus retval = OS_SUCCESS; OsSysLog::add(alarmData->getComponent().data(), 0, FAC_ALARM, alarmData->getSeverity(), "%s: %s", alarmData->getCode().data(), alarmMsg.data()); OsDateTime logTime(alarmTime); UtlString strTime ; logTime.getIsoTimeStringZus(strTime); char tempMsg[500 + alarmMsg.length()]; snprintf(tempMsg, sizeof(tempMsg), "\"%s\":%zd:%s:%s:%s:%s::%s:\"%s\"", strTime.data(), ++mEventCount, OsSysLog::sFacilityNames[FAC_ALARM], OsSysLog::priorityName(alarmData->getSeverity()), callingHost.data(), alarmData->getComponent().data(), alarmData->getCode().data(), escape(alarmMsg).data()); tempMsg[sizeof(tempMsg)-2]='"'; tempMsg[sizeof(tempMsg)-1]=0; char* szPtr = strdup(tempMsg); OsSysLogMsg msg(OsSysLogMsg::LOG, szPtr); mpOsSysLogTask->postMessage(msg); return retval; }
/** * @param zone to be updated * @param armed */ void SensorManager::arm( int zone, bool armed ) { if (zone < 0 || zone > 8) return; if (zone == 0 && armed) { // system arm implies reset for( int i = 0; i < cfg->sensors->num_sensors; i++ ) { triggered(i, false); } } // update zoneArmed state accordingly unsigned char mask = 1 << zone; if (armed) zoneArmed |= mask; else zoneArmed &= ~mask; #ifdef DEBUG_EVT if (debug > 1) { // excuse: strings take up data space logTime( millis() ); putchar(armed ? 'A' : 'd'); putchar(' '); putchar('Z'); putchar('='); putchar('0' + zone%10); putchar('\n'); } #endif }
void Log::print(const char *fmt, ...) { char buf[BUFSIZE]; va_list args; va_start(args, fmt); snprintf(buf, sizeof(buf), "%s| %s", logTime(curTime), fmt); vfprintf(logFile, buf, args); fflush(logFile); va_end(args); }
static void readFromClient(void *pParam) { struct iocLogClient *pclient = (struct iocLogClient *)pParam; int recvLength; int size; logTime(pclient); size = (int) (sizeof(pclient->recvbuf) - pclient->nChar); recvLength = recv(pclient->insock, &pclient->recvbuf[pclient->nChar], size, 0); if (recvLength <= 0) { if (recvLength<0) { int errnoCpy = SOCKERRNO; if (errnoCpy==SOCK_EWOULDBLOCK || errnoCpy==SOCK_EINTR) { return; } if (errnoCpy != SOCK_ECONNRESET && errnoCpy != SOCK_ECONNABORTED && errnoCpy != SOCK_EPIPE && errnoCpy != SOCK_ETIMEDOUT ) { char sockErrBuf[64]; epicsSocketConvertErrnoToString ( sockErrBuf, sizeof ( sockErrBuf ) ); fprintf(stderr, "%s:%d socket=%d size=%d read error=%s\n", __FILE__, __LINE__, pclient->insock, size, sockErrBuf); } } /* * disconnect */ freeLogClient (pclient); return; } pclient->nChar += (size_t) recvLength; writeMessagesToLog (pclient); }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int main (int argc, char const *argv[]) { // This code is NOT READY to run AT ALL. IT was just a PLACE TO START BOOST_ASSERT(false); QString configFile; try { // Handle program options passed on command line. TCLAP::CmdLine cmd("PipelineRunner", ' ', DREAM3DLib::Version::Complete()); TCLAP::ValueArg<std::string> inputFileArg( "c", "config", "The text file containing the pipeline information.", true, "", "Pipeline Config File"); cmd.add(inputFileArg); // Parse the argv array. cmd.parse(argc, argv); if (argc == 1) { std::cout << "PipelineRunner program was not provided any arguments. Use the --help argument to show the help listing." << std::endl; return EXIT_FAILURE; } configFile = QString::fromStdString(inputFileArg.getValue()); } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << logTime() << " error: " << e.error() << " for arg " << e.argId() << std::endl; return EXIT_FAILURE; } // Create the QSettings Object QSettings prefs(configFile, QSettings::IniFormat, NULL); readSettings(prefs); return EXIT_SUCCESS; }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int openHDF5File(const std::string m_FileName, bool appendData) { // Try to open a file to append data into if (APPEND_DATA_TRUE == appendData) { m_FileId = H5Utilities::openFile(m_FileName, false); } // No file was found or we are writing new data only to a clean file if (APPEND_DATA_FALSE == appendData || m_FileId < 0) { m_FileId = H5Utilities::createFile (m_FileName); } //Something went wrong either opening or creating the file. Error messages have // Alread been written at this point so just return. if (m_FileId < 0) { std::cout << logTime() << "The hdf5 file could not be opened or created.\n The Given filename was:\n\t[" << m_FileName<< "]" << std::endl; } return m_FileId; }
void processData(void* data, uint64_t dataCount, int rank, int timestep, char* selName, FastBitDataType ft, ADIOS_VARINFO* v) { char bmsVarName[100]; char keyVarName[100]; char offsetName[100]; int64_t var_ids_bms; int64_t var_ids_key; int64_t var_ids_offset; sprintf(bmsVarName, "bms-%d-%d-%s", v->varid, timestep, selName); sprintf(keyVarName, "key-%d-%d-%s", v->varid, timestep, selName); sprintf(offsetName, "offset-%d-%d-%s", v->varid, timestep, selName); double* keys = NULL; int64_t *offsets = NULL; uint32_t *bms = NULL; uint64_t nk=0, no=0, nb=0; const char* datasetName = "test"; logTime(" data collected, fastbit start indexing"); logTimeMillis(" data collected, fastbit start indexing"); //fastbit_adios_util_printData(data, v->type, blockBytes/adios_type_size(v->type, v->value)); fastbitIndex(datasetName, data, dataCount, ft, &keys, &nk, &offsets, &no, &bms, &nb); logTime(" indexed on block"); logTimeMillis(" indexed on block"); printf(" RANK:%d, index created = %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", on var:%d, timestep: %d, block %s\n", rank, nb, nk, no, v->varid, timestep, selName); sum_nb += nb; sum_nk += nk, sum_no += no; defineFastbitVar(1, bmsVarName, &var_ids_bms, adios_unsigned_integer, &nb,0,0); defineFastbitVar(1, keyVarName, &var_ids_key, adios_double, &nk, 0, 0); defineFastbitVar(1, offsetName, &var_ids_offset, adios_long, &no, 0, 0); printf("bms[0] = %" PRIu64 ", bms[1]=%" PRIu64 " \n", bms[0], bms[1]); //var_ids_bms = defineAdiosVar(bmsVarName, adios_unsigned_integer, nb, 0, 0); //var_ids_key = defineAdiosVar(keyVarName, adios_double, nk, 0, 0); //var_ids_offset = defineAdiosVar(offsetName, adios_long, no, 0, 0); logTime(" write starts"); logTimeMillis(" write starts"); adios_write_byid(gAdios_write_file, var_ids_bms, bms); adios_write_byid(gAdios_write_file, var_ids_key, keys); adios_write_byid(gAdios_write_file, var_ids_offset, offsets); logTime(" write ends"); logTimeMillis(" write ends"); sumLogTime(1); sumLogTimeMillis(1); free(data); data = NULL; free(bms); bms = NULL; free(keys); keys = NULL; free(offsets); offsets = NULL; }
/** * read all of the inputs, debounce them, and update * the sensor and LED status accordingly. * * Notes on defibrilation: * We burned up some relays as a result of a failing sensor. * ctrl->minInterval() is fastest acceptable change rate * ctrl->maxTriggers() is defibrilation threshold * we increment a per-zone count every time a sensor changes * we decrement the count every minInterval * while count > maxTriggers, we consider zone to be fibrilating * and it is not allowed to trigger an alarm * we fast blink any triggered sensor in a fibrilating zone */ void SensorManager::sample() { // note the time of this sample unsigned long now = millis(); // latch the current values inshifter->read(); // start all relays out normal zoneState = 0; // note whether or not system is currently armed unsigned char armed = zoneArmed & 1; // run through all of the configured sensors for( int i = 0; i < cfg->sensors->num_sensors; i++ ) { // if sensor isn't configured ignore it int x = cfg->sensors->in(i); if (x == 255) { setLed(i, led_off, led_none); // show no status continue; } // get the current (normalized) value of this sensor bool v = (inshifter->get( x ) == cfg->sensors->sense(i)); // see if the value is stable (same as last sample) if (v != previous(i)) { previous(i,v); #ifdef DEBOUNCE debounce[i] = cfg->sensors->delay(i) + 1; } if (debounce[i] > 0) { debounce[i] = debounce[i] - 1; continue; #endif } // note what zone this sensor is in int z = cfg->sensors->zone(i); // see if the stable value is a change if (v != status(i)) { status( i, v ); #ifdef DEFIB // count recent transitions in each zone if (z >= 1 && z <= 8 && defib[z] < 255) defib[z]++; #endif #ifdef DEBUG_EVT if (debug > 1) { // excuse: strings take up data space logTime( now ); putchar( v == 0 ? '!' : '-' ); putchar(' '); putchar('S'); putchar('='); putchar('0' + i/10); putchar('0' + i%10); putchar('\n'); } #endif } // figure out whether system and sensor/zone are armed unsigned char enabled; // is the zone enabled unsigned char fibrilating = 0; if (z >= 1 && z <= 8) { enabled = zoneArmed & (1 << z); #ifdef DEFIB fibrilating = (defib[z] >= cfg->controls->maxTriggers()); #endif if (enabled && !v && !fibrilating) { zoneState |= 1 << z; if (armed) triggered(i, true); } } // figure out what to do with the LEDs for this sensor enum ledState state = led_green; enum ledBlink blink = led_none; if (!v) { state = (armed && enabled) ? led_red : led_yellow; blink = fibrilating ? led_fast : led_none; } else if (triggered(i)) { state = led_red; blink = fibrilating ? led_fast : led_med; } else if (armed && enabled) blink = led_slow; setLed( i, state, blink ); } }
std::unique_ptr<UnitEmitter> compile( const char* filename, const MD5& md5, folly::StringPiece code, const Native::FuncTable& nativeFuncs, bool forDebuggerEval, AsmCallbacks* callbacks ) { if (!isRunning()) { start(); } std::string prog; std::unique_ptr<Unit> u; try { m_compilations++; StructuredLogEntry log; log.setStr("filename", filename); int64_t t = logTime(log, 0, nullptr, true); writeProgram(filename, md5, code, forDebuggerEval); t = logTime(log, t, "send_source"); prog = readResult(&log); t = logTime(log, t, "receive_hhas"); auto ue = assemble_string(prog.data(), prog.length(), filename, md5, nativeFuncs, false /* swallow errors */, callbacks ); logTime(log, t, "assemble_hhas"); if (RuntimeOption::EvalLogExternCompilerPerf) { StructuredLog::log("hhvm_detailed_frontend_performance", log); } return ue; } catch (CompileException& ex) { stop(); if (m_options.verboseErrors) { Logger::FError("ExternCompiler Error: {}", ex.what()); } throw; } catch (CompilerFatal& ex) { // this catch is here so we don't fall into the std::runtime_error one throw; } catch (FatalErrorException&) { // we want these to propagate out of the compiler throw; } catch (AssemblerUnserializationError& ex) { // This (probably) has nothing to do with the php/hhas, so don't do the // verbose error handling we have in the AssemblerError case. throw; } catch (AssemblerError& ex) { if (m_options.verboseErrors) { auto const msg = folly::sformat( "{}\n" "========== PHP Source ==========\n" "{}\n" "========== ExternCompiler Result ==========\n" "{}\n", ex.what(), code, prog); Logger::FError("ExternCompiler Generated a bad unit: {}", msg); // Throw the extended message to ensure the fataling unit contains the // additional context throw AssemblerError(msg); } throw; } catch (std::runtime_error& ex) { if (m_options.verboseErrors) { Logger::FError("ExternCompiler Runtime Error: {}", ex.what()); } throw; } }
/* * acceptNewClient() * */ static void acceptNewClient ( void *pParam ) { struct ioc_log_server *pserver = (struct ioc_log_server *) pParam; struct iocLogClient *pclient; osiSocklen_t addrSize; struct sockaddr_in addr; int status; osiSockIoctl_t optval; pclient = ( struct iocLogClient * ) malloc ( sizeof ( *pclient ) ); if ( ! pclient ) { return; } addrSize = sizeof ( addr ); pclient->insock = epicsSocketAccept ( pserver->sock, (struct sockaddr *)&addr, &addrSize ); if ( pclient->insock==INVALID_SOCKET || addrSize < sizeof (addr) ) { static unsigned acceptErrCount; static int lastErrno; int thisErrno; free ( pclient ); if ( SOCKERRNO == SOCK_EWOULDBLOCK || SOCKERRNO == SOCK_EINTR ) { return; } thisErrno = SOCKERRNO; if ( acceptErrCount % 1000 || lastErrno != thisErrno ) { fprintf ( stderr, "Accept Error %d\n", SOCKERRNO ); } acceptErrCount++; lastErrno = thisErrno; return; } /* * Set non blocking IO * to prevent dead locks */ optval = TRUE; status = socket_ioctl( pclient->insock, FIONBIO, &optval); if(status<0){ char sockErrBuf[64]; epicsSocketConvertErrnoToString ( sockErrBuf, sizeof ( sockErrBuf ) ); fprintf(stderr, "%s:%d ioctl FBIO client er %s\n", __FILE__, __LINE__, sockErrBuf); epicsSocketDestroy ( pclient->insock ); free(pclient); return; } pclient->pserver = pserver; pclient->nChar = 0u; ipAddrToA (&addr, pclient->name, sizeof(pclient->name)); logTime(pclient); #if 0 status = fprintf( pclient->pserver->poutfile, "%s %s ----- Client Connect -----\n", pclient->name, pclient->ascii_time); if(status<0){ handleLogFileError(); } #endif /* * turn on KEEPALIVE so if the client crashes * this task will find out and exit */ { long true = 1; status = setsockopt( pclient->insock, SOL_SOCKET, SO_KEEPALIVE, (char *)&true, sizeof(true) ); if(status<0){ fprintf(stderr, "Keepalive option set failed\n"); } } status = shutdown(pclient->insock, SHUT_WR); if(status<0){ char sockErrBuf[64]; epicsSocketConvertErrnoToString ( sockErrBuf, sizeof ( sockErrBuf ) ); fprintf (stderr, "%s:%d shutdown err %s\n", __FILE__, __LINE__, sockErrBuf); epicsSocketDestroy ( pclient->insock ); free(pclient); return; } status = fdmgr_add_callback( pserver->pfdctx, pclient->insock, fdi_read, readFromClient, pclient); if (status<0) { epicsSocketDestroy ( pclient->insock ); free(pclient); fprintf(stderr, "%s:%d client fdmgr_add_callback() failed\n", __FILE__, __LINE__); return; } }
Scheme CompositeGenerator::generate(const TruthTable& table, ostream& outputLog) { float totalTime = 0; float time = 0; // process truth table with Reed-Muller generator uint size = table.size(); uint n = (uint)(log(size) / log(2)); outputLog << "n = " << n << endl; uint threshold = getRmGeneratorWeightThreshold(n); outputLog << "RM generator index weight threshold: " << threshold << endl; RmGenerator rmGenerator(threshold); RmGenerator::SynthesisResult rmResult; { AutoTimer timer(&time); rmGenerator.generate(table, &rmResult); } totalTime += time; outputLog << "RM generator time: "; logTime(outputLog, time); outputLog << "RM scheme complexity: " << rmResult.scheme.size() << endl; // process residual truth table with Group Theory based generator GtGenerator gtGenerator; Scheme gtLeftScheme; Scheme gtRightScheme; { AutoTimer timer(&time); gtLeftScheme = gtGenerator.generate(rmResult.leftMultTable); gtRightScheme = gtGenerator.generate(rmResult.rightMultTable); } totalTime += time; outputLog << "GT generator time: "; logTime(outputLog, time); outputLog << "GT left scheme complexity: " << gtLeftScheme.size() << endl; outputLog << "GT right scheme complexity: " << gtRightScheme.size() << endl; // combine GT and RM schemes Scheme& scheme = rmResult.scheme; RmGenerator::PushPolicy pushPolicy = rmGenerator.getPushPolicy(); if (pushPolicy.defaultPolicy) { if (gtLeftScheme.size() < gtRightScheme.size()) scheme.insert(scheme.begin(), gtLeftScheme.cbegin(), gtLeftScheme.cend()); else scheme.insert(scheme.end(), gtRightScheme.cbegin(), gtRightScheme.cend()); } else { scheme.insert(scheme.begin(), gtLeftScheme.cbegin(), gtLeftScheme.cend()); scheme.insert(scheme.end(), gtRightScheme.cbegin(), gtRightScheme.cend()); } outputLog << "Complexity before optimization: " << scheme.size() << endl; outputLog << "Quantum cost before optimization: "; outputLog << SchemeUtils::calculateQuantumCost(scheme) << endl; // optimize scheme complexity PostProcessor postProcessor; { AutoTimer timer(&time); scheme = postProcessor.optimize(scheme); } totalTime += time; bool isValid = TruthTableUtils::checkSchemeAgainstPermutationVector(scheme, table); assert(isValid, string("Generated scheme is not valid")); // log post processing parameters outputLog << "Optimization time: "; logTime(outputLog, time); outputLog << "Complexity after optimization: " << scheme.size() << endl; outputLog << "Quantum cost after optimization: "; outputLog << SchemeUtils::calculateQuantumCost(scheme) << endl; outputLog << "Total time: "; logTime(outputLog, totalTime); return scheme; }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int MXALoggerTest_EntryPoint() { int err = 0; uint8_t ui8 = 50; int8_t i8 = 51; uint16_t ui16 = 53; int16_t i16 = 54; uint32_t ui32 = 55; int32_t i32 = 56; uint64_t ui64 = 57; int64_t i64 = 58; float f = 59.59f; double d = 60.60; std::string str("String"); std::cout << logTime() << "Logging To File: " << MXAUnitTest::MXALoggerTest::TestFile << std::endl; { MXALOGGER_METHOD_VARIABLE_INSTANCE; std::stringstream ss; ss << "This is a test of the stringstream"; logger.open(MXAUnitTest::MXALoggerTest::TestFile); MXA_REQUIRE((logger.getIsFileBased()) == true); logger << logTime() << (ui8) << (i8) << (ui16) << (i16) << (ui32) << (i32) << (ui64) << (i64) << (f) << (d) << std::endl; logger << logTime() << (str) << std::endl; logger << logTime() << ss.str() << std::endl; logger.close(); MXA_REQUIRE(logger.getIsFileBased() == false); logger << logTime() << ss.str() << std::endl; logger << "+++++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl; logger.open(MXAUnitTest::MXALoggerTest::TestFile, std::ios::app); MXA_REQUIRE(logger.getIsFileBased() == true); logger << logTime() << (ss.str()) << std::endl; logger.close();; MXA_REQUIRE(logger.getIsFileBased() == false); } std::cout << logTime() << "Logging to std::cout" << std::endl; { MXALOGGER_METHOD_VARIABLE_INSTANCE; logger << logTime() << (ui8) << (i8) << (ui16) << (i16) << (ui32) << (i32) << (ui64) << (i64) << (f) << (d) << std::endl; logger << logTime() << (str) << std::endl; logger.close();; MXA_REQUIRE(logger.getIsFileBased() == false); logger.open(MXAUnitTest::MXALoggerTest::TestFile, std::ios::app); MXA_REQUIRE(logger.getIsFileBased() == true); std::stringstream ss; ss.str(); ss << "This is a test of the stringstream"; logger << logTime() << (ss.str()) << std::endl; logger.close();; MXA_REQUIRE(logger.getIsFileBased() == false); } return err; }
OsStatus EmailNotifier::handleAlarm(const OsTime alarmTime, const UtlString& callingHost, const cAlarmData* alarmData, const UtlString& alarmMsg) { OsStatus retval = OS_FAILED; //execute the mail command for each user UtlString groupKey(alarmData->getGroupName()); if (!groupKey.isNull()) { UtlContainable* pContact = mContacts.findValue(&groupKey); if (pContact) { // Process the comma separated list of contacts UtlString* contactList = dynamic_cast<UtlString*> (pContact); if (!contactList->isNull()) { MailMessage message(mEmailStrFrom, mReplyTo, mSmtpServer); UtlTokenizer tokenList(*contactList); UtlString entry; while (tokenList.next(entry, ",")) { message.To(entry, entry); } UtlString body; UtlString tempStr; body = mEmailStrIntro; body.append("\n"); assembleMsg(mEmailStrAlarm, alarmData->getCode(), tempStr); body.append(tempStr); body.append("\n"); assembleMsg(mEmailStrHost, callingHost, tempStr); body.append(tempStr); body.append("\n"); OsDateTime logTime(alarmTime); UtlString strTime; logTime.getIsoTimeStringZus(strTime); assembleMsg(mEmailStrTime, strTime, tempStr); body.append(tempStr); body.append("\n"); UtlString sevStr = OsSysLog::priorityName(alarmData->getSeverity()); assembleMsg(mEmailStrSeverity, sevStr, tempStr); body.append(tempStr); body.append("\n"); assembleMsg(mEmailStrDescription, alarmMsg, tempStr); body.append(tempStr); body.append("\n"); assembleMsg(mEmailStrResolution, alarmData->getResolution(), tempStr); body.append(tempStr); OsSysLog::add(FAC_ALARM, PRI_DEBUG, "AlarmServer: email body is %s", body.data()); message.Body(body); UtlSList subjectParams; UtlString codeStr(alarmData->getCode()); UtlString titleStr(alarmData->getShortTitle()); subjectParams.append(&codeStr); subjectParams.append(&titleStr); assembleMsg(mEmailStrSubject, subjectParams, tempStr); message.Subject(tempStr); // delegate send to separate task so as not to block EmailSendTask::getInstance()->sendMessage(message); } } } return retval; }
int main( int argc, char *argv[] ) { // Variables char c; // Character to write to our program int sock; // Our Socket int index; // Index to get data from frame struct sockaddr_in servAddr; // Server Address struct sockaddr_in cliAddr; // Client Address unsigned int cliLen = sizeof( cliAddr ); // Length of Client struct int nbytes; // Number of bytes read char ack[2]; // Acknowledgment packet SwpState server; // Window state FILE *log, *out; // File pointers to log and output file // Initalize Variables server.hdr.SeqNum = 0; server.hdr.Flags = 0; server.LFRead = 0; server.LFRcvd = -1; server.LAF = RWS; server.NFE = 0; ack[SEQNUM] = -1; ack[FLAGS] = 0; // Check command line args. if( argc < 6 ) { printf( "Usage: %s <server_port> <error rate> <random seed> <output_file> <recieve_log> \n", argv[0] ); exit( EXIT_FAILURE ); } // Note: you must initialize the network library first before calling sendto_(). // The arguments are the <errorrate> and <random seed> init_net_lib( atof( argv[2] ), atoi( argv[3] ) ); printf( "Error rate: %f\n", atof( argv[2] ) ); // Open log and output file out = fopen( argv[4], "w" ); ERROR( out == NULL ); log = fopen( argv[5], "w" ); ERROR( log == NULL ); // Socket creation sock = socket( AF_INET, SOCK_DGRAM, 0 ); ERROR( sock < 0 ); // Bind server port to "well-known" port whose value is known by the client bzero( &servAddr, sizeof( servAddr ) ); // Zero the struct servAddr.sin_family = AF_INET; // Address family servAddr.sin_port = htons( atoi( argv[1] ) ); // htons() sets the port # to network byte order servAddr.sin_addr.s_addr = INADDR_ANY; // Supplies the IP address of the local machine ERROR( bind( sock, (struct sockaddr *) &servAddr, sizeof( servAddr ) ) < 0 ); char buffer[PACKETSIZE]; bzero( &buffer, PACKETSIZE ); do { // Receive message from client nbytes = recvfrom( sock, &buffer, PACKETSIZE, 0, (struct sockaddr *) &cliAddr, &cliLen ); ERROR( nbytes < 0 ); // Make sure to cap string buffer[nbytes] = '\0'; server.hdr.SeqNum = buffer[SEQNUM]; // Check to see if packet is what we need if ( ( buffer[SEQNUM] >= server.LAF - RWS ) && ( buffer[SEQNUM] < server.LAF ) ) { // Set Last Frame Recieved to this buffer number server.LFRcvd = buffer[SEQNUM]; memcpy( server.recvQ[ server.LFRcvd % RWS ].msg, buffer, PACKETSIZE); // Update log logTime( log, "RECEIVE", &server ); } // Check to see if the one we recieved is the next frame if ( server.LFRcvd == server.NFE ) { // Copy and write recieved data index = 2; do { c = server.recvQ[server.NFE % RWS].msg[index]; if ( c == '\0' ) break; fputc( c, out ); index++; } while ( index < PACKETSIZE - 1 ); server.LFRead = server.NFE; // Set Ack Header Data ack[SEQNUM] = server.LFRcvd; ack[FLAGS] = 0; } // Respond using sendto_ in order to simulate dropped packets nbytes = sendto_( sock, ack, PACKETSIZE, 0, (struct sockaddr *) &cliAddr, sizeof( cliAddr ) ); ERROR( nbytes < 0 ); // Check to see if the one we recieved is the next frame if ( server.LFRcvd == server.NFE ) { // Update log logTime( log, "SEND", &server ); // Increment Next Frame Expected server.NFE++; // Increment Largest Acceptable Frame server.LAF++; } else { // Update log logTime( log, "RESEND", &server ); } } while ( buffer[FLAGS] != 1 ); // Close files fclose( log ); fclose( out ); return EXIT_SUCCESS; }
void AccessLog::customLog( HttpConnection* pConn ) { CustomFormat::iterator iter = m_pCustomFormat->begin(); HttpReq * pReq = pConn->getReq(); LogFormatItem *pItem; const char * pValue = NULL; char * pBuf; int n; while( iter != m_pCustomFormat->end() ) { pItem = *iter; switch( pItem->m_itemId ) { case REF_STRING: appendStrNoQuote( pItem->m_sExtra.c_str(), pItem->m_sExtra.len() ); break; case REF_STRFTIME: if ( pItem->m_sExtra.c_str() ) { logTime( &m_buf, pConn->getReqTime(), pItem->m_sExtra.c_str() ); } else { DateTime::getLogTime( pConn->getReqTime(), m_buf.end() ); m_buf.used( 28 ); } break; case REF_CONN_STATE: if ( pConn->isConnCanceled() ) { m_buf.append( 'X' ); } else if ( pConn->isClosing() ) { m_buf.append( '-' ); } else m_buf.append( '+' ); break; case REF_COOKIE_VAL: case REF_ENV: case REF_HTTP_HEADER: switch( pItem->m_itemId ) { case REF_COOKIE_VAL: pValue = RequestVars::getCookieValue( pReq, pItem->m_sExtra.c_str(), pItem->m_sExtra.len(), n ); break; case REF_ENV: pValue = RequestVars::getEnv(pConn, pItem->m_sExtra.c_str(), pItem->m_sExtra.len(), n ); break; case REF_HTTP_HEADER: pValue = pReq->getHeader( pItem->m_sExtra.c_str(), pItem->m_sExtra.len(), n ); break; } if ( pValue ) appendStrNoQuote( pValue, n ); else m_buf.append( '-' ); break; default: pBuf= m_buf.end(); n = RequestVars::getReqVar( pConn, pItem->m_itemId, pBuf, m_buf.available() ); if ( n ) { if ( pBuf != m_buf.end() ) appendStrNoQuote( pBuf, n ); else m_buf.used( n ); } else m_buf.append( '-' ); break; } ++iter; } m_buf.append( '\n' ); if (( m_buf.available() < MAX_LOG_LINE_LEN ) ||!asyncAccessLog() ) { flush(); } }
// Add a log entry given a variable argument list OsStatus OsSysLog::vadd(const char* taskName, const OsTaskId_t taskId, const OsSysLogFacility facility, const OsSysLogPriority priority, const char* format, va_list ap) { // If the log has not been initialized, print everything to the console if (!isTaskPtrNull()) { if (willLog(facility, priority)) { UtlString logData; UtlString logEntry; myvsprintf(logData, format, ap) ; logData = escape(logData) ; #ifdef ANDROID __android_log_print(androidPri(priority), "sipXsyslog", "[%s] %s", OsSysLog::sFacilityNames[facility], logData.data()); #endif OsTime timeNow; OsDateTime::getCurTime(timeNow); OsDateTime logTime(timeNow); UtlString strTime ; logTime.getIsoTimeStringZus(strTime) ; UtlString taskHex; // TODO: Should get abstracted into a OsTaskBase method #ifdef __pingtel_on_posix__ OsTaskLinux::getIdString_X(taskHex, taskId); #endif mysprintf(logEntry, "\"%s\":%d:%s:%s:%s:%s:%s:%s:\"%s\"", strTime.data(), ++sEventCount, OsSysLog::sFacilityNames[facility], OsSysLog::sPriorityNames[priority], sHostname.data(), (taskName == NULL) ? "" : taskName, taskHex.data(), sProcessId.data(), logData.data()) ; // If the logger for some reason trys to log a message // there is a recursive problem. Drop the message on the // floor for now. This can occur if one of the os utilities // logs a message. if(strcmp("syslog", taskName) == 0) { // Just discard the log entry // // (rschaaf): // NOTE: Don't try to use osPrintf() to emit the log entry since this // can cause consternation for applications (e.g. CGIs) that expect to // use stdout for further processing. } else { char* szPtr = strdup(logEntry.data()) ; OsSysLogMsg msg(OsSysLogMsg::LOG, szPtr) ; OsTime timeout(1000) ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if ( pOsSysLogTask != NULL && pOsSysLogTask->postMessage(msg, timeout) != OS_SUCCESS) { printf("OsSysLog jammed: %s\n", szPtr) ; free(szPtr) ; OsTask::yield() ; } } } } return OS_SUCCESS ; }
void Logger::Log(const char *log) { logTime(); logfile << log << std::endl; logfile.flush(); }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int main(int argc, char **argv) { std::cout << "Starting Ph to HDF5 Merging..." << std::endl; try { // Handle program options passed on command line. TCLAP::CmdLine cmd("PhToHDF5", ' ', DREAM3DLib::Version::Complete()); TCLAP::ValueArg<std::string> phFileArg( "p", "phfile", "Ph Input File", true, "", "Ph Input File"); cmd.add(phFileArg); TCLAP::ValueArg<std::string> angleFileArg( "e", "eulerfile", "Euler Angle File", false, "", "Euler Angle File"); cmd.add(angleFileArg); TCLAP::ValueArg<std::string> h5InputFileArg( "t", "h5file", "Target HDF5 File", true, "", "Target HDF5 File"); cmd.add(h5InputFileArg); // Parse the argv array. cmd.parse(argc, argv); if (argc == 1) { std::cout << "PhToHDF5 program was not provided any arguments. Use the --help argument to show the help listing." << std::endl; return EXIT_FAILURE; } std::string phFile = phFileArg.getValue(); std::string h5File = h5InputFileArg.getValue(); std::vector<int> voxels; int nx = 0; int ny = 0; int nz = 0; std::cout << "Merging the GrainID data from " << phFile << std::endl; std::cout << " into" << std::endl; std::cout << "file: " << h5File << std::endl; std::cout << "Reading the Ph data file...." << std::endl; int err = ReadPHFile(phFile, voxels, nx, ny, nz); if (err < 0) { return EXIT_FAILURE; } std::cout << "Ph File has dimensions: " << nx << " x " << ny << " x " << nz << std::endl; std::cout << "Now Overwriting the GrainID data set in the HDF5 file...." << std::endl; err = writePhDataToHDF5File(h5File, voxels, nz, ny, nz); if (err < 0) { std::cout << "There was an error writing the grain id data. Check other errors for possible clues." << std::endl; return EXIT_FAILURE; } std::cout << "+ Done Writing the Grain ID Data." << std::endl; std::map<int, EulerSet> gidToEulerMap; if (angleFileArg.getValue().empty() == false) { std::cout << "Reading the Euler Angle Data...." << std::endl; err = ReadEulerFile(angleFileArg.getValue(), gidToEulerMap); if (err < 0) { std::cout << "Error Reading the Euler Angle File" << std::endl; return EXIT_FAILURE; } // Over Write the Euler Angles if the Euler File was supplied std::cout << "Now Over Writing the Euler Angles data in the HDF5 file....." << std::endl; int totalPoints = nx * ny * nz; int numComp = 3; // Loop over each Voxel getting its Grain ID and then setting the Euler Angle std::vector<float> dataf(totalPoints * 3); for (int i = 0; i < totalPoints; ++i) { EulerSet& angle = gidToEulerMap[voxels[i]]; dataf[i * 3] = angle.e0; dataf[i * 3 + 1] = angle.e1; dataf[i * 3 + 2] = angle.e2; } // This is going to be a 2 Dimension Table Data set. int32_t rank = 2; hsize_t dims[2] = {totalPoints, numComp}; err = writeEulerDataToHDF5File(h5File, dataf, numComp, rank, dims); if (err < 0) { std::cout << "There was an error writing the Euler Angle data. Check other errors for possible clues." << std::endl; return EXIT_FAILURE; } std::cout << "+ Done Writing the Euler Angle Data." << std::endl; } } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << logTime() << " error: " << e.error() << " for arg " << e.argId() << std::endl; return EXIT_FAILURE; } std::cout << "Successfully completed the merge." << std::endl; return EXIT_SUCCESS; }
/* parseIncoming() will parse all incoming headers. It is important to note that * at this point all headers are discarded and only the request line is * reviewed. */ void parseIncoming(int sock, struct http_request *req) { struct tm iftime; char c; char line[BUF_SIZE]; char *method_tok, *path_tok, *http_ver_tok; int i=0, line_no=0; /* default status, if there is a problem it will be changed */ req->status=MSG_OK; for (;;) { bzero(line,sizeof(line)); i=0; /* get the request, character by character */ while ( recv(sock,&c,1,0)>0 ) { line[i] = c; /* Check for a consecutive CRLF, signifying end of the header */ if ( (i==1) && (line_no>0) ) { if ( (line[i-1]=='\r') && (line[i]=='\n') ) { return; } } /* Check for end of line */ if ( (i>0) && (line[i-1]=='\r') && (line[i]=='\n') ) { break; } i++; /* don't let the request exceed the buffer size */ if (i>BUF_SIZE) { req->status = MSG_BAD_REQ; break; } } /* This section will parse the request line */ if (line_no==0) { /* remove CRLF */ line[strlen(line)-1]='\0'; line[strlen(line)-1]='\0'; logTime(req); logRequest(req,line); /* Find out the method */ method_tok=strtok(line," "); if (method_tok==NULL) { req->status = MSG_BAD_REQ; break; } else if (strcmp(method_tok,"GET")==0) { req->method=MTHD_GET; } else if (strcmp(method_tok,"HEAD")==0) { req->method=MTHD_HEAD; } else if (strcmp(method_tok,"POST")==0) { req->method=MTHD_POST; } else { req->method=-1; } /* Find out the path of the requested file */ path_tok=strtok(NULL," "); strcpy(req->path,path_tok); /* Find out if the request is full or simple */ http_ver_tok=strtok(NULL," "); if ( http_ver_tok==NULL ) { req->flag_simple=1; } else if ( (strcmp(http_ver_tok,"HTTP/1.0")==0) || (strcmp(http_ver_tok,"HTTP/1.1")==0) ) { /* default, so do nothing */ } else { req->status = MSG_BAD_REQ; } /* There should be nothing else on this line */ if ( strtok(NULL," ") != NULL ) { req->status = MSG_BAD_REQ; } } /*end of request line parsing*/ if (line_no>0) { if (strncmp( "If-Modified-Since", line, strlen("If-Modified-Since")) ==0 ) { memset(&iftime, 0, sizeof(struct tm)); if ( (strptime( line+strlen("If-Modified-Since: XXX, "), "%d %b %Y %H:%M:%S %z", &iftime))==NULL ) { warn("unable to parse time from request header"); } else { req->flag_if_mod=1; req->if_time = mktime(&iftime); } } } line_no++; } }
OsStatus EmailNotifier::handleAlarm(const OsTime alarmTime, const UtlString& callingHost, const cAlarmData* alarmData, const UtlString& alarmMsg) { OsStatus retval = OS_FAILED; UtlString body; UtlString tempStr; body = mEmailStrIntro; body.append("\n"); assembleMsg(mEmailStrAlarm, alarmData->getCode(), tempStr); body.append(tempStr); body.append("\n"); assembleMsg(mEmailStrHost, callingHost, tempStr); body.append(tempStr); body.append("\n"); OsDateTime logTime(alarmTime); UtlString strTime; logTime.getIsoTimeStringZus(strTime); assembleMsg(mEmailStrTime, strTime, tempStr); body.append(tempStr); body.append("\n"); UtlString sevStr = OsSysLog::priorityName(alarmData->getSeverity()); assembleMsg(mEmailStrSeverity, sevStr, tempStr); body.append(tempStr); body.append("\n"); assembleMsg(mEmailStrDescription, alarmMsg, tempStr); body.append(tempStr); body.append("\n"); assembleMsg(mEmailStrResolution, alarmData->getResolution(), tempStr); body.append(tempStr); OsSysLog::add(FAC_ALARM, PRI_DEBUG, "AlarmServer: email body is %s", body.data()); MailMessage message( mEmailStrFrom, mReplyTo, mSmtpServer ); message.Body(body); UtlSList subjectParams; UtlString codeStr(alarmData->getCode()); UtlString titleStr(alarmData->getShortTitle()); subjectParams.append(&codeStr); subjectParams.append(&titleStr); assembleMsg(mEmailStrSubject, subjectParams, tempStr); message.Subject(tempStr); //execute the mail command for each user UtlSListIterator iterator(mContacts); UtlString* pObject; while ( (pObject = dynamic_cast<UtlString*>(iterator()))) { message.To(*pObject, *pObject); } // delegate send to separate task so as not to block EmailSendTask::getInstance()->sendMessage(message); return retval; }