Update style to (almost) conform to ndn-cxx style using clang-format
diff --git a/src/action-log.cpp b/src/action-log.cpp
index 18a8fa8..f6663ae 100644
--- a/src/action-log.cpp
+++ b/src/action-log.cpp
@@ -27,7 +27,7 @@
using namespace std;
using namespace Ndnx;
-INIT_LOGGER ("ActionLog");
+INIT_LOGGER("ActionLog");
const std::string INIT_DATABASE = "\
CREATE TABLE ActionLog ( \n\
@@ -82,194 +82,194 @@
END; \n\
";
-// static void xTrace (void*, const char* q)
+// static void
+// xTrace(void*, const char* q)
// {
-// _LOG_TRACE ("SQLITE: " << q);
+// _LOG_TRACE("SQLITE: " << q);
// }
-ActionLog::ActionLog (Ndnx::NdnxWrapperPtr ndnx, const boost::filesystem::path &path,
- SyncLogPtr syncLog,
- const std::string &sharedFolder, const std::string &appName,
- OnFileAddedOrChangedCallback onFileAddedOrChanged, OnFileRemovedCallback onFileRemoved)
- : DbHelper (path / ".chronoshare", "action-log.db")
- , m_syncLog (syncLog)
- , m_ndnx (ndnx)
- , m_sharedFolderName (sharedFolder)
- , m_appName (appName)
- , m_onFileAddedOrChanged (onFileAddedOrChanged)
- , m_onFileRemoved (onFileRemoved)
+ActionLog::ActionLog(Ccnx::CcnxWrapperPtr ccnx, const boost::filesystem::path& path,
+ SyncLogPtr syncLog, const std::string& sharedFolder,
+ const std::string& appName, OnFileAddedOrChangedCallback onFileAddedOrChanged,
+ OnFileRemovedCallback onFileRemoved)
+ : DbHelper(path / ".chronoshare", "action-log.db")
+ , m_syncLog(syncLog)
+ , m_ccnx(ccnx)
+ , m_sharedFolderName(sharedFolder)
+ , m_appName(appName)
+ , m_onFileAddedOrChanged(onFileAddedOrChanged)
+ , m_onFileRemoved(onFileRemoved)
{
- sqlite3_exec (m_db, "PRAGMA foreign_keys = OFF", NULL, NULL, NULL);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_exec(m_db, "PRAGMA foreign_keys = OFF", NULL, NULL, NULL);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_exec (m_db, INIT_DATABASE.c_str (), NULL, NULL, NULL);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_exec(m_db, INIT_DATABASE.c_str(), NULL, NULL, NULL);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- int res = sqlite3_create_function (m_db, "apply_action", -1, SQLITE_ANY, reinterpret_cast<void*> (this),
- ActionLog::apply_action_xFun,
- 0, 0);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Cannot create function ``apply_action''"));
- }
+ int res =
+ sqlite3_create_function(m_db, "apply_action", -1, SQLITE_ANY, reinterpret_cast<void*>(this),
+ ActionLog::apply_action_xFun, 0, 0);
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Cannot create function ``apply_action''"));
+ }
- m_fileState = make_shared<FileState> (path);
+ m_fileState = make_shared<FileState>(path);
}
-tuple<sqlite3_int64 /*version*/, Ndnx::NdnxCharbufPtr /*device name*/, sqlite3_int64 /*seq_no*/>
-ActionLog::GetLatestActionForFile (const std::string &filename)
+tuple<sqlite3_int64 /*version*/, Ccnx::CcnxCharbufPtr /*device name*/, sqlite3_int64 /*seq_no*/>
+ActionLog::GetLatestActionForFile(const std::string& filename)
{
// check if something already exists
- sqlite3_stmt *stmt;
- int res = sqlite3_prepare_v2 (m_db, "SELECT version,device_name,seq_no,action "
- "FROM ActionLog "
- "WHERE filename=? ORDER BY version DESC LIMIT 1", -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ int res = sqlite3_prepare_v2(m_db, "SELECT version,device_name,seq_no,action "
+ "FROM ActionLog "
+ "WHERE filename=? ORDER BY version DESC LIMIT 1",
+ -1, &stmt, 0);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Some error with GetExistingRecord"));
- }
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Some error with GetExistingRecord"));
+ }
sqlite3_int64 version = -1;
NdnxCharbufPtr parent_device_name;
sqlite3_int64 parent_seq_no = -1;
- sqlite3_bind_text (stmt, 1, filename.c_str (), filename.size (), SQLITE_STATIC);
- if (sqlite3_step (stmt) == SQLITE_ROW)
+ sqlite3_bind_text(stmt, 1, filename.c_str(), filename.size(), SQLITE_STATIC);
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ version = sqlite3_column_int64(stmt, 0);
+
+ if (sqlite3_column_int(stmt, 3) == 0) // prevent "linking" if the file was previously deleted
{
- version = sqlite3_column_int64 (stmt, 0);
-
- if (sqlite3_column_int (stmt, 3) == 0) // prevent "linking" if the file was previously deleted
- {
- parent_device_name = make_shared<NdnxCharbuf> (sqlite3_column_blob (stmt, 1), sqlite3_column_bytes (stmt, 1));
- parent_seq_no = sqlite3_column_int64 (stmt, 2);
- }
+ parent_device_name =
+ make_shared<CcnxCharbuf>(sqlite3_column_blob(stmt, 1), sqlite3_column_bytes(stmt, 1));
+ parent_seq_no = sqlite3_column_int64(stmt, 2);
}
+ }
- sqlite3_finalize (stmt);
- return make_tuple (version, parent_device_name, parent_seq_no);
+ sqlite3_finalize(stmt);
+ return make_tuple(version, parent_device_name, parent_seq_no);
}
// local add action. remote action is extracted from content object
ActionItemPtr
-ActionLog::AddLocalActionUpdate (const std::string &filename,
- const Hash &hash,
- time_t wtime,
- int mode,
- int seg_num)
+ActionLog::AddLocalActionUpdate(const std::string& filename,
+ const Hash& hash,
+ time_t wtime,
+ int mode,
+ int seg_num)
{
- sqlite3_exec (m_db, "BEGIN TRANSACTION;", 0,0,0);
+ sqlite3_exec(m_db, "BEGIN TRANSACTION;", 0, 0, 0);
- NdnxCharbufPtr device_name = m_syncLog->GetLocalName ().toNdnxCharbuf ();
- sqlite3_int64 seq_no = m_syncLog->GetNextLocalSeqNo ();
- sqlite3_int64 version;
- NdnxCharbufPtr parent_device_name;
- sqlite3_int64 parent_seq_no = -1;
+ CcnxCharbufPtr device_name = m_syncLog->GetLocalName().toCcnxCharbuf();
+ sqlite3_int64 seq_no = m_syncLog->GetNextLocalSeqNo();
+ sqlite3_int64 version;
+ CcnxCharbufPtr parent_device_name;
+ sqlite3_int64 parent_seq_no = -1;
- sqlite3_int64 action_time = time (0);
+ sqlite3_int64 action_time = time(0);
- tie (version, parent_device_name, parent_seq_no) = GetLatestActionForFile (filename);
- version ++;
+ tie(version, parent_device_name, parent_seq_no) = GetLatestActionForFile(filename);
+ version++;
- sqlite3_stmt *stmt;
- int res = sqlite3_prepare_v2 (m_db, "INSERT INTO ActionLog "
- "(device_name, seq_no, action, filename, version, action_timestamp, "
- "file_hash, file_atime, file_mtime, file_ctime, file_chmod, file_seg_num, "
- "parent_device_name, parent_seq_no, "
- "action_name, action_content_object) "
- "VALUES (?, ?, ?, ?, ?, datetime(?, 'unixepoch'),"
- " ?, datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?,?, "
- " ?, ?, "
- " ?, ?);", -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ int res =
+ sqlite3_prepare_v2(m_db,
+ "INSERT INTO ActionLog "
+ "(device_name, seq_no, action, filename, version, action_timestamp, "
+ "file_hash, file_atime, file_mtime, file_ctime, file_chmod, file_seg_num, "
+ "parent_device_name, parent_seq_no, "
+ "action_name, action_content_object) "
+ "VALUES (?, ?, ?, ?, ?, datetime(?, 'unixepoch'),"
+ " ?, datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?,?, "
+ " ?, ?, "
+ " ?, ?);",
+ -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str (sqlite3_errmsg (m_db))
- );
- }
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str(sqlite3_errmsg(m_db)));
+ }
- sqlite3_bind_blob (stmt, 1, device_name->buf (), device_name->length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 2, seq_no);
- sqlite3_bind_int (stmt, 3, 0);
- sqlite3_bind_text (stmt, 4, filename.c_str (), filename.size (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 5, version);
- sqlite3_bind_int64 (stmt, 6, action_time);
+ sqlite3_bind_blob(stmt, 1, device_name->buf(), device_name->length(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 2, seq_no);
+ sqlite3_bind_int(stmt, 3, 0);
+ sqlite3_bind_text(stmt, 4, filename.c_str(), filename.size(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 5, version);
+ sqlite3_bind_int64(stmt, 6, action_time);
- sqlite3_bind_blob (stmt, 7, hash.GetHash (), hash.GetHashBytes (), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 7, hash.GetHash(), hash.GetHashBytes(), SQLITE_STATIC);
// sqlite3_bind_int64 (stmt, 8, atime); // NULL
- sqlite3_bind_int64 (stmt, 9, wtime);
+ sqlite3_bind_int64(stmt, 9, wtime);
// sqlite3_bind_int64 (stmt, 10, ctime); // NULL
- sqlite3_bind_int (stmt, 11, mode);
- sqlite3_bind_int (stmt, 12, seg_num);
+ sqlite3_bind_int(stmt, 11, mode);
+ sqlite3_bind_int(stmt, 12, seg_num);
- if (parent_device_name && parent_seq_no > 0)
- {
- sqlite3_bind_blob (stmt, 13, parent_device_name->buf (), parent_device_name->length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 14, parent_seq_no);
- }
+ if (parent_device_name && parent_seq_no > 0) {
+ sqlite3_bind_blob(stmt, 13, parent_device_name->buf(), parent_device_name->length(),
+ SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 14, parent_seq_no);
+ }
- ActionItemPtr item = make_shared<ActionItem> ();
- item->set_action (ActionItem::UPDATE);
- item->set_filename (filename);
- item->set_version (version);
- item->set_timestamp (action_time);
- item->set_file_hash (hash.GetHash (), hash.GetHashBytes ());
+ ActionItemPtr item = make_shared<ActionItem>();
+ item->set_action(ActionItem::UPDATE);
+ item->set_filename(filename);
+ item->set_version(version);
+ item->set_timestamp(action_time);
+ item->set_file_hash(hash.GetHash(), hash.GetHashBytes());
// item->set_atime (atime);
- item->set_mtime (wtime);
+ item->set_mtime(wtime);
// item->set_ctime (ctime);
- item->set_mode (mode);
- item->set_seg_num (seg_num);
+ item->set_mode(mode);
+ item->set_seg_num(seg_num);
- if (parent_device_name && parent_seq_no > 0)
- {
- // cout << Name (*parent_device_name) << endl;
+ if (parent_device_name && parent_seq_no > 0) {
+ // cout << Name (*parent_device_name) << endl;
- item->set_parent_device_name (parent_device_name->buf (), parent_device_name->length ());
- item->set_parent_seq_no (parent_seq_no);
- }
+ item->set_parent_device_name(parent_device_name->buf(), parent_device_name->length());
+ item->set_parent_seq_no(parent_seq_no);
+ }
// assign name to the action, serialize action, and create content object
string item_msg;
- item->SerializeToString (&item_msg);
+ item->SerializeToString(&item_msg);
// action name: /<device_name>/<appname>/action/<shared-folder>/<action-seq>
- Name actionName = Name ("/")(m_syncLog->GetLocalName ())(m_appName)("action")(m_sharedFolderName)(seq_no);
- _LOG_DEBUG ("ActionName: " << actionName);
+ Name actionName =
+ Name("/")(m_syncLog->GetLocalName())(m_appName)("action")(m_sharedFolderName)(seq_no);
+ _LOG_DEBUG("ActionName: " << actionName);
- Bytes actionData = m_ndnx->createContentObject (actionName, item_msg.c_str (), item_msg.size ());
- NdnxCharbufPtr namePtr = actionName.toNdnxCharbuf ();
+ Bytes actionData = m_ccnx->createContentObject(actionName, item_msg.c_str(), item_msg.size());
+ CcnxCharbufPtr namePtr = actionName.toCcnxCharbuf();
// _LOG_DEBUG (" >>>>>>> " << Name (namePtr->buf () << " " << namePtr->length ());
- sqlite3_bind_blob (stmt, 15, namePtr->buf (), namePtr->length (), SQLITE_STATIC);
- sqlite3_bind_blob (stmt, 16, head (actionData), actionData.size (), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 15, namePtr->buf(), namePtr->length(), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 16, head(actionData), actionData.size(), SQLITE_STATIC);
- sqlite3_step (stmt);
+ sqlite3_step(stmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
// I had a problem including directory_name assignment as part of the initial insert.
- sqlite3_prepare_v2 (m_db, "UPDATE ActionLog SET directory=directory_name(filename) WHERE device_name=? AND seq_no=?", -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_prepare_v2(m_db,
+ "UPDATE ActionLog SET directory=directory_name(filename) WHERE device_name=? AND seq_no=?",
+ -1, &stmt, 0);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_blob (stmt, 1, device_name->buf (), device_name->length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 2, seq_no);
- sqlite3_step (stmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ sqlite3_bind_blob(stmt, 1, device_name->buf(), device_name->length(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 2, seq_no);
+ sqlite3_step(stmt);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
- sqlite3_exec (m_db, "END TRANSACTION;", 0,0,0);
+ sqlite3_exec(m_db, "END TRANSACTION;", 0, 0, 0);
// set complete for local file
m_fileState->SetFileComplete(filename);
@@ -286,357 +286,370 @@
// }
ActionItemPtr
-ActionLog::AddLocalActionDelete (const std::string &filename)
+ActionLog::AddLocalActionDelete(const std::string& filename)
{
- _LOG_DEBUG ("Adding local action DELETE");
+ _LOG_DEBUG("Adding local action DELETE");
- sqlite3_exec (m_db, "BEGIN TRANSACTION;", 0,0,0);
+ sqlite3_exec(m_db, "BEGIN TRANSACTION;", 0, 0, 0);
- NdnxCharbufPtr device_name = m_syncLog->GetLocalName ().toNdnxCharbuf ();
- sqlite3_int64 version;
- NdnxCharbufPtr parent_device_name;
- sqlite3_int64 parent_seq_no = -1;
+ CcnxCharbufPtr device_name = m_syncLog->GetLocalName().toCcnxCharbuf();
+ sqlite3_int64 version;
+ CcnxCharbufPtr parent_device_name;
+ sqlite3_int64 parent_seq_no = -1;
- sqlite3_int64 action_time = time (0);
+ sqlite3_int64 action_time = time(0);
- tie (version, parent_device_name, parent_seq_no) = GetLatestActionForFile (filename);
+ tie(version, parent_device_name, parent_seq_no) = GetLatestActionForFile(filename);
if (!parent_device_name) // no records exist or file was already deleted
- {
- _LOG_DEBUG ("Nothing to delete... [" << filename << "]");
+ {
+ _LOG_DEBUG("Nothing to delete... [" << filename << "]");
- // just in case, remove data from FileState
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "DELETE FROM FileState WHERE filename = ? ", -1, &stmt, 0);
- sqlite3_bind_text (stmt, 1, filename.c_str (), filename.size (), SQLITE_STATIC); // file
+ // just in case, remove data from FileState
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db, "DELETE FROM FileState WHERE filename = ? ", -1, &stmt, 0);
+ sqlite3_bind_text(stmt, 1, filename.c_str(), filename.size(), SQLITE_STATIC); // file
- sqlite3_step (stmt);
+ sqlite3_step(stmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
- sqlite3_exec (m_db, "END TRANSACTION;", 0,0,0);
- return ActionItemPtr ();
- }
- version ++;
+ sqlite3_exec(m_db, "END TRANSACTION;", 0, 0, 0);
+ return ActionItemPtr();
+ }
+ version++;
- sqlite3_int64 seq_no = m_syncLog->GetNextLocalSeqNo ();
+ sqlite3_int64 seq_no = m_syncLog->GetNextLocalSeqNo();
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "INSERT INTO ActionLog "
- "(device_name, seq_no, action, filename, version, action_timestamp, "
- "parent_device_name, parent_seq_no, "
- "action_name, action_content_object) "
- "VALUES (?, ?, ?, ?, ?, datetime(?, 'unixepoch'),"
- " ?, ?,"
- " ?, ?)", -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db, "INSERT INTO ActionLog "
+ "(device_name, seq_no, action, filename, version, action_timestamp, "
+ "parent_device_name, parent_seq_no, "
+ "action_name, action_content_object) "
+ "VALUES (?, ?, ?, ?, ?, datetime(?, 'unixepoch'),"
+ " ?, ?,"
+ " ?, ?)",
+ -1, &stmt, 0);
- sqlite3_bind_blob (stmt, 1, device_name->buf (), device_name->length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 2, seq_no);
- sqlite3_bind_int (stmt, 3, 1);
- sqlite3_bind_text (stmt, 4, filename.c_str (), filename.size (), SQLITE_STATIC); // file
+ sqlite3_bind_blob(stmt, 1, device_name->buf(), device_name->length(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 2, seq_no);
+ sqlite3_bind_int(stmt, 3, 1);
+ sqlite3_bind_text(stmt, 4, filename.c_str(), filename.size(), SQLITE_STATIC); // file
- sqlite3_bind_int64 (stmt, 5, version);
- sqlite3_bind_int64 (stmt, 6, action_time);
+ sqlite3_bind_int64(stmt, 5, version);
+ sqlite3_bind_int64(stmt, 6, action_time);
- sqlite3_bind_blob (stmt, 7, parent_device_name->buf (), parent_device_name->length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 8, parent_seq_no);
+ sqlite3_bind_blob(stmt, 7, parent_device_name->buf(), parent_device_name->length(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 8, parent_seq_no);
- ActionItemPtr item = make_shared<ActionItem> ();
- item->set_action (ActionItem::DELETE);
- item->set_filename (filename);
- item->set_version (version);
- item->set_timestamp (action_time);
- item->set_parent_device_name (parent_device_name->buf (), parent_device_name->length ());
- item->set_parent_seq_no (parent_seq_no);
+ ActionItemPtr item = make_shared<ActionItem>();
+ item->set_action(ActionItem::DELETE);
+ item->set_filename(filename);
+ item->set_version(version);
+ item->set_timestamp(action_time);
+ item->set_parent_device_name(parent_device_name->buf(), parent_device_name->length());
+ item->set_parent_seq_no(parent_seq_no);
string item_msg;
- item->SerializeToString (&item_msg);
+ item->SerializeToString(&item_msg);
// action name: /<device_name>/<appname>/action/<shared-folder>/<action-seq>
- Name actionName = Name ("/")(m_syncLog->GetLocalName ())(m_appName)("action")(m_sharedFolderName)(seq_no);
- _LOG_DEBUG ("ActionName: " << actionName);
+ Name actionName =
+ Name("/")(m_syncLog->GetLocalName())(m_appName)("action")(m_sharedFolderName)(seq_no);
+ _LOG_DEBUG("ActionName: " << actionName);
- Bytes actionData = m_ndnx->createContentObject (actionName, item_msg.c_str (), item_msg.size ());
- NdnxCharbufPtr namePtr = actionName.toNdnxCharbuf ();
+ Bytes actionData = m_ccnx->createContentObject(actionName, item_msg.c_str(), item_msg.size());
+ CcnxCharbufPtr namePtr = actionName.toCcnxCharbuf();
- sqlite3_bind_blob (stmt, 9, namePtr->buf (), namePtr->length (), SQLITE_STATIC);
- sqlite3_bind_blob (stmt, 10, &actionData[0], actionData.size (), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 9, namePtr->buf(), namePtr->length(), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 10, &actionData[0], actionData.size(), SQLITE_STATIC);
- sqlite3_step (stmt);
+ sqlite3_step(stmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
// cout << Ndnx::Name (parent_device_name) << endl;
// assign name to the action, serialize action, and create content object
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
// I had a problem including directory_name assignment as part of the initial insert.
- sqlite3_prepare_v2 (m_db, "UPDATE ActionLog SET directory=directory_name(filename) WHERE device_name=? AND seq_no=?", -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_prepare_v2(m_db,
+ "UPDATE ActionLog SET directory=directory_name(filename) WHERE device_name=? AND seq_no=?",
+ -1, &stmt, 0);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_blob (stmt, 1, device_name->buf (), device_name->length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 2, seq_no);
- sqlite3_step (stmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ sqlite3_bind_blob(stmt, 1, device_name->buf(), device_name->length(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 2, seq_no);
+ sqlite3_step(stmt);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
- sqlite3_exec (m_db, "END TRANSACTION;", 0,0,0);
+ sqlite3_exec(m_db, "END TRANSACTION;", 0, 0, 0);
return item;
}
PcoPtr
-ActionLog::LookupActionPco (const Ndnx::Name &deviceName, sqlite3_int64 seqno)
+ActionLog::LookupActionPco(const Ccnx::Name& deviceName, sqlite3_int64 seqno)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "SELECT action_content_object FROM ActionLog WHERE device_name=? AND seq_no=?", -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db,
+ "SELECT action_content_object FROM ActionLog WHERE device_name=? AND seq_no=?",
+ -1, &stmt, 0);
- NdnxCharbufPtr name = deviceName.toNdnxCharbuf ();
+ CcnxCharbufPtr name = deviceName.toCcnxCharbuf();
- sqlite3_bind_blob (stmt, 1, name->buf (), name->length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 2, seqno);
+ sqlite3_bind_blob(stmt, 1, name->buf(), name->length(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 2, seqno);
PcoPtr retval;
- if (sqlite3_step (stmt) == SQLITE_ROW)
- {
- // _LOG_DEBUG (sqlite3_column_blob (stmt, 0) << ", " << sqlite3_column_bytes (stmt, 0));
- retval = make_shared<ParsedContentObject> (reinterpret_cast<const unsigned char *> (sqlite3_column_blob (stmt, 0)), sqlite3_column_bytes (stmt, 0));
- }
- else
- {
- _LOG_TRACE ("No action found for deviceName [" << deviceName << "] and seqno:" << seqno);
- }
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ // _LOG_DEBUG (sqlite3_column_blob (stmt, 0) << ", " << sqlite3_column_bytes (stmt, 0));
+ retval = make_shared<ParsedContentObject>(reinterpret_cast<const unsigned char*>(
+ sqlite3_column_blob(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0));
+ }
+ else {
+ _LOG_TRACE("No action found for deviceName [" << deviceName << "] and seqno:" << seqno);
+ }
// _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK && sqlite3_errcode (m_db) != SQLITE_ROW, sqlite3_errmsg (m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
return retval;
}
ActionItemPtr
-ActionLog::LookupAction (const Ndnx::Name &deviceName, sqlite3_int64 seqno)
+ActionLog::LookupAction(const Ccnx::Name& deviceName, sqlite3_int64 seqno)
{
- PcoPtr pco = LookupActionPco (deviceName, seqno);
- if (!pco) return ActionItemPtr ();
+ PcoPtr pco = LookupActionPco(deviceName, seqno);
+ if (!pco)
+ return ActionItemPtr();
- ActionItemPtr action = deserializeMsg<ActionItem> (pco->content ());
+ ActionItemPtr action = deserializeMsg<ActionItem>(pco->content());
return action;
}
-Ndnx::PcoPtr
-ActionLog::LookupActionPco (const Ndnx::Name &actionName)
+Ccnx::PcoPtr
+ActionLog::LookupActionPco(const Ccnx::Name& actionName)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "SELECT action_content_object FROM ActionLog WHERE action_name=?", -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db, "SELECT action_content_object FROM ActionLog WHERE action_name=?", -1,
+ &stmt, 0);
- _LOG_DEBUG (actionName);
- NdnxCharbufPtr name = actionName.toNdnxCharbuf ();
+ _LOG_DEBUG(actionName);
+ CcnxCharbufPtr name = actionName.toCcnxCharbuf();
- _LOG_DEBUG (" <<<<<<< " << name->buf () << " " << name->length ());
+ _LOG_DEBUG(" <<<<<<< " << name->buf() << " " << name->length());
- sqlite3_bind_blob (stmt, 1, name->buf (), name->length (), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 1, name->buf(), name->length(), SQLITE_STATIC);
PcoPtr retval;
- if (sqlite3_step (stmt) == SQLITE_ROW)
- {
- // _LOG_DEBUG (sqlite3_column_blob (stmt, 0) << ", " << sqlite3_column_bytes (stmt, 0));
- retval = make_shared<ParsedContentObject> (reinterpret_cast<const unsigned char *> (sqlite3_column_blob (stmt, 0)), sqlite3_column_bytes (stmt, 0));
- }
- else
- {
- _LOG_TRACE ("No action found for name: " << actionName);
- }
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_ROW, sqlite3_errmsg (m_db));
- sqlite3_finalize (stmt);
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ // _LOG_DEBUG (sqlite3_column_blob (stmt, 0) << ", " << sqlite3_column_bytes (stmt, 0));
+ retval = make_shared<ParsedContentObject>(reinterpret_cast<const unsigned char*>(
+ sqlite3_column_blob(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0));
+ }
+ else {
+ _LOG_TRACE("No action found for name: " << actionName);
+ }
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_ROW, sqlite3_errmsg(m_db));
+ sqlite3_finalize(stmt);
return retval;
}
ActionItemPtr
-ActionLog::LookupAction (const Ndnx::Name &actionName)
+ActionLog::LookupAction(const Ccnx::Name& actionName)
{
- PcoPtr pco = LookupActionPco (actionName);
- if (!pco) return ActionItemPtr ();
+ PcoPtr pco = LookupActionPco(actionName);
+ if (!pco)
+ return ActionItemPtr();
- ActionItemPtr action = deserializeMsg<ActionItem> (pco->content ());
+ ActionItemPtr action = deserializeMsg<ActionItem>(pco->content());
return action;
}
FileItemPtr
-ActionLog::LookupAction (const std::string &filename, sqlite3_int64 version, const Hash &filehash)
+ActionLog::LookupAction(const std::string& filename, sqlite3_int64 version, const Hash& filehash)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db,
- "SELECT device_name, seq_no, strftime('%s', file_mtime), file_chmod, file_seg_num, file_hash "
- " FROM ActionLog "
- " WHERE action = 0 AND "
- " filename=? AND "
- " version=? AND "
- " is_prefix (?, file_hash)=1", -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db,
+ "SELECT device_name, seq_no, strftime('%s', file_mtime), file_chmod, file_seg_num, file_hash "
+ " FROM ActionLog "
+ " WHERE action = 0 AND "
+ " filename=? AND "
+ " version=? AND "
+ " is_prefix (?, file_hash)=1",
+ -1, &stmt, 0);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_text (stmt, 1, filename.c_str (), filename.size (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 2, version);
- sqlite3_bind_blob (stmt, 3, filehash.GetHash (), filehash.GetHashBytes (), SQLITE_STATIC);
+ sqlite3_bind_text(stmt, 1, filename.c_str(), filename.size(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 2, version);
+ sqlite3_bind_blob(stmt, 3, filehash.GetHash(), filehash.GetHashBytes(), SQLITE_STATIC);
FileItemPtr fileItem;
- if (sqlite3_step (stmt) == SQLITE_ROW)
- {
- fileItem = make_shared<FileItem> ();
- fileItem->set_filename (filename);
- fileItem->set_device_name (sqlite3_column_blob (stmt, 0), sqlite3_column_bytes (stmt, 0));
- fileItem->set_seq_no (sqlite3_column_int64 (stmt, 1));
- fileItem->set_mtime (sqlite3_column_int64 (stmt, 2));
- fileItem->set_mode (sqlite3_column_int64 (stmt, 3));
- fileItem->set_seg_num (sqlite3_column_int64 (stmt, 4));
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ fileItem = make_shared<FileItem>();
+ fileItem->set_filename(filename);
+ fileItem->set_device_name(sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0));
+ fileItem->set_seq_no(sqlite3_column_int64(stmt, 1));
+ fileItem->set_mtime(sqlite3_column_int64(stmt, 2));
+ fileItem->set_mode(sqlite3_column_int64(stmt, 3));
+ fileItem->set_seg_num(sqlite3_column_int64(stmt, 4));
- fileItem->set_file_hash (sqlite3_column_blob (stmt, 5), sqlite3_column_bytes (stmt, 5));
- }
+ fileItem->set_file_hash(sqlite3_column_blob(stmt, 5), sqlite3_column_bytes(stmt, 5));
+ }
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE || sqlite3_errcode (m_db) != SQLITE_ROW || sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE || sqlite3_errcode(m_db) != SQLITE_ROW ||
+ sqlite3_errcode(m_db) != SQLITE_OK,
+ sqlite3_errmsg(m_db));
return fileItem;
}
ActionItemPtr
-ActionLog::AddRemoteAction (const Ndnx::Name &deviceName, sqlite3_int64 seqno, Ndnx::PcoPtr actionPco)
+ActionLog::AddRemoteAction(const Ccnx::Name& deviceName, sqlite3_int64 seqno, Ccnx::PcoPtr actionPco)
{
- if (!actionPco)
- {
- _LOG_ERROR ("actionPco is not valid");
- return ActionItemPtr ();
- }
- ActionItemPtr action = deserializeMsg<ActionItem> (actionPco->content ());
+ if (!actionPco) {
+ _LOG_ERROR("actionPco is not valid");
+ return ActionItemPtr();
+ }
+ ActionItemPtr action = deserializeMsg<ActionItem>(actionPco->content());
- if (!action)
- {
- _LOG_ERROR ("action cannot be decoded");
- return ActionItemPtr ();
- }
+ if (!action) {
+ _LOG_ERROR("action cannot be decoded");
+ return ActionItemPtr();
+ }
- _LOG_DEBUG ("AddRemoteAction: [" << deviceName << "] seqno: " << seqno);
+ _LOG_DEBUG("AddRemoteAction: [" << deviceName << "] seqno: " << seqno);
- sqlite3_stmt *stmt;
- int res = sqlite3_prepare_v2 (m_db, "INSERT INTO ActionLog "
- "(device_name, seq_no, action, filename, version, action_timestamp, "
- "file_hash, file_atime, file_mtime, file_ctime, file_chmod, file_seg_num, "
- "parent_device_name, parent_seq_no, "
- "action_name, action_content_object) "
- "VALUES (?, ?, ?, ?, ?, datetime(?, 'unixepoch'),"
- " ?, datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?,?, "
- " ?, ?, "
- " ?, ?);", -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_stmt* stmt;
+ int res =
+ sqlite3_prepare_v2(m_db,
+ "INSERT INTO ActionLog "
+ "(device_name, seq_no, action, filename, version, action_timestamp, "
+ "file_hash, file_atime, file_mtime, file_ctime, file_chmod, file_seg_num, "
+ "parent_device_name, parent_seq_no, "
+ "action_name, action_content_object) "
+ "VALUES (?, ?, ?, ?, ?, datetime(?, 'unixepoch'),"
+ " ?, datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?,?, "
+ " ?, ?, "
+ " ?, ?);",
+ -1, &stmt, 0);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- NdnxCharbufPtr device_name = deviceName.toNdnxCharbuf ();
- sqlite3_bind_blob (stmt, 1, device_name->buf (), device_name->length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 2, seqno);
+ CcnxCharbufPtr device_name = deviceName.toCcnxCharbuf();
+ sqlite3_bind_blob(stmt, 1, device_name->buf(), device_name->length(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 2, seqno);
- sqlite3_bind_int (stmt, 3, action->action ());
- sqlite3_bind_text (stmt, 4, action->filename ().c_str (), action->filename ().size (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 5, action->version ());
- sqlite3_bind_int64 (stmt, 6, action->timestamp ());
+ sqlite3_bind_int(stmt, 3, action->action());
+ sqlite3_bind_text(stmt, 4, action->filename().c_str(), action->filename().size(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 5, action->version());
+ sqlite3_bind_int64(stmt, 6, action->timestamp());
- if (action->action () == ActionItem::UPDATE)
- {
- sqlite3_bind_blob (stmt, 7, action->file_hash ().c_str (), action->file_hash ().size (), SQLITE_STATIC);
+ if (action->action() == ActionItem::UPDATE) {
+ sqlite3_bind_blob(stmt, 7, action->file_hash().c_str(), action->file_hash().size(),
+ SQLITE_STATIC);
- // sqlite3_bind_int64 (stmt, 8, atime); // NULL
- sqlite3_bind_int64 (stmt, 9, action->mtime ());
- // sqlite3_bind_int64 (stmt, 10, ctime); // NULL
+ // sqlite3_bind_int64 (stmt, 8, atime); // NULL
+ sqlite3_bind_int64(stmt, 9, action->mtime());
+ // sqlite3_bind_int64 (stmt, 10, ctime); // NULL
- sqlite3_bind_int (stmt, 11, action->mode ());
- sqlite3_bind_int (stmt, 12, action->seg_num ());
- }
+ sqlite3_bind_int(stmt, 11, action->mode());
+ sqlite3_bind_int(stmt, 12, action->seg_num());
+ }
- if (action->has_parent_device_name ())
- {
- sqlite3_bind_blob (stmt, 13, action->parent_device_name ().c_str (), action->parent_device_name ().size (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 14, action->parent_seq_no ());
- }
+ if (action->has_parent_device_name()) {
+ sqlite3_bind_blob(stmt, 13, action->parent_device_name().c_str(),
+ action->parent_device_name().size(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 14, action->parent_seq_no());
+ }
- Name actionName = Name (deviceName)("action")(m_sharedFolderName)(seqno);
- NdnxCharbufPtr namePtr = actionName.toNdnxCharbuf ();
+ Name actionName = Name(deviceName)("action")(m_sharedFolderName)(seqno);
+ CcnxCharbufPtr namePtr = actionName.toCcnxCharbuf();
- sqlite3_bind_blob (stmt, 15, namePtr->buf (), namePtr->length (), SQLITE_STATIC);
- sqlite3_bind_blob (stmt, 16, head (actionPco->buf ()), actionPco->buf ().size (), SQLITE_STATIC);
- sqlite3_step (stmt);
+ sqlite3_bind_blob(stmt, 15, namePtr->buf(), namePtr->length(), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 16, head(actionPco->buf()), actionPco->buf().size(), SQLITE_STATIC);
+ sqlite3_step(stmt);
// if action needs to be applied to file state, the trigger will take care of it
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
// I had a problem including directory_name assignment as part of the initial insert.
- sqlite3_prepare_v2 (m_db, "UPDATE ActionLog SET directory=directory_name(filename) WHERE device_name=? AND seq_no=?", -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_prepare_v2(m_db,
+ "UPDATE ActionLog SET directory=directory_name(filename) WHERE device_name=? AND seq_no=?",
+ -1, &stmt, 0);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_blob (stmt, 1, device_name->buf (), device_name->length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 2, seqno);
- sqlite3_step (stmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ sqlite3_bind_blob(stmt, 1, device_name->buf(), device_name->length(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 2, seqno);
+ sqlite3_step(stmt);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
return action;
}
ActionItemPtr
-ActionLog::AddRemoteAction (Ndnx::PcoPtr actionPco)
+ActionLog::AddRemoteAction(Ccnx::PcoPtr actionPco)
{
- Name name = actionPco->name ();
+ Name name = actionPco->name();
// action name: /<device_name>/<appname>/action/<shared-folder>/<action-seq>
- uint64_t seqno = name.getCompFromBackAsInt (0);
- string sharedFolder = name.getCompFromBackAsString (1);
+ uint64_t seqno = name.getCompFromBackAsInt(0);
+ string sharedFolder = name.getCompFromBackAsString(1);
- if (sharedFolder != m_sharedFolderName)
- {
- _LOG_ERROR ("Action doesn't belong to this shared folder");
- return ActionItemPtr ();
- }
+ if (sharedFolder != m_sharedFolderName) {
+ _LOG_ERROR("Action doesn't belong to this shared folder");
+ return ActionItemPtr();
+ }
- string action = name.getCompFromBackAsString (2);
+ string action = name.getCompFromBackAsString(2);
- if (action != "action")
- {
- _LOG_ERROR ("not an action");
- return ActionItemPtr ();
- }
+ if (action != "action") {
+ _LOG_ERROR("not an action");
+ return ActionItemPtr();
+ }
- string appName = name.getCompFromBackAsString (3);
- if (appName != m_appName)
- {
- _LOG_ERROR ("Action doesn't belong to this application");
- return ActionItemPtr ();
- }
+ string appName = name.getCompFromBackAsString(3);
+ if (appName != m_appName) {
+ _LOG_ERROR("Action doesn't belong to this application");
+ return ActionItemPtr();
+ }
- Name deviceName = name.getPartialName (0, name.size ()-4);
+ Name deviceName = name.getPartialName(0, name.size() - 4);
- _LOG_DEBUG ("From [" << name << "] extracted deviceName: " << deviceName << ", sharedFolder: " << sharedFolder << ", seqno: " << seqno);
+ _LOG_DEBUG("From [" << name << "] extracted deviceName: " << deviceName << ", sharedFolder: "
+ << sharedFolder
+ << ", seqno: "
+ << seqno);
- return AddRemoteAction (deviceName, seqno, actionPco);
+ return AddRemoteAction(deviceName, seqno, actionPco);
}
sqlite3_int64
-ActionLog::LogSize ()
+ActionLog::LogSize()
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "SELECT count(*) FROM ActionLog", -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db, "SELECT count(*) FROM ActionLog", -1, &stmt, 0);
sqlite3_int64 retval = -1;
- if (sqlite3_step (stmt) == SQLITE_ROW)
- {
- retval = sqlite3_column_int64 (stmt, 0);
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ retval = sqlite3_column_int64(stmt, 0);
}
return retval;
@@ -644,85 +657,86 @@
bool
-ActionLog::LookupActionsInFolderRecursively (const boost::function<void (const Ndnx::Name &name, sqlite3_int64 seq_no, const ActionItem &)> &visitor,
- const std::string &folder, int offset/*=0*/, int limit/*=-1*/)
+ActionLog::LookupActionsInFolderRecursively(
+ const boost::function<void(const Ccnx::Name& name, sqlite3_int64 seq_no, const ActionItem&)>& visitor,
+ const std::string& folder, int offset /*=0*/, int limit /*=-1*/)
{
- _LOG_DEBUG ("LookupActionsInFolderRecursively: [" << folder << "]");
+ _LOG_DEBUG("LookupActionsInFolderRecursively: [" << folder << "]");
if (limit >= 0)
limit += 1; // to check if there is more data
- sqlite3_stmt *stmt;
- if (folder != "")
- {
- /// @todo Do something to improve efficiency of this query. Right now it is basically scanning the whole database
+ sqlite3_stmt* stmt;
+ if (folder != "") {
+ /// @todo Do something to improve efficiency of this query. Right now it is basically scanning the whole database
- sqlite3_prepare_v2 (m_db,
- "SELECT device_name,seq_no,action,filename,directory,version,strftime('%s', action_timestamp), "
- " file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num, "
- " parent_device_name,parent_seq_no "
- " FROM ActionLog "
- " WHERE is_dir_prefix (?, directory)=1 "
- " ORDER BY action_timestamp DESC "
- " LIMIT ? OFFSET ?", -1, &stmt, 0); // there is a small ambiguity with is_prefix matching, but should be ok for now
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_prepare_v2(m_db,
+ "SELECT device_name,seq_no,action,filename,directory,version,strftime('%s', action_timestamp), "
+ " file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num, "
+ " parent_device_name,parent_seq_no "
+ " FROM ActionLog "
+ " WHERE is_dir_prefix (?, directory)=1 "
+ " ORDER BY action_timestamp DESC "
+ " LIMIT ? OFFSET ?",
+ -1, &stmt,
+ 0); // there is a small ambiguity with is_prefix matching, but should be ok for now
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_text (stmt, 1, folder.c_str (), folder.size (), SQLITE_STATIC);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_bind_text(stmt, 1, folder.c_str(), folder.size(), SQLITE_STATIC);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_int (stmt, 2, limit);
- sqlite3_bind_int (stmt, 3, offset);
+ sqlite3_bind_int(stmt, 2, limit);
+ sqlite3_bind_int(stmt, 3, offset);
+ }
+ else {
+ sqlite3_prepare_v2(m_db,
+ "SELECT device_name,seq_no,action,filename,directory,version,strftime('%s', action_timestamp), "
+ " file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num, "
+ " parent_device_name,parent_seq_no "
+ " FROM ActionLog "
+ " ORDER BY action_timestamp DESC "
+ " LIMIT ? OFFSET ?",
+ -1, &stmt, 0);
+ sqlite3_bind_int(stmt, 1, limit);
+ sqlite3_bind_int(stmt, 2, offset);
+ }
+
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
+
+ while (sqlite3_step(stmt) == SQLITE_ROW) {
+ if (limit == 1)
+ break;
+
+ ActionItem action;
+
+ Ccnx::Name device_name(sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0));
+ sqlite3_int64 seq_no = sqlite3_column_int64(stmt, 1);
+ action.set_action(static_cast<ActionItem_ActionType>(sqlite3_column_int(stmt, 2)));
+ action.set_filename(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 3)),
+ sqlite3_column_bytes(stmt, 3));
+ std::string directory(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 4)),
+ sqlite3_column_bytes(stmt, 4));
+ action.set_version(sqlite3_column_int64(stmt, 5));
+ action.set_timestamp(sqlite3_column_int64(stmt, 6));
+
+ if (action.action() == 0) {
+ action.set_file_hash(sqlite3_column_blob(stmt, 7), sqlite3_column_bytes(stmt, 7));
+ action.set_mtime(sqlite3_column_int(stmt, 8));
+ action.set_mode(sqlite3_column_int(stmt, 9));
+ action.set_seg_num(sqlite3_column_int64(stmt, 10));
}
- else
- {
- sqlite3_prepare_v2 (m_db,
- "SELECT device_name,seq_no,action,filename,directory,version,strftime('%s', action_timestamp), "
- " file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num, "
- " parent_device_name,parent_seq_no "
- " FROM ActionLog "
- " ORDER BY action_timestamp DESC "
- " LIMIT ? OFFSET ?", -1, &stmt, 0);
- sqlite3_bind_int (stmt, 1, limit);
- sqlite3_bind_int (stmt, 2, offset);
+ if (sqlite3_column_bytes(stmt, 11) > 0) {
+ action.set_parent_device_name(sqlite3_column_blob(stmt, 11), sqlite3_column_bytes(stmt, 11));
+ action.set_parent_seq_no(sqlite3_column_int64(stmt, 12));
}
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ visitor(device_name, seq_no, action);
+ limit--;
+ }
- while (sqlite3_step (stmt) == SQLITE_ROW)
- {
- if (limit == 1)
- break;
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- ActionItem action;
-
- Ndnx::Name device_name (sqlite3_column_blob (stmt, 0), sqlite3_column_bytes (stmt, 0));
- sqlite3_int64 seq_no = sqlite3_column_int64 (stmt, 1);
- action.set_action (static_cast<ActionItem_ActionType> (sqlite3_column_int (stmt, 2)));
- action.set_filename (reinterpret_cast<const char *> (sqlite3_column_text (stmt, 3)), sqlite3_column_bytes (stmt, 3));
- std::string directory (reinterpret_cast<const char *> (sqlite3_column_text (stmt, 4)), sqlite3_column_bytes (stmt, 4));
- action.set_version (sqlite3_column_int64 (stmt, 5));
- action.set_timestamp (sqlite3_column_int64 (stmt, 6));
-
- if (action.action () == 0)
- {
- action.set_file_hash (sqlite3_column_blob (stmt, 7), sqlite3_column_bytes (stmt, 7));
- action.set_mtime (sqlite3_column_int (stmt, 8));
- action.set_mode (sqlite3_column_int (stmt, 9));
- action.set_seg_num (sqlite3_column_int64 (stmt, 10));
- }
- if (sqlite3_column_bytes (stmt, 11) > 0)
- {
- action.set_parent_device_name (sqlite3_column_blob (stmt, 11), sqlite3_column_bytes (stmt, 11));
- action.set_parent_seq_no (sqlite3_column_int64 (stmt, 12));
- }
-
- visitor (device_name, seq_no, action);
- limit --;
- }
-
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
-
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
return (limit == 1); // more data is available
}
@@ -731,105 +745,108 @@
* @todo Figure out the way to minimize code duplication
*/
bool
-ActionLog::LookupActionsForFile (const boost::function<void (const Ndnx::Name &name, sqlite3_int64 seq_no, const ActionItem &)> &visitor,
- const std::string &file, int offset/*=0*/, int limit/*=-1*/)
+ActionLog::LookupActionsForFile(
+ const boost::function<void(const Ccnx::Name& name, sqlite3_int64 seq_no, const ActionItem&)>& visitor,
+ const std::string& file, int offset /*=0*/, int limit /*=-1*/)
{
- _LOG_DEBUG ("LookupActionsInFolderRecursively: [" << file << "]");
- if (file.empty ())
+ _LOG_DEBUG("LookupActionsInFolderRecursively: [" << file << "]");
+ if (file.empty())
return false;
if (limit >= 0)
limit += 1; // to check if there is more data
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db,
- "SELECT device_name,seq_no,action,filename,directory,version,strftime('%s', action_timestamp), "
- " file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num, "
- " parent_device_name,parent_seq_no "
- " FROM ActionLog "
- " WHERE filename=? "
- " ORDER BY action_timestamp DESC "
- " LIMIT ? OFFSET ?", -1, &stmt, 0); // there is a small ambiguity with is_prefix matching, but should be ok for now
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db,
+ "SELECT device_name,seq_no,action,filename,directory,version,strftime('%s', action_timestamp), "
+ " file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num, "
+ " parent_device_name,parent_seq_no "
+ " FROM ActionLog "
+ " WHERE filename=? "
+ " ORDER BY action_timestamp DESC "
+ " LIMIT ? OFFSET ?",
+ -1, &stmt,
+ 0); // there is a small ambiguity with is_prefix matching, but should be ok for now
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_text (stmt, 1, file.c_str (), file.size (), SQLITE_STATIC);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_bind_text(stmt, 1, file.c_str(), file.size(), SQLITE_STATIC);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_int (stmt, 2, limit);
- sqlite3_bind_int (stmt, 3, offset);
+ sqlite3_bind_int(stmt, 2, limit);
+ sqlite3_bind_int(stmt, 3, offset);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- while (sqlite3_step (stmt) == SQLITE_ROW)
- {
- if (limit == 1)
- break;
+ while (sqlite3_step(stmt) == SQLITE_ROW) {
+ if (limit == 1)
+ break;
- ActionItem action;
+ ActionItem action;
- Ndnx::Name device_name (sqlite3_column_blob (stmt, 0), sqlite3_column_bytes (stmt, 0));
- sqlite3_int64 seq_no = sqlite3_column_int64 (stmt, 1);
- action.set_action (static_cast<ActionItem_ActionType> (sqlite3_column_int (stmt, 2)));
- action.set_filename (reinterpret_cast<const char *> (sqlite3_column_text (stmt, 3)), sqlite3_column_bytes (stmt, 3));
- std::string directory (reinterpret_cast<const char *> (sqlite3_column_text (stmt, 4)), sqlite3_column_bytes (stmt, 4));
- action.set_version (sqlite3_column_int64 (stmt, 5));
- action.set_timestamp (sqlite3_column_int64 (stmt, 6));
+ Ccnx::Name device_name(sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0));
+ sqlite3_int64 seq_no = sqlite3_column_int64(stmt, 1);
+ action.set_action(static_cast<ActionItem_ActionType>(sqlite3_column_int(stmt, 2)));
+ action.set_filename(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 3)),
+ sqlite3_column_bytes(stmt, 3));
+ std::string directory(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 4)),
+ sqlite3_column_bytes(stmt, 4));
+ action.set_version(sqlite3_column_int64(stmt, 5));
+ action.set_timestamp(sqlite3_column_int64(stmt, 6));
- if (action.action () == 0)
- {
- action.set_file_hash (sqlite3_column_blob (stmt, 7), sqlite3_column_bytes (stmt, 7));
- action.set_mtime (sqlite3_column_int (stmt, 8));
- action.set_mode (sqlite3_column_int (stmt, 9));
- action.set_seg_num (sqlite3_column_int64 (stmt, 10));
- }
- if (sqlite3_column_bytes (stmt, 11) > 0)
- {
- action.set_parent_device_name (sqlite3_column_blob (stmt, 11), sqlite3_column_bytes (stmt, 11));
- action.set_parent_seq_no (sqlite3_column_int64 (stmt, 12));
- }
-
- visitor (device_name, seq_no, action);
- limit --;
+ if (action.action() == 0) {
+ action.set_file_hash(sqlite3_column_blob(stmt, 7), sqlite3_column_bytes(stmt, 7));
+ action.set_mtime(sqlite3_column_int(stmt, 8));
+ action.set_mode(sqlite3_column_int(stmt, 9));
+ action.set_seg_num(sqlite3_column_int64(stmt, 10));
+ }
+ if (sqlite3_column_bytes(stmt, 11) > 0) {
+ action.set_parent_device_name(sqlite3_column_blob(stmt, 11), sqlite3_column_bytes(stmt, 11));
+ action.set_parent_seq_no(sqlite3_column_int64(stmt, 12));
}
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ visitor(device_name, seq_no, action);
+ limit--;
+ }
- sqlite3_finalize (stmt);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
+
+ sqlite3_finalize(stmt);
return (limit == 1); // more data is available
}
void
-ActionLog::LookupRecentFileActions(const boost::function<void (const string &, int, int)> &visitor, int limit)
+ActionLog::LookupRecentFileActions(const boost::function<void(const string&, int, int)>& visitor,
+ int limit)
{
- sqlite3_stmt *stmt;
+ sqlite3_stmt* stmt;
- sqlite3_prepare_v2 (m_db,
- "SELECT AL.filename, AL.action"
- " FROM ActionLog AL"
- " JOIN "
- " (SELECT filename, MAX(action_timestamp) AS action_timestamp "
- " FROM ActionLog "
- " GROUP BY filename ) AS GAL"
- " ON AL.filename = GAL.filename AND AL.action_timestamp = GAL.action_timestamp "
- " ORDER BY AL.action_timestamp DESC "
- " LIMIT ?;",
- -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_prepare_v2(m_db,
+ "SELECT AL.filename, AL.action"
+ " FROM ActionLog AL"
+ " JOIN "
+ " (SELECT filename, MAX(action_timestamp) AS action_timestamp "
+ " FROM ActionLog "
+ " GROUP BY filename ) AS GAL"
+ " ON AL.filename = GAL.filename AND AL.action_timestamp = GAL.action_timestamp "
+ " ORDER BY AL.action_timestamp DESC "
+ " LIMIT ?;",
+ -1, &stmt, 0);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
sqlite3_bind_int(stmt, 1, limit);
int index = 0;
- while (sqlite3_step(stmt) == SQLITE_ROW)
- {
- std::string filename(reinterpret_cast<const char *> (sqlite3_column_text (stmt, 0)), sqlite3_column_bytes (stmt, 0));
- int action = sqlite3_column_int (stmt, 1);
+ while (sqlite3_step(stmt) == SQLITE_ROW) {
+ std::string filename(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0));
+ int action = sqlite3_column_int(stmt, 1);
visitor(filename, action, index);
index++;
}
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
}
@@ -838,50 +855,46 @@
///////////////////////////////////////////////////////////////////////////////////
void
-ActionLog::apply_action_xFun (sqlite3_context *context, int argc, sqlite3_value **argv)
+ActionLog::apply_action_xFun(sqlite3_context* context, int argc, sqlite3_value** argv)
{
- ActionLog *the = reinterpret_cast<ActionLog*> (sqlite3_user_data (context));
+ ActionLog* the = reinterpret_cast<ActionLog*>(sqlite3_user_data(context));
- if (argc != 11)
- {
- sqlite3_result_error (context, "``apply_action'' expects 10 arguments", -1);
- return;
- }
+ if (argc != 11) {
+ sqlite3_result_error(context, "``apply_action'' expects 10 arguments", -1);
+ return;
+ }
- NdnxCharbuf device_name (sqlite3_value_blob (argv[0]), sqlite3_value_bytes (argv[0]));
- sqlite3_int64 seq_no = sqlite3_value_int64 (argv[1]);
- int action = sqlite3_value_int (argv[2]);
- string filename = reinterpret_cast<const char*> (sqlite3_value_text (argv[3]));
- sqlite3_int64 version = sqlite3_value_int64 (argv[4]);
+ CcnxCharbuf device_name(sqlite3_value_blob(argv[0]), sqlite3_value_bytes(argv[0]));
+ sqlite3_int64 seq_no = sqlite3_value_int64(argv[1]);
+ int action = sqlite3_value_int(argv[2]);
+ string filename = reinterpret_cast<const char*>(sqlite3_value_text(argv[3]));
+ sqlite3_int64 version = sqlite3_value_int64(argv[4]);
- _LOG_TRACE ("apply_function called with " << argc);
- _LOG_TRACE ("device_name: " << Name (device_name)
- << ", action: " << action
- << ", file: " << filename);
+ _LOG_TRACE("apply_function called with " << argc);
+ _LOG_TRACE("device_name: " << Name(device_name) << ", action: " << action << ", file: " << filename);
if (action == 0) // update
- {
- Hash hash (sqlite3_value_blob (argv[5]), sqlite3_value_bytes (argv[5]));
- time_t atime = static_cast<time_t> (sqlite3_value_int64 (argv[6]));
- time_t mtime = static_cast<time_t> (sqlite3_value_int64 (argv[7]));
- time_t ctime = static_cast<time_t> (sqlite3_value_int64 (argv[8]));
- int mode = sqlite3_value_int (argv[9]);
- int seg_num = sqlite3_value_int (argv[10]);
+ {
+ Hash hash(sqlite3_value_blob(argv[5]), sqlite3_value_bytes(argv[5]));
+ time_t atime = static_cast<time_t>(sqlite3_value_int64(argv[6]));
+ time_t mtime = static_cast<time_t>(sqlite3_value_int64(argv[7]));
+ time_t ctime = static_cast<time_t>(sqlite3_value_int64(argv[8]));
+ int mode = sqlite3_value_int(argv[9]);
+ int seg_num = sqlite3_value_int(argv[10]);
- _LOG_DEBUG ("Update " << filename << " " << atime << " " << mtime << " " << ctime << " " << hash);
+ _LOG_DEBUG("Update " << filename << " " << atime << " " << mtime << " " << ctime << " " << hash);
- the->m_fileState->UpdateFile (filename, version, hash, device_name, seq_no, atime, mtime, ctime, mode, seg_num);
+ the->m_fileState->UpdateFile(filename, version, hash, device_name, seq_no, atime, mtime, ctime,
+ mode, seg_num);
- // no callback here
- }
+ // no callback here
+ }
else if (action == 1) // delete
- {
- the->m_fileState->DeleteFile (filename);
+ {
+ the->m_fileState->DeleteFile(filename);
- the->m_onFileRemoved (filename);
- }
+ the->m_onFileRemoved(filename);
+ }
- sqlite3_result_null (context);
+ sqlite3_result_null(context);
}
-
-
diff --git a/src/action-log.hpp b/src/action-log.hpp
index 6c5e51a..80f354c 100644
--- a/src/action-log.hpp
+++ b/src/action-log.hpp
@@ -21,13 +21,13 @@
#ifndef ACTION_LOG_H
#define ACTION_LOG_H
+#include "action-item.pb.hpp"
+#include "ccnx-pco.hpp"
+#include "ccnx-wrapper.hpp"
#include "db-helper.hpp"
+#include "file-item.pb.hpp"
#include "file-state.hpp"
#include "sync-log.hpp"
-#include "action-item.pb.hpp"
-#include "file-item.pb.hpp"
-#include "ccnx-wrapper.hpp"
-#include "ccnx-pco.hpp"
#include <boost/tuple/tuple.hpp>
@@ -38,41 +38,43 @@
class ActionLog : public DbHelper
{
public:
- typedef boost::function<void (std::string /*filename*/, Ndnx::Name /*device_name*/, sqlite3_int64 /*seq_no*/,
- HashPtr /*hash*/, time_t /*m_time*/, int /*mode*/, int /*seg_num*/)> OnFileAddedOrChangedCallback;
+ typedef boost::function<void(std::string /*filename*/, Ccnx::Name /*device_name*/, sqlite3_int64 /*seq_no*/,
+ HashPtr /*hash*/, time_t /*m_time*/, int /*mode*/, int /*seg_num*/)>
+ OnFileAddedOrChangedCallback;
- typedef boost::function<void (std::string /*filename*/)> OnFileRemovedCallback;
+ typedef boost::function<void(std::string /*filename*/)> OnFileRemovedCallback;
public:
- ActionLog (Ndnx::NdnxWrapperPtr ndnx, const boost::filesystem::path &path,
- SyncLogPtr syncLog,
- const std::string &sharedFolder, const std::string &appName,
- OnFileAddedOrChangedCallback onFileAddedOrChanged, OnFileRemovedCallback onFileRemoved);
+ ActionLog(Ccnx::CcnxWrapperPtr ccnx, const boost::filesystem::path& path, SyncLogPtr syncLog,
+ const std::string& sharedFolder, const std::string& appName,
+ OnFileAddedOrChangedCallback onFileAddedOrChanged, OnFileRemovedCallback onFileRemoved);
- virtual ~ActionLog () { }
+ virtual ~ActionLog()
+ {
+ }
//////////////////////////
// Local operations //
//////////////////////////
ActionItemPtr
- AddLocalActionUpdate (const std::string &filename,
- const Hash &hash,
- time_t wtime,
- int mode,
- int seg_num);
+ AddLocalActionUpdate(const std::string& filename,
+ const Hash& hash,
+ time_t wtime,
+ int mode,
+ int seg_num);
// void
// AddActionMove (const std::string &oldFile, const std::string &newFile);
ActionItemPtr
- AddLocalActionDelete (const std::string &filename);
+ AddLocalActionDelete(const std::string& filename);
//////////////////////////
// Remote operations //
//////////////////////////
ActionItemPtr
- AddRemoteAction (const Ndnx::Name &deviceName, sqlite3_int64 seqno, Ndnx::PcoPtr actionPco);
+ AddRemoteAction(const Ccnx::Name& deviceName, sqlite3_int64 seqno, Ccnx::PcoPtr actionPco);
/**
* @brief Add remote action using just action's parsed content object
@@ -80,56 +82,59 @@
* This function extracts device name and sequence number from the content object's and calls the overloaded method
*/
ActionItemPtr
- AddRemoteAction (Ndnx::PcoPtr actionPco);
+ AddRemoteAction(Ccnx::PcoPtr actionPco);
///////////////////////////
// General operations //
///////////////////////////
- Ndnx::PcoPtr
- LookupActionPco (const Ndnx::Name &deviceName, sqlite3_int64 seqno);
+ Ccnx::PcoPtr
+ LookupActionPco(const Ccnx::Name& deviceName, sqlite3_int64 seqno);
- Ndnx::PcoPtr
- LookupActionPco (const Ndnx::Name &actionName);
+ Ccnx::PcoPtr
+ LookupActionPco(const Ccnx::Name& actionName);
ActionItemPtr
- LookupAction (const Ndnx::Name &deviceName, sqlite3_int64 seqno);
+ LookupAction(const Ccnx::Name& deviceName, sqlite3_int64 seqno);
ActionItemPtr
- LookupAction (const Ndnx::Name &actionName);
+ LookupAction(const Ccnx::Name& actionName);
FileItemPtr
- LookupAction (const std::string &filename, sqlite3_int64 version, const Hash &filehash);
+ LookupAction(const std::string& filename, sqlite3_int64 version, const Hash& filehash);
/**
* @brief Lookup up to [limit] actions starting [offset] in decreasing order (by timestamp) and calling visitor(device_name,seqno,action) for each action
*/
bool
- LookupActionsInFolderRecursively (const boost::function<void (const Ndnx::Name &name, sqlite3_int64 seq_no, const ActionItem &)> &visitor,
- const std::string &folder, int offset=0, int limit=-1);
+ LookupActionsInFolderRecursively(
+ const boost::function<void(const Ccnx::Name& name, sqlite3_int64 seq_no, const ActionItem&)>& visitor,
+ const std::string& folder, int offset = 0, int limit = -1);
bool
- LookupActionsForFile (const boost::function<void (const Ndnx::Name &name, sqlite3_int64 seq_no, const ActionItem &)> &visitor,
- const std::string &file, int offset=0, int limit=-1);
+ LookupActionsForFile(
+ const boost::function<void(const Ccnx::Name& name, sqlite3_int64 seq_no, const ActionItem&)>& visitor,
+ const std::string& file, int offset = 0, int limit = -1);
void
- LookupRecentFileActions(const boost::function<void (const std::string &, int, int)> &visitor, int limit = 5);
+ LookupRecentFileActions(const boost::function<void(const std::string&, int, int)>& visitor,
+ int limit = 5);
//
inline FileStatePtr
- GetFileState ();
+ GetFileState();
public:
// for test purposes
sqlite3_int64
- LogSize ();
+ LogSize();
private:
- boost::tuple<sqlite3_int64 /*version*/, Ndnx::NdnxCharbufPtr /*device name*/, sqlite3_int64 /*seq_no*/>
- GetLatestActionForFile (const std::string &filename);
+ boost::tuple<sqlite3_int64 /*version*/, Ccnx::CcnxCharbufPtr /*device name*/, sqlite3_int64 /*seq_no*/>
+ GetLatestActionForFile(const std::string& filename);
static void
- apply_action_xFun (sqlite3_context *context, int argc, sqlite3_value **argv);
+ apply_action_xFun(sqlite3_context* context, int argc, sqlite3_value** argv);
private:
SyncLogPtr m_syncLog;
@@ -140,15 +145,17 @@
std::string m_appName;
OnFileAddedOrChangedCallback m_onFileAddedOrChanged;
- OnFileRemovedCallback m_onFileRemoved;
+ OnFileRemovedCallback m_onFileRemoved;
};
namespace Error {
-struct ActionLog : virtual boost::exception, virtual std::exception { };
+struct ActionLog : virtual boost::exception, virtual std::exception
+{
+};
}
inline FileStatePtr
-ActionLog::GetFileState ()
+ActionLog::GetFileState()
{
return m_fileState;
}
diff --git a/src/content-server.cpp b/src/content-server.cpp
index 26c45f8..bbd9235 100644
--- a/src/content-server.cpp
+++ b/src/content-server.cpp
@@ -20,14 +20,14 @@
#include "content-server.hpp"
#include "logging.hpp"
-#include <boost/make_shared.hpp>
-#include <utility>
-#include "task.hpp"
#include "periodic-task.hpp"
#include "simple-interval-generator.hpp"
+#include "task.hpp"
#include <boost/lexical_cast.hpp>
+#include <boost/make_shared.hpp>
+#include <utility>
-INIT_LOGGER ("ContentServer");
+INIT_LOGGER("ContentServer");
using namespace Ndnx;
using namespace std;
@@ -35,65 +35,68 @@
static const int DB_CACHE_LIFETIME = 60;
-ContentServer::ContentServer(NdnxWrapperPtr ndnx, ActionLogPtr actionLog,
- const boost::filesystem::path &rootDir,
- const Ndnx::Name &userName, const std::string &sharedFolderName,
- const std::string &appName,
+ContentServer::ContentServer(CcnxWrapperPtr ccnx, ActionLogPtr actionLog,
+ const boost::filesystem::path& rootDir, const Ccnx::Name& userName,
+ const std::string& sharedFolderName, const std::string& appName,
int freshness)
: m_ndnx(ndnx)
, m_actionLog(actionLog)
, m_dbFolder(rootDir / ".chronoshare")
, m_freshness(freshness)
- , m_scheduler (new Scheduler())
- , m_userName (userName)
- , m_sharedFolderName (sharedFolderName)
- , m_appName (appName)
+ , m_scheduler(new Scheduler())
+ , m_userName(userName)
+ , m_sharedFolderName(sharedFolderName)
+ , m_appName(appName)
{
- m_scheduler->start ();
- TaskPtr flushStaleDbCacheTask = boost::make_shared<PeriodicTask>(boost::bind(&ContentServer::flushStaleDbCache, this), "flush-state-db-cache", m_scheduler, boost::make_shared<SimpleIntervalGenerator>(DB_CACHE_LIFETIME));
+ m_scheduler->start();
+ TaskPtr flushStaleDbCacheTask =
+ boost::make_shared<PeriodicTask>(boost::bind(&ContentServer::flushStaleDbCache, this),
+ "flush-state-db-cache", m_scheduler,
+ boost::make_shared<SimpleIntervalGenerator>(DB_CACHE_LIFETIME));
m_scheduler->addTask(flushStaleDbCacheTask);
}
ContentServer::~ContentServer()
{
- m_scheduler->shutdown ();
+ m_scheduler->shutdown();
- ScopedLock lock (m_mutex);
- for (PrefixIt forwardingHint = m_prefixes.begin(); forwardingHint != m_prefixes.end(); ++forwardingHint)
- {
- m_ndnx->clearInterestFilter (*forwardingHint);
+ ScopedLock lock(m_mutex);
+ for (PrefixIt forwardingHint = m_prefixes.begin(); forwardingHint != m_prefixes.end();
+ ++forwardingHint) {
+ m_ccnx->clearInterestFilter(*forwardingHint);
}
- m_prefixes.clear ();
+ m_prefixes.clear();
}
void
-ContentServer::registerPrefix(const Name &forwardingHint)
+ContentServer::registerPrefix(const Name& forwardingHint)
{
// Format for files: /<forwarding-hint>/<device_name>/<appname>/file/<hash>/<segment>
// Format for actions: /<forwarding-hint>/<device_name>/<appname>/action/<shared-folder>/<action-seq>
- _LOG_DEBUG (">> content server: register " << forwardingHint);
+ _LOG_DEBUG(">> content server: register " << forwardingHint);
- m_ndnx->setInterestFilter (forwardingHint, bind(&ContentServer::filterAndServe, this, forwardingHint, _1));
+ m_ccnx->setInterestFilter(forwardingHint,
+ bind(&ContentServer::filterAndServe, this, forwardingHint, _1));
- ScopedLock lock (m_mutex);
+ ScopedLock lock(m_mutex);
m_prefixes.insert(forwardingHint);
}
void
-ContentServer::deregisterPrefix (const Name &forwardingHint)
+ContentServer::deregisterPrefix(const Name& forwardingHint)
{
- _LOG_DEBUG ("<< content server: deregister " << forwardingHint);
- m_ndnx->clearInterestFilter(forwardingHint);
+ _LOG_DEBUG("<< content server: deregister " << forwardingHint);
+ m_ccnx->clearInterestFilter(forwardingHint);
- ScopedLock lock (m_mutex);
- m_prefixes.erase (forwardingHint);
+ ScopedLock lock(m_mutex);
+ m_prefixes.erase(forwardingHint);
}
void
-ContentServer::filterAndServeImpl (const Name &forwardingHint, const Name &name, const Name &interest)
+ContentServer::filterAndServeImpl(const Name& forwardingHint, const Name& name, const Name& interest)
{
// interest for files: /<forwarding-hint>/<device_name>/<appname>/file/<hash>/<segment>
// interest for actions: /<forwarding-hint>/<device_name>/<appname>/action/<shared-folder>/<action-seq>
@@ -101,175 +104,160 @@
// name for files: /<device_name>/<appname>/file/<hash>/<segment>
// name for actions: /<device_name>/<appname>/action/<shared-folder>/<action-seq>
- try
- {
- if (name.size() >= 4 && name.getCompFromBackAsString (3) == m_appName)
- {
- string type = name.getCompFromBackAsString (2);
- if (type == "file")
- {
- serve_File (forwardingHint, name, interest);
- }
- else if (type == "action")
- {
- string folder = name.getCompFromBackAsString (1);
- if (folder == m_sharedFolderName)
- {
- serve_Action (forwardingHint, name, interest);
- }
- }
+ try {
+ if (name.size() >= 4 && name.getCompFromBackAsString(3) == m_appName) {
+ string type = name.getCompFromBackAsString(2);
+ if (type == "file") {
+ serve_File(forwardingHint, name, interest);
+ }
+ else if (type == "action") {
+ string folder = name.getCompFromBackAsString(1);
+ if (folder == m_sharedFolderName) {
+ serve_Action(forwardingHint, name, interest);
}
+ }
}
- catch (Ndnx::NameException &ne)
- {
- // ignore any unexpected interests and errors
- _LOG_ERROR(boost::get_error_info<Ndnx::error_info_str>(ne));
- }
+ }
+ catch (Ccnx::NameException& ne) {
+ // ignore any unexpected interests and errors
+ _LOG_ERROR(boost::get_error_info<Ccnx::error_info_str>(ne));
+ }
}
void
-ContentServer::filterAndServe (Name forwardingHint, const Name &interest)
+ContentServer::filterAndServe(Name forwardingHint, const Name& interest)
{
- try
- {
- if (forwardingHint.size () > 0 &&
- m_userName.size () >= forwardingHint.size () &&
- m_userName.getPartialName (0, forwardingHint.size ()) == forwardingHint)
- {
- filterAndServeImpl (Name ("/"), interest, interest); // try without forwarding hints
- }
-
- filterAndServeImpl (forwardingHint, interest.getPartialName (forwardingHint.size()), interest); // always try with hint... :( have to
+ try {
+ if (forwardingHint.size() > 0 && m_userName.size() >= forwardingHint.size() &&
+ m_userName.getPartialName(0, forwardingHint.size()) == forwardingHint) {
+ filterAndServeImpl(Name("/"), interest, interest); // try without forwarding hints
}
- catch (Ndnx::NameException &ne)
- {
- // ignore any unexpected interests and errors
- _LOG_ERROR(boost::get_error_info<Ndnx::error_info_str>(ne));
- }
+
+ filterAndServeImpl(forwardingHint, interest.getPartialName(forwardingHint.size()),
+ interest); // always try with hint... :( have to
+ }
+ catch (Ccnx::NameException& ne) {
+ // ignore any unexpected interests and errors
+ _LOG_ERROR(boost::get_error_info<Ccnx::error_info_str>(ne));
+ }
}
void
-ContentServer::serve_Action (const Name &forwardingHint, const Name &name, const Name &interest)
+ContentServer::serve_Action(const Name& forwardingHint, const Name& name, const Name& interest)
{
- _LOG_DEBUG (">> content server serving ACTION, hint: " << forwardingHint << ", interest: " << interest);
- m_scheduler->scheduleOneTimeTask (m_scheduler, 0, bind (&ContentServer::serve_Action_Execute, this, forwardingHint, name, interest), boost::lexical_cast<string>(name));
- // need to unlock ndnx mutex... or at least don't lock it
+ _LOG_DEBUG(">> content server serving ACTION, hint: " << forwardingHint
+ << ", interest: " << interest);
+ m_scheduler->scheduleOneTimeTask(m_scheduler, 0, bind(&ContentServer::serve_Action_Execute, this,
+ forwardingHint, name, interest),
+ boost::lexical_cast<string>(name));
+ // need to unlock ccnx mutex... or at least don't lock it
}
void
-ContentServer::serve_File (const Name &forwardingHint, const Name &name, const Name &interest)
+ContentServer::serve_File(const Name& forwardingHint, const Name& name, const Name& interest)
{
- _LOG_DEBUG (">> content server serving FILE, hint: " << forwardingHint << ", interest: " << interest);
+ _LOG_DEBUG(">> content server serving FILE, hint: " << forwardingHint
+ << ", interest: " << interest);
- m_scheduler->scheduleOneTimeTask (m_scheduler, 0, bind (&ContentServer::serve_File_Execute, this, forwardingHint, name, interest), boost::lexical_cast<string>(name));
- // need to unlock ndnx mutex... or at least don't lock it
+ m_scheduler->scheduleOneTimeTask(m_scheduler, 0, bind(&ContentServer::serve_File_Execute, this,
+ forwardingHint, name, interest),
+ boost::lexical_cast<string>(name));
+ // need to unlock ccnx mutex... or at least don't lock it
}
void
-ContentServer::serve_File_Execute (const Name &forwardingHint, const Name &name, const Name &interest)
+ContentServer::serve_File_Execute(const Name& forwardingHint, const Name& name, const Name& interest)
{
// forwardingHint: /<forwarding-hint>
// interest: /<forwarding-hint>/<device_name>/<appname>/file/<hash>/<segment>
// name: /<device_name>/<appname>/file/<hash>/<segment>
- int64_t segment = name.getCompFromBackAsInt (0);
- Name deviceName = name.getPartialName (0, name.size () - 4);
- Hash hash (head(name.getCompFromBack (1)), name.getCompFromBack (1).size());
+ int64_t segment = name.getCompFromBackAsInt(0);
+ Name deviceName = name.getPartialName(0, name.size() - 4);
+ Hash hash(head(name.getCompFromBack(1)), name.getCompFromBack(1).size());
- _LOG_DEBUG (" server FILE for device: " << deviceName << ", file_hash: " << hash.shortHash () << " segment: " << segment);
+ _LOG_DEBUG(" server FILE for device: " << deviceName << ", file_hash: " << hash.shortHash()
+ << " segment: "
+ << segment);
- string hashStr = lexical_cast<string> (hash);
+ string hashStr = lexical_cast<string>(hash);
ObjectDbPtr db;
ScopedLock(m_dbCacheMutex);
{
DbCache::iterator it = m_dbCache.find(hash);
- if (it != m_dbCache.end())
- {
+ if (it != m_dbCache.end()) {
db = it->second;
}
- else
- {
- if (ObjectDb::DoesExist (m_dbFolder, deviceName, hashStr)) // this is kind of overkill, as it counts available segments
- {
- db = boost::make_shared<ObjectDb>(m_dbFolder, hashStr);
- m_dbCache.insert(make_pair(hash, db));
- }
- else
- {
- _LOG_ERROR ("ObjectDd doesn't exist for device: " << deviceName << ", file_hash: " << hash.shortHash ());
- }
+ else {
+ if (ObjectDb::DoesExist(m_dbFolder, deviceName,
+ hashStr)) // this is kind of overkill, as it counts available segments
+ {
+ db = boost::make_shared<ObjectDb>(m_dbFolder, hashStr);
+ m_dbCache.insert(make_pair(hash, db));
+ }
+ else {
+ _LOG_ERROR("ObjectDd doesn't exist for device: " << deviceName << ", file_hash: "
+ << hash.shortHash());
+ }
}
}
- if (db)
- {
- BytesPtr co = db->fetchSegment (deviceName, segment);
- if (co)
- {
- if (forwardingHint.size () == 0)
- {
- _LOG_DEBUG (ParsedContentObject (*co).name ());
- m_ndnx->putToNdnd (*co);
- }
- else
- {
- if (m_freshness > 0)
- {
- m_ndnx->publishData(interest, *co, m_freshness);
- }
- else
- {
- m_ndnx->publishData(interest, *co);
- }
- }
-
+ if (db) {
+ BytesPtr co = db->fetchSegment(deviceName, segment);
+ if (co) {
+ if (forwardingHint.size() == 0) {
+ _LOG_DEBUG(ParsedContentObject(*co).name());
+ m_ccnx->putToCcnd(*co);
}
- else
- {
- _LOG_ERROR ("ObjectDd exists, but no segment " << segment << " for device: " << deviceName << ", file_hash: " << hash.shortHash ());
+ else {
+ if (m_freshness > 0) {
+ m_ccnx->publishData(interest, *co, m_freshness);
+ }
+ else {
+ m_ccnx->publishData(interest, *co);
+ }
}
-
+ }
+ else {
+ _LOG_ERROR("ObjectDd exists, but no segment " << segment << " for device: " << deviceName
+ << ", file_hash: "
+ << hash.shortHash());
+ }
}
}
void
-ContentServer::serve_Action_Execute (const Name &forwardingHint, const Name &name, const Name &interest)
+ContentServer::serve_Action_Execute(const Name& forwardingHint, const Name& name, const Name& interest)
{
// forwardingHint: /<forwarding-hint>
// interest: /<forwarding-hint>/<device_name>/<appname>/action/<shared-folder>/<action-seq>
// name for actions: /<device_name>/<appname>/action/<shared-folder>/<action-seq>
- int64_t seqno = name.getCompFromBackAsInt (0);
- Name deviceName = name.getPartialName (0, name.size () - 4);
+ int64_t seqno = name.getCompFromBackAsInt(0);
+ Name deviceName = name.getPartialName(0, name.size() - 4);
- _LOG_DEBUG (" server ACTION for device: " << deviceName << " and seqno: " << seqno);
+ _LOG_DEBUG(" server ACTION for device: " << deviceName << " and seqno: " << seqno);
- PcoPtr pco = m_actionLog->LookupActionPco (deviceName, seqno);
- if (pco)
- {
- if (forwardingHint.size () == 0)
- {
- m_ndnx->putToNdnd (pco->buf ());
- }
- else
- {
- const Bytes &content = pco->buf ();
- if (m_freshness > 0)
- {
- m_ndnx->publishData(interest, content, m_freshness);
- }
- else
- {
- m_ndnx->publishData(interest, content);
- }
- }
+ PcoPtr pco = m_actionLog->LookupActionPco(deviceName, seqno);
+ if (pco) {
+ if (forwardingHint.size() == 0) {
+ m_ccnx->putToCcnd(pco->buf());
}
- else
- {
- _LOG_ERROR ("ACTION not found for device: " << deviceName << " and seqno: " << seqno);
+ else {
+ const Bytes& content = pco->buf();
+ if (m_freshness > 0) {
+ m_ccnx->publishData(interest, content, m_freshness);
+ }
+ else {
+ m_ccnx->publishData(interest, content);
+ }
}
+ }
+ else {
+ _LOG_ERROR("ACTION not found for device: " << deviceName << " and seqno: " << seqno);
+ }
}
void
@@ -277,15 +265,12 @@
{
ScopedLock(m_dbCacheMutex);
DbCache::iterator it = m_dbCache.begin();
- while (it != m_dbCache.end())
- {
+ while (it != m_dbCache.end()) {
ObjectDbPtr db = it->second;
- if (db->secondsSinceLastUse() >= DB_CACHE_LIFETIME)
- {
+ if (db->secondsSinceLastUse() >= DB_CACHE_LIFETIME) {
m_dbCache.erase(it++);
}
- else
- {
+ else {
++it;
}
}
diff --git a/src/content-server.hpp b/src/content-server.hpp
index ff046e3..c8676a1 100644
--- a/src/content-server.hpp
+++ b/src/content-server.hpp
@@ -21,48 +21,53 @@
#ifndef CONTENT_SERVER_H
#define CONTENT_SERVER_H
+#include "action-log.hpp"
#include "ccnx-wrapper.hpp"
#include "object-db.hpp"
-#include "action-log.hpp"
-#include <set>
-#include <map>
-#include <boost/thread/shared_mutex.hpp>
-#include <boost/thread/locks.hpp>
#include "scheduler.hpp"
+#include <boost/thread/locks.hpp>
+#include <boost/thread/shared_mutex.hpp>
+#include <map>
+#include <set>
class ContentServer
{
public:
- ContentServer(Ndnx::NdnxWrapperPtr ndnx, ActionLogPtr actionLog, const boost::filesystem::path &rootDir,
- const Ndnx::Name &userName, const std::string &sharedFolderName, const std::string &appName,
- int freshness = -1);
+ ContentServer(Ccnx::CcnxWrapperPtr ccnx, ActionLogPtr actionLog,
+ const boost::filesystem::path& rootDir, const Ccnx::Name& userName,
+ const std::string& sharedFolderName, const std::string& appName, int freshness = -1);
~ContentServer();
// the assumption is, when the interest comes in, interest is informs of
// /some-prefix/topology-independent-name
// currently /topology-independent-name must begin with /action or /file
// so that ContentServer knows where to look for the content object
- void registerPrefix(const Ndnx::Name &prefix);
- void deregisterPrefix(const Ndnx::Name &prefix);
+ void
+ registerPrefix(const Ccnx::Name& prefix);
+ void
+ deregisterPrefix(const Ccnx::Name& prefix);
private:
void
- filterAndServe (Ndnx::Name forwardingHint, const Ndnx::Name &interest);
+ filterAndServe(Ccnx::Name forwardingHint, const Ccnx::Name& interest);
void
- filterAndServeImpl (const Ndnx::Name &forwardingHint, const Ndnx::Name &name, const Ndnx::Name &interest);
+ filterAndServeImpl(const Ccnx::Name& forwardingHint, const Ccnx::Name& name,
+ const Ccnx::Name& interest);
void
- serve_Action (const Ndnx::Name &forwardingHint, const Ndnx::Name &name, const Ndnx::Name &interest);
+ serve_Action(const Ccnx::Name& forwardingHint, const Ccnx::Name& name, const Ccnx::Name& interest);
void
- serve_File (const Ndnx::Name &forwardingHint, const Ndnx::Name &name, const Ndnx::Name &interest);
+ serve_File(const Ccnx::Name& forwardingHint, const Ccnx::Name& name, const Ccnx::Name& interest);
void
- serve_Action_Execute(const Ndnx::Name &forwardingHint, const Ndnx::Name &name, const Ndnx::Name &interest);
+ serve_Action_Execute(const Ccnx::Name& forwardingHint, const Ccnx::Name& name,
+ const Ccnx::Name& interest);
void
- serve_File_Execute(const Ndnx::Name &forwardingHint, const Ndnx::Name &name, const Ndnx::Name &interest);
+ serve_File_Execute(const Ccnx::Name& forwardingHint, const Ccnx::Name& name,
+ const Ccnx::Name& interest);
void
flushStaleDbCache();
@@ -79,12 +84,12 @@
boost::filesystem::path m_dbFolder;
int m_freshness;
- SchedulerPtr m_scheduler;
+ SchedulerPtr m_scheduler;
typedef std::map<Hash, ObjectDbPtr> DbCache;
DbCache m_dbCache;
Mutex m_dbCacheMutex;
- Ndnx::Name m_userName;
+ Ccnx::Name m_userName;
std::string m_sharedFolderName;
std::string m_appName;
};
diff --git a/src/db-helper.cpp b/src/db-helper.cpp
index 7b8115d..e677a75 100644
--- a/src/db-helper.cpp
+++ b/src/db-helper.cpp
@@ -25,7 +25,7 @@
#include <boost/ref.hpp>
#include <boost/throw_exception.hpp>
-INIT_LOGGER ("DbHelper");
+INIT_LOGGER("DbHelper");
using namespace boost;
namespace fs = boost::filesystem;
@@ -34,223 +34,201 @@
PRAGMA foreign_keys = ON; \
";
-DbHelper::DbHelper (const fs::path &path, const std::string &dbname)
+DbHelper::DbHelper(const fs::path& path, const std::string& dbname)
{
- fs::create_directories (path);
+ fs::create_directories(path);
- int res = sqlite3_open((path / dbname).c_str (), &m_db);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Cannot open/create dabatabase: [" + (path / dbname).string () + "]"));
- }
+ int res = sqlite3_open((path / dbname).c_str(), &m_db);
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Cannot open/create dabatabase: [" +
+ (path / dbname).string() + "]"));
+ }
- res = sqlite3_create_function (m_db, "hash", 2, SQLITE_ANY, 0, 0,
- DbHelper::hash_xStep, DbHelper::hash_xFinal);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Cannot create function ``hash''"));
- }
+ res = sqlite3_create_function(m_db, "hash", 2, SQLITE_ANY, 0, 0, DbHelper::hash_xStep,
+ DbHelper::hash_xFinal);
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Cannot create function ``hash''"));
+ }
- res = sqlite3_create_function (m_db, "is_prefix", 2, SQLITE_ANY, 0, DbHelper::is_prefix_xFun, 0, 0);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Cannot create function ``is_prefix''"));
- }
+ res = sqlite3_create_function(m_db, "is_prefix", 2, SQLITE_ANY, 0, DbHelper::is_prefix_xFun, 0, 0);
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Cannot create function ``is_prefix''"));
+ }
- res = sqlite3_create_function (m_db, "directory_name", -1, SQLITE_ANY, 0, DbHelper::directory_name_xFun, 0, 0);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Cannot create function ``directory_name''"));
- }
+ res = sqlite3_create_function(m_db, "directory_name", -1, SQLITE_ANY, 0,
+ DbHelper::directory_name_xFun, 0, 0);
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db()
+ << errmsg_info_str("Cannot create function ``directory_name''"));
+ }
- res = sqlite3_create_function (m_db, "is_dir_prefix", 2, SQLITE_ANY, 0, DbHelper::is_dir_prefix_xFun, 0, 0);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Cannot create function ``is_dir_prefix''"));
- }
+ res = sqlite3_create_function(m_db, "is_dir_prefix", 2, SQLITE_ANY, 0,
+ DbHelper::is_dir_prefix_xFun, 0, 0);
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Cannot create function ``is_dir_prefix''"));
+ }
- sqlite3_exec (m_db, INIT_DATABASE.c_str (), NULL, NULL, NULL);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_exec(m_db, INIT_DATABASE.c_str(), NULL, NULL, NULL);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
}
-DbHelper::~DbHelper ()
+DbHelper::~DbHelper()
{
- int res = sqlite3_close (m_db);
- if (res != SQLITE_OK)
- {
- // complain
- }
+ int res = sqlite3_close(m_db);
+ if (res != SQLITE_OK) {
+ // complain
+ }
}
void
-DbHelper::hash_xStep (sqlite3_context *context, int argc, sqlite3_value **argv)
+DbHelper::hash_xStep(sqlite3_context* context, int argc, sqlite3_value** argv)
{
- if (argc != 2)
- {
- // _LOG_ERROR ("Wrong arguments are supplied for ``hash'' function");
- sqlite3_result_error (context, "Wrong arguments are supplied for ``hash'' function", -1);
- return;
- }
- if (sqlite3_value_type (argv[0]) != SQLITE_BLOB ||
- sqlite3_value_type (argv[1]) != SQLITE_INTEGER)
- {
- // _LOG_ERROR ("Hash expects (blob,integer) parameters");
- sqlite3_result_error (context, "Hash expects (blob,integer) parameters", -1);
- return;
- }
+ if (argc != 2) {
+ // _LOG_ERROR ("Wrong arguments are supplied for ``hash'' function");
+ sqlite3_result_error(context, "Wrong arguments are supplied for ``hash'' function", -1);
+ return;
+ }
+ if (sqlite3_value_type(argv[0]) != SQLITE_BLOB || sqlite3_value_type(argv[1]) != SQLITE_INTEGER) {
+ // _LOG_ERROR ("Hash expects (blob,integer) parameters");
+ sqlite3_result_error(context, "Hash expects (blob,integer) parameters", -1);
+ return;
+ }
- EVP_MD_CTX **hash_context = reinterpret_cast<EVP_MD_CTX **> (sqlite3_aggregate_context (context, sizeof (EVP_MD_CTX *)));
+ EVP_MD_CTX** hash_context =
+ reinterpret_cast<EVP_MD_CTX**>(sqlite3_aggregate_context(context, sizeof(EVP_MD_CTX*)));
- if (hash_context == 0)
- {
- sqlite3_result_error_nomem (context);
- return;
- }
+ if (hash_context == 0) {
+ sqlite3_result_error_nomem(context);
+ return;
+ }
- if (*hash_context == 0)
- {
- *hash_context = EVP_MD_CTX_create ();
- EVP_DigestInit_ex (*hash_context, HASH_FUNCTION (), 0);
- }
+ if (*hash_context == 0) {
+ *hash_context = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(*hash_context, HASH_FUNCTION(), 0);
+ }
- int nameBytes = sqlite3_value_bytes (argv[0]);
- const void *name = sqlite3_value_blob (argv[0]);
- sqlite3_int64 seqno = sqlite3_value_int64 (argv[1]);
+ int nameBytes = sqlite3_value_bytes(argv[0]);
+ const void* name = sqlite3_value_blob(argv[0]);
+ sqlite3_int64 seqno = sqlite3_value_int64(argv[1]);
- EVP_DigestUpdate (*hash_context, name, nameBytes);
- EVP_DigestUpdate (*hash_context, &seqno, sizeof(sqlite3_int64));
+ EVP_DigestUpdate(*hash_context, name, nameBytes);
+ EVP_DigestUpdate(*hash_context, &seqno, sizeof(sqlite3_int64));
}
void
-DbHelper::hash_xFinal (sqlite3_context *context)
+DbHelper::hash_xFinal(sqlite3_context* context)
{
- EVP_MD_CTX **hash_context = reinterpret_cast<EVP_MD_CTX **> (sqlite3_aggregate_context (context, sizeof (EVP_MD_CTX *)));
+ EVP_MD_CTX** hash_context =
+ reinterpret_cast<EVP_MD_CTX**>(sqlite3_aggregate_context(context, sizeof(EVP_MD_CTX*)));
- if (hash_context == 0)
- {
- sqlite3_result_error_nomem (context);
- return;
- }
+ if (hash_context == 0) {
+ sqlite3_result_error_nomem(context);
+ return;
+ }
if (*hash_context == 0) // no rows
- {
- char charNullResult = 0;
- sqlite3_result_blob (context, &charNullResult, 1, SQLITE_TRANSIENT); //SQLITE_TRANSIENT forces to make a copy
- return;
- }
+ {
+ char charNullResult = 0;
+ sqlite3_result_blob(context, &charNullResult, 1,
+ SQLITE_TRANSIENT); //SQLITE_TRANSIENT forces to make a copy
+ return;
+ }
- unsigned char *hash = new unsigned char [EVP_MAX_MD_SIZE];
+ unsigned char* hash = new unsigned char[EVP_MAX_MD_SIZE];
unsigned int hashLength = 0;
- int ok = EVP_DigestFinal_ex (*hash_context,
- hash, &hashLength);
+ int ok = EVP_DigestFinal_ex(*hash_context, hash, &hashLength);
- sqlite3_result_blob (context, hash, hashLength, SQLITE_TRANSIENT); //SQLITE_TRANSIENT forces to make a copy
- delete [] hash;
+ sqlite3_result_blob(context, hash, hashLength,
+ SQLITE_TRANSIENT); //SQLITE_TRANSIENT forces to make a copy
+ delete[] hash;
- EVP_MD_CTX_destroy (*hash_context);
+ EVP_MD_CTX_destroy(*hash_context);
}
void
-DbHelper::is_prefix_xFun (sqlite3_context *context, int argc, sqlite3_value **argv)
+DbHelper::is_prefix_xFun(sqlite3_context* context, int argc, sqlite3_value** argv)
{
- int len1 = sqlite3_value_bytes (argv[0]);
- int len2 = sqlite3_value_bytes (argv[1]);
+ int len1 = sqlite3_value_bytes(argv[0]);
+ int len2 = sqlite3_value_bytes(argv[1]);
- if (len1 == 0)
- {
- sqlite3_result_int (context, 1);
- return;
- }
+ if (len1 == 0) {
+ sqlite3_result_int(context, 1);
+ return;
+ }
if (len1 > len2) // first parameter should be at most equal in length to the second one
- {
- sqlite3_result_int (context, 0);
- return;
- }
+ {
+ sqlite3_result_int(context, 0);
+ return;
+ }
- if (memcmp (sqlite3_value_blob (argv[0]), sqlite3_value_blob (argv[1]), len1) == 0)
- {
- sqlite3_result_int (context, 1);
- }
- else
- {
- sqlite3_result_int (context, 0);
- }
+ if (memcmp(sqlite3_value_blob(argv[0]), sqlite3_value_blob(argv[1]), len1) == 0) {
+ sqlite3_result_int(context, 1);
+ }
+ else {
+ sqlite3_result_int(context, 0);
+ }
}
void
-DbHelper::directory_name_xFun (sqlite3_context *context, int argc, sqlite3_value **argv)
+DbHelper::directory_name_xFun(sqlite3_context* context, int argc, sqlite3_value** argv)
{
- if (argc != 1)
- {
- sqlite3_result_error (context, "``directory_name'' expects 1 text argument", -1);
- sqlite3_result_null (context);
- return;
- }
+ if (argc != 1) {
+ sqlite3_result_error(context, "``directory_name'' expects 1 text argument", -1);
+ sqlite3_result_null(context);
+ return;
+ }
- if (sqlite3_value_bytes (argv[0]) == 0)
- {
- sqlite3_result_null (context);
- return;
- }
+ if (sqlite3_value_bytes(argv[0]) == 0) {
+ sqlite3_result_null(context);
+ return;
+ }
- boost::filesystem::path filePath (std::string (reinterpret_cast<const char*> (sqlite3_value_text (argv[0])), sqlite3_value_bytes (argv[0])));
- std::string dirPath = filePath.parent_path ().generic_string ();
- // _LOG_DEBUG ("directory_name FUN: " << dirPath);
- if (dirPath.size () == 0)
- {
- sqlite3_result_null (context);
- }
- else
- {
- sqlite3_result_text (context, dirPath.c_str (), dirPath.size (), SQLITE_TRANSIENT);
- }
+ boost::filesystem::path filePath(
+ std::string(reinterpret_cast<const char*>(sqlite3_value_text(argv[0])),
+ sqlite3_value_bytes(argv[0])));
+ std::string dirPath = filePath.parent_path().generic_string();
+ // _LOG_DEBUG("directory_name FUN: " << dirPath);
+ if (dirPath.size() == 0) {
+ sqlite3_result_null(context);
+ }
+ else {
+ sqlite3_result_text(context, dirPath.c_str(), dirPath.size(), SQLITE_TRANSIENT);
+ }
}
void
-DbHelper::is_dir_prefix_xFun (sqlite3_context *context, int argc, sqlite3_value **argv)
+DbHelper::is_dir_prefix_xFun(sqlite3_context* context, int argc, sqlite3_value** argv)
{
- int len1 = sqlite3_value_bytes (argv[0]);
- int len2 = sqlite3_value_bytes (argv[1]);
+ int len1 = sqlite3_value_bytes(argv[0]);
+ int len2 = sqlite3_value_bytes(argv[1]);
- if (len1 == 0)
- {
- sqlite3_result_int (context, 1);
- return;
- }
+ if (len1 == 0) {
+ sqlite3_result_int(context, 1);
+ return;
+ }
if (len1 > len2) // first parameter should be at most equal in length to the second one
- {
- sqlite3_result_int (context, 0);
- return;
- }
+ {
+ sqlite3_result_int(context, 0);
+ return;
+ }
- if (memcmp (sqlite3_value_blob (argv[0]), sqlite3_value_blob (argv[1]), len1) == 0)
- {
- if (len1 == len2)
- {
- sqlite3_result_int (context, 1);
- }
- else
- {
- if (reinterpret_cast<const char*> (sqlite3_value_blob (argv[1]))[len1] == '/')
- {
- sqlite3_result_int (context, 1);
- }
- else
- {
- sqlite3_result_int (context, 0);
- }
- }
+ if (memcmp(sqlite3_value_blob(argv[0]), sqlite3_value_blob(argv[1]), len1) == 0) {
+ if (len1 == len2) {
+ sqlite3_result_int(context, 1);
}
- else
- {
- sqlite3_result_int (context, 0);
+ else {
+ if (reinterpret_cast<const char*>(sqlite3_value_blob(argv[1]))[len1] == '/') {
+ sqlite3_result_int(context, 1);
+ }
+ else {
+ sqlite3_result_int(context, 0);
+ }
}
+ }
+ else {
+ sqlite3_result_int(context, 0);
+ }
}
diff --git a/src/db-helper.hpp b/src/db-helper.hpp
index 632e126..7e75892 100644
--- a/src/db-helper.hpp
+++ b/src/db-helper.hpp
@@ -21,44 +21,46 @@
#ifndef DB_HELPER_H
#define DB_HELPER_H
-#include <stdint.h>
-#include <sqlite3.h>
-#include <openssl/evp.h>
-#include <boost/exception/all.hpp>
-#include <string>
#include "hash-helper.hpp"
+#include <boost/exception/all.hpp>
#include <boost/filesystem.hpp>
+#include <openssl/evp.h>
+#include <sqlite3.h>
+#include <stdint.h>
+#include <string>
typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info_str;
class DbHelper
{
public:
- DbHelper (const boost::filesystem::path &path, const std::string &dbname);
- virtual ~DbHelper ();
+ DbHelper(const boost::filesystem::path& path, const std::string& dbname);
+ virtual ~DbHelper();
private:
static void
- hash_xStep (sqlite3_context *context, int argc, sqlite3_value **argv);
+ hash_xStep(sqlite3_context* context, int argc, sqlite3_value** argv);
static void
- hash_xFinal (sqlite3_context *context);
+ hash_xFinal(sqlite3_context* context);
static void
- is_prefix_xFun (sqlite3_context *context, int argc, sqlite3_value **argv);
+ is_prefix_xFun(sqlite3_context* context, int argc, sqlite3_value** argv);
static void
- directory_name_xFun (sqlite3_context *context, int argc, sqlite3_value **argv);
+ directory_name_xFun(sqlite3_context* context, int argc, sqlite3_value** argv);
static void
- is_dir_prefix_xFun (sqlite3_context *context, int argc, sqlite3_value **argv);
+ is_dir_prefix_xFun(sqlite3_context* context, int argc, sqlite3_value** argv);
protected:
- sqlite3 *m_db;
+ sqlite3* m_db;
};
namespace Error {
-struct Db : virtual boost::exception, virtual std::exception { };
+struct Db : virtual boost::exception, virtual std::exception
+{
+};
}
typedef boost::shared_ptr<DbHelper> DbHelperPtr;
diff --git a/src/dispatcher.cpp b/src/dispatcher.cpp
index 831f588..4a07b14 100644
--- a/src/dispatcher.cpp
+++ b/src/dispatcher.cpp
@@ -19,161 +19,159 @@
*/
#include "dispatcher.hpp"
-#include "logging.hpp"
#include "ccnx-discovery.hpp"
#include "fetch-task-db.hpp"
+#include "logging.hpp"
-#include <boost/make_shared.hpp>
#include <boost/lexical_cast.hpp>
+#include <boost/make_shared.hpp>
using namespace Ndnx;
using namespace std;
using namespace boost;
-INIT_LOGGER ("Dispatcher");
+INIT_LOGGER("Dispatcher");
static const string CHRONOSHARE_APP = "chronoshare";
static const string BROADCAST_DOMAIN = "/ndn/broadcast";
-static const int CONTENT_FRESHNESS = 1800; // seconds
+static const int CONTENT_FRESHNESS = 1800; // seconds
const static double DEFAULT_SYNC_INTEREST_INTERVAL = 10.0; // seconds;
-Dispatcher::Dispatcher(const std::string &localUserName
- , const std::string &sharedFolder
- , const filesystem::path &rootDir
- , Ndnx::NdnxWrapperPtr ndnx
- , bool enablePrefixDiscovery
- )
- : m_ndnx(ndnx)
- , m_core(NULL)
- , m_rootDir(rootDir)
- , m_executor(1) // creates problems with file assembly. need to ensure somehow that FinishExectute is called after all Segment_Execute finished
- , m_objectManager(ndnx, rootDir, CHRONOSHARE_APP)
- , m_localUserName(localUserName)
- , m_sharedFolder(sharedFolder)
- , m_server(NULL)
- , m_enablePrefixDiscovery(enablePrefixDiscovery)
+Dispatcher::Dispatcher(const std::string& localUserName, const std::string& sharedFolder,
+ const filesystem::path& rootDir, Ccnx::CcnxWrapperPtr ccnx,
+ bool enablePrefixDiscovery)
+ : m_ccnx(ccnx)
+ , m_core(NULL)
+ , m_rootDir(rootDir)
+ , m_executor(
+ 1) // creates problems with file assembly. need to ensure somehow that FinishExectute is called after all Segment_Execute finished
+ , m_objectManager(ccnx, rootDir, CHRONOSHARE_APP)
+ , m_localUserName(localUserName)
+ , m_sharedFolder(sharedFolder)
+ , m_server(NULL)
+ , m_enablePrefixDiscovery(enablePrefixDiscovery)
{
m_syncLog = make_shared<SyncLog>(m_rootDir, localUserName);
- m_actionLog = make_shared<ActionLog>(m_ndnx, m_rootDir, m_syncLog, sharedFolder, CHRONOSHARE_APP,
- // bind (&Dispatcher::Did_ActionLog_ActionApply_AddOrModify, this, _1, _2, _3, _4, _5, _6, _7),
- ActionLog::OnFileAddedOrChangedCallback (), // don't really need this callback
- bind (&Dispatcher::Did_ActionLog_ActionApply_Delete, this, _1));
- m_fileState = m_actionLog->GetFileState ();
- m_fileStateCow = make_shared<FileState> (m_rootDir, true);
+ m_actionLog =
+ make_shared<ActionLog>(m_ccnx, m_rootDir, m_syncLog, sharedFolder, CHRONOSHARE_APP,
+ // bind (&Dispatcher::Did_ActionLog_ActionApply_AddOrModify, this, _1, _2, _3, _4, _5, _6, _7),
+ ActionLog::OnFileAddedOrChangedCallback(), // don't really need this callback
+ bind(&Dispatcher::Did_ActionLog_ActionApply_Delete, this, _1));
+ m_fileState = m_actionLog->GetFileState();
Name syncPrefix = Name(BROADCAST_DOMAIN)(CHRONOSHARE_APP)(sharedFolder);
- // m_server needs a different ndnx face
- m_server = new ContentServer(make_shared<NdnxWrapper>(), m_actionLog, rootDir, m_localUserName, m_sharedFolder, CHRONOSHARE_APP, CONTENT_FRESHNESS);
+ // m_server needs a different ccnx face
+ m_server = new ContentServer(make_shared<CcnxWrapper>(), m_actionLog, rootDir, m_localUserName,
+ m_sharedFolder, CHRONOSHARE_APP, CONTENT_FRESHNESS);
m_server->registerPrefix(Name("/"));
m_server->registerPrefix(Name(BROADCAST_DOMAIN));
- m_stateServer = new StateServer (make_shared<NdnxWrapper>(), m_actionLog, rootDir, m_localUserName, m_sharedFolder, CHRONOSHARE_APP, m_objectManager, CONTENT_FRESHNESS);
+ m_stateServer =
+ new StateServer(make_shared<CcnxWrapper>(), m_actionLog, rootDir, m_localUserName,
+ m_sharedFolder, CHRONOSHARE_APP, m_objectManager, CONTENT_FRESHNESS);
// no need to register, right now only listening on localhost prefix
- m_core = new SyncCore (m_syncLog, localUserName, Name("/"), syncPrefix,
- bind(&Dispatcher::Did_SyncLog_StateChange, this, _1), ndnx, DEFAULT_SYNC_INTEREST_INTERVAL);
+ m_core = new SyncCore(m_syncLog, localUserName, Name("/"), syncPrefix,
+ bind(&Dispatcher::Did_SyncLog_StateChange, this, _1), ccnx,
+ DEFAULT_SYNC_INTEREST_INTERVAL);
FetchTaskDbPtr actionTaskDb = make_shared<FetchTaskDb>(m_rootDir, "action");
- m_actionFetcher = make_shared<FetchManager> (m_ndnx, bind (&SyncLog::LookupLocator, &*m_syncLog, _1),
- Name(BROADCAST_DOMAIN), // no appname suffix now
- 3,
- bind (&Dispatcher::Did_FetchManager_ActionFetch, this, _1, _2, _3, _4), FetchManager::FinishCallback(), actionTaskDb);
+ m_actionFetcher =
+ make_shared<FetchManager>(m_ccnx, bind(&SyncLog::LookupLocator, &*m_syncLog, _1),
+ Name(BROADCAST_DOMAIN), // no appname suffix now
+ 3,
+ bind(&Dispatcher::Did_FetchManager_ActionFetch, this, _1, _2, _3, _4),
+ FetchManager::FinishCallback(), actionTaskDb);
FetchTaskDbPtr fileTaskDb = make_shared<FetchTaskDb>(m_rootDir, "file");
- m_fileFetcher = make_shared<FetchManager> (m_ndnx, bind (&SyncLog::LookupLocator, &*m_syncLog, _1),
- Name(BROADCAST_DOMAIN), // no appname suffix now
- 3,
- bind (&Dispatcher::Did_FetchManager_FileSegmentFetch, this, _1, _2, _3, _4),
- bind (&Dispatcher::Did_FetchManager_FileFetchComplete, this, _1, _2),
- fileTaskDb);
+ m_fileFetcher =
+ make_shared<FetchManager>(m_ccnx, bind(&SyncLog::LookupLocator, &*m_syncLog, _1),
+ Name(BROADCAST_DOMAIN), // no appname suffix now
+ 3, bind(&Dispatcher::Did_FetchManager_FileSegmentFetch, this, _1, _2,
+ _3, _4),
+ bind(&Dispatcher::Did_FetchManager_FileFetchComplete, this, _1, _2),
+ fileTaskDb);
- if (m_enablePrefixDiscovery)
- {
+ if (m_enablePrefixDiscovery) {
_LOG_DEBUG("registering prefix discovery in Dispatcher");
string tag = "dispatcher" + m_localUserName.toString();
- Ndnx::NdnxDiscovery::registerCallback (TaggedFunction (bind (&Dispatcher::Did_LocalPrefix_Updated, this, _1), tag));
+ Ccnx::CcnxDiscovery::registerCallback(
+ TaggedFunction(bind(&Dispatcher::Did_LocalPrefix_Updated, this, _1), tag));
}
- m_executor.start ();
+ m_executor.start();
}
Dispatcher::~Dispatcher()
{
- _LOG_DEBUG ("Enter destructor of dispatcher");
- m_executor.shutdown ();
+ _LOG_DEBUG("Enter destructor of dispatcher");
+ m_executor.shutdown();
// _LOG_DEBUG (">>");
- if (m_enablePrefixDiscovery)
- {
+ if (m_enablePrefixDiscovery) {
_LOG_DEBUG("deregistering prefix discovery in Dispatcher");
string tag = "dispatcher" + m_localUserName.toString();
- Ndnx::NdnxDiscovery::deregisterCallback (TaggedFunction (bind (&Dispatcher::Did_LocalPrefix_Updated, this, _1), tag));
+ Ccnx::CcnxDiscovery::deregisterCallback(
+ TaggedFunction(bind(&Dispatcher::Did_LocalPrefix_Updated, this, _1), tag));
}
- if (m_core != NULL)
- {
+ if (m_core != NULL) {
delete m_core;
m_core = NULL;
}
- if (m_server != NULL)
- {
+ if (m_server != NULL) {
delete m_server;
m_server = NULL;
}
- if (m_stateServer != NULL)
- {
+ if (m_stateServer != NULL) {
delete m_stateServer;
m_stateServer = NULL;
}
}
void
-Dispatcher::Did_LocalPrefix_Updated (const Ndnx::Name &forwardingHint)
+Dispatcher::Did_LocalPrefix_Updated(const Ccnx::Name& forwardingHint)
{
Name effectiveForwardingHint;
- if (m_localUserName.size () >= forwardingHint.size () &&
- m_localUserName.getPartialName (0, forwardingHint.size ()) == forwardingHint)
- {
- effectiveForwardingHint = Name ("/"); // "directly" accesible
- }
- else
- {
- effectiveForwardingHint = forwardingHint;
- }
+ if (m_localUserName.size() >= forwardingHint.size() &&
+ m_localUserName.getPartialName(0, forwardingHint.size()) == forwardingHint) {
+ effectiveForwardingHint = Name("/"); // "directly" accesible
+ }
+ else {
+ effectiveForwardingHint = forwardingHint;
+ }
- Name oldLocalPrefix = m_syncLog->LookupLocalLocator ();
+ Name oldLocalPrefix = m_syncLog->LookupLocalLocator();
- if (oldLocalPrefix == effectiveForwardingHint)
- {
- _LOG_DEBUG ("Got notification about prefix change from " << oldLocalPrefix << " to: " << forwardingHint << ", but effective prefix didn't change");
- return;
- }
+ if (oldLocalPrefix == effectiveForwardingHint) {
+ _LOG_DEBUG(
+ "Got notification about prefix change from " << oldLocalPrefix << " to: " << forwardingHint
+ << ", but effective prefix didn't change");
+ return;
+ }
- if (effectiveForwardingHint == Name ("/") ||
- effectiveForwardingHint == Name (BROADCAST_DOMAIN))
- {
- _LOG_DEBUG ("Basic effective prefix [" << effectiveForwardingHint << "]. Updating local prefix, but don't reregister");
- m_syncLog->UpdateLocalLocator (effectiveForwardingHint);
- return;
- }
+ if (effectiveForwardingHint == Name("/") || effectiveForwardingHint == Name(BROADCAST_DOMAIN)) {
+ _LOG_DEBUG("Basic effective prefix [" << effectiveForwardingHint
+ << "]. Updating local prefix, but don't reregister");
+ m_syncLog->UpdateLocalLocator(effectiveForwardingHint);
+ return;
+ }
- _LOG_DEBUG ("LocalPrefix changed from: " << oldLocalPrefix << " to: " << effectiveForwardingHint);
+ _LOG_DEBUG("LocalPrefix changed from: " << oldLocalPrefix << " to: " << effectiveForwardingHint);
m_server->registerPrefix(effectiveForwardingHint);
- m_syncLog->UpdateLocalLocator (effectiveForwardingHint);
+ m_syncLog->UpdateLocalLocator(effectiveForwardingHint);
- if (oldLocalPrefix == Name ("/") ||
- oldLocalPrefix == Name (BROADCAST_DOMAIN))
- {
- _LOG_DEBUG ("Don't deregister basic prefix: " << oldLocalPrefix);
- return;
- }
+ if (oldLocalPrefix == Name("/") || oldLocalPrefix == Name(BROADCAST_DOMAIN)) {
+ _LOG_DEBUG("Don't deregister basic prefix: " << oldLocalPrefix);
+ return;
+ }
m_server->deregisterPrefix(oldLocalPrefix);
}
@@ -189,83 +187,81 @@
/////////////////////////////////////////////////////////////////////////////////////////////////////
void
-Dispatcher::Did_LocalFile_AddOrModify (const filesystem::path &relativeFilePath)
+Dispatcher::Did_LocalFile_AddOrModify(const filesystem::path& relativeFilePath)
{
- m_executor.execute (bind (&Dispatcher::Did_LocalFile_AddOrModify_Execute, this, relativeFilePath));
+ m_executor.execute(bind(&Dispatcher::Did_LocalFile_AddOrModify_Execute, this, relativeFilePath));
}
void
-Dispatcher::Did_LocalFile_AddOrModify_Execute (filesystem::path relativeFilePath)
+Dispatcher::Did_LocalFile_AddOrModify_Execute(filesystem::path relativeFilePath)
{
_LOG_DEBUG(m_localUserName << " calls LocalFile_AddOrModify_Execute");
filesystem::path absolutePath = m_rootDir / relativeFilePath;
- if (!filesystem::exists(absolutePath))
- {
- //BOOST_THROW_EXCEPTION (Error::Dispatcher() << error_info_str("Update non exist file: " + absolutePath.string() ));
- _LOG_DEBUG("Update non exist file: " << absolutePath.string());
- return;
- }
+ if (!filesystem::exists(absolutePath)) {
+ //BOOST_THROW_EXCEPTION (Error::Dispatcher() << error_info_str("Update non exist file: " + absolutePath.string() ));
+ _LOG_DEBUG("Update non exist file: " << absolutePath.string());
+ return;
+ }
- FileItemPtr currentFile = m_fileStateCow->LookupFile (relativeFilePath.generic_string ());
- if(!currentFile)
- currentFile = m_fileState->LookupFile (relativeFilePath.generic_string ());
-
+ FileItemPtr currentFile = m_fileState->LookupFile(relativeFilePath.generic_string());
if (currentFile &&
- *Hash::FromFileContent (absolutePath) == Hash (currentFile->file_hash ().c_str (), currentFile->file_hash ().size ())
+ *Hash::FromFileContent(absolutePath) ==
+ Hash(currentFile->file_hash().c_str(), currentFile->file_hash().size())
// The following two are commented out to prevent front end from reporting intermediate files
// should enable it if there is other way to prevent this
// && last_write_time (absolutePath) == currentFile->mtime ()
// && status (absolutePath).permissions () == static_cast<filesystem::perms> (currentFile->mode ())
- )
- {
- _LOG_ERROR ("Got notification about the same file [" << relativeFilePath << "]");
- return;
- }
+ ) {
+ _LOG_ERROR("Got notification about the same file [" << relativeFilePath << "]");
+ return;
+ }
+
+ if (currentFile && !currentFile->is_complete()) {
+ _LOG_ERROR("Got notification about incomplete file [" << relativeFilePath << "]");
+ return;
+ }
int seg_num;
HashPtr hash;
- tie (hash, seg_num) = m_objectManager.localFileToObjects (absolutePath, m_localUserName);
+ tie(hash, seg_num) = m_objectManager.localFileToObjects(absolutePath, m_localUserName);
- try
- {
- m_actionLog->AddLocalActionUpdate (relativeFilePath.generic_string(),
- *hash,
- last_write_time (absolutePath),
+ try {
+ m_actionLog->AddLocalActionUpdate(relativeFilePath.generic_string(),
+ *hash,
+ last_write_time(absolutePath),
#if BOOST_VERSION >= 104900
- status (absolutePath).permissions (),
+ status(absolutePath).permissions(),
#else
- 0,
+ 0,
#endif
- seg_num);
+ seg_num);
- // notify SyncCore to propagate the change
- m_core->localStateChangedDelayed ();
- }
- catch (filesystem::filesystem_error &error)
- {
- _LOG_ERROR ("File operations failed on [" << relativeFilePath << "] (ignoring)");
- }
+ // notify SyncCore to propagate the change
+ m_core->localStateChangedDelayed();
+ }
+ catch (filesystem::filesystem_error& error) {
+ _LOG_ERROR("File operations failed on [" << relativeFilePath << "] (ignoring)");
+ }
}
void
-Dispatcher::Did_LocalFile_Delete (const filesystem::path &relativeFilePath)
+Dispatcher::Did_LocalFile_Delete(const filesystem::path& relativeFilePath)
{
- m_executor.execute (bind (&Dispatcher::Did_LocalFile_Delete_Execute, this, relativeFilePath));
+ m_executor.execute(bind(&Dispatcher::Did_LocalFile_Delete_Execute, this, relativeFilePath));
}
void
-Dispatcher::Did_LocalFile_Delete_Execute (filesystem::path relativeFilePath)
+Dispatcher::Did_LocalFile_Delete_Execute(filesystem::path relativeFilePath)
{
filesystem::path absolutePath = m_rootDir / relativeFilePath;
- if (filesystem::exists(absolutePath))
- {
- //BOOST_THROW_EXCEPTION (Error::Dispatcher() << error_info_str("Delete notification but file exists: " + absolutePath.string() ));
- _LOG_ERROR("DELETE command, but file still exists: " << absolutePath.string());
- return;
- }
+ if (filesystem::exists(absolutePath)) {
+ //BOOST_THROW_EXCEPTION (Error::Dispatcher() << error_info_str("Delete notification but file exists: " + absolutePath.string() ));
+ _LOG_ERROR("DELETE command, but file still exists: " << absolutePath.string());
+ return;
+ }
- m_actionLog->AddLocalActionDelete (relativeFilePath.generic_string());
+ m_actionLog->AddLocalActionDelete(relativeFilePath.generic_string());
// notify SyncCore to propagate the change
m_core->localStateChangedDelayed();
}
@@ -291,145 +287,145 @@
*/
void
-Dispatcher::Did_SyncLog_StateChange (SyncStateMsgPtr stateMsg)
+Dispatcher::Did_SyncLog_StateChange(SyncStateMsgPtr stateMsg)
{
- m_executor.execute (bind (&Dispatcher::Did_SyncLog_StateChange_Execute, this, stateMsg));
+ m_executor.execute(bind(&Dispatcher::Did_SyncLog_StateChange_Execute, this, stateMsg));
}
void
-Dispatcher::Did_SyncLog_StateChange_Execute (SyncStateMsgPtr stateMsg)
+Dispatcher::Did_SyncLog_StateChange_Execute(SyncStateMsgPtr stateMsg)
{
int size = stateMsg->state_size();
int index = 0;
// iterate and fetch the actions
- for (; index < size; index++)
- {
- SyncState state = stateMsg->state (index);
- if (state.has_old_seq() && state.has_seq())
- {
+ for (; index < size; index++) {
+ SyncState state = stateMsg->state(index);
+ if (state.has_old_seq() && state.has_seq()) {
uint64_t oldSeq = state.old_seq();
uint64_t newSeq = state.seq();
- Name userName (reinterpret_cast<const unsigned char *> (state.name ().c_str ()), state.name ().size ());
+ Name userName(reinterpret_cast<const unsigned char*>(state.name().c_str()),
+ state.name().size());
// fetch actions with oldSeq + 1 to newSeq (inclusive)
- Name actionNameBase = Name ("/")(userName)(CHRONOSHARE_APP)("action")(m_sharedFolder);
+ Name actionNameBase = Name("/")(userName)(CHRONOSHARE_APP)("action")(m_sharedFolder);
- m_actionFetcher->Enqueue (userName, actionNameBase,
- std::max<uint64_t> (oldSeq + 1, 1), newSeq, FetchManager::PRIORITY_HIGH);
+ m_actionFetcher->Enqueue(userName, actionNameBase, std::max<uint64_t>(oldSeq + 1, 1), newSeq,
+ FetchManager::PRIORITY_HIGH);
}
}
}
void
-Dispatcher::Did_FetchManager_ActionFetch (const Ndnx::Name &deviceName, const Ndnx::Name &actionBaseName, uint32_t seqno, Ndnx::PcoPtr actionPco)
+Dispatcher::Did_FetchManager_ActionFetch(const Ccnx::Name& deviceName,
+ const Ccnx::Name& actionBaseName, uint32_t seqno,
+ Ccnx::PcoPtr actionPco)
{
/// @todo Errors and exception checking
- _LOG_DEBUG ("Received action deviceName: " << deviceName << ", actionBaseName: " << actionBaseName << ", seqno: " << seqno);
+ _LOG_DEBUG("Received action deviceName: " << deviceName << ", actionBaseName: " << actionBaseName
+ << ", seqno: "
+ << seqno);
- ActionItemPtr action = m_actionLog->AddRemoteAction (deviceName, seqno, actionPco);
- if (!action)
- {
- _LOG_ERROR ("AddRemoteAction did not insert action, ignoring");
- return;
- }
+ ActionItemPtr action = m_actionLog->AddRemoteAction(deviceName, seqno, actionPco);
+ if (!action) {
+ _LOG_ERROR("AddRemoteAction did not insert action, ignoring");
+ return;
+ }
// trigger may invoke Did_ActionLog_ActionApply_Delete or Did_ActionLog_ActionApply_AddOrModify callbacks
- if (action->action () == ActionItem::UPDATE)
- {
- Hash hash (action->file_hash ().c_str(), action->file_hash ().size ());
+ if (action->action() == ActionItem::UPDATE) {
+ Hash hash(action->file_hash().c_str(), action->file_hash().size());
- Name fileNameBase = Name ("/")(deviceName)(CHRONOSHARE_APP)("file")(hash.GetHash (), hash.GetHashBytes ());
+ Name fileNameBase =
+ Name("/")(deviceName)(CHRONOSHARE_APP)("file")(hash.GetHash(), hash.GetHashBytes());
- string hashStr = lexical_cast<string> (hash);
- if (ObjectDb::DoesExist (m_rootDir / ".chronoshare", deviceName, hashStr))
- {
- _LOG_DEBUG ("File already exists in the database. No need to refetch, just directly applying the action");
- Did_FetchManager_FileFetchComplete (deviceName, fileNameBase);
- }
- else
- {
- if (m_objectDbMap.find (hash) == m_objectDbMap.end ())
- {
- _LOG_DEBUG ("create ObjectDb for " << hash);
- m_objectDbMap [hash] = make_shared<ObjectDb> (m_rootDir / ".chronoshare", hashStr);
- }
-
- m_fileFetcher->Enqueue (deviceName, fileNameBase,
- 0, action->seg_num () - 1, FetchManager::PRIORITY_NORMAL);
- }
+ string hashStr = lexical_cast<string>(hash);
+ if (ObjectDb::DoesExist(m_rootDir / ".chronoshare", deviceName, hashStr)) {
+ _LOG_DEBUG(
+ "File already exists in the database. No need to refetch, just directly applying the action");
+ Did_FetchManager_FileFetchComplete(deviceName, fileNameBase);
}
+ else {
+ if (m_objectDbMap.find(hash) == m_objectDbMap.end()) {
+ _LOG_DEBUG("create ObjectDb for " << hash);
+ m_objectDbMap[hash] = make_shared<ObjectDb>(m_rootDir / ".chronoshare", hashStr);
+ }
+
+ m_fileFetcher->Enqueue(deviceName, fileNameBase, 0, action->seg_num() - 1,
+ FetchManager::PRIORITY_NORMAL);
+ }
+ }
// if necessary (when version number is the highest) delete will be applied through the trigger in m_actionLog->AddRemoteAction call
}
void
-Dispatcher::Did_ActionLog_ActionApply_Delete (const std::string &filename)
+Dispatcher::Did_ActionLog_ActionApply_Delete(const std::string& filename)
{
- m_executor.execute (bind (&Dispatcher::Did_ActionLog_ActionApply_Delete_Execute, this, filename));
+ m_executor.execute(bind(&Dispatcher::Did_ActionLog_ActionApply_Delete_Execute, this, filename));
}
void
-Dispatcher::Did_ActionLog_ActionApply_Delete_Execute (std::string filename)
+Dispatcher::Did_ActionLog_ActionApply_Delete_Execute(std::string filename)
{
- _LOG_DEBUG ("Action to delete " << filename);
+ _LOG_DEBUG("Action to delete " << filename);
filesystem::path absolutePath = m_rootDir / filename;
- try
- {
- if (filesystem::exists(absolutePath))
- {
- // need some protection from local detection of removal
- remove (absolutePath);
+ try {
+ if (filesystem::exists(absolutePath)) {
+ // need some protection from local detection of removal
+ remove(absolutePath);
- // hack to remove empty parent dirs
- filesystem::path parentPath = absolutePath.parent_path();
- while (parentPath > m_rootDir)
- {
- if (filesystem::is_empty(parentPath))
- {
- filesystem::remove(parentPath);
- parentPath = parentPath.parent_path();
- }
- else
- {
- break;
- }
+ // hack to remove empty parent dirs
+ filesystem::path parentPath = absolutePath.parent_path();
+ while (parentPath > m_rootDir) {
+ if (filesystem::is_empty(parentPath)) {
+ filesystem::remove(parentPath);
+ parentPath = parentPath.parent_path();
+ }
+ else {
+ break;
}
}
+ }
// don't exist
}
- catch (filesystem::filesystem_error &error)
- {
- _LOG_ERROR ("File operations failed when removing [" << absolutePath << "] (ignoring)");
+ catch (filesystem::filesystem_error& error) {
+ _LOG_ERROR("File operations failed when removing [" << absolutePath << "] (ignoring)");
}
}
void
-Dispatcher::Did_FetchManager_FileSegmentFetch (const Ndnx::Name &deviceName, const Ndnx::Name &fileSegmentBaseName, uint32_t segment, Ndnx::PcoPtr fileSegmentPco)
+Dispatcher::Did_FetchManager_FileSegmentFetch(const Ccnx::Name& deviceName,
+ const Ccnx::Name& fileSegmentBaseName,
+ uint32_t segment, Ccnx::PcoPtr fileSegmentPco)
{
- m_executor.execute (bind (&Dispatcher::Did_FetchManager_FileSegmentFetch_Execute, this, deviceName, fileSegmentBaseName, segment, fileSegmentPco));
+ m_executor.execute(bind(&Dispatcher::Did_FetchManager_FileSegmentFetch_Execute, this, deviceName,
+ fileSegmentBaseName, segment, fileSegmentPco));
}
void
-Dispatcher::Did_FetchManager_FileSegmentFetch_Execute (Ndnx::Name deviceName, Ndnx::Name fileSegmentBaseName, uint32_t segment, Ndnx::PcoPtr fileSegmentPco)
+Dispatcher::Did_FetchManager_FileSegmentFetch_Execute(Ccnx::Name deviceName,
+ Ccnx::Name fileSegmentBaseName,
+ uint32_t segment, Ccnx::PcoPtr fileSegmentPco)
{
// fileSegmentBaseName: /<device_name>/<appname>/file/<hash>
- const Bytes &hashBytes = fileSegmentBaseName.getCompFromBack (0);
- Hash hash (head(hashBytes), hashBytes.size());
+ const Bytes& hashBytes = fileSegmentBaseName.getCompFromBack(0);
+ Hash hash(head(hashBytes), hashBytes.size());
- _LOG_DEBUG ("Received segment deviceName: " << deviceName << ", segmentBaseName: " << fileSegmentBaseName << ", segment: " << segment);
+ _LOG_DEBUG("Received segment deviceName: " << deviceName << ", segmentBaseName: " << fileSegmentBaseName
+ << ", segment: "
+ << segment);
// _LOG_DEBUG ("Looking up objectdb for " << hash);
- map<Hash, ObjectDbPtr>::iterator db = m_objectDbMap.find (hash);
- if (db != m_objectDbMap.end())
- {
- db->second->saveContentObject(deviceName, segment, fileSegmentPco->buf ());
+ map<Hash, ObjectDbPtr>::iterator db = m_objectDbMap.find(hash);
+ if (db != m_objectDbMap.end()) {
+ db->second->saveContentObject(deviceName, segment, fileSegmentPco->buf());
}
- else
- {
- _LOG_ERROR ("no db available for this content object: " << fileSegmentBaseName << ", size: " << fileSegmentPco->buf ().size());
+ else {
+ _LOG_ERROR("no db available for this content object: " << fileSegmentBaseName << ", size: "
+ << fileSegmentPco->buf().size());
}
// ObjectDb objectDb (m_rootDir / ".chronoshare", lexical_cast<string> (hash));
@@ -437,88 +433,73 @@
}
void
-Dispatcher::Did_FetchManager_FileFetchComplete (const Ndnx::Name &deviceName, const Ndnx::Name &fileBaseName)
+Dispatcher::Did_FetchManager_FileFetchComplete(const Ccnx::Name& deviceName,
+ const Ccnx::Name& fileBaseName)
{
- m_executor.execute (bind (&Dispatcher::Did_FetchManager_FileFetchComplete_Execute, this, deviceName, fileBaseName));
+ m_executor.execute(
+ bind(&Dispatcher::Did_FetchManager_FileFetchComplete_Execute, this, deviceName, fileBaseName));
}
void
-Dispatcher::Did_FetchManager_FileFetchComplete_Execute (Ndnx::Name deviceName, Ndnx::Name fileBaseName)
+Dispatcher::Did_FetchManager_FileFetchComplete_Execute(Ccnx::Name deviceName, Ccnx::Name fileBaseName)
{
// fileBaseName: /<device_name>/<appname>/file/<hash>
- _LOG_DEBUG ("Finished fetching " << deviceName << ", fileBaseName: " << fileBaseName);
+ _LOG_DEBUG("Finished fetching " << deviceName << ", fileBaseName: " << fileBaseName);
- const Bytes &hashBytes = fileBaseName.getCompFromBack (0);
- Hash hash (head (hashBytes), hashBytes.size ());
- _LOG_DEBUG ("Extracted hash: " << hash.shortHash ());
+ const Bytes& hashBytes = fileBaseName.getCompFromBack(0);
+ Hash hash(head(hashBytes), hashBytes.size());
+ _LOG_DEBUG("Extracted hash: " << hash.shortHash());
- if (m_objectDbMap.find (hash) != m_objectDbMap.end())
- {
+ if (m_objectDbMap.find(hash) != m_objectDbMap.end()) {
// remove the db handle
- m_objectDbMap.erase (hash); // to commit write
+ m_objectDbMap.erase(hash); // to commit write
}
- else
- {
- _LOG_ERROR ("no db available for this file: " << hash);
+ else {
+ _LOG_ERROR("no db available for this file: " << hash);
}
- FileItemsPtr filesToAssemble = m_fileState->LookupFilesForHash (hash);
+ FileItemsPtr filesToAssemble = m_fileState->LookupFilesForHash(hash);
- for (FileItems::iterator file = filesToAssemble->begin ();
- file != filesToAssemble->end ();
- file++)
- {
- m_fileStateCow->UpdateFile (file->filename(), file->version(),
- Hash(file->file_hash ().c_str(), file->file_hash ().size ()),
- NdnxCharbuf (file->device_name().c_str(), file->device_name().size()), file->seq_no(),
- file->mtime(), file->mtime(), file->mtime(),
- file->mode(), file->seg_num());
+ for (FileItems::iterator file = filesToAssemble->begin(); file != filesToAssemble->end(); file++) {
+ boost::filesystem::path filePath = m_rootDir / file->filename();
- boost::filesystem::path filePath = m_rootDir / file->filename ();
-
- try
- {
- if (filesystem::exists (filePath) &&
- filesystem::last_write_time (filePath) == file->mtime () &&
+ try {
+ if (filesystem::exists(filePath) && filesystem::last_write_time(filePath) == file->mtime() &&
#if BOOST_VERSION >= 104900
- filesystem::status (filePath).permissions () == static_cast<filesystem::perms> (file->mode ()) &&
+ filesystem::status(filePath).permissions() == static_cast<filesystem::perms>(file->mode()) &&
#endif
- *Hash::FromFileContent (filePath) == hash)
- {
- _LOG_DEBUG ("Asking to assemble a file, but file already exists on a filesystem");
- continue;
- }
- }
- catch (filesystem::filesystem_error &error)
- {
- _LOG_ERROR ("File operations failed on [" << filePath << "] (ignoring)");
- }
-
- if (ObjectDb::DoesExist (m_rootDir / ".chronoshare", deviceName, boost::lexical_cast<string>(hash)))
- {
- bool ok = m_objectManager.objectsToLocalFile (deviceName, hash, filePath);
- if (ok)
- {
- last_write_time (filePath, file->mtime ());
-#if BOOST_VERSION >= 104900
- permissions (filePath, static_cast<filesystem::perms> (file->mode ()));
-#endif
-
- m_fileState->SetFileComplete (file->filename ());
- m_fileStateCow->DeleteFile(file->filename());
- }
- else
- {
- _LOG_ERROR ("Notified about complete fetch, but file cannot be restored from the database: [" << filePath << "]");
- }
- }
- else
- {
- _LOG_ERROR (filePath << " supposed to have all segments, but not");
- // should abort for debugging
+ *Hash::FromFileContent(filePath) == hash) {
+ _LOG_DEBUG("Asking to assemble a file, but file already exists on a filesystem");
+ continue;
}
}
+ catch (filesystem::filesystem_error& error) {
+ _LOG_ERROR("File operations failed on [" << filePath << "] (ignoring)");
+ }
+
+ if (ObjectDb::DoesExist(m_rootDir / ".chronoshare", deviceName,
+ boost::lexical_cast<string>(hash))) {
+ bool ok = m_objectManager.objectsToLocalFile(deviceName, hash, filePath);
+ if (ok) {
+ last_write_time(filePath, file->mtime());
+#if BOOST_VERSION >= 104900
+ permissions(filePath, static_cast<filesystem::perms>(file->mode()));
+#endif
+
+ m_fileState->SetFileComplete(file->filename());
+ }
+ else {
+ _LOG_ERROR("Notified about complete fetch, but file cannot be restored from the database: ["
+ << filePath
+ << "]");
+ }
+ }
+ else {
+ _LOG_ERROR(filePath << " supposed to have all segments, but not");
+ // should abort for debugging
+ }
+ }
}
// moved to state-server
diff --git a/src/dispatcher.hpp b/src/dispatcher.hpp
index 75121ea..526a633 100644
--- a/src/dispatcher.hpp
+++ b/src/dispatcher.hpp
@@ -22,17 +22,17 @@
#define DISPATCHER_H
#include "action-log.hpp"
-#include "sync-core.hpp"
#include "ccnx-wrapper.hpp"
+#include "content-server.hpp"
#include "executor.hpp"
+#include "fetch-manager.hpp"
#include "object-db.hpp"
#include "object-manager.hpp"
-#include "content-server.hpp"
#include "state-server.hpp"
-#include "fetch-manager.hpp"
+#include "sync-core.hpp"
-#include <boost/function.hpp>
#include <boost/filesystem.hpp>
+#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
#include <map>
@@ -46,12 +46,9 @@
public:
// sharedFolder is the name to be used in NDN name;
// rootDir is the shared folder dir in local file system;
- Dispatcher(const std::string &localUserName
- , const std::string &sharedFolder
- , const boost::filesystem::path &rootDir
- , Ndnx::NdnxWrapperPtr ndnx
- , bool enablePrefixDiscovery = true
- );
+ Dispatcher(const std::string& localUserName, const std::string& sharedFolder,
+ const boost::filesystem::path& rootDir, Ccnx::CcnxWrapperPtr ccnx,
+ bool enablePrefixDiscovery = true);
~Dispatcher();
// ----- Callbacks, they only submit the job to executor and immediately return so that event processing thread won't be blocked for too long -------
@@ -59,33 +56,42 @@
// callback to process local file change
void
- Did_LocalFile_AddOrModify (const boost::filesystem::path &relativeFilepath);
+ Did_LocalFile_AddOrModify(const boost::filesystem::path& relativeFilepath);
void
- Did_LocalFile_Delete (const boost::filesystem::path &relativeFilepath);
+ Did_LocalFile_Delete(const boost::filesystem::path& relativeFilepath);
/**
* @brief Invoked when FileState is detected to have a file which does not exist on a file system
*/
void
- Restore_LocalFile (FileItemPtr file);
+ Restore_LocalFile(FileItemPtr file);
// for test
HashPtr
- SyncRoot() { return m_core->root(); }
+ SyncRoot()
+ {
+ return m_core->root();
+ }
inline void
- LookupRecentFileActions(const boost::function<void(const std::string &, int, int)> &visitor, int limit) { m_actionLog->LookupRecentFileActions(visitor, limit); }
+ LookupRecentFileActions(const boost::function<void(const std::string&, int, int)>& visitor,
+ int limit)
+ {
+ m_actionLog->LookupRecentFileActions(visitor, limit);
+ }
private:
void
- Did_LocalFile_AddOrModify_Execute (boost::filesystem::path relativeFilepath); // cannot be const & for Execute event!!! otherwise there will be segfault
+ Did_LocalFile_AddOrModify_Execute(
+ boost::filesystem::path relativeFilepath); // cannot be const & for Execute event!!! otherwise there will be segfault
void
- Did_LocalFile_Delete_Execute (boost::filesystem::path relativeFilepath); // cannot be const & for Execute event!!! otherwise there will be segfault
+ Did_LocalFile_Delete_Execute(
+ boost::filesystem::path relativeFilepath); // cannot be const & for Execute event!!! otherwise there will be segfault
void
- Restore_LocalFile_Execute (FileItemPtr file);
+ Restore_LocalFile_Execute(FileItemPtr file);
private:
/**
@@ -106,42 +112,46 @@
// callback to process remote sync state change
void
- Did_SyncLog_StateChange (SyncStateMsgPtr stateMsg);
+ Did_SyncLog_StateChange(SyncStateMsgPtr stateMsg);
void
- Did_SyncLog_StateChange_Execute (SyncStateMsgPtr stateMsg);
+ Did_SyncLog_StateChange_Execute(SyncStateMsgPtr stateMsg);
void
- Did_FetchManager_ActionFetch (const Ndnx::Name &deviceName, const Ndnx::Name &actionName, uint32_t seqno, Ndnx::PcoPtr actionPco);
+ Did_FetchManager_ActionFetch(const Ccnx::Name& deviceName, const Ccnx::Name& actionName,
+ uint32_t seqno, Ccnx::PcoPtr actionPco);
void
- Did_ActionLog_ActionApply_Delete (const std::string &filename);
+ Did_ActionLog_ActionApply_Delete(const std::string& filename);
void
- Did_ActionLog_ActionApply_Delete_Execute (std::string filename);
+ Did_ActionLog_ActionApply_Delete_Execute(std::string filename);
// void
// Did_ActionLog_ActionApply_AddOrModify (const std::string &filename, Ndnx::Name device_name, sqlite3_int64 seq_no,
// HashPtr hash, time_t m_time, int mode, int seg_num);
void
- Did_FetchManager_FileSegmentFetch (const Ndnx::Name &deviceName, const Ndnx::Name &fileSegmentName, uint32_t segment, Ndnx::PcoPtr fileSegmentPco);
+ Did_FetchManager_FileSegmentFetch(const Ccnx::Name& deviceName, const Ccnx::Name& fileSegmentName,
+ uint32_t segment, Ccnx::PcoPtr fileSegmentPco);
void
- Did_FetchManager_FileSegmentFetch_Execute (Ndnx::Name deviceName, Ndnx::Name fileSegmentName, uint32_t segment, Ndnx::PcoPtr fileSegmentPco);
+ Did_FetchManager_FileSegmentFetch_Execute(Ccnx::Name deviceName, Ccnx::Name fileSegmentName,
+ uint32_t segment, Ccnx::PcoPtr fileSegmentPco);
void
- Did_FetchManager_FileFetchComplete (const Ndnx::Name &deviceName, const Ndnx::Name &fileBaseName);
+ Did_FetchManager_FileFetchComplete(const Ccnx::Name& deviceName, const Ccnx::Name& fileBaseName);
void
- Did_FetchManager_FileFetchComplete_Execute (Ndnx::Name deviceName, Ndnx::Name fileBaseName);
+ Did_FetchManager_FileFetchComplete_Execute(Ccnx::Name deviceName, Ccnx::Name fileBaseName);
void
- Did_LocalPrefix_Updated (const Ndnx::Name &prefix);
+ Did_LocalPrefix_Updated(const Ccnx::Name& prefix);
private:
void
- AssembleFile_Execute (const Ndnx::Name &deviceName, const Hash &filehash, const boost::filesystem::path &relativeFilepath);
+ AssembleFile_Execute(const Ccnx::Name& deviceName, const Hash& filehash,
+ const boost::filesystem::path& relativeFilepath);
// void
// fileChanged(const boost::filesystem::path &relativeFilepath, ActionType type);
@@ -159,9 +169,9 @@
// fileReady(const Ndnx::Name &fileNamePrefix);
private:
- Ndnx::NdnxWrapperPtr m_ndnx;
- SyncCore *m_core;
- SyncLogPtr m_syncLog;
+ Ccnx::CcnxWrapperPtr m_ccnx;
+ SyncCore* m_core;
+ SyncLogPtr m_syncLog;
ActionLogPtr m_actionLog;
FileStatePtr m_fileState;
FileStatePtr m_fileStateCow;
@@ -176,19 +186,19 @@
std::map<Hash, ObjectDbPtr> m_objectDbMap;
std::string m_sharedFolder;
- ContentServer *m_server;
- StateServer *m_stateServer;
+ ContentServer* m_server;
+ StateServer* m_stateServer;
bool m_enablePrefixDiscovery;
FetchManagerPtr m_actionFetcher;
FetchManagerPtr m_fileFetcher;
};
-namespace Error
+namespace Error {
+struct Dispatcher : virtual boost::exception, virtual std::exception
{
- struct Dispatcher : virtual boost::exception, virtual std::exception {};
- typedef boost::error_info<struct tag_errmsg, std::string> error_info_str;
+};
+typedef boost::error_info<struct tag_errmsg, std::string> error_info_str;
}
#endif // DISPATCHER_H
-
diff --git a/src/fetch-manager.cpp b/src/fetch-manager.cpp
index a6176c0..27f8d6d 100644
--- a/src/fetch-manager.cpp
+++ b/src/fetch-manager.cpp
@@ -19,249 +19,247 @@
*/
#include "fetch-manager.hpp"
+#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
#include <boost/ref.hpp>
#include <boost/throw_exception.hpp>
-#include <boost/lexical_cast.hpp>
-#include "simple-interval-generator.hpp"
#include "logging.hpp"
+#include "simple-interval-generator.hpp"
-INIT_LOGGER ("FetchManager");
+INIT_LOGGER("FetchManager");
using namespace boost;
using namespace std;
using namespace Ndnx;
//The disposer object function
-struct fetcher_disposer { void operator() (Fetcher *delete_this) { delete delete_this; } };
+struct fetcher_disposer
+{
+ void
+ operator()(Fetcher* delete_this)
+ {
+ delete delete_this;
+ }
+};
static const string SCHEDULE_FETCHES_TAG = "ScheduleFetches";
-FetchManager::FetchManager (Ndnx::NdnxWrapperPtr ndnx,
- const Mapping &mapping,
- const Name &broadcastForwardingHint,
- uint32_t parallelFetches, // = 3
- const SegmentCallback &defaultSegmentCallback,
- const FinishCallback &defaultFinishCallback,
- const FetchTaskDbPtr &taskDb
- )
- : m_ndnx (ndnx)
- , m_mapping (mapping)
- , m_maxParallelFetches (parallelFetches)
- , m_currentParallelFetches (0)
- , m_scheduler (new Scheduler)
- , m_executor (new Executor(1))
+FetchManager::FetchManager(Ccnx::CcnxWrapperPtr ccnx,
+ const Mapping& mapping,
+ const Name& broadcastForwardingHint,
+ uint32_t parallelFetches, // = 3
+ const SegmentCallback& defaultSegmentCallback,
+ const FinishCallback& defaultFinishCallback,
+ const FetchTaskDbPtr& taskDb)
+ : m_ccnx(ccnx)
+ , m_mapping(mapping)
+ , m_maxParallelFetches(parallelFetches)
+ , m_currentParallelFetches(0)
+ , m_scheduler(new Scheduler)
+ , m_executor(new Executor(1))
, m_defaultSegmentCallback(defaultSegmentCallback)
, m_defaultFinishCallback(defaultFinishCallback)
, m_taskDb(taskDb)
- , m_broadcastHint (broadcastForwardingHint)
+ , m_broadcastHint(broadcastForwardingHint)
{
- m_scheduler->start ();
+ m_scheduler->start();
m_executor->start();
- m_scheduleFetchesTask = Scheduler::schedulePeriodicTask (m_scheduler,
- make_shared<SimpleIntervalGenerator> (300), // no need to check to often. if needed, will be rescheduled
- bind (&FetchManager::ScheduleFetches, this), SCHEDULE_FETCHES_TAG);
+ m_scheduleFetchesTask =
+ Scheduler::schedulePeriodicTask(m_scheduler,
+ make_shared<SimpleIntervalGenerator>(
+ 300), // no need to check to often. if needed, will be rescheduled
+ bind(&FetchManager::ScheduleFetches, this),
+ SCHEDULE_FETCHES_TAG);
// resume un-finished fetches if there is any
- if (m_taskDb)
- {
+ if (m_taskDb) {
m_taskDb->foreachTask(bind(&FetchManager::Enqueue, this, _1, _2, _3, _4, _5));
}
}
-FetchManager::~FetchManager ()
+FetchManager::~FetchManager()
{
- m_scheduler->shutdown ();
+ m_scheduler->shutdown();
m_executor->shutdown();
- m_ndnx.reset ();
+ m_ccnx.reset();
- m_fetchList.clear_and_dispose (fetcher_disposer ());
+ m_fetchList.clear_and_dispose(fetcher_disposer());
}
// Enqueue using default callbacks
void
-FetchManager::Enqueue (const Ndnx::Name &deviceName, const Ndnx::Name &baseName,
- uint64_t minSeqNo, uint64_t maxSeqNo, int priority)
+FetchManager::Enqueue(const Ccnx::Name& deviceName, const Ccnx::Name& baseName, uint64_t minSeqNo,
+ uint64_t maxSeqNo, int priority)
{
- Enqueue(deviceName, baseName, m_defaultSegmentCallback, m_defaultFinishCallback, minSeqNo, maxSeqNo, priority);
+ Enqueue(deviceName, baseName, m_defaultSegmentCallback, m_defaultFinishCallback, minSeqNo,
+ maxSeqNo, priority);
}
void
-FetchManager::Enqueue (const Ndnx::Name &deviceName, const Ndnx::Name &baseName,
- const SegmentCallback &segmentCallback, const FinishCallback &finishCallback,
- uint64_t minSeqNo, uint64_t maxSeqNo, int priority/*PRIORITY_NORMAL*/)
+FetchManager::Enqueue(const Ccnx::Name& deviceName, const Ccnx::Name& baseName,
+ const SegmentCallback& segmentCallback, const FinishCallback& finishCallback,
+ uint64_t minSeqNo, uint64_t maxSeqNo, int priority /*PRIORITY_NORMAL*/)
{
// Assumption for the following code is minSeqNo <= maxSeqNo
- if (minSeqNo > maxSeqNo)
- {
+ if (minSeqNo > maxSeqNo) {
return;
}
// we may need to guarantee that LookupLocator will gives an answer and not throw exception...
Name forwardingHint;
- forwardingHint = m_mapping (deviceName);
+ forwardingHint = m_mapping(deviceName);
- if (m_taskDb)
- {
- m_taskDb->addTask(deviceName, baseName, minSeqNo, maxSeqNo, priority);
- }
+ if (m_taskDb) {
+ m_taskDb->addTask(deviceName, baseName, minSeqNo, maxSeqNo, priority);
+ }
- unique_lock<mutex> lock (m_parellelFetchMutex);
+ unique_lock<mutex> lock(m_parellelFetchMutex);
- _LOG_TRACE ("++++ Create fetcher: " << baseName);
- Fetcher *fetcher = new Fetcher (m_ndnx,
- m_executor,
- segmentCallback,
- finishCallback,
- bind (&FetchManager::DidFetchComplete, this, _1, _2, _3),
- bind (&FetchManager::DidNoDataTimeout, this, _1),
- deviceName, baseName, minSeqNo, maxSeqNo,
- boost::posix_time::seconds (30),
- forwardingHint);
+ _LOG_TRACE("++++ Create fetcher: " << baseName);
+ Fetcher* fetcher =
+ new Fetcher(m_ccnx, m_executor, segmentCallback, finishCallback,
+ bind(&FetchManager::DidFetchComplete, this, _1, _2, _3),
+ bind(&FetchManager::DidNoDataTimeout, this, _1), deviceName, baseName, minSeqNo,
+ maxSeqNo, boost::posix_time::seconds(30), forwardingHint);
- switch (priority)
- {
+ switch (priority) {
case PRIORITY_HIGH:
- _LOG_TRACE ("++++ Push front fetcher: " << fetcher->GetName ());
- m_fetchList.push_front (*fetcher);
+ _LOG_TRACE("++++ Push front fetcher: " << fetcher->GetName());
+ m_fetchList.push_front(*fetcher);
break;
case PRIORITY_NORMAL:
default:
- _LOG_TRACE ("++++ Push back fetcher: " << fetcher->GetName ());
- m_fetchList.push_back (*fetcher);
+ _LOG_TRACE("++++ Push back fetcher: " << fetcher->GetName());
+ m_fetchList.push_back(*fetcher);
break;
- }
+ }
- _LOG_DEBUG ("++++ Reschedule fetcher task");
- m_scheduler->rescheduleTaskAt (m_scheduleFetchesTask, 0);
+ _LOG_DEBUG("++++ Reschedule fetcher task");
+ m_scheduler->rescheduleTaskAt(m_scheduleFetchesTask, 0);
// ScheduleFetches (); // will start a fetch if m_currentParallelFetches is less than max, otherwise does nothing
}
void
-FetchManager::ScheduleFetches ()
+FetchManager::ScheduleFetches()
{
- unique_lock<mutex> lock (m_parellelFetchMutex);
+ unique_lock<mutex> lock(m_parellelFetchMutex);
- boost::posix_time::ptime currentTime = date_time::second_clock<boost::posix_time::ptime>::universal_time ();
- boost::posix_time::ptime nextSheduleCheck = currentTime + posix_time::seconds (300); // no reason to have anything, but just in case
+ boost::posix_time::ptime currentTime =
+ date_time::second_clock<boost::posix_time::ptime>::universal_time();
+ boost::posix_time::ptime nextSheduleCheck =
+ currentTime + posix_time::seconds(300); // no reason to have anything, but just in case
- for (FetchList::iterator item = m_fetchList.begin ();
- m_currentParallelFetches < m_maxParallelFetches && item != m_fetchList.end ();
- item++)
- {
- if (item->IsActive ())
- {
- _LOG_DEBUG ("Item is active");
- continue;
- }
-
- if (item->IsTimedWait ())
- {
- _LOG_DEBUG ("Item is in timed-wait");
- continue;
- }
-
- if (currentTime < item->GetNextScheduledRetry ())
- {
- if (item->GetNextScheduledRetry () < nextSheduleCheck)
- nextSheduleCheck = item->GetNextScheduledRetry ();
-
- _LOG_DEBUG ("Item is delayed");
- continue;
- }
-
- _LOG_DEBUG ("Start fetching of " << item->GetName ());
-
- m_currentParallelFetches ++;
- _LOG_TRACE ("++++ RESTART PIPELINE: " << item->GetName ());
- item->RestartPipeline ();
+ for (FetchList::iterator item = m_fetchList.begin();
+ m_currentParallelFetches < m_maxParallelFetches && item != m_fetchList.end();
+ item++) {
+ if (item->IsActive()) {
+ _LOG_DEBUG("Item is active");
+ continue;
}
- m_scheduler->rescheduleTaskAt (m_scheduleFetchesTask, (nextSheduleCheck - currentTime).total_seconds ());
+ if (item->IsTimedWait()) {
+ _LOG_DEBUG("Item is in timed-wait");
+ continue;
+ }
+
+ if (currentTime < item->GetNextScheduledRetry()) {
+ if (item->GetNextScheduledRetry() < nextSheduleCheck)
+ nextSheduleCheck = item->GetNextScheduledRetry();
+
+ _LOG_DEBUG("Item is delayed");
+ continue;
+ }
+
+ _LOG_DEBUG("Start fetching of " << item->GetName());
+
+ m_currentParallelFetches++;
+ _LOG_TRACE("++++ RESTART PIPELINE: " << item->GetName());
+ item->RestartPipeline();
+ }
+
+ m_scheduler->rescheduleTaskAt(m_scheduleFetchesTask,
+ (nextSheduleCheck - currentTime).total_seconds());
}
void
-FetchManager::DidNoDataTimeout (Fetcher &fetcher)
+FetchManager::DidNoDataTimeout(Fetcher& fetcher)
{
- _LOG_DEBUG ("No data timeout for " << fetcher.GetName () << " with forwarding hint: " << fetcher.GetForwardingHint ());
+ _LOG_DEBUG("No data timeout for " << fetcher.GetName() << " with forwarding hint: "
+ << fetcher.GetForwardingHint());
{
- unique_lock<mutex> lock (m_parellelFetchMutex);
- m_currentParallelFetches --;
+ unique_lock<mutex> lock(m_parellelFetchMutex);
+ m_currentParallelFetches--;
// no need to do anything with the m_fetchList
}
- if (fetcher.GetForwardingHint ().size () == 0)
- {
- // will be tried initially and again after empty forwarding hint
+ if (fetcher.GetForwardingHint().size() == 0) {
+ // will be tried initially and again after empty forwarding hint
- /// @todo Handle potential exception
- Name forwardingHint;
- forwardingHint = m_mapping (fetcher.GetDeviceName ());
+ /// @todo Handle potential exception
+ Name forwardingHint;
+ forwardingHint = m_mapping(fetcher.GetDeviceName());
- if (forwardingHint.size () == 0)
- {
- // make sure that we will try broadcast forwarding hint eventually
- fetcher.SetForwardingHint (m_broadcastHint);
- }
- else
- {
- fetcher.SetForwardingHint (forwardingHint);
- }
+ if (forwardingHint.size() == 0) {
+ // make sure that we will try broadcast forwarding hint eventually
+ fetcher.SetForwardingHint(m_broadcastHint);
}
- else if (fetcher.GetForwardingHint () == m_broadcastHint)
- {
- // will be tried after broadcast forwarding hint
- fetcher.SetForwardingHint (Name ("/"));
+ else {
+ fetcher.SetForwardingHint(forwardingHint);
}
- else
- {
- // will be tried after normal forwarding hint
- fetcher.SetForwardingHint (m_broadcastHint);
- }
+ }
+ else if (fetcher.GetForwardingHint() == m_broadcastHint) {
+ // will be tried after broadcast forwarding hint
+ fetcher.SetForwardingHint(Name("/"));
+ }
+ else {
+ // will be tried after normal forwarding hint
+ fetcher.SetForwardingHint(m_broadcastHint);
+ }
- double delay = fetcher.GetRetryPause ();
+ double delay = fetcher.GetRetryPause();
if (delay < 1) // first time
- {
- delay = 1;
- }
- else
- {
- delay = std::min (2*delay, 300.0); // 5 minutes max
- }
+ {
+ delay = 1;
+ }
+ else {
+ delay = std::min(2 * delay, 300.0); // 5 minutes max
+ }
- fetcher.SetRetryPause (delay);
- fetcher.SetNextScheduledRetry (date_time::second_clock<boost::posix_time::ptime>::universal_time () + posix_time::seconds (delay));
+ fetcher.SetRetryPause(delay);
+ fetcher.SetNextScheduledRetry(date_time::second_clock<boost::posix_time::ptime>::universal_time() +
+ posix_time::seconds(delay));
- m_scheduler->rescheduleTaskAt (m_scheduleFetchesTask, 0);
+ m_scheduler->rescheduleTaskAt(m_scheduleFetchesTask, 0);
}
void
-FetchManager::DidFetchComplete (Fetcher &fetcher, const Name &deviceName, const Name &baseName)
+FetchManager::DidFetchComplete(Fetcher& fetcher, const Name& deviceName, const Name& baseName)
{
{
- unique_lock<mutex> lock (m_parellelFetchMutex);
- m_currentParallelFetches --;
+ unique_lock<mutex> lock(m_parellelFetchMutex);
+ m_currentParallelFetches--;
- if (m_taskDb)
- {
- m_taskDb->deleteTask(deviceName, baseName);
- }
+ if (m_taskDb) {
+ m_taskDb->deleteTask(deviceName, baseName);
+ }
}
// like TCP timed-wait
- m_scheduler->scheduleOneTimeTask(m_scheduler, 10, boost::bind(&FetchManager::TimedWait, this, ref(fetcher)), boost::lexical_cast<string>(baseName));
+ m_scheduler->scheduleOneTimeTask(m_scheduler, 10,
+ boost::bind(&FetchManager::TimedWait, this, ref(fetcher)),
+ boost::lexical_cast<string>(baseName));
- m_scheduler->rescheduleTaskAt (m_scheduleFetchesTask, 0);
+ m_scheduler->rescheduleTaskAt(m_scheduleFetchesTask, 0);
}
void
-FetchManager::TimedWait (Fetcher &fetcher)
+FetchManager::TimedWait(Fetcher& fetcher)
{
- unique_lock<mutex> lock (m_parellelFetchMutex);
- _LOG_TRACE ("+++++ removing fetcher: " << fetcher.GetName ());
- m_fetchList.erase_and_dispose (FetchList::s_iterator_to (fetcher), fetcher_disposer ());
+ unique_lock<mutex> lock(m_parellelFetchMutex);
+ _LOG_TRACE("+++++ removing fetcher: " << fetcher.GetName());
+ m_fetchList.erase_and_dispose(FetchList::s_iterator_to(fetcher), fetcher_disposer());
}
diff --git a/src/fetch-manager.hpp b/src/fetch-manager.hpp
index fd8df7e..8372e9d 100644
--- a/src/fetch-manager.hpp
+++ b/src/fetch-manager.hpp
@@ -21,72 +21,68 @@
#ifndef FETCH_MANAGER_H
#define FETCH_MANAGER_H
+#include "ccnx-wrapper.h"
+#include "executor.h"
+#include "fetch-task-db.h"
+#include "scheduler.h"
#include <boost/exception/all.hpp>
-#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
-#include <string>
+#include <boost/shared_ptr.hpp>
#include <list>
#include <stdint.h>
-#include "scheduler.h"
-#include "executor.h"
-#include "ndnx-wrapper.h"
-#include "fetch-task-db.h"
+#include <string>
#include "fetcher.h"
class FetchManager
{
public:
- enum
- {
- PRIORITY_NORMAL,
- PRIORITY_HIGH
- };
+ enum { PRIORITY_NORMAL, PRIORITY_HIGH };
- typedef boost::function<Ndnx::Name(const Ndnx::Name &)> Mapping;
- typedef boost::function<void(Ndnx::Name &deviceName, Ndnx::Name &baseName, uint64_t seq, Ndnx::PcoPtr pco)> SegmentCallback;
- typedef boost::function<void(Ndnx::Name &deviceName, Ndnx::Name &baseName)> FinishCallback;
- FetchManager (Ndnx::NdnxWrapperPtr ndnx,
- const Mapping &mapping,
- const Ndnx::Name &broadcastForwardingHint,
- uint32_t parallelFetches = 3,
- const SegmentCallback &defaultSegmentCallback = SegmentCallback(),
- const FinishCallback &defaultFinishCallback = FinishCallback(),
- const FetchTaskDbPtr &taskDb = FetchTaskDbPtr()
- );
- virtual ~FetchManager ();
+ typedef boost::function<Ccnx::Name(const Ccnx::Name&)> Mapping;
+ typedef boost::function<void(Ccnx::Name& deviceName, Ccnx::Name& baseName, uint64_t seq, Ccnx::PcoPtr pco)>
+ SegmentCallback;
+ typedef boost::function<void(Ccnx::Name& deviceName, Ccnx::Name& baseName)> FinishCallback;
+ FetchManager(Ccnx::CcnxWrapperPtr ccnx,
+ const Mapping& mapping,
+ const Ccnx::Name& broadcastForwardingHint,
+ uint32_t parallelFetches = 3,
+ const SegmentCallback& defaultSegmentCallback = SegmentCallback(),
+ const FinishCallback& defaultFinishCallback = FinishCallback(),
+ const FetchTaskDbPtr& taskDb = FetchTaskDbPtr());
+ virtual ~FetchManager();
void
- Enqueue (const Ndnx::Name &deviceName, const Ndnx::Name &baseName,
- const SegmentCallback &segmentCallback, const FinishCallback &finishCallback,
- uint64_t minSeqNo, uint64_t maxSeqNo, int priority=PRIORITY_NORMAL);
+ Enqueue(const Ccnx::Name& deviceName, const Ccnx::Name& baseName,
+ const SegmentCallback& segmentCallback, const FinishCallback& finishCallback,
+ uint64_t minSeqNo, uint64_t maxSeqNo, int priority = PRIORITY_NORMAL);
// Enqueue using default callbacks
void
- Enqueue (const Ndnx::Name &deviceName, const Ndnx::Name &baseName,
- uint64_t minSeqNo, uint64_t maxSeqNo, int priority=PRIORITY_NORMAL);
+ Enqueue(const Ccnx::Name& deviceName, const Ccnx::Name& baseName, uint64_t minSeqNo,
+ uint64_t maxSeqNo, int priority = PRIORITY_NORMAL);
// only for Fetcher
- inline Ndnx::NdnxWrapperPtr
- GetNdnx ();
+ inline Ccnx::CcnxWrapperPtr
+ GetCcnx();
private:
// Fetch Events
void
- DidDataSegmentFetched (Fetcher &fetcher, uint64_t seqno, const Ndnx::Name &basename,
- const Ndnx::Name &name, Ndnx::PcoPtr data);
+ DidDataSegmentFetched(Fetcher& fetcher, uint64_t seqno, const Ccnx::Name& basename,
+ const Ccnx::Name& name, Ccnx::PcoPtr data);
void
- DidNoDataTimeout (Fetcher &fetcher);
+ DidNoDataTimeout(Fetcher& fetcher);
void
- DidFetchComplete (Fetcher &fetcher, const Ndnx::Name &deviceName, const Ndnx::Name &baseName);
+ DidFetchComplete(Fetcher& fetcher, const Ccnx::Name& deviceName, const Ccnx::Name& baseName);
void
- ScheduleFetches ();
+ ScheduleFetches();
void
- TimedWait (Fetcher &fetcher);
+ TimedWait(Fetcher& fetcher);
private:
Ndnx::NdnxWrapperPtr m_ndnx;
@@ -97,8 +93,9 @@
boost::mutex m_parellelFetchMutex;
// optimized list structure for fetch queue
- typedef boost::intrusive::member_hook< Fetcher,
- boost::intrusive::list_member_hook<>, &Fetcher::m_managerListHook> MemberOption;
+ typedef boost::intrusive::member_hook<Fetcher, boost::intrusive::list_member_hook<>,
+ &Fetcher::m_managerListHook>
+ MemberOption;
typedef boost::intrusive::list<Fetcher, MemberOption> FetchList;
FetchList m_fetchList;
@@ -112,15 +109,17 @@
const Ndnx::Name m_broadcastHint;
};
-Ndnx::NdnxWrapperPtr
-FetchManager::GetNdnx ()
+Ccnx::CcnxWrapperPtr
+FetchManager::GetCcnx()
{
return m_ndnx;
}
typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info_str;
namespace Error {
-struct FetchManager : virtual boost::exception, virtual std::exception { };
+struct FetchManager : virtual boost::exception, virtual std::exception
+{
+};
}
typedef boost::shared_ptr<FetchManager> FetchManagerPtr;
diff --git a/src/fetch-task-db.cpp b/src/fetch-task-db.cpp
index c24bd92..912f063 100644
--- a/src/fetch-task-db.cpp
+++ b/src/fetch-task-db.cpp
@@ -38,45 +38,45 @@
CREATE INDEX identifier ON Task (deviceName, baseName); \n\
";
-FetchTaskDb::FetchTaskDb(const boost::filesystem::path &folder, const std::string &tag)
+FetchTaskDb::FetchTaskDb(const boost::filesystem::path& folder, const std::string& tag)
{
fs::path actualFolder = folder / ".chronoshare" / "fetch_tasks";
- fs::create_directories (actualFolder);
+ fs::create_directories(actualFolder);
int res = sqlite3_open((actualFolder / tag).c_str(), &m_db);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Cannot open database: " + (actualFolder / tag).string()));
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(
+ Error::Db() << errmsg_info_str("Cannot open database: " + (actualFolder / tag).string()));
}
- char *errmsg = 0;
+ char* errmsg = 0;
res = sqlite3_exec(m_db, INIT_DATABASE.c_str(), NULL, NULL, &errmsg);
- if (res != SQLITE_OK && errmsg != 0)
- {
- // _LOG_TRACE ("Init \"error\": " << errmsg);
- sqlite3_free (errmsg);
+ if (res != SQLITE_OK && errmsg != 0) {
+ // _LOG_TRACE ("Init \"error\": " << errmsg);
+ sqlite3_free(errmsg);
}
- else
- {
+ else {
}
}
FetchTaskDb::~FetchTaskDb()
{
int res = sqlite3_close(m_db);
- if (res != SQLITE_OK)
- {
+ if (res != SQLITE_OK) {
// _LOG_ERROR
}
}
void
-FetchTaskDb::addTask(const Name &deviceName, const Name &baseName, uint64_t minSeqNo, uint64_t maxSeqNo, int priority)
+FetchTaskDb::addTask(const Name& deviceName, const Name& baseName, uint64_t minSeqNo,
+ uint64_t maxSeqNo, int priority)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2(m_db, "INSERT OR IGNORE INTO Task (deviceName, baseName, minSeqNo, maxSeqNo, priority) VALUES (?, ?, ?, ?, ?)", -1, &stmt, 0);
- NdnxCharbufPtr deviceBuf = NdnxCharbufPtr(deviceName);
- NdnxCharbufPtr baseBuf = NdnxCharbufPtr(baseName);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db,
+ "INSERT OR IGNORE INTO Task (deviceName, baseName, minSeqNo, maxSeqNo, priority) VALUES (?, ?, ?, ?, ?)",
+ -1, &stmt, 0);
+ CcnxCharbufPtr deviceBuf = CcnxCharbufPtr(deviceName);
+ CcnxCharbufPtr baseBuf = CcnxCharbufPtr(baseName);
sqlite3_bind_blob(stmt, 1, deviceBuf->buf(), deviceBuf->length(), SQLITE_STATIC);
sqlite3_bind_blob(stmt, 2, baseBuf->buf(), baseBuf->length(), SQLITE_STATIC);
sqlite3_bind_int64(stmt, 3, minSeqNo);
@@ -84,41 +84,38 @@
sqlite3_bind_int(stmt, 5, priority);
int res = sqlite3_step(stmt);
- if (res == SQLITE_OK)
- {
+ if (res == SQLITE_OK) {
}
sqlite3_finalize(stmt);
}
void
-FetchTaskDb::deleteTask(const Name &deviceName, const Name &baseName)
+FetchTaskDb::deleteTask(const Name& deviceName, const Name& baseName)
{
- sqlite3_stmt *stmt;
+ sqlite3_stmt* stmt;
sqlite3_prepare_v2(m_db, "DELETE FROM Task WHERE deviceName = ? AND baseName = ?;", -1, &stmt, 0);
NdnxCharbufPtr deviceBuf = NdnxCharbufPtr(deviceName);
NdnxCharbufPtr baseBuf = NdnxCharbufPtr(baseName);
sqlite3_bind_blob(stmt, 1, deviceBuf->buf(), deviceBuf->length(), SQLITE_STATIC);
sqlite3_bind_blob(stmt, 2, baseBuf->buf(), baseBuf->length(), SQLITE_STATIC);
int res = sqlite3_step(stmt);
- if (res == SQLITE_OK)
- {
+ if (res == SQLITE_OK) {
}
sqlite3_finalize(stmt);
}
void
-FetchTaskDb::foreachTask(const FetchTaskCallback &callback)
+FetchTaskDb::foreachTask(const FetchTaskCallback& callback)
{
- sqlite3_stmt *stmt;
+ sqlite3_stmt* stmt;
sqlite3_prepare_v2(m_db, "SELECT * FROM Task;", -1, &stmt, 0);
- while (sqlite3_step(stmt) == SQLITE_ROW)
- {
- Name deviceName(sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0));
- Name baseName(sqlite3_column_blob(stmt, 1), sqlite3_column_bytes(stmt, 1));
- uint64_t minSeqNo = sqlite3_column_int64(stmt, 2);
- uint64_t maxSeqNo = sqlite3_column_int64(stmt, 3);
- int priority = sqlite3_column_int(stmt, 4);
- callback(deviceName, baseName, minSeqNo, maxSeqNo, priority);
+ while (sqlite3_step(stmt) == SQLITE_ROW) {
+ Name deviceName(sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0));
+ Name baseName(sqlite3_column_blob(stmt, 1), sqlite3_column_bytes(stmt, 1));
+ uint64_t minSeqNo = sqlite3_column_int64(stmt, 2);
+ uint64_t maxSeqNo = sqlite3_column_int64(stmt, 3);
+ int priority = sqlite3_column_int(stmt, 4);
+ callback(deviceName, baseName, minSeqNo, maxSeqNo, priority);
}
sqlite3_finalize(stmt);
diff --git a/src/fetch-task-db.hpp b/src/fetch-task-db.hpp
index 573f836..ab3fdc9 100644
--- a/src/fetch-task-db.hpp
+++ b/src/fetch-task-db.hpp
@@ -20,33 +20,35 @@
#ifndef FETCH_TASK_DB_H
#define FETCH_TASK_DB_H
-#include <sqlite3.h>
-#include <ndnx-common.h>
-#include <ndnx-name.h>
#include <boost/filesystem.hpp>
#include <boost/shared_ptr.hpp>
+#include <ccnx-common.h>
+#include <ccnx-name.h>
+#include <sqlite3.h>
class FetchTaskDb
{
public:
- FetchTaskDb(const boost::filesystem::path &folder, const std::string &tag);
+ FetchTaskDb(const boost::filesystem::path& folder, const std::string& tag);
~FetchTaskDb();
// task with same deviceName and baseName combination will be added only once
// if task already exists, this call does nothing
void
- addTask(const Ndnx::Name &deviceName, const Ndnx::Name &baseName, uint64_t minSeqNo, uint64_t maxSeqNo, int priority);
+ addTask(const Ccnx::Name& deviceName, const Ccnx::Name& baseName, uint64_t minSeqNo,
+ uint64_t maxSeqNo, int priority);
void
- deleteTask(const Ndnx::Name &deviceName, const Ndnx::Name &baseName);
+ deleteTask(const Ccnx::Name& deviceName, const Ccnx::Name& baseName);
- typedef boost::function<void(const Ndnx::Name &, const Ndnx::Name &, uint64_t, uint64_t, int)> FetchTaskCallback;
+ typedef boost::function<void(const Ccnx::Name&, const Ccnx::Name&, uint64_t, uint64_t, int)>
+ FetchTaskCallback;
void
- foreachTask(const FetchTaskCallback &callback);
+ foreachTask(const FetchTaskCallback& callback);
private:
- sqlite3 *m_db;
+ sqlite3* m_db;
};
typedef boost::shared_ptr<FetchTaskDb> FetchTaskDbPtr;
diff --git a/src/fetcher.cpp b/src/fetcher.cpp
index 40c1ecd..e2ee6d0 100644
--- a/src/fetcher.cpp
+++ b/src/fetcher.cpp
@@ -19,170 +19,152 @@
*/
#include "fetcher.h"
+#include "ccnx-pco.h"
#include "fetch-manager.h"
-#include "ndnx-pco.h"
#include "logging.h"
+#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/make_shared.hpp>
#include <boost/ref.hpp>
#include <boost/throw_exception.hpp>
-#include <boost/date_time/posix_time/posix_time.hpp>
-INIT_LOGGER ("Fetcher");
+INIT_LOGGER("Fetcher");
using namespace boost;
using namespace std;
using namespace Ndnx;
-Fetcher::Fetcher (Ndnx::NdnxWrapperPtr ndnx,
- ExecutorPtr executor,
- const SegmentCallback &segmentCallback,
- const FinishCallback &finishCallback,
- OnFetchCompleteCallback onFetchComplete, OnFetchFailedCallback onFetchFailed,
- const Ndnx::Name &deviceName, const Ndnx::Name &name, int64_t minSeqNo, int64_t maxSeqNo,
- boost::posix_time::time_duration timeout/* = boost::posix_time::seconds (30)*/,
- const Ndnx::Name &forwardingHint/* = Ndnx::Name ()*/)
- : m_ndnx (ndnx)
+Fetcher::Fetcher(Ccnx::CcnxWrapperPtr ccnx, ExecutorPtr executor,
+ const SegmentCallback& segmentCallback, const FinishCallback& finishCallback,
+ OnFetchCompleteCallback onFetchComplete, OnFetchFailedCallback onFetchFailed,
+ const Ccnx::Name& deviceName, const Ccnx::Name& name, int64_t minSeqNo,
+ int64_t maxSeqNo,
+ boost::posix_time::time_duration timeout /* = boost::posix_time::seconds (30)*/,
+ const Ccnx::Name& forwardingHint /* = Ccnx::Name ()*/)
+ : m_ccnx(ccnx)
- , m_segmentCallback (segmentCallback)
- , m_onFetchComplete (onFetchComplete)
- , m_onFetchFailed (onFetchFailed)
- , m_finishCallback (finishCallback)
+ , m_segmentCallback(segmentCallback)
+ , m_onFetchComplete(onFetchComplete)
+ , m_onFetchFailed(onFetchFailed)
+ , m_finishCallback(finishCallback)
- , m_active (false)
- , m_timedwait (false)
- , m_name (name)
- , m_deviceName (deviceName)
- , m_forwardingHint (forwardingHint)
- , m_maximumNoActivityPeriod (timeout)
+ , m_active(false)
+ , m_timedwait(false)
+ , m_name(name)
+ , m_deviceName(deviceName)
+ , m_forwardingHint(forwardingHint)
+ , m_maximumNoActivityPeriod(timeout)
- , m_minSendSeqNo (minSeqNo-1)
- , m_maxInOrderRecvSeqNo (minSeqNo-1)
- , m_minSeqNo (minSeqNo)
- , m_maxSeqNo (maxSeqNo)
+ , m_minSendSeqNo(minSeqNo - 1)
+ , m_maxInOrderRecvSeqNo(minSeqNo - 1)
+ , m_minSeqNo(minSeqNo)
+ , m_maxSeqNo(maxSeqNo)
- , m_pipeline (1) // initial "congestion window"
- , m_activePipeline (0)
-
- , m_rto(1) // for temporary congestion control, should be removed when NDN provide transport functionality.
- , m_maxRto(static_cast<double>(timeout.total_seconds())/2)
- , m_slowStart(true)
- , m_threshold(4)
- , m_roundCount(0)
-
- , m_retryPause (0)
- , m_nextScheduledRetry (date_time::second_clock<boost::posix_time::ptime>::universal_time ())
- , m_executor (executor) // must be 1
+ , m_pipeline(6) // initial "congestion window"
+ , m_activePipeline(0)
+ , m_retryPause(0)
+ , m_nextScheduledRetry(date_time::second_clock<boost::posix_time::ptime>::universal_time())
+ , m_executor(executor) // must be 1
{
}
-Fetcher::~Fetcher ()
+Fetcher::~Fetcher()
{
}
void
-Fetcher::RestartPipeline ()
+Fetcher::RestartPipeline()
{
m_active = true;
m_minSendSeqNo = m_maxInOrderRecvSeqNo;
// cout << "Restart: " << m_minSendSeqNo << endl;
m_lastPositiveActivity = date_time::second_clock<boost::posix_time::ptime>::universal_time();
- m_executor->execute (bind (&Fetcher::FillPipeline, this));
+ m_executor->execute(bind(&Fetcher::FillPipeline, this));
}
void
-Fetcher::SetForwardingHint (const Ndnx::Name &forwardingHint)
+Fetcher::SetForwardingHint(const Ccnx::Name& forwardingHint)
{
m_forwardingHint = forwardingHint;
}
void
-Fetcher::FillPipeline ()
+Fetcher::FillPipeline()
{
- for (; m_minSendSeqNo < m_maxSeqNo && m_activePipeline < m_pipeline; m_minSendSeqNo++)
- {
- unique_lock<mutex> lock (m_seqNoMutex);
+ for (; m_minSendSeqNo < m_maxSeqNo && m_activePipeline < m_pipeline; m_minSendSeqNo++) {
+ unique_lock<mutex> lock(m_seqNoMutex);
- if (m_outOfOrderRecvSeqNo.find (m_minSendSeqNo+1) != m_outOfOrderRecvSeqNo.end ())
- continue;
+ if (m_outOfOrderRecvSeqNo.find(m_minSendSeqNo + 1) != m_outOfOrderRecvSeqNo.end())
+ continue;
- if (m_inActivePipeline.find (m_minSendSeqNo+1) != m_inActivePipeline.end ())
- continue;
+ if (m_inActivePipeline.find(m_minSendSeqNo + 1) != m_inActivePipeline.end())
+ continue;
- m_inActivePipeline.insert (m_minSendSeqNo+1);
+ m_inActivePipeline.insert(m_minSendSeqNo + 1);
- _LOG_DEBUG (" >>> i " << Name (m_forwardingHint)(m_name) << ", seq = " << (m_minSendSeqNo + 1 ));
+ _LOG_DEBUG(" >>> i " << Name(m_forwardingHint)(m_name) << ", seq = " << (m_minSendSeqNo + 1));
- // cout << ">>> " << m_minSendSeqNo+1 << endl;
- m_ndnx->sendInterest (Name (m_forwardingHint)(m_name)(m_minSendSeqNo+1),
- Closure (bind(&Fetcher::OnData, this, m_minSendSeqNo+1, _1, _2),
- bind(&Fetcher::OnTimeout, this, m_minSendSeqNo+1, _1, _2, _3)),
- Selectors().interestLifetime (m_rto)); // Alex: this lifetime should be changed to RTO
- _LOG_DEBUG (" >>> i ok");
+ // cout << ">>> " << m_minSendSeqNo+1 << endl;
+ m_ccnx->sendInterest(Name(m_forwardingHint)(m_name)(m_minSendSeqNo + 1),
+ Closure(bind(&Fetcher::OnData, this, m_minSendSeqNo + 1, _1, _2),
+ bind(&Fetcher::OnTimeout, this, m_minSendSeqNo + 1, _1, _2, _3)),
+ Selectors().interestLifetime(1)); // Alex: this lifetime should be changed to RTO
+ _LOG_DEBUG(" >>> i ok");
- m_activePipeline ++;
- }
+ m_activePipeline++;
+ }
}
void
-Fetcher::OnData (uint64_t seqno, const Ndnx::Name &name, PcoPtr data)
+Fetcher::OnData(uint64_t seqno, const Ccnx::Name& name, PcoPtr data)
{
- m_executor->execute (bind (&Fetcher::OnData_Execute, this, seqno, name, data));
+ m_executor->execute(bind(&Fetcher::OnData_Execute, this, seqno, name, data));
}
void
-Fetcher::OnData_Execute (uint64_t seqno, Ndnx::Name name, Ndnx::PcoPtr data)
+Fetcher::OnData_Execute(uint64_t seqno, Ccnx::Name name, Ccnx::PcoPtr data)
{
- _LOG_DEBUG (" <<< d " << name.getPartialName (0, name.size () - 1) << ", seq = " << seqno);
+ _LOG_DEBUG(" <<< d " << name.getPartialName(0, name.size() - 1) << ", seq = " << seqno);
- if (m_forwardingHint == Name ())
- {
+ if (m_forwardingHint == Name()) {
// TODO: check verified!!!!
- if (true)
- {
- if (!m_segmentCallback.empty ())
- {
- m_segmentCallback (m_deviceName, m_name, seqno, data);
+ if (true) {
+ if (!m_segmentCallback.empty()) {
+ m_segmentCallback(m_deviceName, m_name, seqno, data);
}
}
- else
- {
+ else {
_LOG_ERROR("Can not verify signature content. Name = " << data->name());
// probably needs to do more in the future
}
// we don't have to tell FetchManager about this
}
- else
- {
- // in this case we don't care whether "data" is verified, in fact, we expect it is unverified
- try {
- PcoPtr pco = make_shared<ParsedContentObject> (*data->contentPtr ());
+ else {
+ // in this case we don't care whether "data" is verified, in fact, we expect it is unverified
+ try {
+ PcoPtr pco = make_shared<ParsedContentObject>(*data->contentPtr());
- // we need to verify this pco and apply callback only when verified
- // TODO: check verified !!!
- if (true)
- {
- if (!m_segmentCallback.empty ())
- {
- m_segmentCallback (m_deviceName, m_name, seqno, pco);
- }
- }
- else
- {
- _LOG_ERROR("Can not verify signature content. Name = " << pco->name());
- // probably needs to do more in the future
+ // we need to verify this pco and apply callback only when verified
+ // TODO: check verified !!!
+ if (true) {
+ if (!m_segmentCallback.empty()) {
+ m_segmentCallback(m_deviceName, m_name, seqno, pco);
}
}
- catch (MisformedContentObjectException &e)
- {
- cerr << "MisformedContentObjectException..." << endl;
- // no idea what should do...
- // let's ignore for now
- }
+ else {
+ _LOG_ERROR("Can not verify signature content. Name = " << pco->name());
+ // probably needs to do more in the future
+ }
}
+ catch (MisformedContentObjectException& e) {
+ cerr << "MisformedContentObjectException..." << endl;
+ // no idea what should do...
+ // let's ignore for now
+ }
+ }
- m_activePipeline --;
+ m_activePipeline--;
m_lastPositiveActivity = date_time::second_clock<boost::posix_time::ptime>::universal_time();
{
@@ -206,132 +188,99 @@
////////////////////////////////////////////////////////////////////////////
- unique_lock<mutex> lock (m_seqNoMutex);
+ unique_lock<mutex> lock(m_seqNoMutex);
- m_outOfOrderRecvSeqNo.insert (seqno);
- m_inActivePipeline.erase (seqno);
- _LOG_DEBUG ("Total segments received: " << m_outOfOrderRecvSeqNo.size ());
- set<int64_t>::iterator inOrderSeqNo = m_outOfOrderRecvSeqNo.begin ();
- for (; inOrderSeqNo != m_outOfOrderRecvSeqNo.end ();
- inOrderSeqNo++)
- {
- _LOG_TRACE ("Checking " << *inOrderSeqNo << " and " << m_maxInOrderRecvSeqNo+1);
- if (*inOrderSeqNo == m_maxInOrderRecvSeqNo+1)
- {
- m_maxInOrderRecvSeqNo = *inOrderSeqNo;
- }
- else if (*inOrderSeqNo < m_maxInOrderRecvSeqNo+1) // not possible anymore, but just in case
- {
- continue;
- }
- else
- break;
+ m_outOfOrderRecvSeqNo.insert(seqno);
+ m_inActivePipeline.erase(seqno);
+ _LOG_DEBUG("Total segments received: " << m_outOfOrderRecvSeqNo.size());
+ set<int64_t>::iterator inOrderSeqNo = m_outOfOrderRecvSeqNo.begin();
+ for (; inOrderSeqNo != m_outOfOrderRecvSeqNo.end(); inOrderSeqNo++) {
+ _LOG_TRACE("Checking " << *inOrderSeqNo << " and " << m_maxInOrderRecvSeqNo + 1);
+ if (*inOrderSeqNo == m_maxInOrderRecvSeqNo + 1) {
+ m_maxInOrderRecvSeqNo = *inOrderSeqNo;
}
- m_outOfOrderRecvSeqNo.erase (m_outOfOrderRecvSeqNo.begin (), inOrderSeqNo);
+ else if (*inOrderSeqNo < m_maxInOrderRecvSeqNo + 1) // not possible anymore, but just in case
+ {
+ continue;
+ }
+ else
+ break;
+ }
+ m_outOfOrderRecvSeqNo.erase(m_outOfOrderRecvSeqNo.begin(), inOrderSeqNo);
////////////////////////////////////////////////////////////////////////////
- _LOG_TRACE ("Max in order received: " << m_maxInOrderRecvSeqNo << ", max seqNo to request: " << m_maxSeqNo);
+ _LOG_TRACE("Max in order received: " << m_maxInOrderRecvSeqNo
+ << ", max seqNo to request: " << m_maxSeqNo);
- if (m_maxInOrderRecvSeqNo == m_maxSeqNo)
- {
- _LOG_TRACE ("Fetch finished: " << m_name);
- m_active = false;
- // invoke callback
- if (!m_finishCallback.empty ())
- {
- _LOG_TRACE ("Notifying callback");
- m_finishCallback(m_deviceName, m_name);
- }
+ if (m_maxInOrderRecvSeqNo == m_maxSeqNo) {
+ _LOG_TRACE("Fetch finished: " << m_name);
+ m_active = false;
+ // invoke callback
+ if (!m_finishCallback.empty()) {
+ _LOG_TRACE("Notifying callback");
+ m_finishCallback(m_deviceName, m_name);
+ }
- // tell FetchManager that we have finish our job
- // m_onFetchComplete (*this);
- // using executor, so we won't be deleted if there is scheduled FillPipeline call
- if (!m_onFetchComplete.empty ())
- {
- m_timedwait = true;
- m_executor->execute (bind (m_onFetchComplete, ref(*this), m_deviceName, m_name));
- }
+ // tell FetchManager that we have finish our job
+ // m_onFetchComplete (*this);
+ // using executor, so we won't be deleted if there is scheduled FillPipeline call
+ if (!m_onFetchComplete.empty()) {
+ m_timedwait = true;
+ m_executor->execute(bind(m_onFetchComplete, ref(*this), m_deviceName, m_name));
}
- else
- {
- m_executor->execute (bind (&Fetcher::FillPipeline, this));
- }
+ }
+ else {
+ m_executor->execute(bind(&Fetcher::FillPipeline, this));
+ }
}
void
-Fetcher::OnTimeout (uint64_t seqno, const Ndnx::Name &name, const Closure &closure, Selectors selectors)
+Fetcher::OnTimeout(uint64_t seqno, const Ccnx::Name& name, const Closure& closure, Selectors selectors)
{
- _LOG_DEBUG (this << ", " << m_executor.get ());
- m_executor->execute (bind (&Fetcher::OnTimeout_Execute, this, seqno, name, closure, selectors));
+ _LOG_DEBUG(this << ", " << m_executor.get());
+ m_executor->execute(bind(&Fetcher::OnTimeout_Execute, this, seqno, name, closure, selectors));
}
void
-Fetcher::OnTimeout_Execute (uint64_t seqno, Ndnx::Name name, Ndnx::Closure closure, Ndnx::Selectors selectors)
+Fetcher::OnTimeout_Execute(uint64_t seqno, Ccnx::Name name, Ccnx::Closure closure,
+ Ccnx::Selectors selectors)
{
- _LOG_DEBUG (" <<< :( timeout " << name.getPartialName (0, name.size () - 1) << ", seq = " << seqno);
+ _LOG_DEBUG(" <<< :( timeout " << name.getPartialName(0, name.size() - 1) << ", seq = " << seqno);
// cout << "Fetcher::OnTimeout: " << name << endl;
// cout << "Last: " << m_lastPositiveActivity << ", config: " << m_maximumNoActivityPeriod
// << ", now: " << date_time::second_clock<boost::posix_time::ptime>::universal_time()
// << ", oldest: " << (date_time::second_clock<boost::posix_time::ptime>::universal_time() - m_maximumNoActivityPeriod) << endl;
- if (m_lastPositiveActivity <
- (date_time::second_clock<boost::posix_time::ptime>::universal_time() - m_maximumNoActivityPeriod))
+ if (m_lastPositiveActivity < (date_time::second_clock<boost::posix_time::ptime>::universal_time() -
+ m_maximumNoActivityPeriod)) {
+ bool done = false;
{
- bool done = false;
- {
- unique_lock<mutex> lock (m_seqNoMutex);
- m_inActivePipeline.erase (seqno);
- m_activePipeline --;
+ unique_lock<mutex> lock(m_seqNoMutex);
+ m_inActivePipeline.erase(seqno);
+ m_activePipeline--;
- if (m_activePipeline == 0)
- {
- done = true;
- }
+ if (m_activePipeline == 0) {
+ done = true;
+ }
+ }
+
+ if (done) {
+ {
+ unique_lock<mutex> lock(m_seqNoMutex);
+ _LOG_DEBUG("Telling that fetch failed");
+ _LOG_DEBUG("Active pipeline size should be zero: " << m_inActivePipeline.size());
}
- if (done)
- {
- {
- unique_lock<mutex> lock (m_seqNoMutex);
- _LOG_DEBUG ("Telling that fetch failed");
- _LOG_DEBUG ("Active pipeline size should be zero: " << m_inActivePipeline.size ());
- }
-
- m_active = false;
- if (!m_onFetchFailed.empty ())
- {
- m_onFetchFailed (ref (*this));
- }
- // this is not valid anymore, but we still should be able finish work
- }
- }
- else
- {
- _LOG_DEBUG ("Asking to reexpress seqno: " << seqno);
- {
- unique_lock<mutex> lock (m_rtoMutex);
- _LOG_DEBUG ("Interest Timeout");
- m_rto = m_rto * 2;
- if(m_rto > m_maxRto)
- {
- m_rto = m_maxRto;
- _LOG_DEBUG ("RTO is max: " << m_rto);
- }
- else
- {
- _LOG_DEBUG ("RTO is doubled: " << m_rto);
-}
+ m_active = false;
+ if (!m_onFetchFailed.empty()) {
+ m_onFetchFailed(ref(*this));
}
-
- {
- unique_lock<mutex> lock (m_pipelineMutex);
- m_threshold = m_pipeline / 2;
- m_pipeline = 1;
- m_roundCount = 0;
- m_slowStart = true;
- }
-
- m_ndnx->sendInterest (name, closure, selectors.interestLifetime (m_rto));
+ // this is not valid anymore, but we still should be able finish work
}
+ }
+ else {
+ _LOG_DEBUG("Asking to reexpress seqno: " << seqno);
+ m_ccnx->sendInterest(name, closure, selectors);
+ }
}
diff --git a/src/fetcher.hpp b/src/fetcher.hpp
index 5ce4746..c1da2a3 100644
--- a/src/fetcher.hpp
+++ b/src/fetcher.hpp
@@ -21,12 +21,12 @@
#ifndef FETCHER_H
#define FETCHER_H
-#include "ndnx-wrapper.h"
-#include "ndnx-name.h"
+#include "ccnx-name.h"
+#include "ccnx-wrapper.h"
#include "executor.h"
-#include <boost/intrusive/list.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
+#include <boost/intrusive/list.hpp>
#include <set>
#include <set>
@@ -36,70 +36,99 @@
class Fetcher
{
public:
- typedef boost::function<void(Ndnx::Name &deviceName, Ndnx::Name &baseName, uint64_t seq, Ndnx::PcoPtr pco)> SegmentCallback;
- typedef boost::function<void(Ndnx::Name &deviceName, Ndnx::Name &baseName)> FinishCallback;
- typedef boost::function<void (Fetcher &, const Ndnx::Name &deviceName, const Ndnx::Name &baseName)> OnFetchCompleteCallback;
- typedef boost::function<void (Fetcher &)> OnFetchFailedCallback;
+ typedef boost::function<void(Ccnx::Name& deviceName, Ccnx::Name& baseName, uint64_t seq, Ccnx::PcoPtr pco)>
+ SegmentCallback;
+ typedef boost::function<void(Ccnx::Name& deviceName, Ccnx::Name& baseName)> FinishCallback;
+ typedef boost::function<void(Fetcher&, const Ccnx::Name& deviceName, const Ccnx::Name& baseName)>
+ OnFetchCompleteCallback;
+ typedef boost::function<void(Fetcher&)> OnFetchFailedCallback;
- Fetcher (Ndnx::NdnxWrapperPtr ndnx,
- ExecutorPtr executor,
- const SegmentCallback &segmentCallback, // callback passed by caller of FetchManager
- const FinishCallback &finishCallback, // callback passed by caller of FetchManager
- OnFetchCompleteCallback onFetchComplete, OnFetchFailedCallback onFetchFailed, // callbacks provided by FetchManager
- const Ndnx::Name &deviceName, const Ndnx::Name &name, int64_t minSeqNo, int64_t maxSeqNo,
- boost::posix_time::time_duration timeout = boost::posix_time::seconds (30), // this time is not precise, but sets min bound
- // actual time depends on how fast Interests timeout
- const Ndnx::Name &forwardingHint = Ndnx::Name ());
- virtual ~Fetcher ();
+ Fetcher(Ccnx::CcnxWrapperPtr ccnx, ExecutorPtr executor,
+ const SegmentCallback& segmentCallback, // callback passed by caller of FetchManager
+ const FinishCallback& finishCallback, // callback passed by caller of FetchManager
+ OnFetchCompleteCallback onFetchComplete,
+ OnFetchFailedCallback onFetchFailed, // callbacks provided by FetchManager
+ const Ccnx::Name& deviceName, const Ccnx::Name& name, int64_t minSeqNo, int64_t maxSeqNo,
+ boost::posix_time::time_duration timeout =
+ boost::posix_time::seconds(30), // this time is not precise, but sets min bound
+ // actual time depends on how fast Interests timeout
+ const Ccnx::Name& forwardingHint = Ccnx::Name());
+ virtual ~Fetcher();
inline bool
- IsActive () const;
+ IsActive() const;
inline bool
- IsTimedWait() const { return m_timedwait; }
+ IsTimedWait() const
+ {
+ return m_timedwait;
+ }
void
- RestartPipeline ();
+ RestartPipeline();
void
- SetForwardingHint (const Ndnx::Name &forwardingHint);
+ SetForwardingHint(const Ccnx::Name& forwardingHint);
- const Ndnx::Name &
- GetForwardingHint () const { return m_forwardingHint; }
+ const Ccnx::Name&
+ GetForwardingHint() const
+ {
+ return m_forwardingHint;
+ }
- const Ndnx::Name &
- GetName () const { return m_name; }
+ const Ccnx::Name&
+ GetName() const
+ {
+ return m_name;
+ }
- const Ndnx::Name &
- GetDeviceName () const { return m_deviceName; }
+ const Ccnx::Name&
+ GetDeviceName() const
+ {
+ return m_deviceName;
+ }
double
- GetRetryPause () const { return m_retryPause; }
+ GetRetryPause() const
+ {
+ return m_retryPause;
+ }
void
- SetRetryPause (double pause) { m_retryPause = pause; }
+ SetRetryPause(double pause)
+ {
+ m_retryPause = pause;
+ }
boost::posix_time::ptime
- GetNextScheduledRetry () const { return m_nextScheduledRetry; }
+ GetNextScheduledRetry() const
+ {
+ return m_nextScheduledRetry;
+ }
void
- SetNextScheduledRetry (boost::posix_time::ptime nextScheduledRetry) { m_nextScheduledRetry = nextScheduledRetry; }
+ SetNextScheduledRetry(boost::posix_time::ptime nextScheduledRetry)
+ {
+ m_nextScheduledRetry = nextScheduledRetry;
+ }
private:
void
- FillPipeline ();
+ FillPipeline();
void
- OnData (uint64_t seqno, const Ndnx::Name &name, Ndnx::PcoPtr data);
+ OnData(uint64_t seqno, const Ccnx::Name& name, Ccnx::PcoPtr data);
void
- OnData_Execute (uint64_t seqno, Ndnx::Name name, Ndnx::PcoPtr data);
+ OnData_Execute(uint64_t seqno, Ccnx::Name name, Ccnx::PcoPtr data);
void
- OnTimeout (uint64_t seqno, const Ndnx::Name &name, const Ndnx::Closure &closure, Ndnx::Selectors selectors);
+ OnTimeout(uint64_t seqno, const Ccnx::Name& name, const Ccnx::Closure& closure,
+ Ccnx::Selectors selectors);
void
- OnTimeout_Execute (uint64_t seqno, Ndnx::Name name, Ndnx::Closure closure, Ndnx::Selectors selectors);
+ OnTimeout_Execute(uint64_t seqno, Ccnx::Name name, Ccnx::Closure closure,
+ Ccnx::Selectors selectors);
public:
boost::intrusive::list_member_hook<> m_managerListHook;
@@ -153,13 +182,15 @@
typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info_str;
namespace Error {
-struct Fetcher : virtual boost::exception, virtual std::exception { };
+struct Fetcher : virtual boost::exception, virtual std::exception
+{
+};
}
typedef boost::shared_ptr<Fetcher> FetcherPtr;
bool
-Fetcher::IsActive () const
+Fetcher::IsActive() const
{
return m_active;
}
diff --git a/src/file-state.cpp b/src/file-state.cpp
index 7904586..8ff065c 100644
--- a/src/file-state.cpp
+++ b/src/file-state.cpp
@@ -22,7 +22,7 @@
#include "logging.h"
#include <boost/bind.hpp>
-INIT_LOGGER ("FileState");
+INIT_LOGGER("FileState");
using namespace boost;
using namespace std;
@@ -51,122 +51,123 @@
CREATE INDEX FileState_type_file_hash ON FileState (type, file_hash); \n\
";
-FileState::FileState (const boost::filesystem::path &path, bool cow)
- : DbHelper (path / ".chronoshare", (cow ? "file-state-tmp.db" : "file-state.db"))
+FileState::FileState(const boost::filesystem::path& path)
+ : DbHelper(path / ".chronoshare", "file-state.db")
{
- sqlite3_exec (m_db, INIT_DATABASE.c_str (), NULL, NULL, NULL);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_exec(m_db, INIT_DATABASE.c_str(), NULL, NULL, NULL);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
}
-FileState::~FileState ()
+FileState::~FileState()
{
}
void
-FileState::UpdateFile (const std::string &filename, sqlite3_int64 version,
- const Hash &hash, const Ndnx::NdnxCharbuf &device_name, sqlite3_int64 seq_no,
- time_t atime, time_t mtime, time_t ctime, int mode, int seg_num)
+FileState::UpdateFile(const std::string& filename, sqlite3_int64 version, const Hash& hash,
+ const Ccnx::CcnxCharbuf& device_name, sqlite3_int64 seq_no, time_t atime,
+ time_t mtime, time_t ctime, int mode, int seg_num)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "UPDATE FileState "
- "SET "
- "device_name=?, seq_no=?, "
- "version=?,"
- "file_hash=?,"
- "file_atime=datetime(?, 'unixepoch'),"
- "file_mtime=datetime(?, 'unixepoch'),"
- "file_ctime=datetime(?, 'unixepoch'),"
- "file_chmod=?, "
- "file_seg_num=? "
- "WHERE type=0 AND filename=?", -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db, "UPDATE FileState "
+ "SET "
+ "device_name=?, seq_no=?, "
+ "version=?,"
+ "file_hash=?,"
+ "file_atime=datetime(?, 'unixepoch'),"
+ "file_mtime=datetime(?, 'unixepoch'),"
+ "file_ctime=datetime(?, 'unixepoch'),"
+ "file_chmod=?, "
+ "file_seg_num=? "
+ "WHERE type=0 AND filename=?",
+ -1, &stmt, 0);
- sqlite3_bind_blob (stmt, 1, device_name.buf (), device_name.length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 2, seq_no);
- sqlite3_bind_int64 (stmt, 3, version);
- sqlite3_bind_blob (stmt, 4, hash.GetHash (), hash.GetHashBytes (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 5, atime);
- sqlite3_bind_int64 (stmt, 6, mtime);
- sqlite3_bind_int64 (stmt, 7, ctime);
- sqlite3_bind_int (stmt, 8, mode);
- sqlite3_bind_int (stmt, 9, seg_num);
- sqlite3_bind_text (stmt, 10, filename.c_str (), -1, SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 1, device_name.buf(), device_name.length(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 2, seq_no);
+ sqlite3_bind_int64(stmt, 3, version);
+ sqlite3_bind_blob(stmt, 4, hash.GetHash(), hash.GetHashBytes(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 5, atime);
+ sqlite3_bind_int64(stmt, 6, mtime);
+ sqlite3_bind_int64(stmt, 7, ctime);
+ sqlite3_bind_int(stmt, 8, mode);
+ sqlite3_bind_int(stmt, 9, seg_num);
+ sqlite3_bind_text(stmt, 10, filename.c_str(), -1, SQLITE_STATIC);
- sqlite3_step (stmt);
+ sqlite3_step(stmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_ROW && sqlite3_errcode (m_db) != SQLITE_DONE,
- sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_ROW && sqlite3_errcode(m_db) != SQLITE_DONE,
+ sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
- int affected_rows = sqlite3_changes (m_db);
+ int affected_rows = sqlite3_changes(m_db);
if (affected_rows == 0) // file didn't exist
- {
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "INSERT INTO FileState "
- "(type,filename,version,device_name,seq_no,file_hash,file_atime,file_mtime,file_ctime,file_chmod,file_seg_num) "
- "VALUES (0, ?, ?, ?, ?, ?, "
- "datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?, ?)", -1, &stmt, 0);
+ {
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db,
+ "INSERT INTO FileState "
+ "(type,filename,version,device_name,seq_no,file_hash,file_atime,file_mtime,file_ctime,file_chmod,file_seg_num) "
+ "VALUES (0, ?, ?, ?, ?, ?, "
+ "datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?, ?)",
+ -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_text (stmt, 1, filename.c_str (), -1, SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 2, version);
- sqlite3_bind_blob (stmt, 3, device_name.buf (), device_name.length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 4, seq_no);
- sqlite3_bind_blob (stmt, 5, hash.GetHash (), hash.GetHashBytes (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 6, atime);
- sqlite3_bind_int64 (stmt, 7, mtime);
- sqlite3_bind_int64 (stmt, 8, ctime);
- sqlite3_bind_int (stmt, 9, mode);
- sqlite3_bind_int (stmt, 10, seg_num);
+ sqlite3_bind_text(stmt, 1, filename.c_str(), -1, SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 2, version);
+ sqlite3_bind_blob(stmt, 3, device_name.buf(), device_name.length(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 4, seq_no);
+ sqlite3_bind_blob(stmt, 5, hash.GetHash(), hash.GetHashBytes(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 6, atime);
+ sqlite3_bind_int64(stmt, 7, mtime);
+ sqlite3_bind_int64(stmt, 8, ctime);
+ sqlite3_bind_int(stmt, 9, mode);
+ sqlite3_bind_int(stmt, 10, seg_num);
- sqlite3_step (stmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE,
- sqlite3_errmsg (m_db));
- sqlite3_finalize (stmt);
+ sqlite3_step(stmt);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
+ sqlite3_finalize(stmt);
- sqlite3_prepare_v2 (m_db, "UPDATE FileState SET directory=directory_name(filename) WHERE filename=?", -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_prepare_v2(m_db,
+ "UPDATE FileState SET directory=directory_name(filename) WHERE filename=?",
+ -1, &stmt, 0);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_text (stmt, 1, filename.c_str (), -1, SQLITE_STATIC);
- sqlite3_step (stmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE,
- sqlite3_errmsg (m_db));
- sqlite3_finalize (stmt);
- }
+ sqlite3_bind_text(stmt, 1, filename.c_str(), -1, SQLITE_STATIC);
+ sqlite3_step(stmt);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
+ sqlite3_finalize(stmt);
+ }
}
void
-FileState::DeleteFile (const std::string &filename)
+FileState::DeleteFile(const std::string& filename)
{
-
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "DELETE FROM FileState WHERE type=0 AND filename=?", -1, &stmt, 0);
- sqlite3_bind_text (stmt, 1, filename.c_str (), -1, SQLITE_STATIC);
-
- _LOG_DEBUG ("Delete " << filename);
-
- sqlite3_step (stmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE,
- sqlite3_errmsg (m_db));
- sqlite3_finalize (stmt);
-}
-
-
-void
-FileState::SetFileComplete (const std::string &filename)
-{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db,
- "UPDATE FileState SET is_complete=1 WHERE type = 0 AND filename = ?", -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db, "DELETE FROM FileState WHERE type=0 AND filename=?", -1, &stmt, 0);
sqlite3_bind_text(stmt, 1, filename.c_str(), -1, SQLITE_STATIC);
- sqlite3_step (stmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ _LOG_DEBUG("Delete " << filename);
- sqlite3_finalize (stmt);
+ sqlite3_step(stmt);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
+ sqlite3_finalize(stmt);
+}
+
+
+void
+FileState::SetFileComplete(const std::string& filename)
+{
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db, "UPDATE FileState SET is_complete=1 WHERE type = 0 AND filename = ?", -1,
+ &stmt, 0);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
+ sqlite3_bind_text(stmt, 1, filename.c_str(), -1, SQLITE_STATIC);
+
+ sqlite3_step(stmt);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
+
+ sqlite3_finalize(stmt);
}
@@ -174,191 +175,199 @@
* @todo Implement checking modification time and permissions
*/
FileItemPtr
-FileState::LookupFile (const std::string &filename)
+FileState::LookupFile(const std::string& filename)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db,
- "SELECT filename,version,device_name,seq_no,file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num,is_complete "
- " FROM FileState "
- " WHERE type = 0 AND filename = ?", -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db,
+ "SELECT filename,version,device_name,seq_no,file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num,is_complete "
+ " FROM FileState "
+ " WHERE type = 0 AND filename = ?",
+ -1, &stmt, 0);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
sqlite3_bind_text(stmt, 1, filename.c_str(), -1, SQLITE_STATIC);
FileItemPtr retval;
- if (sqlite3_step (stmt) == SQLITE_ROW)
- {
- retval = make_shared<FileItem> ();
- retval->set_filename (reinterpret_cast<const char *> (sqlite3_column_text (stmt, 0)), sqlite3_column_bytes (stmt, 0));
- retval->set_version (sqlite3_column_int64 (stmt, 1));
- retval->set_device_name (sqlite3_column_blob (stmt, 2), sqlite3_column_bytes (stmt, 2));
- retval->set_seq_no (sqlite3_column_int64 (stmt, 3));
- retval->set_file_hash (sqlite3_column_blob (stmt, 4), sqlite3_column_bytes (stmt, 4));
- retval->set_mtime (sqlite3_column_int (stmt, 5));
- retval->set_mode (sqlite3_column_int (stmt, 6));
- retval->set_seg_num (sqlite3_column_int64 (stmt, 7));
- retval->set_is_complete (sqlite3_column_int (stmt, 8));
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ retval = make_shared<FileItem>();
+ retval->set_filename(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0));
+ retval->set_version(sqlite3_column_int64(stmt, 1));
+ retval->set_device_name(sqlite3_column_blob(stmt, 2), sqlite3_column_bytes(stmt, 2));
+ retval->set_seq_no(sqlite3_column_int64(stmt, 3));
+ retval->set_file_hash(sqlite3_column_blob(stmt, 4), sqlite3_column_bytes(stmt, 4));
+ retval->set_mtime(sqlite3_column_int(stmt, 5));
+ retval->set_mode(sqlite3_column_int(stmt, 6));
+ retval->set_seg_num(sqlite3_column_int64(stmt, 7));
+ retval->set_is_complete(sqlite3_column_int(stmt, 8));
}
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
- sqlite3_finalize (stmt);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
+ sqlite3_finalize(stmt);
return retval;
}
FileItemsPtr
-FileState::LookupFilesForHash (const Hash &hash)
+FileState::LookupFilesForHash(const Hash& hash)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db,
- "SELECT filename,version,device_name,seq_no,file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num,is_complete "
- " FROM FileState "
- " WHERE type = 0 AND file_hash = ?", -1, &stmt, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
- sqlite3_bind_blob(stmt, 1, hash.GetHash (), hash.GetHashBytes (), SQLITE_STATIC);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db,
+ "SELECT filename,version,device_name,seq_no,file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num,is_complete "
+ " FROM FileState "
+ " WHERE type = 0 AND file_hash = ?",
+ -1, &stmt, 0);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
+ sqlite3_bind_blob(stmt, 1, hash.GetHash(), hash.GetHashBytes(), SQLITE_STATIC);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- FileItemsPtr retval = make_shared<FileItems> ();
- while (sqlite3_step (stmt) == SQLITE_ROW)
- {
- FileItem file;
- file.set_filename (reinterpret_cast<const char *> (sqlite3_column_text (stmt, 0)), sqlite3_column_bytes (stmt, 0));
- file.set_version (sqlite3_column_int64 (stmt, 1));
- file.set_device_name (sqlite3_column_blob (stmt, 2), sqlite3_column_bytes (stmt, 2));
- file.set_seq_no (sqlite3_column_int64 (stmt, 3));
- file.set_file_hash (sqlite3_column_blob (stmt, 4), sqlite3_column_bytes (stmt, 4));
- file.set_mtime (sqlite3_column_int (stmt, 5));
- file.set_mode (sqlite3_column_int (stmt, 6));
- file.set_seg_num (sqlite3_column_int64 (stmt, 7));
- file.set_is_complete (sqlite3_column_int (stmt, 8));
+ FileItemsPtr retval = make_shared<FileItems>();
+ while (sqlite3_step(stmt) == SQLITE_ROW) {
+ FileItem file;
+ file.set_filename(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0));
+ file.set_version(sqlite3_column_int64(stmt, 1));
+ file.set_device_name(sqlite3_column_blob(stmt, 2), sqlite3_column_bytes(stmt, 2));
+ file.set_seq_no(sqlite3_column_int64(stmt, 3));
+ file.set_file_hash(sqlite3_column_blob(stmt, 4), sqlite3_column_bytes(stmt, 4));
+ file.set_mtime(sqlite3_column_int(stmt, 5));
+ file.set_mode(sqlite3_column_int(stmt, 6));
+ file.set_seg_num(sqlite3_column_int64(stmt, 7));
+ file.set_is_complete(sqlite3_column_int(stmt, 8));
- retval->push_back (file);
- }
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ retval->push_back(file);
+ }
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
return retval;
}
void
-FileState::LookupFilesInFolder (const boost::function<void (const FileItem&)> &visitor, const std::string &folder, int offset/*=0*/, int limit/*=-1*/)
+FileState::LookupFilesInFolder(const boost::function<void(const FileItem&)>& visitor,
+ const std::string& folder, int offset /*=0*/, int limit /*=-1*/)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db,
- "SELECT filename,version,device_name,seq_no,file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num,is_complete "
- " FROM FileState "
- " WHERE type = 0 AND directory = ?"
- " LIMIT ? OFFSET ?", -1, &stmt, 0);
- if (folder.size () == 0)
- sqlite3_bind_null (stmt, 1);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db,
+ "SELECT filename,version,device_name,seq_no,file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num,is_complete "
+ " FROM FileState "
+ " WHERE type = 0 AND directory = ?"
+ " LIMIT ? OFFSET ?",
+ -1, &stmt, 0);
+ if (folder.size() == 0)
+ sqlite3_bind_null(stmt, 1);
else
- sqlite3_bind_text (stmt, 1, folder.c_str (), folder.size (), SQLITE_STATIC);
+ sqlite3_bind_text(stmt, 1, folder.c_str(), folder.size(), SQLITE_STATIC);
- sqlite3_bind_int (stmt, 2, limit);
- sqlite3_bind_int (stmt, 3, offset);
+ sqlite3_bind_int(stmt, 2, limit);
+ sqlite3_bind_int(stmt, 3, offset);
- while (sqlite3_step (stmt) == SQLITE_ROW)
- {
- FileItem file;
- file.set_filename (reinterpret_cast<const char *> (sqlite3_column_text (stmt, 0)), sqlite3_column_bytes (stmt, 0));
- file.set_version (sqlite3_column_int64 (stmt, 1));
- file.set_device_name (sqlite3_column_blob (stmt, 2), sqlite3_column_bytes (stmt, 2));
- file.set_seq_no (sqlite3_column_int64 (stmt, 3));
- file.set_file_hash (sqlite3_column_blob (stmt, 4), sqlite3_column_bytes (stmt, 4));
- file.set_mtime (sqlite3_column_int (stmt, 5));
- file.set_mode (sqlite3_column_int (stmt, 6));
- file.set_seg_num (sqlite3_column_int64 (stmt, 7));
- file.set_is_complete (sqlite3_column_int (stmt, 8));
+ while (sqlite3_step(stmt) == SQLITE_ROW) {
+ FileItem file;
+ file.set_filename(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0));
+ file.set_version(sqlite3_column_int64(stmt, 1));
+ file.set_device_name(sqlite3_column_blob(stmt, 2), sqlite3_column_bytes(stmt, 2));
+ file.set_seq_no(sqlite3_column_int64(stmt, 3));
+ file.set_file_hash(sqlite3_column_blob(stmt, 4), sqlite3_column_bytes(stmt, 4));
+ file.set_mtime(sqlite3_column_int(stmt, 5));
+ file.set_mode(sqlite3_column_int(stmt, 6));
+ file.set_seg_num(sqlite3_column_int64(stmt, 7));
+ file.set_is_complete(sqlite3_column_int(stmt, 8));
- visitor (file);
- }
+ visitor(file);
+ }
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
}
FileItemsPtr
-FileState::LookupFilesInFolder (const std::string &folder, int offset/*=0*/, int limit/*=-1*/)
+FileState::LookupFilesInFolder(const std::string& folder, int offset /*=0*/, int limit /*=-1*/)
{
- FileItemsPtr retval = make_shared<FileItems> ();
- LookupFilesInFolder (boost::bind (&FileItems::push_back, retval.get (), _1), folder, offset, limit);
+ FileItemsPtr retval = make_shared<FileItems>();
+ LookupFilesInFolder(boost::bind(&FileItems::push_back, retval.get(), _1), folder, offset, limit);
return retval;
}
bool
-FileState::LookupFilesInFolderRecursively (const boost::function<void (const FileItem&)> &visitor, const std::string &folder, int offset/*=0*/, int limit/*=-1*/)
+FileState::LookupFilesInFolderRecursively(const boost::function<void(const FileItem&)>& visitor,
+ const std::string& folder, int offset /*=0*/,
+ int limit /*=-1*/)
{
- _LOG_DEBUG ("LookupFilesInFolderRecursively: [" << folder << "]");
+ _LOG_DEBUG("LookupFilesInFolderRecursively: [" << folder << "]");
if (limit >= 0)
- limit ++;
+ limit++;
- sqlite3_stmt *stmt;
- if (folder != "")
- {
- /// @todo Do something to improve efficiency of this query. Right now it is basically scanning the whole database
+ sqlite3_stmt* stmt;
+ if (folder != "") {
+ /// @todo Do something to improve efficiency of this query. Right now it is basically scanning the whole database
- sqlite3_prepare_v2 (m_db,
- "SELECT filename,version,device_name,seq_no,file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num,is_complete "
- " FROM FileState "
- " WHERE type = 0 AND is_dir_prefix (?, directory)=1 "
- " ORDER BY filename "
- " LIMIT ? OFFSET ?", -1, &stmt, 0); // there is a small ambiguity with is_prefix matching, but should be ok for now
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_prepare_v2(m_db,
+ "SELECT filename,version,device_name,seq_no,file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num,is_complete "
+ " FROM FileState "
+ " WHERE type = 0 AND is_dir_prefix (?, directory)=1 "
+ " ORDER BY filename "
+ " LIMIT ? OFFSET ?",
+ -1, &stmt,
+ 0); // there is a small ambiguity with is_prefix matching, but should be ok for now
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_text (stmt, 1, folder.c_str (), folder.size (), SQLITE_STATIC);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_bind_text(stmt, 1, folder.c_str(), folder.size(), SQLITE_STATIC);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_bind_int (stmt, 2, limit);
- sqlite3_bind_int (stmt, 3, offset);
- }
- else
- {
- sqlite3_prepare_v2 (m_db,
- "SELECT filename,version,device_name,seq_no,file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num,is_complete "
- " FROM FileState "
- " WHERE type = 0"
- " ORDER BY filename "
- " LIMIT ? OFFSET ?", -1, &stmt, 0);
- sqlite3_bind_int (stmt, 1, limit);
- sqlite3_bind_int (stmt, 2, offset);
- }
+ sqlite3_bind_int(stmt, 2, limit);
+ sqlite3_bind_int(stmt, 3, offset);
+ }
+ else {
+ sqlite3_prepare_v2(m_db,
+ "SELECT filename,version,device_name,seq_no,file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num,is_complete "
+ " FROM FileState "
+ " WHERE type = 0"
+ " ORDER BY filename "
+ " LIMIT ? OFFSET ?",
+ -1, &stmt, 0);
+ sqlite3_bind_int(stmt, 1, limit);
+ sqlite3_bind_int(stmt, 2, offset);
+ }
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- while (sqlite3_step (stmt) == SQLITE_ROW)
- {
- if (limit == 1)
- break;
+ while (sqlite3_step(stmt) == SQLITE_ROW) {
+ if (limit == 1)
+ break;
- FileItem file;
- file.set_filename (reinterpret_cast<const char *> (sqlite3_column_text (stmt, 0)), sqlite3_column_bytes (stmt, 0));
- file.set_version (sqlite3_column_int64 (stmt, 1));
- file.set_device_name (sqlite3_column_blob (stmt, 2), sqlite3_column_bytes (stmt, 2));
- file.set_seq_no (sqlite3_column_int64 (stmt, 3));
- file.set_file_hash (sqlite3_column_blob (stmt, 4), sqlite3_column_bytes (stmt, 4));
- file.set_mtime (sqlite3_column_int (stmt, 5));
- file.set_mode (sqlite3_column_int (stmt, 6));
- file.set_seg_num (sqlite3_column_int64 (stmt, 7));
- file.set_is_complete (sqlite3_column_int (stmt, 8));
+ FileItem file;
+ file.set_filename(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0));
+ file.set_version(sqlite3_column_int64(stmt, 1));
+ file.set_device_name(sqlite3_column_blob(stmt, 2), sqlite3_column_bytes(stmt, 2));
+ file.set_seq_no(sqlite3_column_int64(stmt, 3));
+ file.set_file_hash(sqlite3_column_blob(stmt, 4), sqlite3_column_bytes(stmt, 4));
+ file.set_mtime(sqlite3_column_int(stmt, 5));
+ file.set_mode(sqlite3_column_int(stmt, 6));
+ file.set_seg_num(sqlite3_column_int64(stmt, 7));
+ file.set_is_complete(sqlite3_column_int(stmt, 8));
- visitor (file);
- limit --;
- }
+ visitor(file);
+ limit--;
+ }
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
return (limit == 1);
}
FileItemsPtr
-FileState::LookupFilesInFolderRecursively (const std::string &folder, int offset/*=0*/, int limit/*=-1*/)
+FileState::LookupFilesInFolderRecursively(const std::string& folder, int offset /*=0*/,
+ int limit /*=-1*/)
{
- FileItemsPtr retval = make_shared<FileItems> ();
- LookupFilesInFolder (boost::bind (&FileItems::push_back, retval.get (), _1), folder, offset, limit);
+ FileItemsPtr retval = make_shared<FileItems>();
+ LookupFilesInFolder(boost::bind(&FileItems::push_back, retval.get(), _1), folder, offset, limit);
return retval;
}
diff --git a/src/file-state.hpp b/src/file-state.hpp
index 1eff885..e074794 100644
--- a/src/file-state.hpp
+++ b/src/file-state.hpp
@@ -27,35 +27,35 @@
#include "file-item.pb.hpp"
#include "hash-helper.hpp"
-#include <boost/tuple/tuple.hpp>
#include <boost/exception/all.hpp>
+#include <boost/tuple/tuple.hpp>
#include <list>
typedef std::list<FileItem> FileItems;
-typedef boost::shared_ptr<FileItem> FileItemPtr;
+typedef boost::shared_ptr<FileItem> FileItemPtr;
typedef boost::shared_ptr<FileItems> FileItemsPtr;
class FileState : public DbHelper
{
public:
- FileState (const boost::filesystem::path &path, bool cow = false);
- ~FileState ();
+ FileState(const boost::filesystem::path& path);
+ ~FileState();
/**
* @brief Update or add a file
*/
void
- UpdateFile (const std::string &filename, sqlite3_int64 version,
- const Hash &hash, const Ndnx::NdnxCharbuf &device_name, sqlite3_int64 seqno,
- time_t atime, time_t mtime, time_t ctime, int mode, int seg_num);
+ UpdateFile(const std::string& filename, sqlite3_int64 version, const Hash& hash,
+ const Ccnx::CcnxCharbuf& device_name, sqlite3_int64 seqno, time_t atime, time_t mtime,
+ time_t ctime, int mode, int seg_num);
/**
* @brief Delete file
*/
void
- DeleteFile (const std::string &filename);
+ DeleteFile(const std::string& filename);
/**
* @brief Set "complete" flag
@@ -63,49 +63,53 @@
* The call will do nothing if FileState does not have a record for the file (e.g., file got subsequently deleted)
*/
void
- SetFileComplete (const std::string &filename);
+ SetFileComplete(const std::string& filename);
/**
* @brief Lookup file state using file name
*/
FileItemPtr
- LookupFile (const std::string &filename) ;
+ LookupFile(const std::string& filename);
/**
* @brief Lookup file state using content hash (multiple items may be returned)
*/
FileItemsPtr
- LookupFilesForHash (const Hash &hash);
+ LookupFilesForHash(const Hash& hash);
/**
* @brief Lookup all files in the specified folder and call visitor(file) for each file
*/
void
- LookupFilesInFolder (const boost::function<void (const FileItem&)> &visitor, const std::string &folder, int offset=0, int limit=-1);
+ LookupFilesInFolder(const boost::function<void(const FileItem&)>& visitor,
+ const std::string& folder, int offset = 0, int limit = -1);
/**
* @brief Lookup all files in the specified folder (wrapper around the overloaded version)
*/
FileItemsPtr
- LookupFilesInFolder (const std::string &folder, int offset=0, int limit=-1);
+ LookupFilesInFolder(const std::string& folder, int offset = 0, int limit = -1);
/**
* @brief Recursively lookup all files in the specified folder and call visitor(file) for each file
*/
bool
- LookupFilesInFolderRecursively (const boost::function<void (const FileItem&)> &visitor, const std::string &folder, int offset=0, int limit=-1);
+ LookupFilesInFolderRecursively(const boost::function<void(const FileItem&)>& visitor,
+ const std::string& folder, int offset = 0, int limit = -1);
/**
* @brief Recursively lookup all files in the specified folder (wrapper around the overloaded version)
*/
FileItemsPtr
- LookupFilesInFolderRecursively (const std::string &folder, int offset=0, int limit=-1);
+ LookupFilesInFolderRecursively(const std::string& folder, int offset = 0, int limit = -1);
};
typedef boost::shared_ptr<FileState> FileStatePtr;
namespace Error {
-struct FileState : virtual boost::exception, virtual std::exception { };
+struct FileState : virtual boost::exception, virtual std::exception
+{
+};
}
diff --git a/src/hash-helper.cpp b/src/hash-helper.cpp
index cfd94e4..6ffdbcd 100644
--- a/src/hash-helper.cpp
+++ b/src/hash-helper.cpp
@@ -21,118 +21,123 @@
#include "hash-helper.h"
#include <boost/assert.hpp>
-#include <boost/throw_exception.hpp>
-#include <boost/make_shared.hpp>
#include <boost/lexical_cast.hpp>
-#include <openssl/evp.h>
+#include <boost/make_shared.hpp>
+#include <boost/throw_exception.hpp>
#include <fstream>
+#include <openssl/evp.h>
typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info_str;
typedef boost::error_info<struct tag_errmsg, int> errmsg_info_int;
-#include <boost/archive/iterators/transform_width.hpp>
-#include <boost/iterator/transform_iterator.hpp>
#include <boost/archive/iterators/dataflow_exception.hpp>
+#include <boost/archive/iterators/transform_width.hpp>
#include <boost/filesystem/fstream.hpp>
+#include <boost/iterator/transform_iterator.hpp>
using namespace boost;
using namespace boost::archive::iterators;
using namespace std;
namespace fs = boost::filesystem;
-template<class CharType>
+template <class CharType>
struct hex_from_4_bit
{
typedef CharType result_type;
- CharType operator () (CharType ch) const
+ CharType
+ operator()(CharType ch) const
{
- const char *lookup_table = "0123456789abcdef";
+ const char* lookup_table = "0123456789abcdef";
// cout << "New character: " << (int) ch << " (" << (char) ch << ")" << "\n";
- BOOST_ASSERT (ch < 16);
+ BOOST_ASSERT(ch < 16);
return lookup_table[static_cast<size_t>(ch)];
}
};
typedef transform_iterator<hex_from_4_bit<string::const_iterator::value_type>,
- transform_width<string::const_iterator, 4, 8, string::const_iterator::value_type> > string_from_binary;
+ transform_width<string::const_iterator, 4, 8, string::const_iterator::value_type>>
+ string_from_binary;
-template<class CharType>
+template <class CharType>
struct hex_to_4_bit
{
typedef CharType result_type;
- CharType operator () (CharType ch) const
+ CharType
+ operator()(CharType ch) const
{
- const signed char lookup_table [] = {
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
- -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
- };
+ const signed char lookup_table[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1,
+ -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1};
// cout << "New character: " << hex << (int) ch << " (" << (char) ch << ")" << "\n";
signed char value = -1;
if ((unsigned)ch < 128)
- value = lookup_table [(unsigned)ch];
+ value = lookup_table[(unsigned)ch];
if (value == -1)
- BOOST_THROW_EXCEPTION (Error::HashConversion () << errmsg_info_int ((int)ch));
+ BOOST_THROW_EXCEPTION(Error::HashConversion() << errmsg_info_int((int)ch));
return value;
}
};
-typedef transform_width<transform_iterator<hex_to_4_bit<string::const_iterator::value_type>, string::const_iterator>, 8, 4> string_to_binary;
+typedef transform_width<
+ transform_iterator<hex_to_4_bit<string::const_iterator::value_type>, string::const_iterator>,
+ 8,
+ 4>
+ string_to_binary;
-std::ostream &
-operator << (std::ostream &os, const Hash &hash)
+std::ostream&
+operator<<(std::ostream& os, const Hash& hash)
{
if (hash.m_length == 0)
return os;
- ostreambuf_iterator<char> out_it (os); // ostream iterator
+ ostreambuf_iterator<char> out_it(os); // ostream iterator
// need to encode to base64
- copy (string_from_binary (reinterpret_cast<const char*> (hash.m_buf)),
- string_from_binary (reinterpret_cast<const char*> (hash.m_buf+hash.m_length)),
- out_it);
+ copy(string_from_binary(reinterpret_cast<const char*>(hash.m_buf)),
+ string_from_binary(reinterpret_cast<const char*>(hash.m_buf + hash.m_length)),
+ out_it);
return os;
}
std::string
-Hash::shortHash () const
+Hash::shortHash() const
{
- return lexical_cast<string> (*this).substr (0, 10);
+ return lexical_cast<string>(*this).substr(0, 10);
}
unsigned char Hash::_origin = 0;
-HashPtr Hash::Origin(new Hash(&Hash::_origin, sizeof(unsigned char)));
+HashPtr
+Hash::Origin(new Hash(&Hash::_origin, sizeof(unsigned char)));
HashPtr
-Hash::FromString (const std::string &hashInTextEncoding)
+Hash::FromString(const std::string& hashInTextEncoding)
{
- HashPtr retval = make_shared<Hash> (reinterpret_cast<void*> (0), 0);
+ HashPtr retval = make_shared<Hash>(reinterpret_cast<void*>(0), 0);
- if (hashInTextEncoding.size () == 0)
- {
- return retval;
- }
+ if (hashInTextEncoding.size() == 0) {
+ return retval;
+ }
- if (hashInTextEncoding.size () > EVP_MAX_MD_SIZE * 2)
- {
- cerr << "Input hash is too long. Returning an empty hash" << endl;
- return retval;
- }
+ if (hashInTextEncoding.size() > EVP_MAX_MD_SIZE * 2) {
+ cerr << "Input hash is too long. Returning an empty hash" << endl;
+ return retval;
+ }
- retval->m_buf = new unsigned char [EVP_MAX_MD_SIZE];
+ retval->m_buf = new unsigned char[EVP_MAX_MD_SIZE];
- unsigned char *end = copy (string_to_binary (hashInTextEncoding.begin ()),
- string_to_binary (hashInTextEncoding.end ()),
+ unsigned char* end = copy(string_to_binary(hashInTextEncoding.begin()),
+ string_to_binary(hashInTextEncoding.end()),
retval->m_buf);
retval->m_length = end - retval->m_buf;
@@ -141,50 +146,47 @@
}
HashPtr
-Hash::FromFileContent (const fs::path &filename)
+Hash::FromFileContent(const fs::path& filename)
{
- HashPtr retval = make_shared<Hash> (reinterpret_cast<void*> (0), 0);
- retval->m_buf = new unsigned char [EVP_MAX_MD_SIZE];
+ HashPtr retval = make_shared<Hash>(reinterpret_cast<void*>(0), 0);
+ retval->m_buf = new unsigned char[EVP_MAX_MD_SIZE];
- EVP_MD_CTX *hash_context = EVP_MD_CTX_create ();
- EVP_DigestInit_ex (hash_context, HASH_FUNCTION (), 0);
+ EVP_MD_CTX* hash_context = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(hash_context, HASH_FUNCTION(), 0);
- fs::ifstream iff (filename, std::ios::in | std::ios::binary);
- while (iff.good ())
- {
- char buf[1024];
- iff.read (buf, 1024);
- EVP_DigestUpdate (hash_context, buf, iff.gcount ());
- }
+ fs::ifstream iff(filename, std::ios::in | std::ios::binary);
+ while (iff.good()) {
+ char buf[1024];
+ iff.read(buf, 1024);
+ EVP_DigestUpdate(hash_context, buf, iff.gcount());
+ }
- retval->m_buf = new unsigned char [EVP_MAX_MD_SIZE];
+ retval->m_buf = new unsigned char[EVP_MAX_MD_SIZE];
- EVP_DigestFinal_ex (hash_context,
- retval->m_buf, &retval->m_length);
+ EVP_DigestFinal_ex(hash_context, retval->m_buf, &retval->m_length);
- EVP_MD_CTX_destroy (hash_context);
+ EVP_MD_CTX_destroy(hash_context);
return retval;
}
HashPtr
-Hash::FromBytes (const Ndnx::Bytes &bytes)
+Hash::FromBytes(const Ccnx::Bytes& bytes)
{
- HashPtr retval = make_shared<Hash> (reinterpret_cast<void*> (0), 0);
- retval->m_buf = new unsigned char [EVP_MAX_MD_SIZE];
+ HashPtr retval = make_shared<Hash>(reinterpret_cast<void*>(0), 0);
+ retval->m_buf = new unsigned char[EVP_MAX_MD_SIZE];
- EVP_MD_CTX *hash_context = EVP_MD_CTX_create ();
- EVP_DigestInit_ex (hash_context, HASH_FUNCTION (), 0);
+ EVP_MD_CTX* hash_context = EVP_MD_CTX_create();
+ EVP_DigestInit_ex(hash_context, HASH_FUNCTION(), 0);
// not sure whether it's bad to do so if bytes.size is huge
EVP_DigestUpdate(hash_context, Ndnx::head(bytes), bytes.size());
- retval->m_buf = new unsigned char [EVP_MAX_MD_SIZE];
+ retval->m_buf = new unsigned char[EVP_MAX_MD_SIZE];
- EVP_DigestFinal_ex (hash_context,
- retval->m_buf, &retval->m_length);
+ EVP_DigestFinal_ex(hash_context, retval->m_buf, &retval->m_length);
- EVP_MD_CTX_destroy (hash_context);
+ EVP_MD_CTX_destroy(hash_context);
return retval;
}
diff --git a/src/hash-helper.hpp b/src/hash-helper.hpp
index 9376871..7346e23 100644
--- a/src/hash-helper.hpp
+++ b/src/hash-helper.hpp
@@ -21,12 +21,12 @@
#ifndef HASH_HELPER_H
#define HASH_HELPER_H
-#include <string.h>
-#include <iostream>
-#include <boost/shared_ptr.hpp>
+#include "ccnx-common.hpp"
#include <boost/exception/all.hpp>
#include <boost/filesystem.hpp>
-#include "ccnx-common.hpp"
+#include <boost/shared_ptr.hpp>
+#include <iostream>
+#include <string.h>
// Other options: VP_md2, EVP_md5, EVP_sha, EVP_sha1, EVP_sha256, EVP_dss, EVP_dss1, EVP_mdc2, EVP_ripemd160
#define HASH_FUNCTION EVP_sha256
@@ -40,79 +40,76 @@
static unsigned char _origin;
static HashPtr Origin;
- Hash ()
+ Hash()
: m_buf(0)
, m_length(0)
{
}
- Hash (const void *buf, unsigned int length)
- : m_length (length)
+ Hash(const void* buf, unsigned int length)
+ : m_length(length)
{
- if (m_length != 0)
- {
- m_buf = new unsigned char [length];
- memcpy (m_buf, buf, length);
- }
+ if (m_length != 0) {
+ m_buf = new unsigned char[length];
+ memcpy(m_buf, buf, length);
+ }
}
- Hash (const Hash &otherHash)
- : m_length (otherHash.m_length)
+ Hash(const Hash& otherHash)
+ : m_length(otherHash.m_length)
{
- if (m_length != 0)
- {
- m_buf = new unsigned char [m_length];
- memcpy (m_buf, otherHash.m_buf, otherHash.m_length);
- }
+ if (m_length != 0) {
+ m_buf = new unsigned char[m_length];
+ memcpy(m_buf, otherHash.m_buf, otherHash.m_length);
+ }
}
static HashPtr
- FromString (const std::string &hashInTextEncoding);
+ FromString(const std::string& hashInTextEncoding);
static HashPtr
- FromFileContent (const boost::filesystem::path &fileName);
+ FromFileContent(const boost::filesystem::path& fileName);
static HashPtr
- FromBytes (const Ndnx::Bytes &bytes);
+ FromBytes(const Ccnx::Bytes& bytes);
- ~Hash ()
+ ~Hash()
{
if (m_length != 0)
- delete [] m_buf;
+ delete[] m_buf;
}
- Hash &
- operator = (const Hash &otherHash)
+ Hash&
+ operator=(const Hash& otherHash)
{
if (m_length != 0)
- delete [] m_buf;
+ delete[] m_buf;
m_length = otherHash.m_length;
- if (m_length != 0)
- {
- m_buf = new unsigned char [m_length];
- memcpy (m_buf, otherHash.m_buf, otherHash.m_length);
- }
+ if (m_length != 0) {
+ m_buf = new unsigned char[m_length];
+ memcpy(m_buf, otherHash.m_buf, otherHash.m_length);
+ }
return *this;
}
bool
- IsZero () const
+ IsZero() const
{
- return m_length == 0 ||
- (m_length == 1 && m_buf[0] == 0);
+ return m_length == 0 || (m_length == 1 && m_buf[0] == 0);
}
bool
- operator == (const Hash &otherHash) const
+ operator==(const Hash& otherHash) const
{
if (m_length != otherHash.m_length)
return false;
- return memcmp (m_buf, otherHash.m_buf, m_length) == 0;
+ return memcmp(m_buf, otherHash.m_buf, m_length) == 0;
}
- bool operator < (const Hash &otherHash) const
+ bool
+ operator<(const Hash& otherHash) const
{
if (m_length < otherHash.m_length)
return true;
@@ -120,49 +117,50 @@
if (m_length > otherHash.m_length)
return false;
- for (unsigned int i = 0; i < m_length; i++)
- {
- if (m_buf [i] < otherHash.m_buf [i])
- return true;
+ for (unsigned int i = 0; i < m_length; i++) {
+ if (m_buf[i] < otherHash.m_buf[i])
+ return true;
- if (m_buf [i] > otherHash.m_buf [i])
- return false;
+ if (m_buf[i] > otherHash.m_buf[i])
+ return false;
- // if equal, continue
- }
+ // if equal, continue
+ }
return false;
}
- const void *
- GetHash () const
+ const void*
+ GetHash() const
{
return m_buf;
}
unsigned int
- GetHashBytes () const
+ GetHashBytes() const
{
return m_length;
}
std::string
- shortHash () const;
+ shortHash() const;
private:
- unsigned char *m_buf;
+ unsigned char* m_buf;
unsigned int m_length;
- friend std::ostream &
- operator << (std::ostream &os, const Hash &digest);
+ friend std::ostream&
+ operator<<(std::ostream& os, const Hash& digest);
};
namespace Error {
-struct HashConversion : virtual boost::exception, virtual std::exception { };
+struct HashConversion : virtual boost::exception, virtual std::exception
+{
+};
}
-std::ostream &
-operator << (std::ostream &os, const Hash &digest);
+std::ostream&
+operator<<(std::ostream& os, const Hash& digest);
#endif // HASH_STRING_CONVERTER_H
diff --git a/src/logging.cpp b/src/logging.cpp
index f381a7a..b92f83a 100644
--- a/src/logging.cpp
+++ b/src/logging.cpp
@@ -22,36 +22,36 @@
#ifdef HAVE_LOG4CXX
-#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/consoleappender.h>
-#include <log4cxx/patternlayout.h>
-#include <log4cxx/level.h>
-#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/defaultconfigurator.h>
#include <log4cxx/helpers/exception.h>
+#include <log4cxx/level.h>
+#include <log4cxx/logger.h>
+#include <log4cxx/patternlayout.h>
+#include <log4cxx/propertyconfigurator.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
#include <unistd.h>
void
-INIT_LOGGERS ()
+INIT_LOGGERS()
{
static bool configured = false;
- if (configured) return;
+ if (configured)
+ return;
- if (access ("log4cxx.properties", R_OK)==0)
- PropertyConfigurator::configureAndWatch ("log4cxx.properties");
- else
- {
- PatternLayoutPtr layout (new PatternLayout ("%d{HH:mm:ss} %p %c{1} - %m%n"));
- ConsoleAppenderPtr appender (new ConsoleAppender (layout));
+ if (access("log4cxx.properties", R_OK) == 0)
+ PropertyConfigurator::configureAndWatch("log4cxx.properties");
+ else {
+ PatternLayoutPtr layout(new PatternLayout("%d{HH:mm:ss} %p %c{1} - %m%n"));
+ ConsoleAppenderPtr appender(new ConsoleAppender(layout));
- BasicConfigurator::configure( appender );
- Logger::getRootLogger()->setLevel (log4cxx::Level::getInfo ());
- }
+ BasicConfigurator::configure(appender);
+ Logger::getRootLogger()->setLevel(log4cxx::Level::getInfo());
+ }
configured = true;
}
diff --git a/src/logging.hpp b/src/logging.hpp
index 68a8762..211601f 100644
--- a/src/logging.hpp
+++ b/src/logging.hpp
@@ -27,38 +27,36 @@
#include <log4cxx/logger.h>
-#define MEMBER_LOGGER \
- static log4cxx::LoggerPtr staticModuleLogger;
+#define MEMBER_LOGGER static log4cxx::LoggerPtr staticModuleLogger;
-#define INIT_MEMBER_LOGGER(className,name) \
- log4cxx::LoggerPtr className::staticModuleLogger = log4cxx::Logger::getLogger (name);
+#define INIT_MEMBER_LOGGER(className, name) \
+ log4cxx::LoggerPtr className::staticModuleLogger = log4cxx::Logger::getLogger(name);
#define INIT_LOGGER(name) \
- static log4cxx::LoggerPtr staticModuleLogger = log4cxx::Logger::getLogger (name);
+ static log4cxx::LoggerPtr staticModuleLogger = log4cxx::Logger::getLogger(name);
-#define _LOG_DEBUG(x) \
- LOG4CXX_DEBUG(staticModuleLogger, x);
+#define _LOG_DEBUG(x) LOG4CXX_DEBUG(staticModuleLogger, x);
-#define _LOG_TRACE(x) \
- LOG4CXX_TRACE(staticModuleLogger, x);
+#define _LOG_TRACE(x) LOG4CXX_TRACE(staticModuleLogger, x);
-#define _LOG_FUNCTION(x) \
- LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "(" << x << ")");
+#define _LOG_FUNCTION(x) LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "(" << x << ")");
-#define _LOG_FUNCTION_NOARGS \
- LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "()");
+#define _LOG_FUNCTION_NOARGS LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "()");
-#define _LOG_ERROR(x) \
- LOG4CXX_ERROR(staticModuleLogger, x);
+#define _LOG_ERROR(x) LOG4CXX_ERROR(staticModuleLogger, x);
-#define _LOG_ERROR_COND(cond,x) \
- if (cond) { _LOG_ERROR(x) }
+#define _LOG_ERROR_COND(cond, x) \
+ if (cond) { \
+ _LOG_ERROR(x) \
+ }
-#define _LOG_DEBUG_COND(cond,x) \
- if (cond) { _LOG_DEBUG(x) }
+#define _LOG_DEBUG_COND(cond, x) \
+ if (cond) { \
+ _LOG_DEBUG(x) \
+ }
void
-INIT_LOGGERS ();
+INIT_LOGGERS();
#else // else HAVE_LOG4CXX
@@ -68,20 +66,21 @@
#define _LOG_TRACE(x)
#define INIT_LOGGERS(x)
#define _LOG_ERROR(x)
-#define _LOG_ERROR_COND(cond,x)
-#define _LOG_DEBUG_COND(cond,x)
+#define _LOG_ERROR_COND(cond, x)
+#define _LOG_DEBUG_COND(cond, x)
#define MEMBER_LOGGER
-#define INIT_MEMBER_LOGGER(className,name)
+#define INIT_MEMBER_LOGGER(className, name)
#ifdef _DEBUG
-#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
+#include <boost/thread/thread.hpp>
#include <iostream>
-#define _LOG_DEBUG(x) \
- std::clog << boost::get_system_time () << " " << boost::this_thread::get_id () << " " << x << std::endl;
+#define _LOG_DEBUG(x) \
+ std::clog << boost::get_system_time() << " " << boost::this_thread::get_id() << " " << x \
+ << std::endl;
#else
#define _LOG_DEBUG(x)
diff --git a/src/object-db.cpp b/src/object-db.cpp
index 3b1a0f2..fd4223e 100644
--- a/src/object-db.cpp
+++ b/src/object-db.cpp
@@ -19,13 +19,13 @@
*/
#include "object-db.h"
-#include <iostream>
-#include <boost/make_shared.hpp>
#include "db-helper.h"
-#include <sys/stat.h>
#include "logging.h"
+#include <boost/make_shared.hpp>
+#include <iostream>
+#include <sys/stat.h>
-INIT_LOGGER ("Object.Db");
+INIT_LOGGER("Object.Db");
using namespace std;
using namespace Ndnx;
@@ -44,133 +44,132 @@
CREATE INDEX device ON File(device_name); \n\
";
-ObjectDb::ObjectDb (const fs::path &folder, const std::string &hash)
- : m_lastUsed (time(NULL))
+ObjectDb::ObjectDb(const fs::path& folder, const std::string& hash)
+ : m_lastUsed(time(NULL))
{
- fs::path actualFolder = folder / "objects" / hash.substr (0, 2);
- fs::create_directories (actualFolder);
+ fs::path actualFolder = folder / "objects" / hash.substr(0, 2);
+ fs::create_directories(actualFolder);
- _LOG_DEBUG ("Open " << (actualFolder / hash.substr (2, hash.size () - 2)));
+ _LOG_DEBUG("Open " << (actualFolder / hash.substr(2, hash.size() - 2)));
- int res = sqlite3_open((actualFolder / hash.substr (2, hash.size () - 2)).c_str (), &m_db);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Cannot open/create dabatabase: [" +
- (actualFolder / hash.substr (2, hash.size () - 2)).string () + "]"));
- }
+ int res = sqlite3_open((actualFolder / hash.substr(2, hash.size() - 2)).c_str(), &m_db);
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str(
+ "Cannot open/create dabatabase: [" +
+ (actualFolder / hash.substr(2, hash.size() - 2)).string() + "]"));
+ }
// Alex: determine if tables initialized. if not, initialize... not sure what is the best way to go...
// for now, just attempt to create everything
- char *errmsg = 0;
- res = sqlite3_exec (m_db, INIT_DATABASE.c_str (), NULL, NULL, &errmsg);
- if (res != SQLITE_OK && errmsg != 0)
- {
- // _LOG_TRACE ("Init \"error\": " << errmsg);
- sqlite3_free (errmsg);
- }
+ char* errmsg = 0;
+ res = sqlite3_exec(m_db, INIT_DATABASE.c_str(), NULL, NULL, &errmsg);
+ if (res != SQLITE_OK && errmsg != 0) {
+ // _LOG_TRACE ("Init \"error\": " << errmsg);
+ sqlite3_free(errmsg);
+ }
// _LOG_DEBUG ("open db");
- willStartSave ();
+ willStartSave();
}
bool
-ObjectDb::DoesExist (const boost::filesystem::path &folder, const Ndnx::Name &deviceName, const std::string &hash)
+ObjectDb::DoesExist(const boost::filesystem::path& folder, const Ccnx::Name& deviceName,
+ const std::string& hash)
{
- fs::path actualFolder = folder / "objects" / hash.substr (0, 2);
+ fs::path actualFolder = folder / "objects" / hash.substr(0, 2);
bool retval = false;
- sqlite3 *db;
- int res = sqlite3_open((actualFolder / hash.substr (2, hash.size () - 2)).c_str (), &db);
- if (res == SQLITE_OK)
- {
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (db, "SELECT count(*), count(nullif(content_object,0)) FROM File WHERE device_name=?", -1, &stmt, 0);
+ sqlite3* db;
+ int res = sqlite3_open((actualFolder / hash.substr(2, hash.size() - 2)).c_str(), &db);
+ if (res == SQLITE_OK) {
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(db,
+ "SELECT count(*), count(nullif(content_object,0)) FROM File WHERE device_name=?",
+ -1, &stmt, 0);
- NdnxCharbufPtr buf = deviceName.toNdnxCharbuf ();
- sqlite3_bind_blob (stmt, 1, buf->buf (), buf->length (), SQLITE_TRANSIENT);
+ CcnxCharbufPtr buf = deviceName.toCcnxCharbuf();
+ sqlite3_bind_blob(stmt, 1, buf->buf(), buf->length(), SQLITE_TRANSIENT);
- int res = sqlite3_step (stmt);
- if (res == SQLITE_ROW)
- {
- int countAll = sqlite3_column_int (stmt, 0);
- int countNonNull = sqlite3_column_int (stmt, 1);
+ int res = sqlite3_step(stmt);
+ if (res == SQLITE_ROW) {
+ int countAll = sqlite3_column_int(stmt, 0);
+ int countNonNull = sqlite3_column_int(stmt, 1);
- _LOG_TRACE ("Total segments: " << countAll << ", non-empty segments: " << countNonNull);
+ _LOG_TRACE("Total segments: " << countAll << ", non-empty segments: " << countNonNull);
- if (countAll > 0 && countAll==countNonNull)
- {
- retval = true;
- }
- }
-
- sqlite3_finalize (stmt);
+ if (countAll > 0 && countAll == countNonNull) {
+ retval = true;
+ }
}
- sqlite3_close (db);
+ sqlite3_finalize(stmt);
+ }
+
+ sqlite3_close(db);
return retval;
}
-ObjectDb::~ObjectDb ()
+ObjectDb::~ObjectDb()
{
- didStopSave ();
+ didStopSave();
// _LOG_DEBUG ("close db");
- int res = sqlite3_close (m_db);
- if (res != SQLITE_OK)
- {
- // complain
- }
+ int res = sqlite3_close(m_db);
+ if (res != SQLITE_OK) {
+ // complain
+ }
}
void
-ObjectDb::saveContentObject (const Ndnx::Name &deviceName, sqlite3_int64 segment, const Ndnx::Bytes &data)
+ObjectDb::saveContentObject(const Ccnx::Name& deviceName, sqlite3_int64 segment,
+ const Ccnx::Bytes& data)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "INSERT INTO File "
- "(device_name, segment, content_object) "
- "VALUES (?, ?, ?)", -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db, "INSERT INTO File "
+ "(device_name, segment, content_object) "
+ "VALUES (?, ?, ?)",
+ -1, &stmt, 0);
//_LOG_DEBUG ("Saving content object for [" << deviceName << ", seqno: " << segment << ", size: " << data.size () << "]");
- NdnxCharbufPtr buf = deviceName.toNdnxCharbuf ();
- sqlite3_bind_blob (stmt, 1, buf->buf (), buf->length (), SQLITE_STATIC);
- sqlite3_bind_int64 (stmt, 2, segment);
- sqlite3_bind_blob (stmt, 3, &data[0], data.size (), SQLITE_STATIC);
+ CcnxCharbufPtr buf = deviceName.toCcnxCharbuf();
+ sqlite3_bind_blob(stmt, 1, buf->buf(), buf->length(), SQLITE_STATIC);
+ sqlite3_bind_int64(stmt, 2, segment);
+ sqlite3_bind_blob(stmt, 3, &data[0], data.size(), SQLITE_STATIC);
- sqlite3_step (stmt);
+ sqlite3_step(stmt);
//_LOG_DEBUG ("After saving object: " << sqlite3_errmsg (m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
// update last used time
m_lastUsed = time(NULL);
}
-Ndnx::BytesPtr
-ObjectDb::fetchSegment (const Ndnx::Name &deviceName, sqlite3_int64 segment)
+Ccnx::BytesPtr
+ObjectDb::fetchSegment(const Ccnx::Name& deviceName, sqlite3_int64 segment)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "SELECT content_object FROM File WHERE device_name=? AND segment=?", -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db, "SELECT content_object FROM File WHERE device_name=? AND segment=?", -1,
+ &stmt, 0);
- NdnxCharbufPtr buf = deviceName.toNdnxCharbuf ();
- sqlite3_bind_blob (stmt, 1, buf->buf (), buf->length (), SQLITE_TRANSIENT);
- sqlite3_bind_int64 (stmt, 2, segment);
+ CcnxCharbufPtr buf = deviceName.toCcnxCharbuf();
+ sqlite3_bind_blob(stmt, 1, buf->buf(), buf->length(), SQLITE_TRANSIENT);
+ sqlite3_bind_int64(stmt, 2, segment);
BytesPtr ret;
- int res = sqlite3_step (stmt);
- if (res == SQLITE_ROW)
- {
- const unsigned char *buf = reinterpret_cast<const unsigned char*> (sqlite3_column_blob (stmt, 0));
- int bufBytes = sqlite3_column_bytes (stmt, 0);
+ int res = sqlite3_step(stmt);
+ if (res == SQLITE_ROW) {
+ const unsigned char* buf = reinterpret_cast<const unsigned char*>(sqlite3_column_blob(stmt, 0));
+ int bufBytes = sqlite3_column_bytes(stmt, 0);
- ret = make_shared<Bytes> (buf, buf+bufBytes);
- }
+ ret = make_shared<Bytes>(buf, buf + bufBytes);
+ }
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
// update last used time
m_lastUsed = time(NULL);
@@ -202,15 +201,15 @@
// }
void
-ObjectDb::willStartSave ()
+ObjectDb::willStartSave()
{
- sqlite3_exec (m_db, "BEGIN TRANSACTION;", 0,0,0);
+ sqlite3_exec(m_db, "BEGIN TRANSACTION;", 0, 0, 0);
// _LOG_DEBUG ("Open transaction: " << sqlite3_errmsg (m_db));
}
void
-ObjectDb::didStopSave ()
+ObjectDb::didStopSave()
{
- sqlite3_exec (m_db, "END TRANSACTION;", 0,0,0);
+ sqlite3_exec(m_db, "END TRANSACTION;", 0, 0, 0);
// _LOG_DEBUG ("Close transaction: " << sqlite3_errmsg (m_db));
}
diff --git a/src/object-db.hpp b/src/object-db.hpp
index c2c2282..3e6f9cd 100644
--- a/src/object-db.hpp
+++ b/src/object-db.hpp
@@ -21,27 +21,27 @@
#ifndef OBJECT_DB_H
#define OBJECT_DB_H
-#include <string>
-#include <sqlite3.h>
-#include <ndnx-common.h>
-#include <ndnx-name.h>
#include <boost/filesystem.hpp>
#include <boost/shared_ptr.hpp>
+#include <ccnx-common.h>
+#include <ccnx-name.h>
#include <ctime>
+#include <sqlite3.h>
+#include <string>
#include <vector>
class ObjectDb
{
public:
// database will be create in <folder>/<first-pair-of-hash-bytes>/<rest-of-hash>
- ObjectDb (const boost::filesystem::path &folder, const std::string &hash);
- ~ObjectDb ();
+ ObjectDb(const boost::filesystem::path& folder, const std::string& hash);
+ ~ObjectDb();
void
- saveContentObject (const Ndnx::Name &deviceName, sqlite3_int64 segment, const Ndnx::Bytes &data);
+ saveContentObject(const Ccnx::Name& deviceName, sqlite3_int64 segment, const Ccnx::Bytes& data);
- Ndnx::BytesPtr
- fetchSegment (const Ndnx::Name &deviceName, sqlite3_int64 segment);
+ Ccnx::BytesPtr
+ fetchSegment(const Ccnx::Name& deviceName, sqlite3_int64 segment);
// sqlite3_int64
// getNumberOfSegments (const Ndnx::Name &deviceName);
@@ -50,17 +50,18 @@
secondsSinceLastUse();
static bool
- DoesExist (const boost::filesystem::path &folder, const Ndnx::Name &deviceName, const std::string &hash);
+ DoesExist(const boost::filesystem::path& folder, const Ccnx::Name& deviceName,
+ const std::string& hash);
private:
void
- willStartSave ();
+ willStartSave();
void
- didStopSave ();
+ didStopSave();
private:
- sqlite3 *m_db;
+ sqlite3* m_db;
time_t m_lastUsed;
};
diff --git a/src/object-manager.cpp b/src/object-manager.cpp
index 610a2fb..ba3e5f2 100644
--- a/src/object-manager.cpp
+++ b/src/object-manager.cpp
@@ -19,20 +19,20 @@
*/
#include "object-manager.hpp"
-#include "ccnx-name.hpp"
#include "ccnx-common.hpp"
+#include "ccnx-name.hpp"
#include "ccnx-pco.hpp"
-#include "object-db.hpp"
#include "logging.hpp"
+#include "object-db.hpp"
#include <sys/stat.h>
-#include <fstream>
+#include <boost/filesystem/fstream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/throw_exception.hpp>
-#include <boost/filesystem/fstream.hpp>
+#include <fstream>
-INIT_LOGGER ("Object.Manager");
+INIT_LOGGER("Object.Manager");
using namespace Ndnx;
using namespace boost;
@@ -41,94 +41,93 @@
const int MAX_FILE_SEGMENT_SIZE = 1024;
-ObjectManager::ObjectManager (Ndnx::NdnxWrapperPtr ndnx, const fs::path &folder, const std::string &appName)
- : m_ndnx (ndnx)
- , m_folder (folder / ".chronoshare")
- , m_appName (appName)
+ObjectManager::ObjectManager(Ccnx::CcnxWrapperPtr ccnx, const fs::path& folder,
+ const std::string& appName)
+ : m_ccnx(ccnx)
+ , m_folder(folder / ".chronoshare")
+ , m_appName(appName)
{
- fs::create_directories (m_folder);
+ fs::create_directories(m_folder);
}
-ObjectManager::~ObjectManager ()
+ObjectManager::~ObjectManager()
{
}
// /<devicename>/<appname>/file/<hash>/<segment>
boost::tuple<HashPtr /*object-db name*/, size_t /* number of segments*/>
-ObjectManager::localFileToObjects (const fs::path &file, const Ndnx::Name &deviceName)
+ObjectManager::localFileToObjects(const fs::path& file, const Ccnx::Name& deviceName)
{
- HashPtr fileHash = Hash::FromFileContent (file);
- ObjectDb fileDb (m_folder, lexical_cast<string> (*fileHash));
+ HashPtr fileHash = Hash::FromFileContent(file);
+ ObjectDb fileDb(m_folder, lexical_cast<string>(*fileHash));
- fs::ifstream iff (file, std::ios::in | std::ios::binary);
+ fs::ifstream iff(file, std::ios::in | std::ios::binary);
sqlite3_int64 segment = 0;
- while (iff.good () && !iff.eof ())
- {
- char buf[MAX_FILE_SEGMENT_SIZE];
- iff.read (buf, MAX_FILE_SEGMENT_SIZE);
- if (iff.gcount () == 0)
- {
- // stupid streams...
- break;
- }
-
- Name name = Name ("/")(deviceName)(m_appName)("file")(fileHash->GetHash (), fileHash->GetHashBytes ())(segment);
-
- // cout << *fileHash << endl;
- // cout << name << endl;
- //_LOG_DEBUG ("Read " << iff.gcount () << " from " << file << " for segment " << segment);
-
- Bytes data = m_ndnx->createContentObject (name, buf, iff.gcount ());
- fileDb.saveContentObject (deviceName, segment, data);
-
- segment ++;
+ while (iff.good() && !iff.eof()) {
+ char buf[MAX_FILE_SEGMENT_SIZE];
+ iff.read(buf, MAX_FILE_SEGMENT_SIZE);
+ if (iff.gcount() == 0) {
+ // stupid streams...
+ break;
}
+
+ Name name = Name("/")(deviceName)(m_appName)("file")(fileHash->GetHash(),
+ fileHash->GetHashBytes())(segment);
+
+ // cout << *fileHash << endl;
+ // cout << name << endl;
+ //_LOG_DEBUG ("Read " << iff.gcount () << " from " << file << " for segment " << segment);
+
+ Bytes data = m_ccnx->createContentObject(name, buf, iff.gcount());
+ fileDb.saveContentObject(deviceName, segment, data);
+
+ segment++;
+ }
if (segment == 0) // handle empty files
- {
- Name name = Name ("/")(m_appName)("file")(fileHash->GetHash (), fileHash->GetHashBytes ())(deviceName)(0);
- Bytes data = m_ndnx->createContentObject (name, 0, 0);
- fileDb.saveContentObject (deviceName, 0, data);
+ {
+ Name name =
+ Name("/")(m_appName)("file")(fileHash->GetHash(), fileHash->GetHashBytes())(deviceName)(0);
+ Bytes data = m_ccnx->createContentObject(name, 0, 0);
+ fileDb.saveContentObject(deviceName, 0, data);
- segment ++;
- }
+ segment++;
+ }
- return make_tuple (fileHash, segment);
+ return make_tuple(fileHash, segment);
}
bool
-ObjectManager::objectsToLocalFile (/*in*/const Ndnx::Name &deviceName, /*in*/const Hash &fileHash, /*out*/ const fs::path &file)
+ObjectManager::objectsToLocalFile(/*in*/ const Ccnx::Name& deviceName, /*in*/ const Hash& fileHash,
+ /*out*/ const fs::path& file)
{
- string hashStr = lexical_cast<string> (fileHash);
- if (!ObjectDb::DoesExist (m_folder, deviceName, hashStr))
- {
- _LOG_ERROR ("ObjectDb for [" << m_folder << ", " << deviceName << ", " << hashStr << "] does not exist or not all segments are available");
- return false;
- }
+ string hashStr = lexical_cast<string>(fileHash);
+ if (!ObjectDb::DoesExist(m_folder, deviceName, hashStr)) {
+ _LOG_ERROR("ObjectDb for [" << m_folder << ", " << deviceName << ", " << hashStr
+ << "] does not exist or not all segments are available");
+ return false;
+ }
- if (!exists (file.parent_path ()))
- {
- create_directories (file.parent_path ());
- }
+ if (!exists(file.parent_path())) {
+ create_directories(file.parent_path());
+ }
- fs::ofstream off (file, std::ios::out | std::ios::binary);
- ObjectDb fileDb (m_folder, hashStr);
+ fs::ofstream off(file, std::ios::out | std::ios::binary);
+ ObjectDb fileDb(m_folder, hashStr);
sqlite3_int64 segment = 0;
- BytesPtr bytes = fileDb.fetchSegment (deviceName, 0);
- while (bytes)
- {
- ParsedContentObject obj (*bytes);
- BytesPtr data = obj.contentPtr ();
+ BytesPtr bytes = fileDb.fetchSegment(deviceName, 0);
+ while (bytes) {
+ ParsedContentObject obj(*bytes);
+ BytesPtr data = obj.contentPtr();
- if (data)
- {
- off.write (reinterpret_cast<const char*> (head(*data)), data->size());
- }
-
- segment ++;
- bytes = fileDb.fetchSegment (deviceName, segment);
+ if (data) {
+ off.write(reinterpret_cast<const char*>(head(*data)), data->size());
}
+ segment++;
+ bytes = fileDb.fetchSegment(deviceName, segment);
+ }
+
// permission and timestamp should be assigned somewhere else (ObjectManager has no idea about that)
return true;
diff --git a/src/object-manager.hpp b/src/object-manager.hpp
index f66e979..51a5880 100644
--- a/src/object-manager.hpp
+++ b/src/object-manager.hpp
@@ -21,19 +21,20 @@
#ifndef OBJECT_MANAGER_H
#define OBJECT_MANAGER_H
-#include <string>
-#include <ndnx-wrapper.h>
-#include <hash-helper.h>
#include <boost/filesystem.hpp>
#include <boost/tuple/tuple.hpp>
+#include <ccnx-wrapper.h>
+#include <hash-helper.h>
+#include <string>
// everything related to managing object files
class ObjectManager
{
public:
- ObjectManager (Ndnx::NdnxWrapperPtr ndnx, const boost::filesystem::path &folder, const std::string &appName);
- virtual ~ObjectManager ();
+ ObjectManager(Ccnx::CcnxWrapperPtr ccnx, const boost::filesystem::path& folder,
+ const std::string& appName);
+ virtual ~ObjectManager();
/**
* @brief Creates and saves local file in a local database file
@@ -41,10 +42,11 @@
* Format: /<appname>/file/<hash>/<devicename>/<segment>
*/
boost::tuple<HashPtr /*object-db name*/, size_t /* number of segments*/>
- localFileToObjects (const boost::filesystem::path &file, const Ndnx::Name &deviceName);
+ localFileToObjects(const boost::filesystem::path& file, const Ccnx::Name& deviceName);
bool
- objectsToLocalFile (/*in*/const Ndnx::Name &deviceName, /*in*/const Hash &hash, /*out*/ const boost::filesystem::path &file);
+ objectsToLocalFile(/*in*/ const Ccnx::Name& deviceName, /*in*/ const Hash& hash,
+ /*out*/ const boost::filesystem::path& file);
private:
Ndnx::NdnxWrapperPtr m_ndnx;
@@ -55,7 +57,9 @@
typedef boost::shared_ptr<ObjectManager> ObjectManagerPtr;
namespace Error {
-struct ObjectManager : virtual boost::exception, virtual std::exception { };
+struct ObjectManager : virtual boost::exception, virtual std::exception
+{
+};
}
#endif // OBJECT_MANAGER_H
diff --git a/src/state-server.cpp b/src/state-server.cpp
index 7e002dd..b791e16 100644
--- a/src/state-server.cpp
+++ b/src/state-server.cpp
@@ -20,87 +20,89 @@
#include "state-server.h"
#include "logging.h"
-#include <boost/make_shared.hpp>
-#include <utility>
-#include "task.h"
#include "periodic-task.h"
#include "simple-interval-generator.h"
-#include <boost/lexical_cast.hpp>
+#include "task.h"
#include <boost/date_time/posix_time/posix_time.hpp>
+#include <boost/lexical_cast.hpp>
+#include <boost/make_shared.hpp>
+#include <utility>
-INIT_LOGGER ("StateServer");
+INIT_LOGGER("StateServer");
using namespace Ndnx;
using namespace std;
using namespace boost;
-StateServer::StateServer(NdnxWrapperPtr ndnx, ActionLogPtr actionLog,
- const boost::filesystem::path &rootDir,
- const Ndnx::Name &userName, const std::string &sharedFolderName,
- const std::string &appName,
- ObjectManager &objectManager,
- int freshness/* = -1*/)
- : m_ndnx(ndnx)
+StateServer::StateServer(CcnxWrapperPtr ccnx, ActionLogPtr actionLog,
+ const boost::filesystem::path& rootDir, const Ccnx::Name& userName,
+ const std::string& sharedFolderName, const std::string& appName,
+ ObjectManager& objectManager, int freshness /* = -1*/)
+ : m_ccnx(ccnx)
, m_actionLog(actionLog)
- , m_objectManager (objectManager)
+ , m_objectManager(objectManager)
, m_rootDir(rootDir)
, m_freshness(freshness)
- , m_executor (1)
- , m_userName (userName)
- , m_sharedFolderName (sharedFolderName)
- , m_appName (appName)
+ , m_executor(1)
+ , m_userName(userName)
+ , m_sharedFolderName(sharedFolderName)
+ , m_appName(appName)
{
// may be later /localhost should be replaced with /%C1.M.S.localhost
// <PREFIX_INFO> = /localhost/<user's-device-name>/"chronoshare"/"info"
- m_PREFIX_INFO = Name ("/localhost")(m_userName)("chronoshare")(m_sharedFolderName)("info");
+ m_PREFIX_INFO = Name("/localhost")(m_userName)("chronoshare")(m_sharedFolderName)("info");
// <PREFIX_CMD> = /localhost/<user's-device-name>/"chronoshare"/"cmd"
- m_PREFIX_CMD = Name ("/localhost")(m_userName)("chronoshare")(m_sharedFolderName)("cmd");
+ m_PREFIX_CMD = Name("/localhost")(m_userName)("chronoshare")(m_sharedFolderName)("cmd");
- m_executor.start ();
+ m_executor.start();
- registerPrefixes ();
+ registerPrefixes();
}
StateServer::~StateServer()
{
- m_executor.shutdown ();
+ m_executor.shutdown();
- deregisterPrefixes ();
+ deregisterPrefixes();
}
void
-StateServer::registerPrefixes ()
+StateServer::registerPrefixes()
{
// currently supporting limited number of command.
// will be extended to support all planned commands later
// <PREFIX_INFO>/"actions"/"all"/<segment> get list of all actions
- m_ndnx->setInterestFilter (Name (m_PREFIX_INFO)("actions")("folder"), bind(&StateServer::info_actions_folder, this, _1));
- m_ndnx->setInterestFilter (Name (m_PREFIX_INFO)("actions")("file"), bind(&StateServer::info_actions_file, this, _1));
+ m_ccnx->setInterestFilter(Name(m_PREFIX_INFO)("actions")("folder"),
+ bind(&StateServer::info_actions_folder, this, _1));
+ m_ccnx->setInterestFilter(Name(m_PREFIX_INFO)("actions")("file"),
+ bind(&StateServer::info_actions_file, this, _1));
// <PREFIX_INFO>/"filestate"/"all"/<segment>
- m_ndnx->setInterestFilter (Name (m_PREFIX_INFO)("files")("folder"), bind(&StateServer::info_files_folder, this, _1));
+ m_ccnx->setInterestFilter(Name(m_PREFIX_INFO)("files")("folder"),
+ bind(&StateServer::info_files_folder, this, _1));
// <PREFIX_CMD>/"restore"/"file"/<one-component-relative-file-name>/<version>/<file-hash>
- m_ndnx->setInterestFilter (Name (m_PREFIX_CMD)("restore")("file"), bind(&StateServer::cmd_restore_file, this, _1));
+ m_ccnx->setInterestFilter(Name(m_PREFIX_CMD)("restore")("file"),
+ bind(&StateServer::cmd_restore_file, this, _1));
}
void
-StateServer::deregisterPrefixes ()
+StateServer::deregisterPrefixes()
{
- m_ndnx->clearInterestFilter (Name (m_PREFIX_INFO)("actions")("folder"));
- m_ndnx->clearInterestFilter (Name (m_PREFIX_INFO)("actions")("file"));
- m_ndnx->clearInterestFilter (Name (m_PREFIX_INFO)("files")("folder"));
- m_ndnx->clearInterestFilter (Name (m_PREFIX_CMD) ("restore")("file"));
+ m_ccnx->clearInterestFilter(Name(m_PREFIX_INFO)("actions")("folder"));
+ m_ccnx->clearInterestFilter(Name(m_PREFIX_INFO)("actions")("file"));
+ m_ccnx->clearInterestFilter(Name(m_PREFIX_INFO)("files")("folder"));
+ m_ccnx->clearInterestFilter(Name(m_PREFIX_CMD)("restore")("file"));
}
void
-StateServer::formatActionJson (json_spirit::Array &actions,
- const Ndnx::Name &name, sqlite3_int64 seq_no, const ActionItem &action)
+StateServer::formatActionJson(json_spirit::Array& actions, const Ccnx::Name& name,
+ sqlite3_int64 seq_no, const ActionItem& action)
{
-/*
+ /*
* {
* "id": {
* "userName": "<NDN-NAME-OF-THE-USER>",
@@ -133,89 +135,84 @@
Object json;
Object id;
- id.push_back (Pair ("userName", boost::lexical_cast<string> (name)));
- id.push_back (Pair ("seqNo", static_cast<int64_t> (seq_no)));
+ id.push_back(Pair("userName", boost::lexical_cast<string>(name)));
+ id.push_back(Pair("seqNo", static_cast<int64_t>(seq_no)));
- json.push_back (Pair ("id", id));
+ json.push_back(Pair("id", id));
- json.push_back (Pair ("timestamp", to_iso_extended_string (from_time_t (action.timestamp ()))));
- json.push_back (Pair ("filename", action.filename ()));
- json.push_back (Pair ("version", action.version ()));
- json.push_back (Pair ("action", (action.action () == 0) ? "UPDATE" : "DELETE"));
+ json.push_back(Pair("timestamp", to_iso_extended_string(from_time_t(action.timestamp()))));
+ json.push_back(Pair("filename", action.filename()));
+ json.push_back(Pair("version", action.version()));
+ json.push_back(Pair("action", (action.action() == 0) ? "UPDATE" : "DELETE"));
- if (action.action () == 0)
- {
- Object update;
- update.push_back (Pair ("hash", boost::lexical_cast<string> (Hash (action.file_hash ().c_str (), action.file_hash ().size ()))));
- update.push_back (Pair ("timestamp", to_iso_extended_string (from_time_t (action.mtime ()))));
+ if (action.action() == 0) {
+ Object update;
+ update.push_back(Pair("hash", boost::lexical_cast<string>(
+ Hash(action.file_hash().c_str(), action.file_hash().size()))));
+ update.push_back(Pair("timestamp", to_iso_extended_string(from_time_t(action.mtime()))));
- ostringstream chmod;
- chmod << setbase (8) << setfill ('0') << setw (4) << action.mode ();
- update.push_back (Pair ("chmod", chmod.str ()));
+ ostringstream chmod;
+ chmod << setbase(8) << setfill('0') << setw(4) << action.mode();
+ update.push_back(Pair("chmod", chmod.str()));
- update.push_back (Pair ("segNum", action.seg_num ()));
- json.push_back (Pair ("update", update));
- }
+ update.push_back(Pair("segNum", action.seg_num()));
+ json.push_back(Pair("update", update));
+ }
- if (action.has_parent_device_name ())
- {
- Object parentId;
- Ndnx::Name parent_device_name (action.parent_device_name ().c_str (), action.parent_device_name ().size ());
- id.push_back (Pair ("userName", boost::lexical_cast<string> (parent_device_name)));
- id.push_back (Pair ("seqNo", action.parent_seq_no ()));
+ if (action.has_parent_device_name()) {
+ Object parentId;
+ Ccnx::Name parent_device_name(action.parent_device_name().c_str(),
+ action.parent_device_name().size());
+ id.push_back(Pair("userName", boost::lexical_cast<string>(parent_device_name)));
+ id.push_back(Pair("seqNo", action.parent_seq_no()));
- json.push_back (Pair ("parentId", parentId));
- }
+ json.push_back(Pair("parentId", parentId));
+ }
- actions.push_back (json);
+ actions.push_back(json);
}
void
-StateServer::info_actions_folder (const Name &interest)
+StateServer::info_actions_folder(const Name& interest)
{
- if (interest.size () - m_PREFIX_INFO.size () != 3 &&
- interest.size () - m_PREFIX_INFO.size () != 4)
- {
- _LOG_DEBUG ("Invalid interest: " << interest);
- return;
- }
+ if (interest.size() - m_PREFIX_INFO.size() != 3 && interest.size() - m_PREFIX_INFO.size() != 4) {
+ _LOG_DEBUG("Invalid interest: " << interest);
+ return;
+ }
- _LOG_DEBUG (">> info_actions_folder: " << interest);
- m_executor.execute (bind (&StateServer::info_actions_fileOrFolder_Execute, this, interest, true));
+ _LOG_DEBUG(">> info_actions_folder: " << interest);
+ m_executor.execute(bind(&StateServer::info_actions_fileOrFolder_Execute, this, interest, true));
}
void
-StateServer::info_actions_file (const Name &interest)
+StateServer::info_actions_file(const Name& interest)
{
- if (interest.size () - m_PREFIX_INFO.size () != 3 &&
- interest.size () - m_PREFIX_INFO.size () != 4)
- {
- _LOG_DEBUG ("Invalid interest: " << interest);
- return;
- }
+ if (interest.size() - m_PREFIX_INFO.size() != 3 && interest.size() - m_PREFIX_INFO.size() != 4) {
+ _LOG_DEBUG("Invalid interest: " << interest);
+ return;
+ }
- _LOG_DEBUG (">> info_actions_file: " << interest);
- m_executor.execute (bind (&StateServer::info_actions_fileOrFolder_Execute, this, interest, false));
+ _LOG_DEBUG(">> info_actions_file: " << interest);
+ m_executor.execute(bind(&StateServer::info_actions_fileOrFolder_Execute, this, interest, false));
}
void
-StateServer::info_actions_fileOrFolder_Execute (const Ndnx::Name &interest, bool isFolder/* = true*/)
+StateServer::info_actions_fileOrFolder_Execute(const Ccnx::Name& interest, bool isFolder /* = true*/)
{
// <PREFIX_INFO>/"actions"/"folder|file"/<folder|file>/<offset> get list of all actions
- try
- {
- int offset = interest.getCompFromBackAsInt (0);
+ try {
+ int offset = interest.getCompFromBackAsInt(0);
- /// @todo !!! add security checking
+ /// @todo !!! add security checking
- string fileOrFolderName;
- if (interest.size () - m_PREFIX_INFO.size () == 4)
- fileOrFolderName = interest.getCompFromBackAsString (1);
- else // == 3
- fileOrFolderName = "";
-/*
+ string fileOrFolderName;
+ if (interest.size() - m_PREFIX_INFO.size() == 4)
+ fileOrFolderName = interest.getCompFromBackAsString(1);
+ else // == 3
+ fileOrFolderName = "";
+ /*
* {
* "actions": [
* ...
@@ -226,48 +223,45 @@
* }
*/
- using namespace json_spirit;
- Object json;
+ using namespace json_spirit;
+ Object json;
- Array actions;
- bool more;
- if (isFolder)
- {
- more = m_actionLog->LookupActionsInFolderRecursively
- (boost::bind (StateServer::formatActionJson, boost::ref(actions), _1, _2, _3),
- fileOrFolderName, offset*10, 10);
- }
- else
- {
- more = m_actionLog->LookupActionsForFile
- (boost::bind (StateServer::formatActionJson, boost::ref(actions), _1, _2, _3),
- fileOrFolderName, offset*10, 10);
- }
-
- json.push_back (Pair ("actions", actions));
-
- if (more)
- {
- json.push_back (Pair ("more", lexical_cast<string> (offset + 1)));
- // Ndnx::Name more = Name (interest.getPartialName (0, interest.size () - 1))(offset + 1);
- // json.push_back (Pair ("more", lexical_cast<string> (more)));
- }
-
- ostringstream os;
- write_stream (Value (json), os, pretty_print | raw_utf8);
- m_ndnx->publishData (interest, os.str (), 1);
+ Array actions;
+ bool more;
+ if (isFolder) {
+ more =
+ m_actionLog->LookupActionsInFolderRecursively(boost::bind(StateServer::formatActionJson,
+ boost::ref(actions), _1, _2, _3),
+ fileOrFolderName, offset * 10, 10);
}
- catch (Ndnx::NameException &ne)
- {
- // ignore any unexpected interests and errors
- _LOG_ERROR (*boost::get_error_info<Ndnx::error_info_str>(ne));
+ else {
+ more = m_actionLog->LookupActionsForFile(boost::bind(StateServer::formatActionJson,
+ boost::ref(actions), _1, _2, _3),
+ fileOrFolderName, offset * 10, 10);
}
+
+ json.push_back(Pair("actions", actions));
+
+ if (more) {
+ json.push_back(Pair("more", lexical_cast<string>(offset + 1)));
+ // Ccnx::Name more = Name (interest.getPartialName (0, interest.size () - 1))(offset + 1);
+ // json.push_back (Pair ("more", lexical_cast<string> (more)));
+ }
+
+ ostringstream os;
+ write_stream(Value(json), os, pretty_print | raw_utf8);
+ m_ccnx->publishData(interest, os.str(), 1);
+ }
+ catch (Ccnx::NameException& ne) {
+ // ignore any unexpected interests and errors
+ _LOG_ERROR(*boost::get_error_info<Ccnx::error_info_str>(ne));
+ }
}
void
-StateServer::formatFilestateJson (json_spirit::Array &files, const FileItem &file)
+StateServer::formatFilestateJson(json_spirit::Array& files, const FileItem& file)
{
-/**
+ /**
* {
* "filestate": [
* {
@@ -293,66 +287,65 @@
Object json;
- json.push_back (Pair ("filename", file.filename ()));
- json.push_back (Pair ("version", file.version ()));
+ json.push_back(Pair("filename", file.filename()));
+ json.push_back(Pair("version", file.version()));
{
Object owner;
- Ndnx::Name device_name (file.device_name ().c_str (), file.device_name ().size ());
- owner.push_back (Pair ("userName", boost::lexical_cast<string> (device_name)));
- owner.push_back (Pair ("seqNo", file.seq_no ()));
+ Ccnx::Name device_name(file.device_name().c_str(), file.device_name().size());
+ owner.push_back(Pair("userName", boost::lexical_cast<string>(device_name)));
+ owner.push_back(Pair("seqNo", file.seq_no()));
- json.push_back (Pair ("owner", owner));
+ json.push_back(Pair("owner", owner));
}
- json.push_back (Pair ("hash", boost::lexical_cast<string> (Hash (file.file_hash ().c_str (), file.file_hash ().size ()))));
- json.push_back (Pair ("timestamp", to_iso_extended_string (from_time_t (file.mtime ()))));
+ json.push_back(Pair("hash", boost::lexical_cast<string>(
+ Hash(file.file_hash().c_str(), file.file_hash().size()))));
+ json.push_back(Pair("timestamp", to_iso_extended_string(from_time_t(file.mtime()))));
ostringstream chmod;
- chmod << setbase (8) << setfill ('0') << setw (4) << file.mode ();
- json.push_back (Pair ("chmod", chmod.str ()));
+ chmod << setbase(8) << setfill('0') << setw(4) << file.mode();
+ json.push_back(Pair("chmod", chmod.str()));
- json.push_back (Pair ("segNum", file.seg_num ()));
+ json.push_back(Pair("segNum", file.seg_num()));
- files.push_back (json);
-}
-
-void debugFileState (const FileItem &file)
-{
- std::cout << file.filename () << std::endl;
+ files.push_back(json);
}
void
-StateServer::info_files_folder (const Ndnx::Name &interest)
+debugFileState(const FileItem& file)
{
- if (interest.size () - m_PREFIX_INFO.size () != 3 &&
- interest.size () - m_PREFIX_INFO.size () != 4)
- {
- _LOG_DEBUG ("Invalid interest: " << interest << ", " << interest.size () - m_PREFIX_INFO.size ());
- return;
- }
+ std::cout << file.filename() << std::endl;
+}
- _LOG_DEBUG (">> info_files_folder: " << interest);
- m_executor.execute (bind (&StateServer::info_files_folder_Execute, this, interest));
+void
+StateServer::info_files_folder(const Ccnx::Name& interest)
+{
+ if (interest.size() - m_PREFIX_INFO.size() != 3 && interest.size() - m_PREFIX_INFO.size() != 4) {
+ _LOG_DEBUG("Invalid interest: " << interest << ", " << interest.size() - m_PREFIX_INFO.size());
+ return;
+ }
+
+ _LOG_DEBUG(">> info_files_folder: " << interest);
+ m_executor.execute(bind(&StateServer::info_files_folder_Execute, this, interest));
}
void
-StateServer::info_files_folder_Execute (const Ndnx::Name &interest)
+StateServer::info_files_folder_Execute(const Ccnx::Name& interest)
{
// <PREFIX_INFO>/"filestate"/"folder"/<one-component-relative-folder-name>/<offset>
- try
- {
- int offset = interest.getCompFromBackAsInt (0);
+ try {
+ int offset = interest.getCompFromBackAsInt(0);
- // /// @todo !!! add security checking
+ // /// @todo !!! add security checking
- string folder;
- if (interest.size () - m_PREFIX_INFO.size () == 4)
- folder = interest.getCompFromBackAsString (1);
- else // == 3
- folder = "";
+ string folder;
+ if (interest.size() - m_PREFIX_INFO.size() == 4)
+ folder = interest.getCompFromBackAsString(1);
+ else // == 3
+ folder = "";
-/*
+ /*
* {
* "files": [
* ...
@@ -363,138 +356,125 @@
* }
*/
- using namespace json_spirit;
- Object json;
+ using namespace json_spirit;
+ Object json;
- Array files;
- bool more = m_actionLog
- ->GetFileState ()
- ->LookupFilesInFolderRecursively
- (boost::bind (StateServer::formatFilestateJson, boost::ref (files), _1),
- folder, offset*10, 10);
+ Array files;
+ bool more = m_actionLog->GetFileState()
+ ->LookupFilesInFolderRecursively(boost::bind(StateServer::formatFilestateJson,
+ boost::ref(files), _1),
+ folder, offset * 10, 10);
- json.push_back (Pair ("files", files));
+ json.push_back(Pair("files", files));
- if (more)
- {
- json.push_back (Pair ("more", lexical_cast<string> (offset + 1)));
- // Ndnx::Name more = Name (interest.getPartialName (0, interest.size () - 1))(offset + 1);
- // json.push_back (Pair ("more", lexical_cast<string> (more)));
- }
-
- ostringstream os;
- write_stream (Value (json), os, pretty_print | raw_utf8);
- m_ndnx->publishData (interest, os.str (), 1);
+ if (more) {
+ json.push_back(Pair("more", lexical_cast<string>(offset + 1)));
+ // Ccnx::Name more = Name (interest.getPartialName (0, interest.size () - 1))(offset + 1);
+ // json.push_back (Pair ("more", lexical_cast<string> (more)));
}
- catch (Ndnx::NameException &ne)
- {
- // ignore any unexpected interests and errors
- _LOG_ERROR (*boost::get_error_info<Ndnx::error_info_str>(ne));
- }
+
+ ostringstream os;
+ write_stream(Value(json), os, pretty_print | raw_utf8);
+ m_ccnx->publishData(interest, os.str(), 1);
+ }
+ catch (Ccnx::NameException& ne) {
+ // ignore any unexpected interests and errors
+ _LOG_ERROR(*boost::get_error_info<Ccnx::error_info_str>(ne));
+ }
}
void
-StateServer::cmd_restore_file (const Ndnx::Name &interest)
+StateServer::cmd_restore_file(const Ccnx::Name& interest)
{
- if (interest.size () - m_PREFIX_CMD.size () != 4 &&
- interest.size () - m_PREFIX_CMD.size () != 5)
- {
- _LOG_DEBUG ("Invalid interest: " << interest);
- return;
- }
+ if (interest.size() - m_PREFIX_CMD.size() != 4 && interest.size() - m_PREFIX_CMD.size() != 5) {
+ _LOG_DEBUG("Invalid interest: " << interest);
+ return;
+ }
- _LOG_DEBUG (">> cmd_restore_file: " << interest);
- m_executor.execute (bind (&StateServer::cmd_restore_file_Execute, this, interest));
+ _LOG_DEBUG(">> cmd_restore_file: " << interest);
+ m_executor.execute(bind(&StateServer::cmd_restore_file_Execute, this, interest));
}
void
-StateServer::cmd_restore_file_Execute (const Ndnx::Name &interest)
+StateServer::cmd_restore_file_Execute(const Ccnx::Name& interest)
{
// <PREFIX_CMD>/"restore"/"file"/<one-component-relative-file-name>/<version>/<file-hash>
/// @todo !!! add security checking
- try
- {
- FileItemPtr file;
+ try {
+ FileItemPtr file;
- if (interest.size () - m_PREFIX_CMD.size () == 5)
- {
- Hash hash (head(interest.getCompFromBack (0)), interest.getCompFromBack (0).size());
- int64_t version = interest.getCompFromBackAsInt (1);
- string filename = interest.getCompFromBackAsString (2); // should be safe even with full relative path
+ if (interest.size() - m_PREFIX_CMD.size() == 5) {
+ Hash hash(head(interest.getCompFromBack(0)), interest.getCompFromBack(0).size());
+ int64_t version = interest.getCompFromBackAsInt(1);
+ string filename =
+ interest.getCompFromBackAsString(2); // should be safe even with full relative path
- file = m_actionLog->LookupAction (filename, version, hash);
- if (!file)
- {
- _LOG_ERROR ("Requested file is not found: [" << filename << "] version [" << version << "] hash [" << hash.shortHash () << "]");
- }
- }
- else
- {
- int64_t version = interest.getCompFromBackAsInt (0);
- string filename = interest.getCompFromBackAsString (1); // should be safe even with full relative path
-
- file = m_actionLog->LookupAction (filename, version, Hash (0,0));
- if (!file)
- {
- _LOG_ERROR ("Requested file is not found: [" << filename << "] version [" << version << "]");
- }
- }
-
- if (!file)
- {
- m_ndnx->publishData (interest, "FAIL: Requested file is not found", 1);
- return;
- }
-
- Hash hash = Hash (file->file_hash ().c_str (), file->file_hash ().size ());
-
- ///////////////////
- // now the magic //
- ///////////////////
-
- boost::filesystem::path filePath = m_rootDir / file->filename ();
- Name deviceName (file->device_name ().c_str (), file->device_name ().size ());
-
- try
- {
- if (filesystem::exists (filePath) &&
- filesystem::last_write_time (filePath) == file->mtime () &&
-#if BOOST_VERSION >= 104900
- filesystem::status (filePath).permissions () == static_cast<filesystem::perms> (file->mode ()) &&
-#endif
- *Hash::FromFileContent (filePath) == hash)
- {
- m_ndnx->publishData (interest, "OK: File already exists", 1);
- _LOG_DEBUG ("Asking to assemble a file, but file already exists on a filesystem");
- return;
- }
- }
- catch (filesystem::filesystem_error &error)
- {
- m_ndnx->publishData (interest, "FAIL: File operation failed", 1);
- _LOG_ERROR ("File operations failed on [" << filePath << "] (ignoring)");
- }
-
- _LOG_TRACE ("Restoring file [" << filePath << "]");
- if (m_objectManager.objectsToLocalFile (deviceName, hash, filePath))
- {
- last_write_time (filePath, file->mtime ());
-#if BOOST_VERSION >= 104900
- permissions (filePath, static_cast<filesystem::perms> (file->mode ()));
-#endif
- m_ndnx->publishData (interest, "OK", 1);
- }
- else
- {
- m_ndnx->publishData (interest, "FAIL: Unknown error while restoring file", 1);
- }
+ file = m_actionLog->LookupAction(filename, version, hash);
+ if (!file) {
+ _LOG_ERROR("Requested file is not found: [" << filename << "] version [" << version
+ << "] hash ["
+ << hash.shortHash()
+ << "]");
+ }
}
- catch (Ndnx::NameException &ne)
- {
- // ignore any unexpected interests and errors
- _LOG_ERROR(*boost::get_error_info<Ndnx::error_info_str>(ne));
+ else {
+ int64_t version = interest.getCompFromBackAsInt(0);
+ string filename =
+ interest.getCompFromBackAsString(1); // should be safe even with full relative path
+
+ file = m_actionLog->LookupAction(filename, version, Hash(0, 0));
+ if (!file) {
+ _LOG_ERROR("Requested file is not found: [" << filename << "] version [" << version << "]");
+ }
}
+
+ if (!file) {
+ m_ccnx->publishData(interest, "FAIL: Requested file is not found", 1);
+ return;
+ }
+
+ Hash hash = Hash(file->file_hash().c_str(), file->file_hash().size());
+
+ ///////////////////
+ // now the magic //
+ ///////////////////
+
+ boost::filesystem::path filePath = m_rootDir / file->filename();
+ Name deviceName(file->device_name().c_str(), file->device_name().size());
+
+ try {
+ if (filesystem::exists(filePath) && filesystem::last_write_time(filePath) == file->mtime() &&
+#if BOOST_VERSION >= 104900
+ filesystem::status(filePath).permissions() == static_cast<filesystem::perms>(file->mode()) &&
+#endif
+ *Hash::FromFileContent(filePath) == hash) {
+ m_ccnx->publishData(interest, "OK: File already exists", 1);
+ _LOG_DEBUG("Asking to assemble a file, but file already exists on a filesystem");
+ return;
+ }
+ }
+ catch (filesystem::filesystem_error& error) {
+ m_ccnx->publishData(interest, "FAIL: File operation failed", 1);
+ _LOG_ERROR("File operations failed on [" << filePath << "] (ignoring)");
+ }
+
+ _LOG_TRACE("Restoring file [" << filePath << "]");
+ if (m_objectManager.objectsToLocalFile(deviceName, hash, filePath)) {
+ last_write_time(filePath, file->mtime());
+#if BOOST_VERSION >= 104900
+ permissions(filePath, static_cast<filesystem::perms>(file->mode()));
+#endif
+ m_ccnx->publishData(interest, "OK", 1);
+ }
+ else {
+ m_ccnx->publishData(interest, "FAIL: Unknown error while restoring file", 1);
+ }
+ }
+ catch (Ccnx::NameException& ne) {
+ // ignore any unexpected interests and errors
+ _LOG_ERROR(*boost::get_error_info<Ccnx::error_info_str>(ne));
+ }
}
diff --git a/src/state-server.hpp b/src/state-server.hpp
index 30f9e45..72dd275 100644
--- a/src/state-server.hpp
+++ b/src/state-server.hpp
@@ -21,18 +21,18 @@
#ifndef STATE_SERVER_H
#define STATE_SERVER_H
-#include "ccnx-wrapper.hpp"
-#include "object-manager.hpp"
-#include "object-db.hpp"
#include "action-log.hpp"
-#include <set>
-#include <map>
-#include <boost/thread/shared_mutex.hpp>
-#include <boost/thread/locks.hpp>
+#include "ccnx-wrapper.hpp"
#include "executor.hpp"
+#include "object-db.hpp"
+#include "object-manager.hpp"
+#include <boost/thread/locks.hpp>
+#include <boost/thread/shared_mutex.hpp>
+#include <map>
+#include <set>
-#include "../contrib/json_spirit/json_spirit_writer_template.h"
#include "../contrib/json_spirit/json_spirit_value.h"
+#include "../contrib/json_spirit/json_spirit_writer_template.h"
#ifndef JSON_SPIRIT_VALUE_ENABLED
#error Please define JSON_SPIRIT_VALUE_ENABLED for the Value type to be enabled
@@ -151,51 +151,52 @@
class StateServer
{
public:
- StateServer(Ndnx::NdnxWrapperPtr ndnx, ActionLogPtr actionLog, const boost::filesystem::path &rootDir,
- const Ndnx::Name &userName, const std::string &sharedFolderName, const std::string &appName,
- ObjectManager &objectManager,
- int freshness = -1);
+ StateServer(Ccnx::CcnxWrapperPtr ccnx, ActionLogPtr actionLog,
+ const boost::filesystem::path& rootDir, const Ccnx::Name& userName,
+ const std::string& sharedFolderName, const std::string& appName,
+ ObjectManager& objectManager, int freshness = -1);
~StateServer();
private:
void
- info_actions_folder (const Ndnx::Name &interest);
+ info_actions_folder(const Ccnx::Name& interest);
void
- info_actions_file (const Ndnx::Name &interest);
+ info_actions_file(const Ccnx::Name& interest);
void
- info_actions_fileOrFolder_Execute (const Ndnx::Name &interest, bool isFolder = true);
+ info_actions_fileOrFolder_Execute(const Ccnx::Name& interest, bool isFolder = true);
void
- info_files_folder (const Ndnx::Name &interest);
+ info_files_folder(const Ccnx::Name& interest);
void
- info_files_folder_Execute (const Ndnx::Name &interest);
+ info_files_folder_Execute(const Ccnx::Name& interest);
void
- cmd_restore_file (const Ndnx::Name &interest);
+ cmd_restore_file(const Ccnx::Name& interest);
void
- cmd_restore_file_Execute (const Ndnx::Name &interest);
+ cmd_restore_file_Execute(const Ccnx::Name& interest);
private:
void
- registerPrefixes ();
+ registerPrefixes();
void
- deregisterPrefixes ();
+ deregisterPrefixes();
static void
- formatActionJson (json_spirit::Array &actions, const Ndnx::Name &name, sqlite3_int64 seq_no, const ActionItem &action);
+ formatActionJson(json_spirit::Array& actions, const Ccnx::Name& name, sqlite3_int64 seq_no,
+ const ActionItem& action);
static void
- formatFilestateJson (json_spirit::Array &files, const FileItem &file);
+ formatFilestateJson(json_spirit::Array& files, const FileItem& file);
private:
Ndnx::NdnxWrapperPtr m_ndnx;
ActionLogPtr m_actionLog;
- ObjectManager &m_objectManager;
+ ObjectManager& m_objectManager;
Ndnx::Name m_PREFIX_INFO;
Ndnx::Name m_PREFIX_CMD;
@@ -203,9 +204,9 @@
boost::filesystem::path m_rootDir;
int m_freshness;
- Executor m_executor;
+ Executor m_executor;
- Ndnx::Name m_userName;
+ Ccnx::Name m_userName;
std::string m_sharedFolderName;
std::string m_appName;
};
diff --git a/src/sync-core.cpp b/src/sync-core.cpp
index 1442bd3..0a5efa6 100644
--- a/src/sync-core.cpp
+++ b/src/sync-core.cpp
@@ -19,16 +19,16 @@
*/
#include "sync-core.hpp"
-#include "sync-state-helper.hpp"
#include "logging.hpp"
+#include "periodic-task.hpp"
#include "random-interval-generator.hpp"
#include "simple-interval-generator.hpp"
-#include "periodic-task.hpp"
+#include "sync-state-helper.hpp"
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
-INIT_LOGGER ("Sync.Core");
+INIT_LOGGER("Sync.Core");
const string SyncCore::RECOVER = "RECOVER";
const double SyncCore::WAIT = 0.05;
@@ -42,40 +42,46 @@
using namespace boost;
using namespace Ndnx;
-SyncCore::SyncCore(SyncLogPtr syncLog, const Name &userName, const Name &localPrefix, const Name &syncPrefix,
- const StateMsgCallback &callback, NdnxWrapperPtr ndnx, double syncInterestInterval/*= -1.0*/)
- : m_ndnx (ndnx)
+SyncCore::SyncCore(SyncLogPtr syncLog, const Name& userName, const Name& localPrefix,
+ const Name& syncPrefix, const StateMsgCallback& callback, CcnxWrapperPtr ccnx,
+ double syncInterestInterval /*= -1.0*/)
+ : m_ccnx(ccnx)
, m_log(syncLog)
- , m_scheduler(new Scheduler ())
+ , m_scheduler(new Scheduler())
, m_stateMsgCallback(callback)
, m_syncPrefix(syncPrefix)
- , m_recoverWaitGenerator(new RandomIntervalGenerator(WAIT, RANDOM_PERCENT, RandomIntervalGenerator::UP))
+ , m_recoverWaitGenerator(
+ new RandomIntervalGenerator(WAIT, RANDOM_PERCENT, RandomIntervalGenerator::UP))
, m_syncInterestInterval(syncInterestInterval)
{
m_rootHash = m_log->RememberStateInStateLog();
m_ndnx->setInterestFilter(m_syncPrefix, boost::bind(&SyncCore::handleInterest, this, _1));
// m_log->initYP(m_yp);
- m_log->UpdateLocalLocator (localPrefix);
+ m_log->UpdateLocalLocator(localPrefix);
m_scheduler->start();
- double interval = (m_syncInterestInterval > 0 && m_syncInterestInterval < 30.0) ? m_syncInterestInterval : 4.0;
- m_sendSyncInterestTask = make_shared<PeriodicTask>(bind(&SyncCore::sendSyncInterest, this), SYNC_INTEREST_TAG, m_scheduler, make_shared<SimpleIntervalGenerator>(interval));
+ double interval =
+ (m_syncInterestInterval > 0 && m_syncInterestInterval < 30.0) ? m_syncInterestInterval : 4.0;
+ m_sendSyncInterestTask =
+ make_shared<PeriodicTask>(bind(&SyncCore::sendSyncInterest, this), SYNC_INTEREST_TAG,
+ m_scheduler, make_shared<SimpleIntervalGenerator>(interval));
// sendSyncInterest();
- Scheduler::scheduleOneTimeTask (m_scheduler, 0.1, bind(&SyncCore::sendSyncInterest, this), SYNC_INTEREST_TAG2);
+ Scheduler::scheduleOneTimeTask(m_scheduler, 0.1, bind(&SyncCore::sendSyncInterest, this),
+ SYNC_INTEREST_TAG2);
}
SyncCore::~SyncCore()
{
- m_scheduler->shutdown ();
+ m_scheduler->shutdown();
// need to "deregister" closures
}
void
SyncCore::updateLocalState(sqlite3_int64 seqno)
{
- m_log->UpdateLocalSeqNo (seqno);
+ m_log->UpdateLocalSeqNo(seqno);
localStateChanged();
}
@@ -88,119 +94,110 @@
SyncStateMsgPtr msg = m_log->FindStateDifferences(*oldHash, *m_rootHash);
// reply sync Interest with oldHash as last component
- Name syncName = Name (m_syncPrefix)(oldHash->GetHash(), oldHash->GetHashBytes());
- BytesPtr syncData = serializeGZipMsg (*msg);
+ Name syncName = Name(m_syncPrefix)(oldHash->GetHash(), oldHash->GetHashBytes());
+ BytesPtr syncData = serializeGZipMsg(*msg);
- m_ndnx->publishData(syncName, *syncData, FRESHNESS);
- _LOG_DEBUG ("[" << m_log->GetLocalName () << "] localStateChanged ");
- _LOG_TRACE ("[" << m_log->GetLocalName () << "] publishes: " << oldHash->shortHash ());
+ m_ccnx->publishData(syncName, *syncData, FRESHNESS);
+ _LOG_DEBUG("[" << m_log->GetLocalName() << "] localStateChanged ");
+ _LOG_TRACE("[" << m_log->GetLocalName() << "] publishes: " << oldHash->shortHash());
// _LOG_TRACE (msg);
- m_scheduler->deleteTask (SYNC_INTEREST_TAG2);
+ m_scheduler->deleteTask(SYNC_INTEREST_TAG2);
// no hurry in sending out new Sync Interest; if others send the new Sync Interest first, no problem, we know the new root hash already;
// this is trying to avoid the situation that the order of SyncData and new Sync Interest gets reversed at receivers
- Scheduler::scheduleOneTimeTask (m_scheduler, 0.05,
- bind(&SyncCore::sendSyncInterest, this),
- SYNC_INTEREST_TAG2);
+ Scheduler::scheduleOneTimeTask(m_scheduler, 0.05, bind(&SyncCore::sendSyncInterest, this),
+ SYNC_INTEREST_TAG2);
- //sendSyncInterest();
+ // sendSyncInterest();
}
void
-SyncCore::localStateChangedDelayed ()
+SyncCore::localStateChangedDelayed()
{
// many calls to localStateChangedDelayed within 0.5 second will be suppressed to one localStateChanged calls
- Scheduler::scheduleOneTimeTask (m_scheduler, 0.5,
- bind (&SyncCore::localStateChanged, this),
- LOCAL_STATE_CHANGE_DELAYED_TAG);
+ Scheduler::scheduleOneTimeTask(m_scheduler, 0.5, bind(&SyncCore::localStateChanged, this),
+ LOCAL_STATE_CHANGE_DELAYED_TAG);
}
void
-SyncCore::handleInterest(const Name &name)
+SyncCore::handleInterest(const Name& name)
{
int size = name.size();
int prefixSize = m_syncPrefix.size();
- if (size == prefixSize + 1)
- {
+ if (size == prefixSize + 1) {
// this is normal sync interest
handleSyncInterest(name);
}
- else if (size == prefixSize + 2 && name.getCompAsString(m_syncPrefix.size()) == RECOVER)
- {
+ else if (size == prefixSize + 2 && name.getCompAsString(m_syncPrefix.size()) == RECOVER) {
// this is recovery interest
handleRecoverInterest(name);
}
}
void
-SyncCore::handleRecoverInterest(const Name &name)
+SyncCore::handleRecoverInterest(const Name& name)
{
- _LOG_DEBUG ("[" << m_log->GetLocalName () << "] <<<<< RECOVER Interest with name " << name);
+ _LOG_DEBUG("[" << m_log->GetLocalName() << "] <<<<< RECOVER Interest with name " << name);
Bytes hashBytes = name.getComp(name.size() - 1);
// this is the hash unkonwn to the sender of the interest
Hash hash(head(hashBytes), hashBytes.size());
- if (m_log->LookupSyncLog(hash) > 0)
- {
+ if (m_log->LookupSyncLog(hash) > 0) {
// we know the hash, should reply everything
SyncStateMsgPtr msg = m_log->FindStateDifferences(*(Hash::Origin), *m_rootHash);
- BytesPtr syncData = serializeGZipMsg (*msg);
- m_ndnx->publishData(name, *syncData, FRESHNESS);
- _LOG_TRACE ("[" << m_log->GetLocalName () << "] publishes " << hash.shortHash ());
+ BytesPtr syncData = serializeGZipMsg(*msg);
+ m_ccnx->publishData(name, *syncData, FRESHNESS);
+ _LOG_TRACE("[" << m_log->GetLocalName() << "] publishes " << hash.shortHash());
// _LOG_TRACE (msg);
}
- else
- {
- // we don't recognize this hash, can not help
- }
+ else {
+ // we don't recognize this hash, can not help
+ }
}
void
-SyncCore::handleSyncInterest(const Name &name)
+SyncCore::handleSyncInterest(const Name& name)
{
- _LOG_DEBUG ("[" << m_log->GetLocalName () << "] <<<<< SYNC Interest with name " << name);
+ _LOG_DEBUG("[" << m_log->GetLocalName() << "] <<<<< SYNC Interest with name " << name);
Bytes hashBytes = name.getComp(name.size() - 1);
HashPtr hash(new Hash(head(hashBytes), hashBytes.size()));
- if (*hash == *m_rootHash)
- {
+ if (*hash == *m_rootHash) {
// we have the same hash; nothing needs to be done
- _LOG_TRACE ("same as root hash: " << hash->shortHash ());
+ _LOG_TRACE("same as root hash: " << hash->shortHash());
return;
}
- else if (m_log->LookupSyncLog(*hash) > 0)
- {
+ else if (m_log->LookupSyncLog(*hash) > 0) {
// we know something more
- _LOG_TRACE ("found hash in sync log");
+ _LOG_TRACE("found hash in sync log");
SyncStateMsgPtr msg = m_log->FindStateDifferences(*hash, *m_rootHash);
- BytesPtr syncData = serializeGZipMsg (*msg);
- m_ndnx->publishData(name, *syncData, FRESHNESS);
- _LOG_TRACE (m_log->GetLocalName () << " publishes: " << hash->shortHash ());
- _LOG_TRACE (msg);
+ BytesPtr syncData = serializeGZipMsg(*msg);
+ m_ccnx->publishData(name, *syncData, FRESHNESS);
+ _LOG_TRACE(m_log->GetLocalName() << " publishes: " << hash->shortHash());
+ _LOG_TRACE(msg);
}
- else
- {
+ else {
// we don't recognize the hash, send recover Interest if still don't know the hash after a randomized wait period
double wait = m_recoverWaitGenerator->nextInterval();
- _LOG_TRACE (m_log->GetLocalName () << ", rootHash: " << *m_rootHash << ", hash: " << hash->shortHash ());
- _LOG_TRACE ("recover task scheduled after wait: " << wait);
+ _LOG_TRACE(m_log->GetLocalName() << ", rootHash: " << *m_rootHash
+ << ", hash: " << hash->shortHash());
+ _LOG_TRACE("recover task scheduled after wait: " << wait);
- Scheduler::scheduleOneTimeTask (m_scheduler,
- wait, boost::bind(&SyncCore::recover, this, hash),
- "r-"+lexical_cast<string> (*hash));
+ Scheduler::scheduleOneTimeTask(m_scheduler, wait, boost::bind(&SyncCore::recover, this, hash),
+ "r-" + lexical_cast<string>(*hash));
}
}
void
-SyncCore::handleSyncInterestTimeout(const Name &name, const Closure &closure, Selectors selectors)
+SyncCore::handleSyncInterestTimeout(const Name& name, const Closure& closure, Selectors selectors)
{
// sync interest will be resent by scheduler
}
void
-SyncCore::handleRecoverInterestTimeout(const Name &name, const Closure &closure, Selectors selectors)
+SyncCore::handleRecoverInterestTimeout(const Name& name, const Closure& closure, Selectors selectors)
{
// We do not re-express recovery interest for now
// if difference is not resolved, the sync interest will trigger
@@ -209,89 +206,78 @@
}
void
-SyncCore::handleRecoverData(const Name &name, PcoPtr content)
+SyncCore::handleRecoverData(const Name& name, PcoPtr content)
{
- _LOG_DEBUG ("[" << m_log->GetLocalName () << "] <<<<< RECOVER DATA with name: " << name);
+ _LOG_DEBUG("[" << m_log->GetLocalName() << "] <<<<< RECOVER DATA with name: " << name);
//cout << "handle recover data" << end;
- if (content && content->contentPtr () && content->contentPtr ()->size () > 0)
- {
- handleStateData(*content->contentPtr ());
- }
- else
- {
- _LOG_ERROR ("Got recovery DATA with empty content");
- }
+ if (content && content->contentPtr() && content->contentPtr()->size() > 0) {
+ handleStateData(*content->contentPtr());
+ }
+ else {
+ _LOG_ERROR("Got recovery DATA with empty content");
+ }
// sendSyncInterest();
- m_scheduler->deleteTask (SYNC_INTEREST_TAG2);
- Scheduler::scheduleOneTimeTask (m_scheduler, 0,
- bind(&SyncCore::sendSyncInterest, this),
- SYNC_INTEREST_TAG2);
+ m_scheduler->deleteTask(SYNC_INTEREST_TAG2);
+ Scheduler::scheduleOneTimeTask(m_scheduler, 0, bind(&SyncCore::sendSyncInterest, this),
+ SYNC_INTEREST_TAG2);
}
void
-SyncCore::handleSyncData(const Name &name, PcoPtr content)
+SyncCore::handleSyncData(const Name& name, PcoPtr content)
{
- _LOG_DEBUG ("[" << m_log->GetLocalName () << "] <<<<< SYNC DATA with name: " << name);
+ _LOG_DEBUG("[" << m_log->GetLocalName() << "] <<<<< SYNC DATA with name: " << name);
// suppress recover in interest - data out of order case
- if (content && content->contentPtr () && content->contentPtr ()->size () > 0)
- {
- handleStateData(*content->contentPtr ());
- }
- else
- {
- _LOG_ERROR ("Got sync DATA with empty content");
- }
+ if (content && content->contentPtr() && content->contentPtr()->size() > 0) {
+ handleStateData(*content->contentPtr());
+ }
+ else {
+ _LOG_ERROR("Got sync DATA with empty content");
+ }
// resume outstanding sync interest
// sendSyncInterest();
- m_scheduler->deleteTask (SYNC_INTEREST_TAG2);
- Scheduler::scheduleOneTimeTask (m_scheduler, 0,
- bind(&SyncCore::sendSyncInterest, this),
- SYNC_INTEREST_TAG2);
+ m_scheduler->deleteTask(SYNC_INTEREST_TAG2);
+ Scheduler::scheduleOneTimeTask(m_scheduler, 0, bind(&SyncCore::sendSyncInterest, this),
+ SYNC_INTEREST_TAG2);
}
void
-SyncCore::handleStateData(const Bytes &content)
+SyncCore::handleStateData(const Bytes& content)
{
SyncStateMsgPtr msg = deserializeGZipMsg<SyncStateMsg>(content);
- if(!(msg))
- {
+ if (!(msg)) {
// ignore misformed SyncData
- _LOG_ERROR ("Misformed SyncData");
+ _LOG_ERROR("Misformed SyncData");
return;
}
- _LOG_TRACE (m_log->GetLocalName () << " receives Msg ");
- _LOG_TRACE (msg);
+ _LOG_TRACE(m_log->GetLocalName() << " receives Msg ");
+ _LOG_TRACE(msg);
int size = msg->state_size();
int index = 0;
- while (index < size)
- {
+ while (index < size) {
SyncState state = msg->state(index);
string devStr = state.name();
- Name deviceName((const unsigned char *)devStr.c_str(), devStr.size());
- // cout << "Got Name: " << deviceName;
- if (state.type() == SyncState::UPDATE)
- {
+ Name deviceName((const unsigned char*)devStr.c_str(), devStr.size());
+ // cout << "Got Name: " << deviceName;
+ if (state.type() == SyncState::UPDATE) {
sqlite3_int64 seqno = state.seq();
- // cout << ", Got seq: " << seqno << endl;
m_log->UpdateDeviceSeqNo(deviceName, seqno);
- if (state.has_locator())
- {
+ if (state.has_locator()) {
string locStr = state.locator();
- Name locatorName((const unsigned char *)locStr.c_str(), locStr.size());
- // cout << ", Got loc: " << locatorName << endl;
+ Name locatorName((const unsigned char*)locStr.c_str(), locStr.size());
+ // cout << ", Got loc: " << locatorName << endl;
m_log->UpdateLocator(deviceName, locatorName);
- _LOG_TRACE ("self: " << m_log->GetLocalName () << ", device: " << deviceName << " < == > " << locatorName);
+ _LOG_TRACE("self: " << m_log->GetLocalName() << ", device: " << deviceName << " < == > "
+ << locatorName);
}
}
- else
- {
- _LOG_ERROR ("Receive SYNC DELETE, but we don't support it yet");
+ else {
+ _LOG_ERROR("Receive SYNC DELETE, but we don't support it yet");
deregister(deviceName);
}
index++;
@@ -303,28 +289,28 @@
// get diff with both new SeqNo and old SeqNo
SyncStateMsgPtr diff = m_log->FindStateDifferences(*oldHash, *m_rootHash, true);
- if (diff->state_size() > 0)
- {
- m_stateMsgCallback (diff);
+ if (diff->state_size() > 0) {
+ m_stateMsgCallback(diff);
}
}
void
SyncCore::sendSyncInterest()
{
- Name syncInterest = Name (m_syncPrefix)(m_rootHash->GetHash(), m_rootHash->GetHashBytes());
+ Name syncInterest = Name(m_syncPrefix)(m_rootHash->GetHash(), m_rootHash->GetHashBytes());
- _LOG_DEBUG ("[" << m_log->GetLocalName () << "] >>> SYNC Interest for " << m_rootHash->shortHash () << ": " << syncInterest);
+ _LOG_DEBUG("[" << m_log->GetLocalName() << "] >>> SYNC Interest for " << m_rootHash->shortHash()
+ << ": "
+ << syncInterest);
Selectors selectors;
- if (m_syncInterestInterval > 0 && m_syncInterestInterval < 30.0)
- {
+ if (m_syncInterestInterval > 0 && m_syncInterestInterval < 30.0) {
selectors.interestLifetime(m_syncInterestInterval);
}
- m_ndnx->sendInterest(syncInterest,
- Closure (boost::bind(&SyncCore::handleSyncData, this, _1, _2),
- boost::bind(&SyncCore::handleSyncInterestTimeout, this, _1, _2, _3)),
- selectors);
+ m_ccnx->sendInterest(syncInterest,
+ Closure(boost::bind(&SyncCore::handleSyncData, this, _1, _2),
+ boost::bind(&SyncCore::handleSyncInterestTimeout, this, _1, _2, _3)),
+ selectors);
// if there is a pending syncSyncInterest task, reschedule it to be m_syncInterestInterval seconds from now
// if no such task exists, it will be added
@@ -334,38 +320,36 @@
void
SyncCore::recover(HashPtr hash)
{
- if (!(*hash == *m_rootHash) && m_log->LookupSyncLog(*hash) <= 0)
- {
- _LOG_TRACE (m_log->GetLocalName () << ", Recover for: " << hash->shortHash ());
+ if (!(*hash == *m_rootHash) && m_log->LookupSyncLog(*hash) <= 0) {
+ _LOG_TRACE(m_log->GetLocalName() << ", Recover for: " << hash->shortHash());
// unfortunately we still don't recognize this hash
Bytes bytes;
- readRaw(bytes, (const unsigned char *)hash->GetHash(), hash->GetHashBytes());
+ readRaw(bytes, (const unsigned char*)hash->GetHash(), hash->GetHashBytes());
// append the unknown hash
- Name recoverInterest = Name (m_syncPrefix)(RECOVER)(bytes);
+ Name recoverInterest = Name(m_syncPrefix)(RECOVER)(bytes);
- _LOG_DEBUG ("[" << m_log->GetLocalName () << "] >>> RECOVER Interests for " << hash->shortHash ());
+ _LOG_DEBUG("[" << m_log->GetLocalName() << "] >>> RECOVER Interests for " << hash->shortHash());
- m_ndnx->sendInterest(recoverInterest,
- Closure (boost::bind(&SyncCore::handleRecoverData, this, _1, _2),
- boost::bind(&SyncCore::handleRecoverInterestTimeout, this, _1, _2, _3)));
-
+ m_ccnx->sendInterest(recoverInterest,
+ Closure(boost::bind(&SyncCore::handleRecoverData, this, _1, _2),
+ boost::bind(&SyncCore::handleRecoverInterestTimeout, this, _1, _2,
+ _3)));
}
- else
- {
+ else {
// we already learned the hash; cheers!
}
}
void
-SyncCore::deregister(const Name &name)
+SyncCore::deregister(const Name& name)
{
// Do nothing for now
// TODO: handle deregistering
}
sqlite3_int64
-SyncCore::seq(const Name &name)
+SyncCore::seq(const Name& name)
{
return m_log->SeqNo(name);
}
diff --git a/src/sync-core.hpp b/src/sync-core.hpp
index 0d7f98d..7f10717 100644
--- a/src/sync-core.hpp
+++ b/src/sync-core.hpp
@@ -21,10 +21,10 @@
#ifndef SYNC_CORE_H
#define SYNC_CORE_H
-#include "sync-log.hpp"
-#include "ccnx-wrapper.hpp"
#include "ccnx-selectors.hpp"
+#include "ccnx-wrapper.hpp"
#include "scheduler.hpp"
+#include "sync-log.hpp"
#include "task.hpp"
#include <boost/function.hpp>
@@ -32,25 +32,26 @@
class SyncCore
{
public:
- typedef boost::function<void (SyncStateMsgPtr stateMsg) > StateMsgCallback;
+ typedef boost::function<void(SyncStateMsgPtr stateMsg)> StateMsgCallback;
static const int FRESHNESS = 2; // seconds
static const string RECOVER;
- static const double WAIT; // seconds;
+ static const double WAIT; // seconds;
static const double RANDOM_PERCENT; // seconds;
public:
- SyncCore(SyncLogPtr syncLog
- , const Ndnx::Name &userName
- , const Ndnx::Name &localPrefix // routable name used by the local user
- , const Ndnx::Name &syncPrefix // the prefix for the sync collection
- , const StateMsgCallback &callback // callback when state change is detected
- , Ndnx::NdnxWrapperPtr ndnx
- , double syncInterestInterval = -1.0);
+ SyncCore(SyncLogPtr syncLog, const Ccnx::Name& userName,
+ const Ccnx::Name& localPrefix // routable name used by the local user
+ ,
+ const Ccnx::Name& syncPrefix // the prefix for the sync collection
+ ,
+ const StateMsgCallback& callback // callback when state change is detected
+ ,
+ Ccnx::CcnxWrapperPtr ccnx, double syncInterestInterval = -1.0);
~SyncCore();
void
- localStateChanged ();
+ localStateChanged();
/**
* @brief Schedule an event to update local state with a small delay
@@ -59,37 +60,41 @@
* are anticipated within a short period of time
*/
void
- localStateChangedDelayed ();
+ localStateChangedDelayed();
- void
- updateLocalState (sqlite3_int64);
+ void updateLocalState(sqlite3_int64);
-// ------------------ only used in test -------------------------
+ // ------------------ only used in test -------------------------
public:
HashPtr
- root() const { return m_rootHash; }
+ root() const
+ {
+ return m_rootHash;
+ }
sqlite3_int64
- seq (const Ndnx::Name &name);
+ seq(const Ccnx::Name& name);
private:
void
- handleInterest(const Ndnx::Name &name);
+ handleInterest(const Ccnx::Name& name);
void
- handleSyncData(const Ndnx::Name &name, Ndnx::PcoPtr content);
+ handleSyncData(const Ccnx::Name& name, Ccnx::PcoPtr content);
void
- handleRecoverData(const Ndnx::Name &name, Ndnx::PcoPtr content);
+ handleRecoverData(const Ccnx::Name& name, Ccnx::PcoPtr content);
void
- handleSyncInterestTimeout(const Ndnx::Name &name, const Ndnx::Closure &closure, Ndnx::Selectors selectors);
+ handleSyncInterestTimeout(const Ccnx::Name& name, const Ccnx::Closure& closure,
+ Ccnx::Selectors selectors);
void
- handleRecoverInterestTimeout(const Ndnx::Name &name, const Ndnx::Closure &closure, Ndnx::Selectors selectors);
+ handleRecoverInterestTimeout(const Ccnx::Name& name, const Ccnx::Closure& closure,
+ Ccnx::Selectors selectors);
void
- deregister(const Ndnx::Name &name);
+ deregister(const Ccnx::Name& name);
void
recover(HashPtr hash);
@@ -99,13 +104,13 @@
sendSyncInterest();
void
- handleSyncInterest(const Ndnx::Name &name);
+ handleSyncInterest(const Ccnx::Name& name);
void
- handleRecoverInterest(const Ndnx::Name &name);
+ handleRecoverInterest(const Ccnx::Name& name);
void
- handleStateData(const Ndnx::Bytes &content);
+ handleStateData(const Ccnx::Bytes& content);
private:
Ndnx::NdnxWrapperPtr m_ndnx;
diff --git a/src/sync-log.cpp b/src/sync-log.cpp
index b9f4209..ced80fe 100644
--- a/src/sync-log.cpp
+++ b/src/sync-log.cpp
@@ -25,13 +25,14 @@
#include <boost/make_shared.hpp>
#include <boost/thread.hpp>
-INIT_LOGGER ("Sync.Log");
+INIT_LOGGER("Sync.Log");
using namespace boost;
using namespace std;
using namespace Ndnx;
-// static void xTrace (void*, const char* q)
+// static void
+// xTrace(void*, const char* q)
// {
// cout << q << endl;
// }
@@ -96,243 +97,226 @@
";
-SyncLog::SyncLog (const boost::filesystem::path &path, const Ndnx::Name &localName)
- : DbHelper (path / ".chronoshare", "sync-log.db")
- , m_localName (localName)
+SyncLog::SyncLog(const boost::filesystem::path& path, const Ccnx::Name& localName)
+ : DbHelper(path / ".chronoshare", "sync-log.db")
+ , m_localName(localName)
{
- sqlite3_exec (m_db, INIT_DATABASE.c_str (), NULL, NULL, NULL);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ sqlite3_exec(m_db, INIT_DATABASE.c_str(), NULL, NULL, NULL);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- UpdateDeviceSeqNo (localName, 0);
+ UpdateDeviceSeqNo(localName, 0);
- sqlite3_stmt *stmt;
- int res = sqlite3_prepare_v2 (m_db, "SELECT device_id, seq_no FROM SyncNodes WHERE device_name=?", -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ int res = sqlite3_prepare_v2(m_db, "SELECT device_id, seq_no FROM SyncNodes WHERE device_name=?",
+ -1, &stmt, 0);
- Ndnx::NdnxCharbufPtr name = m_localName;
- sqlite3_bind_blob (stmt, 1, name->buf (), name->length (), SQLITE_STATIC);
+ Ccnx::CcnxCharbufPtr name = m_localName;
+ sqlite3_bind_blob(stmt, 1, name->buf(), name->length(), SQLITE_STATIC);
- if (sqlite3_step (stmt) == SQLITE_ROW)
- {
- m_localDeviceId = sqlite3_column_int64 (stmt, 0);
- }
- else
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Impossible thing in SyncLog::SyncLog"));
- }
- sqlite3_finalize (stmt);
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ m_localDeviceId = sqlite3_column_int64(stmt, 0);
+ }
+ else {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Impossible thing in SyncLog::SyncLog"));
+ }
+ sqlite3_finalize(stmt);
}
sqlite3_int64
-SyncLog::GetNextLocalSeqNo ()
+SyncLog::GetNextLocalSeqNo()
{
- sqlite3_stmt *stmt_seq;
- sqlite3_prepare_v2 (m_db, "SELECT seq_no FROM SyncNodes WHERE device_id = ?", -1, &stmt_seq, 0);
- sqlite3_bind_int64 (stmt_seq, 1, m_localDeviceId);
+ sqlite3_stmt* stmt_seq;
+ sqlite3_prepare_v2(m_db, "SELECT seq_no FROM SyncNodes WHERE device_id = ?", -1, &stmt_seq, 0);
+ sqlite3_bind_int64(stmt_seq, 1, m_localDeviceId);
- if (sqlite3_step (stmt_seq) != SQLITE_ROW)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Impossible thing in SyncLog::GetNextLocalSeqNo"));
- }
+ if (sqlite3_step(stmt_seq) != SQLITE_ROW) {
+ BOOST_THROW_EXCEPTION(Error::Db()
+ << errmsg_info_str("Impossible thing in SyncLog::GetNextLocalSeqNo"));
+ }
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));
- sqlite3_int64 seq_no = sqlite3_column_int64 (stmt_seq, 0) + 1;
- sqlite3_finalize (stmt_seq);
+ sqlite3_int64 seq_no = sqlite3_column_int64(stmt_seq, 0) + 1;
+ sqlite3_finalize(stmt_seq);
- UpdateDeviceSeqNo (m_localDeviceId, seq_no);
+ UpdateDeviceSeqNo(m_localDeviceId, seq_no);
return seq_no;
}
HashPtr
-SyncLog::RememberStateInStateLog ()
+SyncLog::RememberStateInStateLog()
{
- WriteLock lock (m_stateUpdateMutex);
+ WriteLock lock(m_stateUpdateMutex);
- int res = sqlite3_exec (m_db, "BEGIN TRANSACTION;", 0,0,0);
+ int res = sqlite3_exec(m_db, "BEGIN TRANSACTION;", 0, 0, 0);
- res += sqlite3_exec (m_db, "\
+ res += sqlite3_exec(m_db, "\
INSERT INTO SyncLog \
(state_hash, last_update) \
SELECT \
hash(device_name, seq_no), datetime('now') \
FROM (SELECT * FROM SyncNodes \
ORDER BY device_name); \
-", 0,0,0);
+",
+ 0, 0, 0);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, "DbError: " << sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, "DbError: " << sqlite3_errmsg(m_db));
- if (res != SQLITE_OK)
- {
- sqlite3_exec (m_db, "ROLLBACK TRANSACTION;", 0,0,0);
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str (sqlite3_errmsg(m_db)));
- }
+ if (res != SQLITE_OK) {
+ sqlite3_exec(m_db, "ROLLBACK TRANSACTION;", 0, 0, 0);
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str(sqlite3_errmsg(m_db)));
+ }
- sqlite3_int64 rowId = sqlite3_last_insert_rowid (m_db);
+ sqlite3_int64 rowId = sqlite3_last_insert_rowid(m_db);
- sqlite3_stmt *insertStmt;
- res += sqlite3_prepare (m_db, "\
+ sqlite3_stmt* insertStmt;
+ res += sqlite3_prepare(m_db, "\
INSERT INTO SyncStateNodes \
(state_id, device_id, seq_no) \
SELECT ?, device_id, seq_no \
FROM SyncNodes; \
-", -1, &insertStmt, 0);
+",
+ -1, &insertStmt, 0);
- res += sqlite3_bind_int64 (insertStmt, 1, rowId);
- sqlite3_step (insertStmt);
+ res += sqlite3_bind_int64(insertStmt, 1, rowId);
+ sqlite3_step(insertStmt);
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_DONE, "DbError: " << sqlite3_errmsg (m_db));
- if (res != SQLITE_OK)
- {
- sqlite3_exec (m_db, "ROLLBACK TRANSACTION;", 0,0,0);
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str (sqlite3_errmsg(m_db)));
- }
- sqlite3_finalize (insertStmt);
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, "DbError: " << sqlite3_errmsg(m_db));
+ if (res != SQLITE_OK) {
+ sqlite3_exec(m_db, "ROLLBACK TRANSACTION;", 0, 0, 0);
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str(sqlite3_errmsg(m_db)));
+ }
+ sqlite3_finalize(insertStmt);
- sqlite3_stmt *getHashStmt;
- res += sqlite3_prepare (m_db, "\
+ sqlite3_stmt* getHashStmt;
+ res += sqlite3_prepare(m_db, "\
SELECT state_hash FROM SyncLog WHERE state_id = ?\
-", -1, &getHashStmt, 0);
- res += sqlite3_bind_int64 (getHashStmt, 1, rowId);
+",
+ -1, &getHashStmt, 0);
+ res += sqlite3_bind_int64(getHashStmt, 1, rowId);
HashPtr retval;
- int stepRes = sqlite3_step (getHashStmt);
- if (stepRes == SQLITE_ROW)
- {
- retval = make_shared<Hash> (sqlite3_column_blob (getHashStmt, 0),
- sqlite3_column_bytes (getHashStmt, 0));
- }
- else
- {
- sqlite3_exec (m_db, "ROLLBACK TRANSACTION;", 0,0,0);
+ int stepRes = sqlite3_step(getHashStmt);
+ if (stepRes == SQLITE_ROW) {
+ retval =
+ make_shared<Hash>(sqlite3_column_blob(getHashStmt, 0), sqlite3_column_bytes(getHashStmt, 0));
+ }
+ else {
+ sqlite3_exec(m_db, "ROLLBACK TRANSACTION;", 0, 0, 0);
- _LOG_ERROR ("DbError: " << sqlite3_errmsg (m_db));
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Not a valid hash in rememberStateInStateLog"));
- }
- sqlite3_finalize (getHashStmt);
- res += sqlite3_exec (m_db, "COMMIT;", 0,0,0);
+ _LOG_ERROR("DbError: " << sqlite3_errmsg(m_db));
+ BOOST_THROW_EXCEPTION(Error::Db()
+ << errmsg_info_str("Not a valid hash in rememberStateInStateLog"));
+ }
+ sqlite3_finalize(getHashStmt);
+ res += sqlite3_exec(m_db, "COMMIT;", 0, 0, 0);
- if (res != SQLITE_OK)
- {
- sqlite3_exec (m_db, "ROLLBACK TRANSACTION;", 0,0,0);
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Some error with rememberStateInStateLog"));
- }
+ if (res != SQLITE_OK) {
+ sqlite3_exec(m_db, "ROLLBACK TRANSACTION;", 0, 0, 0);
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Some error with rememberStateInStateLog"));
+ }
return retval;
}
sqlite3_int64
-SyncLog::LookupSyncLog (const std::string &stateHash)
+SyncLog::LookupSyncLog(const std::string& stateHash)
{
- return LookupSyncLog (*Hash::FromString (stateHash));
+ return LookupSyncLog(*Hash::FromString(stateHash));
}
sqlite3_int64
-SyncLog::LookupSyncLog (const Hash &stateHash)
+SyncLog::LookupSyncLog(const Hash& stateHash)
{
- sqlite3_stmt *stmt;
- int res = sqlite3_prepare (m_db, "SELECT state_id FROM SyncLog WHERE state_hash = ?",
- -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ int res = sqlite3_prepare(m_db, "SELECT state_id FROM SyncLog WHERE state_hash = ?", -1, &stmt, 0);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Cannot prepare statement"));
- }
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Cannot prepare statement"));
+ }
- res = sqlite3_bind_blob (stmt, 1, stateHash.GetHash (), stateHash.GetHashBytes (), SQLITE_STATIC);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Cannot bind"));
- }
+ res = sqlite3_bind_blob(stmt, 1, stateHash.GetHash(), stateHash.GetHashBytes(), SQLITE_STATIC);
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Cannot bind"));
+ }
sqlite3_int64 row = 0; // something bad
- if (sqlite3_step (stmt) == SQLITE_ROW)
- {
- row = sqlite3_column_int64 (stmt, 0);
- }
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ row = sqlite3_column_int64(stmt, 0);
+ }
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
return row;
}
void
-SyncLog::UpdateDeviceSeqNo (const Ndnx::Name &name, sqlite3_int64 seqNo)
+SyncLog::UpdateDeviceSeqNo(const Ccnx::Name& name, sqlite3_int64 seqNo)
{
- sqlite3_stmt *stmt;
+ sqlite3_stmt* stmt;
// update is performed using trigger
- int res = sqlite3_prepare (m_db, "INSERT INTO SyncNodes (device_name, seq_no) VALUES (?,?);",
- -1, &stmt, 0);
+ int res =
+ sqlite3_prepare(m_db, "INSERT INTO SyncNodes (device_name, seq_no) VALUES (?,?);", -1, &stmt, 0);
- Ndnx::NdnxCharbufPtr nameBuf = name;
- res += sqlite3_bind_blob (stmt, 1, nameBuf->buf (), nameBuf->length (), SQLITE_STATIC);
- res += sqlite3_bind_int64 (stmt, 2, seqNo);
- sqlite3_step (stmt);
+ Ccnx::CcnxCharbufPtr nameBuf = name;
+ res += sqlite3_bind_blob(stmt, 1, nameBuf->buf(), nameBuf->length(), SQLITE_STATIC);
+ res += sqlite3_bind_int64(stmt, 2, seqNo);
+ sqlite3_step(stmt);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Some error with UpdateDeviceSeqNo (name)"));
- }
- sqlite3_finalize (stmt);
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Some error with UpdateDeviceSeqNo (name)"));
+ }
+ sqlite3_finalize(stmt);
}
void
-SyncLog::UpdateLocalSeqNo (sqlite3_int64 seqNo)
+SyncLog::UpdateLocalSeqNo(sqlite3_int64 seqNo)
{
- return UpdateDeviceSeqNo (m_localDeviceId, seqNo);
+ return UpdateDeviceSeqNo(m_localDeviceId, seqNo);
}
void
-SyncLog::UpdateDeviceSeqNo (sqlite3_int64 deviceId, sqlite3_int64 seqNo)
+SyncLog::UpdateDeviceSeqNo(sqlite3_int64 deviceId, sqlite3_int64 seqNo)
{
- sqlite3_stmt *stmt;
+ sqlite3_stmt* stmt;
// update is performed using trigger
- int res = sqlite3_prepare (m_db, "UPDATE SyncNodes SET seq_no=MAX(seq_no,?) WHERE device_id=?;",
- -1, &stmt, 0);
+ int res = sqlite3_prepare(m_db, "UPDATE SyncNodes SET seq_no=MAX(seq_no,?) WHERE device_id=?;",
+ -1, &stmt, 0);
- res += sqlite3_bind_int64 (stmt, 1, seqNo);
- res += sqlite3_bind_int64 (stmt, 2, deviceId);
- sqlite3_step (stmt);
+ res += sqlite3_bind_int64(stmt, 1, seqNo);
+ res += sqlite3_bind_int64(stmt, 2, deviceId);
+ sqlite3_step(stmt);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Some error with UpdateDeviceSeqNo (id)"));
- }
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Some error with UpdateDeviceSeqNo (id)"));
+ }
- _LOG_DEBUG_COND (sqlite3_errcode (m_db) != SQLITE_OK, sqlite3_errmsg (m_db));
+ _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));
- sqlite3_finalize (stmt);
+ sqlite3_finalize(stmt);
}
Name
-SyncLog::LookupLocator (const Name &deviceName)
+SyncLog::LookupLocator(const Name& deviceName)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "SELECT last_known_locator FROM SyncNodes WHERE device_name=?;", -1, &stmt, 0);
- Ndnx::NdnxCharbufPtr nameBuf = deviceName;
- sqlite3_bind_blob (stmt, 1, nameBuf->buf(), nameBuf->length(), SQLITE_STATIC);
- int res = sqlite3_step (stmt);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db, "SELECT last_known_locator FROM SyncNodes WHERE device_name=?;", -1,
+ &stmt, 0);
+ Ccnx::CcnxCharbufPtr nameBuf = deviceName;
+ sqlite3_bind_blob(stmt, 1, nameBuf->buf(), nameBuf->length(), SQLITE_STATIC);
+ int res = sqlite3_step(stmt);
Name locator;
- switch (res)
- {
- case SQLITE_ROW:
- {
- locator = Name((const unsigned char *)sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0));
+ switch (res) {
+ case SQLITE_ROW: {
+ locator =
+ Name((const unsigned char*)sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0));
}
- case SQLITE_DONE: break;
- default:
- BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Error in LookupLocator()"));
+ case SQLITE_DONE:
+ break;
+ default:
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Error in LookupLocator()"));
}
sqlite3_finalize(stmt);
@@ -340,25 +324,26 @@
return locator;
}
-Ndnx::Name
-SyncLog::LookupLocalLocator ()
+Ccnx::Name
+SyncLog::LookupLocalLocator()
{
- return LookupLocator (m_localName);
+ return LookupLocator(m_localName);
}
void
-SyncLog::UpdateLocator(const Name &deviceName, const Name &locator)
+SyncLog::UpdateLocator(const Name& deviceName, const Name& locator)
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "UPDATE SyncNodes SET last_known_locator=?,last_update=datetime('now') WHERE device_name=?;", -1, &stmt, 0);
- Ndnx::NdnxCharbufPtr nameBuf = deviceName;
- Ndnx::NdnxCharbufPtr locatorBuf = locator;
- sqlite3_bind_blob (stmt, 1, locatorBuf->buf(), locatorBuf->length(), SQLITE_STATIC);
- sqlite3_bind_blob (stmt, 2, nameBuf->buf(), nameBuf->length(), SQLITE_STATIC);
- int res = sqlite3_step (stmt);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db,
+ "UPDATE SyncNodes SET last_known_locator=?,last_update=datetime('now') WHERE device_name=?;",
+ -1, &stmt, 0);
+ Ccnx::CcnxCharbufPtr nameBuf = deviceName;
+ Ccnx::CcnxCharbufPtr locatorBuf = locator;
+ sqlite3_bind_blob(stmt, 1, locatorBuf->buf(), locatorBuf->length(), SQLITE_STATIC);
+ sqlite3_bind_blob(stmt, 2, nameBuf->buf(), nameBuf->length(), SQLITE_STATIC);
+ int res = sqlite3_step(stmt);
- if (res != SQLITE_OK && res != SQLITE_DONE)
- {
+ if (res != SQLITE_OK && res != SQLITE_DONE) {
BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Error in UpdateLoactor()"));
}
@@ -366,23 +351,24 @@
}
void
-SyncLog::UpdateLocalLocator (const Ndnx::Name &forwardingHint)
+SyncLog::UpdateLocalLocator(const Ccnx::Name& forwardingHint)
{
- return UpdateLocator (m_localName, forwardingHint);
+ return UpdateLocator(m_localName, forwardingHint);
}
SyncStateMsgPtr
-SyncLog::FindStateDifferences (const std::string &oldHash, const std::string &newHash, bool includeOldSeq)
+SyncLog::FindStateDifferences(const std::string& oldHash, const std::string& newHash,
+ bool includeOldSeq)
{
- return FindStateDifferences (*Hash::FromString (oldHash), *Hash::FromString (newHash), includeOldSeq);
+ return FindStateDifferences(*Hash::FromString(oldHash), *Hash::FromString(newHash), includeOldSeq);
}
SyncStateMsgPtr
-SyncLog::FindStateDifferences (const Hash &oldHash, const Hash &newHash, bool includeOldSeq)
+SyncLog::FindStateDifferences(const Hash& oldHash, const Hash& newHash, bool includeOldSeq)
{
- sqlite3_stmt *stmt;
+ sqlite3_stmt* stmt;
- int res = sqlite3_prepare_v2 (m_db, "\
+ int res = sqlite3_prepare_v2(m_db, "\
SELECT sn.device_name, sn.last_known_locator, s_old.seq_no, s_new.seq_no\
FROM (SELECT * \
FROM SyncStateNodes \
@@ -419,68 +405,62 @@
JOIN SyncNodes sn ON sn.device_id = s_new.device_id \
\
WHERE s_old.seq_no IS NULL \
-", -1, &stmt, 0);
+",
+ -1, &stmt, 0);
- if (res != SQLITE_OK)
- {
- BOOST_THROW_EXCEPTION (Error::Db ()
- << errmsg_info_str ("Some error with FindStateDifferences"));
- }
+ if (res != SQLITE_OK) {
+ BOOST_THROW_EXCEPTION(Error::Db() << errmsg_info_str("Some error with FindStateDifferences"));
+ }
- res += sqlite3_bind_blob (stmt, 1, oldHash.GetHash (), oldHash.GetHashBytes (), SQLITE_STATIC);
- res += sqlite3_bind_blob (stmt, 2, newHash.GetHash (), newHash.GetHashBytes (), SQLITE_STATIC);
+ res += sqlite3_bind_blob(stmt, 1, oldHash.GetHash(), oldHash.GetHashBytes(), SQLITE_STATIC);
+ res += sqlite3_bind_blob(stmt, 2, newHash.GetHash(), newHash.GetHashBytes(), SQLITE_STATIC);
- SyncStateMsgPtr msg = make_shared<SyncStateMsg> ();
+ SyncStateMsgPtr msg = make_shared<SyncStateMsg>();
// sqlite3_trace(m_db, xTrace, NULL);
- while (sqlite3_step (stmt) == SQLITE_ROW)
- {
- SyncState *state = msg->add_state ();
+ while (sqlite3_step(stmt) == SQLITE_ROW) {
+ SyncState* state = msg->add_state();
- // set name
- state->set_name (reinterpret_cast<const char*> (sqlite3_column_blob (stmt, 0)), sqlite3_column_bytes (stmt, 0));
+ // set name
+ state->set_name(reinterpret_cast<const char*>(sqlite3_column_blob(stmt, 0)),
+ sqlite3_column_bytes(stmt, 0));
- // locator is optional, so must check if it is null
- if (sqlite3_column_type(stmt, 1) == SQLITE_BLOB)
- {
- state->set_locator (reinterpret_cast<const char*> (sqlite3_column_blob (stmt, 1)), sqlite3_column_bytes (stmt, 1));
- }
-
- // set old seq
- if (includeOldSeq)
- {
- if (sqlite3_column_type (stmt, 2) == SQLITE_NULL)
- {
- // old seq is zero; we always have an initial action of zero seq
- // other's do not need to fetch this action
- state->set_old_seq(0);
- }
- else
- {
- sqlite3_int64 oldSeqNo = sqlite3_column_int64 (stmt, 2);
- state->set_old_seq(oldSeqNo);
- }
- }
-
- // set new seq
- if (sqlite3_column_type (stmt, 3) == SQLITE_NULL)
- {
- state->set_type (SyncState::DELETE);
- }
- else
- {
- sqlite3_int64 newSeqNo = sqlite3_column_int64 (stmt, 3);
- state->set_type (SyncState::UPDATE);
- state->set_seq (newSeqNo);
- }
-
- // std::cout << sqlite3_column_text (stmt, 0) <<
- // ": from " << sqlite3_column_int64 (stmt, 1) <<
- // " to " << sqlite3_column_int64 (stmt, 2) <<
- // std::endl;
+ // locator is optional, so must check if it is null
+ if (sqlite3_column_type(stmt, 1) == SQLITE_BLOB) {
+ state->set_locator(reinterpret_cast<const char*>(sqlite3_column_blob(stmt, 1)),
+ sqlite3_column_bytes(stmt, 1));
}
- sqlite3_finalize (stmt);
+
+ // set old seq
+ if (includeOldSeq) {
+ if (sqlite3_column_type(stmt, 2) == SQLITE_NULL) {
+ // old seq is zero; we always have an initial action of zero seq
+ // other's do not need to fetch this action
+ state->set_old_seq(0);
+ }
+ else {
+ sqlite3_int64 oldSeqNo = sqlite3_column_int64(stmt, 2);
+ state->set_old_seq(oldSeqNo);
+ }
+ }
+
+ // set new seq
+ if (sqlite3_column_type(stmt, 3) == SQLITE_NULL) {
+ state->set_type(SyncState::DELETE);
+ }
+ else {
+ sqlite3_int64 newSeqNo = sqlite3_column_int64(stmt, 3);
+ state->set_type(SyncState::UPDATE);
+ state->set_seq(newSeqNo);
+ }
+
+ // std::cout << sqlite3_column_text (stmt, 0) <<
+ // ": from " << sqlite3_column_int64 (stmt, 1) <<
+ // " to " << sqlite3_column_int64 (stmt, 2) <<
+ // std::endl;
+ }
+ sqlite3_finalize(stmt);
// sqlite3_trace(m_db, NULL, NULL);
@@ -488,33 +468,30 @@
}
sqlite3_int64
-SyncLog::SeqNo(const Name &name)
+SyncLog::SeqNo(const Name& name)
{
- sqlite3_stmt *stmt;
+ sqlite3_stmt* stmt;
sqlite3_int64 seq = -1;
- sqlite3_prepare_v2 (m_db, "SELECT seq_no FROM SyncNodes WHERE device_name=?;", -1, &stmt, 0);
- Ndnx::NdnxCharbufPtr nameBuf = name;
- sqlite3_bind_blob (stmt, 1, nameBuf->buf (), nameBuf->length (), SQLITE_STATIC);
- if (sqlite3_step (stmt) == SQLITE_ROW)
- {
- seq = sqlite3_column_int64 (stmt, 0);
+ sqlite3_prepare_v2(m_db, "SELECT seq_no FROM SyncNodes WHERE device_name=?;", -1, &stmt, 0);
+ Ccnx::CcnxCharbufPtr nameBuf = name;
+ sqlite3_bind_blob(stmt, 1, nameBuf->buf(), nameBuf->length(), SQLITE_STATIC);
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ seq = sqlite3_column_int64(stmt, 0);
}
return seq;
}
sqlite3_int64
-SyncLog::LogSize ()
+SyncLog::LogSize()
{
- sqlite3_stmt *stmt;
- sqlite3_prepare_v2 (m_db, "SELECT count(*) FROM SyncLog", -1, &stmt, 0);
+ sqlite3_stmt* stmt;
+ sqlite3_prepare_v2(m_db, "SELECT count(*) FROM SyncLog", -1, &stmt, 0);
sqlite3_int64 retval = -1;
- if (sqlite3_step (stmt) == SQLITE_ROW)
- {
- retval = sqlite3_column_int64 (stmt, 0);
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ retval = sqlite3_column_int64(stmt, 0);
}
return retval;
}
-
diff --git a/src/sync-log.hpp b/src/sync-log.hpp
index babbd69..e757a0c 100644
--- a/src/sync-log.hpp
+++ b/src/sync-log.hpp
@@ -22,78 +22,79 @@
#define SYNC_LOG_H
#include "db-helper.hpp"
-#include <sync-state.pb.h>
-#include <ndnx-name.h>
-#include <map>
#include <boost/thread/shared_mutex.hpp>
+#include <ccnx-name.h>
+#include <map>
+#include <sync-state.pb.hpp>
typedef boost::shared_ptr<SyncStateMsg> SyncStateMsgPtr;
class SyncLog : public DbHelper
{
public:
- SyncLog (const boost::filesystem::path &path, const Ndnx::Name &localName);
+ SyncLog(const boost::filesystem::path& path, const Ccnx::Name& localName);
/**
* @brief Get local username
*/
- inline const Ndnx::Name &
- GetLocalName () const;
+ inline const Ccnx::Name&
+ GetLocalName() const;
sqlite3_int64
- GetNextLocalSeqNo (); // side effect: local seq_no will be increased
+ GetNextLocalSeqNo(); // side effect: local seq_no will be increased
// done
void
- UpdateDeviceSeqNo (const Ndnx::Name &name, sqlite3_int64 seqNo);
+ UpdateDeviceSeqNo(const Ccnx::Name& name, sqlite3_int64 seqNo);
void
- UpdateLocalSeqNo (sqlite3_int64 seqNo);
+ UpdateLocalSeqNo(sqlite3_int64 seqNo);
- Ndnx::Name
- LookupLocator (const Ndnx::Name &deviceName);
+ Ccnx::Name
+ LookupLocator(const Ccnx::Name& deviceName);
- Ndnx::Name
- LookupLocalLocator ();
+ Ccnx::Name
+ LookupLocalLocator();
void
- UpdateLocator (const Ndnx::Name &deviceName, const Ndnx::Name &locator);
+ UpdateLocator(const Ccnx::Name& deviceName, const Ccnx::Name& locator);
void
- UpdateLocalLocator (const Ndnx::Name &locator);
+ UpdateLocalLocator(const Ccnx::Name& locator);
// done
/**
* Create an entry in SyncLog and SyncStateNodes corresponding to the current state of SyncNodes
*/
HashPtr
- RememberStateInStateLog ();
+ RememberStateInStateLog();
// done
sqlite3_int64
- LookupSyncLog (const std::string &stateHash);
+ LookupSyncLog(const std::string& stateHash);
// done
sqlite3_int64
- LookupSyncLog (const Hash &stateHash);
+ LookupSyncLog(const Hash& stateHash);
// How difference is exposed will be determined later by the actual protocol
SyncStateMsgPtr
- FindStateDifferences (const std::string &oldHash, const std::string &newHash, bool includeOldSeq = false);
+ FindStateDifferences(const std::string& oldHash, const std::string& newHash,
+ bool includeOldSeq = false);
SyncStateMsgPtr
- FindStateDifferences (const Hash &oldHash, const Hash &newHash, bool includeOldSeq = false);
+ FindStateDifferences(const Hash& oldHash, const Hash& newHash, bool includeOldSeq = false);
//-------- only used in test -----------------
sqlite3_int64
- SeqNo(const Ndnx::Name &name);
+ SeqNo(const Ccnx::Name& name);
sqlite3_int64
- LogSize ();
+ LogSize();
protected:
void
- UpdateDeviceSeqNo (sqlite3_int64 deviceId, sqlite3_int64 seqNo);
+ UpdateDeviceSeqNo(sqlite3_int64 deviceId, sqlite3_int64 seqNo);
protected:
Ndnx::Name m_localName;
@@ -108,8 +109,8 @@
typedef boost::shared_ptr<SyncLog> SyncLogPtr;
-const Ndnx::Name &
-SyncLog::GetLocalName () const
+const Ccnx::Name&
+SyncLog::GetLocalName() const
{
return m_localName;
}
diff --git a/src/sync-state-helper.hpp b/src/sync-state-helper.hpp
index b59af8f..7bcf3f4 100644
--- a/src/sync-state-helper.hpp
+++ b/src/sync-state-helper.hpp
@@ -23,30 +23,27 @@
#include "sync-state.pb.hpp"
-inline std::ostream &
-operator << (std::ostream &os, const SyncStateMsgPtr &msg)
+inline std::ostream&
+operator<<(std::ostream& os, const SyncStateMsgPtr& msg)
{
os << " ===== start Msg ======" << std::endl;
int size = msg->state_size();
- if (size > 0)
- {
+ if (size > 0) {
int index = 0;
- while (index < size)
- {
+ while (index < size) {
SyncState state = msg->state(index);
string strName = state.name();
string strLocator = state.locator();
sqlite3_int64 seq = state.seq();
- os << "Name: " << Ndnx::Name((const unsigned char *)strName.c_str(), strName.size())
- << ", Locator: " << Ndnx::Name((const unsigned char *)strLocator.c_str(), strLocator.size())
+ os << "Name: " << Ccnx::Name((const unsigned char*)strName.c_str(), strName.size())
+ << ", Locator: " << Ccnx::Name((const unsigned char*)strLocator.c_str(), strLocator.size())
<< ", seq: " << seq << std::endl;
- index ++;
+ index++;
}
}
- else
- {
+ else {
os << "Msg size 0" << std::endl;
}
os << " ++++++++ end Msg ++++++++ " << std::endl;