ping: refactor ping client to use a modular architecture

refs #2702

Change-Id: I0ee0403f84eaec35bdbf07af7b3bb52558113452
diff --git a/tools/ping/client/ndn-ping.cpp b/tools/ping/client/ndn-ping.cpp
new file mode 100644
index 0000000..2115b81
--- /dev/null
+++ b/tools/ping/client/ndn-ping.cpp
@@ -0,0 +1,228 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2015,  Arizona Board of Regents.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-tools 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
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * @author: Jerald Paul Abraham <jeraldabraham@email.arizona.edu>
+ * @author: Eric Newberry <enewberry@email.arizona.edu>
+ */
+
+#include "core/common.hpp"
+#include "core/version.hpp"
+
+#include "ping.hpp"
+#include "statistics-collector.hpp"
+#include "tracer.hpp"
+
+namespace ndn {
+namespace ping {
+namespace client {
+
+static time::milliseconds
+getPingMinimumInterval()
+{
+  return time::milliseconds(1000);
+}
+
+static time::milliseconds
+getDefaultPingTimeoutThreshold()
+{
+  return time::milliseconds(4000);
+}
+
+static void
+usage(const boost::program_options::options_description& options)
+{
+  std::cout << "Usage: ndnping [options] ndn:/name/prefix\n"
+      "\n"
+      "Ping a NDN name prefix using Interests with name ndn:/name/prefix/ping/number.\n"
+      "The numbers in the Interests are randomly generated unless specified.\n"
+      "\n";
+  std::cout << options;
+  exit(2);
+}
+
+static void
+signalHandler(Face& face, StatisticsCollector& statisticsCollector)
+{
+  face.shutdown();
+  Statistics statistics = statisticsCollector.computeStatistics();
+  std::cout << statistics << "\n";
+
+  if (statistics.nReceived == statistics.nSent) {
+    exit(0);
+  }
+  else {
+    exit(1);
+  }
+}
+
+int
+main(int argc, char* argv[])
+{
+  Options options;
+  options.shouldAllowStaleData = false;
+  options.nPings = -1;
+  options.interval = time::milliseconds(getPingMinimumInterval());
+  options.timeout = time::milliseconds(getDefaultPingTimeoutThreshold());
+  options.startSeq = 0;
+  options.shouldGenerateRandomSeq = true;
+  options.shouldPrintTimestamp = false;
+
+  std::string identifier;
+
+  namespace po = boost::program_options;
+
+  po::options_description visibleOptDesc("Allowed options");
+  visibleOptDesc.add_options()
+    ("help,h", "print this message and exit")
+    ("version,V", "display version and exit")
+    ("interval,i", po::value<int>(),
+                   ("set ping interval in milliseconds (minimum " +
+                   std::to_string(getPingMinimumInterval().count()) + " ms)").c_str())
+    ("timeout,o", po::value<int>(),
+                  ("set ping timeout in milliseconds (default " +
+                  std::to_string(getDefaultPingTimeoutThreshold().count()) + " ms)").c_str())
+    ("count,c", po::value<int>(&options.nPings), "set total number of pings")
+    ("start,n", po::value<uint64_t>(&options.startSeq),
+                "set the starting seq number, the number is incremented by 1 after each Interest")
+    ("identifier,p", po::value<std::string>(&identifier),
+                     "add identifier to the Interest names before the numbers to avoid conflict")
+    ("cache,a", "allows routers to return stale Data from cache")
+    ("timestamp,t", "print timestamp with messages")
+  ;
+  po::options_description hiddenOptDesc("Hidden options");
+  hiddenOptDesc.add_options()
+    ("prefix", po::value<std::string>(), "prefix to send pings to")
+  ;
+
+  po::options_description optDesc("Allowed options");
+  optDesc.add(visibleOptDesc).add(hiddenOptDesc);
+
+  try {
+    po::positional_options_description optPos;
+    optPos.add("prefix", -1);
+
+    po::variables_map optVm;
+    po::store(po::command_line_parser(argc, argv).options(optDesc).positional(optPos).run(), optVm);
+    po::notify(optVm);
+
+    if (optVm.count("help") > 0) {
+      usage(visibleOptDesc);
+    }
+
+    if (optVm.count("version") > 0) {
+      std::cout << "ndnping " << tools::VERSION << std::endl;
+      exit(0);
+    }
+
+    if (optVm.count("prefix") > 0) {
+      options.prefix = Name(optVm["prefix"].as<std::string>());
+    }
+    else {
+      std::cerr << "ERROR: No prefix specified" << std::endl;
+      usage(visibleOptDesc);
+    }
+
+    if (optVm.count("interval") > 0) {
+      options.interval = time::milliseconds(optVm["interval"].as<int>());
+
+      if (options.interval.count() < getPingMinimumInterval().count()) {
+        std::cerr << "ERROR: Specified ping interval is less than the minimum " <<
+                     getPingMinimumInterval() << std::endl;
+        usage(visibleOptDesc);
+      }
+    }
+
+    if (optVm.count("timeout") > 0) {
+      options.timeout = time::milliseconds(optVm["timeout"].as<int>());
+    }
+
+    if (optVm.count("count") > 0) {
+      if (options.nPings <= 0) {
+        std::cerr << "ERROR: Number of ping must be positive" << std::endl;
+        usage(visibleOptDesc);
+      }
+    }
+
+    if (optVm.count("start") > 0) {
+      options.shouldGenerateRandomSeq = false;
+    }
+
+    if (optVm.count("identifier") > 0) {
+      bool isIdentifierAcceptable = std::all_of(identifier.begin(), identifier.end(), &isalnum);
+      if (identifier.empty() || !isIdentifierAcceptable) {
+        std::cerr << "ERROR: Unacceptable client identifier" << std::endl;
+        usage(visibleOptDesc);
+      }
+
+      options.clientIdentifier = name::Component(identifier);
+    }
+
+    if (optVm.count("cache") > 0) {
+      options.shouldAllowStaleData = true;
+    }
+
+    if (optVm.count("timestamp") > 0) {
+      options.shouldPrintTimestamp = true;
+    }
+  }
+  catch (const po::error& e) {
+    std::cerr << "ERROR: " << e.what() << std::endl;
+    usage(visibleOptDesc);
+  }
+
+  boost::asio::io_service ioService;
+  Face face(ioService);
+  Ping ping(face, options);
+  StatisticsCollector statisticsCollector(ping, options);
+  Tracer tracer(ping, options);
+
+  boost::asio::signal_set signalSet(face.getIoService(), SIGINT);
+  signalSet.async_wait(bind(&signalHandler, ref(face), ref(statisticsCollector)));
+
+  std::cout << "PING " << options.prefix << std::endl;
+
+  try {
+    ping.run();
+  }
+  catch (std::exception& e) {
+    tracer.onError(e.what());
+    face.getIoService().stop();
+    return 2;
+  }
+
+  Statistics statistics = statisticsCollector.computeStatistics();
+
+  std::cout << statistics << std::endl;
+
+  if (statistics.nReceived == statistics.nSent) {
+    return 0;
+  }
+  else {
+    return 1;
+  }
+}
+
+} // namespace client
+} // namespace ping
+} // namespace ndn
+
+int
+main(int argc, char** argv)
+{
+  return ndn::ping::client::main(argc, argv);
+}
diff --git a/tools/ping/client/ping.cpp b/tools/ping/client/ping.cpp
new file mode 100644
index 0000000..74cbcac
--- /dev/null
+++ b/tools/ping/client/ping.cpp
@@ -0,0 +1,123 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2015,  Arizona Board of Regents.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-tools 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
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * @author: Jerald Paul Abraham <jeraldabraham@email.arizona.edu>
+ * @author: Eric Newberry <enewberry@email.arizona.edu>
+ */
+
+#include "ping.hpp"
+
+namespace ndn {
+namespace ping {
+namespace client {
+
+Ping::Ping(Face& face, const Options& options)
+  : m_options(options)
+  , m_nSent(0)
+  , m_nextSeq(options.startSeq)
+  , m_nOutstanding(0)
+  , m_face(face)
+  , m_scheduler(m_face.getIoService())
+{
+  if (m_options.shouldGenerateRandomSeq) {
+    m_nextSeq = random::generateWord64();
+  }
+}
+
+void
+Ping::run()
+{
+  performPing();
+
+  m_face.processEvents();
+}
+
+void
+Ping::performPing()
+{
+  BOOST_ASSERT((m_options.nPings < 0) || (m_nSent < m_options.nPings));
+
+  Name pingPacketName = makePingName(m_nextSeq);
+
+  Interest interest(pingPacketName);
+  interest.setMustBeFresh(!m_options.shouldAllowStaleData);
+  interest.setInterestLifetime(m_options.timeout);
+  interest.setNonce(m_nextSeq);
+
+  m_face.expressInterest(interest,
+                         bind(&Ping::onData, this, _1, _2, m_nextSeq, time::steady_clock::now()),
+                         bind(&Ping::onTimeout, this, _1, m_nextSeq));
+
+  ++m_nSent;
+  ++m_nextSeq;
+  ++m_nOutstanding;
+
+  if ((m_options.nPings < 0) || (m_nSent < m_options.nPings)) {
+    m_scheduler.scheduleEvent(m_options.interval, bind(&Ping::performPing, this));
+  }
+  else {
+    finish();
+  }
+}
+
+void
+Ping::onData(const Interest& interest, Data& data, uint64_t seq, const time::steady_clock::TimePoint& sendTime)
+{
+  time::nanoseconds rtt = time::steady_clock::now() - sendTime;
+
+  afterResponse(seq, rtt);
+
+  finish();
+}
+
+void
+Ping::onTimeout(const Interest& interest, uint64_t seq)
+{
+  afterTimeout(seq);
+
+  finish();
+}
+
+void
+Ping::finish()
+{
+  if (--m_nOutstanding >= 0) {
+    return;
+  }
+
+  m_face.shutdown();
+  afterFinish();
+  m_face.getIoService().stop();
+}
+
+Name
+Ping::makePingName(uint64_t seq) const
+{
+  Name name(m_options.prefix);
+  name.append("ping");
+  if (!m_options.clientIdentifier.empty()) {
+    name.append(m_options.clientIdentifier);
+  }
+  name.append(std::to_string(seq));
+
+  return name;
+}
+
+} // namespace client
+} // namespace ping
+} // namespace ndn
diff --git a/tools/ping/client/ping.hpp b/tools/ping/client/ping.hpp
new file mode 100644
index 0000000..9d30067
--- /dev/null
+++ b/tools/ping/client/ping.hpp
@@ -0,0 +1,133 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2015,  Arizona Board of Regents.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-tools 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
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * @author: Jerald Paul Abraham <jeraldabraham@email.arizona.edu>
+ * @author: Eric Newberry <enewberry@email.arizona.edu>
+ */
+
+#ifndef NDN_TOOLS_PING_CLIENT_PING_HPP
+#define NDN_TOOLS_PING_CLIENT_PING_HPP
+
+#include "core/common.hpp"
+
+namespace ndn {
+namespace ping {
+namespace client {
+
+typedef time::duration<double, time::milliseconds::period> Rtt;
+
+/**
+ * @brief options for ndnping client
+ */
+struct Options
+{
+  Name prefix;                      //!< prefix pinged
+  bool shouldAllowStaleData;        //!< allow stale Data
+  bool shouldGenerateRandomSeq;     //!< random ping sequence
+  bool shouldPrintTimestamp;        //!< print timestamp
+  int nPings;                       //!< number of pings
+  time::milliseconds interval;      //!< ping interval
+  time::milliseconds timeout;       //!< timeout threshold
+  uint64_t startSeq;                //!< start ping sequence number
+  name::Component clientIdentifier; //!< client identifier
+};
+
+/**
+ * @brief NDN modular ping client
+ */
+class Ping : noncopyable
+{
+public:
+  Ping(Face& face, const Options& options);
+
+  /**
+   * Signals on the successful return of a packet
+   * @param seq ping sequence number
+   * @param rtt round trip time
+   */
+  signal::Signal<Ping, uint64_t, Rtt> afterResponse;
+
+  /**
+   * Signals on timeout of a packet
+   * @param seq ping sequence number
+   */
+  signal::Signal<Ping, uint64_t> afterTimeout;
+
+  /**
+   * Signals when finished pinging
+   */
+  signal::Signal<Ping> afterFinish;
+
+  /**
+   * Executes the pings
+   */
+  void
+  run();
+
+private:
+  /**
+   * Creates a ping Name from the sequence number
+   * @param seq ping sequence number
+   */
+  Name
+  makePingName(uint64_t seq) const;
+
+  /**
+   * Performs individual ping
+   */
+  void
+  performPing();
+
+  /**
+   * Called when ping returned successfully
+   * @param interest NDN interest
+   * @param data returned data
+   * @param seq ping sequence number
+   * @param sendTime time ping sent
+   */
+  void
+  onData(const Interest& interest, Data& data, uint64_t seq, const time::steady_clock::TimePoint& sendTime);
+
+  /**
+   * Called when ping timed out
+   * @param interest NDN interest
+   * @param seq ping sequence number
+   */
+  void
+  onTimeout(const Interest& interest, uint64_t seq);
+
+  /**
+   * Called after ping received or timed out
+   */
+  void
+  finish();
+
+private:
+  const Options& m_options;
+  int m_nSent;
+  uint64_t m_nextSeq;
+  int m_nOutstanding;
+  Face& m_face;
+  scheduler::Scheduler m_scheduler;
+};
+
+} // namespace client
+} // namespace ping
+} // namespace ndn
+
+#endif // NDN_TOOLS_PING_CLIENT_PING_HPP
diff --git a/tools/ping/client/statistics-collector.cpp b/tools/ping/client/statistics-collector.cpp
new file mode 100644
index 0000000..b02db12
--- /dev/null
+++ b/tools/ping/client/statistics-collector.cpp
@@ -0,0 +1,108 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2015,  Arizona Board of Regents.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-tools 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
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * @author: Eric Newberry <enewberry@email.arizona.edu>
+ * @author: Jerald Paul Abraham <jeraldabraham@email.arizona.edu>
+ */
+
+#include "statistics-collector.hpp"
+
+namespace ndn {
+namespace ping {
+namespace client {
+
+StatisticsCollector::StatisticsCollector(Ping& ping, const Options& options)
+  : m_ping(ping)
+  , m_options(options)
+  , m_nSent(0)
+  , m_nReceived(0)
+  , m_pingStartTime(time::steady_clock::now())
+  , m_minRtt(std::numeric_limits<double>::max())
+  , m_maxRtt(0.0)
+  , m_sumRtt(0.0)
+  , m_sumRttSquared(0.0)
+{
+  m_ping.afterResponse.connect(bind(&StatisticsCollector::recordResponse, this, _2));
+  m_ping.afterTimeout.connect(bind(&StatisticsCollector::recordTimeout, this));
+}
+
+void
+StatisticsCollector::recordResponse(Rtt rtt)
+{
+  m_nSent++;
+  m_nReceived++;
+
+  double rttMs = rtt.count();
+
+  m_minRtt = std::min(m_minRtt, rttMs);
+
+  m_maxRtt = std::max(m_maxRtt, rttMs);
+
+  m_sumRtt += rttMs;
+  m_sumRttSquared += rttMs * rttMs;
+}
+
+void
+StatisticsCollector::recordTimeout()
+{
+  m_nSent++;
+}
+
+Statistics
+StatisticsCollector::computeStatistics()
+{
+  Statistics statistics;
+
+  statistics.prefix = m_options.prefix;
+  statistics.nSent = m_nSent;
+  statistics.nReceived = m_nReceived;
+  statistics.pingStartTime = m_pingStartTime;
+  statistics.minRtt = m_minRtt;
+  statistics.maxRtt = m_maxRtt;
+  statistics.packetLossRate = (double)(m_nSent - m_nReceived) / (double)m_nSent;
+  statistics.sumRtt = m_sumRtt;
+  statistics.avgRtt = m_sumRtt / m_nReceived;
+  statistics.stdDevRtt = std::sqrt((m_sumRttSquared / m_nReceived) - (statistics.avgRtt * statistics.avgRtt));
+
+  return statistics;
+}
+
+std::ostream&
+operator<<(std::ostream& os, const Statistics& statistics)
+{
+  os << "\n";
+  os << "--- " << statistics.prefix <<" ping statistics ---\n";
+  os << statistics.nSent << " packets transmitted";
+  os << ", " << statistics.nReceived << " received";
+  os << ", " << statistics.packetLossRate * 100.0 << "% packet loss";
+  os << ", time " << statistics.sumRtt << " ms";
+  if (statistics.nReceived > 0) {
+    os << "\n";
+    os << "rtt min/avg/max/mdev = ";
+    os << statistics.minRtt << "/";
+    os << statistics.avgRtt << "/";
+    os << statistics.maxRtt << "/";
+    os << statistics.stdDevRtt << " ms";
+  }
+
+  return os;
+}
+
+} // namespace client
+} // namespace ping
+} // namespace ndn
diff --git a/tools/ping/client/statistics-collector.hpp b/tools/ping/client/statistics-collector.hpp
new file mode 100644
index 0000000..6e98577
--- /dev/null
+++ b/tools/ping/client/statistics-collector.hpp
@@ -0,0 +1,101 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2015,  Arizona Board of Regents.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-tools 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
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * @author: Eric Newberry <enewberry@email.arizona.edu>
+ * @author: Jerald Paul Abraham <jeraldabraham@email.arizona.edu>
+ */
+
+#ifndef NDN_TOOLS_PING_CLIENT_STATISTICS_COLLECTOR_HPP
+#define NDN_TOOLS_PING_CLIENT_STATISTICS_COLLECTOR_HPP
+
+#include "core/common.hpp"
+
+#include "ping.hpp"
+
+namespace ndn {
+namespace ping {
+namespace client {
+
+/**
+ * @brief statistics data
+ */
+struct Statistics
+{
+  Name prefix;                                  //!< prefix pinged
+  int nSent;                                    //!< number of pings sent
+  int nReceived;                                //!< number of pings received
+  time::steady_clock::TimePoint pingStartTime;  //!< time pings started
+  double minRtt;                                //!< minimum round trip time
+  double maxRtt;                                //!< maximum round trip time
+  double packetLossRate;                        //!< packet loss rate
+  double sumRtt;                                //!< sum of round trip times
+  double avgRtt;                                //!< average round trip time
+  double stdDevRtt;                             //!< std dev of round trip time
+};
+
+/**
+ * @brief collects statistics from ping client
+ */
+class StatisticsCollector : noncopyable
+{
+public:
+  /**
+   * @param ping NDN ping client
+   * @param options ping client options
+   */
+  StatisticsCollector(Ping& ping, const Options& options);
+
+  /**
+   * Called on ping response received
+   * @param rtt round trip time
+   */
+  void
+  recordResponse(Rtt rtt);
+
+  /**
+   * Called on ping timeout
+   */
+  void
+  recordTimeout();
+
+  /**
+   * Returns ping statistics as structure
+   */
+  Statistics
+  computeStatistics();
+
+private:
+  Ping& m_ping;
+  const Options& m_options;
+  int m_nSent;
+  int m_nReceived;
+  time::steady_clock::TimePoint m_pingStartTime;
+  double m_minRtt;
+  double m_maxRtt;
+  double m_sumRtt;
+  double m_sumRttSquared;
+};
+
+std::ostream&
+operator<<(std::ostream& os, const Statistics& statistics);
+
+} // namespace client
+} // namespace ping
+} // namespace ndn
+
+#endif // NDN_TOOLS_PING_CLIENT_STATISTICS_COLLECTOR_HPP
diff --git a/tools/ping/client/tracer.cpp b/tools/ping/client/tracer.cpp
new file mode 100644
index 0000000..c521b20
--- /dev/null
+++ b/tools/ping/client/tracer.cpp
@@ -0,0 +1,64 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2015,  Arizona Board of Regents.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-tools 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
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * @author: Eric Newberry <enewberry@email.arizona.edu>
+ */
+
+#include "tracer.hpp"
+
+namespace ndn {
+namespace ping {
+namespace client {
+
+Tracer::Tracer(Ping& ping, const Options& options)
+  : m_options(options)
+{
+  ping.afterResponse.connect(bind(&Tracer::onResponse, this, _1, _2));
+  ping.afterTimeout.connect(bind(&Tracer::onTimeout, this, _1));
+}
+
+void
+Tracer::onResponse(uint64_t seq, Rtt rtt)
+{
+  if (m_options.shouldPrintTimestamp) {
+    std::cout << time::toIsoString(time::system_clock::now()) << " - ";
+  }
+
+  std::cout << "content from " << m_options.prefix << ": seq=" << seq << " time="
+            << rtt.count() << " ms" << std::endl;
+}
+
+void
+Tracer::onTimeout(uint64_t seq)
+{
+  if (m_options.shouldPrintTimestamp) {
+    std::cout << time::toIsoString(time::system_clock::now()) << " - ";
+  }
+
+  std::cout << "timeout from " << m_options.prefix << ": seq=" << seq << std::endl;
+}
+
+void
+Tracer::onError(std::string msg)
+{
+  std::cerr << "ERROR: " << msg << std::endl;
+}
+
+} // namespace client
+} // namespace ping
+} // namespace ndn
diff --git a/tools/ping/client/tracer.hpp b/tools/ping/client/tracer.hpp
new file mode 100644
index 0000000..5a8cd35
--- /dev/null
+++ b/tools/ping/client/tracer.hpp
@@ -0,0 +1,74 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2015,  Arizona Board of Regents.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-tools 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
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * @author: Eric Newberry <enewberry@email.arizona.edu>
+ */
+
+#ifndef NDN_TOOLS_PING_CLIENT_TRACER_HPP
+#define NDN_TOOLS_PING_CLIENT_TRACER_HPP
+
+#include "core/common.hpp"
+
+#include "ping.hpp"
+
+namespace ndn {
+namespace ping {
+namespace client {
+
+/**
+ * @brief prints ping responses and timeouts
+ */
+class Tracer : noncopyable
+{
+public:
+  /**
+   * @param ping NDN ping client
+   * @param options ping client options
+   */
+  Tracer(Ping& ping, const Options& options);
+
+  /**
+   * Prints ping results when response received
+   * @param seq ping sequence number
+   * @param rtt round trip time
+   */
+  void
+  onResponse(uint64_t seq, Rtt rtt);
+
+  /**
+   * Prints ping results when timed out
+   * @param seq ping sequence number
+   */
+  void
+  onTimeout(uint64_t seq);
+
+  /**
+   * Outputs ping errors to cerr
+   */
+  void
+  onError(std::string msg);
+
+private:
+  const Options& m_options;
+};
+
+} // namespace client
+} // namespace ping
+} // namespace ndn
+
+#endif // NDN_TOOLS_PING_CLIENT_TRACER_HPP
diff --git a/tools/ping/ndn-ping.cpp b/tools/ping/ndn-ping.cpp
deleted file mode 100644
index 5d0908e..0000000
--- a/tools/ping/ndn-ping.cpp
+++ /dev/null
@@ -1,450 +0,0 @@
-/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
-/**
- * Copyright (c) 2014-2015,  Arizona Board of Regents.
- *
- * This file is part of ndn-tools (Named Data Networking Essential Tools).
- * See AUTHORS.md for complete list of ndn-tools authors and contributors.
- *
- * ndn-tools is free software: you can redistribute it and/or modify it under the terms
- * of the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * ndn-tools 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
- * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
- */
-/**
- * Copyright (C) 2014 Arizona Board of Regents
- *
- * This file is part of ndn-tlv-ping (Ping Application for Named Data Networking).
- *
- * ndn-tlv-ping is a free software: you can redistribute it and/or modify it under
- * the terms of the GNU General Public License as published by the Free Software
- * Foundation, either version 3 of the License, or (at your option) any later version.
- *
- * ndn-tlv-ping 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
- * ndn-tlv-ping, e.g., in LICENSE file.  If not, see <http://www.gnu.org/licenses/>.
- *
- * @author: Jerald Paul Abraham <jeraldabraham@email.arizona.edu>
- */
-
-#include "core/version.hpp"
-
-#include <boost/date_time/posix_time/posix_time.hpp>
-
-namespace ndn {
-namespace ping {
-
-class NdnPing : boost::noncopyable
-{
-public:
-  explicit
-  NdnPing(char* programName)
-    : m_programName(programName)
-    , m_isAllowCachingSet(false)
-    , m_isPrintTimestampSet(false)
-    , m_hasError(false)
-    , m_totalPings(-1)
-    , m_startPingNumber(-1)
-    , m_pingsSent(0)
-    , m_pingsReceived(0)
-    , m_pingInterval(getPingMinimumInterval())
-    , m_clientIdentifier(0)
-    , m_pingTimeoutThreshold(getPingTimeoutThreshold())
-    , m_outstanding(0)
-    , m_face(m_ioService)
-  {
-  }
-
-  class PingStatistics : boost::noncopyable
-  {
-  public:
-    explicit
-    PingStatistics()
-      : m_sentPings(0)
-      , m_receivedPings(0)
-      , m_pingStartTime(time::steady_clock::now())
-      , m_minimumRoundTripTime(std::numeric_limits<double>::max())
-      , m_averageRoundTripTimeData(0)
-      , m_standardDeviationRoundTripTimeData(0)
-    {
-    }
-
-    void
-    addToPingStatistics(time::nanoseconds roundTripNanoseconds)
-    {
-      double roundTripTime = roundTripNanoseconds.count() / 1000000.0;
-      if (roundTripTime < m_minimumRoundTripTime)
-        m_minimumRoundTripTime = roundTripTime;
-      if (roundTripTime > m_maximumRoundTripTime)
-        m_maximumRoundTripTime = roundTripTime;
-
-      m_averageRoundTripTimeData += roundTripTime;
-      m_standardDeviationRoundTripTimeData += roundTripTime * roundTripTime;
-    }
-
-  public:
-    int m_sentPings;
-    int m_receivedPings;
-    time::steady_clock::TimePoint m_pingStartTime;
-    double m_minimumRoundTripTime;
-    double m_maximumRoundTripTime;
-    double m_averageRoundTripTimeData;
-    double m_standardDeviationRoundTripTimeData;
-
-  };
-
-  void
-  usage()
-  {
-    std::cout << "\n Usage:\n " << m_programName << " ndn:/name/prefix [options]\n"
-        " Ping a NDN name prefix using Interests with name"
-        " ndn:/name/prefix/ping/number.\n"
-        " The numbers in the Interests are randomly generated unless specified.\n"
-        "   [-i interval]   - set ping interval in seconds (minimum "
-        << getPingMinimumInterval().count() << " milliseconds)\n"
-        "   [-c count]      - set total number of pings\n"
-        "   [-n number]     - set the starting number, the number is incremented by 1"
-        " after each Interest\n"
-        "   [-p identifier] - add identifier to the Interest names before the"
-        " numbers to avoid conflict\n"
-        "   [-a]            - allow routers to return stale Data from cache\n"
-        "   [-t]            - print timestamp with messages\n"
-        "   [-h]            - print this message and exit\n\n";
-    exit(1);
-  }
-
-  time::milliseconds
-  getPingMinimumInterval()
-  {
-    return time::milliseconds(1000);
-  }
-
-  time::milliseconds
-  getPingTimeoutThreshold()
-  {
-    return time::milliseconds(4000);
-  }
-
-  void
-  setTotalPings(int totalPings)
-  {
-    if (totalPings <= 0)
-      usage();
-
-    m_totalPings = totalPings;
-  }
-
-  void
-  setPingInterval(int pingInterval)
-  {
-    if (pingInterval < getPingMinimumInterval().count())
-      usage();
-
-    m_pingInterval = time::milliseconds(pingInterval);
-  }
-
-  void
-  setStartPingNumber(int64_t startPingNumber)
-  {
-    if (startPingNumber < 0)
-      usage();
-
-    m_startPingNumber = startPingNumber;
-  }
-
-  void
-  setAllowCaching()
-  {
-    m_isAllowCachingSet = true;
-  }
-
-  void
-  setPrintTimestamp()
-  {
-    m_isPrintTimestampSet = true;
-  }
-
-  void
-  setClientIdentifier(char* clientIdentifier)
-  {
-    m_clientIdentifier = clientIdentifier;
-
-    if (strlen(clientIdentifier) == 0)
-      usage();
-
-    while (*clientIdentifier != '\0') {
-      if (isalnum(*clientIdentifier) == 0)
-        usage();
-      clientIdentifier++;
-    }
-  }
-
-  void
-  setPrefix(char* prefix)
-  {
-    m_prefix = prefix;
-  }
-
-  bool
-  hasError() const
-  {
-    return m_hasError;
-  }
-
-
-  void
-  onData(const ndn::Interest& interest,
-         Data& data,
-         time::steady_clock::TimePoint timePoint)
-  {
-    std::string pingReference = interest.getName().toUri();
-    m_pingsReceived++;
-    m_pingStatistics.m_receivedPings++;
-    time::nanoseconds roundTripTime = time::steady_clock::now() - timePoint;
-
-    if (m_isPrintTimestampSet)
-      std::cout << time::toIsoString(time::system_clock::now())  << " - ";
-    std::cout << "Content From " << m_prefix;
-    std::cout << " - Ping Reference = " <<
-      interest.getName().getSubName(interest.getName().size()-1).toUri().substr(1);
-    std::cout << "  \t- Round Trip Time = " <<
-      roundTripTime.count() / 1000000.0 << " ms" << std::endl;
-
-    m_pingStatistics.addToPingStatistics(roundTripTime);
-    this->finish();
-  }
-
-  void
-  onTimeout(const ndn::Interest& interest)
-  {
-    if (m_isPrintTimestampSet)
-      std::cout << time::toIsoString(time::system_clock::now())  << " - ";
-    std::cout << "Timeout From " << m_prefix;
-    std::cout << " - Ping Reference = " <<
-      interest.getName().getSubName(interest.getName().size()-1).toUri().substr(1);
-    std::cout << std::endl;
-
-    this->finish();
-  }
-
-  void
-  printPingStatistics()
-  {
-    std::cout << "\n\n=== " << " Ping Statistics For "<< m_prefix <<" ===" << std::endl;
-    std::cout << "Sent=" << m_pingStatistics.m_sentPings;
-    std::cout << ", Received=" << m_pingStatistics.m_receivedPings;
-    double packetLossRate = m_pingStatistics.m_sentPings - m_pingStatistics.m_receivedPings;
-    packetLossRate /= m_pingStatistics.m_sentPings;
-    std::cout << ", Packet Loss=" << packetLossRate * 100.0 << "%";
-    if (m_pingStatistics.m_sentPings != m_pingStatistics.m_receivedPings)
-      m_hasError = true;
-    std::cout << ", Total Time=" << m_pingStatistics.m_averageRoundTripTimeData << " ms\n";
-    if (m_pingStatistics.m_receivedPings > 0) {
-      double averageRoundTripTime =
-        m_pingStatistics.m_averageRoundTripTimeData / m_pingStatistics.m_receivedPings;
-      double standardDeviationRoundTripTime =
-        m_pingStatistics.m_standardDeviationRoundTripTimeData / m_pingStatistics.m_receivedPings;
-      standardDeviationRoundTripTime -= averageRoundTripTime * averageRoundTripTime;
-      standardDeviationRoundTripTime = std::sqrt(standardDeviationRoundTripTime);
-      std::cout << "Round Trip Time (Min/Max/Avg/MDev) = (";
-      std::cout << m_pingStatistics.m_minimumRoundTripTime << "/";
-      std::cout << m_pingStatistics.m_maximumRoundTripTime << "/";
-      std::cout << averageRoundTripTime << "/";
-      std::cout << standardDeviationRoundTripTime << ") ms\n";
-    }
-    std::cout << std::endl;
-  }
-
-  void
-  performPing(boost::asio::deadline_timer* deadlineTimer)
-  {
-    if ((m_totalPings < 0) || (m_pingsSent < m_totalPings)) {
-      m_pingsSent++;
-      m_pingStatistics.m_sentPings++;
-
-      //Perform Ping
-      char pingNumberString[20];
-      Name pingPacketName(m_prefix);
-      pingPacketName.append("ping");
-      if (m_clientIdentifier != 0)
-        pingPacketName.append(m_clientIdentifier);
-      std::memset(pingNumberString, 0, 20);
-      if (m_startPingNumber < 0)
-        m_startPingNumber = std::rand();
-      sprintf(pingNumberString, "%lld", static_cast<long long int>(m_startPingNumber));
-      pingPacketName.append(pingNumberString);
-
-      ndn::Interest interest(pingPacketName);
-
-      if (m_isAllowCachingSet)
-        interest.setMustBeFresh(false);
-      else
-        interest.setMustBeFresh(true);
-
-      interest.setInterestLifetime(m_pingTimeoutThreshold);
-      interest.setNonce(m_startPingNumber);
-
-      m_startPingNumber++;
- 
-      try {
-        m_face.expressInterest(interest,
-                               std::bind(&NdnPing::onData, this, _1, _2,
-                                         time::steady_clock::now()),
-                               std::bind(&NdnPing::onTimeout, this, _1));
-        deadlineTimer->expires_at(deadlineTimer->expires_at() +
-                                  boost::posix_time::millisec(m_pingInterval.count()));
-        deadlineTimer->async_wait(bind(&NdnPing::performPing,
-                                       this,
-                                       deadlineTimer));
-      }
-      catch (std::exception& e) {
-        std::cerr << "ERROR: " << e.what() << std::endl;
-      }
-      ++m_outstanding;
-    }
-    else {
-      this->finish();
-    }
-  }
-
-  void
-  finish()
-  {
-    if (--m_outstanding >= 0) {
-      return;
-    }
-    m_face.shutdown();
-    printPingStatistics();
-    m_ioService.stop();
-  }
-
-  void
-  signalHandler()
-  {
-    m_face.shutdown();
-    printPingStatistics();
-    exit(1);
-  }
-
-  void
-  run()
-  {
-    std::cout << "\n=== Pinging " << m_prefix  << " ===\n" <<std::endl;
-
-    boost::asio::signal_set signalSet(m_ioService, SIGINT, SIGTERM);
-    signalSet.async_wait(bind(&NdnPing::signalHandler, this));
-
-    boost::asio::deadline_timer deadlineTimer(m_ioService,
-                                              boost::posix_time::millisec(0));
-
-    deadlineTimer.async_wait(bind(&NdnPing::performPing,
-                                  this,
-                                  &deadlineTimer));
-    try {
-      m_face.processEvents();
-    }
-    catch (std::exception& e) {
-      std::cerr << "ERROR: " << e.what() << std::endl;
-      m_hasError = true;
-      m_ioService.stop();
-    }
-  }
-
-private:
-  char* m_programName;
-  bool m_isAllowCachingSet;
-  bool m_isPrintTimestampSet;
-  bool m_hasError;
-  int m_totalPings;
-  int64_t m_startPingNumber;
-  int m_pingsSent;
-  int m_pingsReceived;
-  time::milliseconds m_pingInterval;
-  char* m_clientIdentifier;
-  time::milliseconds m_pingTimeoutThreshold;
-  char* m_prefix;
-  PingStatistics m_pingStatistics;
-  ssize_t m_outstanding;
-
-  boost::asio::io_service m_ioService;
-  Face m_face;
-};
-
-int
-main(int argc, char* argv[])
-{
-  std::srand(::time(0));
-  int res;
-
-  NdnPing program(argv[0]);
-  while ((res = getopt(argc, argv, "htai:c:n:p:V")) != -1)
-    {
-      switch (res) {
-      case 'a':
-        program.setAllowCaching();
-        break;
-      case 'c':
-        program.setTotalPings(atoi(optarg));
-        break;
-      case 'h':
-        program.usage();
-        break;
-      case 'i':
-        program.setPingInterval(atoi(optarg));
-        break;
-      case 'n':
-        try {
-          program.setStartPingNumber(boost::lexical_cast<int64_t>(optarg));
-        }
-        catch (boost::bad_lexical_cast&) {
-          program.usage();
-        }
-        break;
-      case 'p':
-        program.setClientIdentifier(optarg);
-        break;
-      case 't':
-        program.setPrintTimestamp();
-        break;
-      case 'V':
-        std::cout << "ndnping " << tools::VERSION << std::endl;
-        return 0;
-      default:
-        program.usage();
-        break;
-      }
-    }
-
-  argc -= optind;
-  argv += optind;
-
-  if (argv[0] == 0)
-    program.usage();
-
-  program.setPrefix(argv[0]);
-  program.run();
-
-  std::cout << std::endl;
-
-  if (program.hasError())
-    return 1;
-  else
-    return 0;
-}
-
-} // namespace ping
-} // namespace ndn
-
-int
-main(int argc, char** argv)
-{
-  return ndn::ping::main(argc, argv);
-}
diff --git a/tools/ping/wscript b/tools/ping/wscript
index 406537b..0301eeb 100644
--- a/tools/ping/wscript
+++ b/tools/ping/wscript
@@ -5,7 +5,7 @@
     bld.program(
         features='cxx',
         target='../../bin/ndnping',
-        source='ndn-ping.cpp',
+        source=bld.path.ant_glob('client/*.cpp'),
         use='core-objects',
         )