예제 #1
0
파일: import.cpp 프로젝트: Fran89/seiscomp3
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Import::readSinkMessages()
{
	while ( !_exitRequested ) {
		int error;
		Communication::NetworkMessagePtr networkMsgPtr;
		networkMsgPtr = _sink->receive(true, &error);
		if ( error != Core::Status::SEISCOMP_SUCCESS ) {
			bool first = true;

			while ( !_exitRequested ) {
				if ( first )
					SEISCOMP_WARNING("Connection lost to sink, trying to reconnect");

				_sink->reconnect();
				if ( _sink->isConnected() ) {
					SEISCOMP_INFO("Reconnected successfully to sink");
					break;
				}
				else {
					if ( first ) {
						first = false;
						SEISCOMP_INFO("Reconnecting to sink failed, trying again every 2 seconds");
					}
					Core::sleep(2);
				}
			}
		}
	}

	SEISCOMP_INFO("Leaving sink message thread");
}
예제 #2
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool DbPlugin::connectToDb() {
	int counter = 0;
	while ( operational() && !_db->connect(_dbWriteConnection.c_str()) ) {
		if ( counter == 0 )
			SEISCOMP_ERROR("Database check... connection refused, retry");
		++counter;
		Core::sleep(1);

		if ( counter > 10 ) {
			SEISCOMP_ERROR("Database check... connection not available, abort");
			return false;
		}
	}

	if ( !operational() ) return true;

	SEISCOMP_INFO("Database connection established");

	_dbArchive = new DataModel::DatabaseArchive(_db.get());

	if ( !_dbArchive ) {
		SEISCOMP_ERROR("DbPlugin: Could not create DBArchive");
		return false;
	}

	if ( _dbArchive->hasError() )
		return false;

	Core::Version localSchemaVersion = Core::Version(DataModel::Version::Major, DataModel::Version::Minor);
	if ( localSchemaVersion > _dbArchive->version() ) {
		SEISCOMP_WARNING("Database schema v%s is older than schema v%s "
		                 "currently supported. Information will be lost when "
		                 "saving objects to the database! This should be fixed!",
		                 _dbArchive->version().toString().c_str(),
		                 localSchemaVersion.toString().c_str());
		if ( _strictVersionMatch ) {
			SEISCOMP_ERROR("Strict version check is enabled and schema versions "
			               "do not match.");
			return false;
		}
		else
			SEISCOMP_INFO("Strict version check is disabled and different "
			              "schema versions are not treated as error");
	}
	else
		SEISCOMP_DEBUG("Database check... ok");

	return true;
}
예제 #3
0
파일: gfz.cpp 프로젝트: palminn/seiscomp3
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool GFZPicker::calculatePick(int ndata, const double *data,
                              int signalStartIndex, int signalEndIndex,
                              int &onsetIndex, int &lowerUncertainty,
                              int &upperUncertainty, double &snr)
// Initially, onsetIndex contains the index of the triggering sample.
{
	const int     n = signalEndIndex - signalStartIndex;
	const double *f = data+signalStartIndex;

	if (n<=10) {
		SEISCOMP_INFO("GFZPicker::calculatePick: not enough data");
		return false;
	}

	// Here we assume that the first third of the seismogram contains only noise.
	// FIXME: somewhat hackish
	int nnoise = n/3;

	// determine offset
	double offset = 0;
	for (int i=0; i<nnoise; i++)
		offset += f[i];
	offset /= nnoise;

	vector<double> tmp(n);
	for (int i=0; i<n; i++)
		tmp[i] = f[i]-offset;

	double fc = 1; // center frequency
	double bw = 2; // bandwidth
	double f1 = fc/sqrt(bw), f2 = fc*sqrt(bw);
//	Math::Filtering::IIR::ButterworthBandpass<double> filter(3, f1, f2, _fsamp);
	Filter *filter = new Math::Filtering::IIR::ButterworthBandpass<double>(3, f1, f2, _stream.fsamp);
//	filter.apply(tmp);
//	filter->apply(tmp);
	delete filter;

	int onset = onsetIndex-signalStartIndex;
	maeda_aic_const(n, &tmp[0], onset, snr);
	if (onset==-1) {
		SEISCOMP_INFO("GFZPicker::calculatePick: no onset found: n=%d fs=%g %g %g %g    %d -> -1", n, _stream.fsamp, _config.signalBegin, _config.signalEnd, offset, onsetIndex-signalStartIndex);
		return false;
	}

	SEISCOMP_INFO("GFZPicker::calculatePick n=%d fs=%g %g %g %g    %d -> %d", n, _stream.fsamp, _config.signalBegin, _config.signalEnd, offset, onsetIndex-signalStartIndex, onset);

	onsetIndex = onset + signalStartIndex;
	return true;
}
예제 #4
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Envelope::done() {
	Core::Time now = Core::Time::GMT();
	int secs = (now-_appStartTime).seconds();
	SEISCOMP_INFO("Sent %ld messages with an average of %d messages per second",
	              (long int)_sentMessagesTotal, (int)(secs > 0?_sentMessagesTotal/secs:_sentMessagesTotal));
	Application::done();
}
예제 #5
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int PluginRegistry::loadPlugins() {
	for ( NameList::const_iterator it = _pluginNames.begin();
	      it != _pluginNames.end(); ++it ) {
		if ( it->empty() ) continue;
		std::string filename = find(*it);
		if ( filename.empty() ) {
			SEISCOMP_ERROR("Did not find plugin %s", it->c_str());
			return -1;
		}

		SEISCOMP_DEBUG("Trying to open plugin at %s", filename.c_str());
		PluginEntry e = open(filename);
		if ( e.plugin == NULL ) {
			if ( e.handle == NULL ) {
				SEISCOMP_ERROR("Unable to load plugin %s", it->c_str());
				return -1;
			}
			else
				SEISCOMP_WARNING("The plugin %s has been loaded already",
				                 it->c_str());
			continue;
		}

		SEISCOMP_INFO("Plugin %s registered", it->c_str());
		_plugins.push_back(e);
	}

	return _plugins.size();
}
예제 #6
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Application::enableStream(const std::string& code, bool enabled) {
	std::pair<StationProcessors::iterator, StationProcessors::iterator> itq = _processors.equal_range(code);
	for (StationProcessors::iterator it = itq.first; it != itq.second; ++it) {
		SEISCOMP_INFO("%s stream %s", enabled?"Enabling":"Disabling", code.c_str());
		it->second->setEnabled(enabled);
	}
}
예제 #7
0
파일: import.cpp 프로젝트: Fran89/seiscomp3
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Import::buildRelayRoutingtable(bool routeUnknownGroup)
{
	SEISCOMP_INFO("Calculating default routing table ...");
	std::vector<std::string> sourceGroups;
	if ( _useSpecifiedGroups ) {
		try {
			sourceGroups = configGetStrings("msggroups");
		}
		catch ( Config::Exception& ) {
			exit(0);
		}
	}
	else
	{
		Communication::Connection* con = connection();
		if (con)
			sourceGroups = connection()->groups();
	}

	std::vector<std::string> sinkGroups = _sink->groups();

	for( std::vector<std::string>::iterator it = sourceGroups.begin();
	        it != sourceGroups.end(); ++it )
	{
		std::vector<std::string>::iterator found =
		    std::find(sinkGroups.begin(), sinkGroups.end(), *it);
		if ( found != sinkGroups.end() )
			_routingTable[*it] = *found;
		else if( routeUnknownGroup )
			_routingTable[*it] = Communication::Protocol::IMPORT_GROUP;
	}
}
예제 #8
0
void QLClient::processResponse(IO::QuakeLink::Response *response) {
	SEISCOMP_INFO("%sreceived message, size: %lu)", _logPrefix.c_str(),
	              (unsigned long)response->length);
	SCCoreApp->sendNotification(Client::Notification(
	                            _notificationID, response));
	++_stats.messages;
	_stats.payloadBytes += response->length;
}
예제 #9
0
QLClient::~QLClient() {
	if ( _thread != NULL ) {
		delete _thread;
		_thread = NULL;
	}

	SEISCOMP_INFO("%sterminated, messages/bytes received: %lu/%lu",
	              _logPrefix.c_str(), (unsigned long)_stats.messages,
	              (unsigned long)_stats.payloadBytes);
}
예제 #10
0
void QLClient::listen() {
	IO::QuakeLink::RequestFormat rf = _config->gzip ?
	                                 (_config->native ? IO::QuakeLink::rfGZNative : IO::QuakeLink::rfGZXML) :
	                                 (_config->native ? IO::QuakeLink::rfNative : IO::QuakeLink::rfXML);
	// activate socket timeout if keepAlive was requested
	if ( _config->options & IO::QuakeLink::opKeepAlive ) {
		if ( _sock ) {
			_sock->setTimeout(60);
		}
		else {
			SEISCOMP_ERROR("%sinstance not initialized", _logPrefix.c_str());
			return;
		}
	}

	while ( !interrupted() ) {
		// determine start time of request
		Core::Time from;
		string filter = _config->filter;
		if ( _backLog > 0 ) {
			Core::Time minTime = Core::Time::GMT() - Core::TimeSpan(_backLog);
			from = lastUpdate();
			if ( !from.valid() || from < minTime )
				from = minTime;
			if ( !filter.empty() )
				filter += " AND ";
			filter += "UPDATED > " + from.toString(IO::QuakeLink::RequestTimeFormat);
		}

		// start request
		try {
			select(from.valid(), Core::Time(), Core::Time(), rf, filter);
		}
		catch ( Core::GeneralException& e) {
			if ( interrupted() )
				break;
			SEISCOMP_DEBUG("%sselect exception: %s", _logPrefix.c_str(), e.what());
		}

		_sock->close(); // clears interrupt flag
		SEISCOMP_WARNING("%sQuakeLink connection closed, trying to reconnect "
		                 "in 5s", _logPrefix.c_str());

		for ( int i = 0; i < 50; ++i ) {
			usleep(100000); // 100ms

			if ( interrupted() )
				break;
		}
	}

	if ( interrupted() )
		SEISCOMP_INFO("%sQuakeLink connection interrupted", _logPrefix.c_str());
	_sock->close();
}
예제 #11
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void MySQLDatabase::disconnect() {
	if ( _handle ) {
		SEISCOMP_INFO("Disconnecting from database");
		if ( _result ) {
			mysql_free_result(_result);
			_result = NULL;
		}
		mysql_close(_handle);
		_handle = NULL;
	}
}
예제 #12
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool MySQLDatabase::reconnect() {
	while ( _handle && !ping() ) {
		if ( _result ) {
			mysql_free_result(_result);
			_result = NULL;
		}
		_row = NULL;
		Seiscomp::Core::msleep(500);
	}

	if ( _handle ) {
		SEISCOMP_INFO("Database connection reestablished");
		return true;
	}

	return false;
}
예제 #13
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool QcPlugin::init(QcApp* app, QcConfig *cfg, std::string streamID) {
	_app = app;
	_qcConfig = cfg;
	_streamID = streamID;
	_qcMessenger = _app->qcMessenger();
	_firstRecord = true; 
	_qcBuffer = new QcBuffer(_app->archiveMode() ? _qcConfig->archiveBuffer() : _qcConfig->buffer());

	if (! _app->archiveMode() && _qcConfig->reportTimeout() != 0) {
		_timer.restart();
		SEISCOMP_INFO("using report timeout %d s for %s", _qcConfig->reportTimeout(), _name.c_str());
		_app->addTimeout(boost::bind(&QcPlugin::onTimeout, this));
	}

	_app->doneSignal.connect(boost::bind(&QcPlugin::done, this));

	return true;
}
예제 #14
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void ObjectCache::updateObjects(Seiscomp::DataModel::DatabaseQuery* query) {

	if ( !query ) {
		SEISCOMP_ERROR("Provided query instance is broken, no cache update performed");
		return;
	}

	// Make a deep copy of the tuple, free the original, store a fresh version
	// of the newly fetched objects...
	Tuple copy = _cache;

	clear();

	Util::StopWatch sw;
	for (size_t i = 0; i < copy.size(); ++i) {
		PO obj = query->getObject(copy[i].second->typeInfo(), copy[i].second->publicID());
		if ( obj )
			addObject(copy[i].first, obj);
	}
	SEISCOMP_INFO("All objects from the cache have been updated: %s",
	    Seiscomp::Core::Time(sw.elapsed()).toString("%T.%f").c_str());
}
예제 #15
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Processor::process(const Record *rec, const DoubleArray &data) {
	// First record after reset?
	if ( !_stream.initialized ) {
		// Try to setup all internal variables
		if ( !init(rec) ) return;
	}
	// Mismatching sampling frequency: reset
	else if ( rec->samplingFrequency() != _stream.fsamp ) {
		SEISCOMP_INFO("%s: mismatching sampling frequency (%f != %f): reset",
		              rec->streamID().c_str(), _stream.fsamp,
		              rec->samplingFrequency());
		reset();
		// Try to setup all internal variables
		if ( !init(rec) ) return;
	}

	// Record time window is after the current time window -> flush
	// existing samples and setup the new interval
	if ( rec->startTime() >= _currentEndTime ) {
		flush();
		setupTimeWindow(rec->startTime());
	}

	Core::Time ts = rec->startTime();
	// Process all samples
	for ( int i = 0; i < data.size(); ++i ) {
		if ( ts >= _currentEndTime ) {
			// Flush existing pool
			flush();
			// Step to next time span
			_currentStartTime = _currentEndTime;
			_currentEndTime = _currentStartTime + Core::TimeSpan(1,0);
		}
		_samplePool.push(data[i]);
		ts += _dt;
	}
}
예제 #16
0
bool Importer::traverse(NodeHandler *handler, void *n, void *c, Core::BaseObject *target) {
	xmlNodePtr node = reinterpret_cast<xmlNodePtr>(n);
	xmlNodePtr childs = reinterpret_cast<xmlNodePtr>(c);
	ChildList remaining;
	TagSet mandatory;

	handler->init(target, n, mandatory);

	bool result = true;

	for ( xmlNodePtr child = childs; child != NULL; child = child->next ) {
		if ( child->type != XML_ELEMENT_NODE ) continue;

		handler->propagate(NULL, false, true);

		try {
			handler->get(target, child);
		}
		catch ( std::exception &e ) {
			if ( handler->isOptional )
				SEISCOMP_WARNING("(optional) %s.%s: %s", node->name, child->name, e.what());
			else
				throw e;
		}

		if ( !handler->isOptional )
			mandatory.erase((const char*)child->name);

		if ( handler->object == NULL && handler->isAnyType ) {
			if ( _any.get(target, child) ) {
				handler->object = _any.object;
				handler->childHandler = _any.childHandler;
				handler->newInstance = _any.newInstance;
			}
		}

		Core::BaseObject *newTarget = handler->object;
		MemberNodeHandler *memberHandler = handler->memberHandler;
		NodeHandler *childHandler = handler->childHandler;
		bool newInstance = handler->newInstance;
		bool optional = handler->isOptional;

		if ( newTarget ) {
			if ( childHandler == NULL ) {
				childHandler = _typemap->getHandler(newTarget->className());
				if ( childHandler == NULL ) {
					SEISCOMP_WARNING("No class handler for %s", newTarget->className());
					if ( newInstance )
						delete newTarget;
					handler->object = NULL;
					newTarget = NULL;
					childHandler = &_none;
				}
			}
		}
		else
			childHandler = &_none;

		try {
			if ( traverse(childHandler, child, child->children, handler->object) ) {
				if ( newTarget && newInstance && !memberHandler )
					remaining.push_back(newTarget);

			}
			else {
				if ( newTarget && newInstance )
					delete newTarget;
				newTarget = NULL;
				if ( optional )
					SEISCOMP_INFO("Invalid %s element: ignoring", child->name);
				else {
					SEISCOMP_WARNING("%s is not optional within %s", child->name, node->name);
					result = false;
				}
			}
		}
		catch ( std::exception &e ) {
			SEISCOMP_WARNING("%s: %s", child->name, e.what());
			if ( newTarget ) {
				if ( newInstance )
					delete newTarget;

				if ( !optional ) {
					SEISCOMP_WARNING("%s is not optional within %s", child->name, node->name);
					result = false;
				}
				else
					SEISCOMP_WARNING("%s: ignoring optional member %s: invalid", node->name, child->name);

				newTarget = NULL;
			}
		}

		if ( memberHandler ) {
			if ( !memberHandler->finalize(target, newTarget) ) {
				if ( newTarget && newInstance )
					remaining.push_back(newTarget);
			}
		}
	}

	handler->finalize(target, &remaining);

	if ( target != NULL ) {
		for ( ChildList::iterator it = remaining.begin(); it != remaining.end(); ++it )
			if ( *it != NULL ) delete *it;
	}
	else {
		for ( ChildList::iterator it = remaining.begin(); it != remaining.end(); ++it ) {
			if ( *it != NULL ) {
				if ( _result == NULL )
					_result = *it;
				else
					delete *it;
			}
		}
	}

	if ( !mandatory.empty() ) {
		std::string attribs;
		for ( TagSet::iterator it = mandatory.begin(); it != mandatory.end(); ++it ) {
			if ( it != mandatory.begin() ) attribs += ", ";
			attribs += *it;
		}
		SEISCOMP_WARNING("%s: missing mandatory attribute%s: %s", node->name, mandatory.size() == 1?"":"s", attribs.c_str());
		return false;
	}

	return result;
}
예제 #17
0
void Autoloc3::Config::dump() const
{
	SEISCOMP_INFO("Configuration:");
	SEISCOMP_INFO("defaultDepth                     %g",     defaultDepth);
	SEISCOMP_INFO("defaultDepthStickiness           %g",     defaultDepthStickiness);
	SEISCOMP_INFO("tryDefaultDepth                  %s",     tryDefaultDepth ? "true":"false");
	SEISCOMP_INFO("adoptManualDepth                 %s",     adoptManualDepth ? "true":"false");
	SEISCOMP_INFO("minimumDepth                     %g",     minimumDepth);
	SEISCOMP_INFO("minPhaseCount                    %d",     minPhaseCount);
	SEISCOMP_INFO("minScore                         %.1f",   minScore);
	SEISCOMP_INFO("minPickSNR                       %.1f",   minPickSNR);
	SEISCOMP_INFO("maxResidual                      %.1f s", maxResidualUse);
	SEISCOMP_INFO("goodRMS                          %.1f s", goodRMS);
	SEISCOMP_INFO("maxRMS                           %.1f s", maxRMS);
	SEISCOMP_INFO("maxDepth                         %.1f km", maxDepth);
	SEISCOMP_INFO("minStaCountIgnorePKP             %d",     minStaCountIgnorePKP);
	SEISCOMP_INFO("maxAge                           %.0f s", maxAge);
	SEISCOMP_INFO("publicationIntervalTimeSlope     %.2f",   publicationIntervalTimeSlope);
	SEISCOMP_INFO("publicationIntervalTimeIntercept %.1f",   publicationIntervalTimeIntercept);
	SEISCOMP_INFO("publicationIntervalPickCount     %d",     publicationIntervalPickCount);
	SEISCOMP_INFO("reportAllPhases                  %s",     reportAllPhases ? "true":"false");
	SEISCOMP_INFO("pickLogFile                      %s",     pickLogFile.size() ? pickLogFile.c_str() : "(none)");
	SEISCOMP_INFO("dynamicPickThresholdInterval     %g",     dynamicPickThresholdInterval);
	SEISCOMP_INFO("offline                          %s",     offline ? "true":"false");
	SEISCOMP_INFO("test                             %s",     test ? "true":"false");
	SEISCOMP_INFO("playback                         %s",     playback ? "true":"false");
	SEISCOMP_INFO("useManualPicks                   %s",     useManualPicks ? "true":"false");
	SEISCOMP_INFO("useManualOrigins                 %s",     useManualOrigins ? "true":"false");
// This isn't used still so we don't want to confuse the user....
//	SEISCOMP_INFO("useImportedOrigins               %s",     useImportedOrigins ? "true":"false");
	SEISCOMP_INFO("locatorProfile                   %s",     locatorProfile.c_str());

	if ( ! xxlEnabled) {
		SEISCOMP_INFO("XXL feature is not enabled");
		return;
	}
	SEISCOMP_INFO("XXL feature is enabled");
	SEISCOMP_INFO("xxl.minPhaseCount                 %d",     xxlMinPhaseCount);
	SEISCOMP_INFO("xxl.minAmplitude                  %g",     xxlMinAmplitude);
	SEISCOMP_INFO("xxl.maxStationDistance           %.1f deg", xxlMaxStaDist);
	SEISCOMP_INFO("xxl.maxDepth                      %g km",  xxlMaxDepth);
	SEISCOMP_INFO("xxl.deadTime                      %g s",  xxlDeadTime);
//	SEISCOMP_INFO("maxRadiusFactor                  %g", 	 maxRadiusFactor);
}
예제 #18
0
void QLClient::run() {
	SEISCOMP_INFO("%sconnecting to URL '%s'", _logPrefix.c_str(),
	              _config->url.c_str());
	_thread = new boost::thread(boost::bind(&QLClient::listen, this));
}
예제 #19
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Environment::init()
{
	const char* installDir = getenv("SEISCOMP_ROOT");
	if (installDir == NULL)
	{
#ifdef SEISCOMP_ROOT
		_installDir = SEISCOMP_ROOT;
		SEISCOMP_DEBUG("Setting predefined installdir: %s", _installDir.c_str());
#else
		_installDir = ".";
		SEISCOMP_DEBUG("Guessing installdir: %s", _installDir.c_str());
#endif
	}
	else
	{
		_installDir = installDir;
		SEISCOMP_DEBUG("Setting installdir from $SEISCOMP_ROOT: %s", _installDir.c_str());
	}


#ifdef SEISCOMP_SHARE_DIR
	_shareDir = _installDir + "/"SEISCOMP_SHARE_DIR;
#else
	_shareDir = _installDir + "/share";
#endif

#ifndef WIN32
	const char *homeDir = getenv("HOME");
	if (!homeDir)
	{
		SEISCOMP_WARNING("Could not read home directory!");
		_homeDir = ".";
	}
#else
	char homeDir[MAX_PATH];
	if ( SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, homeDir) != S_OK ) {
		SEISCOMP_WARNING("Could not get local application data path!");
		_homeDir = ".";
	}
#endif
	else
		_homeDir.assign(homeDir);


#ifdef SEISCOMP_CONFIG_DIR
	_globalConfigDir  = _installDir + "/"SEISCOMP_CONFIG_DIR;
#else
	_globalConfigDir  = _installDir + "/etc/defaults";
#endif

	_appConfigDir = _installDir + "/etc";

	const char* localConfigDir = getenv("SEISCOMP_LOCAL_CONFIG");
	if( localConfigDir == NULL ) {
#ifndef WIN32
		_localConfigDir  = _homeDir + "/.seiscomp3";
#else
		_localConfigDir  = _homeDir + "/seiscomp3";
#endif
	} else {
		_localConfigDir  = localConfigDir;
	}
	SEISCOMP_INFO("using local config dir: %s", _localConfigDir.c_str() );

	_logDir           = _localConfigDir + "/log";
	_archiveFileName  = "_archive.log";

	if (!createDir(_localConfigDir))
		SEISCOMP_WARNING( "Could not create directory: %s", _localConfigDir.c_str() );

	if (!createDir(_logDir))
		SEISCOMP_ERROR("Could not create directory: %s", _logDir.c_str());

	return true;
}
예제 #20
0
파일: import.cpp 프로젝트: Fran89/seiscomp3
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Import::buildImportRoutingtable()
{
	// Build routing table
	SEISCOMP_INFO("Calculating routing table ...");
	try	{
		std::vector<std::string> tmpRoutingTable = configGetStrings("routingtable");

		for ( std::vector<std::string>::iterator it = tmpRoutingTable.begin();
		        it != tmpRoutingTable.end(); ++it )
		{
			std::vector<std::string> tokens;
			Core::split(tokens, it->c_str(), ":");
			if ( tokens.size() != 2 )
				SEISCOMP_INFO("Malformed routing table entry: %s", it->c_str());
			else
				_routingTable[tokens[0]] = tokens[1];
		}
	}
	catch ( Config::Exception& e ) {
		SEISCOMP_ERROR("%s", e.what());
		return false;
	}

	std::vector<std::string> sourceGroups;
	if ( _useSpecifiedGroups ) {
		try {
			sourceGroups = configGetStrings("msggroups");
		}
		catch ( Config::Exception& ) {
			exit(0);
		}
	}
	else
	{
		Communication::Connection *con = connection();
		if (con)
			sourceGroups = con->groups();
	}

	std::map<std::string, std::string>::iterator it, tmp;
	for ( it = _routingTable.begin(); it != _routingTable.end(); ) {
		if ( std::find(sourceGroups.begin(), sourceGroups.end(), it->first) == sourceGroups.end() ) {
			SEISCOMP_ERROR("Group %s is not a member of available source groups. Deleting routing entry", it->first.c_str());
			tmp = it;
			++it;
			_routingTable.erase(tmp);
		}
		else
			++it;
	}

	/*
	std::vector<std::string> sinkGroups = _sink->groups();
	for ( it = _routingTable.begin(); it != _routingTable.end(); ) {
		if ( std::find(sinkGroups.begin(), sinkGroups.end(), it->second) == sinkGroups.end() ) {
			SEISCOMP_ERROR("Group %s is not a member of available sink groups. Deleting routing entry", it->second.c_str());
			tmp = it;
			++it;
			_routingTable.erase(tmp);
		}
		else
			++it;
	}
	*/

	return true;
}
예제 #21
0
파일: import.cpp 프로젝트: Fran89/seiscomp3
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int Import::connectToSink(const std::string& sink) {
	std::string protocol = "spread";
	std::string server = sink;
	size_t pos = sink.find("://");

	if ( pos != std::string::npos ) {
		protocol = sink.substr(0,pos);
		server = sink.substr(pos+3);
	}

	Communication::NetworkInterfacePtr ni = Communication::NetworkInterface::Create(protocol.c_str());
	if (ni == NULL)
	{
		SEISCOMP_ERROR("Networkinterface \"%s\" not found", protocol.c_str());
		return Core::Status::SEISCOMP_FAILURE;
	}

	_sink = new Communication::SystemConnection(ni.get());

	// Connect to the sink master and use a default name
	int ret;
	bool first = true;
	while ( (ret = _sink->connect(server, "", Communication::Protocol::IMPORT_GROUP)) !=
			Core::Status::SEISCOMP_SUCCESS && !_exitRequested ) {
		if ( first ) {
			SEISCOMP_WARNING("Could not connect to the sink master %s : %s, trying again every 2s",
			                 sink.c_str(), Core::Status::StatusToStr(ret));
			first = false;
		}

		Core::sleep(2);
	}

	if (ret != Core::Status::SEISCOMP_SUCCESS)
		return ret;

	// Get rid of data messages and read commands that are may send.
	SEISCOMP_INFO("Successfully connected to sink master: %s", sink.c_str());

	// Build routing table
	if (_mode == RELAY) {
		buildRelayRoutingtable(_routeUnknownGroup);
	}
	else if (_mode == IMPORT) {
		if (!buildImportRoutingtable())
		{
			SEISCOMP_ERROR("Could not built routing table for IMPORT mode.\nThere are no routing entries in specified in the configuration file");
			return 0;
		}
	}
	else {
		SEISCOMP_ERROR("Unknown import mode: %i", _mode);
		return Core::Status::SEISCOMP_FAILURE;
	}

	_sinkMessageThread = new boost::thread(boost::bind(&Import::readSinkMessages, this));

	// Print routing table
	for (std::map<std::string,
		 std::string>::iterator it = _routingTable.begin();
		 it != _routingTable.end(); ++it)
		SEISCOMP_INFO("%s@%s -> %s@%s", it->first.c_str(), connection()->masterAddress().c_str(), it->second.c_str(), sink.c_str());

	// Subscribe to source message groups
	for (std::map<std::string, std::string>::iterator it = _routingTable.begin();
	        it != _routingTable.end(); ++it) {
		if (connection()->subscribe(it->first) != Core::Status::SEISCOMP_SUCCESS)
			SEISCOMP_INFO("Could subscribe to group: %s", it->first.c_str());
	}

	return Core::Status::SEISCOMP_SUCCESS;
}
예제 #22
0
Locator::~Locator()
{
	SEISCOMP_INFO("Locator instance called %d times", _count);
}
예제 #23
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Envelope::addProcessor(SensorLocation *loc, const WaveformStreamID &id,
                            const Core::Time &timestamp, const char *type,
                            const char *short_type) {
	DataModel::ThreeComponents tc;
	DataModel::WaveformStreamID tmp(id);
	try {
		DataModel::getThreeComponents(
			tc, loc, id.channelCode().c_str(), timestamp
		);
	}
	catch ( exception &e ) {
		SEISCOMP_ERROR("%s: cannot query three components: %s: "
		               "%s channels not used",
		               Private::toStreamID(tmp).c_str(),
		               e.what(), type);
	}

	for ( int i = 0; i < 3; ++i ) {
		if ( tc.comps[i] == NULL ) continue;
		tmp.setChannelCode(tc.comps[i]->code());
		if ( !_streamFirewall.isAllowed(Private::toStreamID(tmp)) ) continue;

		SEISCOMP_INFO("%s: +%s", Private::toStreamID(tmp).c_str(), short_type);
		recordStream()->addStream(tmp.networkCode(), tmp.stationCode(),
		                          tmp.locationCode(), tmp.channelCode());
		ProcessorPtr proc = new Processor(_config.baselineCorrectionBufferLength);
		switch ( i ) {
			case ThreeComponents::Vertical:
				proc->setUsedComponent(Processing::WaveformProcessor::Vertical);
				proc->setName("Z");
				break;
			case ThreeComponents::FirstHorizontal:
				proc->setUsedComponent(Processing::WaveformProcessor::FirstHorizontal);
				proc->setName("H1");
				break;
			case ThreeComponents::SecondHorizontal:
				proc->setUsedComponent(Processing::WaveformProcessor::SecondHorizontal);
				proc->setName("H2");
				break;
		}

		Processing::StreamPtr stream = new Processing::Stream;
		stream->init(tmp.networkCode(), tmp.stationCode(),
		             tmp.locationCode(), tmp.channelCode(),
		             timestamp);

		proc->streamConfig((Processing::WaveformProcessor::Component)proc->usedComponent()) = *stream;
		proc->setWaveformID(tmp);
		proc->setSaturationThreshold(_config.saturationThreshold);
		proc->useVSFilterImplementation(!_config.useSC3Filter);

		if ( proc->streamConfig((Processing::WaveformProcessor::Component)proc->usedComponent()).gain == 0.0 ) {
			SEISCOMP_WARNING("%s: -%s: gain not defined (= 0.0)",
			                 short_type, Private::toStreamID(tmp).c_str());
			continue;
		}

		proc->setPublishFunction(boost::bind(&Envelope::emitResult, this, _1, _2, _3, _4, _5, _6));
		_processors[Private::toStreamID(tmp)] = proc;
	}
}