big database plugin update
[profile/ivi/automotive-message-broker.git] / plugins / database / databasesink.cpp
1 #include "databasesink.h"
2 #include "abstractroutingengine.h"
3 #include "listplusplus.h"
4
5 #include <json-glib/json-glib.h>
6
7 extern "C" AbstractSinkManager * create(AbstractRoutingEngine* routingengine, map<string, string> config)
8 {
9         return new DatabaseSinkManager(routingengine, config);
10 }
11
12 void * cbFunc(gpointer data)
13 {
14         Shared *shared = static_cast<Shared*>(data);
15
16         if(!shared)
17         {
18                 throw std::runtime_error("Could not cast shared object.");
19         }
20
21         while(1)
22         {
23                 DBObject* obj = shared->queue.pop();
24
25                 if( obj->quit )
26                 {
27                         delete obj;
28                         break;
29                 }
30
31                 DictionaryList<string> dict;
32
33                 NameValuePair<string> one("key", obj->key);
34                 NameValuePair<string> two("value", obj->value);
35                 NameValuePair<string> three("source", obj->source);
36                 NameValuePair<string> four("time", boost::lexical_cast<string>(obj->time));
37                 NameValuePair<string> five("sequence", boost::lexical_cast<string>(obj->sequence));
38
39                 dict.push_back(one);
40                 dict.push_back(two);
41                 dict.push_back(three);
42                 dict.push_back(four);
43                 dict.push_back(five);
44
45                 shared->db->insert(dict);
46                 delete obj;
47         }
48
49         return NULL;
50 }
51
52 int getNextEvent(gpointer data)
53 {
54         PlaybackShared* pbshared = static_cast<PlaybackShared*>(data);
55
56         if(!pbshared)
57                 throw std::runtime_error("failed to cast PlaybackShared object");
58
59         auto itr = pbshared->playbackQueue.begin();
60
61         if(itr == pbshared->playbackQueue.end())
62         {
63                 return 0;
64         }
65
66         DBObject* obj = *itr;
67
68         AbstractPropertyType* value = VehicleProperty::getPropertyTypeForPropertyNameValue(obj->key,obj->value);
69
70         if(value)
71         {
72                 pbshared->routingEngine->updateProperty(obj->key, value, pbshared->uuid);
73         }
74
75         if(++itr != pbshared->playbackQueue.end())
76         {
77                 DBObject *o2 = *itr;
78                 double t = o2->time - obj->time;
79
80                 if(t > 0)
81                         g_timeout_add(t*1000, getNextEvent, pbshared);
82                 else
83                         g_timeout_add(t, getNextEvent, pbshared);
84         }
85
86         pbshared->playbackQueue.remove(obj);
87         delete obj;
88
89         return 0;
90 }
91
92 DatabaseSink::DatabaseSink(AbstractRoutingEngine *engine, map<std::string, std::string> config)
93         :AbstractSource(engine,config),thread(NULL),shared(NULL),playback(false),playbackShared(NULL)
94 {
95         databaseName = "storage";
96         tablename = "data";
97         tablecreate = "CREATE TABLE IF NOT EXISTS data (key TEXT, value BLOB, source TEXT, time REAL, sequence REAL)";
98
99         //startDb();
100
101         if(config.find("startOnLoad")!= config.end())
102         {
103                 startDb();
104         }
105
106         parseConfig();
107
108         for(auto itr=propertiesToSubscribeTo.begin();itr!=propertiesToSubscribeTo.end();itr++)
109         {
110                 engine->subscribeToProperty(*itr,this);
111         }
112
113         mSupported.push_back(DatabaseFileProperty);
114         mSupported.push_back(DatabaseLoggingProperty);
115         mSupported.push_back(DatabasePlaybackProperty);
116
117         routingEngine->setSupported(mSupported,this);
118
119 }
120
121 DatabaseSink::~DatabaseSink()
122 {
123         if(shared)
124         {
125                 DBObject* obj = new DBObject();
126                 obj->quit = true;
127
128                 shared->queue.append(obj);
129
130                 g_thread_join(thread);
131                 g_thread_unref(thread);
132                 delete shared;
133         }
134 }
135
136
137 void DatabaseSink::supportedChanged(PropertyList supportedProperties)
138 {
139
140 }
141
142 PropertyList DatabaseSink::supported()
143 {
144         return mSupported;
145 }
146
147 void DatabaseSink::parseConfig()
148 {
149         JsonParser* parser = json_parser_new();
150         GError* error = nullptr;
151         if(!json_parser_load_from_data(parser, configuration["properties"].c_str(),configuration["properties"].size(), &error))
152         {
153                 DebugOut()<<"Failed to load config: "<<error->message;
154                 throw std::runtime_error("Failed to load config");
155         }
156
157         JsonNode* node = json_parser_get_root(parser);
158
159         if(node == nullptr)
160                 throw std::runtime_error("Unable to get JSON root object");
161
162         JsonReader* reader = json_reader_new(node);
163
164         if(reader == nullptr)
165                 throw std::runtime_error("Unable to create JSON reader");
166
167         json_reader_read_member(reader,"properties");
168
169         g_assert(json_reader_is_array(reader));
170
171         for(int i=0; i < json_reader_count_elements(reader); i++)
172         {
173                 json_reader_read_element(reader, i);
174                 std::string prop = json_reader_get_string_value(reader);
175                 propertiesToSubscribeTo.push_back(prop);
176                 json_reader_end_element(reader);
177
178                 DebugOut()<<"DatabaseSink logging: "<<prop<<endl;
179         }
180
181         if(error) g_error_free(error);
182
183         g_object_unref(reader);
184         g_object_unref(parser);
185 }
186
187 void DatabaseSink::stopDb()
188 {
189         if(!shared)
190                 return;
191
192         DBObject *obj = new DBObject();
193         obj->quit = true;
194         shared->queue.append(obj);
195
196         g_thread_join(thread);
197         g_thread_unref(thread);
198
199         delete shared;
200         shared = NULL;
201 }
202
203 void DatabaseSink::startDb()
204 {
205         if(playback)
206         {
207                 DebugOut(0)<<"ERROR: tried to start logging during playback.  Only logging or playback can be used at one time"<<endl;
208                 return;
209         }
210
211         if(shared)
212         {
213                 DebugOut(0)<<"WARNING: logging already started.  doing nothing."<<endl;
214                 return;
215         }
216
217         initDb();
218
219 //      thread = g_thread_new("dbthread", cbFunc, shared);
220 }
221
222 void DatabaseSink::startPlayback()
223 {
224         if(playback)
225                 return;
226
227         playback = true;
228
229         initDb();
230
231         /// get supported:
232
233         vector<vector<string> > supportedStr = shared->db->select("SELECT DISTINCT key FROM "+tablename);
234
235         for(int i=0; i < supportedStr.size(); i++)
236         {
237                 if(!ListPlusPlus<VehicleProperty::Property>(&mSupported).contains(supportedStr[i][0]))
238                         mSupported.push_back(supportedStr[i][0]);
239         }
240
241         routingEngine->setSupported(supported(), this);
242
243         /// populate playback queue:
244
245         vector<vector<string> > results = shared->db->select("SELECT * FROM "+tablename);
246
247         if(playbackShared)
248         {
249                 delete playbackShared;
250         }
251
252         playbackShared = new PlaybackShared(routingEngine,uuid());
253
254         for(int i=0;i<results.size();i++)
255         {
256                 if(results[i].size() < 5)
257                 {
258                         throw std::runtime_error("column mismatch in query");
259                 }
260
261                 DBObject* obj = new DBObject();
262
263                 obj->key = results[i][0];
264                 obj->value = results[i][1];
265                 obj->source = results[i][2];
266                 obj->time = boost::lexical_cast<double>(results[i][3]);
267                 obj->sequence = boost::lexical_cast<uint16_t>(results[i][4]);
268
269                 playbackShared->playbackQueue.push_back(obj);
270         }
271 }
272
273 void DatabaseSink::initDb()
274 {
275         if(shared) delete shared;
276
277         shared = new Shared;
278         shared->db->init(databaseName, tablename, tablecreate);
279 }
280
281 void DatabaseSink::propertyChanged(VehicleProperty::Property property, AbstractPropertyType *value, std::string uuid)
282 {
283         if(!shared)
284                 return;
285
286         DBObject* obj = new DBObject;
287         obj->key = property;
288         obj->value = value->toString();
289         obj->source = uuid;
290         obj->time = value->timestamp;
291         obj->sequence = value->sequence;
292
293         shared->queue.append(obj);
294 }
295
296
297 std::string DatabaseSink::uuid()
298 {
299         return "9f88156e-cb92-4472-8775-9c08addf50d3";
300 }
301
302 void DatabaseSink::getPropertyAsync(AsyncPropertyReply *reply)
303 {
304         reply->success = false;
305
306         if(reply->property == DatabaseFileProperty)
307         {
308                 StringPropertyType temp(databaseName);
309                 reply->value = &temp;
310
311                 reply->success = true;
312                 reply->completed(reply);
313
314                 return;
315         }
316         else if(reply->property == DatabaseLoggingProperty)
317         {
318                 BasicPropertyType<bool> temp = shared;
319
320                 reply->value = &temp;
321                 reply->success = true;
322                 reply->completed(reply);
323
324                 return;
325         }
326
327         else if(reply->property == DatabasePlaybackProperty)
328         {
329                 BasicPropertyType<bool> temp = playback;
330                 reply->value = &temp;
331                 reply->success = true;
332                 reply->completed(reply);
333
334                 return;
335         }
336
337         reply->completed(reply);
338 }
339
340 void DatabaseSink::getRangePropertyAsync(AsyncRangePropertyReply *reply)
341 {
342         BaseDB * db = new BaseDB();
343         db->init(databaseName, tablename, tablecreate);
344
345         ostringstream query;
346         query.precision(15);
347
348         query<<"SELECT * from "<<tablename<<" WHERE ";
349
350         if(reply->timeBegin && reply->timeEnd)
351         {
352                 query<<" time BETWEEN "<<reply->timeBegin<<" AND "<<reply->timeEnd;
353         }
354
355         if(reply->sequenceBegin >= 0 && reply->sequenceEnd >=0)
356         {
357                 query<<" AND sequence BETWEEN "<<reply->sequenceBegin<<" AND "<<reply->sequenceEnd;
358         }
359
360         std::vector<std::vector<string>> data = db->select(query.str());
361
362         std::list<AbstractPropertyType*> cleanup;
363
364         for(auto i=0;i<data.size();i++)
365         {
366                 if(data[i].size() != 5)
367                         continue;
368
369                 DBObject dbobj;
370                 dbobj.key = data[i][0];
371                 dbobj.value = data[i][1];
372                 dbobj.source = data[i][2];
373                 dbobj.time = boost::lexical_cast<double>(data[i][3]);
374                 dbobj.sequence = boost::lexical_cast<double>(data[i][4]);
375
376                 AbstractPropertyType* property = VehicleProperty::getPropertyTypeForPropertyNameValue(dbobj.key, dbobj.value);
377                 if(property)
378                 {
379                         property->timestamp = dbobj.time;
380                         property->sequence = dbobj.sequence;
381
382                         reply->values.push_back(property);
383                         cleanup.push_back(property);
384                 }
385         }
386
387         reply->success = true;
388         reply->completed(reply);
389
390         /// reply is owned by the requester of this call.  we own the data:
391         for(auto itr = cleanup.begin(); itr != cleanup.end(); itr++)
392         {
393                 delete *itr;
394         }
395
396         delete db;
397 }
398
399 AsyncPropertyReply *DatabaseSink::setProperty(AsyncSetPropertyRequest request)
400 {
401         AsyncPropertyReply* reply = new AsyncPropertyReply(request);
402         reply->success = false;
403
404         if(request.property == DatabaseLoggingProperty)
405         {
406                 if(request.value->value<bool>())
407                 {
408                         ///TODO: start or stop logging thread
409                         startDb();
410                         reply->success = true;
411                 }
412                 else
413                 {
414                         stopDb();
415                         reply->success = true;
416                 }
417         }
418
419         else if(request.property == DatabaseFileProperty)
420         {
421                 std::string fname = request.value->toString();
422
423                 databaseName = fname;
424
425                 StringPropertyType temp(databaseName);
426
427                 routingEngine->updateProperty(DatabaseFileProperty,&temp,uuid());
428
429                 reply->success = true;
430         }
431         else if( request.property == DatabasePlaybackProperty)
432         {
433                 if(request.value->value<bool>())
434                 {
435                         startPlayback();
436                 }
437                 else
438                 {
439                         /// TODO: stop playback
440                 }
441
442                 reply->success = true;
443         }
444
445         return reply;
446 }
447
448 void DatabaseSink::subscribeToPropertyChanges(VehicleProperty::Property )
449 {
450
451 }
452
453 void DatabaseSink::unsubscribeToPropertyChanges(VehicleProperty::Property )
454 {
455 }