blob: a8396456f7973cf7750360594ef2d6024116b019 [file] [log] [blame]
Alison Craig2a4d5282015-04-10 12:00:02 -06001/** NDN-Atmos: Cataloging Service for distributed data originally developed
2 * for atmospheric science data
3 * Copyright (C) 2015 Colorado State University
4 *
5 * NDN-Atmos is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * NDN-Atmos is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with NDN-Atmos. If not, see <http://www.gnu.org/licenses/>.
17**/
18
19#ifndef ATMOS_PUBLISH_PUBLISH_ADAPTER_HPP
20#define ATMOS_PUBLISH_PUBLISH_ADAPTER_HPP
21
22#include "util/catalog-adapter.hpp"
23#include "util/mysql-util.hpp"
Chengyu Fanc7b87ad2015-07-09 16:44:37 -060024#include <mysql/mysql.h>
Alison Craig2a4d5282015-04-10 12:00:02 -060025
26#include <json/reader.h>
27#include <json/value.h>
28#include <json/writer.h>
29
30#include <ndn-cxx/face.hpp>
31#include <ndn-cxx/interest.hpp>
32#include <ndn-cxx/interest-filter.hpp>
33#include <ndn-cxx/name.hpp>
34#include <ndn-cxx/security/key-chain.hpp>
Chengyu Fanc7b87ad2015-07-09 16:44:37 -060035#include <ndn-cxx/security/validator-config.hpp>
Chengyu Fanf4c747a2015-08-18 13:56:01 -060036#include <ndn-cxx/util/string-helper.hpp>
Alison Craig2a4d5282015-04-10 12:00:02 -060037
Chengyu Fan46398212015-08-11 11:23:13 -060038#include <ChronoSync/socket.hpp>
Alison Craig2a4d5282015-04-10 12:00:02 -060039#include <memory>
40#include <string>
Chengyu Fanb25835b2015-04-28 17:09:35 -060041#include <vector>
42#include <unordered_map>
Chengyu Fan46398212015-08-11 11:23:13 -060043#include <mutex>
Alison Craig2a4d5282015-04-10 12:00:02 -060044
Chengyu Fan71b712b2015-09-09 22:13:56 -060045#include "util/logger.hpp"
46
Alison Craig2a4d5282015-04-10 12:00:02 -060047namespace atmos {
48namespace publish {
Chengyu Fan71b712b2015-09-09 22:13:56 -060049#ifdef HAVE_LOG4CXX
50 INIT_LOGGER("PublishAdapter");
51#endif
Chengyu Fanc7b87ad2015-07-09 16:44:37 -060052
Chengyu Fan46398212015-08-11 11:23:13 -060053#define RETRY_WHEN_TIMEOUT 2
Chengyu Fan46398212015-08-11 11:23:13 -060054
Alison Craig2a4d5282015-04-10 12:00:02 -060055/**
56 * PublishAdapter handles the Publish usecases for the catalog
57 */
58template <typename DatabaseHandler>
Chengyu Fanb25835b2015-04-28 17:09:35 -060059class PublishAdapter : public atmos::util::CatalogAdapter {
Alison Craig2a4d5282015-04-10 12:00:02 -060060public:
61 /**
62 * Constructor
63 *
Chengyu Fancfb80c72015-10-19 16:50:04 -060064 * @param face: Face that will be used for NDN communications
65 * @param keyChain: KeyChain that will be used for data signing
66 * @param syncSocket: ChronoSync socket
Alison Craig2a4d5282015-04-10 12:00:02 -060067 */
Chengyu Fanb25835b2015-04-28 17:09:35 -060068 PublishAdapter(const std::shared_ptr<ndn::Face>& face,
Chengyu Fancfb80c72015-10-19 16:50:04 -060069 const std::shared_ptr<ndn::KeyChain>& keyChain,
70 std::shared_ptr<chronosync::Socket>& syncSocket);
Alison Craig2a4d5282015-04-10 12:00:02 -060071
Alison Craig2a4d5282015-04-10 12:00:02 -060072 virtual
73 ~PublishAdapter();
74
Chengyu Fanb25835b2015-04-28 17:09:35 -060075 /**
76 * Helper function that subscribe to a publish section for the config file
77 */
78 void
79 setConfigFile(util::ConfigFile& config,
Chengyu Fan92440162015-07-09 14:43:31 -060080 const ndn::Name& prefix,
Chengyu Fanf4c747a2015-08-18 13:56:01 -060081 const std::vector<std::string>& nameFields,
82 const std::string& databaseTable);
Chengyu Fanb25835b2015-04-28 17:09:35 -060083
Alison Craig2a4d5282015-04-10 12:00:02 -060084protected:
85 /**
Chengyu Fanb25835b2015-04-28 17:09:35 -060086 * Helper function that configures piblishAdapter instance according to publish section
87 * in config file
88 */
89 void
90 onConfig(const util::ConfigSection& section,
91 bool isDryDun,
92 const std::string& fileName,
93 const ndn::Name& prefix);
94
95 /**
Alison Craig2a4d5282015-04-10 12:00:02 -060096 * Initial "please publish this" Interests
97 *
98 * @param filter: InterestFilter that caused this Interest to be routed
99 * @param interest: Interest that needs to be handled
100 */
101 virtual void
Chengyu Fanb25835b2015-04-28 17:09:35 -0600102 onPublishInterest(const ndn::InterestFilter& filter, const ndn::Interest& interest);
Alison Craig2a4d5282015-04-10 12:00:02 -0600103
Chengyu Fan46398212015-08-11 11:23:13 -0600104 virtual void
105 onTimeout(const ndn::Interest& interest);
106
Alison Craig2a4d5282015-04-10 12:00:02 -0600107 /**
108 * Data containing the actual thing we need to publish
109 *
110 * @param interest: Interest that caused this Data to be routed
111 * @param data: Data that needs to be handled
112 */
113 virtual void
Chengyu Fanb25835b2015-04-28 17:09:35 -0600114 onPublishedData(const ndn::Interest& interest, const ndn::Data& data);
Alison Craig2a4d5282015-04-10 12:00:02 -0600115
Chengyu Fanb25835b2015-04-28 17:09:35 -0600116 /**
Chengyu Fan46398212015-08-11 11:23:13 -0600117 * Helper function to initialize the DatabaseHandler
Chengyu Fanb25835b2015-04-28 17:09:35 -0600118 */
119 void
Chengyu Fan46398212015-08-11 11:23:13 -0600120 initializeDatabase(const util::ConnectionDetails& databaseId);
Alison Craig2a4d5282015-04-10 12:00:02 -0600121
Chengyu Fan31737f12016-01-12 21:08:50 -0700122 void
123 closeDatabaseHandler();
124
Chengyu Fanb25835b2015-04-28 17:09:35 -0600125 /**
126 * Helper function that sets filters to make the adapter work
127 */
128 void
129 setFilters();
130
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600131 void
132 setCatalogId();
133
Chengyu Fanc7b87ad2015-07-09 16:44:37 -0600134 /**
135 * Function to validate publication changes against the trust model, which is, all file
136 * names must be under the publisher's prefix. This function should be called by a callback
137 * function invoked by validator
138 *
139 * @param data: received data from the publisher
140 */
141 bool
142 validatePublicationChanges(const std::shared_ptr<const ndn::Data>& data);
143
Chengyu Fan46398212015-08-11 11:23:13 -0600144 /**
145 * Helper function that processes the sync update
146 *
147 * @param updates: vector that contains all the missing data information
148 */
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600149 void
150 processSyncUpdate(const std::vector<chronosync::MissingDataInfo>& updates);
Chengyu Fan46398212015-08-11 11:23:13 -0600151
152 /**
153 * Helper function that processes the update data
154 *
155 * @param data: shared pointer for the fetched update data
156 */
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600157 void
Chengyu Fan612f11c2015-09-23 16:24:47 -0600158 processUpdateData(const std::shared_ptr<const ndn::Data>& data);
Chengyu Fan46398212015-08-11 11:23:13 -0600159
160 /**
161 * Helper function that add data to or remove data from database
162 *
163 * @param sql: sql string to do the add or remove jobs
164 * @param op: enum value indicates the database operation, could be REMOVE, ADD
165 */
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600166 virtual void
167 operateDatabase(const std::string& sql,
168 util::DatabaseOperation op);
Chengyu Fan46398212015-08-11 11:23:13 -0600169
170 /**
171 * Helper function that parses jsonValue to generate sql string, return value indicates
172 * if it is successfully
173 *
174 * @param sqlString: streamstream to save the sql string
175 * @param jsonValue: Json value that contains the update information
176 * @param op: enum value indicates the database operation, could be REMOVE, ADD
177 */
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600178 bool
179 json2Sql(std::stringstream& sqlString,
180 Json::Value& jsonValue,
181 util::DatabaseOperation op);
Chengyu Fan46398212015-08-11 11:23:13 -0600182
183 /**
184 * Helper function to generate sql string based on file name, return value indicates
185 * if it is successfully
186 *
187 * @param sqlString: streamstream to save the sql string
188 * @param fileName: ndn uri string for a file name
189 */
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600190 bool
191 name2Fields(std::stringstream& sqlstring,
192 std::string& fileName);
Chengyu Fan46398212015-08-11 11:23:13 -0600193
194 /**
195 * Check the local database for the latest sequence number for a ChronoSync update
196 *
197 * @param update: the MissingDataInfo object
198 */
199 chronosync::SeqNo
200 getLatestSeqNo(const chronosync::MissingDataInfo& update);
201
202 /**
203 * Update the local database with the update message
204 *
205 * @param update: the MissingDataInfo object
206 */
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600207 void
208 renewUpdateInformation(const chronosync::MissingDataInfo& update);
Chengyu Fan46398212015-08-11 11:23:13 -0600209
210 /**
211 * Insert the update message into the local database
212 *
213 * @param update: the MissingDataInfo object
214 */
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600215 void
216 addUpdateInformation(const chronosync::MissingDataInfo& update);
Chengyu Fan46398212015-08-11 11:23:13 -0600217
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600218 void
219 onFetchUpdateDataTimeout(const ndn::Interest& interest);
Chengyu Fan46398212015-08-11 11:23:13 -0600220
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600221 void
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600222 onValidationFailed(const std::shared_ptr<const ndn::Data>& data,
223 const std::string& failureInfo);
224
225 void
226 validatePublishedDataPaylod(const std::shared_ptr<const ndn::Data>& data);
Chengyu Fan46398212015-08-11 11:23:13 -0600227
Chengyu Fanb25835b2015-04-28 17:09:35 -0600228protected:
229 typedef std::unordered_map<ndn::Name, const ndn::RegisteredPrefixId*> RegisteredPrefixList;
230 // Prefix for ChronoSync
231 ndn::Name m_syncPrefix;
232 // Handle to the Catalog's database
233 std::shared_ptr<DatabaseHandler> m_databaseHandler;
Chengyu Fanc7b87ad2015-07-09 16:44:37 -0600234 std::unique_ptr<ndn::ValidatorConfig> m_publishValidator;
Chengyu Fanb25835b2015-04-28 17:09:35 -0600235 RegisteredPrefixList m_registeredPrefixList;
Chengyu Fancfb80c72015-10-19 16:50:04 -0600236 std::shared_ptr<chronosync::Socket>& m_socket; // SyncSocket
237 std::vector<std::string> m_tableColumns;
Chengyu Fan46398212015-08-11 11:23:13 -0600238 // mutex to control critical sections
239 std::mutex m_mutex;
Chengyu Fan46398212015-08-11 11:23:13 -0600240 // TODO: create thread for each request, and the variables below should be within the thread
241 bool m_mustBeFresh;
242 bool m_isFinished;
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600243 ndn::Name m_catalogId;
Alison Craig2a4d5282015-04-10 12:00:02 -0600244};
245
Alison Craig2a4d5282015-04-10 12:00:02 -0600246
Chengyu Fanb25835b2015-04-28 17:09:35 -0600247template <typename DatabaseHandler>
248PublishAdapter<DatabaseHandler>::PublishAdapter(const std::shared_ptr<ndn::Face>& face,
Chengyu Fancfb80c72015-10-19 16:50:04 -0600249 const std::shared_ptr<ndn::KeyChain>& keyChain,
250 std::shared_ptr<chronosync::Socket>& syncSocket)
Chengyu Fanb25835b2015-04-28 17:09:35 -0600251 : util::CatalogAdapter(face, keyChain)
Chengyu Fancfb80c72015-10-19 16:50:04 -0600252 , m_socket(syncSocket)
Chengyu Fan46398212015-08-11 11:23:13 -0600253 , m_mustBeFresh(true)
254 , m_isFinished(false)
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600255 , m_catalogId("catalogIdPlaceHolder")
Chengyu Fanb25835b2015-04-28 17:09:35 -0600256{
257}
258
259template <typename DatabaseHandler>
260void
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600261PublishAdapter<DatabaseHandler>::setCatalogId()
262{
263 // empty
264}
265
266template <>
267void
Chengyu Fan31737f12016-01-12 21:08:50 -0700268PublishAdapter<ConnectionPool_T>::setCatalogId()
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600269{
270 // use public key digest as the catalog ID
271 ndn::Name keyId;
272 if (m_signingId.empty()) {
273 keyId = m_keyChain->getDefaultKeyNameForIdentity(m_keyChain->getDefaultIdentity());
274 } else {
275 keyId = m_keyChain->getDefaultKeyNameForIdentity(m_signingId);
276 }
277
278 std::shared_ptr<ndn::PublicKey> pKey = m_keyChain->getPib().getPublicKey(keyId);
279 ndn::Block keyDigest = pKey->computeDigest();
280 m_catalogId.clear();
281 m_catalogId.append(ndn::toHex(*keyDigest.getBuffer()));
282}
283
284template <typename DatabaseHandler>
285void
Chengyu Fanb25835b2015-04-28 17:09:35 -0600286PublishAdapter<DatabaseHandler>::setFilters()
287{
288 ndn::Name publishPrefix = ndn::Name(m_prefix).append("publish");
Chengyu Fan46398212015-08-11 11:23:13 -0600289 m_registeredPrefixList[publishPrefix] =
290 m_face->setInterestFilter(publishPrefix,
291 bind(&PublishAdapter<DatabaseHandler>::onPublishInterest,
292 this, _1, _2),
293 bind(&publish::PublishAdapter<DatabaseHandler>::onRegisterSuccess,
294 this, _1),
295 bind(&publish::PublishAdapter<DatabaseHandler>::onRegisterFailure,
296 this, _1, _2));
297
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600298 ndn::Name catalogSync = ndn::Name(m_prefix).append("sync").append(m_catalogId);
Chengyu Fan46398212015-08-11 11:23:13 -0600299 m_socket.reset(new chronosync::Socket(m_syncPrefix,
300 catalogSync,
301 *m_face,
302 bind(&PublishAdapter<DatabaseHandler>::processSyncUpdate,
303 this, _1)));
Alison Craig2a4d5282015-04-10 12:00:02 -0600304}
305
306template <typename DatabaseHandler>
Chengyu Fan31737f12016-01-12 21:08:50 -0700307void
308PublishAdapter<DatabaseHandler>::closeDatabaseHandler()
309{
310}
311
312template <>
313void
314PublishAdapter<ConnectionPool_T>::closeDatabaseHandler()
315{
316 ConnectionPool_stop(*m_databaseHandler);
317}
318
319template <typename DatabaseHandler>
Alison Craig2a4d5282015-04-10 12:00:02 -0600320PublishAdapter<DatabaseHandler>::~PublishAdapter()
321{
Chengyu Fanb25835b2015-04-28 17:09:35 -0600322 for (const auto& itr : m_registeredPrefixList) {
323 if (static_cast<bool>(itr.second))
324 m_face->unsetInterestFilter(itr.second);
325 }
Chengyu Fan31737f12016-01-12 21:08:50 -0700326
327 closeDatabaseHandler();
Alison Craig2a4d5282015-04-10 12:00:02 -0600328}
329
330template <typename DatabaseHandler>
331void
Chengyu Fanb25835b2015-04-28 17:09:35 -0600332PublishAdapter<DatabaseHandler>::setConfigFile(util::ConfigFile& config,
Chengyu Fan92440162015-07-09 14:43:31 -0600333 const ndn::Name& prefix,
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600334 const std::vector<std::string>& nameFields,
335 const std::string& databaseTable)
Chengyu Fanb25835b2015-04-28 17:09:35 -0600336{
Chengyu Fan92440162015-07-09 14:43:31 -0600337 m_nameFields = nameFields;
Chengyu Fancfb80c72015-10-19 16:50:04 -0600338
339 //initialize m_tableColumns
340 m_tableColumns = nameFields;
341 auto it = m_tableColumns.begin();
342 it = m_tableColumns.insert(it, std::string("name"));
343 it = m_tableColumns.insert(it, std::string("sha256"));
344
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600345 m_databaseTable = databaseTable;
Chengyu Fanb25835b2015-04-28 17:09:35 -0600346 config.addSectionHandler("publishAdapter",
347 bind(&PublishAdapter<DatabaseHandler>::onConfig, this,
348 _1, _2, _3, prefix));
349}
350
351template <typename DatabaseHandler>
352void
353PublishAdapter<DatabaseHandler>::onConfig(const util::ConfigSection& section,
354 bool isDryRun,
355 const std::string& filename,
356 const ndn::Name& prefix)
357{
358 using namespace util;
359 if (isDryRun) {
360 return;
361 }
362
363 std::string signingId, dbServer, dbName, dbUser, dbPasswd;
364 std::string syncPrefix("ndn:/ndn-atmos/broadcast/chronosync");
365
366 for (auto item = section.begin();
367 item != section.end();
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600368 ++item)
Chengyu Fanb25835b2015-04-28 17:09:35 -0600369 {
370 if (item->first == "signingId") {
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600371 signingId = item->second.get_value<std::string>();
Chengyu Fanb25835b2015-04-28 17:09:35 -0600372 if (signingId.empty()) {
373 throw Error("Invalid value for \"signingId\""
Chengyu Fancfb80c72015-10-19 16:50:04 -0600374 " in \"publish\" section");
Chengyu Fanb25835b2015-04-28 17:09:35 -0600375 }
376 }
Chengyu Fanc7b87ad2015-07-09 16:44:37 -0600377 else if (item->first == "security") {
378 // when use, the validator must specify the callback func to handle the validated data
379 // it should be called when the Data packet that contains the published file names is received
380 m_publishValidator.reset(new ndn::ValidatorConfig(m_face.get()));
381 m_publishValidator->load(item->second, filename);
382 }
Chengyu Fanb25835b2015-04-28 17:09:35 -0600383 else if (item->first == "database") {
384 const util::ConfigSection& databaseSection = item->second;
385 for (auto subItem = databaseSection.begin();
386 subItem != databaseSection.end();
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600387 ++subItem) {
Chengyu Fanb25835b2015-04-28 17:09:35 -0600388 if (subItem->first == "dbServer") {
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600389 dbServer = subItem->second.get_value<std::string>();
Chengyu Fanb25835b2015-04-28 17:09:35 -0600390 }
391 if (subItem->first == "dbName") {
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600392 dbName = subItem->second.get_value<std::string>();
Chengyu Fanb25835b2015-04-28 17:09:35 -0600393 }
394 if (subItem->first == "dbUser") {
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600395 dbUser = subItem->second.get_value<std::string>();
Chengyu Fanb25835b2015-04-28 17:09:35 -0600396 }
397 if (subItem->first == "dbPasswd") {
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600398 dbPasswd = subItem->second.get_value<std::string>();
Chengyu Fanb25835b2015-04-28 17:09:35 -0600399 }
400 }
Chengyu Fancfb80c72015-10-19 16:50:04 -0600401
402 // Items below must not be empty
403 if (dbServer.empty()){
404 throw Error("Invalid value for \"dbServer\""
405 " in \"publish\" section");
406 }
407 if (dbName.empty()){
408 throw Error("Invalid value for \"dbName\""
409 " in \"publish\" section");
410 }
411 if (dbUser.empty()){
412 throw Error("Invalid value for \"dbUser\""
413 " in \"publish\" section");
414 }
415 if (dbPasswd.empty()){
416 throw Error("Invalid value for \"dbPasswd\""
417 " in \"publish\" section");
418 }
Chengyu Fanb25835b2015-04-28 17:09:35 -0600419 }
420 else if (item->first == "sync") {
421 const util::ConfigSection& synSection = item->second;
422 for (auto subItem = synSection.begin();
423 subItem != synSection.end();
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600424 ++subItem) {
Chengyu Fanb25835b2015-04-28 17:09:35 -0600425 if (subItem->first == "prefix") {
Chengyu Fancfb80c72015-10-19 16:50:04 -0600426 syncPrefix = subItem->second.get_value<std::string>();
Chengyu Fanb25835b2015-04-28 17:09:35 -0600427 if (syncPrefix.empty()){
428 throw Error("Invalid value for \"prefix\""
Chengyu Fancfb80c72015-10-19 16:50:04 -0600429 " in \"publish\\sync\" section");
Chengyu Fanb25835b2015-04-28 17:09:35 -0600430 }
431 }
432 // todo: parse the sync_security section
433 }
434 }
435 }
436
437 m_prefix = prefix;
438 m_signingId = ndn::Name(signingId);
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600439 setCatalogId();
440
Chengyu Fan71b712b2015-09-09 22:13:56 -0600441 m_syncPrefix = syncPrefix;
Chengyu Fanb25835b2015-04-28 17:09:35 -0600442 util::ConnectionDetails mysqlId(dbServer, dbUser, dbPasswd, dbName);
443
Chengyu Fan46398212015-08-11 11:23:13 -0600444 initializeDatabase(mysqlId);
Chengyu Fanb25835b2015-04-28 17:09:35 -0600445 setFilters();
446}
447
448template <typename DatabaseHandler>
449void
Chengyu Fan46398212015-08-11 11:23:13 -0600450PublishAdapter<DatabaseHandler>::initializeDatabase(const util::ConnectionDetails& databaseId)
Chengyu Fanb25835b2015-04-28 17:09:35 -0600451{
452 //empty
453}
454
455template <>
456void
Chengyu Fan31737f12016-01-12 21:08:50 -0700457PublishAdapter<ConnectionPool_T>::initializeDatabase(const util::ConnectionDetails& databaseId)
Chengyu Fanb25835b2015-04-28 17:09:35 -0600458{
Chengyu Fan31737f12016-01-12 21:08:50 -0700459 m_databaseHandler = zdbConnectionSetup(databaseId);
Chengyu Fanb25835b2015-04-28 17:09:35 -0600460
Chengyu Fan31737f12016-01-12 21:08:50 -0700461 Connection_T conn = ConnectionPool_getConnection(*m_databaseHandler);
Chengyu Fan46398212015-08-11 11:23:13 -0600462
Chengyu Fan31737f12016-01-12 21:08:50 -0700463 if (conn != NULL) {
464
Chengyu Fan46398212015-08-11 11:23:13 -0600465 // Ignore errors (when database already exists, errors are expected)
466 std::string createSyncTable =
467 "CREATE TABLE `chronosync_update_info` (\
468 `id` int(11) NOT NULL AUTO_INCREMENT, \
469 `session_name` varchar(1000) NOT NULL, \
470 `seq_num` int(11) NOT NULL, \
471 PRIMARY KEY (`id`), \
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600472 UNIQUE KEY `id_UNIQUE` (`id`) \
Chengyu Fan46398212015-08-11 11:23:13 -0600473 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
474
Chengyu Fan31737f12016-01-12 21:08:50 -0700475 // must use libzdb's try-catch style
476 TRY {
477 Connection_execute(conn,
478 reinterpret_cast<const char*>(createSyncTable.c_str()), createSyncTable.size());
479 }
480 CATCH(SQLException) {
481 _LOG_ERROR(Connection_getLastError(conn));
482 }
483 END_TRY;
Chengyu Fan46398212015-08-11 11:23:13 -0600484
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600485 // create SQL string for table creation, id, sha256, and name are columns that we need
486 std::stringstream ss;
487 ss << "CREATE TABLE `" << m_databaseTable << "` (\
488 `id` int(100) NOT NULL AUTO_INCREMENT, \
489 `sha256` varchar(64) NOT NULL, \
490 `name` varchar(1000) NOT NULL,";
491 for (size_t i = 0; i < m_nameFields.size(); i++) {
492 ss << "`" << m_nameFields[i] << "` varchar(100) NOT NULL, ";
493 }
494 ss << "PRIMARY KEY (`id`), UNIQUE KEY `sha256` (`sha256`)\
Chengyu Fan46398212015-08-11 11:23:13 -0600495 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
496
Chengyu Fan31737f12016-01-12 21:08:50 -0700497 // must use libzdb's try-catch style
498 TRY {
499 Connection_execute(conn,
500 reinterpret_cast<const char*>(ss.str().c_str()), ss.str().size());
501 }
502 CATCH(SQLException) {
503 _LOG_ERROR(Connection_getLastError(conn));
504 }
505 END_TRY;
Chengyu Fancfb80c72015-10-19 16:50:04 -0600506
Chengyu Fan31737f12016-01-12 21:08:50 -0700507 Connection_close(conn);
Chengyu Fan46398212015-08-11 11:23:13 -0600508 }
509 else {
510 throw Error("cannot connect to the Database");
511 }
Chengyu Fanb25835b2015-04-28 17:09:35 -0600512}
513
514template <typename DatabaseHandler>
515void
516PublishAdapter<DatabaseHandler>::onPublishInterest(const ndn::InterestFilter& filter,
517 const ndn::Interest& interest)
Alison Craig2a4d5282015-04-10 12:00:02 -0600518{
Chengyu Fan71b712b2015-09-09 22:13:56 -0600519 _LOG_DEBUG(">> PublishAdapter::onPublishInterest");
520
Chengyu Fan46398212015-08-11 11:23:13 -0600521 // Example Interest : /cmip5/publish/<uri>/<nonce>
Chengyu Fan71b712b2015-09-09 22:13:56 -0600522 _LOG_DEBUG(interest.getName().toUri());
Chengyu Fan46398212015-08-11 11:23:13 -0600523
524 //send back ACK
Chengyu Fan71b712b2015-09-09 22:13:56 -0600525 char buf[] = "ACK";
Chengyu Fan46398212015-08-11 11:23:13 -0600526 std::shared_ptr<ndn::Data> data = std::make_shared<ndn::Data>(interest.getName());
527 data->setFreshnessPeriod(ndn::time::milliseconds(10)); // 10 msec
528 data->setContent(reinterpret_cast<const uint8_t*>(buf), strlen(buf));
529 m_keyChain->sign(*data);
530 m_face->put(*data);
Chengyu Fan71b712b2015-09-09 22:13:56 -0600531
Chengyu Fancfb80c72015-10-19 16:50:04 -0600532 _LOG_DEBUG("Ack interest : " << interest.getName().toUri());
Chengyu Fan46398212015-08-11 11:23:13 -0600533
534
535 //TODO: if already in catalog, what do we do?
536 //ask for content
537 ndn::Name interestStr = interest.getName().getSubName(m_prefix.size()+1);
538 size_t m_nextSegment = 0;
539 std::shared_ptr<ndn::Interest> retrieveInterest =
540 std::make_shared<ndn::Interest>(interestStr.appendSegment(m_nextSegment));
541 retrieveInterest->setInterestLifetime(ndn::time::milliseconds(4000));
542 retrieveInterest->setMustBeFresh(m_mustBeFresh);
543 m_face->expressInterest(*retrieveInterest,
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600544 bind(&PublishAdapter<DatabaseHandler>::onPublishedData,
Chengyu Fan46398212015-08-11 11:23:13 -0600545 this,_1, _2),
Chengyu Fan71b712b2015-09-09 22:13:56 -0600546 bind(&publish::PublishAdapter<DatabaseHandler>::onTimeout, this, _1));
547
548 _LOG_DEBUG("Expressing Interest " << retrieveInterest->toUri());
549 _LOG_DEBUG("<< PublishAdapter::onPublishInterest");
Chengyu Fan46398212015-08-11 11:23:13 -0600550}
551
552template <typename DatabaseHandler>
553void
554PublishAdapter<DatabaseHandler>::onTimeout(const ndn::Interest& interest)
555{
Chengyu Fancfb80c72015-10-19 16:50:04 -0600556 _LOG_ERROR(interest.getName() << "timed out");
Alison Craig2a4d5282015-04-10 12:00:02 -0600557}
558
559template <typename DatabaseHandler>
560void
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600561PublishAdapter<DatabaseHandler>::onValidationFailed(const std::shared_ptr<const ndn::Data>& data,
562 const std::string& failureInfo)
563{
Chengyu Fancfb80c72015-10-19 16:50:04 -0600564 _LOG_ERROR(data->getName() << " validation failed: " << failureInfo);
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600565}
566
567template <typename DatabaseHandler>
568void
Chengyu Fanb25835b2015-04-28 17:09:35 -0600569PublishAdapter<DatabaseHandler>::onPublishedData(const ndn::Interest& interest,
570 const ndn::Data& data)
Alison Craig2a4d5282015-04-10 12:00:02 -0600571{
Chengyu Fan71b712b2015-09-09 22:13:56 -0600572 _LOG_DEBUG(">> PublishAdapter::onPublishedData");
Chengyu Fancfb80c72015-10-19 16:50:04 -0600573 _LOG_DEBUG("Recv data : " << data.getName());
Chengyu Fan46398212015-08-11 11:23:13 -0600574 if (data.getContent().empty()) {
575 return;
576 }
Chengyu Fan612f11c2015-09-23 16:24:47 -0600577 if (m_publishValidator != nullptr) {
578 m_publishValidator->validate(data,
579 bind(&PublishAdapter<DatabaseHandler>::validatePublishedDataPaylod, this, _1),
580 bind(&PublishAdapter<DatabaseHandler>::onValidationFailed, this, _1, _2));
581 }
582 else {
583 std::shared_ptr<ndn::Data> dataPtr = std::make_shared<ndn::Data>(data);
584 validatePublishedDataPaylod(dataPtr);
585 }
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600586}
Chengyu Fan46398212015-08-11 11:23:13 -0600587
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600588template <typename DatabaseHandler>
589void
Chengyu Fan612f11c2015-09-23 16:24:47 -0600590PublishAdapter<DatabaseHandler>::validatePublishedDataPaylod(const std::shared_ptr<const ndn::Data>& data)
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600591{
Chengyu Fan71b712b2015-09-09 22:13:56 -0600592 _LOG_DEBUG(">> PublishAdapter::onValidatePublishedDataPayload");
593
Chengyu Fan46398212015-08-11 11:23:13 -0600594 // validate published data payload, if failed, return
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600595 if (!validatePublicationChanges(data)) {
Chengyu Fancfb80c72015-10-19 16:50:04 -0600596 _LOG_ERROR("Data validation failed : " << data->getName());
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600597 const std::string payload(reinterpret_cast<const char*>(data->getContent().value()),
598 data->getContent().value_size());
Chengyu Fan71b712b2015-09-09 22:13:56 -0600599 _LOG_DEBUG(payload);
Chengyu Fan46398212015-08-11 11:23:13 -0600600 return;
601 }
602
603 // todo: return value to indicate if the insertion succeeds
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600604 processUpdateData(data);
Chengyu Fan46398212015-08-11 11:23:13 -0600605
606 // ideally, data should not be stale?
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600607 m_socket->publishData(data->getContent(), ndn::time::seconds(3600));
Chengyu Fan46398212015-08-11 11:23:13 -0600608
609 // if this is not the final block, continue to fetch the next one
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600610 const ndn::name::Component& finalBlockId = data->getMetaInfo().getFinalBlockId();
611 if (finalBlockId == data->getName()[-1]) {
Chengyu Fan46398212015-08-11 11:23:13 -0600612 m_isFinished = true;
613 }
614 //else, get the next segment
615 if (!m_isFinished) {
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600616 ndn::Name nextInterestName = data->getName().getPrefix(-1);
617 uint64_t incomingSegment = data->getName()[-1].toSegment();
618 incomingSegment++;
Chengyu Fan71b712b2015-09-09 22:13:56 -0600619
620 _LOG_DEBUG("Next Interest Name " << nextInterestName << " Segment " << incomingSegment);
621
Chengyu Fan46398212015-08-11 11:23:13 -0600622 std::shared_ptr<ndn::Interest> nextInterest =
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600623 std::make_shared<ndn::Interest>(nextInterestName.appendSegment(incomingSegment));
Chengyu Fan46398212015-08-11 11:23:13 -0600624 nextInterest->setInterestLifetime(ndn::time::milliseconds(4000));
625 nextInterest->setMustBeFresh(m_mustBeFresh);
626 m_face->expressInterest(*nextInterest,
627 bind(&publish::PublishAdapter<DatabaseHandler>::onPublishedData,
628 this,_1, _2),
629 bind(&publish::PublishAdapter<DatabaseHandler>::onTimeout,
630 this, _1));
631 }
632}
633
634template <typename DatabaseHandler>
635void
Chengyu Fan612f11c2015-09-23 16:24:47 -0600636PublishAdapter<DatabaseHandler>::processUpdateData(const std::shared_ptr<const ndn::Data>& data)
Chengyu Fan46398212015-08-11 11:23:13 -0600637{
Chengyu Fan71b712b2015-09-09 22:13:56 -0600638 _LOG_DEBUG(">> PublishAdapter::processUpdateData");
639
Chengyu Fan46398212015-08-11 11:23:13 -0600640 const std::string payload(reinterpret_cast<const char*>(data->getContent().value()),
641 data->getContent().value_size());
642
643 if (payload.length() <= 0) {
644 return;
645 }
646
647 // the data payload must be JSON format
648 // http://redmine.named-data.net/projects/ndn-atmos/wiki/Sync
649 Json::Value parsedFromPayload;
650 Json::Reader jsonReader;
651 if (!jsonReader.parse(payload, parsedFromPayload)) {
652 // todo: logging events
Chengyu Fan71b712b2015-09-09 22:13:56 -0600653 _LOG_DEBUG("Fail to parse the update data");
Chengyu Fan46398212015-08-11 11:23:13 -0600654 return;
655 }
Chengyu Fan71b712b2015-09-09 22:13:56 -0600656
Chengyu Fan46398212015-08-11 11:23:13 -0600657 std::stringstream ss;
658 if (json2Sql(ss, parsedFromPayload, util::ADD)) {
Chengyu Fan46398212015-08-11 11:23:13 -0600659 // todo: before use, check if the connection is not NULL
660 // we may need to use lock here to ensure thread safe
661 operateDatabase(ss.str(), util::ADD);
662 }
663
664 ss.str("");
665 ss.clear();
666 if (json2Sql(ss, parsedFromPayload, util::REMOVE)) {
Chengyu Fan46398212015-08-11 11:23:13 -0600667 operateDatabase(ss.str(), util::REMOVE);
668 }
669}
670
671template <typename DatabaseHandler>
672chronosync::SeqNo
673PublishAdapter<DatabaseHandler>::getLatestSeqNo(const chronosync::MissingDataInfo& update)
674{
675 // empty
676 return 0;
677}
678
679template <>
680chronosync::SeqNo
Chengyu Fan31737f12016-01-12 21:08:50 -0700681PublishAdapter<ConnectionPool_T>::getLatestSeqNo(const chronosync::MissingDataInfo& update)
Chengyu Fan46398212015-08-11 11:23:13 -0600682{
Chengyu Fan71b712b2015-09-09 22:13:56 -0600683 _LOG_DEBUG(">> PublishAdapter::getLatestSeqNo");
684
Chengyu Fan31737f12016-01-12 21:08:50 -0700685 Connection_T conn = ConnectionPool_getConnection(*m_databaseHandler);
Chengyu Fan71b712b2015-09-09 22:13:56 -0600686
Chengyu Fan31737f12016-01-12 21:08:50 -0700687 if (!conn) {
688 _LOG_DEBUG("No available database connections");
689 return 0;
Chengyu Fan46398212015-08-11 11:23:13 -0600690 }
Chengyu Fan46398212015-08-11 11:23:13 -0600691
Chengyu Fan31737f12016-01-12 21:08:50 -0700692 PreparedStatement_T ps4SeqNum =
693 Connection_prepareStatement(conn,
694 "SELECT seq_num FROM chronosync_update_info WHERE session_name = ?");
695 PreparedStatement_setString(ps4SeqNum, 1, update.session.toUri().c_str());
696 ResultSet_T res4SeqNum;
697 TRY {
698 res4SeqNum = PreparedStatement_executeQuery(ps4SeqNum);
Chengyu Fan46398212015-08-11 11:23:13 -0600699 }
Chengyu Fan31737f12016-01-12 21:08:50 -0700700 CATCH(SQLException) {
701 _LOG_ERROR(Connection_getLastError(conn));
702 }
703 END_TRY;
704
705 while (ResultSet_next(res4SeqNum)) {
706 return ResultSet_getInt(res4SeqNum, 1);
707 }
708
709 Connection_close(conn);
710
Chengyu Fan46398212015-08-11 11:23:13 -0600711 return 0;
712}
713
714template <typename DatabaseHandler>
715void
716PublishAdapter<DatabaseHandler>::renewUpdateInformation(const chronosync::MissingDataInfo& update)
717{
718 //empty
719}
720
721template <>
722void
Chengyu Fan31737f12016-01-12 21:08:50 -0700723PublishAdapter<ConnectionPool_T>::renewUpdateInformation(const chronosync::MissingDataInfo& update)
Chengyu Fan46398212015-08-11 11:23:13 -0600724{
Chengyu Fan31737f12016-01-12 21:08:50 -0700725 Connection_T conn = ConnectionPool_getConnection(*m_databaseHandler);
Chengyu Fan71b712b2015-09-09 22:13:56 -0600726
Chengyu Fan31737f12016-01-12 21:08:50 -0700727 if (!conn) {
728 _LOG_DEBUG("No available database connections");
729 return;
730 }
731
732 PreparedStatement_T ps4UpdateSeqNum =
733 Connection_prepareStatement(conn,
734 "UPDATE chronosync_update_info SET seq_num = ? WHERE session_name = ?");
735 PreparedStatement_setLLong(ps4UpdateSeqNum, 1, update.high);
736 PreparedStatement_setString(ps4UpdateSeqNum, 1, update.session.toUri().c_str());
737
738 TRY {
739 PreparedStatement_execute(ps4UpdateSeqNum);
740 }
741 CATCH(SQLException) {
742 _LOG_ERROR(Connection_getLastError(conn));
743 }
744 END_TRY;
745
746 Connection_close(conn);
747
Chengyu Fan46398212015-08-11 11:23:13 -0600748}
749
750template <typename DatabaseHandler>
751void
752PublishAdapter<DatabaseHandler>::addUpdateInformation(const chronosync::MissingDataInfo& update)
753{
754 //empty
755}
756
757template <>
758void
Chengyu Fan31737f12016-01-12 21:08:50 -0700759PublishAdapter<ConnectionPool_T>::addUpdateInformation(const chronosync::MissingDataInfo& update)
Chengyu Fan46398212015-08-11 11:23:13 -0600760{
Chengyu Fan31737f12016-01-12 21:08:50 -0700761 Connection_T conn = ConnectionPool_getConnection(*m_databaseHandler);
Chengyu Fan46398212015-08-11 11:23:13 -0600762
Chengyu Fan31737f12016-01-12 21:08:50 -0700763 if (!conn) {
764 _LOG_DEBUG("No available database connections");
765 return;
766 }
767
768 PreparedStatement_T ps4UpdateChronosync =
769 Connection_prepareStatement(conn, "INSERT INTO chronosync_update_info (session_name, seq_num) VALUES (?, ?)");
770
771 PreparedStatement_setString(ps4UpdateChronosync, 1, update.session.toUri().c_str());
772 PreparedStatement_setLLong(ps4UpdateChronosync, 1, update.high);
773
774 TRY {
775 PreparedStatement_execute(ps4UpdateChronosync);
776 }
777 CATCH(SQLException) {
778 _LOG_ERROR(Connection_getLastError(conn));
779 }
780 END_TRY;
781
782 Connection_close(conn);
783
Chengyu Fan46398212015-08-11 11:23:13 -0600784}
785
786template <typename DatabaseHandler>
787void
788PublishAdapter<DatabaseHandler>::onFetchUpdateDataTimeout(const ndn::Interest& interest)
789{
790 // todo: record event, and use recovery Interest to fetch the whole table
Chengyu Fancfb80c72015-10-19 16:50:04 -0600791 _LOG_ERROR("UpdateData retrieval timed out: " << interest.getName());
Chengyu Fan46398212015-08-11 11:23:13 -0600792}
793
794template <typename DatabaseHandler>
795void
Chengyu Fan46398212015-08-11 11:23:13 -0600796PublishAdapter<DatabaseHandler>::processSyncUpdate(const std::vector<chronosync::MissingDataInfo>&
797 updates)
798{
Chengyu Fan71b712b2015-09-09 22:13:56 -0600799 _LOG_DEBUG(">> PublishAdapter::processSyncUpdate");
800
Chengyu Fan46398212015-08-11 11:23:13 -0600801 if (updates.empty()) {
802 return;
803 }
804
805 // multiple updates from different catalog are possible
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600806 for (size_t i = 0; i < updates.size(); ++i) {
Chengyu Fan46398212015-08-11 11:23:13 -0600807 // check if the session is in local DB
808 // if yes, only fetch packets whose seq number is bigger than the one in the DB
809 // if no, directly fetch Data
810 chronosync::SeqNo localSeqNo = getLatestSeqNo(updates[i]);
811 bool update = false;
812
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600813 for (chronosync::SeqNo seq = updates[i].low; seq <= updates[i].high; ++seq) {
Chengyu Fan46398212015-08-11 11:23:13 -0600814 if (seq > localSeqNo) {
815 m_socket->fetchData(updates[i].session, seq,
816 bind(&PublishAdapter<DatabaseHandler>::processUpdateData,this, _1),
Chengyu Fan3b9bb342015-09-21 10:53:37 -0600817 bind(&PublishAdapter<DatabaseHandler>::onValidationFailed,
Chengyu Fan46398212015-08-11 11:23:13 -0600818 this, _1, _2),
819 bind(&PublishAdapter<DatabaseHandler>::onFetchUpdateDataTimeout,
820 this, _1),
821 RETRY_WHEN_TIMEOUT);
Chengyu Fan71b712b2015-09-09 22:13:56 -0600822
823 _LOG_DEBUG("Interest for [" << updates[i].session << ":" << seq << "]");
824
Chengyu Fan46398212015-08-11 11:23:13 -0600825 update = true;
826 }
827 }
828 // update the seq session name and seq number in local DB
829 // indicating they are processed. So latter when this node reboots again, won't redo it
830 if (update) {
831 if (localSeqNo > 0)
832 renewUpdateInformation(updates[i]);
833 else
834 addUpdateInformation(updates[i]);
835 }
836 }
837}
838
839template <typename DatabaseHandler>
840void
841PublishAdapter<DatabaseHandler>::operateDatabase(const std::string& sql, util::DatabaseOperation op)
842{
843 // empty
844}
845
846template <>
847void
Chengyu Fan31737f12016-01-12 21:08:50 -0700848PublishAdapter<ConnectionPool_T>::operateDatabase(const std::string& sql, util::DatabaseOperation op)
Chengyu Fan46398212015-08-11 11:23:13 -0600849{
Chengyu Fan31737f12016-01-12 21:08:50 -0700850 Connection_T conn = ConnectionPool_getConnection(*m_databaseHandler);
851
852 if (!conn) {
853 _LOG_DEBUG("No available database connections");
854 return;
855 }
856
857 TRY {
858 Connection_execute(conn, reinterpret_cast<const char*>(sql.c_str()), sql.size());
859 }
860 CATCH(SQLException) {
861 _LOG_ERROR(Connection_getLastError(conn));
862 }
863 END_TRY;
864
865 Connection_close(conn);
Chengyu Fan46398212015-08-11 11:23:13 -0600866}
867
868template<typename DatabaseHandler>
869bool
870PublishAdapter<DatabaseHandler>::json2Sql(std::stringstream& sqlString,
871 Json::Value& jsonValue,
872 util::DatabaseOperation op)
873{
874 if (jsonValue.type() != Json::objectValue) {
Chengyu Fan46398212015-08-11 11:23:13 -0600875 return false;
876 }
877 if (op == util::ADD) {
878 size_t updateNumber = jsonValue["add"].size();
879 if (updateNumber <= 0)
880 return false;
881
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600882 sqlString << "INSERT INTO " << m_databaseTable << " (";
Chengyu Fancfb80c72015-10-19 16:50:04 -0600883 for (size_t i = 0; i < m_tableColumns.size(); ++i) {
Chengyu Fan46398212015-08-11 11:23:13 -0600884 if (i != 0)
885 sqlString << ", ";
Chengyu Fancfb80c72015-10-19 16:50:04 -0600886 sqlString << m_tableColumns[i];
Chengyu Fan46398212015-08-11 11:23:13 -0600887 }
888 sqlString << ") VALUES";
889
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600890 for (size_t i = 0; i < updateNumber; ++i) { //parse each file name
Chengyu Fan46398212015-08-11 11:23:13 -0600891 if (i > 0)
892 sqlString << ",";
893 // cast might be overflowed
894 Json::Value item = jsonValue["add"][static_cast<int>(i)];
895 if (!item.isConvertibleTo(Json::stringValue)) {
Chengyu Fancfb80c72015-10-19 16:50:04 -0600896 _LOG_ERROR("Malformed JsonQuery string");
Chengyu Fan46398212015-08-11 11:23:13 -0600897 return false;
898 }
899 std::string fileName(item.asString());
900 // use digest sha256 for now, may be removed
901 ndn::util::Digest<CryptoPP::SHA256> digest;
902 digest.update(reinterpret_cast<const uint8_t*>(fileName.data()), fileName.length());
903
904 sqlString << "('" << digest.toString() << "','" << fileName << "'";
905
906 // parse the ndn name to get each value for each field
907 if (!name2Fields(sqlString, fileName))
908 return false;
909 sqlString << ")";
910 }
911 sqlString << ";";
912 }
913 else if (op == util::REMOVE) {
914 // remove files from db
915 size_t updateNumber = jsonValue["remove"].size();
916 if (updateNumber <= 0)
917 return false;
918
Chengyu Fan71b712b2015-09-09 22:13:56 -0600919 sqlString << "DELETE FROM " << m_databaseTable << " WHERE name IN (";
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600920 for (size_t i = 0; i < updateNumber; ++i) {
Chengyu Fan46398212015-08-11 11:23:13 -0600921 if (i > 0)
922 sqlString << ",";
923 // cast might be overflowed
924 Json::Value item = jsonValue["remove"][static_cast<int>(i)];
925 if (!item.isConvertibleTo(Json::stringValue)) {
Chengyu Fancfb80c72015-10-19 16:50:04 -0600926 _LOG_ERROR("Malformed JsonQuery");
Chengyu Fan46398212015-08-11 11:23:13 -0600927 return false;
928 }
929 std::string fileName(item.asString());
930
931 sqlString << "'" << fileName << "'";
932 }
933 sqlString << ");";
934 }
935 return true;
936}
937
938template<typename DatabaseHandler>
939bool
940PublishAdapter<DatabaseHandler>::name2Fields(std::stringstream& sqlString,
941 std::string& fileName)
942{
943 size_t start = 0;
944 size_t pos = 0;
945 size_t count = 0;
946 std::string token;
947 std::string delimiter = "/";
948 // fileName must starts with either ndn:/ or /
949 std::string nameWithNdn("ndn:/");
950 std::string nameWithSlash("/");
951 if (fileName.find(nameWithNdn) == 0) {
952 start = nameWithNdn.size();
953 }
954 else if (fileName.find(nameWithSlash) == 0) {
955 start = nameWithSlash.size();
956 }
957 else
958 return false;
959
960 while ((pos = fileName.find(delimiter, start)) != std::string::npos) {
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600961 count++;
Chengyu Fan46398212015-08-11 11:23:13 -0600962 token = fileName.substr(start, pos - start);
Chengyu Fancfb80c72015-10-19 16:50:04 -0600963 // exclude the sha256 and name (already processed)
964 if (count >= m_tableColumns.size() - 2) {
965 return false;
Chengyu Fan46398212015-08-11 11:23:13 -0600966 }
967 sqlString << ",'" << token << "'";
968 start = pos + 1;
969 }
970
Chengyu Fancfb80c72015-10-19 16:50:04 -0600971 // sha256 and name have been processed, and the last token will be processed later
972 if (count != m_tableColumns.size() - 3 || std::string::npos == start)
Chengyu Fan46398212015-08-11 11:23:13 -0600973 return false;
974 token = fileName.substr(start, std::string::npos - start);
975 sqlString << ",'" << token << "'";
976 return true;
Chengyu Fanc7b87ad2015-07-09 16:44:37 -0600977}
978
979template<typename DatabaseHandler>
980bool
Chengyu Fanf4c747a2015-08-18 13:56:01 -0600981PublishAdapter<DatabaseHandler>::validatePublicationChanges(const
982 std::shared_ptr<const ndn::Data>& data)
Chengyu Fanc7b87ad2015-07-09 16:44:37 -0600983{
Chengyu Fan71b712b2015-09-09 22:13:56 -0600984 _LOG_DEBUG(">> PublishAdapter::validatePublicationChanges");
985
Chengyu Fanc7b87ad2015-07-09 16:44:37 -0600986 // The data name must be "/<publisher-prefix>/<nonce>"
987 // the prefix is the data name removes the last component
988 ndn::Name publisherPrefix = data->getName().getPrefix(-1);
989
990 const std::string payload(reinterpret_cast<const char*>(data->getContent().value()),
991 data->getContent().value_size());
992 Json::Value parsedFromString;
993 Json::Reader reader;
994 if (!reader.parse(payload, parsedFromString)) {
995 // parse error, log events
Chengyu Fan71b712b2015-09-09 22:13:56 -0600996 _LOG_DEBUG("Fail to parse the published Data" << data->getName());
Chengyu Fanc7b87ad2015-07-09 16:44:37 -0600997 return false;
998 }
999
1000 // validate added files...
1001 for (size_t i = 0; i < parsedFromString["add"].size(); i++) {
1002 if (!publisherPrefix.isPrefixOf(
1003 ndn::Name(parsedFromString["add"][static_cast<int>(i)].asString())))
1004 return false;
1005 }
1006
1007 // validate removed files ...
1008 for (size_t i = 0; i < parsedFromString["remove"].size(); i++) {
1009 if (!publisherPrefix.isPrefixOf(
1010 ndn::Name(parsedFromString["remove"][static_cast<int>(i)].asString())))
1011 return false;
1012 }
1013 return true;
Alison Craig2a4d5282015-04-10 12:00:02 -06001014}
1015
1016} // namespace publish
1017} // namespace atmos
1018#endif //ATMOS_PUBLISH_PUBLISH_ADAPTER_HPP