-
Notifications
You must be signed in to change notification settings - Fork 1
/
pyWrapper.cpp
769 lines (678 loc) · 25.3 KB
/
pyWrapper.cpp
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
#include "pyWrapper.h"
#include <dlfcn.h>
//namespace py = pybind11;
//using namespace std::chrono_literals;
const char *wrapperFileKey = "wrapper.file";
const char *wrapperFileClass = "wrapper.class";
const char *WrapperFile = "wrapper";
const char *WrapperClass = "Wrapper";
const char *PythonSo = "libpython3.so";
wrapperMeterCustom g_metric_cb;
wrapperTraceLog g_trace_cb;
wrapperCallback g_resp_cb;
std::mutex RECORD_MUTEX;
std::map <std::string, std::string> SID_RECORD;
std::map <std::string, wrapperCallback> SID_CB;
std::map<std::string, const char *> SID_USRTAG;
PYBIND11_EMBEDDED_MODULE(aiges_embed, module) {
module.def("callback_metric", &callbackMetric, py::return_value_policy::automatic_reference);
module.def("callback_trace", &callbackTrace, py::return_value_policy::automatic_reference);
module.def("callback", &callBack, py::return_value_policy::automatic_reference);
py::class_<ResponseData> responseData(module, "ResponseData");
responseData.def(py::init<>())
.def(py::init<std::string, unsigned int, int, int>())
.def("setDataType",
[](ResponseData &r, int i) {
r.type = i;
})
.def("setData", [](ResponseData &r, const py::bytes &b) {
r.data = b;
Py_ssize_t size = PyBytes_GET_SIZE(b.ptr());
r.len = size;
})
.def_readwrite("key", &ResponseData::key, py::return_value_policy::automatic_reference)
.def_readwrite("data", &ResponseData::data, py::return_value_policy::automatic_reference)
.def_readwrite("status", &ResponseData::status, py::return_value_policy::automatic_reference)
.def_readwrite("len", &ResponseData::len, py::return_value_policy::automatic_reference)
.def_readwrite("type", &ResponseData::type, py::return_value_policy::automatic_reference);
py::class_<Response> response(module, "Response");
response.def(py::init<>())
.def_readwrite("list", &Response::list, py::return_value_policy::automatic_reference)
.def_readwrite("error_code", &Response::errCode, py::return_value_policy::automatic_reference)
.def("response_err", &Response::responseErr, py::return_value_policy::automatic_reference);
py::class_<DataListNode> dataListNode(module, "DataListNode");
dataListNode.def(py::init<>())
.def_readwrite("key", &DataListNode::key, py::return_value_policy::automatic_reference)
.def_readwrite("data", &DataListNode::data, py::return_value_policy::automatic_reference)
.def_readwrite("len", &DataListNode::len, py::return_value_policy::automatic_reference)
.def_readwrite("status", &DataListNode::status, py::return_value_policy::automatic_reference)
.def_readwrite("type", &DataListNode::type, py::return_value_policy::automatic_reference)
.def("get_data", &DataListNode::get_data, py::return_value_policy::reference);
py::class_<DataListCls> dataListCls(module, "DataListCls");
dataListCls.def(py::init<>())
.def_readwrite("list", &DataListCls::list, py::return_value_policy::automatic_reference)
.def("get", &DataListCls::get, py::return_value_policy::reference);
py::class_<SessionCreateResponse> sessionCreateResponse(module, "SessionCreateResponse");
sessionCreateResponse.def(py::init<>())
.def_readwrite("handle", &SessionCreateResponse::handle, py::return_value_policy::automatic_reference)
.def_readwrite("error_code", &SessionCreateResponse::errCode, py::return_value_policy::reference);
}
/**
* 默认Response构造函数
*/
Response::Response() {
this->errCode = 0;
}
/**
* 默认Response构造函数, 带错误码
*/
Response::Response(int err) {
this->errCode = err;
}
std::unique_ptr <Response> Response::responseErr(int errCode) {
Response *resp = new Response(errCode);
resp->errCode = errCode;
return std::unique_ptr<Response>(resp);
}
py::bytes DataListNode::get_data() {
return data;
}
DataListNode *DataListCls::get(std::string key) {
for (size_t idx = 0; idx < list.size(); idx++) {
DataListNode *node = &list[idx];
if (strcmp(node->key.c_str(), key.c_str()) == 0) {
return node;
}
}
return nullptr;
}
PyWrapper::PyWrapper() {
// 仅仅为了 加载下python lib库使 其部分函数可被导出使用
// https://stackoverflow.com/questions/67891197/ctypes-cpython-39-x86-64-linux-gnu-so-undefined-symbol-pyfloat-type-in-embedd
dlopen(PythonSo, RTLD_GLOBAL | RTLD_NOW);
// if (config.count(wrapperFileKey) == 0)
py::gil_scoped_acquire acquire;
_wrapper = py::module::import(WrapperFile);
_obj = _wrapper.attr(WrapperClass)();
_wrapper_abs = _wrapper.attr("__file__").cast<std::string>(); // 获取加载的wrapper.py的绝对地址
_wrapperInit = _obj.attr("wrapperInit");
_wrapperFini = _obj.attr("wrapperFini");
_wrapperOnceExec = _obj.attr("wrapperOnceExec");
_wrapperOnceExecAsync = _obj.attr("wrapperOnceExecAsync");
_wrapperError = _obj.attr("wrapperError");
// 个性化
_wrapperLoadRes = _obj.attr("wrapperLoadRes");
_wrapperUnloadRes = _obj.attr("wrapperUnloadRes");
// stream support
_wrapperCreate = _obj.attr("wrapperCreate");
_wrapperWrite = _obj.attr("wrapperWrite");
_wrapperRead = _obj.attr("wrapperRead");
_wrapperDestroy = _obj.attr("wrapperDestroy");
_wrapperTest = _obj.attr("wrapperTestFunc");
py::gil_scoped_release release;
// StartMonitorWrapperClass(_wrapper_abs);
}
//PyWrapper::PyWrapper(std::map <std::string, std::string> config) {
// // if (config.count(wrapperFileKey) == 0)
// // 带config初始化,暂未实现 todo
// py::gil_scoped_acquire acquire;
// _obj = py::module::import(WrapperFile).attr(WrapperClass)();
//
// _wrapperInit = _obj.attr("wrapperInit");
// _wrapperFini = _obj.attr("wrapperFini");
// _wrapperOnceExec = _obj.attr("wrapperOnceExec");
// _wrapperError = _obj.attr("wrapperError");
// _wrapperTest = _obj.attr("wrapperTestFunc");
//
//}
PyWrapper::~PyWrapper() {
_wrapperError.release();
_wrapperInit.release();
_wrapperFini.release();
_wrapperOnceExec.release();
_wrapperTest.release();
_wrapperCreate.release();
_wrapperWrite.release();
_wrapperRead.release();
_wrapperUnloadRes.release();
_wrapperLoadRes.release();
pybind11::gil_scoped_release release;
}
void PyWrapper::ReloadWrapper() {
// 保存原有实例
// todo 需要吗?
// 重新import wrapper.py
py::gil_scoped_acquire acquire;
_wrapper.reload();
_obj = _wrapper.attr(WrapperClass)();
_wrapperInit = _obj.attr("wrapperInit");
_wrapperFini = _obj.attr("wrapperFini");
_wrapperOnceExec = _obj.attr("wrapperOnceExec");
_wrapperError = _obj.attr("wrapperError");
_wrapperTest = _obj.attr("wrapperTestFunc");
// stream support
_wrapperCreate = _obj.attr("wrapperCreate");
_wrapperWrite = _obj.attr("wrapperWrite");
_wrapperRead = _obj.attr("wrapperRead");
_wrapperLoadRes = _obj.attr("wrapperLoadRes");
_wrapperUnloadRes = _obj.attr("wrapperUnloadRes");
pybind11::gil_scoped_release release;
}
void reloadWrapper(const std::string event_file, void *flags) {
if (flags == nullptr) {
return; //什么都不做
}
printf("reloading...wrapper\n");
PyWrapper *w = (PyWrapper *) flags;
w->ReloadWrapper();
printf("reloaded...wrapper Done!\n");
return;
}
void PyWrapper::StartMonitorWrapperClass(std::string wrapperFileAbs) {
FSInotify *ino = new FSInotify();
pthread_t _pid;
std::vector <std::string> s;
printf("starting monitoring %s, pid is: %lu\n", wrapperFileAbs.c_str(), _pid);
s.push_back(wrapperFileAbs);
std::map <std::string, EventHandle> funs;
/** 变化后,重载wrapper **/
funs.insert({"IN_MOVE_SELF", reloadWrapper});
ino->InitWatchFile(s, this);
int ret = ino->StartWatchThread(funs, _pid);
if (ret != 0) {
printf("Error starting monitoring %s, pid is: %lu\n", wrapperFileAbs.c_str(), _pid);
}
}
int PyWrapper::wrapperInit(std::map <std::string, std::string> config) {
try {
py::gil_scoped_acquire acquire;
int ret = _wrapperInit(config).cast<int>();
py::gil_scoped_release release;
return ret;
}
catch (py::cast_error &e) {
spdlog::get("stderr_console")->error("_wrapperInit cast error: {}", e.what());
return -1;
}
catch (py::error_already_set &e) {
spdlog::get("stderr_console")->error("_wrapperInit error_already_set error: {}", e.what());
return -1;
}
}
int PyWrapper::wrapperFini() {
try {
py::gil_scoped_acquire acquire;
return _wrapperFini().cast<int>();
}
catch (py::cast_error &e) {
spdlog::get("stderr_console")->error("Fini cast error: {}", e.what());
return -1;
}
catch (py::error_already_set &e) {
spdlog::get("stderr_console")->error("Fini error_already_set error: {}", e.what());
return -1;
}
}
int PyWrapper::wrapperOnceExec(const char *usrTag, std::map <std::string, std::string> params, DataListCls reqData,
pDataList *respData, std::string sid, wrapperCallback cb, unsigned int psrId) {
// SetSidUsrTag(sid, usrTag);
try {
if (cb != nullptr) {
SetSidCallBack(cb, sid);
}
params["sid"] = sid;
// 执行python exec 推理
py::object r = _wrapperOnceExec(params, reqData, usrTag, psrId);
// 此段根据python的返回 ,回写 respData
Response *resp;
spdlog::debug("start cast python resp to c++ object, thread_id: {}, sid: {}", gettid(), sid);
resp = r.cast<Response *>();
pDataList headPtr;
pDataList curPtr;
char *ptr;
// 先判断python有没有抛出错误. response中的 errorCode
if (resp->errCode != 0) {
spdlog::error("find error from python: {}", resp->errCode);
DelSidUsrTag(sid);
return resp->errCode;
}
int dataSize = resp->list.size();
if (dataSize == 0) {
spdlog::error("error, not find any data from resp");
DelSidUsrTag(sid);
return -1;
}
for (int idx = 0; idx < dataSize; idx++) {
pDataList tmpData = new (DataList);
tmpData->next = nullptr;
ResponseData itemData = resp->list[idx];
char *key = strdup(itemData.key.c_str());
tmpData->key = key;
tmpData->len = itemData.len;
tmpData->type = DataType(itemData.type);
tmpData->desc = nullptr;
// 这里判断数据类型,todo 未来根据数据类型 决定是否拷贝,比如某些数据比较大,可以不拷贝
void *pr;
pr = malloc(itemData.len);
if (pr == nullptr) {
int ret = -1;
spdlog::error("can't malloc memory for data, sid:{}", sid);
DelSidUsrTag(sid);
return ret;
}
ptr = PyBytes_AsString(itemData.data.ptr());
// Py_ssize_t size = PyBytes_GET_SIZE(itemData.data.ptr());
// printf("GetSIze, %d", size);
// printf("item data len: %d", itemData.len);
memcpy(pr, ptr, itemData.len);
//char *data_ = new char[itemData.data.length()+1];
// strdup(.c_str());
tmpData->data = pr;
//tmpData->status = DataStatus(itemData.status);
tmpData->status = DataOnce;
if (idx == 0) {
headPtr = tmpData;
curPtr = tmpData;
} else {
curPtr->next = tmpData;
curPtr = tmpData;
}
spdlog::debug("get result,key:{},data:{},len:{},type:{},status:{},sid:{}",
tmpData->key, (char *) tmpData->data, tmpData->len, tmpData->type,
tmpData->status, sid);
}
*respData = headPtr;
}
catch (py::cast_error &e) {
spdlog::error("cast error: {}", e.what());
DelSidUsrTag(sid);
return -1;
}
catch (py::error_already_set &e) {
spdlog::error("error_already_set error: {}", e.what());
DelSidUsrTag(sid);
return -1;
}
catch (const std::exception &e) {
spdlog::error("error_already_set error: {}", e.what());
DelSidUsrTag(sid);
return -1;
}
DelSidUsrTag(sid);
return 0;
}
int PyWrapper::wrapperOnceExecAsync(const char *usrTag, std::map <std::string, std::string> params, DataListCls reqData,
std::string sid, wrapperCallback cb, unsigned int psrId) {
try {
if (cb != nullptr) {
SetSidCallBack(cb, sid);
}
int ret = 0;
params["sid"] = sid;
// 执行python exec 推理
py::object r = _wrapperOnceExecAsync(params, reqData, usrTag, psrId);
// 此段根据python的返回 ,回写 respData
spdlog::info("start wrapperExecAsync cast python resp to c++ object, thread_id: {}, sid: {}", gettid(), sid);
ret = r.cast<int>();
return ret;
}
catch (py::cast_error &e) {
spdlog::get("stderr_console")->error("cast error: {}", e.what());
return -1;
}
catch (py::error_already_set &e) {
spdlog::get("stderr_console")->error("error_already_set error: {}", e.what());
return -1;
}
return 0;
}
std::string PyWrapper::wrapperError(int err) {
try {
py::gil_scoped_acquire acquire;
return _wrapperError(err).cast<std::string>();
}
catch (py::cast_error &e) {
spdlog::error("cast error: {}", e.what());
return e.what();
}
catch (py::error_already_set &e) {
spdlog::error("error_already_set error: {}", e.what());
return e.what();
}
}
int PyWrapper::wrapperSetMetricFunc(CtrlType type, wrapperMeterCustom mc) {
if (type == CTMeterCustom) {
g_metric_cb = mc;
}
return 0;
}
int PyWrapper::wrapperSetTraceFunc(CtrlType type, wrapperTraceLog mc) {
if (type == CTTraceLog) {
g_trace_cb = mc;
}
return 0;
}
std::string
PyWrapper::wrapperCreate(const char *usrTag, std::map <std::string, std::string> params, wrapperCallback cb,
int *errNum, std::string sid, unsigned int psrId) {
SessionCreateResponse *resp;
SetSidCallBack(cb, sid);
try {
py::gil_scoped_acquire acquire;
// 此段根据python的返回 ,回写 respData
py::object r = _wrapperCreate(params, sid, psrId, usrTag);
resp = r.cast<SessionCreateResponse *>();
*errNum = resp->errCode;
if (*errNum != 0) {
spdlog::get("stderr_console")->error("errNum: {}", *errNum);
}
return resp->handle;
}
catch (py::cast_error &e) {
spdlog::get("stderr_console")->error("cast error: {}", e.what());
return e.what();
}
catch (py::error_already_set &e) {
spdlog::get("stderr_console")->error("error_already_set error: {}", e.what());
return e.what();
}
}
// 上行数据
int PyWrapper::wrapperWrite(char *handle, DataListCls reqData) {
try {
int ret = 0;
// 执行python exec 推理
py::object r = _wrapperWrite(handle, reqData);
ret = r.cast<int>();
return ret;
}
catch (py::cast_error &e) {
spdlog::get("stderr_console")->error("cast error: {}", e.what());
return -1;
}
catch (py::error_already_set &e) {
spdlog::get("stderr_console")->error("error_already_set error: {}", e.what());
return -1;
}
}
// 下行数据
int PyWrapper::wrapperRead(char *handle, pDataList *respData) {
try {
Response *resp;
// 执行python exec 推理
py::object r = _wrapperRead(handle);
spdlog::debug("start cast python resp to c++ object, thread_id: {}, handle: {}", gettid(), handle);
resp = r.cast<Response *>();
pDataList headPtr;
pDataList curPtr;
// 先判断python有没有抛出错误. response中的 errorCode
if (resp->errCode != 0) {
spdlog::get("stderr_console")->error("find error from python: {}", resp->errCode);
return resp->errCode;
}
int dataSize = resp->list.size();
if (dataSize == 0) {
spdlog::get("stderr_console")->error("error, not find any data from resp");
return -1;
}
for (int idx = 0; idx < dataSize; idx++) {
pDataList tmpData = new (DataList);
tmpData->next = nullptr;
ResponseData itemData = resp->list[idx];
char *key = strdup(itemData.key.c_str());
tmpData->key = key;
tmpData->len = itemData.len;
tmpData->type = DataType(itemData.type);
tmpData->desc = nullptr;
// 这里判断数据类型,todo 未来根据数据类型 决定是否拷贝,比如某些数据比较大,可以不拷贝
void *pr;
pr = malloc(itemData.len);
if (pr == nullptr) {
int ret = -1;
spdlog::get("stderr_console")->error("can't malloc memory for data, handle:{}", handle);
return ret;
}
memcpy(pr, (const void *) itemData.data.ptr(), itemData.len);
//char *data_ = new char[itemData.data.length()+1];
// strdup(.c_str());
tmpData->data = pr;
tmpData->status = DataStatus(itemData.status);
if (idx == 0) {
headPtr = tmpData;
curPtr = tmpData;
} else {
curPtr->next = tmpData;
curPtr = tmpData;
}
spdlog::debug("get result,key:{},data:{},len:{},type:{},status:{},handle:{}",
tmpData->key, (char *) tmpData->data, tmpData->len, tmpData->type,
tmpData->status, handle);
}
*respData = headPtr;
}
catch (py::cast_error &e) {
spdlog::get("stderr_console")->error("cast error: {}", e.what());
return -1;
}
catch (py::error_already_set &e) {
spdlog::get("stderr_console")->error("error_already_set error: {}", e.what());
return -1;
}
return 0;
}
int PyWrapper::wrapperDestroy(char * handle) {
py::object r = _wrapperDestroy(handle);
// 此段根据python的返回 ,回写 respData
spdlog::info("Destroy .. thread_id: {}, handle: {}", gettid(), handle);
int ret = r.cast<int>();
return ret;
}
int PyWrapper::wrapperExecFree(const char *usrTag) {
return 0;
}
int PyWrapper::wrapperLoadRes(pDataList p, std::string patch_id) {
DataListCls perData;
//构建请求数据
int dataNum = 0;
for (pDataList tmpDataPtr = p; tmpDataPtr != NULL; tmpDataPtr = tmpDataPtr->next) {
dataNum++;
}
if (dataNum > 0) {
for (int tmpIdx = 0; tmpIdx < dataNum; tmpIdx++) {
DataListNode item;
item.key = p->key;
// 直接拷贝
size_t len = static_cast<size_t>(p->len);
item.data = py::bytes((char *) (p->data), len);
item.len = p->len;
// char t = static_cast<int>(p->type);
item.type = p->type;
item.status = p->status;
spdlog::debug("reqDatatype :{},patch_id:{}", p->type, patch_id);
perData.list.push_back(item);
p = p->next;
}
}
py::gil_scoped_acquire acquire;
// 执行python exec 推理
int ret = _wrapperLoadRes(perData, patch_id).cast<int>();;
return ret;
}
int PyWrapper::wrapperUnloadRes(std::string patch_id) {
py::gil_scoped_acquire acquire;
// 执行python exec 推理
int ret = _wrapperUnloadRes(patch_id).cast<int>();;
return ret;
}
int PyWrapper::wrapperTest() {
py::gil_scoped_acquire acquire;
std::vector <py::dict> req;
py::dict item;
item["key"] = "33";
item["data"] = "ccccc";
item["len"] = 11;
item["type"] = 22;
req.push_back(item);
std::vector <py::object> resp;
resp.push_back(py::str("cfc"));
py::object ret = _wrapperTest(req, resp);
Response *l;
try {
l = ret.cast<Response *>();
// py::object r = _wrapperOnceExec(params, reqData);
}
catch (py::cast_error &e) {
std::cout << e.what() << std::endl;
return -1;
}
for (size_t i = 0; i < l->list.size(); ++i) {
ResponseData d = l->list[i];
// std::cout << "Response len" << d.len << std::endl;
// std::cout << "response actual data Size " << d.data.length() << std::endl;
}
return 0;
// auto message = ret.cast<std::vector<std::string>>();
// printf("%s,:", message[0].c_str());
// printf("%s,:", message[1].c_str());
// printf("resp len%d\n",resp.size());
// printf("%d", ret);
}
int callbackMetric(const char *usrTag, const char *meterKey, int count) {
printf("callback Metric: %s, %s, %d\n", usrTag, meterKey, count);
return g_metric_cb(usrTag, meterKey, count);
}
int callbackTrace(const char *usrTag, const char *key, const char *value) {
printf("callback Trace: %s, %s, %s\n", usrTag, key, value);
return g_trace_cb(usrTag, key, value);
}
int callBack(Response *resp, char *usrTag) {
wrapperCallback cb_;
cb_ = g_resp_cb;
if (cb_ == NULL) {
printf("null cb....\n");
return -1;
}
int ret;
pDataList headPtr = nullptr;
pDataList curPtr = nullptr;
// 先判断python有没有抛出错误. response中的 errorCode
if (resp->errCode != 0) {
spdlog::get("stderr_console")->error("find error from python: {}", resp->errCode);
ret = cb_(usrTag, NULL,resp->errCode);
return ret;
}
char *ptr;
int dataSize = resp->list.size();
if (dataSize == 0) {
spdlog::get("stderr_console")->error("error, not find any data from resp");
return -1;
}
for (int idx = 0; idx < dataSize; idx++) {
pDataList tmpData = new (DataList);
tmpData->next = nullptr;
ResponseData itemData = resp->list[idx];
char *key = strdup(itemData.key.c_str());
tmpData->key = key;
tmpData->len = itemData.len;
tmpData->type = DataType(itemData.type);
tmpData->desc = nullptr;
// 这里判断数据类型,todo 未来根据数据类型 决定是否拷贝,比如某些数据比较大,可以不拷贝
void *pr;
pr = malloc(itemData.len);
if (pr == nullptr) {
int ret = -1;
spdlog::get("stderr_console")->error("can't malloc memory for data, usrTag:{}", usrTag);
return ret;
}
ptr = PyBytes_AsString(itemData.data.ptr());
Py_ssize_t size = PyBytes_GET_SIZE(itemData.data.ptr());
memcpy(pr, ptr, itemData.len);
// 还是有问题::memcpy(pr, (const void *) itemData.data.ptr(), itemData.len);
//char *data_ = new char[itemData.data.length()+1];
// strdup(.c_str());
tmpData->data = pr;
tmpData->status = DataStatus(itemData.status);
if (idx == 0) {
headPtr = tmpData;
curPtr = tmpData;
} else {
curPtr->next = tmpData;
curPtr = tmpData;
}
spdlog::debug("callback result,key:{},data:{},len:{},type:{},status:{},usrTag:{}",
tmpData->key, (char *) tmpData->data, tmpData->len, tmpData->type,
tmpData->status, usrTag);
}
int cb_ret = cb_(usrTag, headPtr, 0);
while (headPtr != nullptr) {
pDataList ptr = headPtr;
headPtr = headPtr->next;
if (ptr->key) {
free(ptr->key);
}
if (ptr->data) {
free(ptr->data);
}
delete ptr;
}
spdlog::debug("call c's callback, usrTag:{} ret {}",usrTag, cb_ret);
return 0;
}
void SetSidCallBack(wrapperCallback cb, std::string sid) {
g_resp_cb = cb;
}
wrapperCallback GetSidCB(std::string sid) {
// ugly
return g_resp_cb;
}
void SetSidUsrTag(std::string sid, const char *usrTag) {
RECORD_MUTEX.lock();
SID_USRTAG[sid] = usrTag;
RECORD_MUTEX.unlock();
}
const char *GetSidUsrTag(std::string sid) {
const char *usrTag;
RECORD_MUTEX.lock();
usrTag = SID_USRTAG[sid];
RECORD_MUTEX.unlock();
return usrTag;
}
const std::string GetSidByUsrTag(const char *usrTag) {
RECORD_MUTEX.lock();
//通过value找 key
for (std::map<std::string, const char *>::iterator it = SID_USRTAG.begin(); it != SID_USRTAG.end(); it++) {
if (it->second == usrTag) {
RECORD_MUTEX.unlock();
return it->first;
}
}
RECORD_MUTEX.unlock();
return "";
}
void SetHandleSid(char *handle, std::string sid) {
RECORD_MUTEX.lock();
SID_RECORD[std::string(handle)] = sid;
RECORD_MUTEX.unlock();
}
std::string GetHandleSid(char *handle) {
std::string rlt;
RECORD_MUTEX.lock();
rlt = SID_RECORD[std::string(handle)];
RECORD_MUTEX.unlock();
return rlt;
}
//暂时没用上
void DelHandleSid(char *handle) {
RECORD_MUTEX.lock();
RECORD_MUTEX.unlock();
}
void DelSidCallback(std::string sid) {
RECORD_MUTEX.lock();
SID_CB.erase(sid);
RECORD_MUTEX.unlock();
}
void DelSidUsrTag(std::string sid) {
RECORD_MUTEX.lock();
SID_USRTAG.erase(sid);
RECORD_MUTEX.unlock();
}