Example #1
0
			virtual hexabus::Packet::Ptr handle_query() const {
				if ( !is_readable() )
					return Packet::Ptr(new ErrorPacket(HXB_ERR_UNKNOWNEID));

				boost::optional<TValue> value = _read();
				if ( !value ) {
					std::stringstream oss;
					oss << "Error reading endpoint " << name() << " (" << eid() << ")";
					throw hexabus::GenericException(oss.str());
				}
				return Packet::Ptr(new InfoPacket<TValue>(eid(), *value));
			}
Example #2
0
File: View.cpp Project: sajty/eris
void View::create(const RootEntity& gent)
{
    std::string eid(gent->getId());
    if (m_contents.count(eid))
    {
        // already known locally, just emit the signal
        EntityCreated.emit( m_contents[eid] );
        return;
    }
    
    bool alreadyAppeared = false;
    PendingSightMap::iterator pending = m_pending.find(eid);
    if (pending != m_pending.end())
    {
        // already being retrieved, but we have the data now
        alreadyAppeared = (pending->second == SACTION_QUEUED) || 
            (pending->second == SACTION_APPEAR);
        pending->second = SACTION_DISCARD; // when the SIGHT turns up
    }
    
    Entity* ent = createEntity(gent);
    m_contents[eid] = ent;
    ent->init(gent, true);
    
    if (gent->isDefaultLoc()) setTopLevelEntity(ent);

    InitialSightEntity.emit(ent);
    
    // depends on relative order that sight(create) and appear are received in
    if (alreadyAppeared)
    {
        ent->setVisible(true);
        EntityCreated.emit(ent);
    }
}
Example #3
0
void Network::setStringEdgeAttribute(vertex_id vid1, vertex_id vid2, const std::string& attribute_name, const std::string& val) {
	if (!containsVertex(vid1)) throw ElementNotFoundException("Vertex " + std::to_string(vid1));
	if (!containsVertex(vid2)) throw ElementNotFoundException("Vertex " + std::to_string(vid2));
	if (!containsEdge(vid1, vid2)) throw ElementNotFoundException("Edge (" + std::to_string(vid2) + ", " + std::to_string(vid2) + ")");
	if (edge_string_attribute.count(attribute_name)==0) throw ElementNotFoundException("Attribute " + attribute_name);
	edge_id eid(vid1, vid2, isDirected());
	edge_string_attribute.at(attribute_name)[eid] = val;
}
Example #4
0
std::string Network::getStringEdgeAttribute(vertex_id vid1, vertex_id vid2, const std::string& attribute_name) const {
	if (!containsVertex(vid1)) throw ElementNotFoundException("Vertex " + std::to_string(vid1));
	if (!containsVertex(vid2)) throw ElementNotFoundException("Vertex " + std::to_string(vid2));
	if (!containsEdge(vid1, vid2)) throw ElementNotFoundException("Edge (" + std::to_string(vid1) + ", " + std::to_string(vid2) + ")");
	if (edge_string_attribute.count(attribute_name)==0) throw ElementNotFoundException("Attribute " + attribute_name);
	edge_id eid(vid1, vid2, isDirected());
	if (edge_string_attribute.at(attribute_name).count(eid)==0)  throw ElementNotFoundException("No attribute value for attribute " + attribute_name + " on edge (" + std::to_string(vid1) + "," +  std::to_string(vid2) + ")");
	return edge_string_attribute.at(attribute_name).at(eid);
}
		std::istream& DeliveryPredictabilityMap::deserialize(std::istream& stream)
		{
			data::Number elements_read(0);
			data::Number map_size;
			stream >> map_size;

			while(elements_read < map_size)
			{
				/* read the EID */
				data::Number eid_len;
				stream >> eid_len;

				// create a buffer for the EID
				std::vector<char> eid_cstr(eid_len.get<size_t>());

				// read the EID string
				stream.read(&eid_cstr[0], eid_cstr.size());

				// convert the string into an EID object
				dtn::data::EID eid(std::string(eid_cstr.begin(), eid_cstr.end()));

				if(eid == data::EID())
					throw dtn::InvalidDataException("EID could not be casted, while parsing a dp_map.");

				/* read the probability (float) */
				float f;
				dtn::data::Number float_len;
				stream >> float_len;

				// create a buffer for the data string
				std::vector<char> f_cstr(float_len.get<size_t>());

				// read the data string
				stream.read(&f_cstr[0], f_cstr.size());

				// convert string data into a stringstream
				std::stringstream ss(std::string(f_cstr.begin(), f_cstr.end()));

				// convert string data into a float
				ss >> f;
				if(ss.fail())
					throw dtn::InvalidDataException("Float could not be casted, while parsing a dp_map.");

				/* check if f is in a proper range */
				if(f < 0 || f > 1)
					continue;

				/* insert the data into the map */
				_predictmap[eid] = f;

				elements_read += 1;
			}

			IBRCOMMON_LOGGER_DEBUG_TAG("DeliveryPredictabilityMap", 20) << "Deserialized with " << _predictmap.size() << " items." << IBRCOMMON_LOGGER_ENDL;
			IBRCOMMON_LOGGER_DEBUG_TAG("DeliveryPredictabilityMap", 60) << *this << IBRCOMMON_LOGGER_ENDL;
			return stream;
		}
    virtual void visit(ElementType type, long id)
    {
      ElementId eid(type, id);

      ElementPtr e = _map->getElement(eid);

      if (e->getTags().get("REF1") != _ref && e->getTags().get("REF2") != _ref)
      {
        RecursiveElementRemover(eid).apply(_map);
      }
    }
Example #7
0
// See eq. 2.1.4
Matrix<std::complex<double> > U23(double delta, double angle)
{
	std::complex<double> eid(cos(delta), sin(delta));
	Matrix<std::complex<double> > ret(3, 3);
	ret(0, 0) = 1;
	ret(1, 1) = cos(angle);
	ret(1, 2) = sin(angle) * eid;
	ret(2, 1) = -sin(angle) * std::conj(eid);
	ret(2, 2) = cos(angle);
	return ret;
}
void BundleStorageTest::testRaiseEvent(dtn::storage::BundleStorage &storage)
{
		/* test signature (const Event *evt) */
	dtn::data::EID eid("dtn://node-one/test");
	dtn::data::Bundle b;
	b.lifetime = 60;
	b.source = dtn::data::EID("dtn://node-two/foo");

	storage.store(b);
	storage.wait();
	dtn::core::TimeEvent::raise(dtn::utils::Clock::getTime() + 3600, dtn::core::TIME_SECOND_TICK);
}
		/**
		Assumes unit viscosity.

		@todo Dont like the total_volume bare here
		*/
		UpscaledTensor analyze(const std::vector<FlowResults>& frv, double total_volume)
		{
			const size_t d = frv.size();
			UpscaledTensor r(d);

			// averaging
			const auto& volumes = frv[0].volumes(); // assumption: element info for all exps identical
			const auto elements = volumes.size(); // assumption: element info for all exps identical
			// average xy(z) components for pressure gradients and velocities for each experiment (outer index)
			// and each component (inner index)
			vector<vector<double>> vel_avgs(d, vector<double>(d)), pgrad_avgs(d, vector<double>(d));
			for (size_t I(0); I < d; ++I) // experiment, 0..d-1
				for (size_t c(0); c < d; ++c) { // for each spatial component, 0..d-1
					auto& pgrads = frv[I].components(FlowResults::Data::pressure_gradient, c);
					auto& vels = frv[I].components(FlowResults::Data::velocity, c);
					double pgrad_avg(0.), vel_avg(0.);
					for (size_t eid(0); eid < elements; ++eid) {
						pgrad_avg += pgrads[eid] * volumes[eid];
						vel_avg += vels[eid] * volumes[eid];
					}
					vel_avgs[I][c] = vel_avg / total_volume;
					pgrad_avgs[I][c] = pgrad_avg / total_volume;
				}

			// accumulating upscaled darcy problem
			// 1) velocity
			const size_t odiags = d == 3 ? 3 : 1; // number of off-diagonal terms
			vector<double64> u(d*d + odiags, 0.); // rhs, velocity component averages plus zeros
			for (size_t I(0); I < d; ++I)
				for (size_t c(0); c < d; ++c)
					u[I*d + c] = -vel_avgs[I][c];
			// 2) pressure gradients, 3D only from here
			DenseMatrix<12> capacity(12, 9); capacity = 0.;
			for (size_t I(0); I < d; ++I)
				for (size_t t(0); t < d; ++t)
					for (size_t c(0); c < d; ++c)
						capacity(I*3+t, t*d+c) = pgrad_avgs[I][c];
			// symmetry conditions
			capacity(9, 1) = capacity(10, 2) = capacity(11, 5) = 1.;
			capacity(9, 3) = capacity(10, 6) = capacity(11, 7) = -1;
			// solving overdetermined system and initializing tensor
			auto k = solve_overdet(capacity, u);
			for (size_t i(0); i < d; ++i)
				for (size_t j(0); j < d; ++j)
						r(i, j) = k[i*d + j];			
			return r;
		}
Example #10
0
bool Network::deleteEdge(vertex_id vid1, vertex_id vid2) {
	if (!containsEdge(vid1,vid2)) return false;
	edge_id eid(vid1,vid2,isDirected());
	out_edges[vid1].erase(vid2);
	in_edges[vid2].erase(vid1);
	if (!isDirected()) {
		out_edges[vid2].erase(vid1);
		in_edges[vid1].erase(vid2);
	}
	// remove attribute values (including WEIGHT, if present, which is treated as any other numeric attribute)
	for (std::map<std::string,std::map<edge_id,std::string> >::iterator it=edge_string_attribute.begin(); it!=edge_string_attribute.end(); it++)
		edge_string_attribute[it->first].erase(eid);
	for (std::map<std::string,std::map<edge_id,double> >::iterator it=edge_numeric_attribute.begin(); it!=edge_numeric_attribute.end(); it++)
		edge_numeric_attribute[it->first].erase(eid);
	num_edges--;
	return true;
}
TEST_F(ExtentIdTest, malformed)
{
    const fd::ContainerId cid("container");
    const uint32_t off(23);

    const fd::ExtentId eid(cid, off);

    const std::string eidstr(eid.str());

    // suffix too short
    EXPECT_THROW(fd::ExtentId(eidstr.substr(0, eidstr.size() - 2)),
                 fd::ExtentId::NotAnExtentId);

    // suffix too long
    EXPECT_THROW(fd::ExtentId(eidstr + "0"),
                 fd::ExtentId::NotAnExtentId);

    // wrong separator
    TODO("AR: figure out what's wrong here");
    // This is really curious:
    //
    // EXPECT_THROW(fd::ExtentId(str),
    //              fd::ExtentId::NotAnExtentId);
    //
    // yields a compiler error:
    //
    // /home/arne/Projects/CloudFounders/3.6/volumedriver-core/src/filedriver/test/ExtentIdTest.cpp:56:34: error: no matching function for call to 'filedriver::ExtentId::ExtentId()'
    //  EXPECT_THROW(fd::ExtentId(str),
    // ...
    //
    // . The nonsensical lambda is to work around that.
    auto fun([&]
             {
                 std::string str(eidstr);
                 const char sep = '*';
                 ASSERT_NE(sep, separator[0]);
                 str[str.find_last_of(separator)] = sep;

                 fd::ExtentId eid(str);
             });

    EXPECT_THROW(fun(),
                 fd::ExtentId::NotAnExtentId);
}
  void checkForMatch(const shared_ptr<const Node>& n)
  {
    // find other nearby candidates
    set<long> neighbors = _findNeighbors(n);

    ElementId from(n->getElementId());

    _elementsEvaluated++;
    int neighborCount = 0;
    vector<double> classes;

    for (set<long>::const_iterator it = neighbors.begin(); it != neighbors.end(); ++it)
    {
      ElementId eid(ElementType::Node, *it);
      const shared_ptr<const Node>& neighbor = _map->getNode(*it);

      // make sure we only create one match per pair. Use the node with the larger circular error
      // to make sure we do the larger of the two queries. If the CE is equal then use the eid
      // with the lower id. Arbitrary, but it will prevent duplicates.
      if ((neighbor->getCircularError() < n->getCircularError()) ||
          (neighbor->getCircularError() == n->getCircularError() && from.getId() < eid.getId()))
      {
        if (OsmSchema::getInstance().isPoi(*n))
        {
          // score each candidate and push it on the result vector
          PlacesPoiMatch* m = new PlacesPoiMatch(_map, from, eid, _threshold);
          // if we're confident this is a miss
          if (m->getClassification().getMissP() >= _rejectScore)
          {
            delete m;
          }
          else
          {
            _result.push_back(m);
            neighborCount++;
          }
        }
      }
    }

    _neighborCountSum += neighborCount;
    _neighborCountMax = std::max(_neighborCountMax, neighborCount);
  }
Example #13
0
int main(int argc, char *argv[])
{
	int index;
	int c;

	std::string ptp_dev("tun0");
	std::string app_name("tunnel");
	std::string endpoint("dtn:none");
	unsigned int lifetime = 60;
	bool daemonize = false;
	bool stop_daemon = false;
	std::string pidfile;
	bool throughput = false;

#ifdef HAVE_LIBDAEMON
	while ((c = getopt (argc, argv, "td:s:l:hDkp:")) != -1)
#else
	while ((c = getopt (argc, argv, "td:s:l:h")) != -1)
#endif
	switch (c)
	{
#ifdef HAVE_LIBDAEMON
		case 'D':
			daemonize = true;
			break;

		case 'k':
			daemonize = true;
			stop_daemon = true;
			break;

		case 'p':
			pidfile = optarg;
			break;
#endif
		case 'd':
			ptp_dev = optarg;
			break;

		case 't':
			throughput = true;
			break;

		case 's':
			app_name = optarg;
			break;

		case 'l':
			lifetime = atoi(optarg);
			break;

		default:
			print_help(argv[0]);
			return 1;
	}

	int optindex = 0;
	for (index = optind; index < argc; ++index)
	{
		switch (optindex)
		{
		case 0:
			endpoint = std::string(argv[index]);
			break;
		}

		optindex++;
	}

	// print help if not enough parameters are set
	if (!stop_daemon && (optindex < 1)) { print_help(argv[0]); exit(0); }

	// catch process signals
	ibrcommon::SignalHandler sighandler(term);
	sighandler.handle(SIGINT);
	sighandler.handle(SIGTERM);
	sighandler.handle(SIGQUIT);

	//initialize sighandler after possible exit call
	sighandler.initialize();

	// logging options
	//const unsigned char logopts = ibrcommon::Logger::LOG_DATETIME | ibrcommon::Logger::LOG_LEVEL;
	const unsigned char logopts = 0;

	// error filter
	const unsigned char logerr = ibrcommon::Logger::LOGGER_ERR | ibrcommon::Logger::LOGGER_CRIT;

	// logging filter, everything but debug, err and crit
	const unsigned char logstd = ibrcommon::Logger::LOGGER_ALL ^ (ibrcommon::Logger::LOGGER_DEBUG | logerr);

	// syslog filter, everything but DEBUG and NOTICE
	const unsigned char logsys = ibrcommon::Logger::LOGGER_ALL ^ (ibrcommon::Logger::LOGGER_DEBUG | ibrcommon::Logger::LOGGER_NOTICE);

#ifdef HAVE_LIBDAEMON
	if (daemonize) {
		// enable syslog logging
		ibrcommon::Logger::enableSyslog(argv[0], LOG_PID, LOG_DAEMON, logsys);
	} else
#endif
	{
		// add logging to the cout
		ibrcommon::Logger::addStream(std::cout, logstd, logopts);

		// add logging to the cerr
		ibrcommon::Logger::addStream(std::cerr, logerr, logopts);
	}

#ifdef HAVE_LIBDAEMON
	if (daemonize)
	{
#ifdef HAVE_DAEMON_RESET_SIGS
		/* Reset signal handlers */
		if (daemon_reset_sigs(-1) < 0) {
			IBRCOMMON_LOGGER_TAG("Core", error) << "Failed to reset all signal handlers: " << strerror(errno) << IBRCOMMON_LOGGER_ENDL;
			return 1;
		}

		/* Unblock signals */
		if (daemon_unblock_sigs(-1) < 0) {
			IBRCOMMON_LOGGER_TAG("Core", error) << "Failed to unblock all signals: " << strerror(errno) << IBRCOMMON_LOGGER_ENDL;
			return 1;
		}
#endif
		pid_t pid;

		/* Set identification string for the daemon for both syslog and PID file */
		daemon_pid_file_ident = daemon_log_ident = daemon_ident_from_argv0(argv[0]);

		/* set the pid file path */
		if (pidfile.length() > 0) {
			__daemon_pidfile__ = new char[pidfile.length() + 1];
			::strcpy(__daemon_pidfile__, pidfile.c_str());
			daemon_pid_file_proc = __daemon_pid_file_proc__;
		}

		/* Check if we are called with -k parameter */
		if (stop_daemon)
		{
			int ret;

			/* Kill daemon with SIGTERM */

			/* Check if the new function daemon_pid_file_kill_wait() is available, if it is, use it. */
			if ((ret = daemon_pid_file_kill_wait(SIGTERM, 5)) < 0)
				IBRCOMMON_LOGGER_TAG("Core", warning) << "Failed to kill daemon: " << strerror(errno) << IBRCOMMON_LOGGER_ENDL;

			return ret < 0 ? 1 : 0;
		}

		/* Check that the daemon is not rung twice a the same time */
		if ((pid = daemon_pid_file_is_running()) >= 0) {
			IBRCOMMON_LOGGER_TAG("Core", error) << "Daemon already running on PID file " << pid << IBRCOMMON_LOGGER_ENDL;
			return 1;
		}

		/* Prepare for return value passing from the initialization procedure of the daemon process */
		if (daemon_retval_init() < 0) {
			IBRCOMMON_LOGGER_TAG("Core", error) << "Failed to create pipe." << IBRCOMMON_LOGGER_ENDL;
			return 1;
		}

		/* Do the fork */
		if ((pid = daemon_fork()) < 0) {

			/* Exit on error */
			daemon_retval_done();
			return 1;

		} else if (pid) { /* The parent */
			int ret;

			/* Wait for 20 seconds for the return value passed from the daemon process */
			if ((ret = daemon_retval_wait(20)) < 0) {
				IBRCOMMON_LOGGER_TAG("Core", error) << "Could not recieve return value from daemon process: " << strerror(errno) << IBRCOMMON_LOGGER_ENDL;
				return 255;
			}

			return ret;

		} else { /* The daemon */
			/* Close FDs */
			if (daemon_close_all(-1) < 0) {
				IBRCOMMON_LOGGER_TAG("Core", error) << "Failed to close all file descriptors: " << strerror(errno) << IBRCOMMON_LOGGER_ENDL;

				/* Send the error condition to the parent process */
				daemon_retval_send(1);

				/* Do a cleanup */
				daemon_retval_send(255);
				daemon_signal_done();
				daemon_pid_file_remove();

				return -1;
			}

			/* Create the PID file */
			if (daemon_pid_file_create() < 0) {
				IBRCOMMON_LOGGER_TAG("Core", error) << "Could not create PID file ( " << strerror(errno) << ")." << IBRCOMMON_LOGGER_ENDL;
				daemon_retval_send(2);

				/* Do a cleanup */
				daemon_retval_send(255);
				daemon_signal_done();
				daemon_pid_file_remove();

				return -1;
			}

			/* Send OK to parent process */
			daemon_retval_send(0);
		}
	}
#endif

	IBRCOMMON_LOGGER_TAG("Core", info) << "IBR-DTN IP <-> Bundle Tunnel" << IBRCOMMON_LOGGER_ENDL;

	// create a connection to the dtn daemon
	ibrcommon::vaddress addr("localhost", 4550);
	ibrcommon::socketstream conn(new ibrcommon::tcpsocket(addr));

	try {
		// set-up tun2bundle gateway
		TUN2BundleGateway gateway(app_name, conn, ptp_dev);
		_gateway = &gateway;

		IBRCOMMON_LOGGER_TAG("Core", info) << "Local:  " << app_name << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", info) << "Peer:   " << endpoint << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", info) << "Device: " << gateway.getDeviceName() << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", notice) << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", notice) << "Now you need to set-up the ip tunnel. You can use commands like this:" << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", notice) << "# sudo ip link set " << gateway.getDeviceName() << " up mtu 65535" << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", notice) << "# sudo ip addr add 10.0.0.1/24 dev " << gateway.getDeviceName() << IBRCOMMON_LOGGER_ENDL;
		IBRCOMMON_LOGGER_TAG("Core", notice) << IBRCOMMON_LOGGER_ENDL;

		timer_t timerid;
		struct sigevent sev;

		if (!daemonize && throughput) {
			// enable throughput timer
			signal(SIGRTMIN, timer_display_throughput);

			sev.sigev_notify = SIGEV_SIGNAL;
			sev.sigev_signo = SIGRTMIN;
			sev.sigev_value.sival_ptr = &timerid;

			// create a timer
			timer_create(CLOCK_MONOTONIC, &sev, &timerid);

			// arm the timer
			struct itimerspec its;
			size_t freq_nanosecs = 200000000;
			its.it_value.tv_sec = freq_nanosecs / 1000000000;;
			its.it_value.tv_nsec = freq_nanosecs % 1000000000;
			its.it_interval.tv_sec = its.it_value.tv_sec;
			its.it_interval.tv_nsec = its.it_value.tv_nsec;

			if (timer_settime(timerid, 0, &its, NULL) == -1) {
				IBRCOMMON_LOGGER_TAG("Core", error) << "Timer set failed." << IBRCOMMON_LOGGER_ENDL;
			}
		}

		// destination
		dtn::data::EID eid(endpoint);

		while (m_running)
		{
			gateway.process(eid, lifetime);
		}

		gateway.shutdown();
	} catch (const ibrcommon::Exception &ex) {
		if (m_running) {
			IBRCOMMON_LOGGER_TAG("Core", error) << ex.what() << IBRCOMMON_LOGGER_ENDL;
			return -1;
		}
	}

#ifdef HAVE_LIBDAEMON
	if (daemonize) {
		/* Do a cleanup */
		IBRCOMMON_LOGGER_TAG("Core", info) << "Stopped " << app_name << IBRCOMMON_LOGGER_ENDL;
		daemon_retval_send(255);
		daemon_signal_done();
		daemon_pid_file_remove();
	} else
#endif
	{
		std::cout << std::endl;
	}

	return 0;
}