Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

We’re showing branches in this repository, but you can also compare across forks.

base: d09824eb67
...
compare: 49e4dfee7a
  • 11 commits
  • 26 files changed
  • 0 commit comments
  • 1 contributor
6 CMakeLists.txt
View
@@ -64,9 +64,9 @@ SET(PROTOBUF_REQUIRE_CPP TRUE)
FIND_PACKAGE(ProtocolBuffers REQUIRED)
INCLUDE_DIRECTORIES (${PROTOC_OUT_DIR}) # For generated protobuf headers.
-# Setup the glog package
-FIND_PACKAGE(Glog REQUIRED)
-INCLUDE_DIRECTORIES(${GLOG_INCLUDE_DIRS})
+# Setup the logging package
+FIND_PACKAGE(Log4cplus REQUIRED)
+INCLUDE_DIRECTORIES(${LOG4CLPUS_INCLUDE_DIRS})
FIND_PACKAGE(PkgConfig REQUIRED)
2  README
View
@@ -37,7 +37,7 @@ Build requirements (Ubuntu Package Names)
libboost-all-dev (>= 1.46, might work with earlier, may not need all modules)
libcrypto++-dev
libfuse-dev
- libgoogle-glog-dev
+ liblog4cplus-dev
libprotobuf-dev
pkg-config
2  bithorded/CMakeLists.txt
View
@@ -25,7 +25,7 @@ ADD_EXECUTABLE(bithorded
TARGET_LINK_LIBRARIES(bithorded
${Boost_LIBRARIES}
- ${GLOG_LIBRARIES}
+ ${LOG4CPLUS_LIBRARIES}
bithorde
)
3  bithorded/lib/randomaccessfile.cpp
View
@@ -73,7 +73,8 @@ ssize_t RandomAccessFile::write(uint64_t offset, void* src, size_t size)
{
BOOST_ASSERT( size <= WINDOW_SIZE );
ssize_t written = pwrite64(_fd, src, size, offset);
- BOOST_ASSERT( (size_t)written == size ); // TODO: Real error-handling
+ if ((size_t)written != size)
+ throw std::ios_base::failure("Failed to write");
return written;
}
7 bithorded/main.cpp
View
@@ -5,6 +5,7 @@
#include <iostream>
#include <crypto++/files.h>
+#include <log4cplus/configurator.h>
#include "buildconf.hpp"
#include "lib/hashes.h"
@@ -12,8 +13,6 @@
#include "server/config.hpp"
#include "server/server.hpp"
-#include <glog/logging.h>
-
using namespace std;
namespace asio = boost::asio;
namespace fs = boost::filesystem;
@@ -22,8 +21,8 @@ namespace po = boost::program_options;
using namespace bithorded;
int main(int argc, char* argv[]) {
- google::InitGoogleLogging(argv[0]);
- google::LogToStderr();
+ log4cplus::BasicConfigurator config;
+ config.configure();
try {
Config cfg(argc, argv);
44 bithorded/router/asset.cpp
View
@@ -17,52 +17,62 @@
#include "asset.hpp"
+#include <boost/foreach.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <utility>
-#include <glog/logging.h>
+#include <log4cplus/logger.h>
+#include <log4cplus/loggingmacros.h>
using namespace bithorded::router;
using namespace std;
+namespace bithorded { namespace router {
+ log4cplus::Logger assetLogger = log4cplus::Logger::getInstance("router");
+} }
+
bool bithorded::router::ForwardedAsset::hasUpstream(const std::string peername)
{
return _upstream.count(peername);
}
-void bithorded::router::ForwardedAsset::bindUpstream(const bithorded::Client::Ptr& f)
+void bithorded::router::ForwardedAsset::bindUpstreams(const std::map< string, bithorded::Client::Ptr >& friends, uint64_t uuid)
{
- if (f->requestsAsset(_ids)) // This path surely doesn't have the asset.
- return;
- auto upstream = new bithorde::ReadAsset(f, _ids);
- auto peername = f->peerName();
- upstream->statusUpdate.connect(boost::bind(&ForwardedAsset::onUpstreamStatus, this, peername, bithorde::ASSET_ARG_STATUS));
- upstream->dataArrived.connect(boost::bind(&ForwardedAsset::onData, this,
- bithorde::ASSET_ARG_OFFSET, bithorde::ASSET_ARG_DATA, bithorde::ASSET_ARG_TAG));
- auto& upstream_ = _upstream[peername];
- upstream_.reset(upstream);
- f->bind(*upstream_);
+ BOOST_FOREACH(auto f_, friends) {
+ auto f = f_.second;
+ if (f->requestsAsset(_ids)) // This path surely doesn't have the asset.
+ continue;
+ auto upstream = new bithorde::ReadAsset(f, _ids);
+ auto peername = f->peerName();
+ upstream->statusUpdate.connect(boost::bind(&ForwardedAsset::onUpstreamStatus, this, peername, bithorde::ASSET_ARG_STATUS));
+ upstream->dataArrived.connect(boost::bind(&ForwardedAsset::onData, this,
+ bithorde::ASSET_ARG_OFFSET, bithorde::ASSET_ARG_DATA, bithorde::ASSET_ARG_TAG));
+ auto& upstream_ = _upstream[peername];
+ upstream_.reset(upstream);
+ f->bind(*upstream_, uuid);
+ }
+ updateStatus();
}
void bithorded::router::ForwardedAsset::onUpstreamStatus(const string& peername, const bithorde::AssetStatus& status)
{
if (status.status() == bithorde::Status::SUCCESS) {
- DLOG(INFO) << "Found upstream " << peername;
+ LOG4CPLUS_DEBUG(assetLogger, "Found upstream " << peername);
if (status.has_size()) {
if (_size == -1) {
_size = status.size();
} else if (_size != (int64_t)status.size()) {
- LOG(WARNING) << peername << " responded with mismatching size, ignoring...";
+ LOG4CPLUS_WARN(assetLogger, peername << " responded with mismatching size, ignoring...");
_upstream.erase(peername);
}
} else {
- LOG(WARNING) << peername << " SUCCESS response not accompanied with asset-size.";
+ LOG4CPLUS_WARN(assetLogger, peername << " SUCCESS response not accompanied with asset-size.");
}
} else {
- DLOG(INFO) << "Failed upstream " << peername;
+ LOG4CPLUS_DEBUG(assetLogger, "Failed upstream " << peername);
_upstream.erase(peername);
}
- updateStatus();
+ updateStatus();
}
void bithorded::router::ForwardedAsset::updateStatus() {
2  bithorded/router/asset.hpp
View
@@ -57,7 +57,7 @@ class ForwardedAsset : public bithorded::Asset
{}
bool hasUpstream(const std::string peername);
- void bindUpstream(const bithorded::Client::Ptr& f);
+ void bindUpstreams(const std::map<std::string, Client::Ptr>& friends, uint64_t uuid);
virtual size_t can_read(uint64_t offset, size_t size);
virtual bool getIds(BitHordeIds& ids);
24 bithorded/router/router.cpp
View
@@ -22,7 +22,8 @@
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
-#include <glog/logging.h>
+#include <log4cplus/logger.h>
+#include <log4cplus/loggingmacros.h>
#include "../server/server.hpp"
@@ -33,6 +34,10 @@ using namespace std;
const boost::posix_time::seconds RECONNECT_INTERVAL(5);
+namespace bithorded { namespace router {
+ log4cplus::Logger routerLog = log4cplus::Logger::getInstance("router");
+} }
+
class bithorded::router::FriendConnector : public boost::enable_shared_from_this<bithorded::router::FriendConnector> {
Server& _server;
boost::shared_ptr<boost::asio::ip::tcp::socket> _socket;
@@ -106,7 +111,7 @@ void Router::onConnected(const bithorded::Client::Ptr& client )
{
string peerName = client->peerName();
if (_friends.count(peerName)) {
- LOG(INFO) << "Friend " << peerName << " connected" << endl;
+ LOG4CPLUS_INFO(routerLog, "Friend " << peerName << " connected");
if (_connectors[peerName].get())
_connectors[peerName]->cancel();
_connectors.erase(peerName);
@@ -121,26 +126,17 @@ void Router::onDisconnected(const bithorded::Client::Ptr& client)
_connectors[peerName] = FriendConnector::create(_server, _friends[peerName]);
}
-bithorded::Asset::Ptr bithorded::router::Router::findAsset(bithorde::BindRead req)
+bithorded::Asset::Ptr bithorded::router::Router::findAsset(const bithorde::BindRead& req)
{
if (_sessionMap.count(req.uuid()))
- return Asset::Ptr(); // TODO: Send proper statusCode WOULDLOOP
+ throw BindError(bithorde::WOULD_LOOP);
auto asset = boost::make_shared<ForwardedAsset, Router&, const BitHordeIds&>(*this, req.ids());
_sessionMap[req.uuid()] = asset;
- bindAsset(asset);
+ asset->bindUpstreams(_connectedFriends, req.uuid());
return asset;
}
-void Router::bindAsset(const bithorded::router::ForwardedAsset::Ptr& asset)
-{
- for (auto iter = _connectedFriends.begin(); iter != _connectedFriends.end(); iter++) {
- auto f = iter->second;
- if (!asset->hasUpstream(f->peerName()))
- asset->bindUpstream(f);
- }
-}
-
3  bithorded/router/router.hpp
View
@@ -53,8 +53,7 @@ class Router
void onConnected(const bithorded::Client::Ptr& client);
void onDisconnected(const bithorded::Client::Ptr& client);
- bithorded::Asset::Ptr findAsset(::bithorde::BindRead req);
- void bindAsset(const ForwardedAsset::Ptr& asset);
+ bithorded::Asset::Ptr findAsset(const bithorde::BindRead& req);
};
}}
1  bithorded/server/asset.hpp
View
@@ -39,6 +39,7 @@ class Asset
{}
typedef boost::shared_ptr<Asset> Ptr;
+ typedef boost::weak_ptr<Asset> WeakPtr;
virtual void async_read(uint64_t offset, size_t& size, ReadCallback cb) = 0;
virtual uint64_t size() = 0;
96 bithorded/server/client.cpp
View
@@ -14,16 +14,17 @@
limitations under the License.
*/
-
#include "client.hpp"
#include <boost/assert.hpp>
#include <iostream>
-#include "server.hpp"
-#include "lib/magneturi.h"
+#include <log4cplus/logger.h>
+#include <log4cplus/loggingmacros.h>
-#include <glog/logging.h>
+#include "server.hpp"
+#include "../../lib/magneturi.h"
+#include "../../lib/random.h"
const size_t MAX_ASSETS = 1024;
const size_t MAX_CHUNK = 64*1024;
@@ -33,6 +34,10 @@ namespace fs = boost::filesystem;
using namespace bithorded;
+namespace bithorded {
+ log4cplus::Logger clientLogger = log4cplus::Logger::getInstance("client");
+}
+
Client::Client( Server& server) :
bithorde::Client(server.ioService(), server.name()),
_server(server)
@@ -54,7 +59,7 @@ bool Client::requestsAsset(const BitHordeIds& ids) {
void Client::onMessage(const bithorde::HandShake& msg)
{
bithorde::Client::onMessage(msg);
- LOG(INFO) << "Connected: " << msg.name() << endl;
+ LOG4CPLUS_INFO(clientLogger, "Connected: " << msg.name());
}
void Client::onMessage(const bithorde::BindWrite& msg)
@@ -66,46 +71,51 @@ void Client::onMessage(const bithorde::BindWrite& msg)
fs::path path(msg.linkpath());
if (path.is_absolute()) {
if (_server.linkAsset(path, boost::bind(&Client::onLinkHashDone, shared_from_this(), h, _1))) {
- LOG(INFO) << "Hashing " << path << endl;
+ LOG4CPLUS_INFO(clientLogger, "Linking " << path);
resp.set_status(bithorde::SUCCESS);
} else {
- LOG(ERROR) << "Upload did not match any allowed assetStore: " << path << endl;
+ LOG4CPLUS_ERROR(clientLogger, "Upload did not match any allowed assetStore: " << path);
resp.set_status(bithorde::ERROR);
}
}
} else {
- LOG(ERROR) << "Sorry, upload isn't supported yet" << endl;
+ LOG4CPLUS_ERROR(clientLogger, "Sorry, upload isn't supported yet");
resp.set_status(bithorde::ERROR);
}
sendMessage(bithorde::Connection::AssetStatus, resp);
}
-void Client::onMessage(const bithorde::BindRead& msg)
+void Client::onMessage(bithorde::BindRead& msg)
{
- auto h = msg.handle();
+ bithorde::Asset::Handle h = msg.handle();
if (msg.ids_size() > 0) {
// Trying to open
- LOG(INFO) << peerName() << ':' << h << " requested: " << MagnetURI(msg) << endl;
-
- auto asset = _server.async_findAsset(msg);
- if (asset && !assignAsset(h, asset)) {
- bithorde::AssetStatus resp;
- resp.set_handle(h);
- resp.set_status(bithorde::INVALID_HANDLE);
- sendMessage(bithorde::Connection::AssetStatus, resp);
- } else if (asset && (asset->status == bithorde::Status::NONE)) {
- asset->statusChange.connect(boost::bind(&Client::onAssetResponse, this, msg, asset)); // TODO: bind weak_ptr
- } else {
- onAssetResponse(msg, asset);
+ LOG4CPLUS_INFO(clientLogger, peerName() << ':' << h << " requested: " << MagnetURI(msg));
+ if (!msg.has_uuid())
+ msg.set_uuid(rand64());
+
+ try {
+ auto asset = _server.async_findAsset(msg);
+ if (!asset)
+ return informAssetStatus(h, bithorde::NOTFOUND);
+ if (!assignAsset(h, asset))
+ return informAssetStatus(h, bithorde::INVALID_HANDLE);
+
+ // Remember to inform peer about changes in asset-status.
+ asset->statusChange.connect(boost::bind(&Client::informAssetStatusUpdate, this, h, Asset::WeakPtr(asset)));
+
+ if (asset->status != bithorde::Status::NONE) {
+ // We already have a valid status for the asset, so inform about it
+ informAssetStatusUpdate(h, asset);
+ }
+ } catch (bithorded::BindError e) {
+ informAssetStatus(h, e.status);
}
} else {
// Trying to close
- LOG(INFO) << peerName() << ':' << h << " closed" << endl;
+ LOG4CPLUS_INFO(clientLogger, peerName() << ':' << h << " closed");
clearAsset(h);
- bithorde::AssetStatus resp;
- resp.set_handle(h);
- resp.set_status(bithorde::NOTFOUND);
- sendMessage(bithorde::Connection::AssetStatus, resp);
+ informAssetStatus(h, bithorde::NOTFOUND);
}
}
@@ -117,7 +127,9 @@ void Client::onMessage(const bithorde::Read::Request& msg)
size_t size = msg.size();
if (size > MAX_CHUNK)
size = MAX_CHUNK;
- asset->async_read(offset, size, boost::bind(&Client::onReadResponse, this, msg, _1, _2)); // TODO: Weak callback
+
+ // Raw pointer to this should be fine here, since asset has ownership of this. (Through member Ptr client)
+ asset->async_read(offset, size, boost::bind(&Client::onReadResponse, this, msg, _1, _2));
} else {
bithorde::Read::Response resp;
resp.set_reqid(msg.reqid());
@@ -139,22 +151,30 @@ void Client::onReadResponse(const bithorde::Read::Request& req, int64_t offset,
sendMessage(bithorde::Connection::ReadResponse, resp);
}
-void Client::onAssetResponse ( const bithorde::BindRead& req, Asset::Ptr a )
+void Client::informAssetStatus(bithorde::Asset::Handle h, bithorde::Status s)
{
bithorde::AssetStatus resp;
- bithorde::Asset::Handle h = req.handle();
resp.set_handle(h);
+ resp.set_status(s);
+ sendMessage(bithorde::Connection::AssetStatus, resp);
+}
- if (a) {
- LOG(INFO) << peerName() << ':' << h << " found and bound" << endl;
- resp.set_status(bithorde::SUCCESS);
- resp.set_availability(1000);
- resp.set_size(a->size());
- a->getIds(*resp.mutable_ids());
+void Client::informAssetStatusUpdate(bithorde::Asset::Handle h, const bithorded::Asset::WeakPtr& asset_)
+{
+ bithorde::AssetStatus resp;
+ resp.set_handle(h);
+
+ if (auto asset = asset_.lock()) {
+ resp.set_status(asset->status);
+ if (asset->status == bithorde::SUCCESS) {
+ resp.set_availability(1000);
+ resp.set_size(asset->size());
+ asset->getIds(*resp.mutable_ids());
+ }
} else {
resp.set_status(bithorde::NOTFOUND);
- LOG(INFO) << peerName() << ':' << h << " not found" << endl;
}
+ LOG4CPLUS_INFO(clientLogger, peerName() << ':' << h << " new state " << bithorde::Status_Name(resp.status()));
sendMessage(bithorde::Connection::AssetStatus, resp);
}
@@ -178,7 +198,7 @@ bool Client::assignAsset(bithorde::Asset::Handle handle_, const Asset::Ptr& a)
size_t handle = handle_;
if (handle >= _assets.size()) {
if (handle > MAX_ASSETS) {
- LOG(ERROR) << peerName() << ": handle larger than allowed limit (" << handle << " < " << MAX_ASSETS << ")" << endl;
+ LOG4CPLUS_ERROR(clientLogger, peerName() << ": handle larger than allowed limit (" << handle << " < " << MAX_ASSETS << ")");
return false;
}
size_t new_size = _assets.size() + (handle - _assets.size() + 1) * 2;
5 bithorded/server/client.hpp
View
@@ -44,11 +44,12 @@ class Client : public bithorde::Client, public boost::enable_shared_from_this<Cl
virtual void onMessage(const bithorde::HandShake& msg);
virtual void onMessage(const bithorde::BindWrite& msg);
- virtual void onMessage(const bithorde::BindRead& msg);
+ virtual void onMessage(bithorde::BindRead& msg);
virtual void onMessage(const bithorde::Read::Request& msg);
private:
- void onAssetResponse( const bithorde::BindRead& req, bithorded::Asset::Ptr a);
+ void informAssetStatus(bithorde::Asset::Handle h, bithorde::Status s);
+ void informAssetStatusUpdate(bithorde::Asset::Handle h, const bithorded::Asset::WeakPtr& asset);
void onReadResponse( const bithorde::Read::Request& req, int64_t offset, const std::string& data);
void onLinkHashDone(bithorde::Asset::Handle handle, bithorded::Asset::Ptr a);
bool assignAsset(bithorde::Asset::Handle handle, const bithorded::Asset::Ptr& a);
15 bithorded/server/server.cpp
View
@@ -25,7 +25,8 @@
#include "client.hpp"
#include "config.hpp"
-#include <glog/logging.h>
+#include <log4cplus/logger.h>
+#include <log4cplus/loggingmacros.h>
using namespace std;
@@ -34,6 +35,16 @@ namespace fs = boost::filesystem;
using namespace bithorded;
+namespace bithorded {
+ log4cplus::Logger serverLog = log4cplus::Logger::getInstance("server");
+}
+
+BindError::BindError(bithorde::Status status):
+ runtime_error("findAsset failed with " + bithorde::Status_Name(status)),
+ status(status)
+{
+}
+
Server::Server(asio::io_service& ioSvc, Config& cfg) :
_cfg(cfg),
_ioSvc(ioSvc),
@@ -128,7 +139,7 @@ void Server::clientAuthenticated(const bithorded::Client::WeakPtr& client_) {
void Server::clientDisconnected(bithorded::Client::Ptr& client)
{
- LOG(INFO) << "Disconnected: " << client->peerName() << endl;
+ LOG4CPLUS_INFO(serverLog, "Disconnected: " << client->peerName());
_router.onDisconnected(client);
// Will destroy the client, unless others are holding references.
client.reset();
6 bithorded/server/server.hpp
View
@@ -37,6 +37,12 @@ namespace bithorded {
class Config;
+class BindError : public std::runtime_error {
+public:
+ bithorde::Status status;
+ explicit BindError(bithorde::Status status);
+};
+
class Server
{
Config &_cfg;
13 bithorded/store/linkedassetstore.cpp
View
@@ -23,7 +23,8 @@
#include <time.h>
#include <utime.h>
-#include <glog/logging.h>
+#include <log4cplus/logger.h>
+#include <log4cplus/loggingmacros.h>
using namespace std;
@@ -37,6 +38,10 @@ const fs::path TIGER_DIR = ".bh_meta/tiger";
const int THREADPOOL_CONCURRENCY = 4;
+namespace bithorded {
+ log4cplus::Logger storeLog = log4cplus::Logger::getInstance("store");
+}
+
LinkedAssetStore::LinkedAssetStore(boost::asio::io_service& ioSvc, const boost::filesystem3::path& baseDir) :
_threadPool(THREADPOOL_CONCURRENCY),
_ioSvc(ioSvc),
@@ -171,7 +176,7 @@ SourceAsset::Ptr openAssetFolder(const fs::path& referrer, const fs::path& asset
auto assetDataPath = assetFolder/"data";
switch (validateDataSymlink(assetDataPath)) {
case OUTDATED:
- LOG(WARNING) << "outdated asset detected, " << assetFolder << endl;
+ LOG4CPLUS_WARN(storeLog, "outdated asset detected, " << assetFolder);
purgeLink(referrer);
fs::remove(referrer/"meta");
case OK:
@@ -179,7 +184,7 @@ SourceAsset::Ptr openAssetFolder(const fs::path& referrer, const fs::path& asset
break;
case BROKEN:
- LOG(WARNING) << "broken asset detected, " << assetFolder << endl;
+ LOG4CPLUS_WARN(storeLog, "broken asset detected, " << assetFolder);
purgeLinkAndAsset(referrer);
default:
break;
@@ -203,7 +208,7 @@ SourceAsset::Ptr LinkedAssetStore::_openTiger(const std::string& tigerId)
_tigerMap[tigerId] = asset;
} else {
asset.reset();
- LOG(WARNING) << "Unhashed asset detected, hashing" << endl;
+ LOG4CPLUS_WARN(storeLog, "Unhashed asset detected, hashing");
_threadPool.post(*new HashTask(asset, _ioSvc, boost::bind(&LinkedAssetStore::_addAsset, this, _1, &noop)));
}
}
1  clients/CMakeLists.txt
View
@@ -37,6 +37,7 @@ SET_TARGET_PROPERTIES(bhfuse PROPERTIES
)
TARGET_LINK_LIBRARIES ( bhfuse
bithorde
+ ${LOG4CPLUS_LIBRARIES}
${Boost_LIBRARIES}
${FUSE_LIBRARIES}
)
22 clients/bhfuse/main.cpp
View
@@ -4,6 +4,10 @@
#include <errno.h>
#include <signal.h>
+#include <log4cplus/logger.h>
+#include <log4cplus/loggingmacros.h>
+#include <log4cplus/configurator.h>
+
#include "buildconf.hpp"
const int RECONNECT_ATTEMPTS = 30;
@@ -17,19 +21,27 @@ static asio::io_service ioSvc;
using namespace bithorde;
+log4cplus::Logger sigLogger = log4cplus::Logger::getInstance("signal");
+bool terminating = false;
void sigint(int sig) {
- cerr << "Intercepted signal#" << sig << endl;
+ LOG4CPLUS_INFO(sigLogger, "Intercepted signal#" << sig);
if (sig == SIGINT) {
- cerr << "Exiting..." << endl;
- ioSvc.stop();
- // TODO: Emergency exit on repeated sig
+ if (terminating) {
+ LOG4CPLUS_INFO(sigLogger, "Force Exiting...");
+ exit(-1);
+ } else {
+ terminating = true;
+ LOG4CPLUS_INFO(sigLogger, "Cleanly Exiting...");
+ ioSvc.stop();
+ }
}
- cerr.flush();
}
int main(int argc, char *argv[])
{
signal(SIGINT, &sigint);
+ log4cplus::BasicConfigurator config;
+ config.configure();
BoostAsioFilesystem_Options opts;
59 cmake/FindGlog.cmake
View
@@ -1,59 +0,0 @@
-# Try to find the libglog libraries
-# Once done this will define :
-#
-# Glog_FOUND - system has libglog
-# Glog_INCLUDE_DIRS - the libglog include directory
-# Glog_LIBRARIES - libglog library
-
-# Inputs to this module:
-# GLOG_ROOT The preferred installation prefix for searching for glog. Set
-# this if the module has problems finding the proper glog installation.
-
-# If GLOG_ROOT was defined in the environment, use it.
-IF (NOT GLOG_ROOT AND NOT $ENV{GLOG_ROOT} STREQUAL "")
- SET(GLOG_ROOT $ENV{GLOG_ROOT})
-ENDIF(NOT GLOG_ROOT AND NOT $ENV{GLOG_ROOT} STREQUAL "")
-IF( GLOG_ROOT )
- file(TO_CMAKE_PATH ${GLOG_ROOT} GLOG_ROOT)
-ENDIF( GLOG_ROOT )
-
-SET (GLOG_INCLUDE_DIRS)
-SET (GLOG_LIBRARIES)
-IF(WIN32)
- IF(MSVC)
- FIND_PATH(GLOG_INCLUDE_DIRS NAMES src/windows/glog/logging.h HINTS ${GLOG_ROOT})
- IF(GLOG_INCLUDE_DIRS)
- SET(GLOG_INCLUDE_DIRS ${GLOG_INCLUDE_DIRS}/src/windows)
- ENDIF(GLOG_INCLUDE_DIRS)
-
- IF (CMAKE_BUILD_TYPE STREQUAL "Release")
- message (STATUS " searching ${GLOG_ROOT}/Release/libglog.lib ...")
- FIND_LIBRARY(GLOG_LIBRARIES NAMES libglog.lib HINTS ${GLOG_ROOT}/Release $ENV{LIB} PATH_SUFFIXES ".lib")
- ELSE (CMAKE_BUILD_TYPE STREQUAL "Release")
- message (STATUS " searching ${GLOG_ROOT}/Debug/libglog.lib ...")
- FIND_LIBRARY(GLOG_LIBRARIES NAMES libglog.lib HINTS ${GLOG_ROOT}/Debug $ENV{LIB} PATH_SUFFIXES ".lib")
- ENDIF (CMAKE_BUILD_TYPE STREQUAL "Release")
- ELSE(MSVC)
- SET(Glog_FOUND FALSE)
- message (STATUS " Crap. this module supports only MSVC in Windows.")
- ENDIF(MSVC)
-ELSE(WIN32)
- FIND_PATH(GLOG_INCLUDE_DIRS NAMES glog/logging.h PATHS ${GLOG_ROOT}/include ${GLOG_ROOT} /include/ /usr/include/ /usr/local/include/)
- FIND_LIBRARY(GLOG_LIBRARIES NAMES glog PATHS ${GLOG_ROOT}/lib ${GLOG_ROOT} /lib /usr/lib /usr/local/lib)
-ENDIF(WIN32)
-
-IF(GLOG_INCLUDE_DIRS AND GLOG_LIBRARIES)
- SET(Glog_FOUND TRUE)
- message (STATUS " glog found in include=${GLOG_INCLUDE_DIRS},lib=${GLOG_LIBRARIES}")
-ELSE(GLOG_INCLUDE_DIRS AND GLOG_LIBRARIES)
- SET(Glog_FOUND FALSE)
- message (STATUS " glog not found. Please set GLOG_ROOT to the root directory containing glog.")
- IF(GLOG_INCLUDE_DIRS)
- message (STATUS " include=${GLOG_INCLUDE_DIRS}, but lib not found")
- ENDIF(GLOG_INCLUDE_DIRS)
- IF(GLOG_LIBRARIES)
- message (STATUS " lib=${GLOG_LIBRARIES}, but include not found")
- ENDIF(GLOG_LIBRARIES)
-ENDIF(GLOG_INCLUDE_DIRS AND GLOG_LIBRARIES)
-
-MARK_AS_ADVANCED(GLOG_INCLUDE_DIRS GLOG_LIBRARIES)
24 cmake/FindLog4cplus.cmake
View
@@ -0,0 +1,24 @@
+# - Try to find Log4cplus
+# Once done this will define
+# LOG4CPLUS_FOUND - System has Log4cplus
+# LOG4CPLUS_INCLUDE_DIRS - The Log4cplus include directories
+# LOG4CPLUS_LIBRARIES - The libraries needed to use Log4cplus
+
+
+find_path(LOG4CPLUS_INCLUDE_DIR log4cplus/config.hxx
+ PATH_SUFFIXES log4cplus )
+
+find_library(LOG4CPLUS_LIBRARY NAMES log4cplus
+ PATHS /usr)
+
+set(LOG4CPLUS_LIBRARIES ${LOG4CPLUS_LIBRARY} )
+set(LOG4CPLUS_INCLUDE_DIRS ${LOG4CPLUS_INCLUDE_DIR} )
+
+include(FindPackageHandleStandardArgs)
+
+# handle the QUIETLY and REQUIRED arguments and set LOG4CPLUS_FOUND to TRUE
+# if all listed variables are TRUE
+find_package_handle_standard_args(Log4cplus DEFAULT_MSG
+ LOG4CPLUS_LIBRARY LOG4CPLUS_INCLUDE_DIR)
+
+mark_as_advanced(LOG4CPLUS_INCLUDE_DIR LOG4CPLUS_LIBRARY)
1  lib/CMakeLists.txt
View
@@ -13,6 +13,7 @@ ADD_LIBRARY(bithorde
connection.h connection.cpp
hashes.h hashes.cpp
magneturi.h magneturi.cpp
+ random.h random.cpp
types.h types.cpp
)
37 lib/client.cpp
View
@@ -1,13 +1,13 @@
#include "client.h"
-#include <iostream>
-#include <stdlib.h>
-#include <string.h>
-
#include <boost/assert.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/xpressive/xpressive.hpp>
+#include <iostream>
+#include <string.h>
+
+#include "random.h"
#define DEFAULT_ASSET_TIMEOUT 4000
@@ -17,11 +17,6 @@ namespace xpressive = boost::xpressive;
using namespace bithorde;
-uint64_t rand64() {
- // TODO: improve seeding throuh srandomdev
- return (((uint64_t)rand()) << 32) | rand();
-}
-
Client::Client(asio::io_service& ioSvc, string myName) :
_ioSvc(ioSvc),
_connection(),
@@ -134,7 +129,8 @@ void Client::onMessage(const bithorde::HandShake &msg)
_protoVersion = 2;
} else {
cerr << "Only Protocol-version 2 or higer supported" << endl;
- // TODO: disconnect properly
+ _connection->close();
+ _connection.reset();
return;
}
@@ -147,14 +143,14 @@ void Client::onMessage(const bithorde::HandShake &msg)
for (auto iter = _assetMap.begin(); iter != _assetMap.end(); iter++) {
ReadAsset* asset = dynamic_cast<ReadAsset*>(iter->second);
BOOST_ASSERT(iter->second);
- informBound(*asset);
+ informBound(*asset, rand64());
}
authenticated(_peerName);
}
}
-void Client::onMessage(const bithorde::BindRead & msg) {
+void Client::onMessage(bithorde::BindRead & msg) {
cerr << "unsupported: handling BindRead" << endl;
bithorde::AssetStatus resp;
resp.set_handle(msg.handle());
@@ -219,6 +215,10 @@ void Client::onMessage(const bithorde::Ping & msg) {
}
bool Client::bind(ReadAsset &asset) {
+ return bind(asset, rand64());
+}
+
+bool Client::bind(ReadAsset &asset, uint64_t uuid) {
if (!asset.isBound()) {
BOOST_ASSERT(asset._handle < 0);
BOOST_ASSERT(asset.requestIds().size() > 0);
@@ -228,12 +228,12 @@ bool Client::bind(ReadAsset &asset) {
_assetMap[asset._handle] = &asset;
}
- return informBound(asset);
+ return informBound(asset, uuid);
}
bool Client::bind(UploadAsset & asset)
{
- // TODO: BOOST_ASSERT(asset._client == this);
+ BOOST_ASSERT(asset._client.get() == this);
BOOST_ASSERT(asset._handle < 0);
BOOST_ASSERT(asset.size() > 0);
asset._handle = _handleAllocator.allocate();
@@ -259,10 +259,13 @@ bool Client::release(Asset & asset)
_assetMap[asset._handle] = NULL;
asset._handle = -1;
- return _connection->sendMessage(Connection::BindRead, msg);
+ if (_connection)
+ return _connection->sendMessage(Connection::BindRead, msg);
+ else
+ return true; // Since connection is down, other side should not have the bound state as it is.
}
-bool Client::informBound(const ReadAsset& asset)
+bool Client::informBound(const ReadAsset& asset, uint64_t uuid)
{
BOOST_ASSERT(_connection);
BOOST_ASSERT(asset._handle >= 0);
@@ -275,7 +278,7 @@ bool Client::informBound(const ReadAsset& asset)
msg.mutable_ids()->CopyFrom(asset.requestIds());
msg.set_timeout(DEFAULT_ASSET_TIMEOUT);
- msg.set_uuid(rand64());
+ msg.set_uuid(uuid);
return _connection->sendMessage(Connection::BindRead, msg);
}
5 lib/client.h
View
@@ -52,6 +52,7 @@ class Client
const std::string& peerName();
bool bind(ReadAsset & asset);
+ bool bind(ReadAsset & asset, uint64_t uuid);
bool bind(UploadAsset & asset);
bool sendMessage(Connection::MessageType type, const ::google::protobuf::Message & msg);
@@ -69,7 +70,7 @@ class Client
void onIncomingMessage(Connection::MessageType type, ::google::protobuf::Message& msg);
virtual void onMessage(const bithorde::HandShake & msg);
- virtual void onMessage(const bithorde::BindRead & msg);
+ virtual void onMessage(bithorde::BindRead& msg);
virtual void onMessage(const bithorde::AssetStatus & msg);
virtual void onMessage(const bithorde::Read::Request & msg);
virtual void onMessage(const bithorde::Read::Response & msg);
@@ -87,7 +88,7 @@ class Client
boost::signals2::scoped_connection _writableConnection;
boost::signals2::scoped_connection _disconnectedConnection;
- bool informBound(const ReadAsset&);
+ bool informBound(const bithorde::ReadAsset& asset, uint64_t uuid);
int allocRPCRequest(Asset::Handle asset);
void releaseRPCRequest(int reqId);
};
2  lib/connection.cpp
View
@@ -148,7 +148,7 @@ void Connection::onRead(const boost::system::error_code& err, size_t count)
if (_state == Authenticated) goto proto_error;
res = dequeue<bithorde::Ping>(Ping, stream); break;
default:
- // TODO: _logger.warning("unknown message tag");
+ cerr << "BitHorde protocol warning: unknown message tag" << endl;
res = ::google::protobuf::internal::WireFormatLite::SkipMessage(&stream);
}
}
2  lib/magneturi.cpp
View
@@ -79,7 +79,7 @@ bool MagnetURI::parse(const string& uri_)
for (vector<string>::iterator iter = attributes.begin(); iter != attributes.end(); iter++) {
string option = *iter;
size_t splitPos = option.find('=');
- if (splitPos == option.size()) // TODO: Error handling
+ if (splitPos == option.size())
continue;
string key = option.substr(0, splitPos);
string value = option.substr(splitPos+1);
43 lib/random.cpp
View
@@ -0,0 +1,43 @@
+/*
+ Copyright 2012 <copyright holder> <email>
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include "random.h"
+
+#include <stdlib.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+class RandomGen {
+public:
+ RandomGen() {
+ timeval t;
+ gettimeofday(&t, NULL);
+ unsigned int seed = t.tv_sec;
+ seed = seed*1000000 + t.tv_sec;
+ seed = (seed << 8) + getpid(); // More than 64 new pids per microsecond is unlikely.
+ srand(1000000*t.tv_sec + t.tv_usec);
+ }
+ uint64_t rand64() {
+ return (((uint64_t)rand()) << 32) | rand();
+ }
+};
+
+RandomGen r;
+
+uint64_t rand64()
+{
+ return r.rand64();
+}
25 lib/random.h
View
@@ -0,0 +1,25 @@
+/*
+ Copyright 2012 <copyright holder> <email>
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+
+#ifndef BITHORDE_RANDOM_H
+#define BITHORDE_RANDOM_H
+
+#include <stdint.h>
+
+uint64_t rand64();
+
+#endif // RANDOM_HPP

No commit comments for this range

Something went wrong with that request. Please try again.