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