New waf/wscript and initial reorganization

This commit is contained in:
Alexander Afanasyev committed 2013-07-14 10:58:26 -07:00
1 parent eb1d865d03
commit 6133f9ac4b
65 files changed
+235 -1552

No files matched your search

-195
View File
@@ -1,195 +0,0 @@
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
/*
* Copyright (c) 2012 University of California, Los Angeles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
* Chaoyi Bian <bcy@pku.edu.cn>
* Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
#ifndef SYNC_CCNX_WRAPPER_H
#define SYNC_CCNX_WRAPPER_H
#include <boost/exception/all.hpp>
#include <boost/function.hpp>
#include <string>
#include <ns3/ptr.h>
#include <ns3/node.h>
#include <ns3/random-variable.h>
#include <ns3/ccnx-app.h>
#include <ns3/ccnx-name-components.h>
#include <ns3/ccnx-name-components-hash-helper.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
/**
* \defgroup sync SYNC protocol
*
* Implementation of SYNC protocol
*/
namespace Sync {
template<class Callback>
struct CcnxFilterEntry
{
public:
CcnxFilterEntry (ns3::Ptr<const ns3::CcnxNameComponents> prefix)
: m_prefix (prefix)
{ }
const ns3::CcnxNameComponents &
GetPrefix () const
{ return *m_prefix; }
void
AddCallback (Callback callback)
{
m_callback = callback;
}
void
ClearCallback ()
{
m_callback = 0;
}
public:
ns3::Ptr<const ns3::CcnxNameComponents> m_prefix; ///< \brief Prefix of the PIT entry
Callback m_callback;
};
template<class Callback>
struct CcnxFilterEntryContainer
{
typedef
boost::multi_index::multi_index_container<
CcnxFilterEntry<Callback>,
boost::multi_index::indexed_by<
// indexed by hash
boost::multi_index::hashed_unique<
boost::multi_index::const_mem_fun< CcnxFilterEntry<Callback>, const ns3::CcnxNameComponents&, &CcnxFilterEntry<Callback>::GetPrefix >,
ns3::CcnxPrefixHash
>
>
> type;
};
struct CcnxOperationException : virtual boost::exception, virtual std::exception { };
/**
* \ingroup sync
* @brief A wrapper for ccnx library; clients of this code do not need to deal
* with ccnx library
*/
class CcnxWrapper
: public ns3::CcnxApp
{
public:
typedef boost::function<void (std::string, std::string)> DataCallback;
typedef boost::function<void (std::string)> InterestCallback;
/**
* @brief initialize the wrapper; a lot of things needs to be done. 1) init
* keystore 2) init keylocator 3) start a thread to hold a loop of ccn_run
*
*/
CcnxWrapper();
~CcnxWrapper();
// from CcnxApp
/**
* @brief Should be called after Node pointer is set to create face and start application
*/
virtual void
StartApplication ();
/**
* @brief Stop application
*/
virtual void
StopApplication ();
/**
* @brief send Interest; need to grab lock m_mutex first
*
* @param strInterest the Interest name
* @param dataCallback the callback function to deal with the returned data
* @return the return code of ccn_express_interest
*/
int
sendInterest (const std::string &strInterest, const DataCallback &dataCallback);
/**
* @brief set Interest filter (specify what interest you want to receive)
*
* @param prefix the prefix of Interest
* @param interestCallback the callback function to deal with the returned data
* @return the return code of ccn_set_interest_filter
*/
int
setInterestFilter (const std::string &prefix, const InterestCallback &interestCallback);
/**
* @brief clear Interest filter
* @param prefix the prefix of Interest
*/
void
clearInterestFilter (const std::string &prefix);
/**
* @brief publish data and put it to local ccn content store; need to grab
* lock m_mutex first
*
* @param name the name for the data object
* @param dataBuffer the data to be published
* @param freshness the freshness time for the data object
* @return code generated by ccnx library calls, >0 if success
*/
int
publishData (const std::string &name, const std::string &dataBuffer, int freshness);
// from CcnxApp
virtual void
OnInterest (const ns3::Ptr<const ns3::CcnxInterestHeader> &interest, ns3::Ptr<ns3::Packet> packet);
virtual void
OnContentObject (const ns3::Ptr<const ns3::CcnxContentObjectHeader> &contentObject,
ns3::Ptr<ns3::Packet> payload);
private:
CcnxFilterEntryContainer<InterestCallback>::type::iterator
InterestCallbackLookup (const ns3::CcnxNameComponents &name);
CcnxFilterEntryContainer<DataCallback>::type::iterator
DataCallbackLookup (const ns3::CcnxNameComponents &name);
private:
ns3::UniformVariable m_rand; // nonce generator
CcnxFilterEntryContainer<DataCallback>::type m_dataCallbacks;
CcnxFilterEntryContainer<InterestCallback>::type m_interestCallbacks;
};
typedef boost::shared_ptr<CcnxWrapper> CcnxWrapperPtr;
} // Sync
#endif // SYNC_CCNX_WRAPPER_H
-108
View File
@@ -1,108 +0,0 @@
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
/*
* Copyright (c) 2012 University of California, Los Angeles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
* Chaoyi Bian <bcy@pku.edu.cn>
* Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
#ifndef SYNC_LOG_H
#define SYNC_LOG_H
#ifdef NS3_MODULE
#include <ns3/log.h>
#ifdef _DEBUG
#define INIT_LOGGER(name) NS_LOG_COMPONENT_DEFINE(name);
#define _LOG_INFO(x) NS_LOG_INFO(x)
#define _LOG_DEBUG(x) NS_LOG_DEBUG(x)
#define _LOG_TRACE(x) NS_LOG_LOGIC(x)
#define _LOG_FUNCTION(x) NS_LOG_FUNCTION(x)
#define _LOG_FUNCTION_NOARGS NS_LOG_FUNCTION_NOARGS
#else
#define INIT_LOGGER(name)
#define _LOG_INFO(x)
#define _LOG_DEBUG(x)
#define _LOG_TRACE(x)
#define _LOG_FUNCTION(x)
#define _LOG_FUNCTION_NOARGS
#endif
#else
#ifdef HAVE_LOG4CXX
#include <log4cxx/logger.h>
#define INIT_LOGGER(name) \
static log4cxx::LoggerPtr staticModuleLogger = log4cxx::Logger::getLogger (name);
#define _LOG_INFO(x) \
LOG4CXX_INFO(staticModuleLogger, x);
#define _LOG_DEBUG(x) \
LOG4CXX_DEBUG(staticModuleLogger, x);
#define _LOG_TRACE(x) \
LOG4CXX_TRACE(staticModuleLogger, x);
#define _LOG_FUNCTION(x) \
LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "(" << x << ")");
#define _LOG_FUNCTION_NOARGS \
LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "()");
void
INIT_LOGGERS ();
#else
#define INIT_LOGGER(name)
#define _LOG_FUNCTION(x)
#define _LOG_FUNCTION_NOARGS
#define _LOG_TRACE(x)
#define _LOG_INFO(x)
#define INIT_LOGGERS(x)
#ifdef _DEBUG
#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#define _LOG_DEBUG(x) \
std::clog << boost::get_system_time () << " " << boost::this_thread::get_id () << " " << x << endl;
#else
#define _LOG_DEBUG(x)
#endif
#endif // HAVE_LOG4CXX
#endif // NS3_MODULE
#endif // SYNC_LOG_H
-115
View File
@@ -1,115 +0,0 @@
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2011 University of California, Los Angeles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
#ifndef SYNC_LOGIC_HELPER_H
#define SYNC_LOGIC_HELPER_H
#include "ns3/object-factory.h"
#include "ns3/attribute.h"
#include "ns3/node-container.h"
#include "ns3/application-container.h"
#include "ns3/ptr.h"
#include <boost/function.hpp>
namespace Sync
{
class SeqNo;
/**
* \brief A helper to make it easier to instantiate an ns3::CcnxConsumer Application
* on a set of nodes.
*/
class SyncLogicHelper
{
public:
typedef boost::function< void ( const std::string &/*prefix*/, const SeqNo &/*newSeq*/, const SeqNo &/*oldSeq*/ ) > LogicUpdateCallback;
typedef boost::function< void ( const std::string &/*prefix*/ ) > LogicRemoveCallback;
/**
* \brief Create an CcnxAppHelper to make it easier to work with CCNx apps
*
* \param app Class of the application
*/
SyncLogicHelper ();
/**
* @brief Set the sync prefix
*/
void
SetPrefix (const std::string &prefix);
/**
* @brief Set onUpdate and onRemove callbacks
*/
void
SetCallbacks (LogicUpdateCallback onUpdate, LogicRemoveCallback onRemove);
/**
* Install an ns3::CcnxConsumer on each node of the input container
* configured with all the attributes set with SetAttribute.
*
* \param c NodeContainer of the set of nodes on which an CcnxConsumer
* will be installed.
* \returns Container of Ptr to the applications installed.
*/
ns3::ApplicationContainer
Install (ns3::NodeContainer c);
/**
* Install an ns3::CcnxConsumer on the node configured with all the
* attributes set with SetAttribute.
*
* \param node The node on which an CcnxConsumer will be installed.
* \returns Container of Ptr to the applications installed.
*/
ns3::ApplicationContainer
Install (ns3::Ptr<ns3::Node> node);
/**
* Install an ns3::CcnxConsumer on the node configured with all the
* attributes set with SetAttribute.
*
* \param nodeName The node on which an CcnxConsumer will be installed.
* \returns Container of Ptr to the applications installed.
*/
ns3::ApplicationContainer
Install (std::string nodeName);
private:
/**
* \internal
* Install an ns3::CcnxConsumer on the node configured with all the
* attributes set with SetAttribute.
*
* \param node The node on which an CcnxConsumer will be installed.
* \returns Ptr to the application installed.
*/
ns3::Ptr<ns3::Application> InstallPriv (ns3::Ptr<ns3::Node> node);
std::string m_prefix; // sync prefix
LogicUpdateCallback m_onUpdate;
LogicRemoveCallback m_onRemove;
};
} // namespace Sync
#endif // SYNC_LOGIC_HELPER_H
-79
View File
@@ -1,79 +0,0 @@
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
/*
* Copyright (c) 2012 University of California, Los Angeles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
* Chaoyi Bian <bcy@pku.edu.cn>
* Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
#ifdef NS3_MODULE
#ifndef SYNC_CCNX_NAME_INFO_H
#define SYNC_CCNX_NAME_INFO_H
#include "sync-name-info.h"
#include "ns3/ptr.h"
#include "ns3/ccnx-name-components.h"
namespace Sync {
class Ns3NameInfo : public NameInfo
{
public:
/**
* @brief Lookup existing or create new NameInfo object
* @param name routable prefix
*/
static NameInfoConstPtr
FindOrCreate (ns3::Ptr<const ns3::CcnxNameComponents> name);
virtual ~Ns3NameInfo () { };
// from NameInfo
virtual bool
operator == (const NameInfo &info) const;
virtual bool
operator < (const NameInfo &info) const;
virtual std::string
toString () const;
private:
// implementing a singleton pattern.
/**
* @brief Disabled default constructor. NameInfo object should be created through FindOrCreate static call.
*/
/**
* @brief Disabled default
*/
Ns3NameInfo () {}
Ns3NameInfo& operator = (const Ns3NameInfo &info) { return *this; }
Ns3NameInfo (ns3::Ptr<const ns3::CcnxNameComponents> name);
ns3::Ptr<const ns3::CcnxNameComponents> m_name;
};
Digest &
operator << (Digest &, const ns3::CcnxNameComponents &name);
} // Sync
#endif // SYNC_CCNX_NAME_INFO_H
#endif // NS3_MODULE
-95
View File
@@ -1,95 +0,0 @@
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
/*
* Copyright (c) 2012 University of California, Los Angeles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
* Chaoyi Bian <bcy@pku.edu.cn>
* Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
#ifndef SYNC_SCHEDULER_H
#define SYNC_SCHEDULER_H
#include <ns3/nstime.h>
#include <ns3/event-id.h>
#include <ns3/simulator.h>
#include <list>
#include <map>
#include "sync-event.h"
#define TIME_SECONDS(number) ns3::Seconds(number)
#define TIME_MILLISECONDS(number) ns3::MilliSeconds(number)
#define TIME_NOW ns3::Simulator::Now ()
typedef ns3::Time TimeDuration;
typedef ns3::Time TimeAbsolute;
namespace Sync {
/**
* @ingroup sync
* @brief General purpose event scheduler
*
* This class internally runs a thread and events can be scheduled by specifying an absolute or relative time of the event
*/
class Scheduler
{
public:
/**
* @brief Default constructor. Thread will be created
*/
Scheduler ();
/**
* @brief Destructor. Thread will be nicely stopped
*/
~Scheduler ();
/**
* @brief Schedule an event at absolute time 'abstime'
* @param abstime Absolute time
* @param event function to be called at the time
* @param label Label for the event
*/
// void
// schedule (const boost::system_time &abstime, Event event, uint32_t label);
/**
* @brief Schedule an event at relative time 'reltime'
* @param reltime Relative time
* @param event function to be called at the time
* @param label Label for the event
*/
void
schedule (const TimeDuration &reltime, Event event, uint32_t label);
/**
* @brief Cancel all events for the label
* @param label Label of the event that needs to be cancelled
*/
void
cancel (uint32_t label);
private:
static void
eventWrapper (Event event);
private:
std::map< uint32_t, std::list< ns3::EventId > > m_labeledEvents;
};
}
#endif // SYNC_SCHEDULER_H
-263
View File
@@ -1,263 +0,0 @@
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
/*
* Copyright (c) 2012 University of California, Los Angeles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
* Chaoyi Bian <bcy@pku.edu.cn>
* Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
#include "sync-ccnx-wrapper.h"
#include "sync-log.h"
#include <boost/throw_exception.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
namespace ll = boost::lambda;
#include "../evaluation/type-tag.h"
#include <ns3/ccnx-name-components.h>
#include <ns3/ccnx-interest-header.h>
#include <ns3/ccnx-content-object-header.h>
#include <ns3/ccnx-face.h>
#include <ns3/packet.h>
#include <ns3/ccnx-fib.h>
typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info_str;
typedef boost::error_info<struct tag_errmsg, int> errmsg_info_int;
using namespace std;
using namespace boost;
using namespace ns3;
INIT_LOGGER ("CcnxWrapper");
namespace Sync {
CcnxWrapper::CcnxWrapper()
: m_rand (0, std::numeric_limits<uint32_t>::max ())
{
}
CcnxWrapper::~CcnxWrapper()
{
}
void
CcnxWrapper::StartApplication ()
{
CcnxApp::StartApplication ();
}
void
CcnxWrapper::StopApplication ()
{
CcnxApp::StopApplication ();
}
int
CcnxWrapper::publishData (const string &dataName, const string &dataBuffer, int freshness)
{
// NS_LOG_INFO ("Requesting Interest: \n" << interestHeader);
_LOG_INFO ("> Data for " << dataName);
Ptr<CcnxNameComponents> name = Create<CcnxNameComponents> ();
istringstream is (dataName);
is >> *name;
static CcnxContentObjectTail trailer;
CcnxContentObjectHeader data;
data.SetName (name);
data.SetFreshness (Seconds (freshness));
Ptr<Packet> packet = Create<Packet> (reinterpret_cast<const uint8_t*> (dataBuffer.c_str ()), dataBuffer.size ());
packet->AddPacketTag (CreateObject<TypeTag> (TypeTag::DATA));
packet->AddHeader (data);
packet->AddTrailer (trailer);
m_protocolHandler (packet);
m_transmittedContentObjects (&data, packet, this, m_face);
return 0;
}
int CcnxWrapper::sendInterest (const string &strInterest, const DataCallback &dataCallback)
{
// NS_LOG_INFO ("Requesting Interest: \n" << interestHeader);
_LOG_INFO ("> Interest for " << strInterest);
Ptr<CcnxNameComponents> name = Create<CcnxNameComponents> ();
istringstream is (strInterest);
is >> *name;
CcnxInterestHeader interestHeader;
uint32_t nonce = m_rand.GetValue ();
_LOG_DEBUG ("Nonce: " << nonce);
interestHeader.SetNonce (nonce);
interestHeader.SetName (name);
interestHeader.SetInterestLifetime (Seconds (9.9)); // really long-lived interests
Ptr<Packet> packet = Create<Packet> ();
packet->AddPacketTag (CreateObject<TypeTag> (TypeTag::INTEREST));
packet->AddHeader (interestHeader);
// NS_LOG_DEBUG (interestHeader);
m_protocolHandler (packet);
m_transmittedInterests (&interestHeader, this, m_face);
// Record the callback
CcnxFilterEntryContainer<DataCallback>::type::iterator entry = m_dataCallbacks.find (*name);
if (entry == m_dataCallbacks.end ())
{
pair<CcnxFilterEntryContainer<DataCallback>::type::iterator, bool> status =
m_dataCallbacks.insert (CcnxFilterEntry<DataCallback> (name));
entry = status.first;
}
m_dataCallbacks.modify (entry, ll::bind (&CcnxFilterEntry<DataCallback>::AddCallback, ll::_1, dataCallback));
return 0;
}
int CcnxWrapper::setInterestFilter (const string &prefix, const InterestCallback &interestCallback)
{
Ptr<CcnxNameComponents> name = Create<CcnxNameComponents> ();
istringstream is (prefix);
is >> *name;
CcnxFilterEntryContainer<InterestCallback>::type::iterator entry = m_interestCallbacks.find (*name);
if (entry == m_interestCallbacks.end ())
{
pair<CcnxFilterEntryContainer<InterestCallback>::type::iterator, bool> status =
m_interestCallbacks.insert (CcnxFilterEntry<InterestCallback> (name));
entry = status.first;
}
m_interestCallbacks.modify (entry, ll::bind (&CcnxFilterEntry<InterestCallback>::AddCallback, ll::_1, interestCallback));
// creating actual face
Ptr<CcnxFib> fib = GetNode ()->GetObject<CcnxFib> ();
CcnxFibEntryContainer::type::iterator fibEntry = fib->Add (*name, m_face, 0);
// make face green, so it will be used primarily
fib->m_fib.modify (fibEntry,
ll::bind (&CcnxFibEntry::UpdateStatus,
ll::_1, m_face, CcnxFibFaceMetric::NDN_FIB_GREEN));
return 0;
}
void
CcnxWrapper::clearInterestFilter (const std::string &prefix)
{
Ptr<CcnxNameComponents> name = Create<CcnxNameComponents> ();
istringstream is (prefix);
is >> *name;
CcnxFilterEntryContainer<InterestCallback>::type::iterator entry = m_interestCallbacks.find (*name);
if (entry == m_interestCallbacks.end ())
return;
m_interestCallbacks.modify (entry, ll::bind (&CcnxFilterEntry<InterestCallback>::ClearCallback, ll::_1));
}
CcnxFilterEntryContainer<CcnxWrapper::InterestCallback>::type::iterator
CcnxWrapper::InterestCallbackLookup (const ns3::CcnxNameComponents &name)
{
CcnxFilterEntryContainer<InterestCallback>::type::iterator entry = m_interestCallbacks.end ();
// do the longest prefix match
for (size_t componentsCount = name.GetComponents ().size ()+1;
componentsCount > 0;
componentsCount--)
{
CcnxNameComponents subPrefix (name.GetSubComponents (componentsCount-1));
entry = m_interestCallbacks.find (subPrefix);
if (entry != m_interestCallbacks.end())
return entry;
}
return entry;
}
CcnxFilterEntryContainer<CcnxWrapper::DataCallback>::type::iterator
CcnxWrapper::DataCallbackLookup (const ns3::CcnxNameComponents &name)
{
CcnxFilterEntryContainer<DataCallback>::type::iterator entry = m_dataCallbacks.end ();
// do the longest prefix match
for (size_t componentsCount = name.GetComponents ().size ()+1;
componentsCount > 0;
componentsCount--)
{
CcnxNameComponents subPrefix (name.GetSubComponents (componentsCount-1));
entry = m_dataCallbacks.find (subPrefix);
if (entry != m_dataCallbacks.end())
return entry;
}
return entry;
}
void
CcnxWrapper::OnInterest (const Ptr<const CcnxInterestHeader> &interest, Ptr<Packet> packet)
{
CcnxApp::OnInterest (interest, packet);
CcnxFilterEntryContainer<InterestCallback>::type::iterator entry = InterestCallbackLookup (interest->GetName ());
if (entry == m_interestCallbacks.end ())
{
_LOG_DEBUG ("No Interest callback set");
return;
}
entry->m_callback (lexical_cast<string> (interest->GetName ()));
}
void
CcnxWrapper::OnContentObject (const Ptr<const CcnxContentObjectHeader> &contentObject,
Ptr<Packet> payload)
{
CcnxApp::OnContentObject (contentObject, payload);
CcnxFilterEntryContainer<DataCallback>::type::iterator entry = DataCallbackLookup (contentObject->GetName ());
if (entry == m_dataCallbacks.end ())
{
_LOG_DEBUG ("No Data callback set");
return;
}
ostringstream content;
payload->CopyData (&content, payload->GetSize ());
entry->m_callback (lexical_cast<string> (contentObject->GetName ()), content.str ());
// i guess it make sense to remove callback when interest is satisfied
m_dataCallbacks.erase (entry);
}
}
-94
View File
@@ -1,94 +0,0 @@
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2011 University of California, Los Angeles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
#include "sync-logic-helper.h"
#include "sync-logic.h"
#include "ns3/log.h"
#include "ns3/string.h"
#include "ns3/names.h"
NS_LOG_COMPONENT_DEFINE ("SyncLogicHelper");
using namespace ns3;
namespace Sync
{
SyncLogicHelper::SyncLogicHelper ()
{
// m_factory.SetTypeId ("Sync::SyncLogic");
}
void
SyncLogicHelper::SetPrefix (const std::string &prefix)
{
m_prefix = prefix;
}
void
SyncLogicHelper::SetCallbacks (LogicUpdateCallback onUpdate, LogicRemoveCallback onRemove)
{
m_onUpdate = onUpdate;
m_onRemove = onRemove;
}
// void
// CcnxAppHelper::SetAttribute (std::string name, const AttributeValue &value)
// {
// m_factory.Set (name, value);
// }
ApplicationContainer
SyncLogicHelper::Install (Ptr<Node> node)
{
return ApplicationContainer (InstallPriv (node));
}
ApplicationContainer
SyncLogicHelper::Install (std::string nodeName)
{
Ptr<Node> node = Names::Find<Node> (nodeName);
return ApplicationContainer (InstallPriv (node));
}
ApplicationContainer
SyncLogicHelper::Install (NodeContainer c)
{
ApplicationContainer apps;
for (NodeContainer::Iterator i = c.Begin (); i != c.End (); ++i)
{
apps.Add (InstallPriv (*i));
}
return apps;
}
Ptr<Application>
SyncLogicHelper::InstallPriv (Ptr<Node> node)
{
Ptr<SyncLogic> app = CreateObject<SyncLogic> ("/sync", m_onUpdate, m_onRemove);
node->AddApplication (app);
return app;
}
}
-126
View File
@@ -1,126 +0,0 @@
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
/*
* Copyright (c) 2012 University of California, Los Angeles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
* Chaoyi Bian <bcy@pku.edu.cn>
* Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
#ifdef NS3_MODULE
#include "sync-ns3-name-info.h"
#include "ns3/ccnx-name-components.h"
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
#include <utility>
using namespace std;
using namespace boost;
namespace Sync {
NameInfoConstPtr
Ns3NameInfo::FindOrCreate (ns3::Ptr<const ns3::CcnxNameComponents> name)
{
mutex::scoped_lock namesLock (m_namesMutex);
NameInfoConstPtr ret;
string key = lexical_cast<string> (*name);
NameMap::iterator item = m_names.find (key);
if (item != m_names.end ())
{
ret = item->second.lock ();
BOOST_ASSERT (ret != 0);
}
else
{
ret = NameInfoPtr (new Ns3NameInfo (name));
weak_ptr<const NameInfo> value (ret);
pair<NameMap::iterator,bool> inserted =
m_names.insert (make_pair (key, value));
BOOST_ASSERT (inserted.second); // previous call has to insert value
item = inserted.first;
}
return ret;
}
Ns3NameInfo::Ns3NameInfo (ns3::Ptr<const ns3::CcnxNameComponents> name)
: m_name (name)
{
m_id = m_ids ++; // set ID for a newly inserted element
m_digest << *name;
m_digest.getHash (); // finalize digest
}
string
Ns3NameInfo::toString () const
{
return lexical_cast<std::string> (*m_name);
}
bool
Ns3NameInfo::operator == (const NameInfo &info) const
{
try
{
return *m_name == *dynamic_cast<const Ns3NameInfo&> (info).m_name;
}
catch (...)
{
return false;
}
}
bool
Ns3NameInfo::operator < (const NameInfo &info) const
{
try
{
return *m_name < *dynamic_cast<const Ns3NameInfo&> (info).m_name;
}
catch (...)
{
return false;
}
}
Digest &
operator << (Digest &digest, const ns3::CcnxNameComponents &name)
{
BOOST_FOREACH (const std::string &component, name.GetComponents ())
{
Digest subhash;
subhash << component;
subhash.getHash (); // finalize hash
digest << subhash;
}
return digest;
}
} // Sync
#endif
-91
View File
@@ -1,91 +0,0 @@
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
/*
* Copyright (c) 2012 University of California, Los Angeles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
* Chaoyi Bian <bcy@pku.edu.cn>
* Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
#include "sync-scheduler.h"
#include "sync-log.h"
#include "ns3/simulator.h"
using namespace boost;
using namespace std;
using namespace ns3;
INIT_LOGGER ("Scheduler");
namespace Sync {
Scheduler::Scheduler ()
{
}
Scheduler::~Scheduler ()
{
}
void
Scheduler::eventWrapper (Event event)
{
event ();
}
void
Scheduler::schedule (const TimeDuration &reltime, Event event, uint32_t label)
{
_LOG_DEBUG ("Schedule event for " << (Simulator::Now () +reltime).ToDouble (Time::S) << "s for label " << label);
list< EventId > &eventsForLabel = m_labeledEvents [label];
list< EventId >::iterator i = eventsForLabel.begin ();
while (i != eventsForLabel.end ())
{
if (i->IsExpired ())
{
list< EventId >::iterator next = i;
next ++;
eventsForLabel.erase (i);
i = next;
}
else
i ++;
}
ns3::EventId eventId = ns3::Simulator::Schedule (reltime, Scheduler::eventWrapper, event);
eventsForLabel.push_back (eventId);
}
void
Scheduler::cancel (uint32_t label)
{
list< EventId > &eventsForLabel = m_labeledEvents [label];
_LOG_DEBUG ("Canceling events for label " << label << " (" << eventsForLabel.size () << " events)");
for (list< EventId >::iterator i = eventsForLabel.begin ();
i != eventsForLabel.end ();
i++)
{
i->Cancel ();
}
eventsForLabel.clear ();
}
} // Sync
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Vendored
BIN
View File
Binary file not shown.
-77
View File
@@ -1,77 +0,0 @@
#! /usr/bin/env python
# encoding: utf-8
'''
When using this tool, the wscript will look like:
def options(opt):
opt.tool_options('ccnx', tooldir=["waf-tools"])
def configure(conf):
conf.load('compiler_cxx ccnx')
def build(bld):
bld(source='main.cpp', target='app', use='CCNX')
Options are generated, in order to specify the location of ccnx includes/libraries.
'''
import sys
import re
from waflib import Utils,Logs,Errors
from waflib.Configure import conf
CCNX_DIR=['/usr','/usr/local','/opt/local','/sw']
CCNX_VERSION_FILE='ccn/ccn.h'
CCNX_VERSION_CODE='''
#include <iostream>
#include <ccn/ccn.h>
int main() { std::cout << ((CCN_API_VERSION/100000) % 100) << "." << ((CCN_API_VERSION/1000) % 100) << "." << (CCN_API_VERSION % 1000); }
'''
def options(opt):
opt.add_option('--ccnx',type='string',default='',dest='ccnx_dir',help='''path to where CCNx is installed, e.g. /usr/local''')
@conf
def __ccnx_get_version_file(self,dir):
# Logs.pprint ('CYAN', ' + %s/%s/%s' % (dir, 'include', CCNX_VERSION_FILE))
try:
return self.root.find_dir(dir).find_node('%s/%s' % ('include', CCNX_VERSION_FILE))
except:
return None
@conf
def ccnx_get_version(self,dir):
val=self.check_cxx(fragment=CCNX_VERSION_CODE,includes=['%s/%s' % (dir, 'include')],execute=True,define_ret = True, mandatory=True)
return val
@conf
def ccnx_get_root(self,*k,**kw):
root=k and k[0]or kw.get('path',None)
# Logs.pprint ('RED', ' %s' %root)
if root and self.__ccnx_get_version_file(root):
return root
for dir in CCNX_DIR:
if self.__ccnx_get_version_file(dir):
return dir
if root:
self.fatal('CCNx not found in %s'%root)
else:
self.fatal('CCNx not found, please provide a --ccnx argument (see help)')
@conf
def check_ccnx(self,*k,**kw):
if not self.env['CXX']:
self.fatal('load a c++ compiler first, conf.load("compiler_cxx")')
var=kw.get('uselib_store','CCNX')
self.start_msg('Checking CCNx')
root = self.ccnx_get_root(*k,**kw);
self.env.CCNX_VERSION=self.ccnx_get_version(root)
self.env['INCLUDES_%s'%var]= '%s/%s' % (root, "include");
self.env['LIB_%s'%var] = "ccn"
self.env['LIBPATH_%s'%var] = '%s/%s' % (root, "lib")
self.end_msg(self.env.CCNX_VERSION)
if Logs.verbose:
Logs.pprint('CYAN',' ccnx include : %s'%self.env['INCLUDES_%s'%var])
Logs.pprint('CYAN',' ccnx lib : %s'%self.env['LIB_%s'%var])
Logs.pprint('CYAN',' ccnx libpath : %s'%self.env['LIBPATH_%s'%var])
+160
View File
@@ -0,0 +1,160 @@
#! /usr/bin/env python
# encoding: utf-8
'''
When using this tool, the wscript will look like:
def options(opt):
opt.tool_options('ndnx')
def configure(conf):
conf.load('compiler_c ndnx')
def build(bld):
bld(source='main.cpp', target='app', use='NDNX')
Options are generated, in order to specify the location of ndnx includes/libraries.
'''
import sys, re
from waflib import Utils, Logs, Errors, Options, ConfigSet
from waflib.Configure import conf
NDNX_DIR=['/usr','/usr/local','/opt/local','/sw']
NDNX_VERSION_FILE='ccn/ccn.h'
NDNX_VERSION_CODE='''
#include <ccn/ccn.h>
#include <stdio.h>
int main() { printf ("%d.%d.%d", ((CCN_API_VERSION/100000) % 100), ((CCN_API_VERSION/1000) % 100), (CCN_API_VERSION % 1000)); return 0; }
'''
@conf
def __ndnx_get_version_file(self,dir):
# Logs.pprint ('CYAN', ' + %s/%s/%s' % (dir, 'include', NDNX_VERSION_FILE))
try:
return self.root.find_dir(dir).find_node('%s/%s' % ('include', NDNX_VERSION_FILE))
except:
return None
@conf
def ndnx_get_version(self,dir):
val=self.check_cc(fragment=NDNX_VERSION_CODE,includes=['%s/%s' % (dir, 'include')],execute=True,define_ret = True, mandatory=True)
return val
@conf
def ndnx_get_root(self,*k,**kw):
root=Options.options.ndnx_dir or (k and k[0]) or kw.get('path',None)
if root:
if self.__ndnx_get_version_file(root):
return root
self.fatal('NDNx not found in %s'%root)
for dir in NDNX_DIR:
if self.__ndnx_get_version_file(dir):
return dir
self.fatal('NDNx not found, please provide a --ndnx argument (see help)')
@conf
def check_openssl(self,*k,**kw):
root = k and k[0] or kw.get('path',None) or Options.options.openssl
mandatory = kw.get('mandatory', True)
var = kw.get('var', 'SSL')
CODE = """
#include <openssl/crypto.h>
#include <stdio.h>
int main(int argc, char **argv) {
(void)argc;
printf ("%s", argv[0]);
return 0;
}
"""
if root:
testApp = self.check_cc (lib=['ssl', 'crypto'],
header_name='openssl/crypto.h',
define_name='HAVE_%s' % var,
uselib_store=var,
mandatory = mandatory,
cflags="-I%s/include" % root,
linkflags="-L%s/lib" % root,
execute = True, fragment = CODE, define_ret = True)
else:
testApp = libcrypto = self.check_cc (lib=['ssl', 'crypto'],
header_name='openssl/crypto.h',
define_name='HAVE_%s' % var,
uselib_store=var,
mandatory = mandatory,
execute = True, fragment = CODE, define_ret = True)
if not testApp:
return
self.start_msg ('Checking if selected openssl matches NDNx')
ndn_var = kw.get('ndn_var', "NDNX")
if Utils.unversioned_sys_platform () == "darwin":
def otool (binary):
p = Utils.subprocess.Popen (['/usr/bin/otool', '-L', binary],
stdout = Utils.subprocess.PIPE, )
for line in p.communicate()[0].split ('\n'):
if re.match ('.*/libcrypto\..*', line):
return line
selected_crypto = otool (testApp)
ccnd_crypto = otool ('%s/bin/ccnd' % self.env['%s_ROOT' % ndn_var])
if ccnd_crypto != selected_crypto:
self.fatal ("Selected openssl does not match used to compile NDNx (%s != %s)" %
(selected_crypto.strip (), ccnd_crypto.strip ()))
self.end_msg (True)
elif Utils.unversioned_sys_platform () == "linux" or Utils.unversioned_sys_platform () == "freebsd":
def ldd (binary):
p = Utils.subprocess.Popen (['/usr/bin/ldd', binary],
stdout = Utils.subprocess.PIPE, )
for line in p.communicate()[0].split ('\n'):
if re.match ('libcrypto\..*', line):
return line
selected_crypto = ldd (testApp)
ccnd_crypto = ldd ('%s/bin/ccnd' % self.env['%s_ROOT' % ndn_var])
if ccnd_crypto != selected_crypto:
self.fatal ("Selected openssl does not match used to compile NDNx (%s != %s)" %
(selected_crypto.strip (), ccnd_crypto.strip ()))
self.end_msg (True)
else:
self.end_msg ("Don't know how to check", 'YELLOW')
@conf
def check_ndnx(self,*k,**kw):
if not self.env['CC']:
self.fatal('load a c compiler first, conf.load("compiler_c")')
var=kw.get('uselib_store', 'NDNX')
self.start_msg('Checking for NDNx')
root = self.ndnx_get_root(*k,**kw);
self.env.NDNX_VERSION=self.ndnx_get_version(root)
self.env['INCLUDES_%s' % var]= '%s/%s' % (root, "include");
self.env['LIB_%s' % var] = "ccn"
self.env['LIBPATH_%s' % var] = '%s/%s' % (root, "lib")
self.env['%s_ROOT' % var] = root
self.end_msg("%s in %s " % (self.env.NDNX_VERSION, root))
if Logs.verbose:
Logs.pprint('CYAN',' NDNx include : %s'%self.env['INCLUDES_%s' % var])
Logs.pprint('CYAN',' NDNx lib : %s'%self.env['LIB_%s' % var])
Logs.pprint('CYAN',' NDNx libpath : %s'%self.env['LIBPATH_%s' % var])
def options(opt):
"""
NDNx options
"""
ndnopt = opt.add_option_group("NDNx Options")
ndnopt.add_option('--ndnx',type='string',default=None,dest='ndnx_dir',help='''path to where NDNx is installed, e.g. /usr/local''')
ndnopt.add_option('--openssl',type='string',default='',dest='openssl',help='''path to openssl, should be the same NDNx is compiled against''')
-71
View File
@@ -1,71 +0,0 @@
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
import waflib
from waflib.Configure import conf
from waflib import Utils,Logs,Errors
@conf
def _print_optional_features(conf):
# Write a summary of optional features status
print "---- Summary of optional NS-3 features:"
Logs.pprint ('RED', "---- Summary of optional NS-3 features:")
# for (name, caption, was_enabled, reason_not_enabled) in conf.env['NS3_OPTIONAL_FEATURES']:
# if was_enabled:
# status = 'enabled'
# else:
# status = 'not enabled (%s)' % reason_not_enabled
# print "%-30s: %s" % (caption, status)
@conf
def _check_dependencies(conf, required, mandatory):
# Logs.pprint ('CYAN', ' + %s' % required)
found = []
libversion = "optimized"
if conf.options.ns3_debug:
libversion = "debug"
for module in required:
retval = conf.check_cfg(package = 'libns3-dev-%s-%s' % (module, libversion),
args='--cflags --libs', mandatory=mandatory,
msg="Checking for ns3-%s" % module,
uselib_store='NS3_%s' % module.upper())
# Logs.pprint ('CYAN', 'NS3_%s' % module.upper())
if not retval is None:
found.append(module)
import copy
if not 'NS3_MODULES_FOUND' in conf.env:
conf.env['NS3_MODULES_FOUND'] = []
conf.env['NS3_MODULES_FOUND'] = conf.env['NS3_MODULES_FOUND'] + copy.copy(found)
def modules_uselib(bld, names):
return ['NS3_%s' % name.upper() for name in names] + \
['NS3_LIBRARY_%s' % name.upper() for name in names] + \
['NS3_HEADERS_%s' % name.upper() for name in names]
def modules_found(bld, needed):
for module in needed:
if not module in bld.env['NS3_MODULES_FOUND']:
return False
return True
@conf
def check_modules(conf, modules, mandatory = True):
import os
if not 'NS3_CHECK_MODULE_ONCE' in conf.env:
conf.env['NS3_CHECK_MODULE_ONCE'] = ''
conf.check_cfg(atleast_pkgconfig_version='0.0.0')
if conf.options.log4cxx:
conf.env.append_value('DEFINES', 'NS3_LOG_ENABLE')
conf._check_dependencies(modules, mandatory)
conf._print_optional_features
@conf
def print_ns3_feature_summary(conf):
Logs.pprint ('CYAN', "---- Summary of optional NS-3 features:")
conf._print_optional_features
-72
View File
@@ -1,72 +0,0 @@
# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
#! /usr/bin/env python
# encoding: utf-8
'''
When using this tool, the wscript will look like:
def options(opt):
opt.tool_options("protobuf", tooldir=["waf-tools"])
def configure(conf):
conf.load("compiler_cxx protobuf")
def build(bld):
bld(source="main.cpp", target="app", use="PROTOBUF")
Options are generated, in order to specify the location of protobuf includes/libraries.
'''
from waflib import Utils, TaskGen, Task, Logs
from waflib import Utils,Logs,Errors
from waflib.Configure import conf
def options(opt):
pass
def configure(conf):
"""
"""
conf.check_cfg(package='protobuf', args=['--cflags', '--libs'], uselib_store='PROTOBUF', mandatory=True)
conf.find_program ('protoc', var='PROTOC', path_list = conf.env['PATH'], mandatory = True)
@TaskGen.extension('.proto')
def add_proto(self, node):
"""
Compile PROTOBUF protocol specifications
"""
prototask = self.create_task ("protobuf", node, node.change_ext (".pb"))
try:
self.compiled_tasks.append (prototask)
except AttributeError:
self.compiled_tasks = [prototask]
class protobuf(Task.Task):
"""
Task for compiling PROTOBUF protocol specifications
"""
run_str = '${PROTOC} --cpp_out ${TGT[0].parent.abspath()} --proto_path ${SRC[0].parent.abspath()} ${SRC[0].abspath()} -o${TGT[0].abspath()}'
color = 'BLUE'
@TaskGen.feature('cxxshlib')
@TaskGen.before_method('process_source')
def dynamic_post(self):
if not getattr(self, 'dynamic_source', None):
return
self.source = Utils.to_list(self.source)
src = self.bld.path.get_bld().ant_glob (Utils.to_list(self.dynamic_source))
for cc in src:
# Signature for the source
cc.sig = Utils.h_file (cc.abspath())
# Signature for the header
h = cc.change_ext (".h")
h.sig = Utils.h_file (h.abspath())
self.source.extend (src)
+75 -166
View File
@@ -3,59 +3,42 @@
VERSION='0.0.1'
APPNAME='sync'
from waflib import Build, Logs
from waflib import Configure, Build, Logs
def options(opt):
opt.add_option('--debug',action='store_true',default=False,dest='debug',help='''debugging mode''')
opt.add_option('--log4cxx', action='store_true',default=False,dest='log4cxx',help='''Compile with log4cxx/native NS3 logging support''')
opt.add_option('--ns3', action='store_true',default=False,dest='ns3_enable',help='''Compile as NS-3 module''')
opt.add_option('--ns3-debug', action='store_true',default=False,dest='ns3_debug',help='''Link against debug NS3 libraries. Optimized version will be used otherwise''')
opt.add_option('--test', action='store_true',default=False,dest='_test',help='''build unit tests''')
opt.load('compiler_c')
opt.load('compiler_cxx')
opt.load('boost')
opt.load('doxygen')
opt.load('gnu_dirs')
opt.load('ccnx ns3 protobuf', tooldir=["waf-tools"])
opt.load('compiler_c compiler_cxx boost doxygen gnu_dirs protoc')
opt.load('ndnx', tooldir=["waf-tools"])
syncopt = opt.add_option_group ("ChronoSync Options")
syncopt.add_option('--debug',action='store_true',default=False,dest='debug',help='''debugging mode''')
syncopt.add_option('--log4cxx', action='store_true',default=False,dest='log4cxx',help='''Compile with log4cxx''')
syncopt.add_option('--test', action='store_true',default=False,dest='_test',help='''build unit tests''')
def configure(conf):
conf.load("compiler_cxx")
conf.load('gnu_dirs')
if not conf.check_cfg(package='openssl', args=['--cflags', '--libs'], uselib_store='SSL', mandatory=False):
libcrypto = conf.check_cc(lib='crypto',
header_name='openssl/crypto.h',
define_name='HAVE_SSL',
uselib_store='SSL')
if not conf.get_define ("HAVE_SSL"):
conf.fatal ("Cannot find SSL libraries")
conf.load('boost')
if conf.options.ns3_enable:
conf.load('ns3')
conf.define('NS3_MODULE', 1)
conf.check_modules(['core', 'network', 'internet'], mandatory = True)
conf.check_modules(['NDNabstraction'], mandatory = True)
conf.check_modules(['point-to-point'], mandatory = False)
conf.check_modules(['point-to-point-layout'], mandatory = False)
conf.check_boost(lib='system iostreams thread')
conf.define ('NS3_LOG_ENABLE', 1)
else:
conf.check_boost(lib='system iostreams test thread')
conf.load ('ccnx')
conf.check_ccnx (path=conf.options.ccnx_dir)
if conf.options.log4cxx:
conf.check_cfg(package='liblog4cxx', args=['--cflags', '--libs'], uselib_store='LOG4CXX', mandatory=True)
conf.load('compiler_c compiler_cxx gnu_dirs boost')
conf.load('ndnx')
if conf.options.debug:
conf.define ('_DEBUG', 1)
conf.env.append_value('CXXFLAGS', ['-O0', '-g3'])
conf.add_supported_cxxflags (cxxflags = ['-O0',
'-Wall',
'-Wno-unused-variable',
'-g3',
'-Wno-unused-private-field', # only clang supports
'-fcolor-diagnostics', # only clang supports
'-Qunused-arguments' # only clang supports
])
else:
conf.env.append_value('CXXFLAGS', ['-O3', '-g'])
conf.add_supported_cxxflags (cxxflags = ['-O3', '-g'])
conf.check_ndnx ()
conf.check_openssl ()
conf.check_boost(lib='system iostreams test thread')
if conf.options.log4cxx:
conf.check_cfg(package='liblog4cxx', args=['--cflags', '--libs'], uselib_store='LOG4CXX', mandatory=True)
if conf.options._test:
conf.define('_TEST', 1)
@@ -65,134 +48,45 @@ def configure(conf):
except:
pass
conf.load('protobuf')
conf.load('protoc')
def build (bld):
bld.post_mode = Build.POST_LAZY
bld.add_group ("protobuf")
x = bld (
features = ["protobuf"],
source = ["model/sync-state.proto"],
target = ["model/sync-state.pb"],
libsync = bld (
target=APPNAME,
features=['cxx', 'cxxshlib'],
source = ant_glob (['src/**/*.cc', 'src/**/*.proto']),
use = 'BOOST BOOST_IOSTREAMS BOOST_THREAD SSL NDNX',
includes = ['include', 'src'],
)
# Unit tests
if bld.get_define("_TEST"):
unittests = bld.program (
target="unit-tests",
source = bld.path.ant_glob(['tests/**/*.cc']),
features=['cxx', 'cxxprogram'],
use = 'BOOST_TEST sync',
includes = ['include', 'src'],
)
bld.add_group ("code")
if bld.get_define ("NS3_MODULE"):
libsync = bld.shlib (
target = "sync-ns3",
features=['cxx', 'cxxshlib'],
source = [
'ns3/sync-ccnx-wrapper.cc',
'ns3/sync-ns3-name-info.cc',
'ns3/sync-scheduler.cc',
'ns3/sync-logic-helper.cc',
# 'model/sync-app-data-fetch.cc',
# 'model/sync-app-data-publish.cc',
# 'ns3/sync-app.cc',
'model/sync-diff-leaf.cc',
'model/sync-diff-state.cc',
'model/sync-digest.cc',
'model/sync-full-leaf.cc',
'model/sync-full-state.cc',
'model/sync-interest-table.cc',
'model/sync-leaf.cc',
'model/sync-logic.cc',
'model/sync-name-info.cc',
'model/sync-seq-no.cc',
'model/sync-state.cc',
'model/sync-std-name-info.cc',
],
dynamic_source = [
'model/sync-state.pb.cc',
],
use = 'BOOST BOOST_IOSTREAMS SSL PROTOBUF ' + ' '.join (['ns3_'+dep for dep in ['core', 'network', 'internet', 'NDNabstraction']]).upper (),
includes = ['include', 'model', 'include/ns3', 'helper'],
)
example = bld.program (
target = "sync-example",
features=['cxx', 'cxxprogram'],
source = ['examples/sync-example.cc'],
use = 'libsync',
includes = ['include', 'model', 'include/ns3', 'helper'],
)
sync_eval = bld.program (
target = "sync-eval",
features=['cxx', 'cxxprogram'],
source = ['evaluation/sync-eval.cc',
'evaluation/standard-muc.cc',
'evaluation/sync-muc.cc',
],
use = 'libsync',
includes = ['include', 'model', 'include/ns3', 'helper'],
)
# from waflib import Utils,Logs,Errors
# Logs.pprint ('CYAN', program.use)
else:
libsync = bld (
target=APPNAME,
features=['cxx', 'cxxshlib'],
source = [
'ccnx/sync-ccnx-wrapper.cc',
'ccnx/sync-scheduler.cc',
'ccnx/sync-log.cc',
'ccnx/sync-app-socket-c.cc',
'ccnx/sync-app-socket.cc',
'model/sync-diff-leaf.cc',
'model/sync-diff-state.cc',
'model/sync-digest.cc',
'model/sync-full-leaf.cc',
'model/sync-full-state.cc',
'model/sync-interest-table.cc',
'model/sync-leaf.cc',
'model/sync-logic.cc',
'model/sync-name-info.cc',
'model/sync-seq-no.cc',
'model/sync-state.cc',
'model/sync-std-name-info.cc',
],
dynamic_source = [
'model/sync-state.pb.cc',
],
use = 'BOOST BOOST_IOSTREAMS BOOST_THREAD SSL PROTOBUF CCNX',
includes = ['include', 'model', 'helper'],
)
# Unit tests
if bld.get_define ("HAVE_LOG4CXX"):
libsync.use += ' LOG4CXX'
if bld.get_define("_TEST"):
unittests = bld.program (
target="unit-tests",
source = bld.path.ant_glob(['test/**/*.cc']),
features=['cxx', 'cxxprogram'],
use = 'BOOST_TEST sync',
includes = ['include', 'model', 'helper'],
)
unittests.use += ' LOG4CXX'
if bld.get_define ("HAVE_LOG4CXX"):
libsync.use += ' LOG4CXX'
if bld.get_define("_TEST"):
unittests.use += ' LOG4CXX'
headers = bld.path.ant_glob(['include/*.h'])
headers.extend (bld.path.get_bld().ant_glob(['model/sync-state.pb.h']))
bld.install_files ("%s/sync" % bld.env['INCLUDEDIR'], headers)
headers = bld.path.ant_glob(['include/*.h'])
headers.extend (bld.path.get_bld().ant_glob(['model/sync-state.pb.h']))
bld.install_files ("%s/sync" % bld.env['INCLUDEDIR'], headers)
pc = bld (
features = "subst",
source='libsync.pc.in',
target='libsync.pc',
install_path = '${LIBDIR}/pkgconfig',
PREFIX = bld.env['PREFIX'],
INCLUDEDIR = "%s/sync" % bld.env['INCLUDEDIR'],
VERSION = VERSION,
)
pc = bld (
features = "subst",
source='libsync.pc.in',
target='libsync.pc',
install_path = '${LIBDIR}/pkgconfig',
PREFIX = bld.env['PREFIX'],
INCLUDEDIR = "%s/sync" % bld.env['INCLUDEDIR'],
VERSION = VERSION,
)
# doxygen docs
from waflib.Build import BuildContext
@@ -206,3 +100,18 @@ def doxygen (bld):
bld (features="doxygen",
doxyfile='doc/doxygen.conf',
output_dir = 'doc')
@Configure.conf
def add_supported_cxxflags(self, cxxflags):
"""
Check which cxxflags are supported by compiler and add them to env.CXXFLAGS variable
"""
self.start_msg('Checking allowed flags for c++ compiler')
supportedFlags = []
for flag in cxxflags:
if self.check_cxx (cxxflags=[flag], mandatory=False):
supportedFlags += [flag]
self.end_msg (' '.join (supportedFlags))
self.env.CXXFLAGS += supportedFlags