Adding boost logging support for NLSR
diff --git a/boost.py b/boost.py
new file mode 100644
index 0000000..c714b5b
--- /dev/null
+++ b/boost.py
@@ -0,0 +1,373 @@
+#!/usr/bin/env python
+# encoding: utf-8
+#
+# partially based on boost.py written by Gernot Vormayr
+# written by Ruediger Sonderfeld <ruediger@c-plusplus.de>, 2008
+# modified by Bjoern Michaelsen, 2008
+# modified by Luca Fossati, 2008
+# rewritten for waf 1.5.1, Thomas Nagy, 2008
+# rewritten for waf 1.6.2, Sylvain Rouquette, 2011
+
+'''
+
+This is an extra tool, not bundled with the default waf binary.
+To add the boost tool to the waf file:
+$ ./waf-light --tools=compat15,boost
+ or, if you have waf >= 1.6.2
+$ ./waf update --files=boost
+
+When using this tool, the wscript will look like:
+
+ def options(opt):
+ opt.load('compiler_cxx boost')
+
+ def configure(conf):
+ conf.load('compiler_cxx boost')
+ conf.check_boost(lib='system filesystem')
+
+ def build(bld):
+ bld(source='main.cpp', target='app', use='BOOST')
+
+Options are generated, in order to specify the location of boost includes/libraries.
+The `check_boost` configuration function allows to specify the used boost libraries.
+It can also provide default arguments to the --boost-static and --boost-mt command-line arguments.
+Everything will be packaged together in a BOOST component that you can use.
+
+When using MSVC, a lot of compilation flags need to match your BOOST build configuration:
+ - you may have to add /EHsc to your CXXFLAGS or define boost::throw_exception if BOOST_NO_EXCEPTIONS is defined.
+ Errors: C4530
+ - boost libraries will try to be smart and use the (pretty but often not useful) auto-linking feature of MSVC
+ So before calling `conf.check_boost` you might want to disabling by adding:
+ conf.env.DEFINES_BOOST += ['BOOST_ALL_NO_LIB']
+ Errors:
+ - boost might also be compiled with /MT, which links the runtime statically.
+ If you have problems with redefined symbols,
+ self.env['DEFINES_%s' % var] += ['BOOST_ALL_NO_LIB']
+ self.env['CXXFLAGS_%s' % var] += ['/MD', '/EHsc']
+Passing `--boost-linkage_autodetect` might help ensuring having a correct linkage in some basic cases.
+
+'''
+
+import sys
+import re
+from waflib import Utils, Logs, Errors
+from waflib.Configure import conf
+
+BOOST_LIBS = ['/usr/lib', '/usr/local/lib', '/opt/local/lib', '/sw/lib', '/lib', '/usr/lib/x86_64-linux-gnu', '/usr/lib/i386-linux-gnu', '/usr/local/ndn/lib']
+BOOST_INCLUDES = ['/usr/include', '/usr/local/include', '/opt/local/include', '/sw/include', '/usr/local/ndn/include']
+BOOST_VERSION_FILE = 'boost/version.hpp'
+BOOST_VERSION_CODE = '''
+#include <iostream>
+#include <boost/version.hpp>
+int main() { std::cout << BOOST_LIB_VERSION << std::endl; }
+'''
+
+# toolsets from {boost_dir}/tools/build/v2/tools/common.jam
+PLATFORM = Utils.unversioned_sys_platform()
+detect_intel = lambda env: (PLATFORM == 'win32') and 'iw' or 'il'
+detect_clang = lambda env: (PLATFORM == 'darwin') and 'clang-darwin' or 'clang'
+detect_mingw = lambda env: (re.search('MinGW', env.CXX[0])) and 'mgw' or 'gcc'
+BOOST_TOOLSETS = {
+ 'borland': 'bcb',
+ 'clang': detect_clang,
+ 'como': 'como',
+ 'cw': 'cw',
+ 'darwin': 'xgcc',
+ 'edg': 'edg',
+ 'g++': detect_mingw,
+ 'gcc': detect_mingw,
+ 'icpc': detect_intel,
+ 'intel': detect_intel,
+ 'kcc': 'kcc',
+ 'kylix': 'bck',
+ 'mipspro': 'mp',
+ 'mingw': 'mgw',
+ 'msvc': 'vc',
+ 'qcc': 'qcc',
+ 'sun': 'sw',
+ 'sunc++': 'sw',
+ 'tru64cxx': 'tru',
+ 'vacpp': 'xlc'
+}
+
+
+def options(opt):
+ opt = opt.add_option_group('Boost Options')
+
+ opt.add_option('--boost-includes', type='string',
+ default='', dest='boost_includes',
+ help='''path to the boost includes root (~boost root)
+ e.g. /path/to/boost_1_47_0''')
+ opt.add_option('--boost-libs', type='string',
+ default='', dest='boost_libs',
+ help='''path to the directory where the boost libs are
+ e.g. /path/to/boost_1_47_0/stage/lib''')
+ opt.add_option('--boost-static', action='store_true',
+ default=False, dest='boost_static',
+ help='link with static boost libraries (.lib/.a)')
+ opt.add_option('--boost-mt', action='store_true',
+ default=False, dest='boost_mt',
+ help='select multi-threaded libraries')
+ opt.add_option('--boost-abi', type='string', default='', dest='boost_abi',
+ help='''select libraries with tags (dgsyp, d for debug),
+ see doc Boost, Getting Started, chapter 6.1''')
+ opt.add_option('--boost-linkage_autodetect', action="store_true", dest='boost_linkage_autodetect',
+ help="auto-detect boost linkage options (don't get used to it / might break other stuff)")
+ opt.add_option('--boost-toolset', type='string',
+ default='', dest='boost_toolset',
+ help='force a toolset e.g. msvc, vc90, \
+ gcc, mingw, mgw45 (default: auto)')
+ py_version = '%d%d' % (sys.version_info[0], sys.version_info[1])
+ opt.add_option('--boost-python', type='string',
+ default=py_version, dest='boost_python',
+ help='select the lib python with this version \
+ (default: %s)' % py_version)
+
+
+@conf
+def __boost_get_version_file(self, d):
+ dnode = self.root.find_dir(d)
+ if dnode:
+ return dnode.find_node(BOOST_VERSION_FILE)
+ return None
+
+@conf
+def boost_get_version(self, d):
+ """silently retrieve the boost version number"""
+ node = self.__boost_get_version_file(d)
+ if node:
+ try:
+ txt = node.read()
+ except (OSError, IOError):
+ Logs.error("Could not read the file %r" % node.abspath())
+ else:
+ re_but = re.compile('^#define\\s+BOOST_LIB_VERSION\\s+"(.*)"', re.M)
+ m = re_but.search(txt)
+ if m:
+ return m.group(1)
+ return self.check_cxx(fragment=BOOST_VERSION_CODE, includes=[d], execute=True, define_ret=True)
+
+@conf
+def boost_get_includes(self, *k, **kw):
+ includes = k and k[0] or kw.get('includes', None)
+ if includes and self.__boost_get_version_file(includes):
+ return includes
+ for d in Utils.to_list(self.environ.get('INCLUDE', '')) + BOOST_INCLUDES:
+ if self.__boost_get_version_file(d):
+ return d
+ if includes:
+ self.end_msg('headers not found in %s' % includes)
+ self.fatal('The configuration failed')
+ else:
+ self.end_msg('headers not found, please provide a --boost-includes argument (see help)')
+ self.fatal('The configuration failed')
+
+
+@conf
+def boost_get_toolset(self, cc):
+ toolset = cc
+ if not cc:
+ build_platform = Utils.unversioned_sys_platform()
+ if build_platform in BOOST_TOOLSETS:
+ cc = build_platform
+ else:
+ cc = self.env.CXX_NAME
+ if cc in BOOST_TOOLSETS:
+ toolset = BOOST_TOOLSETS[cc]
+ return isinstance(toolset, str) and toolset or toolset(self.env)
+
+
+@conf
+def __boost_get_libs_path(self, *k, **kw):
+ ''' return the lib path and all the files in it '''
+ if 'files' in kw:
+ return self.root.find_dir('.'), Utils.to_list(kw['files'])
+ libs = k and k[0] or kw.get('libs', None)
+ if libs:
+ path = self.root.find_dir(libs)
+ files = path.ant_glob('*boost_*')
+ if not libs or not files:
+ for d in Utils.to_list(self.environ.get('LIB', [])) + BOOST_LIBS:
+ path = self.root.find_dir(d)
+ if path:
+ files = path.ant_glob('*boost_*')
+ if files:
+ break
+ path = self.root.find_dir(d + '64')
+ if path:
+ files = path.ant_glob('*boost_*')
+ if files:
+ break
+ if not path:
+ if libs:
+ self.end_msg('libs not found in %s' % libs)
+ self.fatal('The configuration failed')
+ else:
+ self.end_msg('libs not found, please provide a --boost-libs argument (see help)')
+ self.fatal('The configuration failed')
+
+ self.to_log('Found the boost path in %r with the libraries:' % path)
+ for x in files:
+ self.to_log(' %r' % x)
+ return path, files
+
+@conf
+def boost_get_libs(self, *k, **kw):
+ '''
+ return the lib path and the required libs
+ according to the parameters
+ '''
+ path, files = self.__boost_get_libs_path(**kw)
+ t = []
+ if kw.get('mt', False):
+ t.append('mt')
+ if kw.get('abi', None):
+ t.append(kw['abi'])
+ tags = t and '(-%s)+' % '-'.join(t) or ''
+ toolset = self.boost_get_toolset(kw.get('toolset', ''))
+ toolset_pat = '(-%s[0-9]{0,3})+' % toolset
+ version = '(-%s)+' % self.env.BOOST_VERSION
+
+ def find_lib(re_lib, files):
+ for file in files:
+ if re_lib.search(file.name):
+ self.to_log('Found boost lib %s' % file)
+ return file
+ return None
+
+ def format_lib_name(name):
+ if name.startswith('lib') and self.env.CC_NAME != 'msvc':
+ name = name[3:]
+ return name[:name.rfind('.')]
+
+ libs = []
+ for lib in Utils.to_list(k and k[0] or kw.get('lib', None)):
+ py = (lib == 'python') and '(-py%s)+' % kw['python'] or ''
+ # Trying libraries, from most strict match to least one
+ for pattern in ['boost_%s%s%s%s%s' % (lib, toolset_pat, tags, py, version),
+ 'boost_%s%s%s%s' % (lib, tags, py, version),
+ 'boost_%s%s%s' % (lib, tags, version),
+ # Give up trying to find the right version
+ 'boost_%s%s%s%s' % (lib, toolset_pat, tags, py),
+ 'boost_%s%s%s' % (lib, tags, py),
+ 'boost_%s%s' % (lib, tags)]:
+ self.to_log('Trying pattern %s' % pattern)
+ file = find_lib(re.compile(pattern), files)
+ if file:
+ libs.append(format_lib_name(file.name))
+ break
+ else:
+ self.end_msg('lib %s not found in %s' % (lib, path.abspath()))
+ self.fatal('The configuration failed')
+
+ return path.abspath(), libs
+
+
+@conf
+def check_boost(self, *k, **kw):
+ """
+ Initialize boost libraries to be used.
+
+ Keywords: you can pass the same parameters as with the command line (without "--boost-").
+ Note that the command line has the priority, and should preferably be used.
+ """
+ if not self.env['CXX']:
+ self.fatal('load a c++ compiler first, conf.load("compiler_cxx")')
+
+ params = {'lib': k and k[0] or kw.get('lib', None)}
+ for key, value in self.options.__dict__.items():
+ if not key.startswith('boost_'):
+ continue
+ key = key[len('boost_'):]
+ params[key] = value and value or kw.get(key, '')
+
+ var = kw.get('uselib_store', 'BOOST')
+
+ self.start_msg('Checking boost includes')
+ self.env['INCLUDES_%s' % var] = inc = self.boost_get_includes(**params)
+ self.env.BOOST_VERSION = self.boost_get_version(inc)
+ self.end_msg(self.env.BOOST_VERSION)
+ if Logs.verbose:
+ Logs.pprint('CYAN', ' path : %s' % self.env['INCLUDES_%s' % var])
+
+ if not params['lib']:
+ return
+ self.start_msg('Checking boost libs')
+ suffix = params.get('static', None) and 'ST' or ''
+ path, libs = self.boost_get_libs(**params)
+ self.env['%sLIBPATH_%s' % (suffix, var)] = [path]
+ self.env['%sLIB_%s' % (suffix, var)] = libs
+ self.end_msg('ok')
+ if Logs.verbose:
+ Logs.pprint('CYAN', ' path : %s' % path)
+ Logs.pprint('CYAN', ' libs : %s' % libs)
+
+
+ def try_link():
+ if 'system' in params['lib']:
+ self.check_cxx(
+ fragment="\n".join([
+ '#include <boost/system/error_code.hpp>',
+ 'int main() { boost::system::error_code c; }',
+ ]),
+ use=var,
+ execute=False,
+ )
+ if 'thread' in params['lib']:
+ self.check_cxx(
+ fragment="\n".join([
+ '#include <boost/thread.hpp>',
+ 'int main() { boost::thread t; }',
+ ]),
+ use=var,
+ execute=False,
+ )
+
+ if params.get('linkage_autodetect', False):
+ self.start_msg("Attempting to detect boost linkage flags")
+ toolset = self.boost_get_toolset(kw.get('toolset', ''))
+ if toolset in ['vc']:
+ # disable auto-linking feature, causing error LNK1181
+ # because the code wants to be linked against
+ self.env['DEFINES_%s' % var] += ['BOOST_ALL_NO_LIB']
+
+ # if no dlls are present, we guess the .lib files are not stubs
+ has_dlls = False
+ for x in Utils.listdir(path):
+ if x.endswith(self.env.cxxshlib_PATTERN % ''):
+ has_dlls = True
+ break
+ if not has_dlls:
+ self.env['STLIBPATH_%s' % var] = [path]
+ self.env['STLIB_%s' % var] = libs
+ del self.env['LIB_%s' % var]
+ del self.env['LIBPATH_%s' % var]
+
+ # we attempt to play with some known-to-work CXXFLAGS combinations
+ for cxxflags in (['/MD', '/EHsc'], []):
+ self.env.stash()
+ self.env["CXXFLAGS_%s" % var] += cxxflags
+ try:
+ try_link()
+ self.end_msg("ok: winning cxxflags combination: %s" % (self.env["CXXFLAGS_%s" % var]))
+ e = None
+ break
+ except Errors.ConfigurationError as exc:
+ self.env.revert()
+ e = exc
+
+ if e is not None:
+ self.end_msg("Could not auto-detect boost linking flags combination, you may report it to boost.py author", ex=e)
+ self.fatal('The configuration failed')
+ else:
+ self.end_msg("Boost linkage flags auto-detection not implemented (needed ?) for this toolchain")
+ self.fatal('The configuration failed')
+ else:
+ self.start_msg('Checking for boost linkage')
+ try:
+ try_link()
+ except Errors.ConfigurationError as e:
+ self.end_msg("Could not link against boost libraries using supplied options")
+ self.fatal('The configuration failed')
+ self.end_msg('ok')
+
diff --git a/boost.pyc b/boost.pyc
new file mode 100644
index 0000000..f1ee3d3
--- /dev/null
+++ b/boost.pyc
Binary files differ
diff --git a/ndnx.py b/ndnx.py
new file mode 100644
index 0000000..fccad90
--- /dev/null
+++ b/ndnx.py
@@ -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='ndn/ndn.h'
+NDNX_VERSION_CODE='''
+#include <ndn/ndn.h>
+#include <stdio.h>
+int main() { printf ("%d.%d.%d", ((NDN_API_VERSION/100000) % 100), ((NDN_API_VERSION/1000) % 100), (NDN_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)
+ ndnd_crypto = otool ('%s/bin/ndnd' % self.env['%s_ROOT' % ndn_var])
+
+ if ndnd_crypto != selected_crypto:
+ self.fatal ("Selected openssl does not match used to compile NDNx (%s != %s)" %
+ (selected_crypto.strip (), ndnd_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)
+ ndnd_crypto = ldd ('%s/bin/ndnd' % self.env['%s_ROOT' % ndn_var])
+
+ if ndnd_crypto != selected_crypto:
+ self.fatal ("Selected openssl does not match used to compile NDNx (%s != %s)" %
+ (selected_crypto.strip (), ndnd_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] = "ndn"
+ 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''')
diff --git a/ndnx.pyc b/ndnx.pyc
new file mode 100644
index 0000000..80fa8fe
--- /dev/null
+++ b/ndnx.pyc
Binary files differ
diff --git a/src/nlsr.cpp b/src/nlsr.cpp
index f1b5d93..569a40a 100644
--- a/src/nlsr.cpp
+++ b/src/nlsr.cpp
@@ -95,7 +95,7 @@
nlsr.getConfParameter().buildRouterPrefix();
nlsr.getLsdb().setLsaRefreshTime(nlsr.getConfParameter().getLsaRefreshTime());
nlsr.getFib().setFibEntryRefreshTime(2*nlsr.getConfParameter().getLsaRefreshTime());
- nlsr.getFib().scheduleFibRefreshing(nlsr, 60);
+ //nlsr.getFib().scheduleFibRefreshing(nlsr, 60);
nlsr.getLsdb().setThisRouterPrefix(nlsr.getConfParameter().getRouterPrefix());
/* debugging purpose start */
diff --git a/src/nlsr.hpp b/src/nlsr.hpp
index 5ff2ef7..31655f4 100644
--- a/src/nlsr.hpp
+++ b/src/nlsr.hpp
@@ -15,6 +15,7 @@
#include "nlsr_rt.hpp"
#include "nlsr_npt.hpp"
#include "nlsr_fib.hpp"
+#include "nlsr_logger.hpp"
//testing
#include "nlsr_test.hpp"
@@ -45,6 +46,7 @@
, routingTable()
, npt()
, fib()
+ , nlsrLogger()
, nlsrTesting()
{
isDaemonProcess=false;
@@ -196,6 +198,11 @@
{
isRouteCalculationScheduled=ircs;
}
+
+ NlsrLogger& getNlsrLogger()
+ {
+ return nlsrLogger;
+ }
private:
ConfParameter confParam;
@@ -216,7 +223,7 @@
RoutingTable routingTable;
Npt npt;
Fib fib;
-
+ NlsrLogger nlsrLogger;
long int adjBuildCount;
int isBuildAdjLsaSheduled;
diff --git a/src/nlsr_fe.hpp b/src/nlsr_fe.hpp
index 8392dfb..2297315 100644
--- a/src/nlsr_fe.hpp
+++ b/src/nlsr_fe.hpp
@@ -3,6 +3,7 @@
#include<list>
#include <iostream>
+#include <ndn-cpp-dev/util/scheduler.hpp>
#include "nlsr_nexthop.hpp"
#include "nlsr_nhl.hpp"
@@ -15,6 +16,7 @@
FibEntry()
: name()
, timeToRefresh(0)
+ , feSeqNo(0)
{
}
@@ -43,11 +45,33 @@
timeToRefresh=ttr;
}
+ void setFeExpiringEventId(ndn::EventId feid)
+ {
+ feExpiringEventId=feid;
+ }
+
+ ndn::EventId getFeExpiringEventId()
+ {
+ return feExpiringEventId;
+ }
+
+ void setFeSeqNo(int fsn)
+ {
+ feSeqNo=fsn;
+ }
+
+ int getFeSeqNo()
+ {
+ return feSeqNo;
+ }
+
bool isEqualNextHops(Nhl &nhlOther);
private:
string name;
int timeToRefresh;
+ ndn::EventId feExpiringEventId;
+ int feSeqNo;
Nhl nhl;
};
diff --git a/src/nlsr_fib.cpp b/src/nlsr_fib.cpp
index 399584f..fd4b209 100644
--- a/src/nlsr_fib.cpp
+++ b/src/nlsr_fib.cpp
@@ -5,6 +5,7 @@
#include "nlsr.hpp"
using namespace std;
+using namespace ndn;
static bool
fibEntryNameCompare(FibEntry& fe, string name)
@@ -12,10 +13,28 @@
return fe.getName() == name ;
}
+void
+Fib::cancelScheduledFeExpiringEvent(nlsr& pnlsr, EventId eid)
+{
+ pnlsr.getScheduler().cancelEvent(eid);
+}
+ndn::EventId
+Fib::scheduleFibEntryRefreshing(nlsr& pnlsr, string name, int feSeqNum, int refreshTime)
+{
+ return pnlsr.getScheduler().scheduleEvent(ndn::time::seconds(refreshTime),
+ ndn::bind(&Fib::refreshFibEntry,this,name,feSeqNum));
+}
+
+void
+Fib::refreshFibEntry(string name, int feSeqNum)
+{
+
+}
+
void
-Fib::removeFromFib(string name)
+Fib::removeFromFib(nlsr& pnlsr, string name)
{
std::list<FibEntry >::iterator it = std::find_if( fibTable.begin(),
fibTable.end(), bind(&fibEntryNameCompare, _1, name));
@@ -26,13 +45,14 @@
{
//remove entry from NDN-FIB
}
+ cancelScheduledFeExpiringEvent(pnlsr, (*it).getFeExpiringEventId());
fibTable.erase(it);
}
}
void
-Fib::updateFib(string name, Nhl& nextHopList, int maxFacesPerPrefix)
+Fib::updateFib(nlsr& pnlsr,string name, Nhl& nextHopList, int maxFacesPerPrefix)
{
int startFace=0;
int endFace=getNumberOfFacesForName(nextHopList,maxFacesPerPrefix);
@@ -56,6 +76,11 @@
(*it).setTimeToRefresh(fibEntryRefreshTime);
}
(*it).getNhl().sortNhl();
+ cancelScheduledFeExpiringEvent(pnlsr, (*it).getFeExpiringEventId());
+ (*it).setFeSeqNo((*it).getFeSeqNo()+1);
+ (*it).setFeExpiringEventId(scheduleFibEntryRefreshing(pnlsr,
+ (*it).getName() ,
+ (*it).getFeSeqNo(),fibEntryRefreshTime));
//update NDN-FIB
}
else
@@ -70,39 +95,18 @@
}
newEntry.getNhl().sortNhl();
newEntry.setTimeToRefresh(fibEntryRefreshTime);
+ newEntry.setFeSeqNo(1);
fibTable.push_back(newEntry);
+
+ //cancelScheduledFeExpiringEvent(pnlsr, newEntry().getFeExpiringEventId());
+
//Update NDN-FIB
}
}
-void
-Fib::refreshFib(nlsr& pnlsr)
-{
- for ( std::list<FibEntry >::iterator it = fibTable.begin() ;
- it != fibTable.end() ; ++it)
- {
- (*it).setTimeToRefresh((*it).getTimeToRefresh()-60);
- if( (*it).getTimeToRefresh() < 0 )
- {
- cout<<"Refreshing FIB entry : "<<endl;
- cout<<(*it)<<endl;
- (*it).setTimeToRefresh(fibEntryRefreshTime);
- //update NDN-FIB
- }
- }
- printFib();
- scheduleFibRefreshing(pnlsr,60);
-}
-void
-Fib::scheduleFibRefreshing(nlsr& pnlsr, int refreshTime)
-{
- pnlsr.getScheduler().scheduleEvent(ndn::time::seconds(refreshTime),
- ndn::bind(&Fib::refreshFib,this,boost::ref(pnlsr)));
-}
-
-void Fib::cleanFib()
+void Fib::cleanFib(nlsr& pnlsr)
{
for( std::list<FibEntry >::iterator it=fibTable.begin(); it != fibTable.end();
++it)
@@ -110,6 +114,7 @@
for(std::list<NextHop>::iterator nhit=(*it).getNhl().getNextHopList().begin();
nhit != (*it).getNhl().getNextHopList().begin(); nhit++)
{
+ cancelScheduledFeExpiringEvent(pnlsr,(*it).getFeExpiringEventId());
//remove entry from NDN-FIB
}
}
diff --git a/src/nlsr_fib.hpp b/src/nlsr_fib.hpp
index 453b7db..d02d040 100644
--- a/src/nlsr_fib.hpp
+++ b/src/nlsr_fib.hpp
@@ -7,6 +7,7 @@
class nlsr;
using namespace std;
+using namespace ndn;
class Fib
{
@@ -15,10 +16,9 @@
{
}
- void removeFromFib(string name);
- void updateFib(string name, Nhl& nextHopList, int maxFacesPerPrefix);
- void scheduleFibRefreshing(nlsr& pnlsr, int refreshTime);
- void cleanFib();
+ void removeFromFib(nlsr& pnlsr, string name);
+ void updateFib(nlsr& pnlsr, string name, Nhl& nextHopList, int maxFacesPerPrefix);
+ void cleanFib(nlsr& pnlsr);
void setFibEntryRefreshTime(int fert)
{
fibEntryRefreshTime=fert;
@@ -29,7 +29,10 @@
private:
void removeFibEntryHop(Nhl& nl, int doNotRemoveHopFaceId);
int getNumberOfFacesForName(Nhl& nextHopList, int maxFacesPerPrefix);
- void refreshFib(nlsr& pnlsr);
+ ndn::EventId
+ scheduleFibEntryRefreshing(nlsr& pnlsr, string name, int feSeqNum, int refreshTime);
+ void cancelScheduledFeExpiringEvent(nlsr& pnlsr, EventId eid);
+ void refreshFibEntry(string name, int feSeqNum);
private:
std::list<FibEntry> fibTable;
diff --git a/src/nlsr_im.cpp b/src/nlsr_im.cpp
index 6ae0131..886aca8 100644
--- a/src/nlsr_im.cpp
+++ b/src/nlsr_im.cpp
@@ -147,7 +147,7 @@
void
interestManager::scheduleInfoInterest(nlsr& pnlsr, int seconds)
{
- pnlsr.getScheduler().scheduleEvent(ndn::time::seconds(seconds),
+ EventId eid=pnlsr.getScheduler().scheduleEvent(ndn::time::seconds(seconds),
ndn::bind(&interestManager::sendScheduledInfoInterest, this,
boost::ref(pnlsr),seconds));
}
diff --git a/src/nlsr_logger.cpp b/src/nlsr_logger.cpp
new file mode 100644
index 0000000..af263cd
--- /dev/null
+++ b/src/nlsr_logger.cpp
@@ -0,0 +1,58 @@
+#include "nlsr_logger.hpp"
+
+
+string
+NlsrLogger::getEpochTime()
+{
+ std::stringstream ss;
+ boost::posix_time::ptime time_t_epoch(boost::gregorian::date(1970,1,1));
+ boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
+ boost::posix_time::time_duration diff = now - time_t_epoch;
+ ss<<diff.total_seconds()<<"."<<boost::format("%06i")%(diff.total_microseconds()%1000000);
+ return ss.str();
+}
+
+string
+NlsrLogger::getUserHomeDirectory()
+{
+ string homeDirPath(getpwuid(getuid())->pw_dir);
+ if( homeDirPath.empty() )
+ {
+ homeDirPath = getenv("HOME");
+ }
+
+ return homeDirPath;
+}
+
+void
+NlsrLogger::initNlsrLogger(std::string dirPath)
+{
+ string logDirPath(dirPath);
+ if( dirPath.empty() )
+ {
+ logDirPath=getUserHomeDirectory();
+ }
+
+ typedef sinks::synchronous_sink< sinks::text_file_backend > file_sink;
+ shared_ptr< file_sink > sink(new file_sink(
+ keywords::file_name = "NLSR%Y%m%d%H%M%S_%3N.log", // file name pattern
+ keywords::rotation_size = 128 * 1024 * 1024 ,// rotation size, in characters
+ keywords::time_based_rotation = sinks::file::rotation_at_time_point(12, 0, 0)
+ ));
+
+ sink->locked_backend()->set_file_collector(sinks::file::make_collector(
+ keywords::target = logDirPath, // where to store rotated files
+ keywords::max_size = 64 * 1024 * 1024 * 1024, // maximum total size of the stored files, in bytes
+ keywords::min_free_space = 128 * 1024 * 1024 // minimum free space on the drive, in bytes
+ ));
+
+ sink->set_formatter
+ (
+ expr::format("%1%: %2%")
+ % getEpochTime()
+ % expr::smessage
+ );
+
+ // Add it to the core
+ logging::core::get()->add_sink(sink);
+}
diff --git a/src/nlsr_logger.hpp b/src/nlsr_logger.hpp
new file mode 100644
index 0000000..119f172
--- /dev/null
+++ b/src/nlsr_logger.hpp
@@ -0,0 +1,59 @@
+#ifndef NLSR_LOGGER_HPP
+#define NLSR_LOGGER_HPP
+
+#define BOOST_LOG_DYN_LINK 1
+
+#include <stdexcept>
+#include <string>
+#include <iostream>
+#include <sstream>
+#include <pwd.h>
+#include <cstdlib>
+#include <string>
+#include <unistd.h>
+#include <boost/format.hpp>
+#include <boost/smart_ptr/shared_ptr.hpp>
+#include <boost/date_time/posix_time/posix_time.hpp>
+#include <boost/date_time/local_time/local_time.hpp>
+#include <boost/log/common.hpp>
+#include <boost/log/expressions.hpp>
+#include <boost/log/attributes.hpp>
+#include <boost/log/sources/logger.hpp>
+#include <boost/log/sinks/sync_frontend.hpp>
+#include <boost/log/sinks/text_file_backend.hpp>
+
+namespace logging = boost::log;
+namespace attrs = boost::log::attributes;
+namespace src = boost::log::sources;
+namespace sinks = boost::log::sinks;
+namespace expr = boost::log::expressions;
+namespace keywords = boost::log::keywords;
+
+using boost::shared_ptr;
+using namespace std;
+
+
+
+class NlsrLogger
+{
+public:
+ NlsrLogger()
+ {
+ }
+
+ void initNlsrLogger(std::string dirPath);
+
+ boost::log::sources::logger& getLogger()
+ {
+ return mLogger;
+ }
+
+private:
+ string getEpochTime();
+ string getUserHomeDirectory();
+
+private:
+ boost::log::sources::logger mLogger;
+};
+
+#endif
diff --git a/src/nlsr_lsa.hpp b/src/nlsr_lsa.hpp
index 0f3e528..b80d5a9 100644
--- a/src/nlsr_lsa.hpp
+++ b/src/nlsr_lsa.hpp
@@ -1,11 +1,13 @@
#ifndef NLSR_LSA_HPP
#define NLSR_LSA_HPP
+#include <ndn-cpp-dev/util/scheduler.hpp>
#include "nlsr_adjacent.hpp"
#include "nlsr_npl.hpp"
#include "nlsr_adl.hpp"
using namespace std;
+using namespace ndn;
class Lsa{
public:
@@ -13,6 +15,7 @@
: origRouter()
, lsSeqNo()
, lifeTime()
+ , lsaExpiringEventId()
{
}
@@ -56,12 +59,24 @@
{
lifeTime=lt;
}
- //string getLsaKey();
+
+ void setLsaExpiringEventId(ndn::EventId leei)
+ {
+ lsaExpiringEventId=leei;
+ }
+
+ ndn::EventId getLsaExpiringEventId()
+ {
+ return lsaExpiringEventId;
+ }
+
+
protected:
string origRouter;
uint8_t lsType;
uint32_t lsSeqNo;
uint32_t lifeTime;
+ ndn::EventId lsaExpiringEventId;
};
class NameLsa:public Lsa{
diff --git a/src/nlsr_lsdb.cpp b/src/nlsr_lsdb.cpp
index 9e3ffe7..de1343a 100644
--- a/src/nlsr_lsdb.cpp
+++ b/src/nlsr_lsdb.cpp
@@ -5,6 +5,12 @@
using namespace std;
+void
+Lsdb::cancelScheduleLsaExpiringEvent(nlsr& pnlsr, EventId eid)
+{
+ pnlsr.getScheduler().cancelEvent(eid);
+}
+
static bool
nameLsaCompareByKey(NameLsa& nlsa1, string& key){
return nlsa1.getNameLsaKey()==key;
@@ -42,10 +48,10 @@
}
-void
+ndn::EventId
Lsdb::scheduleNameLsaExpiration(nlsr& pnlsr, string key, int seqNo, int expTime)
{
- pnlsr.getScheduler().scheduleEvent(ndn::time::seconds(expTime),
+ return pnlsr.getScheduler().scheduleEvent(ndn::time::seconds(expTime),
ndn::bind(&Lsdb::exprireOrRefreshNameLsa,
this,boost::ref(pnlsr), key, seqNo));
}
@@ -76,8 +82,8 @@
{
timeToExpire=nlsa.getLifeTime();
}
- scheduleNameLsaExpiration( pnlsr, nlsa.getNameLsaKey(),
- nlsa.getLsSeqNo(), timeToExpire);
+ nlsa.setLsaExpiringEventId(scheduleNameLsaExpiration( pnlsr,
+ nlsa.getNameLsaKey(), nlsa.getLsSeqNo(), timeToExpire));
}
else
{
@@ -131,8 +137,10 @@
{
timeToExpire=nlsa.getLifeTime();
}
- scheduleNameLsaExpiration( pnlsr, nlsa.getNameLsaKey(),
- nlsa.getLsSeqNo(), timeToExpire);
+ cancelScheduleLsaExpiringEvent(pnlsr,
+ chkNameLsa.first.getLsaExpiringEventId());
+ chkNameLsa.first.setLsaExpiringEventId(scheduleNameLsaExpiration( pnlsr,
+ nlsa.getNameLsaKey(), nlsa.getLsSeqNo(), timeToExpire));
}
}
@@ -242,10 +250,10 @@
return std::make_pair(boost::ref(clsa),false);
}
-void
+ndn::EventId
Lsdb::scheduleCorLsaExpiration(nlsr& pnlsr, string key, int seqNo, int expTime)
{
- pnlsr.getScheduler().scheduleEvent(ndn::time::seconds(expTime),
+ return pnlsr.getScheduler().scheduleEvent(ndn::time::seconds(expTime),
ndn::bind(&Lsdb::exprireOrRefreshCorLsa,
this,boost::ref(pnlsr),key,seqNo));
}
@@ -298,8 +306,11 @@
{
timeToExpire=clsa.getLifeTime();
}
- scheduleCorLsaExpiration(pnlsr,clsa.getCorLsaKey(),
- clsa.getLsSeqNo(), timeToExpire);
+ cancelScheduleLsaExpiringEvent(pnlsr,
+ chkCorLsa.first.getLsaExpiringEventId());
+ chkCorLsa.first.setLsaExpiringEventId(scheduleCorLsaExpiration(pnlsr,
+ clsa.getCorLsaKey(),
+ clsa.getLsSeqNo(), timeToExpire));
}
}
@@ -444,10 +455,10 @@
-void
+ndn::EventId
Lsdb::scheduleAdjLsaExpiration(nlsr& pnlsr, string key, int seqNo, int expTime)
{
- pnlsr.getScheduler().scheduleEvent(ndn::time::seconds(expTime),
+ return pnlsr.getScheduler().scheduleEvent(ndn::time::seconds(expTime),
ndn::bind(&Lsdb::exprireOrRefreshAdjLsa,
this,boost::ref(pnlsr),key,seqNo));
}
@@ -489,8 +500,10 @@
{
timeToExpire=alsa.getLifeTime();
}
- scheduleAdjLsaExpiration(pnlsr,alsa.getAdjLsaKey(),
- alsa.getLsSeqNo(),timeToExpire);
+ cancelScheduleLsaExpiringEvent(pnlsr,
+ chkAdjLsa.first.getLsaExpiringEventId());
+ chkAdjLsa.first.setLsaExpiringEventId(scheduleAdjLsaExpiration(pnlsr,
+ alsa.getAdjLsaKey(), alsa.getLsSeqNo(),timeToExpire));
}
}
diff --git a/src/nlsr_lsdb.hpp b/src/nlsr_lsdb.hpp
index 62c91ee..a9c8fb3 100644
--- a/src/nlsr_lsdb.hpp
+++ b/src/nlsr_lsdb.hpp
@@ -54,16 +54,21 @@
bool addAdjLsa(AdjLsa &alsa);
bool doesAdjLsaExist(string key);
-
- void scheduleNameLsaExpiration(nlsr& pnlsr, string key, int seqNo, int expTime);
+
+ ndn::EventId
+ scheduleNameLsaExpiration(nlsr& pnlsr, string key, int seqNo, int expTime);
void exprireOrRefreshNameLsa(nlsr& pnlsr, string lsaKey, int seqNo);
- void scheduleAdjLsaExpiration(nlsr& pnlsr, string key, int seqNo, int expTime);
+ ndn::EventId
+ scheduleAdjLsaExpiration(nlsr& pnlsr, string key, int seqNo, int expTime);
void exprireOrRefreshAdjLsa(nlsr& pnlsr, string lsaKey, int seqNo);
- void scheduleCorLsaExpiration(nlsr& pnlsr, string key, int seqNo, int expTime);
+ ndn::EventId
+ scheduleCorLsaExpiration(nlsr& pnlsr, string key, int seqNo, int expTime);
void exprireOrRefreshCorLsa(nlsr& pnlsr, string lsaKey, int seqNo);
private:
+ void cancelScheduleLsaExpiringEvent(nlsr& pnlsr, EventId eid);
+
std::list<NameLsa> nameLsdb;
std::list<AdjLsa> adjLsdb;
std::list<CorLsa> corLsdb;
diff --git a/src/nlsr_npt.cpp b/src/nlsr_npt.cpp
index ba516e5..697d11c 100644
--- a/src/nlsr_npt.cpp
+++ b/src/nlsr_npt.cpp
@@ -28,7 +28,7 @@
newEntry.generateNhlfromRteList();
npteList.push_back(newEntry);
// update FIB here with nhl list newEntry.getNhl()
- pnlsr.getFib().updateFib(name,newEntry.getNhl(),
+ pnlsr.getFib().updateFib(pnlsr, name,newEntry.getNhl(),
pnlsr.getConfParameter().getMaxFacesPerPrefix());
}
else
@@ -36,7 +36,7 @@
(*it).addRoutingTableEntry(rte);
(*it).generateNhlfromRteList();
// update FIB here with nhl list from (*it).getNhl()
- pnlsr.getFib().updateFib(name,(*it).getNhl() ,
+ pnlsr.getFib().updateFib(pnlsr, name,(*it).getNhl() ,
pnlsr.getConfParameter().getMaxFacesPerPrefix());
}
}
@@ -58,14 +58,14 @@
{
npteList.erase(it); // remove entry from NPT
// remove FIB entry with this name
- pnlsr.getFib().removeFromFib(name);
+ pnlsr.getFib().removeFromFib(pnlsr,name);
}
else
{
(*it).generateNhlfromRteList();
// update FIB entry with new NHL
- pnlsr.getFib().updateFib(name,(*it).getNhl(),
+ pnlsr.getFib().updateFib(pnlsr, name,(*it).getNhl(),
pnlsr.getConfParameter().getMaxFacesPerPrefix());
}
}
diff --git a/src/nlsr_params.hpp b/src/nlsr_params.hpp
deleted file mode 100644
index a5f11c5..0000000
--- a/src/nlsr_params.hpp
+++ /dev/null
@@ -1,12 +0,0 @@
-#ifndef NLSR_PARAMS_HPP
-#define NLSR_PARAMS_HPP
-
-class nlsrParams{
-
-
-
-
-
-};
-
-#endif
diff --git a/wscript b/wscript
index 79420c0..b82e73a 100644
--- a/wscript
+++ b/wscript
@@ -1,67 +1,50 @@
# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
-VERSION='1.0.0'
-APPNAME='nlsr'
-
-from waflib import Configure, Build, Logs
+from waflib import Build, Logs, Utils, Task, TaskGen, Configure
def options(opt):
- opt.load('compiler_cxx boost')
+ opt.load('compiler_c compiler_cxx gnu_dirs c_osx')
+ opt.load('boost', tooldir=['.waf-tools'])
- syncopt = opt.add_option_group ("nlsr Options")
-
- syncopt.add_option('--debug',action='store_true',default=False,dest='debug',help='''debugging mode''')
+ opt = opt.add_option_group('Options')
+ opt.add_option('--debug',action='store_true',default=False,dest='debug',help='''debugging mode''')
def configure(conf):
- conf.load('compiler_cxx boost')
+ conf.load("compiler_cxx boost gnu_dirs")
if conf.options.debug:
conf.define ('_DEBUG', 1)
- 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
- '-Wno-tautological-compare', # suppress warnings from CryptoPP
- '-Wno-deprecated-declarations'
- ])
+ flags = ['-O0',
+ '-Wall',
+ # '-Werror',
+ '-Wno-unused-variable',
+ '-g3',
+ '-Wno-unused-private-field', # only clang supports
+ '-fcolor-diagnostics', # only clang supports
+ '-Qunused-arguments', # only clang supports
+ '-Wno-tautological-compare', # suppress warnings from CryptoPP
+ '-Wno-unused-function', # another annoying warning from CryptoPP
+
+ '-Wno-deprecated-declarations',
+ ]
+
+ conf.add_supported_cxxflags (cxxflags = flags)
else:
- conf.add_supported_cxxflags (cxxflags = ['-O3',
- '-g',
- '-Wno-unused-variable',
- '-Wno-tautological-compare',
- '-Wno-unused-function',
- '-Wno-deprecated-declarations'
- ])
+ flags = ['-O3', '-g', '-Wno-tautological-compare','-Wno-unused-variable',
+ '-Wno-unused-function', '-Wno-deprecated-declarations']
+ conf.add_supported_cxxflags (cxxflags = flags)
- conf.check_cfg(package='libndn-cpp-dev', args=['--cflags', '--libs'], uselib_store='NDNCPP', mandatory=True)
-
- conf.check_boost(lib='system iostreams thread unit_test_framework', mandatory=True)
-
- conf.check_cfg(package='ChronoSync', args=['--cflags', '--libs'], uselib_store='ChronoSync', mandatory=True)
-
-
+ conf.check_cfg(package='libndn-cpp-dev', args=['--cflags', '--libs'], uselib_store='NDN_CPP', mandatory=True)
+ conf.check_boost(lib='system iostreams thread unit_test_framework log', uselib_store='BOOST', version='1_55', mandatory=True)
def build (bld):
bld (
- # vnum = "1.0.0",
features=['cxx', 'cxxprogram'],
target="nlsr",
- source = bld.path.ant_glob('src/*.cpp'),
- use = 'BOOST NDNCPP ChronoSync',
- #cwd = bld.path.find_dir ("src"),
- includes = ['src'],
+ source = bld.path.ant_glob('*.cpp'),
+ use = 'NDN_CPP BOOST',
)
- #bld.install_files (
- # dest = "%s/nlsr" % bld.env['INCLUDEDIR'],
- # files = bld.path.ant_glob(['*.hpp']),
- # cwd = bld.path.find_dir ("src"),
- # relative_trick = True,
- # )
-
@Configure.conf
def add_supported_cxxflags(self, cxxflags):
"""
@@ -76,3 +59,4 @@
self.end_msg (' '.join (supportedFlags))
self.env.CXXFLAGS += supportedFlags
+