summaryrefslogtreecommitdiff
path: root/p2pvr/daemon
diff options
context:
space:
mode:
authorDan Goodliffe <dan@randomdan.homeip.net>2017-07-30 00:15:33 +0100
committerDan Goodliffe <dan@randomdan.homeip.net>2017-07-30 00:15:33 +0100
commitadd5644f64c86b635b62d560187c993aa7072b76 (patch)
tree70aaf1ae49ef4f27c4b20809250d5f5d63921d0e /p2pvr/daemon
parentSingle definition of glibmm (diff)
downloadp2pvr-add5644f64c86b635b62d560187c993aa7072b76.tar.bz2
p2pvr-add5644f64c86b635b62d560187c993aa7072b76.tar.xz
p2pvr-add5644f64c86b635b62d560187c993aa7072b76.zip
BIG migration from Project2 based to IceTray/Slicer :D
Diffstat (limited to 'p2pvr/daemon')
-rw-r--r--p2pvr/daemon/Jamfile.jam23
-rw-r--r--p2pvr/daemon/containerIterator.h40
-rw-r--r--p2pvr/daemon/daemon.cpp61
-rw-r--r--p2pvr/daemon/dbClient.cpp56
-rw-r--r--p2pvr/daemon/dbClient.h111
-rw-r--r--p2pvr/daemon/globalDevices.cpp29
-rw-r--r--p2pvr/daemon/globalDevices.h12
-rw-r--r--p2pvr/daemon/maintenance.cpp90
-rw-r--r--p2pvr/daemon/maintenance.h26
-rw-r--r--p2pvr/daemon/maintenance/events.cpp118
-rw-r--r--p2pvr/daemon/maintenance/network.cpp80
-rw-r--r--p2pvr/daemon/maintenance/services.cpp48
-rw-r--r--p2pvr/daemon/muxedFileSink.cpp12
-rw-r--r--p2pvr/daemon/muxedFileSink.h3
-rw-r--r--p2pvr/daemon/objectRowState.cpp89
-rw-r--r--p2pvr/daemon/objectRowState.h48
-rw-r--r--p2pvr/daemon/p2pvr-int.ice4
-rw-r--r--p2pvr/daemon/pch.hpp20
-rw-r--r--p2pvr/daemon/privateExecContext.cpp14
-rw-r--r--p2pvr/daemon/privateExecContext.h13
-rw-r--r--p2pvr/daemon/recorder.cpp44
-rw-r--r--p2pvr/daemon/recorder.h17
-rw-r--r--p2pvr/daemon/recordings.cpp49
-rw-r--r--p2pvr/daemon/recordings.h10
-rw-r--r--p2pvr/daemon/resources.h12
-rw-r--r--p2pvr/daemon/schedulers/bitDumbScheduler.cpp1
-rw-r--r--p2pvr/daemon/schedules.cpp111
-rw-r--r--p2pvr/daemon/schedules.h21
-rw-r--r--p2pvr/daemon/si.cpp122
-rw-r--r--p2pvr/daemon/si.h9
-rw-r--r--p2pvr/daemon/storage.cpp40
-rw-r--r--p2pvr/daemon/storage.h19
-rw-r--r--p2pvr/daemon/unittests/Jamfile.jam221
-rw-r--r--p2pvr/daemon/unittests/datasources/postgres.xml4
-rw-r--r--p2pvr/daemon/unittests/dummySelect.sql1
-rw-r--r--p2pvr/daemon/unittests/mockDefs.cpp12
-rw-r--r--p2pvr/daemon/unittests/mockDefs.h18
-rw-r--r--p2pvr/daemon/unittests/mockDevices.h3
-rw-r--r--p2pvr/daemon/unittests/mockRecorder.h3
-rw-r--r--p2pvr/daemon/unittests/mockScheduler.h3
-rw-r--r--p2pvr/daemon/unittests/testEmbedding.cpp14
-rw-r--r--p2pvr/daemon/unittests/testErrorHandling.cpp66
-rw-r--r--p2pvr/daemon/unittests/testMaint.cpp115
-rw-r--r--p2pvr/daemon/unittests/testRecording.cpp54
-rw-r--r--p2pvr/daemon/unittests/testRecordings.cpp48
-rw-r--r--p2pvr/daemon/unittests/testSched.cpp53
-rw-r--r--p2pvr/daemon/unittests/testSi.cpp34
-rw-r--r--p2pvr/daemon/unittests/testSqlSelectDeserializer.cpp86
-rw-r--r--p2pvr/daemon/unittests/testStorage.cpp69
49 files changed, 712 insertions, 1444 deletions
diff --git a/p2pvr/daemon/Jamfile.jam b/p2pvr/daemon/Jamfile.jam
index 369e714..318a585 100644
--- a/p2pvr/daemon/Jamfile.jam
+++ b/p2pvr/daemon/Jamfile.jam
@@ -1,33 +1,32 @@
+import icetray ;
+
lib slicer : : <name>slicer : : <include>/usr/include/slicer ;
lib slicer-db : : <name>slicer-db : : <include>/usr/include/slicer ;
+lib boost_program_options ;
+lib dbppcore ;
-cpp-pch pch : pch.hpp :
- <library>../ice//p2pvrice
- <library>../lib//p2pvrlib
- <library>../dvb//p2pvrdvb
- <library>..//p2sql
- <library>../devices//p2pvrdevices
- <library>../daemonbase//p2pvrdaemonbase
- <slicer>yes
-;
+path-constant me : . ;
lib p2pvrdaemon :
- pch
[ glob-tree *.ice *.cpp *.sql : bin unittests ]
:
<library>../ice//p2pvrice
<library>../lib//p2pvrlib
<library>../dvb//p2pvrdvb
<library>../../libtmdb//tmdb
- <library>..//p2sql
<library>../devices//p2pvrdevices
- <library>../daemonbase//p2pvrdaemonbase
+ <library>boost_program_options
+ <library>dbppcore
<library>..//adhocutil
+ <library>..//icetray
+ <library>..//IceBox
<implicit-dependency>../../libtmdb//tmdb
<library>slicer
<library>slicer-db
<slicer>yes
<include>.
+ <icetray.sql.basedir>$(me)
+ <icetray.sql.namespace>P2PVR
: :
<include>.
<library>../ice//p2pvrice
diff --git a/p2pvr/daemon/containerIterator.h b/p2pvr/daemon/containerIterator.h
deleted file mode 100644
index 88976af..0000000
--- a/p2pvr/daemon/containerIterator.h
+++ /dev/null
@@ -1,40 +0,0 @@
-#ifndef CONTAINERITERATOR_H
-#define CONTAINERITERATOR_H
-
-#include <iHaveSubTasks.h>
-#include "objectRowState.h"
-
-template <typename T>
-class ContainerIterator : public IHaveSubTasks {
- public:
- ContainerIterator(const T * con, const SelectedColumns & sc) :
- SourceObject(__PRETTY_FUNCTION__),
- IHaveSubTasks(NULL),
- binder(boost::bind(&BindColumns<typename T::value_type>, _1, sc, _2)),
- container(con)
- {
- }
-
- void execute(ExecContext * ec) const
- {
- ObjectRowStateTmpl<typename T::value_type> rs;
- for (const auto & i : *container) {
- binder(rs, i);
- rs.process(ec, boost::bind(&ContainerIterator::executeChildren, this, ec));
- }
- }
-
- private:
- boost::function<void(RowState &, const typename T::value_type &)> binder;
- const T * container;
-
- void executeChildren(ExecContext * ec) const
- {
- for (const Tasks::value_type & sq : normal) {
- sq->execute(ec);
- }
- }
-};
-
-#endif
-
diff --git a/p2pvr/daemon/daemon.cpp b/p2pvr/daemon/daemon.cpp
index 874ea3b..6a62457 100644
--- a/p2pvr/daemon/daemon.cpp
+++ b/p2pvr/daemon/daemon.cpp
@@ -1,5 +1,3 @@
-#include <daemonBase.h>
-#include <options.h>
#include "localDevices.h"
#include "globalDevices.h"
#include "maintenance.h"
@@ -10,44 +8,51 @@
#include "recordings.h"
#include <Ice/ObjectAdapter.h>
#include <tmdb-proxy.h>
+#include <icetrayService.h>
// These configure external components and so they live here
-class P2PVRTMDb {
+class P2PVRTMDb : public IceTray::Options {
public:
- static std::string apikey;
- static std::string baseUrl;
- INITOPTIONS;
+ P2PVRTMDb() : IceTray::Options("P2PVR TMDb configuration") { }
+
+ std::string apikey;
+ std::string baseUrl;
+
+ ICETRAY_OPTIONS_DECLARE;
};
-std::string P2PVRTMDb::apikey;
-std::string P2PVRTMDb::baseUrl;
-DECLARE_OPTIONS(P2PVRTMDb, "P2PVR TMDb configuration")
-("p2pvr.tmdb.apikey", Options::value(&P2PVRTMDb::apikey, "48b32823d2b60c5c1085af36daed03fa"),
- "The Movie Database API key")
-("p2pvr.tmdb.baseurl", Options::value(&P2PVRTMDb::baseUrl, "http://private-5513-themoviedb.apiary-mock.com/3"),
- "The Movie Database API base URL")
-END_OPTIONS(P2PVRTMDb);
+ICETRAY_OPTIONS(P2PVRTMDb,
+ ("p2pvr.tmdb.apikey", boost::program_options::value(&apikey)->default_value("48b32823d2b60c5c1085af36daed03fa"),
+ "The Movie Database API key")
+ ("p2pvr.tmdb.baseurl", boost::program_options::value(&baseUrl)->default_value("http://private-5513-themoviedb.apiary-mock.com/3"),
+ "The Movie Database API base URL")
+);
-class P2PvrDaemon : public DaemonBase {
+class P2PvrDaemon : public IceTray::Service {
public:
- P2PvrDaemon(int argc, char ** argv) :
- DaemonBase(argc, argv)
+ void addObjects(const std::string &, const Ice::CommunicatorPtr & ic, const Ice::StringSeq &, const Ice::ObjectAdapterPtr & adapter) override
{
+ IceTray::OptionsResolver<P2PVRTMDb> tmdbOpts;
+
+ IceUtil::TimerPtr timer = new IceUtil::Timer();
+ auto db = getConnectionPool(ic, "postgresql", "postgres");
+ auto localDevices = add<P2PVR::LocalDevices>(ic, adapter, new LocalDevices(adapter, timer), "Devices");
+ auto globalDevices = add<P2PVR::Devices>(ic, adapter, new GlobalDevices(), "GlobalDevices");
+ auto maintenance = add<P2PVR::Maintenance>(ic, adapter, new Maintenance(db, adapter, timer), "Maintenance");
+ auto si = add<P2PVR::SI>(ic, adapter, new SI(db), "SI");
+ auto schedules = add<P2PVR::Schedules>(ic, adapter, new Schedules(db), "Schedules");
+ auto storage = add<P2PVR::Storage>(ic, adapter, new Storage(), "Storage");
+ auto recorder = add<P2PVR::Recorder>(ic, adapter, new Recorder(adapter, timer), "Recorder");
+ auto recordings = add<P2PVR::Recordings>(ic, adapter, new Recordings(db), "Recordings");
+ auto tmdb = add<TMDb::Proxy>(ic, adapter, new TMDb::Proxy(tmdbOpts->baseUrl, tmdbOpts->apikey), "TMDb");
}
- void addServants(const Ice::ObjectAdapterPtr & adapter, const IceUtil::TimerPtr & timer) const
+ template<typename Object>
+ typename Object::ProxyType add(const Ice::CommunicatorPtr & ic, const Ice::ObjectAdapterPtr & adapter, const IceUtil::Handle<Object> & object, const std::string & name) const
{
- adapter->add(new LocalDevices(adapter, timer), ic->stringToIdentity("Devices"));
- adapter->add(new GlobalDevices(), ic->stringToIdentity("GlobalDevices"));
- adapter->add(new Maintenance(adapter, timer), ic->stringToIdentity("Maintenance"));
- adapter->add(new SI(), ic->stringToIdentity("SI"));
- adapter->add(new Schedules(), ic->stringToIdentity("Schedules"));
- adapter->add(new Storage(), ic->stringToIdentity("Storage"));
- adapter->add(new Recorder(adapter, timer), ic->stringToIdentity("Recorder"));
- adapter->add(new Recordings(), ic->stringToIdentity("Recordings"));
- adapter->add(new TMDb::Proxy(P2PVRTMDb::baseUrl, P2PVRTMDb::apikey), ic->stringToIdentity("TMDb"));
+ return Object::ProxyType::uncheckedCast(adapter->add(object, ic->stringToIdentity(name)));
}
};
-NAMEDFACTORY("p2pvrdaemon", P2PvrDaemon, DaemonFactory);
+FACTORY(P2PvrDaemon, IceTray::ServiceFactory);
diff --git a/p2pvr/daemon/dbClient.cpp b/p2pvr/daemon/dbClient.cpp
deleted file mode 100644
index de4b926..0000000
--- a/p2pvr/daemon/dbClient.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-#include <pch.hpp>
-#include "dbClient.h"
-#include <sqlMergeTask.h>
-
-void
-DatabaseClient::SqlMergeColumnsInserter(SqlMergeTask * merge, const std::string & name, bool key)
-{
- merge->cols.insert(new SqlMergeTask::TargetColumn(name, key));
- if (key) {
- merge->keys.insert(name);
- }
-}
-
-void
-DatabaseClient::onAllDatasources(const DataSourceCall & call) const
-{
- for (const CommonObjects::DataSources::value_type & ds : CommonObjects::datasources) {
- call(ds.second);
- }
-}
-
-DatabaseClient::TxHelper::TxHelper(const DatabaseClient * dbc) :
- client(dbc),
- so(NULL,
- boost::bind(&DatabaseClient::onAllDatasources, dbc, DataSourceCall(boost::bind(&DataSource::commit, _1))),
- boost::bind(&DatabaseClient::onAllDatasources, dbc, DataSourceCall(boost::bind(&DataSource::rollback, _1))))
-{
-}
-
-void
-DatabaseClient::TxHelper::Commit() const
-{
- client->onAllDatasources(boost::bind(&DataSource::commit, _1));
-}
-
-DatabaseClient::NoRowsFoundException::NoRowsFoundException() :
- std::runtime_error("No rows found")
-{
-}
-
-VariableType
-operator/(const DatabaseClient::SelectPtr & cmd, unsigned int col)
-{
- HandleAsVariableType vt;
- (*cmd)[col].apply(vt);
- return vt.variable;
-}
-
-VariableType
-operator/(const DatabaseClient::SelectPtr & cmd, const std::string & col)
-{
- HandleAsVariableType vt;
- (*cmd)[col].apply(vt);
- return vt.variable;
-}
-
diff --git a/p2pvr/daemon/dbClient.h b/p2pvr/daemon/dbClient.h
deleted file mode 100644
index 1fc12e8..0000000
--- a/p2pvr/daemon/dbClient.h
+++ /dev/null
@@ -1,111 +0,0 @@
-#ifndef DBCLIENT_H
-#define DBCLIENT_H
-
-#include <commonObjects.h>
-#include <variableType.h>
-#include <list>
-#include <selectcommand.h>
-#include <modifycommand.h>
-#include <scopeExit.h>
-#include <rdbmsDataSource.h>
-#include <sqlVariableBinder.h>
-#include <sqlHandleAsVariableType.h>
-#include "p2Helpers.h"
-#include <slicer/slicer.h>
-
-class SqlMergeTask;
-
-class DatabaseClient : public virtual CommonObjects {
- public:
- typedef boost::shared_ptr<DB::SelectCommand> SelectPtr;
- typedef boost::shared_ptr<DB::ModifyCommand> ModifyPtr;
-
- static void SqlMergeColumnsInserter(SqlMergeTask * merge, const std::string & name, bool key);
-
- class TxHelper {
- public:
- TxHelper(const DatabaseClient *);
- void Commit() const;
-
- private:
- const DatabaseClient * client;
- AdHoc::ScopeExit so;
- };
-
- template <typename... Args>
- std::pair<RdbmsDataSource::ConnectionRef, ModifyPtr> Modify(const std::string & sql, const Args & ... args) const
- {
- auto db = dataSource<RdbmsDataSource>("postgres")->getWritable();
- auto cmd = ModifyPtr(db->newModifyCommand(sql));
- Bind(cmd.get(), 0, args...);
- return {db, cmd};
- }
-
- template <typename SerializerType, typename Obj, typename ... ExtraArgs>
- void Store(const Obj & o, const ExtraArgs & ... ea) const
- {
- auto db = dataSource<RdbmsDataSource>("postgres")->getWritable();
- Slicer::SerializeAny<SerializerType>(o, db.get(), ea...);
- }
-
- template <typename... Args>
- std::pair<RdbmsDataSource::ConnectionRef, SelectPtr> Select(const std::string & sql, const Args & ... args) const
- {
- auto db = dataSource<RdbmsDataSource>("postgres")->getReadonly();
- auto cmd = SelectPtr(db->newSelectCommand(sql));
- Bind(cmd.get(), 0, args...);
- return {db, cmd};
- }
-
- class NoRowsFoundException : public std::runtime_error {
- public:
- NoRowsFoundException();
- };
-
- template <typename Rtn, typename... Args>
- Rtn SelectScalar(const std::string & sql, const Args & ... args) const
- {
- auto db = dataSource<RdbmsDataSource>("postgres");
- auto cmd = SelectPtr(db->getReadonly()->newSelectCommand(sql));
- Bind(cmd.get(), 0, args...);
- while (cmd->fetch()) {
- HandleAsVariableType h;
- (*cmd)[0].apply(h);
- Rtn r;
- h.variable >> r;
- return r;
- }
- throw NoRowsFoundException();
- }
-
- private:
- static void Bind(DB::Command *, unsigned int) { }
-
- template <typename Arg>
- static void Bind(DB::Command * cmd, unsigned int offset, const Arg & arg)
- {
- VariableType v;
- v << arg;
- boost::apply_visitor<const SqlVariableBinder, const VariableType>(SqlVariableBinder(cmd, offset), v);
- }
-
- template <typename Arg, typename... Args>
- static void Bind(DB::Command * cmd, unsigned int offset, const Arg & arg, const Args & ... args)
- {
- Bind(cmd, offset, arg);
- Bind(cmd, offset + 1, args...);
- }
-
- friend class TxHelper;
- typedef boost::function<void(DataSourcePtr)> DataSourceCall;
- void onAllDatasources(const DataSourceCall &) const;
-};
-
-VariableType
-operator/(const DatabaseClient::SelectPtr & cmd, unsigned int col);
-
-VariableType
-operator/(const DatabaseClient::SelectPtr & cmd, const std::string & col);
-
-#endif
-
diff --git a/p2pvr/daemon/globalDevices.cpp b/p2pvr/daemon/globalDevices.cpp
index 3f0c485..4557fc6 100644
--- a/p2pvr/daemon/globalDevices.cpp
+++ b/p2pvr/daemon/globalDevices.cpp
@@ -1,22 +1,23 @@
-#include <pch.hpp>
#include "globalDevices.h"
#include <Ice/Ice.h>
-std::vector<std::string> GlobalDevices::Devices;
+namespace po = boost::program_options;
-DECLARE_OPTIONS(GlobalDevices, "P2PVR Devices")
-("p2pvr.globaldevices.carddaemon",
- Options::functions(
- [](const VariableType & df) { Devices.push_back(df); },
- []{ Devices.clear(); }),
- "ICE address of remote device pools (<adapter>:<endpoint>)")
-END_OPTIONS(GlobalDevices);
+GlobalDevices::Options::Options() :
+ IceTray::Options("P2PVR Devices")
+{
+}
+
+ICETRAY_OPTIONS(GlobalDevices::Options,
+ ("p2pvr.globaldevices.carddaemon", po::value(&Devices),
+ "ICE address of remote device pools (<object>:<endpoint>)")
+)
P2PVR::TunerPrx
GlobalDevices::GetTunerSpecific(const DVBSI::DeliveryPtr & delivery, const Ice::Current & ice)
{
auto ic = ice.adapter->getCommunicator();
- for (const auto & pool : Devices) {
+ for (const auto & pool : options->Devices) {
try {
auto poolprx = P2PVR::DevicesPrx::checkedCast(ic->stringToProxy(pool));
return poolprx->GetTunerSpecific(delivery);
@@ -31,7 +32,7 @@ P2PVR::TunerPrx
GlobalDevices::GetTunerAny(const DVBSI::DeliveryPtr & delivery, const Ice::Current & ice)
{
auto ic = ice.adapter->getCommunicator();
- for (const auto & pool : Devices) {
+ for (const auto & pool : options->Devices) {
try {
auto poolprx = P2PVR::DevicesPrx::checkedCast(ic->stringToProxy(pool));
return poolprx->GetTunerAny(delivery);
@@ -46,7 +47,7 @@ P2PVR::PrivateTunerPrx
GlobalDevices::GetPrivateTuner(short type, const Ice::Current & ice)
{
auto ic = ice.adapter->getCommunicator();
- for (const auto & pool : Devices) {
+ for (const auto & pool : options->Devices) {
try {
auto poolprx = P2PVR::DevicesPrx::checkedCast(ic->stringToProxy(pool));
return poolprx->GetPrivateTuner(type);
@@ -61,7 +62,7 @@ void
GlobalDevices::ReleaseTuner(const P2PVR::TunerPrx & tuner, const Ice::Current & ice)
{
auto ic = ice.adapter->getCommunicator();
- for (const auto & pool : Devices) {
+ for (const auto & pool : options->Devices) {
auto poolprx = P2PVR::DevicesPrx::checkedCast(ic->stringToProxy(pool));
poolprx->ReleaseTuner(tuner);
}
@@ -72,7 +73,7 @@ GlobalDevices::TunerCount(const Ice::Current & ice)
{
int total = 0;
auto ic = ice.adapter->getCommunicator();
- for (const auto & pool : Devices) {
+ for (const auto & pool : options->Devices) {
try {
auto poolprx = P2PVR::DevicesPrx::checkedCast(ic->stringToProxy(pool));
total += poolprx->TunerCount();
diff --git a/p2pvr/daemon/globalDevices.h b/p2pvr/daemon/globalDevices.h
index 86d80c5..cffb491 100644
--- a/p2pvr/daemon/globalDevices.h
+++ b/p2pvr/daemon/globalDevices.h
@@ -10,15 +10,23 @@
class DLL_PUBLIC GlobalDevices : public P2PVR::Devices {
public:
+ class Options : public IceTray::Options {
+ public:
+ Options();
+
+ ICETRAY_OPTIONS_DECLARE;
+
+ std::vector<std::string> Devices;
+ };
+
P2PVR::TunerPrx GetTunerSpecific(const DVBSI::DeliveryPtr &, const Ice::Current &);
P2PVR::TunerPrx GetTunerAny(const DVBSI::DeliveryPtr &, const Ice::Current &);
P2PVR::PrivateTunerPrx GetPrivateTuner(short type, const Ice::Current &);
void ReleaseTuner(const P2PVR::TunerPrx &, const Ice::Current &);
int TunerCount(const Ice::Current &);
- INITOPTIONS;
private:
- static std::vector<std::string> Devices;
+ IceTray::OptionsResolver<Options> options;
};
#endif
diff --git a/p2pvr/daemon/maintenance.cpp b/p2pvr/daemon/maintenance.cpp
index f6878ec..23eef15 100644
--- a/p2pvr/daemon/maintenance.cpp
+++ b/p2pvr/daemon/maintenance.cpp
@@ -1,4 +1,3 @@
-#include <pch.hpp>
#include <logger.h>
#include <thread>
#include "maintenance.h"
@@ -6,24 +5,26 @@
#include "bindTimerTask.h"
#include <linux/dvb/frontend.h>
#include <cxxabi.h>
+#include <scopeExit.h>
-time_t Maintenance::periodUpdateNetwork;
-time_t Maintenance::periodUpdateServices;
-time_t Maintenance::periodUpdateEvents;
-bool Maintenance::scanOnStart;
+namespace po = boost::program_options;
-DECLARE_OPTIONS(Maintenance, "P2PVR Maintenance options")
-("p2pvr.maintenance.periodUpdateNetwork", Options::value(&periodUpdateNetwork, 86400 * 7),
- "Period between automated updates of DVB network (1 week)")
-("p2pvr.maintenance.periodUpdateServices", Options::value(&periodUpdateServices, 86400 * 7),
- "Period between automated updates of DVB services (1 week)")
-("p2pvr.maintenance.periodUpdateEvents", Options::value(&periodUpdateEvents, 3600 * 12),
- "Period between automated updates of DVB events (12 hours)")
-("p2pvr.maintenance.scanOnStart", Options::value(&scanOnStart, false),
- "Perform the maintenance circle on start-up (false)")
-END_OPTIONS(Maintenance);
+Maintenance::Options::Options() : IceTray::Options("P2PVR Maintenance options") { }
+ICETRAY_OPTIONS(Maintenance::Options,
+ ("p2pvr.maintenance.periodUpdateNetwork", po::value(&periodUpdateNetwork)->default_value(86400 * 7),
+ "Period between automated updates of DVB network (1 week)")
+ ("p2pvr.maintenance.periodUpdateServices", po::value(&periodUpdateServices)->default_value(86400 * 7),
+ "Period between automated updates of DVB services (1 week)")
+ ("p2pvr.maintenance.periodUpdateEvents", po::value(&periodUpdateEvents)->default_value(3600 * 12),
+ "Period between automated updates of DVB events (12 hours)")
+ ("p2pvr.maintenance.scanOnStart", po::value(&scanOnStart)->default_value(false),
+ "Perform the maintenance circle on start-up (false)")
+);
-Maintenance::Maintenance(Ice::ObjectAdapterPtr a, IceUtil::TimerPtr t) :
+IceTray::Logging::LoggerPtr Maintenance::logger(LOGMANAGER()->getLogger<Maintenance>());
+
+Maintenance::Maintenance(IceTray::DatabasePoolPtr db, Ice::ObjectAdapterPtr a, IceUtil::TimerPtr t) :
+ IceTray::AbstractDatabaseClient(db),
adapter(a),
timer(t),
clientCheck(new BindTimerTask(boost::bind(&Maintenance::ScheduledUpdate, this))),
@@ -35,7 +36,7 @@ Maintenance::Maintenance(Ice::ObjectAdapterPtr a, IceUtil::TimerPtr t) :
if (timer) {
timer->scheduleRepeated(clientCheck, IceUtil::Time::seconds(5 * 60));
}
- if (scanOnStart) {
+ if (options->scanOnStart) {
ScheduledUpdate();
}
}
@@ -60,40 +61,39 @@ Maintenance::UpdateAll(short type, const Ice::Current & ice)
void
Maintenance::ScheduledUpdate()
{
- Logger()->messagebf(LOG_DEBUG, "%s: triggered", __PRETTY_FUNCTION__);
+ logger->messagebf(LOG::DEBUG, "%s: triggered", __PRETTY_FUNCTION__);
if (!updateRunning) {
std::thread update([this] {
- try {
+ try {
AdHoc::ScopeExit notRunning([this]{ updateRunning = false; });
- updateRunning = true;
- auto si = P2PVR::MaintenancePrx::checkedCast(adapter->createProxy(adapter->getCommunicator()->stringToIdentity("Maintenance")));
- time_t now = time(NULL);
- if (lastUpdateNetwork < now - periodUpdateNetwork) {
- Logger()->messagebf(LOG_INFO, "%s: updating network", __PRETTY_FUNCTION__);
- si->UpdateNetwork(FE_OFDM);
- time(&lastUpdateNetwork);
- }
- if (lastUpdateServices < now - periodUpdateServices) {
- Logger()->messagebf(LOG_INFO, "%s: updating services", __PRETTY_FUNCTION__);
- si->UpdateServices();
- time(&lastUpdateServices);
- }
- if (lastUpdateEvents < now - periodUpdateEvents) {
- Logger()->messagebf(LOG_INFO, "%s: updating events", __PRETTY_FUNCTION__);
- si->UpdateEvents();
- time(&lastUpdateEvents);
- }
- Logger()->messagebf(LOG_DEBUG, "%s: completed", __PRETTY_FUNCTION__);
+ updateRunning = true;
+ time_t now = time(NULL);
+ if (lastUpdateNetwork < now - options->periodUpdateNetwork) {
+ logger->messagebf(LOG::INFO, "%s: updating network", __PRETTY_FUNCTION__);
+ this->UpdateNetwork(FE_OFDM, Ice::Current());
+ time(&lastUpdateNetwork);
}
- catch (const std::exception & ex) {
- char * buf = __cxxabiv1::__cxa_demangle(typeid(ex).name(), NULL, NULL, NULL);
- Logger()->messagebf(LOG_ERR, "%s: failed %s: %s", __PRETTY_FUNCTION__, buf, ex.what());
- free(buf);
+ if (lastUpdateServices < now - options->periodUpdateServices) {
+ logger->messagebf(LOG::INFO, "%s: updating services", __PRETTY_FUNCTION__);
+ this->UpdateServices(Ice::Current());
+ time(&lastUpdateServices);
}
- catch (...) {
- Logger()->messagebf(LOG_ERR, "%s: failed (unknown exception)", __PRETTY_FUNCTION__);
+ if (lastUpdateEvents < now - options->periodUpdateEvents) {
+ logger->messagebf(LOG::INFO, "%s: updating events", __PRETTY_FUNCTION__);
+ this->UpdateEvents(Ice::Current());
+ time(&lastUpdateEvents);
}
- });
+ logger->messagebf(LOG::DEBUG, "%s: completed", __PRETTY_FUNCTION__);
+ }
+ catch (const std::exception & ex) {
+ char * buf = __cxxabiv1::__cxa_demangle(typeid(ex).name(), NULL, NULL, NULL);
+ logger->messagebf(LOG::ERR, "%s: failed %s: %s", __PRETTY_FUNCTION__, buf, ex.what());
+ free(buf);
+ }
+ catch (...) {
+ logger->messagebf(LOG::ERR, "%s: failed (unknown exception)", __PRETTY_FUNCTION__);
+ }
+ });
update.detach();
}
}
diff --git a/p2pvr/daemon/maintenance.h b/p2pvr/daemon/maintenance.h
index 7c3e9b3..c941d06 100644
--- a/p2pvr/daemon/maintenance.h
+++ b/p2pvr/daemon/maintenance.h
@@ -3,12 +3,24 @@
#include <p2pvr.h>
#include <IceUtil/Timer.h>
-#include "dbClient.h"
+#include <abstractDatabaseClient.h>
+#include <options.h>
+#include <logger.h>
#include <visibility.h>
-class DLL_PUBLIC Maintenance : public P2PVR::Maintenance, public DatabaseClient {
+class DLL_PUBLIC Maintenance : public P2PVR::Maintenance, public IceTray::AbstractDatabaseClient {
public:
- Maintenance(Ice::ObjectAdapterPtr, IceUtil::TimerPtr);
+ class Options : public IceTray::Options {
+ public:
+ Options();
+ ICETRAY_OPTIONS_DECLARE;
+ time_t periodUpdateNetwork;
+ time_t periodUpdateServices;
+ time_t periodUpdateEvents;
+ bool scanOnStart;
+ };
+
+ Maintenance(IceTray::DatabasePoolPtr db, Ice::ObjectAdapterPtr, IceUtil::TimerPtr);
void UpdateAll(const Ice::Current &);
void UpdateAll(short type, const Ice::Current &);
@@ -16,8 +28,6 @@ class DLL_PUBLIC Maintenance : public P2PVR::Maintenance, public DatabaseClient
void UpdateServices(const Ice::Current &);
void UpdateEvents(const Ice::Current &);
- INITOPTIONS;
-
private:
DLL_PRIVATE void ScheduledUpdate();
@@ -30,10 +40,8 @@ class DLL_PUBLIC Maintenance : public P2PVR::Maintenance, public DatabaseClient
time_t lastUpdateEvents;
bool updateRunning;
- static time_t periodUpdateNetwork;
- static time_t periodUpdateServices;
- static time_t periodUpdateEvents;
- static bool scanOnStart;
+ IceTray::OptionsResolver<Options> options;
+ static IceTray::Logging::LoggerPtr logger;
};
#endif
diff --git a/p2pvr/daemon/maintenance/events.cpp b/p2pvr/daemon/maintenance/events.cpp
index c8fee58..b4b3c92 100644
--- a/p2pvr/daemon/maintenance/events.cpp
+++ b/p2pvr/daemon/maintenance/events.cpp
@@ -1,104 +1,92 @@
-#include <pch.hpp>
#include "../maintenance.h"
#include <siParsers/event.h>
-#include <sqlMergeTask.h>
#include <Ice/Communicator.h>
-#include <p2Helpers.h>
-#include <containerIterator.h>
#include <temporaryIceAdapterObject.h>
#include <commonHelpers.h>
-#include <resources.h>
-#include <privateExecContext.h>
+#include <db/sqlTablePatchSerializer.h>
+#include <tablepatch.h>
+#include <sqlWriter.h>
+#include <slicer/modelPartsTypes.impl.h>
+#include "sql/Maint_pruneEvents.sql.h"
-ResourceString(Maint_pruneEvents, sql_Maint_pruneEvents);
+class SiEventsStream : public Slicer::Stream<DVBSI::EventPtr> {
+ private:
+ class SiEventsHandler : public SiEpgParser {
+ public:
+ SiEventsHandler(const Consumer & c, IceTray::Logging::LoggerPtr l) :
+ consumer(c),
+ logger(l)
+ {
+ }
-class SiEventsHandler : public SiEpgParser {
- public:
- SiEventsHandler(const RowProcessorCallback & cb, ExecContext * e, const SelectedColumns & sc) :
- ecs(sc),
- callBack(cb),
- ec(e)
- {
- }
+ bool HandleTable(DVBSI::EventPtr e) override
+ {
+ logger->messagebf(LOG::DEBUG, "Service Id: %d Program Id: %d Title: %s Time: %s - %s",
+ e->ServiceId, e->EventId, e->Title, e->StartTime, e->StopTime);
+ consumer(e);
+ return false;
+ }
- bool HandleTable(DVBSI::EventPtr e)
- {
- Logger()->messagebf(LOG_DEBUG, "Service Id: %d Program Id: %d Title: %s Time: %s - %s",
- e->ServiceId, e->EventId, e->Title, e->StartTime, e->StopTime);
- BindColumns<DVBSI::EventPtr>(rowState, ecs, e);
- rowState.process(ec, callBack);
- return false;
- }
+ private:
+ const Consumer & consumer;
+ const IceTray::Logging::LoggerPtr logger;
+ };
- private:
- ObjectRowStateTmpl<DVBSI::EventPtr> rowState;
- const SelectedColumns & ecs;
- const RowProcessorCallback callBack;
- ExecContext * ec;
-};
-
-class SiEventsMerger : public IHaveSubTasks {
public:
- SiEventsMerger(const Ice::Current & i, const SelectedColumns & sc) :
- SourceObject(__PRETTY_FUNCTION__),
- IHaveSubTasks(NULL),
- ecs(sc),
- ice(i) { }
+ SiEventsStream(const Ice::Current & i, IceTray::Logging::LoggerPtr l) :
+ ice(i),
+ logger(l)
+ {
+ }
- void execute(ExecContext * ec) const
+ void Produce(const Consumer & ch) override
{
auto ic = ice.adapter->getCommunicator();
auto devs = P2PVR::DevicesPrx::checkedCast(ice.adapter->createProxy(ic->stringToIdentity("GlobalDevices")));
auto si = P2PVR::SIPrx::checkedCast(ice.adapter->createProxy(ic->stringToIdentity("SI")));
-
if (!devs || !si) {
throw std::runtime_error("bad proxy(s)");
}
- TemporaryIceAdapterObject<P2PVR::RawDataClient> parser(ice.adapter,
- new SiEventsHandler(boost::bind(&SiEventsMerger::executeChildren, this, ec), ec, ecs));
-
auto delivery = si->GetDeliveryForSi();
if (!delivery) {
throw std::runtime_error("no delivery methods");
}
-
- Logger()->messagebf(LOG_DEBUG, "%s: Getting a tuner", __PRETTY_FUNCTION__);
+ logger->messagebf(LOG::DEBUG, "%s: Getting a tuner", __PRETTY_FUNCTION__);
auto tuner = devs->GetTunerAny(delivery);
- Logger()->messagebf(LOG_DEBUG, "%s: Fetching events", __PRETTY_FUNCTION__);
+ logger->messagebf(LOG::DEBUG, "%s: Fetching events", __PRETTY_FUNCTION__);
+ TemporaryIceAdapterObject<P2PVR::RawDataClient> parser(ice.adapter, new SiEventsHandler(ch, logger));
+
tuner->SendEventInformation(parser);
devs->ReleaseTuner(tuner);
}
private:
- const SelectedColumns & ecs;
const Ice::Current & ice;
-
- void executeChildren(ExecContext * ec) const
- {
- for (const Tasks::value_type & sq : normal) {
- sq->execute(ec);
- }
- }
+ const IceTray::Logging::LoggerPtr logger;
};
+MODELPARTFORSTREAM(SiEventsStream);
+
void
Maintenance::UpdateEvents(const Ice::Current & ice)
{
- TxHelper tx(this);
- PrivateExecContext ec;
- SqlMergeTask mergeEvents("postgres", "events");
- auto ecs = CreateColumns<DVBSI::EventPtr>(boost::bind(SqlMergeColumnsInserter, &mergeEvents, _1, _2));
- mergeEvents.sources.insert(new SiEventsMerger(ice, ecs));
- mergeEvents.insteadOfDelete = new DynamicSql::SqlText("current = false");
- mergeEvents.updateWhere = new DynamicSql::SqlText("a.current");
- mergeEvents.loadComplete(this);
- mergeEvents.execute(&ec);
- Modify(Maint_pruneEvents).second->execute();
- tx.Commit();
- Logger()->messagebf(LOG_INFO, "%s: Updated events", __PRETTY_FUNCTION__);
-
+ auto dbc = db->get();
auto ic = ice.adapter->getCommunicator();
+
+ SiEventsStream stream(ice, logger);
+
+ DB::TransactionScope tx(dbc.get());
+ DB::TablePatch tp;
+ tp.dest = "events";
+ tp.insteadOfDelete = new DB::StaticSqlWriter("current = false");
+ tp.where = new DB::StaticSqlWriter("a.current");
+ Slicer::SerializeAny<Slicer::SqlTablePatchSerializer>(stream, dbc.get(), tp);
+
+
+ P2PVR::sql::Maint_pruneEvents.modify(dbc.get())->execute();
+ logger->messagebf(LOG::INFO, "%s: Updated events", __PRETTY_FUNCTION__);
+
auto sch = P2PVR::SchedulesPrx::checkedCast(ice.adapter->createProxy(ic->stringToIdentity("Schedules")));
sch->DoReschedule();
}
diff --git a/p2pvr/daemon/maintenance/network.cpp b/p2pvr/daemon/maintenance/network.cpp
index fdf2c8e..4b03f6d 100644
--- a/p2pvr/daemon/maintenance/network.cpp
+++ b/p2pvr/daemon/maintenance/network.cpp
@@ -1,88 +1,90 @@
-#include <pch.hpp>
#include "../maintenance.h"
#include <siParsers/network.h>
-#include <sqlMergeTask.h>
#include <Ice/Communicator.h>
-#include <p2Helpers.h>
-#include <containerIterator.h>
#include <temporaryIceAdapterObject.h>
-#include <privateExecContext.h>
+#include <tablepatch.h>
+#include <db/sqlInsertSerializer.h>
+#include <db/sqlTablePatchSerializer.h>
-class SiNetworkInformationMerger : public SiNetworkInformationParser, public PrivateExecContext {
+class SiNetworkInformationMerger : public SiNetworkInformationParser {
public:
- SiNetworkInformationMerger(DatabaseClient * co) : commonObjects(co) { }
+ SiNetworkInformationMerger(DB::Connection * d, IceTray::Logging::LoggerPtr l) :
+ dbc(d),
+ logger(l)
+ {
+ }
bool HandleTable(DVBSI::NetworkPtr n)
{
- Logger()->messagebf(LOG_DEBUG, "Network Id: %d Name: %s", n->NetworkId, *n->Name);
+ logger->messagebf(LOG::DEBUG, "Network Id: %d Name: %s", n->NetworkId, *n->Name);
for (const auto & ts : n->TransportStreams) {
- Logger()->messagebf(LOG_DEBUG, "\tTransport Stream Id: %d Original Network Id: %d", ts->TransportStreamId, ts->OriginalNetworkId);
+ logger->messagebf(LOG::DEBUG, "\tTransport Stream Id: %d Original Network Id: %d", ts->TransportStreamId, ts->OriginalNetworkId);
for (const auto & s : ts->Services) {
- Logger()->messagebf(LOG_DEBUG, "\t\tService Id: %d Service Type: %d", s.ServiceId, s.Type);
+ logger->messagebf(LOG::DEBUG, "\t\tService Id: %d Service Type: %d", s.ServiceId, s.Type);
}
if (ts->Terrestrial) {
- Logger()->messagebf(LOG_DEBUG, "\t\tDVB-T: Frequency: %d", ts->Terrestrial->Frequency);
+ logger->messagebf(LOG::DEBUG, "\t\tDVB-T: Frequency: %d", ts->Terrestrial->Frequency);
}
}
- DatabaseClient::TxHelper tx(commonObjects);
- SqlMergeTask mergeNetwork("postgres", "networks");
- auto ncs = CreateColumns<DVBSI::NetworkPtr>(boost::bind(&DatabaseClient::SqlMergeColumnsInserter, &mergeNetwork, _1, _2));
- std::vector<DVBSI::NetworkPtr> networks = { n };
- mergeNetwork.sources.insert(new ContainerIterator<std::vector<DVBSI::NetworkPtr>>(&networks, ncs));
- mergeNetwork.loadComplete(commonObjects);
- mergeNetwork.execute(this);
+ DB::TablePatch mergeNetwork;
+ mergeNetwork.dest = "networks";
+ Slicer::SerializeAny<Slicer::SqlTablePatchSerializer>(n, dbc, mergeNetwork);
- SqlMergeTask mergeTransports("postgres", "transportstreams");
- auto tscs = CreateColumns<DVBSI::NetworkTransportStreamPtr>(boost::bind(&DatabaseClient::SqlMergeColumnsInserter, &mergeTransports, _1, _2));
- mergeTransports.sources.insert(new ContainerIterator<DVBSI::NetworkTransportStreams>(&n->TransportStreams, tscs));
- mergeTransports.loadComplete(commonObjects);
- mergeTransports.execute(this);
+ DB::TablePatch mergeTransportStreams;
+ mergeTransportStreams.dest = "transportstreams";
+ Slicer::SerializeAny<Slicer::SqlTablePatchSerializer>(n->TransportStreams, dbc, mergeTransportStreams);
mergeDelivery<DVBSI::TerrestrialDeliveryPtr, &DVBSI::NetworkTransportStream::Terrestrial>("delivery_dvbt", n);
mergeDelivery<DVBSI::SatelliteDeliveryPtr, &DVBSI::NetworkTransportStream::Satellite>("delivery_dvbs", n);
mergeDelivery<DVBSI::CableDeliveryPtr, &DVBSI::NetworkTransportStream::Cable>("delivery_dvbc", n);
- SqlMergeTask mergeServices("postgres", "services");
- auto scs = CreateColumns<DVBSI::NetworkService>(boost::bind(&DatabaseClient::SqlMergeColumnsInserter, &mergeServices, _1, _2));
- for (const auto & s : n->TransportStreams) {
- mergeServices.sources.insert(new ContainerIterator<DVBSI::NetworkServiceList>(&s->Services, scs));
+ DVBSI::NetworkServiceList services;
+ for (const auto & ts : n->TransportStreams) {
+ for (const auto & s : ts->Services) {
+ services.push_back(s);
+ }
}
- mergeServices.loadComplete(commonObjects);
- mergeServices.execute(this);
+ DB::TablePatch mergeServices;
+ mergeServices.dest = "services";
+ Slicer::SerializeAny<Slicer::SqlTablePatchSerializer>(services, dbc, mergeServices);
+
return false;
}
private:
template <class Delivery, Delivery DVBSI::NetworkTransportStream::*member>
void mergeDelivery(const std::string & table, DVBSI::NetworkPtr n)
{
- SqlMergeTask merge("postgres", table);
- auto dcs = CreateColumns<Delivery>(boost::bind(&DatabaseClient::SqlMergeColumnsInserter, &merge, _1, _2));
+ DB::TablePatch tp;
+ tp.dest = table;
std::vector<Delivery> dels;
for (const auto & s : n->TransportStreams) {
if (auto d = s.get()->*member) {
dels.push_back(d);
}
}
- merge.sources.insert(new ContainerIterator<decltype(dels)>(&dels, dcs));
- merge.loadComplete(commonObjects);
- merge.execute(this);
+ Slicer::SerializeAny<Slicer::SqlTablePatchSerializer>(dels, dbc, tp);
}
- DatabaseClient * commonObjects;
+ DB::Connection * dbc;
+ IceTray::Logging::LoggerPtr logger;
};
void
Maintenance::UpdateNetwork(short type, const Ice::Current & ice)
{
+ auto dbc = db->get();
auto ic = ice.adapter->getCommunicator();
auto devs = P2PVR::DevicesPrx::checkedCast(ice.adapter->createProxy(ic->stringToIdentity("GlobalDevices")));
auto si = P2PVR::SIPrx::checkedCast(ice.adapter->createProxy(ic->stringToIdentity("SI")));
- auto siparser = new SiNetworkInformationMerger(this);
+ auto siparser = new SiNetworkInformationMerger(dbc.get(), logger);
TemporaryIceAdapterObject<P2PVR::RawDataClient> parser(ice.adapter, siparser);
if (!devs) {
throw std::runtime_error("bad proxy(s)");
}
+
+ DB::TransactionScope tx(dbc.get());
+
auto transport = si->GetDeliveryForSi();
if (transport) {
P2PVR::TunerPrx tuner;
@@ -93,16 +95,16 @@ Maintenance::UpdateNetwork(short type, const Ice::Current & ice)
return;
}
catch (const P2PVR::NoSuitableDeviceAvailable &) {
- Logger()->messagebf(LOG_WARNING, "%s: Failed to get a suitable tuner", __PRETTY_FUNCTION__);
+ logger->messagebf(LOG::WARNING, "%s: Failed to get a suitable tuner", __PRETTY_FUNCTION__);
throw;
}
catch (const std::exception & ex) {
- Logger()->messagebf(LOG_WARNING, "%s: Failed to fetch network information: %s", __PRETTY_FUNCTION__, ex.what());
+ logger->messagebf(LOG::WARNING, "%s: Failed to fetch network information: %s", __PRETTY_FUNCTION__, ex.what());
devs->ReleaseTuner(tuner);
throw;
}
catch (...) {
- Logger()->messagebf(LOG_WARNING, "%s: Failed to fetch network information", __PRETTY_FUNCTION__);
+ logger->messagebf(LOG::WARNING, "%s: Failed to fetch network information", __PRETTY_FUNCTION__);
devs->ReleaseTuner(tuner);
throw;
}
diff --git a/p2pvr/daemon/maintenance/services.cpp b/p2pvr/daemon/maintenance/services.cpp
index e5edbc5..315ca0e 100644
--- a/p2pvr/daemon/maintenance/services.cpp
+++ b/p2pvr/daemon/maintenance/services.cpp
@@ -1,41 +1,41 @@
-#include <pch.hpp>
#include "../maintenance.h"
#include <siParsers/service.h>
-#include <sqlMergeTask.h>
+#include <tablepatch.h>
#include <Ice/Communicator.h>
-#include <p2Helpers.h>
-#include <containerIterator.h>
#include <temporaryIceAdapterObject.h>
-#include <privateExecContext.h>
+#include <slicer/slicer.h>
+#include <db/sqlTablePatchSerializer.h>
+#include <tablepatch.h>
-class SiServicesMerger : public SiServicesParser, public PrivateExecContext {
+class SiServicesMerger : public SiServicesParser {
public:
- SiServicesMerger(DatabaseClient * co) : commonObjects(co) { }
+ SiServicesMerger(IceTray::Logging::LoggerPtr l, DB::Connection * d) :
+ logger(l),
+ dbc(d)
+ {
+ }
bool HandleTable(DVBSI::TransportStreamPtr ts)
{
- Logger()->messagebf(LOG_DEBUG, "Transport Stream Id: %d Original Network Id: %s", ts->TransportStreamId, ts->OriginalNetworkId);
+ logger->messagebf(LOG::DEBUG, "Transport Stream Id: %d Original Network Id: %s", ts->TransportStreamId, ts->OriginalNetworkId);
for (const auto & s : ts->Services) {
- Logger()->messagebf(LOG_DEBUG, "\tService Id: %d Name: %s Type: %d, Provider: %s, DefaultAuthority: %s, RunningStatus %d FreeCaMode %d",
+ logger->messagebf(LOG::DEBUG, "\tService Id: %d Name: %s Type: %d, Provider: %s, DefaultAuthority: %s, RunningStatus %d FreeCaMode %d",
s->ServiceId, (s->Name ? *s->Name : "?"), (s->Type ? *s->Type : -1),
(s->ProviderName ? *s->ProviderName : "?"), (s->DefaultAuthority ? *s->DefaultAuthority : "?"),
s->RunningStatus, s->FreeCaMode);
}
- DatabaseClient::TxHelper tx(commonObjects);
- SqlMergeTask mergeServices("postgres", "services");
- auto scs = CreateColumns<DVBSI::ServicePtr>(boost::bind(&DatabaseClient::SqlMergeColumnsInserter, &mergeServices, _1, _2));
- // Don't change the list of services available from the network
- mergeServices.doDelete = VariableType(false);
- mergeServices.doInsert = VariableType(false);
- mergeServices.sources.insert(new ContainerIterator<DVBSI::ServiceList>(&ts->Services, scs));
- mergeServices.loadComplete(commonObjects);
- mergeServices.execute(this);
+ DB::TablePatch mergeServices;
+ mergeServices.dest = "services";
+ mergeServices.doDeletes = false;
+ mergeServices.doInserts = false;
+ Slicer::SerializeAny<Slicer::SqlTablePatchSerializer>(ts->Services, dbc, mergeServices);
return false;
}
private:
- DatabaseClient * commonObjects;
+ IceTray::Logging::LoggerPtr logger;
+ DB::Connection * dbc;
};
void
@@ -49,7 +49,8 @@ Maintenance::UpdateServices(const Ice::Current & ice)
throw std::runtime_error("bad proxy(s)");
}
- auto siparser = new SiServicesMerger(this);
+ auto dbc = db->get();
+ auto siparser = new SiServicesMerger(logger, dbc.get());
TemporaryIceAdapterObject<P2PVR::RawDataClient> parser(ice.adapter, siparser);
auto delivery = si->GetDeliveryForSi();
@@ -57,11 +58,12 @@ Maintenance::UpdateServices(const Ice::Current & ice)
throw std::runtime_error("no delivery methods");
}
- Logger()->messagebf(LOG_DEBUG, "%s: Getting a tuner", __PRETTY_FUNCTION__);
+ DB::TransactionScope tx(dbc.get());
+ logger->messagebf(LOG::DEBUG, "%s: Getting a tuner", __PRETTY_FUNCTION__);
auto tuner = devs->GetTunerAny(delivery);
- Logger()->messagebf(LOG_DEBUG, "%s: Fetching service list", __PRETTY_FUNCTION__);
+ logger->messagebf(LOG::DEBUG, "%s: Fetching service list", __PRETTY_FUNCTION__);
tuner->SendServiceDescriptions(parser);
- Logger()->messagebf(LOG_INFO, "%s: Updated service list", __PRETTY_FUNCTION__);
+ logger->messagebf(LOG::INFO, "%s: Updated service list", __PRETTY_FUNCTION__);
devs->ReleaseTuner(tuner);
}
diff --git a/p2pvr/daemon/muxedFileSink.cpp b/p2pvr/daemon/muxedFileSink.cpp
index 16a3588..ff6ec35 100644
--- a/p2pvr/daemon/muxedFileSink.cpp
+++ b/p2pvr/daemon/muxedFileSink.cpp
@@ -1,4 +1,3 @@
-#include <pch.hpp>
#include "muxedFileSink.h"
#include <logger.h>
#include <poll.h>
@@ -9,7 +8,8 @@
class MuxerFailure : public P2PVR::DataHandlingException { };
-MuxedFileSink::MuxedFileSink(const boost::filesystem::path & t, const std::string & cmd)
+MuxedFileSink::MuxedFileSink(const boost::filesystem::path & t, const std::string & cmd) :
+ logger(LOGMANAGER()->getLogger<MuxedFileSink>())
{
std::vector<std::string> params;
boost::algorithm::split(params, cmd, isspace, boost::algorithm::token_compress_on);
@@ -20,7 +20,7 @@ MuxedFileSink::MuxedFileSink(const boost::filesystem::path & t, const std::strin
}
fds = ProcessPipesPtr(new AdHoc::System::ProcessPipes(params, true, true, true));
fcntl(fds->fdIn(), F_SETFL, O_NONBLOCK);
- Logger()->messagebf(LOG_INFO, "Muxer::%p started with command '%s' for %s", this, cmd, t);
+ logger->messagebf(LOG::INFO, "Muxer::%p started with command '%s' for %s", this, cmd, t);
}
MuxedFileSink::~MuxedFileSink()
@@ -30,7 +30,7 @@ MuxedFileSink::~MuxedFileSink()
while (waitpid(fds->pid(), &status, WNOHANG) == 0) {
ReadMuxer(5);
}
- Logger()->messagebf(LOG_INFO, "Muxer::%p finished with status %d", this, status);
+ logger->messagebf(LOG::INFO, "Muxer::%p finished with status %d", this, status);
}
bool
@@ -44,7 +44,7 @@ MuxedFileSink::NewData(const P2PVR::Data & data, const Ice::Current &)
// Send some input
auto w = write(fds->fdIn(), &data[off], data.size() - off);
if (w == -1 && errno != EAGAIN && errno != EWOULDBLOCK) {
- Logger()->messagebf(LOG_ERR, "Muxer::%p write failed (%d:%s)", this, errno, strerror(errno));
+ logger->messagebf(LOG::ERR, "Muxer::%p write failed (%d:%s)", this, errno, strerror(errno));
throw MuxerFailure();
}
off += w;
@@ -115,7 +115,7 @@ MuxedFileSink::ReadMuxer(int waitTime) const
boost::algorithm::split(lines, buf, boost::algorithm::is_any_of("\r\n\f"), boost::algorithm::token_compress_on);
for (const auto & line : lines) {
if (line.empty()) continue;
- Logger()->messagebf(LOG_INFO, "Muxer::%p > %s", this, line);
+ logger->messagebf(LOG::INFO, "Muxer::%p > %s", this, line);
}
}
}
diff --git a/p2pvr/daemon/muxedFileSink.h b/p2pvr/daemon/muxedFileSink.h
index ec22a62..d252372 100644
--- a/p2pvr/daemon/muxedFileSink.h
+++ b/p2pvr/daemon/muxedFileSink.h
@@ -6,6 +6,7 @@
#include <boost/filesystem/path.hpp>
#include <boost/shared_ptr.hpp>
#include <processPipes.h>
+#include <logger.h>
class MuxedFileSink : public P2PVR::RawDataClient {
public:
@@ -21,6 +22,8 @@ class MuxedFileSink : public P2PVR::RawDataClient {
typedef boost::shared_ptr<AdHoc::System::ProcessPipes> ProcessPipesPtr;
ProcessPipesPtr fds;
mutable std::mutex lock;
+
+ IceTray::Logging::LoggerPtr logger;
};
#endif
diff --git a/p2pvr/daemon/objectRowState.cpp b/p2pvr/daemon/objectRowState.cpp
deleted file mode 100644
index 89e5ac8..0000000
--- a/p2pvr/daemon/objectRowState.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-#include "objectRowState.h"
-#include <logger.h>
-
-const std::string md_mergeKey("merge:key");
-const std::string md_mergeOmit("merge:omit");
-
-bool
-mdHasFlag(const std::list<std::string> & md, const std::string & flag)
-{
- return std::find(md.begin(), md.end(), flag) != md.end();
-}
-
-SelectedColumns
-CreateColumns(Slicer::ModelPartPtr mp, const ColumnCreator & cc)
-{
- SelectedColumns cols;
- mp->OnEachChild([cc,&cols](const std::string & name, Slicer::ModelPartPtr, Slicer::HookCommonPtr h) {
- auto & md = h->GetMetadata();
- auto omitted = mdHasFlag(md, md_mergeOmit);
- cols.push_back(!omitted);
- if (omitted) return;
- cc(name, mdHasFlag(md, md_mergeKey));
- });
- return cols;
-}
-
-class SqlTarget : public Slicer::ValueTarget,
- public Slicer::TValueTarget<boost::posix_time::time_duration>,
- public Slicer::TValueTarget<boost::posix_time::ptime> {
- public:
- SqlTarget(VariableType & v) : vt(v) {}
-
-#define BIND(Type) \
- virtual void get(const Type & t) const override { vt = t; }
- BIND(bool);
- BIND(::Ice::Byte);
- BIND(::Ice::Short);
- BIND(::Ice::Int);
- BIND(::Ice::Long);
- BIND(::Ice::Float);
- BIND(::Ice::Double);
- BIND(::std::string);
- BIND(boost::posix_time::ptime);
- BIND(boost::posix_time::time_duration);
-
- private:
- VariableType & vt;
-};
-typedef IceUtil::Handle<SqlTarget> SqlTargetPtr;
-
-void
-BindColumns(Slicer::ModelPartPtr mp, const SelectedColumns & sc, RowState & rs)
-{
- unsigned int field = 0;
- mp->OnEachChild([&rs,&field,&sc](const std::string &, Slicer::ModelPartPtr mp, Slicer::HookCommonPtr) {
- if (!sc[field]) return;
- if (mp && mp->HasValue()) {
- SqlTargetPtr st = new SqlTarget(rs.fields[field++]);
- mp->GetValue(st);
- }
- else {
- rs.fields[field++] = Null();
- }
- });
-}
-
-ObjectRowState::ObjectRowState(const ColumnSpecifier & cs) :
- columns(ColumnCreatorHelper(cs))
-{
- fields.resize(columns.size());
-}
-
-const Columns &
-ObjectRowState::getColumns() const
-{
- return columns;
-}
-
-Columns
-ObjectRowState::ColumnCreatorHelper(const ColumnSpecifier & cs)
-{
- int index = 0;
- Columns columns;
- cs([&columns, &index](const std::string & name, bool) {
- columns.insert(new Column(index++, name));
- });
- return columns;
-}
-
diff --git a/p2pvr/daemon/objectRowState.h b/p2pvr/daemon/objectRowState.h
deleted file mode 100644
index 252a411..0000000
--- a/p2pvr/daemon/objectRowState.h
+++ /dev/null
@@ -1,48 +0,0 @@
-#ifndef OBJECT_ROW_STATE_H
-#define OBJECT_ROW_STATE_H
-
-#include <boost/function.hpp>
-#include <string>
-#include <rowSet.h>
-#include <slicer/modelParts.h>
-
-typedef boost::function<void(const std::string &, bool)> ColumnCreator;
-typedef boost::function<void(const ColumnCreator &)> ColumnSpecifier;
-typedef std::vector<bool> SelectedColumns;
-
-void BindColumns(Slicer::ModelPartPtr, const SelectedColumns &, RowState &);
-
-template <typename V>
-void BindColumns(RowState & rs, const SelectedColumns & sc, const V & v)
-{
- BindColumns(Slicer::ModelPart::CreateFor(const_cast<V &>(v)), sc, rs);
-}
-
-SelectedColumns CreateColumns(Slicer::ModelPartPtr, const ColumnCreator &);
-
-template <typename V>
-SelectedColumns CreateColumns(const ColumnCreator & cc)
-{
- V v;
- return CreateColumns(Slicer::ModelPart::CreateFor(v), cc);
-}
-
-class ObjectRowState : public RowState {
- public:
- ObjectRowState(const ColumnSpecifier & cs);
- const Columns & getColumns() const;
-
- private:
- static Columns ColumnCreatorHelper(const ColumnSpecifier & cs);
-
- Columns columns;
-};
-
-template <typename T>
-class ObjectRowStateTmpl : public ObjectRowState {
- public:
- ObjectRowStateTmpl(const ColumnSpecifier & cs = CreateColumns<T>) : ObjectRowState(cs) {}
-};
-
-#endif
-
diff --git a/p2pvr/daemon/p2pvr-int.ice b/p2pvr/daemon/p2pvr-int.ice
index 1dfaf17..a4f2311 100644
--- a/p2pvr/daemon/p2pvr-int.ice
+++ b/p2pvr/daemon/p2pvr-int.ice
@@ -1,4 +1,5 @@
#include <common.ice>
+#include <dvbsi.ice>
module P2PVR {
class ScheduleCandidate {
@@ -12,5 +13,8 @@ module P2PVR {
};
sequence<ScheduleCandidate> ScheduleCandidates;
+ sequence<DVBSI::SatelliteDelivery> SatelliteDeliverySeq;
+ sequence<DVBSI::CableDelivery> CableDeliverySeq;
+ sequence<DVBSI::TerrestrialDelivery> TerrestrialDeliverySeq;
};
diff --git a/p2pvr/daemon/pch.hpp b/p2pvr/daemon/pch.hpp
deleted file mode 100644
index 7c96f52..0000000
--- a/p2pvr/daemon/pch.hpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#ifdef BOOST_BUILD_PCH_ENABLED
-#ifndef P2PVRLIB_PCH
-#define P2PVRLIB_PCH
-
-#include <Ice/Ice.h>
-#include <glibmm.h>
-#include <boost/bind.hpp>
-#include <boost/function/function_fwd.hpp>
-#include <boost/intrusive_ptr.hpp>
-#include <boost/shared_ptr.hpp>
-
-#include <list>
-#include <map>
-#include <set>
-#include <string>
-#include <vector>
-
-#endif
-#endif
-
diff --git a/p2pvr/daemon/privateExecContext.cpp b/p2pvr/daemon/privateExecContext.cpp
deleted file mode 100644
index 47c5773..0000000
--- a/p2pvr/daemon/privateExecContext.cpp
+++ /dev/null
@@ -1,14 +0,0 @@
-#include "privateExecContext.h"
-
-VariableType
-PrivateExecContext::getParameter(const VariableType &) const
-{
- throw NotSupported(__PRETTY_FUNCTION__);
-}
-
-SessionPtr
-PrivateExecContext::getSession() const
-{
- throw NotSupported(__PRETTY_FUNCTION__);
-}
-
diff --git a/p2pvr/daemon/privateExecContext.h b/p2pvr/daemon/privateExecContext.h
deleted file mode 100644
index 1d336b0..0000000
--- a/p2pvr/daemon/privateExecContext.h
+++ /dev/null
@@ -1,13 +0,0 @@
-#ifndef PRIVATEEXECCONTENT_H
-#define PRIVATEEXECCONTENT_H
-
-#include <execContext.h>
-
-class PrivateExecContext : public ExecContext {
- public:
- VariableType getParameter(const VariableType & key) const;
- SessionPtr getSession() const;
-};
-
-#endif
-
diff --git a/p2pvr/daemon/recorder.cpp b/p2pvr/daemon/recorder.cpp
index e965253..548ad11 100644
--- a/p2pvr/daemon/recorder.cpp
+++ b/p2pvr/daemon/recorder.cpp
@@ -1,4 +1,3 @@
-#include <pch.hpp>
#include "recorder.h"
#include "bindTimerTask.h"
#include <boost/bind.hpp>
@@ -10,22 +9,29 @@
#include "muxer.h"
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
+#include <boost/lexical_cast.hpp>
-std::string Recorder::extension;
-std::string Recorder::muxerCommand;
+namespace po = boost::program_options;
-DECLARE_OPTIONS(Recorder, "P2PVR Recorder options")
-("p2pvr.recorder.extension", Options::value(&extension, "mp4"),
- "File extension to save with (default: mp4)")
-("p2pvr.recorder.muxercommand", Options::value(&muxerCommand, "/usr/bin/ffmpeg -f mpegts -i - -f dvd -codec copy -"),
- "Command to perform TS->PS muxing (default: '/usr/bin/ffmpeg -f mpegts -i - -f dvd -codec copy -')")
-END_OPTIONS(Recorder);
+Recorder::Options::Options() :
+ IceTray::Options("P2PVR Recorder options")
+{
+}
+
+ICETRAY_OPTIONS(Recorder::Options,
+ ("p2pvr.recorder.extension", po::value(&extension)->default_value("mp4"),
+ "File extension to save with (default: mp4)")
+ ("p2pvr.recorder.muxercommand", po::value(&muxerCommand)->default_value("/usr/bin/ffmpeg -f mpegts -i - -f dvd -codec copy -"),
+ "Command to perform TS->PS muxing (default: '/usr/bin/ffmpeg -f mpegts -i - -f dvd -codec copy -')")
+);
+
+IceTray::Logging::LoggerPtr Recorder::logger(LOGMANAGER()->getLogger<Recorder>());
Recorder::Recorder(Ice::ObjectAdapterPtr a, IceUtil::TimerPtr t) :
adapter(a),
timer(t)
{
- Logger()->message(LOG_DEBUG, __PRETTY_FUNCTION__);
+ logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
RefreshSchedules(Ice::Current());
}
@@ -53,7 +59,7 @@ Recorder::RefreshSchedules(const Ice::Current &)
IceUtil::TimerTaskPtr startTimer = new BindTimerTask(boost::bind(&Recorder::StartRecording, this, schedule, service, event));
timer->schedule(startTimer, IceUtil::Time::seconds(startIn));
pendingRecordings.push_back(startTimer);
- Logger()->messagebf(LOG_DEBUG, "Recording %s scheduled for %s seconds", event->Title, startIn);
+ logger->messagebf(LOG::DEBUG, "Recording %s scheduled for %s seconds", event->Title, startIn);
}
}
@@ -63,21 +69,23 @@ Recorder::StartRecording(P2PVR::SchedulePtr schedule, DVBSI::ServicePtr service,
std::lock_guard<std::mutex> g(lock);
auto storage = P2PVR::StoragePrx::checkedCast(adapter->createProxy(adapter->getCommunicator()->stringToIdentity("Storage")));
auto recordings = P2PVR::RecordingsPrx::checkedCast(adapter->createProxy(adapter->getCommunicator()->stringToIdentity("Recordings")));
+ auto devices = P2PVR::DevicesPrx::checkedCast(adapter->createProxy(adapter->getCommunicator()->stringToIdentity("GlobalDevices")));
+ auto si = P2PVR::SIPrx::checkedCast(adapter->createProxy(adapter->getCommunicator()->stringToIdentity("SI")));
auto id = boost::lexical_cast<std::string>(boost::uuids::random_generator()());
auto store = storage->OpenForWrite(id);
AdHoc::ScopeExit _store(NULL, NULL, [this,&store,&storage,&id]() { storage->Close(store); storage->Delete(id); });
auto target = store;
P2PVR::RawDataClientPrx muxer;
- if (!muxerCommand.empty()) {
- muxer = P2PVR::RawDataClientPrx::checkedCast(adapter->addWithUUID(new Muxer(store, muxerCommand)));
+ if (!options->muxerCommand.empty()) {
+ muxer = P2PVR::RawDataClientPrx::checkedCast(adapter->addWithUUID(new Muxer(store, options->muxerCommand)));
target = muxer;
}
AdHoc::ScopeExit _muxer(NULL, NULL, [this,&muxer]() { if (muxer) adapter->remove(muxer->ice_getIdentity()); });
- auto ss = ServiceStreamerPtr(new ServiceStreamer(service->ServiceId, target, adapter->getCommunicator(), adapter));
+ auto ss = ServiceStreamerPtr(new ServiceStreamer(service->ServiceId, target, devices, si, adapter));
ss->Start();
- Logger()->messagebf(LOG_INFO, "Started recording %s (%s - %s) on %s (%d)",
+ logger->messagebf(LOG::INFO, "Started recording %s (%s - %s) on %s (%d)",
event->Title, event->StartTime, event->StopTime,
service->Name ? *service->Name : "<no name>", service->ServiceId);
@@ -88,14 +96,14 @@ Recorder::StartRecording(P2PVR::SchedulePtr schedule, DVBSI::ServicePtr service,
auto stopIn = (*event->StopTime + *schedule->Late - boost::posix_time::second_clock::universal_time()).total_seconds();
newCurrent->stopTimer = new BindTimerTask(boost::bind(&Recorder::StopRecording, this, newCurrent));
timer->schedule(newCurrent->stopTimer, IceUtil::Time::seconds(stopIn));
- Logger()->messagebf(LOG_DEBUG, "Recording %s scheduled stop in %s seconds", event->Title, stopIn);
+ logger->messagebf(LOG::DEBUG, "Recording %s scheduled stop in %s seconds", event->Title, stopIn);
}
void
Recorder::StopRecording(CurrentPtr c)
{
std::lock_guard<std::mutex> g(lock);
- Logger()->messagebf(LOG_DEBUG, "Stopping %s", c->event->Title);
+ logger->messagebf(LOG::DEBUG, "Stopping %s", c->event->Title);
c->stream->Stop();
if (c->muxer) {
adapter->remove(c->muxer->ice_getIdentity());
@@ -103,6 +111,6 @@ Recorder::StopRecording(CurrentPtr c)
currentRecordings.erase(c);
auto storage = P2PVR::StoragePrx::checkedCast(adapter->createProxy(adapter->getCommunicator()->stringToIdentity("Storage")));
storage->Close(c->store);
- Logger()->messagebf(LOG_DEBUG, "Stopped %s", c->event->Title);
+ logger->messagebf(LOG::DEBUG, "Stopped %s", c->event->Title);
}
diff --git a/p2pvr/daemon/recorder.h b/p2pvr/daemon/recorder.h
index 6a6940e..e6ff42a 100644
--- a/p2pvr/daemon/recorder.h
+++ b/p2pvr/daemon/recorder.h
@@ -8,9 +8,20 @@
#include <mutex>
#include "serviceStreamer.h"
#include <visibility.h>
+#include <logger.h>
class DLL_PUBLIC Recorder : public P2PVR::Recorder {
public:
+ class Options : public IceTray::Options {
+ public:
+ Options();
+
+ ICETRAY_OPTIONS_DECLARE;
+
+ std::string extension;
+ std::string muxerCommand;
+ };
+
typedef std::vector<IceUtil::TimerTaskPtr> Pendings;
class Current {
@@ -30,8 +41,6 @@ class DLL_PUBLIC Recorder : public P2PVR::Recorder {
void RefreshSchedules(const Ice::Current &);
- INITOPTIONS;
-
private:
DLL_PRIVATE void StartRecording(P2PVR::SchedulePtr schedule, DVBSI::ServicePtr service, P2PVR::EventPtr event);
DLL_PRIVATE void StopRecording(CurrentPtr);
@@ -43,8 +52,8 @@ class DLL_PUBLIC Recorder : public P2PVR::Recorder {
Pendings pendingRecordings;
std::mutex lock;
- static std::string extension;
- static std::string muxerCommand;
+ IceTray::OptionsResolver<Options> options;
+ static IceTray::Logging::LoggerPtr logger;
};
#endif
diff --git a/p2pvr/daemon/recordings.cpp b/p2pvr/daemon/recordings.cpp
index ac8f27a..7c5125b 100644
--- a/p2pvr/daemon/recordings.cpp
+++ b/p2pvr/daemon/recordings.cpp
@@ -1,50 +1,45 @@
-#include <pch.hpp>
#include "recordings.h"
-#include "resources.h"
#include <Ice/Ice.h>
#include <logger.h>
#include <slicer/slicer.h>
#include <slicer/db/sqlSelectDeserializer.h>
#include <slicer/db/sqlInsertSerializer.h>
+#include <sql/Recordings_delete.sql.h>
+#include <sql/Recordings_getAll.sql.h>
+#include <sql/Recordings_getStorage.sql.h>
-ResourceString(Recording_Delete, sql_Recordings_delete);
-ResourceString(Recording_GetStorage, sql_Recordings_getStorage);
-ResourceString(Recording_GetAll, sql_Recordings_getAll);
+IceTray::Logging::LoggerPtr Recordings::logger(LOGMANAGER()->getLogger<Recordings>());
+
+Recordings::Recordings(IceTray::DatabasePoolPtr db) :
+ IceTray::AbstractDatabaseClient(db)
+{
+}
Ice::Int
Recordings::NewRecording(const P2PVR::RecordingPtr & r, const Ice::Current &)
{
- Logger()->messagebf(LOG_INFO, "%s: Creating new recording %s at %s", __PRETTY_FUNCTION__, r->Guid, r->StorageAddress);
- TxHelper tx(this);
- Store<Slicer::SqlFetchIdInsertSerializer>(r, "recordings");
- Logger()->messagebf(LOG_INFO, "%s: Created recording Id: %d", __PRETTY_FUNCTION__, r->RecordingId);
+ auto dbc = db->get();
+ logger->messagebf(LOG::INFO, "%s: Creating new recording %s at %s", __PRETTY_FUNCTION__, r->Guid, r->StorageAddress);
+ DB::TransactionScope tx(dbc.get());
+ Slicer::SerializeAny<Slicer::SqlFetchIdInsertSerializer>(r, dbc.get(), "recordings");
+ logger->messagebf(LOG::INFO, "%s: Created recording Id: %d", __PRETTY_FUNCTION__, r->RecordingId);
return r->RecordingId;
}
void
-Recordings::DeleteRecording(int id, const Ice::Current & ice)
+Recordings::DeleteRecording(int id, const Ice::Current &)
{
- Logger()->messagebf(LOG_INFO, "%s: Deleting recording Id: %d", __PRETTY_FUNCTION__, id);
- auto ic = ice.adapter->getCommunicator();
- TxHelper tx(this);
- auto recordingStorages = Select(Recording_GetStorage, id);
- while (recordingStorages.second->fetch()) {
- std::string addr = recordingStorages.second / "storageaddress";
- std::string guid = recordingStorages.second / "guid";
- auto storage = P2PVR::StoragePrx::checkedCast(ic->stringToProxy(addr));
- if (storage) {
- storage->Delete(guid);
- Logger()->messagebf(LOG_DEBUG, "%s: Delete %s from StorageAddress %s", __PRETTY_FUNCTION__, guid, addr);
- }
- }
- Modify(Recording_Delete, id).second->execute();
+ auto dbc = db->get();
+ logger->messagebf(LOG::INFO, "%s: Deleting recording Id: %d", __PRETTY_FUNCTION__, id);
+ auto del = P2PVR::sql::Recordings_delete.modify(dbc.get());
+ del->bindParamI(0, id);
+ del->execute();
}
P2PVR::RecordingList
Recordings::GetRecordings(const Ice::Current &)
{
- Logger()->message(LOG_DEBUG, __PRETTY_FUNCTION__);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::RecordingList>(
- *Select(Recording_GetAll).second);
+ logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
+ return fetch<P2PVR::RecordingList>(P2PVR::sql::Recordings_getAll);
}
diff --git a/p2pvr/daemon/recordings.h b/p2pvr/daemon/recordings.h
index 482ce23..1182ff6 100644
--- a/p2pvr/daemon/recordings.h
+++ b/p2pvr/daemon/recordings.h
@@ -3,14 +3,20 @@
#include <p2pvr.h>
#include <string>
-#include "dbClient.h"
#include <visibility.h>
+#include <logger.h>
+#include <abstractDatabaseClient.h>
-class DLL_PUBLIC Recordings : public DatabaseClient, public P2PVR::Recordings {
+class DLL_PUBLIC Recordings : public P2PVR::Recordings, public IceTray::AbstractDatabaseClient {
public:
+ Recordings(IceTray::DatabasePoolPtr db);
+
Ice::Int NewRecording(const P2PVR::RecordingPtr & rec, const Ice::Current &);
void DeleteRecording(int recordingId, const Ice::Current &);
P2PVR::RecordingList GetRecordings(const Ice::Current &);
+
+ private:
+ static IceTray::Logging::LoggerPtr logger;
};
#endif
diff --git a/p2pvr/daemon/resources.h b/p2pvr/daemon/resources.h
deleted file mode 100644
index 18b1de2..0000000
--- a/p2pvr/daemon/resources.h
+++ /dev/null
@@ -1,12 +0,0 @@
-#ifndef RESOURCES_H
-#define RESOURCES_H
-
-#define ResourceString(name, resource) \
-extern "C" { \
- extern char resource##_start, resource##_end;\
- extern unsigned int resource##_len; \
-} \
-static const std::string name(&resource##_start, &resource##_end);
-
-#endif
-
diff --git a/p2pvr/daemon/schedulers/bitDumbScheduler.cpp b/p2pvr/daemon/schedulers/bitDumbScheduler.cpp
index 1681103..10955e5 100644
--- a/p2pvr/daemon/schedulers/bitDumbScheduler.cpp
+++ b/p2pvr/daemon/schedulers/bitDumbScheduler.cpp
@@ -1,4 +1,3 @@
-#include <pch.hpp>
#include "../schedules.h"
class TheBitDumbScheduler : public EpisodeGroup {
diff --git a/p2pvr/daemon/schedules.cpp b/p2pvr/daemon/schedules.cpp
index 90a42a9..f343e91 100644
--- a/p2pvr/daemon/schedules.cpp
+++ b/p2pvr/daemon/schedules.cpp
@@ -1,34 +1,35 @@
-#include <pch.hpp>
#include "schedules.h"
-#include <rdbmsDataSource.h>
#include <logger.h>
#include <Ice/Ice.h>
-#include <sqlVariableBinder.h>
-#include <sqlMergeTask.h>
-#include "p2Helpers.h"
#include "commonHelpers.h"
-#include "containerIterator.h"
-#include "resources.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <factory.impl.h>
#include <slicer/db/sqlSelectDeserializer.h>
#include <slicer/db/sqlInsertSerializer.h>
#include <slicer/db/sqlUpdateSerializer.h>
+#include <slicer/db/sqlTablePatchSerializer.h>
+#include <tablepatch.h>
#include <p2pvr-int.h>
-#include <privateExecContext.h>
-ResourceString(Schedules_getCandidates, sql_Schedules_getCandidates);
-ResourceString(Schedules_delete, sql_Schedules_delete);
-ResourceString(Schedules_selectAll, sql_Schedules_selectAll);
-ResourceString(Schedules_selectById, sql_Schedules_selectById);
-ResourceString(Schedules_scheduledToRecord, sql_Schedules_scheduledToRecord);
+#include "sql/Schedules_getCandidates.sql.h"
+#include "sql/Schedules_delete.sql.h"
+#include "sql/Schedules_selectAll.sql.h"
+#include "sql/Schedules_selectById.sql.h"
+#include "sql/Schedules_scheduledToRecord.sql.h"
-std::string Schedules::SchedulerAlgorithm;
+namespace po = boost::program_options;
-DECLARE_OPTIONS(Schedules, "P2PVR Scheduler options")
-("p2pvr.scheduler.algorithm", Options::value(&SchedulerAlgorithm, "BitDumb"),
- "Implementation of episode group scheduler problem solver")
-END_OPTIONS()
+IceTray::Logging::LoggerPtr Schedules::logger(LOGMANAGER()->getLogger<Schedules>());
+
+Schedules::Options::Options() :
+ IceTray::Options("P2PVR Scheduler options")
+{
+}
+
+ICETRAY_OPTIONS(Schedules::Options,
+ ("p2pvr.scheduler.algorithm", po::value(&SchedulerAlgorithm)->default_value("BitDumb"),
+ "Implementation of episode group scheduler problem solver")
+)
Showing::Showing(unsigned int e, unsigned int t, unsigned int sc, datetime start, datetime stop, int p, const Episode * ep) :
episode(ep),
@@ -162,6 +163,11 @@ EpisodeGroup::SuggestWithFeedback(const Showings & showings)
}
}
+Schedules::Schedules(IceTray::DatabasePoolPtr db) :
+ IceTray::AbstractDatabaseClient(db)
+{
+}
+
void
Schedules::GetEpisodeIntersects(Episodes & all, Episodes & grouped)
{
@@ -171,7 +177,7 @@ Schedules::GetEpisodeIntersects(Episodes & all, Episodes & grouped)
for (const auto & gs : ge->showings) {
for (const auto & as : ae->showings) {
if (gs->period.intersects(as->period)) {
- Logger()->messagebf(LOG_DEBUG, " added %s", ae->what);
+ logger->messagebf(LOG::DEBUG, " added %s", ae->what);
grouped.push_back(ae);
all.erase(aei);
GetEpisodeIntersects(all, grouped);
@@ -191,8 +197,7 @@ Schedules::DoReschedule(const Ice::Current & ice)
unsigned int tunerCount = devs->TunerCount();
// Load list from database
- auto episodes = Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::ScheduleCandidates>(
- *Select(Schedules_getCandidates).second);
+ auto episodes = fetch<P2PVR::ScheduleCandidates>(P2PVR::sql::Schedules_getCandidates);
Episodes scheduleList;
Showings allShowings;
@@ -209,9 +214,9 @@ Schedules::DoReschedule(const Ice::Current & ice)
cur->showings.push_back(s);
allShowings.push_back(s);
}
- Logger()->messagebf(LOG_DEBUG, "%d episodes created, %s showings", scheduleList.size(), allShowings.size());
+ logger->messagebf(LOG::DEBUG, "%d episodes created, %s showings", scheduleList.size(), allShowings.size());
for (const auto & e : scheduleList) {
- Logger()->messagebf(LOG_DEBUG, " %s", e->what);
+ logger->messagebf(LOG::DEBUG, " %s", e->what);
for (const auto & s : e->showings) {
s->priority += 1 - minPriority;
e->priority += s->priority;
@@ -223,7 +228,7 @@ Schedules::DoReschedule(const Ice::Current & ice)
// Solve
while (!scheduleList.empty()) {
auto work = scheduleList.begin();
- Logger()->messagebf(LOG_DEBUG, "start %s", (*work)->what);
+ logger->messagebf(LOG::DEBUG, "start %s", (*work)->what);
Episodes group;
group.push_back(*work);
scheduleList.erase(work);
@@ -234,17 +239,17 @@ Schedules::DoReschedule(const Ice::Current & ice)
return a->what < b->what;
});
- Logger()->messagebf(LOG_DEBUG, "group created with %d episodes", group.size());
+ logger->messagebf(LOG::DEBUG, "group created with %d episodes", group.size());
double total = 1;
// Measure and add the optional to not record
for (const auto & e : group) {
- Logger()->messagebf(LOG_DEBUG, " %d * %d:%s", e->showings.size(), e->priority, e->what);
+ logger->messagebf(LOG::DEBUG, " %d * %d:%s", e->showings.size(), e->priority, e->what);
e->showings.push_back(NULL);
total *= e->showings.size();
}
- Logger()->messagebf(LOG_DEBUG, "group complexity of %d options", total);
+ logger->messagebf(LOG::DEBUG, "group complexity of %d options", total);
- EpisodeGroupPtr sched = EpisodeGroupPtr(EpisodeGroupFactory::createNew(SchedulerAlgorithm, group));
+ EpisodeGroupPtr sched = EpisodeGroupPtr(EpisodeGroupFactory::createNew(options->SchedulerAlgorithm, group));
sched->tuners = tunerCount;
std::set<ShowingPtr> selected;
for (const auto & s : sched->Solve()) {
@@ -252,17 +257,17 @@ Schedules::DoReschedule(const Ice::Current & ice)
}
for (const auto & c : group) {
- Logger()->messagebf(LOG_DEBUG, "Episode %s, %d options", c->what, c->showings.size());
+ logger->messagebf(LOG::DEBUG, "Episode %s, %d options", c->what, c->showings.size());
for (const auto & i : c->showings) {
if (selected.find(i) != selected.end()) {
- Logger()->messagebf(LOG_DEBUG, " %s - %s (%d) <-", i->startTime, i->stopTime, i->transportStreamId);
+ logger->messagebf(LOG::DEBUG, " %s - %s (%d) <-", i->startTime, i->stopTime, i->transportStreamId);
}
else if (i) {
- Logger()->messagebf(LOG_DEBUG, " %s - %s (%d)", i->startTime, i->stopTime, i->transportStreamId);
+ logger->messagebf(LOG::DEBUG, " %s - %s (%d)", i->startTime, i->stopTime, i->transportStreamId);
}
}
}
- Logger()->message(LOG_DEBUG, "----------");
+ logger->message(LOG::DEBUG, "----------");
for (const auto & c : group) {
bool found = false;
for (const auto & i : c->showings) {
@@ -282,14 +287,11 @@ Schedules::DoReschedule(const Ice::Current & ice)
}
}
- TxHelper tx(this);
- PrivateExecContext ec;
- SqlMergeTask mergeRecords("postgres", "record");
- auto rcs = CreateColumns<P2PVR::ScheduledToRecordPtr>(boost::bind(&DatabaseClient::SqlMergeColumnsInserter, &mergeRecords, _1, _2));
- mergeRecords.sources.insert(new ContainerIterator<P2PVR::ScheduledToRecordList>(&records, rcs));
- mergeRecords.loadComplete(this);
- mergeRecords.execute(&ec);
- tx.Commit();
+ auto dbc = db->get();
+ DB::TransactionScope tx(dbc.get());
+ DB::TablePatch mergeRecords;
+ mergeRecords.dest = "record";
+ Slicer::SerializeAny<Slicer::SqlTablePatchSerializer>(records, dbc.get(), mergeRecords);
auto recorder = P2PVR::RecorderPrx::checkedCast(ice.adapter->createProxy(ice.adapter->getCommunicator()->stringToIdentity("Recorder")));
recorder->RefreshSchedules();
@@ -298,25 +300,25 @@ Schedules::DoReschedule(const Ice::Current & ice)
void
Schedules::DeleteSchedule(int id, const Ice::Current & ice)
{
- TxHelper tx(this);
- Modify(Schedules_delete, id).second->execute();
+ auto dbc = db->get();
+ auto del = P2PVR::sql::Schedules_delete.modify(dbc.get());
+ del->bindParamI(0, id);
+ del->execute();
DoReschedule(ice);
}
P2PVR::ScheduleList
Schedules::GetSchedules(const Ice::Current &)
{
- Logger()->message(LOG_DEBUG, __PRETTY_FUNCTION__);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::ScheduleList>(
- *Select(Schedules_selectAll).second);
+ logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
+ return fetch<P2PVR::ScheduleList>(P2PVR::sql::Schedules_selectAll);
}
P2PVR::SchedulePtr
Schedules::GetSchedule(int id, const Ice::Current &)
{
- Logger()->messagebf(LOG_DEBUG, "%s(%d)", __PRETTY_FUNCTION__, id);
- auto schedules = Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::ScheduleList>(
- *Select(Schedules_selectById, id).second);
+ logger->messagebf(LOG::DEBUG, "%s(%d)", __PRETTY_FUNCTION__, id);
+ auto schedules = fetch<P2PVR::ScheduleList>(P2PVR::sql::Schedules_selectById, id);
if (schedules.empty()) throw P2PVR::NotFound();
return schedules.front();
}
@@ -324,16 +326,15 @@ Schedules::GetSchedule(int id, const Ice::Current &)
P2PVR::ScheduledToRecordList
Schedules::GetScheduledToRecord(const Ice::Current &)
{
- Logger()->message(LOG_DEBUG, __PRETTY_FUNCTION__);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::ScheduledToRecordList>(
- *Select(Schedules_scheduledToRecord).second);
+ logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
+ return fetch<P2PVR::ScheduledToRecordList>(P2PVR::sql::Schedules_scheduledToRecord);
}
Ice::Int
Schedules::NewSchedule(const P2PVR::SchedulePtr & s, const Ice::Current & ice)
{
- TxHelper tx(this);
- Store<Slicer::SqlFetchIdInsertSerializer>(s, "schedules");
+ auto dbc = db->get();
+ Slicer::SerializeAny<Slicer::SqlFetchIdInsertSerializer>(s, dbc.get(), "schedules");
DoReschedule(ice);
return s->ScheduleId;
}
@@ -341,8 +342,8 @@ Schedules::NewSchedule(const P2PVR::SchedulePtr & s, const Ice::Current & ice)
void
Schedules::UpdateSchedule(const P2PVR::SchedulePtr & s, const Ice::Current & ice)
{
- TxHelper tx(this);
- Store<Slicer::SqlUpdateSerializer>(s, "schedules");
+ auto dbc = db->get();
+ Slicer::SerializeAny<Slicer::SqlUpdateSerializer>(s, dbc.get(), "schedules");
DoReschedule(ice);
}
diff --git a/p2pvr/daemon/schedules.h b/p2pvr/daemon/schedules.h
index 122e214..1acf69f 100644
--- a/p2pvr/daemon/schedules.h
+++ b/p2pvr/daemon/schedules.h
@@ -3,9 +3,11 @@
#include <p2pvr.h>
#include <options.h>
-#include "dbClient.h"
+#include <abstractDatabaseClient.h>
#include <factory.h>
#include <visibility.h>
+#include <intrusivePtrBase.h>
+#include <logger.h>
typedef boost::posix_time::ptime datetime;
class Episode;
@@ -62,8 +64,19 @@ class EpisodeGroup {
Showings selected;
};
-class DLL_PUBLIC Schedules : public P2PVR::Schedules, public DatabaseClient {
+class DLL_PUBLIC Schedules : public P2PVR::Schedules, public IceTray::AbstractDatabaseClient {
public:
+ class Options : public IceTray::Options {
+ public:
+ Options();
+
+ ICETRAY_OPTIONS_DECLARE;
+
+ std::string SchedulerAlgorithm;
+ };
+
+ Schedules(IceTray::DatabasePoolPtr);
+
void DeleteSchedule(int id, const Ice::Current &);
P2PVR::SchedulePtr GetSchedule(int id, const Ice::Current &);
P2PVR::ScheduleList GetSchedules(const Ice::Current &);
@@ -72,12 +85,12 @@ class DLL_PUBLIC Schedules : public P2PVR::Schedules, public DatabaseClient {
void UpdateSchedule(const P2PVR::SchedulePtr &, const Ice::Current &);
void DoReschedule(const Ice::Current &);
- INITOPTIONS;
protected:
static void GetEpisodeIntersects(Episodes &, Episodes &);
private:
- static std::string SchedulerAlgorithm;
+ IceTray::OptionsResolver<Options> options;
+ static IceTray::Logging::LoggerPtr logger;
};
typedef AdHoc::Factory<EpisodeGroup, const Episodes &> EpisodeGroupFactory;
diff --git a/p2pvr/daemon/si.cpp b/p2pvr/daemon/si.cpp
index bff86fb..1186547 100644
--- a/p2pvr/daemon/si.cpp
+++ b/p2pvr/daemon/si.cpp
@@ -1,6 +1,4 @@
-#include <pch.hpp>
#include "si.h"
-#include "resources.h"
#include <slicer/db/sqlSelectDeserializer.h>
#include <slicer/common.h>
#include <slicer/db/sqlExceptions.h>
@@ -8,36 +6,41 @@
#include <slicer/slicer.h>
#include <logger.h>
-ResourceString(SI_allNetworks, sql_SI_allNetworks);
-ResourceString(SI_allDeliveries, sql_SI_allDeliveries);
-ResourceString(SI_deliveryForTransport, sql_SI_deliveryForTransport);
-ResourceString(SI_deliveryForService, sql_SI_deliveryForService);
-ResourceString(SI_serviceNextUsed, sql_SI_serviceNextUsed);
-ResourceString(SI_servicesSelectAll, sql_SI_servicesSelectAll);
-ResourceString(SI_servicesSelectById, sql_SI_servicesSelectById);
-ResourceString(SI_eventByUid, sql_SI_eventByUid);
-ResourceString(SI_eventById, sql_SI_eventById);
-ResourceString(SI_eventsOnNow, sql_SI_eventsOnNow);
-ResourceString(SI_eventsInSchedule, sql_SI_eventsInSchedule);
-ResourceString(SI_eventsInSchedules, sql_SI_eventsInSchedules);
-ResourceString(SI_eventsInRange, sql_SI_eventsInRange);
-ResourceString(SI_eventSearch, sql_SI_eventSearch);
+#include "sql/SI_allNetworks.sql.h"
+#include "sql/SI_allDeliveries.sql.h"
+#include "sql/SI_deliveryForTransport.sql.h"
+#include "sql/SI_deliveryForService.sql.h"
+#include "sql/SI_serviceNextUsed.sql.h"
+#include "sql/SI_servicesSelectAll.sql.h"
+#include "sql/SI_servicesSelectById.sql.h"
+#include "sql/SI_eventByUid.sql.h"
+#include "sql/SI_eventById.sql.h"
+#include "sql/SI_eventsOnNow.sql.h"
+#include "sql/SI_eventsInSchedule.sql.h"
+#include "sql/SI_eventsInSchedules.sql.h"
+#include "sql/SI_eventsInRange.sql.h"
+#include "sql/SI_eventSearch.sql.h"
+
+IceTray::Logging::LoggerPtr SI::logger(LOGMANAGER()->getLogger<SI>());
+
+SI::SI(IceTray::DatabasePoolPtr db) :
+ IceTray::AbstractDatabaseClient(db)
+{
+}
DVBSI::Networks
SI::GetNetworks(const Ice::Current &)
{
- Logger()->message(LOG_DEBUG, __PRETTY_FUNCTION__);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, DVBSI::Networks>(
- *Select(SI_allNetworks).second);
+ logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
+ return fetch<DVBSI::Networks>(P2PVR::sql::SI_allNetworks);
}
P2PVR::Deliveries
SI::GetAllDeliveries(const Ice::Current &)
{
- Logger()->message(LOG_DEBUG, __PRETTY_FUNCTION__);
- auto rtn = Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::Deliveries>(
- *Select(SI_allDeliveries).second, "delivery_type");
- Logger()->messagebf(LOG_DEBUG, "%s: Found %d delivery methods", __PRETTY_FUNCTION__, rtn.size());
+ logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
+ auto rtn = fetch<P2PVR::Deliveries>("delivery_type", P2PVR::sql::SI_allDeliveries);
+ logger->messagebf(LOG::DEBUG, "%s: Found %d delivery methods", __PRETTY_FUNCTION__, rtn.size());
return rtn;
}
@@ -45,9 +48,8 @@ DVBSI::DeliveryPtr
SI::GetDeliveryForTransport(int id, const Ice::Current&)
{
try {
- Logger()->messagef(LOG_DEBUG, "%s(%d)", __PRETTY_FUNCTION__, id);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, DVBSI::DeliveryPtr>(
- *Select(SI_deliveryForTransport, id).second, "delivery_type");
+ logger->messagef(LOG::DEBUG, "%s(%d)", __PRETTY_FUNCTION__, id);
+ return fetch<DVBSI::DeliveryPtr>("delivery_type", P2PVR::sql::SI_deliveryForTransport, id);
}
catch (const Slicer::NoRowsReturned &) {
throw P2PVR::NotFound();
@@ -58,9 +60,8 @@ DVBSI::DeliveryPtr
SI::GetDeliveryForSi(const Ice::Current&)
{
try {
- Logger()->message(LOG_DEBUG, __PRETTY_FUNCTION__);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, DVBSI::DeliveryPtr>(
- *Select(SI_serviceNextUsed).second, "delivery_type");
+ logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
+ return fetch<DVBSI::DeliveryPtr>("delivery_type", P2PVR::sql::SI_serviceNextUsed);
}
catch (const Slicer::NoRowsReturned &) {
return NULL;
@@ -71,9 +72,8 @@ DVBSI::DeliveryPtr
SI::GetDeliveryForService(int id, const Ice::Current&)
{
try {
- Logger()->messagef(LOG_DEBUG, "%s(%d)", __PRETTY_FUNCTION__, id);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, DVBSI::DeliveryPtr>(
- *Select(SI_deliveryForService, id).second, "delivery_type");
+ logger->messagef(LOG::DEBUG, "%s(%d)", __PRETTY_FUNCTION__, id);
+ return fetch<DVBSI::DeliveryPtr>("delivery_type", P2PVR::sql::SI_deliveryForService, id);
}
catch (const Slicer::NoRowsReturned &) {
throw P2PVR::NotFound();
@@ -83,17 +83,15 @@ SI::GetDeliveryForService(int id, const Ice::Current&)
DVBSI::ServiceList
SI::GetServices(const Ice::Current&)
{
- Logger()->message(LOG_DEBUG, __PRETTY_FUNCTION__);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, DVBSI::ServiceList>(
- *Select(SI_servicesSelectAll).second);
+ logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
+ return fetch<DVBSI::ServiceList>(P2PVR::sql::SI_servicesSelectAll);
}
DVBSI::ServicePtr
SI::GetService(int id, const Ice::Current&)
{
- Logger()->messagef(LOG_DEBUG, "%s(%d)", __PRETTY_FUNCTION__, id);
- auto rtn = Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, DVBSI::ServiceList>(
- *Select(SI_servicesSelectById, id).second);
+ logger->messagef(LOG::DEBUG, "%s(%d)", __PRETTY_FUNCTION__, id);
+ auto rtn = fetch<DVBSI::ServiceList>(P2PVR::sql::SI_servicesSelectById, id);
if (rtn.empty()) throw P2PVR::NotFound();
return rtn.front();
}
@@ -101,11 +99,10 @@ SI::GetService(int id, const Ice::Current&)
P2PVR::Events
SI::GetEvents(const P2PVR::IntSequence & eventUids, const Ice::Current &)
{
- Logger()->message(LOG_DEBUG, __PRETTY_FUNCTION__);
+ logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
P2PVR::Events rtn;
for (const auto & uid : eventUids) {
- auto list = Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::Events>(
- *Select(SI_eventByUid, uid).second);
+ auto list = fetch<P2PVR::Events>(P2PVR::sql::SI_eventByUid, uid);
std::copy(list.begin(), list.end(), std::back_inserter(rtn));
}
if (rtn.size() != eventUids.size()) throw P2PVR::NotFound();
@@ -115,9 +112,8 @@ SI::GetEvents(const P2PVR::IntSequence & eventUids, const Ice::Current &)
P2PVR::EventPtr
SI::GetEvent(int serviceId, int eventId, const Ice::Current &)
{
- Logger()->messagef(LOG_DEBUG, "%s(s=%d, e=%d)", __PRETTY_FUNCTION__, serviceId, eventId);
- auto rtn = Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::Events>(
- *Select(SI_eventById, serviceId, eventId).second);
+ logger->messagef(LOG::DEBUG, "%s(s=%d, e=%d)", __PRETTY_FUNCTION__, serviceId, eventId);
+ auto rtn = fetch<P2PVR::Events>(P2PVR::sql::SI_eventById, serviceId, eventId);
if (rtn.empty()) throw P2PVR::NotFound();
return rtn.front();
}
@@ -125,41 +121,49 @@ SI::GetEvent(int serviceId, int eventId, const Ice::Current &)
P2PVR::Events
SI::EventsOnNow(const Ice::Current &)
{
- Logger()->message(LOG_DEBUG, __PRETTY_FUNCTION__);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::Events>(
- *Select(SI_eventsOnNow).second);
+ logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
+ return fetch<P2PVR::Events>(P2PVR::sql::SI_eventsOnNow);
+}
+
+namespace IceTray {
+ template<>
+ void
+ AbstractDatabaseClient::bind1<Common::DateTime>(int x, DB::Command * cmd, const Common::DateTime &);
+}
+
+template<>
+void
+IceTray::AbstractDatabaseClient::bind1<Common::DateTime>(int x, DB::Command * cmd, const Common::DateTime & dt)
+{
+ cmd->bindParamT(x, *dt);
}
P2PVR::Events
SI::EventsInRange(const Common::DateTime & from, const Common::DateTime & to, const Ice::Current &)
{
- Logger()->messagebf(LOG_DEBUG, "%s([%s]-[%s])", from, to, __PRETTY_FUNCTION__);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::Events>(
- *Select(SI_eventsInRange, from, to).second);
+ logger->messagebf(LOG::DEBUG, "%s([%s]-[%s])", from, to, __PRETTY_FUNCTION__);
+ return fetch<P2PVR::Events>(P2PVR::sql::SI_eventsInRange, from, to);
}
P2PVR::Events
SI::EventSearch(const IceUtil::Optional<std::string> & keywords, const IceUtil::Optional<Ice::Int> & serviceId, const IceUtil::Optional<Common::DateTime> & from, const IceUtil::Optional<Common::DateTime> & to, const Ice::Current &)
{
- Logger()->messagebf(LOG_DEBUG, "%s(keywords=%s,serviceId=%s,from=%s,to=%s)",
+ logger->messagebf(LOG::DEBUG, "%s(keywords=%s,serviceId=%s,from=%s,to=%s)",
keywords, serviceId, from, to, __PRETTY_FUNCTION__);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::Events>(
- *Select(SI_eventSearch, from, to, serviceId, serviceId, keywords, keywords, keywords, keywords).second);
+ return fetch<P2PVR::Events>(P2PVR::sql::SI_eventSearch, from, to, serviceId, serviceId, keywords, keywords, keywords, keywords);
}
P2PVR::Events
SI::EventsInSchedules(const Ice::Current &)
{
- Logger()->message(LOG_DEBUG, __PRETTY_FUNCTION__);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::Events>(
- *Select(SI_eventsInSchedules).second);
+ logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
+ return fetch<P2PVR::Events>(P2PVR::sql::SI_eventsInSchedules);
}
P2PVR::Events
SI::EventsInSchedule(int scheduleId, const Ice::Current &)
{
- Logger()->messagebf(LOG_DEBUG, "%s(%d)", scheduleId, __PRETTY_FUNCTION__);
- return Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::Events>(
- *Select(SI_eventsInSchedule, scheduleId).second);
+ logger->messagebf(LOG::DEBUG, "%s(%d)", scheduleId, __PRETTY_FUNCTION__);
+ return fetch<P2PVR::Events>(P2PVR::sql::SI_eventsInSchedule, scheduleId);
}
diff --git a/p2pvr/daemon/si.h b/p2pvr/daemon/si.h
index 0e388a1..c9080ab 100644
--- a/p2pvr/daemon/si.h
+++ b/p2pvr/daemon/si.h
@@ -2,11 +2,14 @@
#define P2PVR_SI_H
#include <p2pvr.h>
-#include "dbClient.h"
+#include <abstractDatabaseClient.h>
#include <visibility.h>
+#include <logger.h>
-class DLL_PUBLIC SI : public P2PVR::SI, public DatabaseClient {
+class DLL_PUBLIC SI : public P2PVR::SI, public IceTray::AbstractDatabaseClient {
public:
+ SI(IceTray::DatabasePoolPtr);
+
DVBSI::Networks GetNetworks(const Ice::Current &);
P2PVR::Deliveries GetAllDeliveries(const Ice::Current &);
DVBSI::DeliveryPtr GetDeliveryForService(int id, const Ice::Current &);
@@ -23,6 +26,8 @@ class DLL_PUBLIC SI : public P2PVR::SI, public DatabaseClient {
P2PVR::Events EventsInSchedule(int scheduleId, const Ice::Current &);
P2PVR::Events EventsInRange(const Common::DateTime &, const Common::DateTime &, const Ice::Current &);
P2PVR::Events EventSearch(const IceUtil::Optional<std::string> & keywords, const IceUtil::Optional<Ice::Int> & serviceId, const IceUtil::Optional<Common::DateTime> & from, const IceUtil::Optional<Common::DateTime> & to, const Ice::Current &);
+
+ static IceTray::Logging::LoggerPtr logger;
};
#endif
diff --git a/p2pvr/daemon/storage.cpp b/p2pvr/daemon/storage.cpp
index d43bddc..e443699 100644
--- a/p2pvr/daemon/storage.cpp
+++ b/p2pvr/daemon/storage.cpp
@@ -1,4 +1,3 @@
-#include <pch.hpp>
#include "storage.h"
#include "fileSink.h"
#include "muxedFileSink.h"
@@ -7,34 +6,39 @@
#include <boost/filesystem/operations.hpp>
namespace fs = boost::filesystem;
+namespace po = boost::program_options;
-std::string Storage::muxerCommand;
-fs::path Storage::root;
+Storage::Options::Options() :
+ IceTray::Options("P2PVR Storage options")
+{
+}
-DECLARE_OPTIONS(Storage, "P2PVR Storage options")
-("p2pvr.storage.muxercommand", Options::value(&muxerCommand, "/usr/bin/ffmpeg -i - -f mp4 -y ${TARGET}"),
+ICETRAY_OPTIONS(Storage::Options,
+("p2pvr.storage.muxercommand", po::value(&muxerCommand)->default_value("/usr/bin/ffmpeg -i - -f mp4 -y ${TARGET}"),
"Command to perform TS->PS muxing (default: '/usr/bin/ffmpeg -i - -f mp4 -y ${TARGET}')")
-("p2pvr.storage.root", Options::value(&root, "recordings"),
+("p2pvr.storage.root", po::value(&root)->default_value("recordings"),
"Root folder in which to store recordings")
-END_OPTIONS(Storage);
+);
+
+IceTray::Logging::LoggerPtr Storage::logger(LOGMANAGER()->getLogger<Storage>());
P2PVR::RawDataClientPrx
Storage::OpenForWrite(const std::string & id, const Ice::Current & ice)
{
- fs::create_directories(root);
- fs::path path = root / id;
+ fs::create_directories(options->root);
+ fs::path path = options->root / id;
P2PVR::RawDataClient * target;
- if (muxerCommand.empty()) {
+ if (options->muxerCommand.empty()) {
auto fd = open(path.string().c_str(), O_WRONLY | O_CREAT | O_EXCL, 0664);
if (fd < 0) {
- Logger()->messagebf(LOG_ERR, "%s: Failed to open file for reading at %s (%d:%s)", __PRETTY_FUNCTION__,
+ logger->messagebf(LOG::ERR, "%s: Failed to open file for reading at %s (%d:%s)", __PRETTY_FUNCTION__,
path, errno, strerror(errno));
throw P2PVR::StorageException(path.string(), strerror(errno));
}
target = new FileSink(fd);
}
else {
- target = new MuxedFileSink(path, muxerCommand);
+ target = new MuxedFileSink(path, options->muxerCommand);
}
auto openFile = OpenFilePtr(new OpenFile(ice.adapter, target));
openFiles.insert(openFile);
@@ -50,18 +54,18 @@ Storage::Close(const P2PVR::RawDataClientPrx & file, const Ice::Current &)
void
Storage::Delete(const std::string & id, const Ice::Current &)
{
- fs::path path = root / id;
- Logger()->messagebf(LOG_INFO, "%s: Deleting %s", __PRETTY_FUNCTION__, path);
+ fs::path path = options->root / id;
+ logger->messagebf(LOG::INFO, "%s: Deleting %s", __PRETTY_FUNCTION__, path);
fs::remove(path);
}
void
Storage::Send(const std::string & id, const P2PVR::RawDataClientPrx & target, Ice::Long start, Ice::Long len, const Ice::Current &)
{
- fs::path path = root / id;
+ fs::path path = options->root / id;
auto fd = open(path.string().c_str(), O_RDONLY | O_LARGEFILE);
if (fd < 0) {
- Logger()->messagebf(LOG_ERR, "%s: Failed to open file for reading at %s (%d:%s)", __PRETTY_FUNCTION__,
+ logger->messagebf(LOG::ERR, "%s: Failed to open file for reading at %s (%d:%s)", __PRETTY_FUNCTION__,
path, errno, strerror(errno));
throw P2PVR::StorageException(path.string(), strerror(errno));
}
@@ -71,7 +75,7 @@ Storage::Send(const std::string & id, const P2PVR::RawDataClientPrx & target, Ic
P2PVR::Data buf(16 * 1024);
auto r = read(fd, &buf.front(), std::min<size_t>(buf.size(), end - start));
if (r < 0) {
- Logger()->messagebf(LOG_ERR, "%s: Failed to read file %s (%d:%s)", __PRETTY_FUNCTION__,
+ logger->messagebf(LOG::ERR, "%s: Failed to read file %s (%d:%s)", __PRETTY_FUNCTION__,
path, errno, strerror(errno));
close(fd);
throw P2PVR::StorageException(path.string(), strerror(errno));
@@ -88,7 +92,7 @@ Storage::Send(const std::string & id, const P2PVR::RawDataClientPrx & target, Ic
Ice::Long
Storage::FileSize(const std::string & id, const Ice::Current &)
{
- fs::path path = root / id;
+ fs::path path = options->root / id;
try {
return fs::file_size(path);
}
diff --git a/p2pvr/daemon/storage.h b/p2pvr/daemon/storage.h
index 982c3fd..d66a5d3 100644
--- a/p2pvr/daemon/storage.h
+++ b/p2pvr/daemon/storage.h
@@ -4,28 +4,37 @@
#include <p2pvr.h>
#include <options.h>
#include <string>
+#include <set>
#include <boost/filesystem/path.hpp>
#include "temporaryIceAdapterObject.h"
#include <visibility.h>
+#include <logger.h>
class DLL_PUBLIC Storage : public P2PVR::Storage {
public:
+ class Options : public IceTray::Options {
+ public:
+ Options();
+
+ ICETRAY_OPTIONS_DECLARE;
+
+ std::string muxerCommand;
+ boost::filesystem::path root;
+ };
+
P2PVR::RawDataClientPrx OpenForWrite(const std::string &, const Ice::Current &) override;
void Close(const P2PVR::RawDataClientPrx & file, const Ice::Current &) override;
void Delete(const std::string &, const Ice::Current &) override;
Ice::Long FileSize(const std::string &, const Ice::Current &) override;
void Send(const std::string &, const P2PVR::RawDataClientPrx & target, Ice::Long start, Ice::Long len, const Ice::Current &) override;
- INITOPTIONS;
-
protected:
typedef TemporaryIceAdapterObject<P2PVR::RawDataClient> OpenFile;
typedef boost::shared_ptr<OpenFile> OpenFilePtr;
typedef std::set<OpenFilePtr> OpenFiles;
OpenFiles openFiles;
-
- static std::string muxerCommand;
- static boost::filesystem::path root;
+ IceTray::OptionsResolver<Options> options;
+ static IceTray::Logging::LoggerPtr logger;
};
#endif
diff --git a/p2pvr/daemon/unittests/Jamfile.jam b/p2pvr/daemon/unittests/Jamfile.jam
index 252dd89..bb39bbb 100644
--- a/p2pvr/daemon/unittests/Jamfile.jam
+++ b/p2pvr/daemon/unittests/Jamfile.jam
@@ -4,11 +4,15 @@ lib boost_system ;
lib boost_filesystem ;
lib IceUtil ;
lib Ice ;
+lib IceBox ;
+lib dbppcore : : : : <include>/usr/include/dbpp ;
lib dbpp-postgresql : : : : <include>/usr/include/dbpp-postgresql ;
+lib dryice : : : : <include>/usr/include/icetray ;
path-constant me : . ;
alias test-data :
+ ../../datasources/schema.sql
datasources/data.sql
datasources/delivery_dvbc
datasources/delivery_dvbs
@@ -24,204 +28,75 @@ alias test-data :
;
lib testCommon :
- mockDefs.cpp
+ [ glob mock*.cpp ]
:
- <library>dbpp-postgresql
- <library>../..//p2sql
- <library>../..//p2common
- <library>../..//adhocutil
- <library>../..//p2ut
<define>ROOT=\"$(me)\"
- <library>boost_system
- <library>boost_filesystem
- ;
-
-run
- testEmbedding.cpp
- dummySelect.sql
- : : :
- <define>BOOST_TEST_DYN_LINK
- <library>../..//boost_utf
- <include>..
- : testEmbedding ;
-
-run
- testMaint.cpp mockDevices.cpp mockScheduler.cpp
- : :
- ../../datasources/schema.sql
- :
- <define>BOOST_TEST_DYN_LINK
- <library>../..//p2common
- <library>../..//p2basics
<library>../..//adhocutil
- <library>../..//p2xml
- <library>../..//p2ut
- <library>..//p2pvrdaemon
- <library>../../devices//p2pvrMockTuner
- <library>IceUtil
+ <library>dryice
<library>Ice
+ <library>IceUtil
+ <library>IceBox
+ <library>dbppcore
+ <library>dbpp-postgresql
+ <library>../../devices//p2pvrMockTuner
<library>boost_system
<library>boost_filesystem
- <library>testCommon
- <library>../..//boost_utf
- <dependency>test-data
- <define>ROOT=\"$(me)\"
- : testMaint ;
-
-run
- testRecording.cpp mockDevices.cpp mockScheduler.cpp
+ <implicit-dependency>../../ice
+ <library>../../ice
: :
- ../../datasources/schema.sql
- :
+ <define>ROOT=\"$(me)\"
<define>BOOST_TEST_DYN_LINK
- <library>../..//p2common
- <library>../..//p2basics
<library>../..//adhocutil
- <library>../..//p2xml
- <library>../..//p2ut
- <library>..//p2pvrdaemon
- <library>../../devices//p2pvrMockTuner
- <library>IceUtil
+ <library>dryice
+ <library>../..//icetray
+ <library>dbppcore
+ <library>dbpp-postgresql
<library>Ice
+ <library>IceBox
+ <library>IceUtil
<library>boost_system
<library>boost_filesystem
- <library>testCommon
<library>../..//boost_utf
+ <library>../../devices//p2pvrMockTuner
+ <library>..//p2pvrdaemon
<dependency>test-data
- <define>ROOT=\"$(me)\"
- : testRecording ;
+ ;
run
- testErrorHandling.cpp mockDevices.cpp mockScheduler.cpp
- : :
- ../../datasources/schema.sql
- :
- <define>BOOST_TEST_DYN_LINK
- <library>../..//p2common
- <library>../..//p2basics
- <library>../..//adhocutil
- <library>../..//p2xml
- <library>../..//p2ut
- <library>..//p2pvrdaemon
- <library>../../devices//p2pvrMockTuner
- <library>../../dvb//p2pvrdvb
- <library>IceUtil
- <library>Ice
- <library>boost_system
- <library>boost_filesystem
+ testMaint.cpp
+ : : :
<library>testCommon
- <library>../..//boost_utf
- <dependency>test-data
- <define>ROOT=\"$(me)\"
- : testErrorHandling ;
+ : testMaint ;
-run
- testRecordings.cpp
- : :
- ../../datasources/schema.sql
- :
- <define>BOOST_TEST_DYN_LINK
- <library>../..//p2common
- <library>../..//p2basics
- <library>../..//adhocutil
- <library>../..//p2xml
- <library>../..//p2ut
- <library>..//p2pvrdaemon
- <library>IceUtil
- <library>Ice
- <library>boost_system
- <library>boost_filesystem
+run testRecording.cpp
+ : : :
<library>testCommon
- <library>../..//boost_utf
- <dependency>test-data
- <define>ROOT=\"$(me)\"
- : testRecordings ;
+ ;
-run
- testSi.cpp
- : :
- ../../datasources/schema.sql
- :
- <define>BOOST_TEST_DYN_LINK
- <library>../..//p2common
- <library>../..//p2basics
- <library>../..//adhocutil
- <library>../..//p2xml
- <library>../..//p2ut
- <library>..//p2pvrdaemon
- <library>IceUtil
- <library>Ice
- <library>boost_system
- <library>boost_filesystem
+run testErrorHandling.cpp
+ : : :
<library>testCommon
- <library>../..//boost_utf
- <dependency>test-data
- <define>ROOT=\"$(me)\"
- : testSi ;
+ <library>../../dvb//p2pvrdvb
+ ;
-run
- testSched.cpp mockDevices.cpp mockRecorder.cpp
- : :
- ../../datasources/schema.sql
- datasources/eventOffset.sql
- :
- <define>BOOST_TEST_DYN_LINK
- <library>../..//p2common
- <library>../..//p2basics
- <library>../..//adhocutil
- <library>../..//p2xml
- <library>../..//p2ut
- <library>..//p2pvrdaemon
- <library>IceUtil
- <library>Ice
- <library>boost_system
- <library>boost_filesystem
- <library>../../devices//p2pvrMockTuner
- <library>../..//boost_utf
+run testRecordings.cpp
+ : : :
<library>testCommon
- <dependency>test-data
- <define>ROOT=\"$(me)\"
- : testSched ;
+ ;
-run
- testStorage.cpp
- : :
- ../../datasources/schema.sql
- :
- <define>BOOST_TEST_DYN_LINK
- <library>../..//p2common
- <library>../..//p2basics
- <library>../..//adhocutil
- <library>../..//p2xml
- <library>../..//p2ut
- <library>..//p2pvrdaemon
- <library>IceUtil
- <library>Ice
- <library>boost_system
- <library>boost_filesystem
+run testSi.cpp
+ : : :
<library>testCommon
- <library>../..//boost_utf
- <dependency>test-data
- <define>ROOT=\"$(me)\"
- : testStorage ;
+ ;
-run
- testSqlSelectDeserializer.cpp
- : :
- ../../datasources/schema.sql
- :
- <define>BOOST_TEST_DYN_LINK
- <library>../..//p2common
- <library>../..//p2sql
- <library>../..//p2ut
- <library>../..//p2xml
- <library>..//p2pvrdaemon
- <library>IceUtil
- <library>Ice
- <library>../..//boost_utf
+run testSched.cpp
+ : : :
<library>testCommon
- <library>..//slicer-db
- <dependency>test-data
- <define>ROOT=\"$(me)\"
- : testSqlSelectDeserializer ;
+ <dependency>datasources/eventOffset.sql
+ ;
+
+run testStorage.cpp
+ : : :
+ <library>testCommon
+ ;
diff --git a/p2pvr/daemon/unittests/datasources/postgres.xml b/p2pvr/daemon/unittests/datasources/postgres.xml
deleted file mode 100644
index 363572d..0000000
--- a/p2pvr/daemon/unittests/datasources/postgres.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0"?>
-<project2:rdbmsdatasource xmlns:project2="http://project2.randomdan.homeip.net" name="postgres">
- <masterdsn provider="mock" dsn="postgres" />
-</project2:rdbmsdatasource>
diff --git a/p2pvr/daemon/unittests/dummySelect.sql b/p2pvr/daemon/unittests/dummySelect.sql
deleted file mode 100644
index 3f9397b..0000000
--- a/p2pvr/daemon/unittests/dummySelect.sql
+++ /dev/null
@@ -1 +0,0 @@
-SELECT stuff FROM things
diff --git a/p2pvr/daemon/unittests/mockDefs.cpp b/p2pvr/daemon/unittests/mockDefs.cpp
index 8c44b9a..d810719 100644
--- a/p2pvr/daemon/unittests/mockDefs.cpp
+++ b/p2pvr/daemon/unittests/mockDefs.cpp
@@ -22,3 +22,15 @@ StandardMockDatabasePlusOffset::StandardMockDatabasePlusOffset() :
{
}
+TestClient::TestClient() :
+ localDevices(getProxy<P2PVR::LocalDevicesPrx>("Devices")),
+ devices(getProxy<P2PVR::DevicesPrx>("GlobalDevices")),
+ maint(getProxy<P2PVR::MaintenancePrx>("Maintenance")),
+ si(getProxy<P2PVR::SIPrx>("SI")),
+ schedules(getProxy<P2PVR::SchedulesPrx>("Schedules")),
+ storage(getProxy<P2PVR::StoragePrx>("Storage")),
+ recorder(getProxy<P2PVR::RecorderPrx>("Recorder")),
+ recordings(getProxy<P2PVR::RecordingsPrx>("Recordings"))
+{
+}
+
diff --git a/p2pvr/daemon/unittests/mockDefs.h b/p2pvr/daemon/unittests/mockDefs.h
index b16b47d..6675c2f 100644
--- a/p2pvr/daemon/unittests/mockDefs.h
+++ b/p2pvr/daemon/unittests/mockDefs.h
@@ -3,8 +3,10 @@
#include <pq-mock.h>
#include <visibility.h>
+#include <dryice.h>
+#include <p2pvr.h>
-#define DECLAREMOCK(Name) class DLL_PUBLIC Name : public PQ::Mock { public: Name(); }
+#define DECLAREMOCK(Name) class DLL_PUBLIC Name : public PQ::Mock, public IceTray::DryIce { public: Name(); }
DECLAREMOCK(SchemaOnlyMockDatabase);
DECLAREMOCK(StandardMockDatabase);
@@ -12,5 +14,19 @@ DECLAREMOCK(StandardMockDatabasePlusOffset);
#undef DECLAREMOCK
+class DLL_PUBLIC TestClient : public IceTray::DryIceClient {
+ public:
+ TestClient();
+
+ P2PVR::LocalDevicesPrx localDevices;
+ P2PVR::DevicesPrx devices;
+ P2PVR::MaintenancePrx maint;
+ P2PVR::SIPrx si;
+ P2PVR::SchedulesPrx schedules;
+ P2PVR::StoragePrx storage;
+ P2PVR::RecorderPrx recorder;
+ P2PVR::RecordingsPrx recordings;
+};
+
#endif
diff --git a/p2pvr/daemon/unittests/mockDevices.h b/p2pvr/daemon/unittests/mockDevices.h
index 195867e..f6e4c43 100644
--- a/p2pvr/daemon/unittests/mockDevices.h
+++ b/p2pvr/daemon/unittests/mockDevices.h
@@ -2,8 +2,9 @@
#define P2PVR_MOCKS_DEVICES_H
#include <dvb.h>
+#include <visibility.h>
-class MockDevices : public P2PVR::Devices {
+class DLL_PUBLIC MockDevices : public P2PVR::Devices {
public:
P2PVR::TunerPrx GetTunerSpecific(const DVBSI::DeliveryPtr&, const Ice::Current & ice) override;
P2PVR::TunerPrx GetTunerAny(const DVBSI::DeliveryPtr&, const Ice::Current & ice) override;
diff --git a/p2pvr/daemon/unittests/mockRecorder.h b/p2pvr/daemon/unittests/mockRecorder.h
index 85f747b..d76904d 100644
--- a/p2pvr/daemon/unittests/mockRecorder.h
+++ b/p2pvr/daemon/unittests/mockRecorder.h
@@ -2,8 +2,9 @@
#define P2PVR_MOCKS_RECORDER_H
#include <p2pvr.h>
+#include <visibility.h>
-class MockRecorder : public P2PVR::Recorder {
+class DLL_PUBLIC MockRecorder : public P2PVR::Recorder {
public:
void RefreshSchedules(const Ice::Current &) override;
};
diff --git a/p2pvr/daemon/unittests/mockScheduler.h b/p2pvr/daemon/unittests/mockScheduler.h
index e90567b..c3640f6 100644
--- a/p2pvr/daemon/unittests/mockScheduler.h
+++ b/p2pvr/daemon/unittests/mockScheduler.h
@@ -2,8 +2,9 @@
#define P2PVR_MOCKS_SCHEDULER_H
#include <p2pvr.h>
+#include <visibility.h>
-class MockScheduler : public P2PVR::Schedules {
+class DLL_PUBLIC MockScheduler : public P2PVR::Schedules {
public:
void DoReschedule(const ::Ice::Current&) override;
void DeleteSchedule(Ice::Int, const Ice::Current&) override;
diff --git a/p2pvr/daemon/unittests/testEmbedding.cpp b/p2pvr/daemon/unittests/testEmbedding.cpp
deleted file mode 100644
index b0e01f1..0000000
--- a/p2pvr/daemon/unittests/testEmbedding.cpp
+++ /dev/null
@@ -1,14 +0,0 @@
-#define BOOST_TEST_MODULE embedding
-#include <boost/test/unit_test.hpp>
-
-#include "resources.h"
-
-ResourceString(DummySql, sql_dummySelect);
-
-BOOST_AUTO_TEST_CASE( embed )
-{
- BOOST_REQUIRE_EQUAL(25, DummySql.length());
- BOOST_REQUIRE_EQUAL(sql_dummySelect_len, DummySql.length());
- BOOST_REQUIRE_EQUAL("SELECT stuff FROM things\n", DummySql);
-}
-
diff --git a/p2pvr/daemon/unittests/testErrorHandling.cpp b/p2pvr/daemon/unittests/testErrorHandling.cpp
index c4ea88d..b04c78c 100644
--- a/p2pvr/daemon/unittests/testErrorHandling.cpp
+++ b/p2pvr/daemon/unittests/testErrorHandling.cpp
@@ -1,7 +1,7 @@
#define BOOST_TEST_MODULE ErrorHandling
#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>
-#include <testOptionsSource.h>
+#include <options.h>
#include <Ice/ObjectAdapter.h>
#include <Ice/Service.h>
#include <maintenance.h>
@@ -15,46 +15,16 @@
#include <siParsers/network.h>
#include <temporaryIceAdapterObject.h>
#include "mockDefs.h"
-#include <testAppInstance.h>
-class Core : public TestAppInstance {
+class Core : public StandardMockDatabase {
public:
Core()
{
- int paramCount = 0;
- ic = Ice::initialize(paramCount, NULL);
- adapter = ic->createObjectAdapterWithEndpoints("Adp", "tcp -p 12006");
- TestOptionsSource::LoadTestOptions({
- { "common.datasourceRoot", (rootDir / "datasources").string() },
- });
- adapter->add(new MockDevices(), ic->stringToIdentity("GlobalDevices"));
- adapter->add(new SI(), ic->stringToIdentity("SI"));
- adapter->activate();
-
- s = P2PVR::SIPrx::checkedCast(ic->stringToProxy("SI"));
- BOOST_REQUIRE(s);
- s->ice_ping();
-
- d = P2PVR::DevicesPrx::checkedCast(ic->stringToProxy("GlobalDevices"));
- BOOST_REQUIRE(d);
- d->ice_ping();
+ replace("GlobalDevices", new MockDevices());
}
-
- ~Core()
- {
- ic->destroy();
- }
-
- P2PVR::DevicesPrx d;
- P2PVR::SIPrx s;
-
- protected:
- Ice::ObjectAdapterPtr adapter;
- private:
- Ice::CommunicatorPtr ic;
};
-class TestClient : public P2PVR::RawDataClient {
+class TestDataClient : public P2PVR::RawDataClient {
public:
virtual bool NewData(const P2PVR::Data &, const Ice::Current &) override
{
@@ -86,16 +56,16 @@ class FailingTestNetworkParser : public SiNetworkInformationParser {
}
};
-BOOST_GLOBAL_FIXTURE( StandardMockDatabase );
+BOOST_GLOBAL_FIXTURE( Core );
-BOOST_FIXTURE_TEST_SUITE(ErrorHandling, Core)
+BOOST_FIXTURE_TEST_SUITE(ErrorHandling, TestClient)
BOOST_AUTO_TEST_CASE(TestRawDataClient)
{
BOOST_TEST_CHECKPOINT("Setup");
- auto del = s->GetDeliveryForSi();
- auto gd = d->GetTunerAny(del);
- TemporaryIceAdapterObject<P2PVR::RawDataClient> a(adapter, new TestClient());
+ auto del = si->GetDeliveryForSi();
+ auto gd = devices->GetTunerAny(del);
+ TemporaryIceAdapterObject<P2PVR::RawDataClient> a(getAdapter(), new TestDataClient());
BOOST_TEST_CHECKPOINT("Make successful call");
gd->SendNetworkInformation(a);
}
@@ -103,9 +73,9 @@ BOOST_AUTO_TEST_CASE(TestRawDataClient)
BOOST_AUTO_TEST_CASE(TestParser)
{
BOOST_TEST_CHECKPOINT("Setup");
- auto del = s->GetDeliveryForSi();
- auto gd = d->GetTunerAny(del);
- TemporaryIceAdapterObject<P2PVR::RawDataClient> a(adapter, new TestNetworkParser());
+ auto del = si->GetDeliveryForSi();
+ auto gd = devices->GetTunerAny(del);
+ TemporaryIceAdapterObject<P2PVR::RawDataClient> a(getAdapter(), new TestNetworkParser());
BOOST_TEST_CHECKPOINT("Make successful call");
gd->SendNetworkInformation(a);
}
@@ -113,9 +83,9 @@ BOOST_AUTO_TEST_CASE(TestParser)
BOOST_AUTO_TEST_CASE(TestRawDataClientWithError)
{
BOOST_TEST_CHECKPOINT("Setup");
- auto del = s->GetDeliveryForSi();
- auto gd = d->GetTunerAny(del);
- TemporaryIceAdapterObject<P2PVR::RawDataClient> a(adapter, new FailingTestClient());
+ auto del = si->GetDeliveryForSi();
+ auto gd = devices->GetTunerAny(del);
+ TemporaryIceAdapterObject<P2PVR::RawDataClient> a(getAdapter(), new FailingTestClient());
BOOST_TEST_CHECKPOINT("Make failing call");
BOOST_REQUIRE_THROW(gd->SendNetworkInformation(a), P2PVR::DataHandlingException);
}
@@ -123,9 +93,9 @@ BOOST_AUTO_TEST_CASE(TestRawDataClientWithError)
BOOST_AUTO_TEST_CASE(TestParserWithError)
{
BOOST_TEST_CHECKPOINT("Setup");
- auto del = s->GetDeliveryForSi();
- auto gd = d->GetTunerAny(del);
- TemporaryIceAdapterObject<P2PVR::RawDataClient> a(adapter, new FailingTestNetworkParser());
+ auto del = si->GetDeliveryForSi();
+ auto gd = devices->GetTunerAny(del);
+ TemporaryIceAdapterObject<P2PVR::RawDataClient> a(getAdapter(), new FailingTestNetworkParser());
BOOST_TEST_CHECKPOINT("Make failing call");
BOOST_REQUIRE_THROW(gd->SendNetworkInformation(a), P2PVR::DataHandlingException);
}
diff --git a/p2pvr/daemon/unittests/testMaint.cpp b/p2pvr/daemon/unittests/testMaint.cpp
index a86ff78..e02abae 100644
--- a/p2pvr/daemon/unittests/testMaint.cpp
+++ b/p2pvr/daemon/unittests/testMaint.cpp
@@ -2,7 +2,7 @@
#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string/predicate.hpp>
-#include <testOptionsSource.h>
+#include <options.h>
#include <Ice/ObjectAdapter.h>
#include <Ice/Service.h>
#include <maintenance.h>
@@ -17,54 +17,19 @@
#include <slicer/db/sqlSelectDeserializer.h>
#include "commonHelpers.h"
#include <slicer/slicer.h>
-#include <testAppInstance.h>
-class Core : public CommonObjects, public TestAppInstance {
+class TestService : public SchemaOnlyMockDatabase {
public:
- Core()
+ TestService()
{
- int paramCount = 0;
- ic = Ice::initialize(paramCount, NULL);
- auto adapter = ic->createObjectAdapterWithEndpoints("Adp", "tcp -p 12000");
- TestOptionsSource::LoadTestOptions({
- { "common.datasourceRoot", (rootDir / "datasources").string() },
- });
- adapter->add(new MockDevices(), ic->stringToIdentity("GlobalDevices"));
- adapter->add(new MockScheduler(), ic->stringToIdentity("Schedules"));
- adapter->add(new SI(), ic->stringToIdentity("SI"));
- adapter->add(new Recordings(), ic->stringToIdentity("Recordings"));
- adapter->add(new Maintenance(adapter, NULL), ic->stringToIdentity("Maintenance"));
- adapter->activate();
-
- r = P2PVR::RecordingsPrx::checkedCast(ic->stringToProxy("Recordings"));
- BOOST_REQUIRE(r);
- r->ice_ping();
-
- s = P2PVR::SIPrx::checkedCast(ic->stringToProxy("SI"));
- BOOST_REQUIRE(s);
- s->ice_ping();
-
- m = P2PVR::MaintenancePrx::checkedCast(ic->stringToProxy("Maintenance"));
- BOOST_REQUIRE(m);
- m->ice_ping();
+ replace("GlobalDevices", new MockDevices());
+ replace("Schedules", new MockScheduler());
}
-
- ~Core()
- {
- ic->destroy();
- }
-
- P2PVR::MaintenancePrx m;
- P2PVR::RecordingsPrx r;
- P2PVR::SIPrx s;
-
- private:
- Ice::CommunicatorPtr ic;
};
-BOOST_GLOBAL_FIXTURE( SchemaOnlyMockDatabase );
+BOOST_GLOBAL_FIXTURE( TestService );
-BOOST_FIXTURE_TEST_SUITE( MaintCore, Core );
+BOOST_FIXTURE_TEST_SUITE( MaintCore, TestClient );
const int serviceId = 4170;
const int transportId = 20544;
@@ -72,47 +37,47 @@ const int eventId1 = 31;
const int eventId2 = 915;
//
-// Run all these tests when there's no data
+// Run all these tests when there'si no data
// This tests behaviour from clean startup/fresh install
//
BOOST_AUTO_TEST_CASE( GetNetworks_emptySet )
{
- BOOST_REQUIRE(s->GetNetworks().empty());
+ BOOST_REQUIRE(si->GetNetworks().empty());
}
BOOST_AUTO_TEST_CASE( GetAllDeliveries_emptySet )
{
- BOOST_REQUIRE(s->GetAllDeliveries().empty());
+ BOOST_REQUIRE(si->GetAllDeliveries().empty());
}
BOOST_AUTO_TEST_CASE( GetDeliveryForService_notFound )
{
- BOOST_REQUIRE_THROW(s->GetDeliveryForService(serviceId), P2PVR::NotFound);
+ BOOST_REQUIRE_THROW(si->GetDeliveryForService(serviceId), P2PVR::NotFound);
}
BOOST_AUTO_TEST_CASE( GetDeliveryForTransport_notFound )
{
- BOOST_REQUIRE_THROW(s->GetDeliveryForTransport(transportId), P2PVR::NotFound);
+ BOOST_REQUIRE_THROW(si->GetDeliveryForTransport(transportId), P2PVR::NotFound);
}
BOOST_AUTO_TEST_CASE( GetDeliveryForSi_null )
{
- BOOST_REQUIRE_EQUAL(s->GetDeliveryForSi(), DVBSI::DeliveryPtr());
+ BOOST_REQUIRE_EQUAL(si->GetDeliveryForSi(), DVBSI::DeliveryPtr());
}
BOOST_AUTO_TEST_CASE( GetServices_emptySet )
{
- BOOST_REQUIRE(s->GetServices().empty());
+ BOOST_REQUIRE(si->GetServices().empty());
}
BOOST_AUTO_TEST_CASE( GetService_notFound )
{
- BOOST_REQUIRE_THROW(s->GetService(serviceId), P2PVR::NotFound);
+ BOOST_REQUIRE_THROW(si->GetService(serviceId), P2PVR::NotFound);
}
BOOST_AUTO_TEST_CASE( GetSpecificEvents_notFound )
{
- BOOST_REQUIRE_THROW(s->GetEvents({ eventId1, eventId2 }), P2PVR::NotFound);
+ BOOST_REQUIRE_THROW(si->GetEvents({ eventId1, eventId2 }), P2PVR::NotFound);
}
//
@@ -121,12 +86,12 @@ BOOST_AUTO_TEST_CASE( GetSpecificEvents_notFound )
BOOST_AUTO_TEST_CASE( update_network )
{
- m->UpdateNetwork(FE_OFDM);
+ maint->UpdateNetwork(FE_OFDM);
}
BOOST_AUTO_TEST_CASE( GetNetworks )
{
- auto ns = s->GetNetworks();
+ auto ns = si->GetNetworks();
BOOST_REQUIRE_EQUAL(ns.size(), 1);
BOOST_REQUIRE_EQUAL(ns[0]->NetworkId, 12333);
BOOST_REQUIRE_EQUAL(ns[0]->Name, "Yorkshire");
@@ -134,7 +99,7 @@ BOOST_AUTO_TEST_CASE( GetNetworks )
BOOST_AUTO_TEST_CASE( GetDeliveryForService )
{
- auto del = s->GetDeliveryForService(serviceId);
+ auto del = si->GetDeliveryForService(serviceId);
BOOST_REQUIRE(del);
BOOST_REQUIRE_EQUAL(del->ice_id(), "::DVBSI::TerrestrialDelivery");
BOOST_REQUIRE_EQUAL(del->Frequency, 682000000);
@@ -142,7 +107,7 @@ BOOST_AUTO_TEST_CASE( GetDeliveryForService )
BOOST_AUTO_TEST_CASE( GetDeliveryForTransport )
{
- auto del = s->GetDeliveryForTransport(transportId);
+ auto del = si->GetDeliveryForTransport(transportId);
BOOST_REQUIRE(del);
BOOST_REQUIRE_EQUAL(del->ice_id(), "::DVBSI::TerrestrialDelivery");
BOOST_REQUIRE_EQUAL(del->Frequency, 722000000);
@@ -150,7 +115,7 @@ BOOST_AUTO_TEST_CASE( GetDeliveryForTransport )
BOOST_AUTO_TEST_CASE( GetServices_stubs )
{
- auto services = s->GetServices();
+ auto services = si->GetServices();
BOOST_REQUIRE_EQUAL(services.size(), 145);
BOOST_REQUIRE_EQUAL(services[0]->ServiceId, 4170);
BOOST_REQUIRE_EQUAL(services[0]->TransportStreamId, 4170);
@@ -160,7 +125,7 @@ BOOST_AUTO_TEST_CASE( GetServices_stubs )
BOOST_AUTO_TEST_CASE( GetService_stubs )
{
- auto service = s->GetService(serviceId);
+ auto service = si->GetService(serviceId);
BOOST_REQUIRE_EQUAL(service->ServiceId, serviceId);
// Definitely a stub
BOOST_REQUIRE(!service->Name);
@@ -168,7 +133,7 @@ BOOST_AUTO_TEST_CASE( GetService_stubs )
BOOST_AUTO_TEST_CASE( GetDeliveryForSi_any )
{
- auto del = s->GetDeliveryForSi();
+ auto del = si->GetDeliveryForSi();
BOOST_REQUIRE(del);
// Any yes, but is our case it should be DVB-T
BOOST_REQUIRE_EQUAL(del->ice_id(), "::DVBSI::TerrestrialDelivery");
@@ -177,7 +142,7 @@ BOOST_AUTO_TEST_CASE( GetDeliveryForSi_any )
BOOST_AUTO_TEST_CASE( UpdateNetwork_prepopulated )
{
// This should now run using existing transport data (although this test doesn't prove that)
- m->UpdateNetwork(FE_OFDM);
+ maint->UpdateNetwork(FE_OFDM);
}
//
@@ -186,12 +151,12 @@ BOOST_AUTO_TEST_CASE( UpdateNetwork_prepopulated )
//
BOOST_AUTO_TEST_CASE( update_services )
{
- m->UpdateServices();
+ maint->UpdateServices();
}
BOOST_AUTO_TEST_CASE( GetServices )
{
- auto services = s->GetServices();
+ auto services = si->GetServices();
BOOST_REQUIRE_EQUAL(services.size(), 145);
BOOST_REQUIRE_EQUAL(services[0]->ServiceId, 4170);
BOOST_REQUIRE_EQUAL(services[0]->TransportStreamId, 4170);
@@ -201,7 +166,7 @@ BOOST_AUTO_TEST_CASE( GetServices )
BOOST_AUTO_TEST_CASE( GetService )
{
- auto service = s->GetService(serviceId);
+ auto service = si->GetService(serviceId);
BOOST_REQUIRE_EQUAL(service->ServiceId, serviceId);
BOOST_REQUIRE_EQUAL(service->TransportStreamId, 4170);
BOOST_REQUIRE_EQUAL(service->Name, "BBC ONE Yorks");
@@ -211,20 +176,20 @@ BOOST_AUTO_TEST_CASE( GetService )
BOOST_AUTO_TEST_CASE( update_events )
{
BOOST_TEST_CHECKPOINT("Get a DB connection for faking stuff");
- auto db = this->dataSource<RdbmsDataSource>("postgres")->getReadonly(); // Naughty, but don't want txs
+ auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("postgres"));
BOOST_TEST_CHECKPOINT("Write first events");
MockTuner::SetEventsSet(0);
- m->UpdateEvents();
- auto dayOneEvents = s->EventSearch(IceUtil::Optional<std::string>(), IceUtil::Optional<int>(),
+ maint->UpdateEvents();
+ auto dayOneEvents = si->EventSearch(IceUtil::Optional<std::string>(), IceUtil::Optional<int>(),
Common::DateTime {2014, 12, 18, 3, 0}, Common::DateTime {2014, 12, 19, 3, 0});
BOOST_REQUIRE_EQUAL(dayOneEvents.size(), 3345);
- BOOST_REQUIRE(s->GetEvent(14448, 27052));
- BOOST_REQUIRE_THROW(s->GetEvent(15856, 3591), P2PVR::NotFound);
+ BOOST_REQUIRE(si->GetEvent(14448, 27052));
+ BOOST_REQUIRE_THROW(si->GetEvent(15856, 3591), P2PVR::NotFound);
BOOST_TEST_CHECKPOINT("Fake some recorded stuff");
- auto keyEvent1 = s->GetEvent(25664, 55689);
- auto keyEvent2 = s->GetEvent(24256, 1014);
+ auto keyEvent1 = si->GetEvent(25664, 55689);
+ auto keyEvent2 = si->GetEvent(24256, 1014);
db->execute("INSERT INTO schedules(repeats) VALUES(false)");
auto irecorded = boost::shared_ptr<DB::ModifyCommand>(
db->newModifyCommand("INSERT INTO recorded(scheduleId, eventUid) VALUES(?, ?)"));
@@ -245,12 +210,12 @@ BOOST_AUTO_TEST_CASE( update_events )
BOOST_TEST_CHECKPOINT("Write second events");
MockTuner::SetEventsSet(1);
- m->UpdateEvents();
- BOOST_REQUIRE_THROW(s->GetEvent(14448, 27052), P2PVR::NotFound);
- BOOST_REQUIRE(s->GetEvent(15856, 3591));
+ maint->UpdateEvents();
+ BOOST_REQUIRE_THROW(si->GetEvent(14448, 27052), P2PVR::NotFound);
+ BOOST_REQUIRE(si->GetEvent(15856, 3591));
BOOST_TEST_CHECKPOINT("Check our faked stuff is still there and right");
- auto dayOneEventsOnDayTwo = s->EventSearch(IceUtil::Optional<std::string>(), IceUtil::Optional<int>(),
+ auto dayOneEventsOnDayTwo = si->EventSearch(IceUtil::Optional<std::string>(), IceUtil::Optional<int>(),
Common::DateTime {2014, 12, 18, 3, 0}, Common::DateTime {2014, 12, 19, 3, 0});
// Some datetime range overlap, but most are gone
BOOST_REQUIRE_EQUAL(dayOneEventsOnDayTwo.size(), 373);
@@ -258,7 +223,7 @@ BOOST_AUTO_TEST_CASE( update_events )
[](const P2PVR::EventPtr & e) {
return (e->ServiceId == 25664 && e->EventId == 55689)
|| (e->ServiceId == 24256 && e->EventId == 1014); }), 0);
- auto keyEventsOnDayTwo = s->GetEvents({keyEvent1->EventUid, keyEvent2->EventUid});
+ auto keyEventsOnDayTwo = si->GetEvents({keyEvent1->EventUid, keyEvent2->EventUid});
BOOST_REQUIRE_EQUAL(keyEventsOnDayTwo.size(), 2);
BOOST_REQUIRE(!keyEventsOnDayTwo[0]->Current);
BOOST_REQUIRE(!keyEventsOnDayTwo[1]->Current);
@@ -269,7 +234,7 @@ BOOST_AUTO_TEST_CASE( update_events )
BOOST_AUTO_TEST_CASE( test_titleFiltering )
{
- auto thingsWithNew = s->EventSearch("new", IceUtil::Optional<int>(),
+ auto thingsWithNew = si->EventSearch("new", IceUtil::Optional<int>(),
IceUtil::Optional<Common::DateTime>(), IceUtil::Optional<Common::DateTime>());
BOOST_REQUIRE_EQUAL(0, std::count_if(thingsWithNew.begin(), thingsWithNew.end(), [](auto e) {
return boost::algorithm::starts_with(e->Title, "New:");
diff --git a/p2pvr/daemon/unittests/testRecording.cpp b/p2pvr/daemon/unittests/testRecording.cpp
index 2ce4080..ca15447 100644
--- a/p2pvr/daemon/unittests/testRecording.cpp
+++ b/p2pvr/daemon/unittests/testRecording.cpp
@@ -1,7 +1,7 @@
#define BOOST_TEST_MODULE Recording
#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>
-#include <testOptionsSource.h>
+#include <options.h>
#include <Ice/ObjectAdapter.h>
#include <Ice/Service.h>
#include <maintenance.h>
@@ -18,50 +18,14 @@
#include "serviceStreamer.h"
#include "temporaryIceAdapterObject.h"
#include <slicer/slicer.h>
-#include <testAppInstance.h>
-class Core : public CommonObjects, public TestAppInstance {
+class TestService : public StandardMockDatabase {
public:
- Core()
+ TestService()
{
- int paramCount = 0;
- ic = Ice::initialize(paramCount, NULL);
- adapter = ic->createObjectAdapterWithEndpoints("Adp", "tcp -p 12005");
- TestOptionsSource::LoadTestOptions({
- { "common.datasourceRoot", (rootDir / "datasources").string() },
- });
- adapter->add(new MockDevices(), ic->stringToIdentity("GlobalDevices"));
- adapter->add(new MockScheduler(), ic->stringToIdentity("Schedules"));
- adapter->add(new SI(), ic->stringToIdentity("SI"));
- adapter->add(new Recordings(), ic->stringToIdentity("Recordings"));
- adapter->add(new Maintenance(adapter, NULL), ic->stringToIdentity("Maintenance"));
- adapter->activate();
-
- r = P2PVR::RecordingsPrx::checkedCast(ic->stringToProxy("Recordings"));
- BOOST_REQUIRE(r);
- r->ice_ping();
-
- s = P2PVR::SIPrx::checkedCast(ic->stringToProxy("SI"));
- BOOST_REQUIRE(s);
- s->ice_ping();
-
- m = P2PVR::MaintenancePrx::checkedCast(ic->stringToProxy("Maintenance"));
- BOOST_REQUIRE(m);
- m->ice_ping();
- }
-
- ~Core()
- {
- ic->destroy();
+ replace("GlobalDevices", new MockDevices());
+ replace("Schedules", new MockScheduler());
}
-
- P2PVR::MaintenancePrx m;
- P2PVR::RecordingsPrx r;
- P2PVR::SIPrx s;
-
- protected:
- Ice::CommunicatorPtr ic;
- Ice::ObjectAdapterPtr adapter;
};
class MockTarget : public P2PVR::RawDataClient {
@@ -77,18 +41,18 @@ class MockTarget : public P2PVR::RawDataClient {
unsigned int bytesReceived;
};
-BOOST_GLOBAL_FIXTURE( StandardMockDatabase );
+BOOST_GLOBAL_FIXTURE( TestService );
-BOOST_FIXTURE_TEST_SUITE( RecordingCore, Core );
+BOOST_FIXTURE_TEST_SUITE( RecordingCore, TestClient );
BOOST_AUTO_TEST_CASE( streamServiceToTarget )
{
BOOST_TEST_CHECKPOINT("Create mock target");
IceUtil::Handle<MockTarget> target = new MockTarget();
- TemporaryIceAdapterObject<P2PVR::RawDataClient> targetPrx(adapter, target);
+ TemporaryIceAdapterObject<P2PVR::RawDataClient> targetPrx(getAdapter(), target);
BOOST_TEST_CHECKPOINT("Create service streamer");
- auto ss = ServiceStreamerPtr(new ServiceStreamer(4170, targetPrx, ic, adapter));
+ auto ss = ServiceStreamerPtr(new ServiceStreamer(4170, targetPrx, devices, si, getAdapter()));
BOOST_TEST_CHECKPOINT("Start");
ss->Start();
diff --git a/p2pvr/daemon/unittests/testRecordings.cpp b/p2pvr/daemon/unittests/testRecordings.cpp
index a0b88b5..de28c8b 100644
--- a/p2pvr/daemon/unittests/testRecordings.cpp
+++ b/p2pvr/daemon/unittests/testRecordings.cpp
@@ -1,7 +1,7 @@
#define BOOST_TEST_MODULE Recordings
#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>
-#include <testOptionsSource.h>
+#include <options.h>
#include <Ice/ObjectAdapter.h>
#include <Ice/Service.h>
#include <maintenance.h>
@@ -14,50 +14,14 @@
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include "mockDefs.h"
-#include <testAppInstance.h>
-
-class Core : public TestAppInstance {
- public:
- Core()
- {
- int paramCount = 0;
- ic = Ice::initialize(paramCount, NULL);
- auto adapter = ic->createObjectAdapterWithEndpoints("Adp", "tcp -p 12001");
- TestOptionsSource::LoadTestOptions({
- { "common.datasourceRoot", (rootDir / "datasources").string() },
- });
- adapter->add(new Recordings(), ic->stringToIdentity("Recordings"));
- adapter->add(new SI(), ic->stringToIdentity("SI"));
- adapter->activate();
-
- r = P2PVR::RecordingsPrx::checkedCast(ic->stringToProxy("Recordings"));
- BOOST_REQUIRE(r);
- r->ice_ping();
-
- si = P2PVR::SIPrx::checkedCast(ic->stringToProxy("SI"));
- BOOST_REQUIRE(si);
- si->ice_ping();
- }
-
- ~Core()
- {
- ic->destroy();
- }
-
- P2PVR::SIPrx si;
- P2PVR::RecordingsPrx r;
-
- private:
- Ice::CommunicatorPtr ic;
-};
BOOST_GLOBAL_FIXTURE( StandardMockDatabase );
-BOOST_FIXTURE_TEST_SUITE( RecCore, Core )
+BOOST_FIXTURE_TEST_SUITE( RecCore, TestClient )
BOOST_AUTO_TEST_CASE( recordings_get )
{
- r->GetRecordings();
+ recordings->GetRecordings();
}
BOOST_AUTO_TEST_CASE( recordings_addAndDelete )
@@ -68,10 +32,10 @@ BOOST_AUTO_TEST_CASE( recordings_addAndDelete )
auto guid = boost::lexical_cast<std::string>(boost::uuids::random_generator()());
auto rec = P2PVR::RecordingPtr(new P2PVR::Recording(0, "", guid, 0, event->EventUid));
- rec->RecordingId = r->NewRecording(rec);
+ rec->RecordingId = recordings->NewRecording(rec);
BOOST_REQUIRE_EQUAL(218, rec->RecordingId);
- r->GetRecordings();
- r->DeleteRecording(rec->RecordingId);
+ recordings->GetRecordings();
+ recordings->DeleteRecording(rec->RecordingId);
}
BOOST_AUTO_TEST_SUITE_END()
diff --git a/p2pvr/daemon/unittests/testSched.cpp b/p2pvr/daemon/unittests/testSched.cpp
index 45414aa..aab5102 100644
--- a/p2pvr/daemon/unittests/testSched.cpp
+++ b/p2pvr/daemon/unittests/testSched.cpp
@@ -1,7 +1,7 @@
#define BOOST_TEST_MODULE Scheduler
#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>
-#include <testOptionsSource.h>
+#include <options.h>
#include <Ice/ObjectAdapter.h>
#include <Ice/Service.h>
#include <maintenance.h>
@@ -16,46 +16,23 @@
#include <boost/lexical_cast.hpp>
#include <commonHelpers.h>
#include "mockDefs.h"
-#include <testAppInstance.h>
-class Core : public TestAppInstance {
+class TestService : public StandardMockDatabasePlusOffset {
public:
- Core()
+ TestService()
{
- int paramCount = 0;
- ic = Ice::initialize(paramCount, NULL);
- auto adapter = ic->createObjectAdapterWithEndpoints("Adp", "tcp -p 12003");
- TestOptionsSource::LoadTestOptions({
- { "common.datasourceRoot", (rootDir / "datasources").string() },
- });
- adapter->add(new Schedules(), ic->stringToIdentity("Schedules"));
- adapter->add(new MockDevices(), ic->stringToIdentity("GlobalDevices"));
- adapter->add(new MockRecorder(), ic->stringToIdentity("Recorder"));
- adapter->activate();
-
- sc = P2PVR::SchedulesPrx::checkedCast(ic->stringToProxy("Schedules"));
- BOOST_REQUIRE(sc);
- sc->ice_ping();
- }
-
- ~Core()
- {
- ic->destroy();
+ replace("GlobalDevices", new MockDevices());
+ replace("Recorder", new MockRecorder());
}
-
- P2PVR::SchedulesPrx sc;
-
- private:
- Ice::CommunicatorPtr ic;
};
-BOOST_GLOBAL_FIXTURE( StandardMockDatabasePlusOffset );
+BOOST_GLOBAL_FIXTURE( TestService );
-BOOST_FIXTURE_TEST_SUITE( ScCore, Core )
+BOOST_FIXTURE_TEST_SUITE( ScCore, TestClient )
BOOST_AUTO_TEST_CASE( sc_getSchedules )
{
- auto ss = sc->GetSchedules();
+ auto ss = schedules->GetSchedules();
BOOST_REQUIRE_EQUAL(ss.size(), 2);
BOOST_REQUIRE(ss[0]->Search);
BOOST_REQUIRE_EQUAL(*ss[0]->Search, "Top Gear");
@@ -65,12 +42,12 @@ BOOST_AUTO_TEST_CASE( sc_getSchedules )
BOOST_AUTO_TEST_CASE( sc_doReschedule )
{
- sc->DoReschedule();
+ schedules->DoReschedule();
}
BOOST_AUTO_TEST_CASE( sc_getScheduled )
{
- auto str = sc->GetScheduledToRecord();
+ auto str = schedules->GetScheduledToRecord();
BOOST_REQUIRE_EQUAL(str.size(), 62);
}
@@ -79,10 +56,10 @@ BOOST_AUTO_TEST_CASE( sc_crud )
P2PVR::SchedulePtr schedule = new P2PVR::Schedule();
schedule->Search = "Top Gear";
- schedule->ScheduleId = sc->NewSchedule(schedule);
+ schedule->ScheduleId = schedules->NewSchedule(schedule);
BOOST_REQUIRE_EQUAL(187, schedule->ScheduleId);
- auto fetched = sc->GetSchedule(schedule->ScheduleId);
+ auto fetched = schedules->GetSchedule(schedule->ScheduleId);
BOOST_REQUIRE_EQUAL(schedule->ScheduleId, fetched->ScheduleId);
BOOST_REQUIRE_EQUAL(*schedule->Search, *fetched->Search);
BOOST_REQUIRE_EQUAL(schedule->Priority, fetched->Priority);
@@ -93,9 +70,9 @@ BOOST_AUTO_TEST_CASE( sc_crud )
schedule->Search = "Top Gear Special";
schedule->Early.Minutes = 5;
schedule->Late.Minutes = 15;
- sc->UpdateSchedule(schedule);
+ schedules->UpdateSchedule(schedule);
- fetched = sc->GetSchedule(schedule->ScheduleId);
+ fetched = schedules->GetSchedule(schedule->ScheduleId);
BOOST_REQUIRE_EQUAL(schedule->ScheduleId, fetched->ScheduleId);
BOOST_REQUIRE_EQUAL(*schedule->Search, *fetched->Search);
BOOST_REQUIRE_EQUAL(schedule->Priority, fetched->Priority);
@@ -103,7 +80,7 @@ BOOST_AUTO_TEST_CASE( sc_crud )
BOOST_REQUIRE_EQUAL(schedule->Early, fetched->Early);
BOOST_REQUIRE_EQUAL(schedule->Late, fetched->Late);
- sc->DeleteSchedule(fetched->ScheduleId);
+ schedules->DeleteSchedule(fetched->ScheduleId);
}
BOOST_AUTO_TEST_SUITE_END()
diff --git a/p2pvr/daemon/unittests/testSi.cpp b/p2pvr/daemon/unittests/testSi.cpp
index 9e42e74..55998f9 100644
--- a/p2pvr/daemon/unittests/testSi.cpp
+++ b/p2pvr/daemon/unittests/testSi.cpp
@@ -1,7 +1,7 @@
#define BOOST_TEST_MODULE SI
#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>
-#include <testOptionsSource.h>
+#include <options.h>
#include <Ice/ObjectAdapter.h>
#include <Ice/Service.h>
#include <maintenance.h>
@@ -13,40 +13,10 @@
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include "mockDefs.h"
-#include <testAppInstance.h>
-
-class Core : public TestAppInstance {
- public:
- Core()
- {
- int paramCount = 0;
- ic = Ice::initialize(paramCount, NULL);
- auto adapter = ic->createObjectAdapterWithEndpoints("Adp", "tcp -p 12002");
- TestOptionsSource::LoadTestOptions({
- { "common.datasourceRoot", (rootDir / "datasources").string() },
- });
- adapter->add(new SI(), ic->stringToIdentity("SI"));
- adapter->activate();
-
- si = P2PVR::SIPrx::checkedCast(ic->stringToProxy("SI"));
- BOOST_REQUIRE(si);
- si->ice_ping();
- }
-
- ~Core()
- {
- ic->destroy();
- }
-
- P2PVR::SIPrx si;
-
- private:
- Ice::CommunicatorPtr ic;
-};
BOOST_GLOBAL_FIXTURE( StandardMockDatabase );
-BOOST_FIXTURE_TEST_SUITE( SiCore, Core )
+BOOST_FIXTURE_TEST_SUITE( SiCore, TestClient )
BOOST_AUTO_TEST_CASE ( si_getEvents )
{
diff --git a/p2pvr/daemon/unittests/testSqlSelectDeserializer.cpp b/p2pvr/daemon/unittests/testSqlSelectDeserializer.cpp
deleted file mode 100644
index 47d36c5..0000000
--- a/p2pvr/daemon/unittests/testSqlSelectDeserializer.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-#define BOOST_TEST_MODULE SqlSelectDeserializer
-#include <boost/test/unit_test.hpp>
-#include <slicer/db/sqlSelectDeserializer.h>
-#include <slicer/slicer.h>
-#include <connection.h>
-#include <p2pvr.h>
-#include <rdbmsDataSource.h>
-#include <commonObjects.h>
-#include <testOptionsSource.h>
-#include <boost/filesystem/operations.hpp>
-#include <definedDirs.h>
-#include <commonHelpers.h>
-#include "mockDefs.h"
-#include <testAppInstance.h>
-
-typedef boost::shared_ptr<DB::SelectCommand> SelectPtr;
-
-class TestCommonObjects : public CommonObjects, public TestAppInstance {
- public:
- TestCommonObjects()
- {
- TestOptionsSource::LoadTestOptions({
- { "common.datasourceRoot", (rootDir / "datasources").string() },
- });
- }
-};
-
-BOOST_GLOBAL_FIXTURE( StandardMockDatabase );
-
-BOOST_FIXTURE_TEST_SUITE ( Sql, TestCommonObjects );
-
-BOOST_AUTO_TEST_CASE( listOfEvents )
-{
- auto db = dataSource<RdbmsDataSource>("postgres")->getReadonly();
- auto sel = SelectPtr(db->newSelectCommand("SELECT * FROM events ORDER BY serviceId, eventId LIMIT 100"));
- auto res = Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::Events>(*sel);
- BOOST_REQUIRE_EQUAL(res.size(), 100);
- BOOST_REQUIRE_EQUAL(res[0]->ServiceId, 4166);
- BOOST_REQUIRE_EQUAL(res[0]->EventId, 49741);
- BOOST_REQUIRE_EQUAL(res[0]->Title, "Skiing Weatherview");
- BOOST_REQUIRE(!res[0]->Subtitle);
- BOOST_REQUIRE_EQUAL(res[0]->Description, "Detailed weather forecast.");
- BOOST_REQUIRE_EQUAL(res[0]->StartTime, Common::DateTime({2014, 12, 19, 0, 25}));
- BOOST_REQUIRE_EQUAL(res[0]->StopTime, Common::DateTime({2014, 12, 19, 0, 30}));
- BOOST_REQUIRE(res[0]->Current);
- BOOST_REQUIRE_EQUAL(res[99]->ServiceId, 4166);
- BOOST_REQUIRE_EQUAL(res[99]->EventId, 52448);
- BOOST_REQUIRE_EQUAL(res[99]->Title, "East Midlands Today");
-}
-
-BOOST_AUTO_TEST_CASE( singleField )
-{
- auto db = dataSource<RdbmsDataSource>("postgres")->getReadonly();
- auto sel = SelectPtr(db->newSelectCommand("SELECT EventId FROM events ORDER BY serviceId, eventId LIMIT 1"));
- auto res = Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, int>(*sel);
- BOOST_REQUIRE_EQUAL(res, 49741);
-}
-
-BOOST_AUTO_TEST_CASE( singleEvent )
-{
- auto db = dataSource<RdbmsDataSource>("postgres")->getReadonly();
- auto sel = SelectPtr(db->newSelectCommand("SELECT * FROM events ORDER BY serviceId, eventId LIMIT 1"));
- auto res = Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::EventPtr>(*sel);
- BOOST_REQUIRE_EQUAL(res->ServiceId, 4166);
- BOOST_REQUIRE_EQUAL(res->EventId, 49741);
- BOOST_REQUIRE_EQUAL(res->Title, "Skiing Weatherview");
- BOOST_REQUIRE(!res->Subtitle);
- BOOST_REQUIRE_EQUAL(res->Description, "Detailed weather forecast.");
- BOOST_REQUIRE_EQUAL(res->StartTime, Common::DateTime({2014, 12, 19, 0, 25}));
- BOOST_REQUIRE_EQUAL(res->StopTime, Common::DateTime({2014, 12, 19, 0, 30}));
-}
-
-BOOST_AUTO_TEST_CASE( dynamicTypes )
-{
- auto db = dataSource<RdbmsDataSource>("postgres")->getReadonly();
- auto sel = SelectPtr(db->newSelectCommand("SELECT d.*, '::DVBSI::TerrestrialDelivery' \"typeid\" FROM delivery_dvbt d ORDER BY TransportStreamId"));
- auto res = Slicer::DeserializeAny<Slicer::SqlSelectDeserializer, P2PVR::Deliveries>(*sel, "typeid");
- BOOST_REQUIRE_EQUAL(res.size(), 6);
- auto dvbt = DVBSI::TerrestrialDeliveryPtr::dynamicCast(res[0]);
- BOOST_REQUIRE_EQUAL(dvbt->Frequency, 682000000);
- BOOST_REQUIRE_EQUAL(dvbt->TransportStreamId, 4170);
- BOOST_REQUIRE_EQUAL(dvbt->CodeRateHP, 2);
-}
-
-BOOST_AUTO_TEST_SUITE_END();
-
diff --git a/p2pvr/daemon/unittests/testStorage.cpp b/p2pvr/daemon/unittests/testStorage.cpp
index 973e93b..9e15662 100644
--- a/p2pvr/daemon/unittests/testStorage.cpp
+++ b/p2pvr/daemon/unittests/testStorage.cpp
@@ -1,7 +1,7 @@
#define BOOST_TEST_MODULE Storage
#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>
-#include <testOptionsSource.h>
+#include <options.h>
#include <Ice/ObjectAdapter.h>
#include <Ice/Service.h>
#include <maintenance.h>
@@ -10,73 +10,60 @@
#include <storage.h>
#include <boost/lexical_cast.hpp>
#include <commonHelpers.h>
-#include <testAppInstance.h>
+#include <definedDirs.h>
+#include "mockDefs.h"
-const boost::filesystem::path rootDir = "/tmp/ut/p2pvr/recordings";
-class Core : public TestAppInstance {
+const boost::filesystem::path storageRootDir = "/tmp/ut/p2pvr/recordings";
+class TestService : public PQ::Mock, public IceTray::DryIce {
public:
- Core()
+ TestService() :
+ PQ::Mock("user=postgres dbname=postgres", "postgres", {
+ rootDir.parent_path().parent_path() / "datasources" / "schema.sql" }),
+ IceTray::DryIce({
+ R"C(--p2pvr.storage.muxercommand="")C",
+ std::string("--p2pvr.storage.root=" + storageRootDir.string()),
+ })
{
- int paramCount = 0;
- ic = Ice::initialize(paramCount, NULL);
- auto adapter = ic->createObjectAdapterWithEndpoints("Adp", "tcp -p 12004");
- TestOptionsSource::LoadTestOptions({
- { "p2pvr.storage.muxercommand", std::string() },
- { "p2pvr.storage.root", rootDir.string() },
- });
- adapter->add(new Storage(), ic->stringToIdentity("Storage"));
- adapter->activate();
-
- st = P2PVR::StoragePrx::checkedCast(ic->stringToProxy("Storage"));
- BOOST_REQUIRE(st);
- st->ice_ping();
}
-
- ~Core()
- {
- ic->destroy();
- }
-
- P2PVR::StoragePrx st;
-
- private:
- Ice::CommunicatorPtr ic;
};
-BOOST_FIXTURE_TEST_SUITE( StCore, Core )
+BOOST_GLOBAL_FIXTURE( TestService );
+
+BOOST_FIXTURE_TEST_SUITE( StCore, TestClient );
BOOST_AUTO_TEST_CASE( st_openWriteClose )
{
- boost::filesystem::remove_all(rootDir);
+ boost::filesystem::remove_all(storageRootDir);
std::string id = "made-up-storage-id";
- auto rdc = st->OpenForWrite(id);
+ auto rdc = storage->OpenForWrite(id);
+ BOOST_REQUIRE(rdc);
P2PVR::Data data;
data.resize(1024);
rdc->NewData(data);
- st->Close(rdc);
+ storage->Close(rdc);
- auto stSize = st->FileSize(id);
+ auto stSize = storage->FileSize(id);
BOOST_REQUIRE_EQUAL(1024, stSize);
- BOOST_REQUIRE_EQUAL(1024, boost::filesystem::file_size(rootDir / id));
+ BOOST_REQUIRE_EQUAL(1024, boost::filesystem::file_size(storageRootDir / id));
- st->Delete(id);
- BOOST_REQUIRE(!boost::filesystem::exists(rootDir / id));
+ storage->Delete(id);
+ BOOST_REQUIRE(!boost::filesystem::exists(storageRootDir / id));
}
BOOST_AUTO_TEST_CASE( st_notuniqueid )
{
- boost::filesystem::remove_all(rootDir);
+ boost::filesystem::remove_all(storageRootDir);
std::string id = "made-up-storage-id";
- auto rdc = st->OpenForWrite(id);
- st->Close(rdc);
+ auto rdc = storage->OpenForWrite(id);
+ storage->Close(rdc);
- BOOST_REQUIRE_THROW(st->OpenForWrite(id), P2PVR::StorageException);
- st->Delete(id);
+ BOOST_REQUIRE_THROW(storage->OpenForWrite(id), P2PVR::StorageException);
+ storage->Delete(id);
}
BOOST_AUTO_TEST_SUITE_END()