database plugin queries support in constructor (untested)
[profile/ivi/automotive-message-broker.git] / plugins / database / databasesink.cpp
1 #include "databasesink.h"
2 #include "abstractroutingengine.h"
3 #include "listplusplus.h"
4
5 extern "C" AbstractSinkManager * create(AbstractRoutingEngine* routingengine, map<string, string> config)
6 {
7         return new DatabaseSinkManager(routingengine, config);
8 }
9
10 void * cbFunc(gpointer data)
11 {
12         Shared *shared = static_cast<Shared*>(data);
13
14         if(!shared)
15         {
16                 throw std::runtime_error("Could not cast shared object.");
17         }
18
19         vector<DictionaryList<string> > insertList;
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                 insertList.push_back(dict);
46
47                 if(insertList.size() > 100)
48                 {
49                         shared->db->exec("BEGIN IMMEDIATE TRANSACTION");
50                         for(int i=0; i< insertList.size(); i++)
51                         {
52                                 DictionaryList<string> d = insertList[i];
53                                 shared->db->insert(d);
54                         }
55                         shared->db->exec("END TRANSACTION");
56                         insertList.clear();
57                 }
58                 delete obj;
59         }
60
61         return NULL;
62 }
63
64 int getNextEvent(gpointer data)
65 {
66         PlaybackShared* pbshared = static_cast<PlaybackShared*>(data);
67
68         if(!pbshared)
69                 throw std::runtime_error("failed to cast PlaybackShared object");
70
71         auto itr = pbshared->playbackQueue.begin();
72
73         if(itr == pbshared->playbackQueue.end())
74         {
75                 return 0;
76         }
77
78         DBObject* obj = *itr;
79
80         AbstractPropertyType* value = VehicleProperty::getPropertyTypeForPropertyNameValue(obj->key,obj->value);
81
82         if(value)
83         {
84                 pbshared->routingEngine->updateProperty(obj->key, value, pbshared->uuid);
85                 value->timestamp = obj->time;
86                 //value->sequence = obj->sequence;
87         }
88
89         if(++itr != pbshared->playbackQueue.end())
90         {
91                 DBObject *o2 = *itr;
92                 double t = o2->time - obj->time;
93
94                 if(t > 0)
95                         g_timeout_add((t*1000) / pbshared->playBackMultiplier, getNextEvent, pbshared);
96                 else
97                         g_timeout_add(t, getNextEvent, pbshared);
98         }
99
100         pbshared->playbackQueue.remove(obj);
101         delete obj;
102
103         return 0;
104 }
105
106 DatabaseSink::DatabaseSink(AbstractRoutingEngine *engine, map<std::string, std::string> config)
107         :AbstractSource(engine,config),thread(NULL),shared(NULL),playback(false),playbackShared(NULL), playbackMultiplier(1)
108 {
109         databaseName = "storage";
110         tablename = "data";
111         tablecreate = "CREATE TABLE IF NOT EXISTS data (key TEXT, value BLOB, source TEXT, time REAL, sequence REAL)";
112
113         if(config.find("databaseFile") != config.end())
114         {
115                 databaseName = config["databaseFile"];
116         }
117
118         if(config.find("properties") != config.end())
119         {
120                 parseConfig();
121         }
122
123         for(auto itr=propertiesToSubscribeTo.begin();itr!=propertiesToSubscribeTo.end();itr++)
124         {
125                 engine->subscribeToProperty(*itr,this);
126         }
127
128         mSupported.push_back(DatabaseFileProperty);
129         mSupported.push_back(DatabaseLoggingProperty);
130         mSupported.push_back(DatabasePlaybackProperty);
131
132
133         initDb();
134
135         /// get supported:
136
137         vector<vector<string> > supportedStr = shared->db->select("SELECT DISTINCT key FROM "+tablename);
138
139         for(int i=0; i < supportedStr.size(); i++)
140         {
141                 if(!ListPlusPlus<VehicleProperty::Property>(&mSupported).contains(supportedStr[i][0]))
142                         mSupported.push_back(supportedStr[i][0]);
143         }
144
145         routingEngine->setSupported(supported(), this);
146
147         if(config.find("startOnLoad")!= config.end())
148         {
149                 startDb();
150         }
151
152         if(config.find("playbackMultiplier")!= config.end())
153         {
154                 playbackMultiplier = boost::lexical_cast<uint>(config["playbackMultiplier"]);
155         }
156
157         if(config.find("playbackOnLoad")!= config.end())
158         {
159                 startPlayback();
160         }
161
162
163 }
164
165 DatabaseSink::~DatabaseSink()
166 {
167         if(shared)
168         {
169                 DBObject* obj = new DBObject();
170                 obj->quit = true;
171
172                 shared->queue.append(obj);
173
174                 g_thread_join(thread);
175                 g_thread_unref(thread);
176                 delete shared;
177         }
178
179         if(playbackShared)
180         {
181                 delete playbackShared;
182         }
183 }
184
185
186 void DatabaseSink::supportedChanged(PropertyList supportedProperties)
187 {
188
189 }
190
191 PropertyList DatabaseSink::supported()
192 {
193         return mSupported;
194 }
195
196 void DatabaseSink::parseConfig()
197 {
198         json_object *rootobject;
199         json_tokener *tokener = json_tokener_new();
200         enum json_tokener_error err;
201         do
202         {
203                 rootobject = json_tokener_parse_ex(tokener, configuration["properties"].c_str(),configuration["properties"].size());
204         } while ((err = json_tokener_get_error(tokener)) == json_tokener_continue);
205         if (err != json_tokener_success)
206         {
207                 fprintf(stderr, "Error: %s\n", json_tokener_error_desc(err));
208         }
209         if (tokener->char_offset < configuration["properties"].size()) // XXX shouldn't access internal fields
210         {
211                 //Should handle the extra data here sometime...
212         }
213         
214         json_object *propobject = json_object_object_get(rootobject,"properties");
215         
216         g_assert(json_object_get_type(propobject) == json_type_array);
217
218         array_list *proplist = json_object_get_array(propobject);
219         
220         for(int i=0; i < array_list_length(proplist); i++)
221         {
222                 json_object *idxobj = (json_object*)array_list_get_idx(proplist,i);
223                 std::string prop = json_object_get_string(idxobj);
224                 propertiesToSubscribeTo.push_back(prop);
225
226                 DebugOut()<<"DatabaseSink logging: "<<prop<<endl;
227         }
228
229         json_object_put(propobject);
230         json_object_put(rootobject);
231 }
232
233 void DatabaseSink::stopDb()
234 {
235         if(!shared)
236                 return;
237
238         DBObject *obj = new DBObject();
239         obj->quit = true;
240         shared->queue.append(obj);
241
242         g_thread_join(thread);
243
244         delete shared;
245         shared = NULL;
246 }
247
248 void DatabaseSink::startDb()
249 {
250         if(playback)
251         {
252                 DebugOut(0)<<"ERROR: tried to start logging during playback.  Only logging or playback can be used at one time"<<endl;
253                 return;
254         }
255
256         if(shared)
257         {
258                 DebugOut(0)<<"WARNING: logging already started.  doing nothing."<<endl;
259                 return;
260         }
261
262         initDb();
263
264         thread = g_thread_new("dbthread", cbFunc, shared);
265 }
266
267 void DatabaseSink::startPlayback()
268 {
269         if(playback)
270                 return;
271
272         playback = true;
273
274         initDb();
275
276         /// populate playback queue:
277
278         vector<vector<string> > results = shared->db->select("SELECT * FROM "+tablename);
279
280         if(playbackShared)
281         {
282                 delete playbackShared;
283         }
284
285         playbackShared = new PlaybackShared(routingEngine, uuid(), playbackMultiplier);
286
287         for(int i=0;i<results.size();i++)
288         {
289                 if(results[i].size() < 5)
290                 {
291                         throw std::runtime_error("column mismatch in query");
292                 }
293
294                 DBObject* obj = new DBObject();
295
296                 obj->key = results[i][0];
297                 obj->value = results[i][1];
298                 obj->source = results[i][2];
299                 obj->time = boost::lexical_cast<double>(results[i][3]);
300 //              obj->sequence = boost::lexical_cast<int>(results[i][4]);
301
302                 playbackShared->playbackQueue.push_back(obj);
303         }
304
305         g_timeout_add(0,getNextEvent,playbackShared);
306 }
307
308 void DatabaseSink::initDb()
309 {
310         if(shared) delete shared;
311
312         shared = new Shared;
313         shared->db->init(databaseName, tablename, tablecreate);
314 }
315
316 void DatabaseSink::propertyChanged(VehicleProperty::Property property, AbstractPropertyType *value, std::string uuid)
317 {
318         if(!shared)
319                 return;
320
321         DBObject* obj = new DBObject;
322         obj->key = property;
323         obj->value = value->toString();
324         obj->source = uuid;
325         obj->time = value->timestamp;
326         obj->sequence = value->sequence;
327
328         shared->queue.append(obj);
329 }
330
331
332 std::string DatabaseSink::uuid()
333 {
334         return "9f88156e-cb92-4472-8775-9c08addf50d3";
335 }
336
337 void DatabaseSink::getPropertyAsync(AsyncPropertyReply *reply)
338 {
339         reply->success = false;
340
341         if(reply->property == DatabaseFileProperty)
342         {
343                 StringPropertyType temp(databaseName);
344                 reply->value = &temp;
345
346                 reply->success = true;
347                 reply->completed(reply);
348
349                 return;
350         }
351         else if(reply->property == DatabaseLoggingProperty)
352         {
353                 BasicPropertyType<bool> temp = shared;
354
355                 reply->value = &temp;
356                 reply->success = true;
357                 reply->completed(reply);
358
359                 return;
360         }
361
362         else if(reply->property == DatabasePlaybackProperty)
363         {
364                 BasicPropertyType<bool> temp = playback;
365                 reply->value = &temp;
366                 reply->success = true;
367                 reply->completed(reply);
368
369                 return;
370         }
371
372         reply->completed(reply);
373 }
374
375 void DatabaseSink::getRangePropertyAsync(AsyncRangePropertyReply *reply)
376 {
377         BaseDB * db = new BaseDB();
378         db->init(databaseName, tablename, tablecreate);
379
380         ostringstream query;
381         query.precision(15);
382
383         query<<"SELECT * from "<<tablename<<" WHERE ";
384
385         if(reply->timeBegin && reply->timeEnd)
386         {
387                 query<<" time BETWEEN "<<reply->timeBegin<<" AND "<<reply->timeEnd;
388         }
389
390         if(reply->sequenceBegin >= 0 && reply->sequenceEnd >=0)
391         {
392                 query<<" AND sequence BETWEEN "<<reply->sequenceBegin<<" AND "<<reply->sequenceEnd;
393         }
394
395         std::vector<std::vector<string>> data = db->select(query.str());
396
397         std::list<AbstractPropertyType*> cleanup;
398
399         for(auto i=0;i<data.size();i++)
400         {
401                 if(data[i].size() != 5)
402                         continue;
403
404                 DBObject dbobj;
405                 dbobj.key = data[i][0];
406                 dbobj.value = data[i][1];
407                 dbobj.source = data[i][2];
408                 dbobj.time = boost::lexical_cast<double>(data[i][3]);
409                 dbobj.sequence = boost::lexical_cast<double>(data[i][4]);
410
411                 AbstractPropertyType* property = VehicleProperty::getPropertyTypeForPropertyNameValue(dbobj.key, dbobj.value);
412                 if(property)
413                 {
414                         property->timestamp = dbobj.time;
415                         property->sequence = dbobj.sequence;
416
417                         reply->values.push_back(property);
418                         cleanup.push_back(property);
419                 }
420         }
421
422         reply->success = true;
423         reply->completed(reply);
424
425         delete db;
426 }
427
428 AsyncPropertyReply *DatabaseSink::setProperty(AsyncSetPropertyRequest request)
429 {
430         AsyncPropertyReply* reply = new AsyncPropertyReply(request);
431         reply->success = false;
432
433         if(request.property == DatabaseLoggingProperty)
434         {
435                 if(request.value->value<bool>())
436                 {
437                         ///TODO: start or stop logging thread
438                         startDb();
439                         reply->success = true;
440                         BasicPropertyType<bool> temp(true);
441                         routingEngine->updateProperty(DatabaseLoggingProperty,&temp,uuid());
442                 }
443                 else
444                 {
445                         stopDb();
446                         reply->success = true;
447                         BasicPropertyType<bool> temp(false);
448                         routingEngine->updateProperty(DatabaseLoggingProperty,&temp,uuid());
449                 }
450         }
451
452         else if(request.property == DatabaseFileProperty)
453         {
454                 std::string fname = request.value->toString();
455
456                 databaseName = fname;
457
458                 StringPropertyType temp(databaseName);
459
460                 routingEngine->updateProperty(DatabaseFileProperty,&temp,uuid());
461
462                 reply->success = true;
463         }
464         else if( request.property == DatabasePlaybackProperty)
465         {
466                 if(request.value->value<bool>())
467                 {
468                         startPlayback();
469
470                         BasicPropertyType<bool> temp(true);
471
472                         routingEngine->updateProperty(DatabasePlaybackProperty,&temp,uuid());
473                 }
474                 else
475                 {
476                         /// TODO: stop playback
477
478                         BasicPropertyType<bool> temp(true);
479
480                         routingEngine->updateProperty(DatabasePlaybackProperty,&temp,uuid());
481                 }
482
483                 reply->success = true;
484         }
485
486         return reply;
487 }
488
489 void DatabaseSink::subscribeToPropertyChanges(VehicleProperty::Property )
490 {
491
492 }
493
494 void DatabaseSink::unsubscribeToPropertyChanges(VehicleProperty::Property )
495 {
496 }