-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathPMGDQueryHandler.cc
More file actions
1089 lines (975 loc) · 33.7 KB
/
PMGDQueryHandler.cc
File metadata and controls
1089 lines (975 loc) · 33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file PMGDQueryHandler.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include <filesystem>
#include "PMGDIterators.h"
#include "PMGDQueryHandler.h"
#include "VDMSConfig.h"
#include "defines.h"
#include "util.h" // PMGD util
#include <limits>
// TODO In the complete version of VDMS, this file will live
// within PMGD which would replace the PMGD namespace. Some of
// these code pieces are temporary.
using namespace PMGD;
using namespace VDMS;
PMGD::Graph *PMGDQueryHandler::_db;
std::list<AutoDeleteNode *> PMGDQueryHandler::_expiration_timestamp_queue;
std::vector<std::string> PMGDQueryHandler::_cleanup_filename_list;
void PMGDQueryHandler::init() {
std::string dbname = VDMSConfig::instance()->get_path_pmgd();
int nalloc = VDMSConfig::instance()->get_int_value(
PARAM_PMGD_NUM_ALLOCATORS, DEFAULT_PMGD_NUM_ALLOCATORS);
PMGD::Graph::Config config;
config.num_allocators = nalloc;
// TODO: Include allocators timeouts params as parameters for VDMS.
// These parameters can be loaded everytime VDMS is run.
// We need PMGD to support these as config params before we can do it here.
if (_db != nullptr) {
delete _db;
_db = nullptr;
}
// Create a db
_db = new PMGD::Graph(dbname.c_str(), PMGD::Graph::Create, &config);
}
void PMGDQueryHandler::destroy() {
if (_db) {
delete _db;
_db = NULL;
}
}
std::vector<PMGDCmdResponses>
PMGDQueryHandler::process_queries(const PMGDCmds &cmds, int num_groups,
bool readonly, bool resultdeletion,
bool autodelete_init) {
std::vector<PMGDCmdResponses> responses(num_groups);
int retry_count = 0;
while (retry_count < PMGD_QUERY_RETRY_LIMIT) {
if (_tx == NULL) {
retry_count = PMGD_QUERY_RETRY_LIMIT; // exit retry loop
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(
20 * retry_count)); // backoff but for a longer time each try
retry_count++;
}
}
assert(_tx == NULL);
// Assuming one query handler handles one TX at a time.
_readonly = readonly;
_resultdeletion = resultdeletion;
_autodelete_init = autodelete_init;
if (_resultdeletion) {
_readonly = false; // change flag so database can be written
}
for (const auto cmd : cmds) {
PMGDCmdResponse *response = new PMGDCmdResponse();
response->set_node_edge(true); // most queries are node related
if (process_query(cmd, response) < 0) {
error_cleanup(responses, response);
break; // Goto cleanup site.
}
PMGDCmdResponses &resp_v = responses[cmd->cmd_grp_id()];
resp_v.push_back(response);
}
// Delete the Reusable iterators here.
for (auto it = _cached_nodes.begin(); it != _cached_nodes.end(); ++it) {
if (it->second != NULL)
delete it->second;
}
_cached_nodes.clear();
if (_tx != NULL) {
delete _tx;
_tx = NULL;
}
return responses;
}
void PMGDQueryHandler::error_cleanup(std::vector<PMGDCmdResponses> &responses,
PMGDCmdResponse *last_resp) {
int num_groups = responses.size();
for (unsigned i = 0; i < num_groups; ++i) {
unsigned size = responses[i].size();
for (unsigned j = 0; j < size; ++j) {
if (responses[i][j] != NULL)
delete responses[i][j];
}
responses[i].clear();
}
responses.clear();
// Since we have shortened the container, this reference will still remain
// valid. So we can reuse the 0th spot.
last_resp->set_cmd_grp_id(0);
PMGDCmdResponses resp_v1;
resp_v1.push_back(last_resp);
responses.push_back(resp_v1);
}
int PMGDQueryHandler::process_query(const PMGDCmd *cmd,
PMGDCmdResponse *response,
bool autodelete_init) {
int retval = 0;
PMGD::protobufs::Node *an;
try {
int code = cmd->cmd_id();
response->set_cmd_grp_id(cmd->cmd_grp_id());
switch (code) {
case PMGDCmd::TxBegin: {
int tx_options =
_readonly ? Transaction::ReadOnly : Transaction::ReadWrite;
_tx = new Transaction(*_db, tx_options);
set_response(response, protobufs::TX, PMGDCmdResponse::Success);
break;
}
case PMGDCmd::TxCommit: {
_tx->commit();
set_response(response, protobufs::TX, PMGDCmdResponse::Success);
break;
}
case PMGDCmd::TxAbort: {
set_response(response, protobufs::TX, PMGDCmdResponse::Abort,
"Abort called");
retval = -1;
break;
}
case PMGDCmd::AddNode:
retval = add_node(cmd->add_node(), response);
break;
case PMGDCmd::AddEdge:
retval = add_edge(cmd->add_edge(), response);
break;
case PMGDCmd::QueryNode:
retval = query_node(cmd->query_node(), response, autodelete_init);
break;
case PMGDCmd::QueryEdge:
retval = query_edge(cmd->query_edge(), response);
break;
case PMGDCmd::UpdateNode:
update_node(cmd->update_node(), response);
break;
case PMGDCmd::UpdateEdge:
update_edge(cmd->update_edge(), response);
break;
case PMGDCmd::DeleteExpired:
retval = delete_expired_nodes();
break;
}
} catch (Exception e) {
set_response(response, PMGDCmdResponse::Exception,
e.name + std::string(": ") + e.msg);
retval = -1;
}
return retval;
}
int PMGDQueryHandler::add_node(const protobufs::AddNode &cn,
PMGDCmdResponse *response) {
Json::UInt64 expiration_time;
long id = cn.identifier();
if (id >= 0 && _cached_nodes.find(id) != _cached_nodes.end()) {
set_response(response, PMGDCmdResponse::Error, "Reuse of _ref value");
return -1;
}
if (cn.has_query_node()) {
query_node(cn.query_node(), response);
// If we found the node we needed and it is unique, then this
// is the expected response. Just change the error code to exists
// as expected by an add_node return instead of Success as done
// in usual query_node. If we were supposed to cache
// the result, it should be done already.
if (response->r_type() == protobufs::NodeID &&
response->error_code() == PMGDCmdResponse::Success) {
response->set_error_code(PMGDCmdResponse::Exists);
return 0;
}
// The only situation where we would have to take further
// action is if the iterator was empty. And if there was some
// error like !unique, then we need to return the response as is.
if (response->error_code() != PMGDCmdResponse::Empty)
return -1;
}
// Since the node wasn't found, now add it.
StringID sid(cn.node().tag().c_str());
Node &n = _db->add_node(sid);
if (id >= 0)
_cached_nodes[id] = new ReusableNodeIterator(&n);
for (int i = 0; i < cn.node().properties_size(); ++i) {
const PMGDProp &p = cn.node().properties(i);
set_property(n, p);
if (cn.expiration_flag()) // Get the expiration time while iterating through
// the properties
{
if (p.key() == "_expiration") {
expiration_time = (Json::UInt64)p.int_value();
}
}
}
// add to deletion priority queue
if (cn.expiration_flag()) {
AutoDeleteNode *tmpDeleteNode = new AutoDeleteNode(expiration_time, &n);
insert_into_queue(&_expiration_timestamp_queue, tmpDeleteNode);
}
set_response(response, protobufs::NodeID, PMGDCmdResponse::Success);
// TODO: Partition code goes here
// For now, fill in the single system node id
response->set_op_int_value(_db->get_id(n));
return 0;
}
int PMGDQueryHandler::update_node(const protobufs::UpdateNode &un,
protobufs::CommandResponse *response) {
long id = un.identifier();
bool query = un.has_query_node();
auto it = _cached_nodes.end();
// If both _ref and query are defined, _ref will have priority.
if (id >= 0)
it = _cached_nodes.find(id);
if (it == _cached_nodes.end()) {
if (!query) {
set_response(response, PMGDCmdResponse::Error,
"Undefined _ref value used in update");
return -1;
} else {
query_node(un.query_node(), response);
if (response->error_code() != PMGDCmdResponse::Success)
return -1;
long qn_id = un.query_node().identifier();
if (qn_id >= 0)
it = _cached_nodes.find(qn_id);
else {
set_response(response, PMGDCmdResponse::Error,
"Undefined _ref value used in update");
return -1;
}
}
}
auto nit = it->second;
long updated = 0;
for (; *nit; nit->next()) {
Node &n = **nit;
updated++;
for (int i = 0; i < un.properties_size(); ++i) {
const protobufs::Property &p = un.properties(i);
set_property(n, p);
}
for (int i = 0; i < un.remove_props_size(); ++i)
n.remove_property(un.remove_props(i).c_str());
}
nit->reset();
set_response(response, protobufs::Count, PMGDCmdResponse::Success);
response->set_op_int_value(updated);
return 0;
}
int PMGDQueryHandler::add_edge(const protobufs::AddEdge &ce,
PMGDCmdResponse *response) {
response->set_node_edge(false);
long id = ce.identifier();
if (id >= 0 && _cached_edges.find(id) != _cached_edges.end()) {
set_response(response, PMGDCmdResponse::Error, "Reuse of _ref value");
return -1;
}
// Presumably this node gets placed here.
StringID sid(ce.edge().tag().c_str());
// Assumes there could be multiple.
ReusableNodeIterator *srcni, *dstni;
// Since _ref is optional, need to make sure the map has the
// right reference.
auto srcit = _cached_nodes.find(ce.edge().src());
auto dstit = _cached_nodes.find(ce.edge().dst());
if (srcit != _cached_nodes.end() && dstit != _cached_nodes.end()) {
srcni = srcit->second;
dstni = dstit->second;
} else {
set_response(response, PMGDCmdResponse::Error,
"Source/destination node references not found");
return -1;
}
if (srcni == NULL || dstni == NULL || !bool(*srcni) || !bool(*dstni)) {
set_response(response, PMGDCmdResponse::Empty,
"Empty node iterators for adding edge");
return -1;
}
ReusableEdgeIterator *rei = NULL;
if (id >= 0)
rei = new ReusableEdgeIterator();
long eid = 0;
// TODO: Partition code goes here
for (; *srcni; srcni->next()) {
Node &src = **srcni;
for (; *dstni; dstni->next()) {
Node &dst = **dstni;
Edge &e = _db->add_edge(src, dst, sid);
if (id >= 0)
rei->add(&e);
for (int i = 0; i < ce.edge().properties_size(); ++i) {
const PMGDProp &p = ce.edge().properties(i);
set_property(e, p);
}
eid = _db->get_id(e);
}
dstni->reset();
}
srcni->reset();
if (id >= 0) {
rei->reset(); // Since we add at tail.
_cached_edges[id] = rei;
}
set_response(response, protobufs::EdgeID, PMGDCmdResponse::Success);
// ID of the last edge added
response->set_op_int_value(eid);
return 0;
}
int PMGDQueryHandler::update_edge(const protobufs::UpdateEdge &ue,
PMGDCmdResponse *response) {
long id = ue.identifier();
bool query = ue.has_query_edge();
auto it = _cached_edges.end();
if (id >= 0)
it = _cached_edges.find(id);
if (it == _cached_edges.end()) {
if (!query) {
set_response(response, PMGDCmdResponse::Error,
"Undefined _ref value used in update");
return -1;
} else {
query_edge(ue.query_edge(), response);
if (response->error_code() != PMGDCmdResponse::Success)
return -1;
long qe_id = ue.query_edge().identifier();
if (qe_id >= 0)
it = _cached_edges.find(qe_id);
else {
set_response(response, PMGDCmdResponse::Error,
"Undefined _ref value used in update");
return -1;
}
}
}
auto eit = it->second;
long updated = 0;
for (; *eit; eit->next()) {
Edge &e = **eit;
updated++;
for (int i = 0; i < ue.properties_size(); ++i) {
const protobufs::Property &p = ue.properties(i);
set_property(e, p);
}
for (int i = 0; i < ue.remove_props_size(); ++i)
// TODO: If many nodes/edges are being updated,
// it would be advantageous
// to get the StringIDs for the properties in advance instead of
// converting each property name to a StringID
// every time it is used.
e.remove_property(ue.remove_props(i).c_str());
}
eit->reset();
set_response(response, protobufs::Count, PMGDCmdResponse::Success);
response->set_op_int_value(updated);
return 0;
}
template <class Element>
void PMGDQueryHandler::set_property(Element &e, const PMGDProp &p) {
switch (p.type()) {
case PMGDProp::BooleanType:
e.set_property(p.key().c_str(), p.bool_value());
break;
case PMGDProp::IntegerType:
e.set_property(p.key().c_str(), (long long)p.int_value());
break;
case PMGDProp::StringType:
e.set_property(p.key().c_str(), p.string_value());
break;
case PMGDProp::FloatType:
e.set_property(p.key().c_str(), p.float_value());
break;
case PMGDProp::TimeType: {
struct tm tm_e;
int hr, min;
unsigned long usec;
string_to_tm(p.time_value(), &tm_e, &usec, &hr, &min);
Time t_e(&tm_e, usec, hr, min); // time diff
e.set_property(p.key().c_str(), t_e);
break;
}
case PMGDProp::BlobType:
e.set_property(p.key().c_str(), p.blob_value());
}
}
int PMGDQueryHandler::query_node(const protobufs::QueryNode &qn,
PMGDCmdResponse *response,
bool autodelete_init) {
ReusableNodeIterator *start_ni = NULL;
PMGD::Direction dir;
StringID edge_tag;
const PMGDQueryConstraints &qc = qn.constraints();
const PMGDQueryResultInfo &qr = qn.results();
long id = qn.identifier();
if (id >= 0 && _cached_nodes.find(id) != _cached_nodes.end()) {
set_response(response, PMGDCmdResponse::Error, "Reuse of _ref value");
return -1;
}
bool has_link = qn.has_link();
if (has_link) { // case where link is used.
const protobufs::LinkInfo &link = qn.link();
if (link.nb_unique()) {
// TODO Add support for unique neighbors across iterators
set_response(response, PMGDCmdResponse::Error,
"Non-repeated neighbors not supported");
return -1;
}
long start_id = link.start_identifier();
auto start = _cached_nodes.find(start_id);
if (start == _cached_nodes.end()) {
set_response(response, PMGDCmdResponse::Error,
"Undefined _ref value used in link");
return -1;
}
start_ni = start->second;
dir = (PMGD::Direction)link.dir();
edge_tag = (link.edgetag_oneof_case() == protobufs::LinkInfo::kETagid)
? StringID(link.e_tagid())
: StringID(link.e_tag().c_str());
}
StringID search_node_tag =
(qc.tag_oneof_case() == PMGDQueryConstraints::kTagid)
? StringID(qc.tagid())
: StringID(qc.tag().c_str());
SearchExpression search(*_db, search_node_tag,
qn.constraints().p_op() == protobufs::Or);
for (int i = 0; i < qc.predicates_size(); ++i) {
const PMGDPropPred &p_pp = qc.predicates(i);
PropertyPredicate j_pp = construct_search_term(p_pp);
search.add_node_predicate(j_pp);
}
if (has_link) { // Check for edges constraints
for (int i = 0; i < qn.link().predicates_size(); ++i) {
const PMGDPropPred &p_pp = qn.link().predicates(i);
PropertyPredicate j_pp = construct_search_term(p_pp);
search.add_edge_predicate(j_pp);
}
}
PMGD::NodeIterator ni =
has_link ? PMGD::NodeIterator(new MultiNeighborIteratorImpl(
start_ni, search, dir, edge_tag))
: search.eval_nodes();
if (!bool(ni) && id >= 0) {
set_response(response, PMGDCmdResponse::Empty, "Null search iterator");
if (has_link)
start_ni->reset();
return -1;
}
// Set these in case there is no results block.
set_response(response, qr.r_type(), PMGDCmdResponse::Success);
// TODO: Also, this triggers a copy of the SearchExpression object
// via the SearchExpressionIterator class, which might be slow,
// especially with a lot of property constraints. Might need another
// way for it.
if (!(id >= 0 || qc.unique() || qr.sort())) {
// If not reusable
build_results<NodeIterator>(ni, qr, response);
// Make sure the starting iterator is reset for later use.
if (has_link)
start_ni->reset();
return 0;
}
ReusableNodeIterator *tni = new ReusableNodeIterator(ni);
if (qc.unique()) {
tni->next();
if (bool(*tni)) { // Not unique and that is an error here.
set_response(response, PMGDCmdResponse::NotUnique,
"Query response not unique");
if (has_link)
start_ni->reset();
delete tni;
return -1;
}
tni->reset();
}
if (qr.sort())
tni->sort(qr.sort_key().c_str(), qr.descending());
if (qr.r_type() != protobufs::Cached)
build_results<ReusableNodeIterator>(*tni, qr, response);
if (id >= 0) {
// We have to traverse the current iterator fully, so we can
// reset start_ni.
if (has_link)
tni->traverse_all();
tni->reset();
_cached_nodes[id] = tni;
} else
delete tni;
// If there is a link, we have to make sure the start_ni can be reset.
if (has_link)
start_ni->reset();
return 0;
}
int PMGDQueryHandler::query_edge(const protobufs::QueryEdge &qe,
PMGDCmdResponse *response) {
ReusableNodeIterator *start_ni = NULL;
PMGD::Direction dir;
const PMGDQueryConstraints &qc = qe.constraints();
const PMGDQueryResultInfo &qr = qe.results();
response->set_node_edge(false);
if (qc.p_op() == protobufs::Or) {
set_response(response, PMGDCmdResponse::Error,
"Or operation not implemented");
return -1;
}
long id = qe.identifier();
if (id >= 0 && _cached_edges.find(id) != _cached_edges.end()) {
set_response(response, PMGDCmdResponse::Error, "Reuse of _ref value");
return -1;
}
// See if we need to match edges based on some starting or
// ending nodes.
long src_id = qe.src_node_id();
ReusableNodeIterator *src_ni = NULL;
if (src_id >= 0) {
auto it = _cached_nodes.find(src_id);
if (it != _cached_nodes.end())
src_ni = it->second;
}
long dest_id = qe.dest_node_id();
ReusableNodeIterator *dest_ni = NULL;
if (dest_id >= 0) {
auto it = _cached_nodes.find(dest_id);
if (it != _cached_nodes.end())
dest_ni = it->second;
}
StringID search_edge_tag =
(qc.tag_oneof_case() == PMGDQueryConstraints::kTagid)
? StringID(qc.tagid())
: StringID(qc.tag().c_str());
SearchExpression search(*_db, search_edge_tag, false);
for (int i = 0; i < qc.predicates_size(); ++i) {
const PMGDPropPred &p_pp = qc.predicates(i);
PropertyPredicate j_pp = construct_search_term(p_pp);
search.add_node_predicate(j_pp);
}
EdgeIterator ei =
PMGD::EdgeIterator(new NodeEdgeIteratorImpl(search, src_ni, dest_ni));
if (!bool(ei) && id >= 0) {
set_response(response, PMGDCmdResponse::Empty, "Null search iterator");
// Make sure the src and dest Node iterators are resettled.
if (src_ni != NULL)
src_ni->reset();
if (dest_ni != NULL)
dest_ni->reset();
return -1;
}
// Set these in case there is no results block.
set_response(response, qr.r_type(), PMGDCmdResponse::Success);
if (!(id >= 0 || qc.unique() || qr.sort())) {
// If not reusable
build_results<EdgeIterator>(ei, qr, response);
// Make sure the src and dest Node iterators are resettled.
if (src_ni != NULL)
src_ni->reset();
if (dest_ni != NULL)
dest_ni->reset();
return 0;
}
ReusableEdgeIterator *tei = new ReusableEdgeIterator(ei);
if (qc.unique()) {
tei->next();
if (bool(*tei)) { // Not unique and that is an error here.
set_response(response, PMGDCmdResponse::NotUnique,
"Query response not unique");
delete tei;
if (src_ni != NULL)
src_ni->reset();
if (dest_ni != NULL)
dest_ni->reset();
return -1;
}
tei->reset();
}
if (qr.sort())
tei->sort(qr.sort_key().c_str(), qr.descending());
if (qr.r_type() != protobufs::Cached)
build_results<ReusableEdgeIterator>(*tei, qr, response);
if (id >= 0) {
tei->traverse_all();
tei->reset();
_cached_edges[id] = tei;
} else
delete tei;
if (src_ni != NULL)
src_ni->reset();
if (dest_ni != NULL)
dest_ni->reset();
return 0;
}
PropertyPredicate
PMGDQueryHandler::construct_search_term(const PMGDPropPred &p_pp) {
StringID key = (p_pp.key_oneof_case() == 2) ? StringID(p_pp.keyid())
: StringID(p_pp.key().c_str());
// Assumes exact match between enum values
// TODO Maybe have some way of verifying certain such assumptions at start?
PropertyPredicate::Op op = (PropertyPredicate::Op)p_pp.op();
if (op == PropertyPredicate::DontCare)
return PropertyPredicate(key);
if (op < PropertyPredicate::GeLe)
return PropertyPredicate(key, op, construct_search_property(p_pp.v1()));
return PropertyPredicate(key, op, construct_search_property(p_pp.v1()),
construct_search_property(p_pp.v2()));
}
Property PMGDQueryHandler::construct_search_property(const PMGDProp &p) {
switch (p.type()) {
case PMGDProp::BooleanType:
return Property(p.bool_value());
case PMGDProp::IntegerType:
return Property((long long)p.int_value());
case PMGDProp::StringType:
return Property(p.string_value());
case PMGDProp::FloatType:
return Property(p.float_value());
case PMGDProp::TimeType: {
struct tm tm_e;
int hr, min;
unsigned long usec;
string_to_tm(p.time_value(), &tm_e, &usec, &hr, &min);
Time t_e(&tm_e, usec, hr, min); // time diff
return Property(t_e);
}
case PMGDProp::BlobType:
// We throw here to avoid extra work when going through
// multiple levels of calls.
throw PMGDException(PropertyTypeInvalid,
"Search on blob property not permitted");
}
return 0;
}
namespace VDMS {
template void PMGDQueryHandler::build_results<PMGD::NodeIterator>(
PMGD::NodeIterator &ni, const protobufs::ResultInfo &qn,
PMGDCmdResponse *response);
template void
PMGDQueryHandler::build_results<PMGDQueryHandler::ReusableNodeIterator>(
PMGDQueryHandler::ReusableNodeIterator &ni, const protobufs::ResultInfo &qn,
PMGDCmdResponse *response);
template void PMGDQueryHandler::build_results<PMGD::EdgeIterator>(
PMGD::EdgeIterator &ni, const protobufs::ResultInfo &qn,
PMGDCmdResponse *response);
}; // namespace VDMS
template <class Iterator>
void PMGDQueryHandler::build_results(Iterator &ni,
const protobufs::ResultInfo &qn,
PMGDCmdResponse *response) {
bool avg = false;
size_t limit =
qn.limit() > 0 ? qn.limit() : std::numeric_limits<size_t>::max();
size_t count = 0;
switch (qn.r_type()) {
case protobufs::List: {
std::vector<StringID> keyids;
for (int i = 0; i < qn.response_keys_size(); ++i)
keyids.push_back(StringID(qn.response_keys(i).c_str()));
auto &rmap = *(response->mutable_prop_values());
for (; ni; ni.next()) {
for (int i = 0; i < keyids.size(); ++i) {
Property j_p;
PMGDPropList &list = rmap[qn.response_keys(i)];
PMGDProp *p_p = list.add_values();
if (!ni->check_property(keyids[i], j_p)) {
construct_missing_property(p_p);
continue;
}
construct_protobuf_property(j_p, p_p);
}
if (_resultdeletion &&
!(ni->get_tag() ==
VDMS_DESC_SET_TAG)) // DescriptorSets should be ignored - they are
// returned with Descriptors
{
delete_by_value((&_expiration_timestamp_queue), (void *)(&(*ni)));
Property img_prop;
if (ni->check_property(VDMS_IM_PATH_PROP,
img_prop)) // delete image if present
{
_cleanup_filename_list.push_back(img_prop.string_value());
}
Property vid_prop;
if (ni->check_property(VDMS_VID_PATH_PROP,
vid_prop)) // delete image if present
{
_cleanup_filename_list.push_back(vid_prop.string_value());
}
Property blob_prop;
if (ni->check_property(VDMS_EN_BLOB_PATH_PROP,
blob_prop)) // delete image if present
{
_cleanup_filename_list.push_back(blob_prop.string_value());
}
_db->remove(*ni);
}
if (_autodelete_init) {
uint64_t tmp_timestamp =
(uint64_t)ni->get_property("_expiration").int_value();
AutoDeleteNode *tmpNode =
new AutoDeleteNode(Json::UInt64(tmp_timestamp), &(*ni));
insert_into_queue(&_expiration_timestamp_queue, tmpNode);
}
count++;
if (count >= limit)
break;
}
response->set_op_int_value(count);
break;
}
case protobufs::Count: {
for (; ni; ni.next())
count++;
response->set_op_int_value(count);
break;
}
// Next two assume that the property requested is either Int or Float.
// Also, only looks at the first property specified.
case protobufs::Average:
avg = true;
case protobufs::Sum: {
// Since the iterator can be null if no _ref is used, make sure
// it has elements before proceeding, else return.
if (!bool(ni)) {
if (avg)
response->set_op_float_value(0.0);
else
response->set_op_int_value(0);
break;
}
// We currently only use the first property key even if multiple
// are provided. And we can assume that the syntax checker makes
// sure of getting one for sure.
StringID keyid(qn.response_keys(0).c_str());
if (ni->get_property(keyid).type() == PropertyType::Integer) {
size_t sum = 0;
for (; ni; ni.next()) {
sum += ni->get_property(keyid).int_value();
count++;
if (count >= limit)
break;
}
if (avg)
response->set_op_float_value((double)sum / count);
else
response->set_op_int_value(sum);
} else if (ni->get_property(keyid).type() == PropertyType::Float) {
double sum = 0.0;
for (; ni; ni.next()) {
sum += ni->get_property(keyid).float_value();
count++;
if (count >= limit)
break;
}
if (avg)
response->set_op_float_value(sum / count);
else
response->set_op_float_value(sum);
} else {
set_response(response, PMGDCmdResponse::Error,
"Wrong first property for sum/average");
}
break;
}
case protobufs::NodeID: {
// Makes sense only when unique was used. Otherwise it sets the
// int value to the global id of the last node in the iterator.
for (; ni; ni.next())
response->set_op_int_value(ni->get_id());
break;
}
default:
set_response(response, PMGDCmdResponse::Error,
"Unknown operation type for query");
}
}
void PMGDQueryHandler::construct_protobuf_property(const Property &j_p,
PMGDProp *p_p) {
// Assumes matching enum values!
p_p->set_type((PMGDProp::PropertyType)j_p.type());
switch (j_p.type()) {
case PropertyType::Boolean:
p_p->set_bool_value(j_p.bool_value());
break;
case PropertyType::Integer:
p_p->set_int_value(j_p.int_value());
break;
case PropertyType::String:
p_p->set_string_value(j_p.string_value());
break;
case PropertyType::Float:
p_p->set_float_value(j_p.float_value());
break;
case PropertyType::Time:
p_p->set_time_value(time_to_string(j_p.time_value()));
break;
case PropertyType::Blob:
p_p->set_blob_value(j_p.blob_value().value, j_p.blob_value().size);
}
}
void PMGDQueryHandler::construct_missing_property(PMGDProp *p_p) {
// Assumes matching enum values!
p_p->set_type(PMGDProp::StringType);
p_p->set_string_value("Missing property");
}
int PMGDQueryHandler::delete_expired_nodes() {
AutoDeleteNode *tmp_node;
Json::UInt64 current_timestamp =
std::chrono::time_point_cast<std::chrono::seconds>(
std::chrono::system_clock::now())
.time_since_epoch()
.count();
Json::UInt64 this_timestamp = 0;
// Continue to loop until queue is empty or we find timestamp greater than
// current time
while (this_timestamp < current_timestamp &&
!_expiration_timestamp_queue.empty()) {
tmp_node = _expiration_timestamp_queue.front();
this_timestamp = tmp_node->GetExpirationTimestamp();
if (this_timestamp < current_timestamp) {
Property img_prop;
PMGD::Node *tmp_node_node = (PMGD::Node *)tmp_node->GetNode();
if (tmp_node_node->check_property(VDMS_IM_PATH_PROP,
img_prop)) // delete image if present
{
remove(img_prop.string_value().c_str());
}
Property vid_prop;
if (tmp_node_node->check_property(VDMS_VID_PATH_PROP,
vid_prop)) // delete image if present
{
remove(vid_prop.string_value().c_str());
}
Property blob_prop;
if (tmp_node_node->check_property(VDMS_EN_BLOB_PATH_PROP,
blob_prop)) // delete image if present
{
remove(blob_prop.string_value().c_str());
}
_db->remove(*(
(PMGD::Node *)(tmp_node
->GetNode()))); // can assume Node since expiration
// only implemented for nodes
_expiration_timestamp_queue.pop_front();
if (!_expiration_timestamp_queue.empty()) {
tmp_node = _expiration_timestamp_queue.front();
this_timestamp = tmp_node->GetExpirationTimestamp();
}
}
}
return 0;
}
void PMGDQueryHandler::cleanup_files() {
cleanup_pmgd_files(&_cleanup_filename_list);
}
void insert_into_queue(std::list<AutoDeleteNode *> *queue,
AutoDeleteNode *new_element) {
bool insert_flag;
long new_timestamp = new_element->GetExpirationTimestamp();
if (queue->empty()) {
queue->push_front(new_element);
} else {
// We assume new entries will have a higher timestamp so start at back of