-
Notifications
You must be signed in to change notification settings - Fork 0
/
twowaystream.cpp
379 lines (364 loc) · 14.3 KB
/
twowaystream.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
/* Copyright (C) 2009 Frederik M.J.V
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* LGPL is available on the internet at
* http://www.gnu.org/licenses/lgpl-2.1.html and from Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "twowaystream.h"
#include "Message.pb.h"
#include "prototools.h"
#include <google/protobuf/message.h>
#include <google/protobuf/service.h>
#include <google/protobuf/descriptor.h>
#include "callentry.h"
#include <string.h>
#include "streamcallbackinfo.h"
#include "simplerpccontroller.h"
#include "twowayrpccontroller.h"
#include "twowaystream.moc"
namespace protorpc{
using namespace google::protobuf;
TwoWayStream::TwoWayStream(QIODevice *dev,google::protobuf::Service* srv,bool autostart,Closure *shutdownClosure)
{
timeout=10000;
spawnCallers=false;
callnum=0;
shutdownCallback=NULL;
this->idev=dev;
this->odev=dev;
this->service=srv;
this->shutdownCallback=shutdownClosure;
connected=false;
streamlock=new QMutex(QMutex::Recursive);
if(autostart)
start();
}
TwoWayStream::~TwoWayStream(){
delete idev;
delete streamlock;
}
void TwoWayStream::start(){
if(!connected){
connected=true;
stopped=false;
((QThread*) this)->start();
}
}
//void TwoWayStream::callMethod(const MethodDescriptor * method, google::protobuf::RpcController * controller, const google::protobuf::Message * request, google::protobuf::Message * response, Closure * done){
void TwoWayStream::CallMethod(const google::protobuf::MethodDescriptor* method, google::protobuf::RpcController* controller, const google::protobuf::Message* request, google::protobuf::Message* response, google::protobuf::Closure* done){
if(spawnCallers){
//Class<?> paramTypes[]={MethodDescriptor.class,RpcController.class,google::protobuf::Message.class,google::protobuf::Message.class,RpcCallback.class};
/* Object params[]={method,controller,request,responsePrototype,done};
try {
ThreadTools.invokeInSeparateThread(getClass().getMethod("callMethodThreaded", paramTypes), this,params);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}else{
callMethodThreaded(method, controller, request, response, done);
}
}
bool TwoWayStream::cancelMethodCall(google::protobuf::Message* response){
QMutexLocker mtxlck(streamlock);
uint32_t mk=0;
bool found=false;
QHashIterator<uint32_t, CallEntry> i(currentCalls);
while (i.hasNext()) {
i.next();
if(i.value().resp==response){
mk=i.key();
found=true;
break;
}
}
if(found)
currentCalls.remove(mk);
return found;
}
void TwoWayStream::callMethodThreaded(const MethodDescriptor * method, google::protobuf::RpcController * controller, const google::protobuf::Message * request, google::protobuf::Message * response, Closure * done) {
QMutexLocker mtxlck(streamlock);
try {
protorpc::Message reqbld;
//MessageProto.Message.Builder reqbld = google::protobuf::MessageProto.Message.newBuilder();
reqbld.set_type(protorpc::REQUEST);
reqbld.set_id(callnum);
reqbld.set_name(method->name());
reqbld.set_buffer(request->SerializeAsString());
writeMessage(&reqbld);
currentCalls.insert(callnum,CallEntry(controller,done,response));
callnum++;
} catch (int e) {
controller->SetFailed("IOError");
}
}
void TwoWayStream::writeMessage(google::protobuf::Message* m){
char sizebuf[4];
uint32_t bs=m->ByteSize();
sizebuf[0]=bs&0xFF000000;
sizebuf[1]=bs&0x00FF0000;
sizebuf[2]=bs&0x0000FF00;
sizebuf[3]=bs&0x000000FF;
if(odev->write(sizebuf,4)<0){
throw odev->errorString().toUtf8().constData();
}
if(odev->write(serializeToByteArray(m))<0)
throw -1;
odev->waitForBytesWritten(10);
// printf("Wrote\n");
}
void TwoWayStream::requestServiceDescriptor(google::protobuf::Closure *cb,google::protobuf::RpcController *ctrl){
QMutexLocker mtxlck(streamlock);
ctrl->SetFailed("Not supported yet");
return;
}
/**Read a Message of type from the device*/
google::protobuf::Message *TwoWayStream::fillMessage(google::protobuf::Message *type){
char bs[4];
uint32_t msglen;
QMutexLocker dl(&devlock);
streamlock->lock();
if(!connected||!idev->isOpen()){
delete(type);
streamlock->unlock();
return NULL;
}
streamlock->unlock();
idev->waitForReadyRead(250);
if(idev->bytesAvailable()<1){
msleep(10);
delete(type);
return NULL;
}
//printf("Waitmsg\n");
uint32_t red=idev->read(bs,4);
//printf("Red%d,%s\n",red,idev->errorString().toUtf8().data());
if(red<4){
delete(type);
return NULL;
}
//msglen=(bs[0]<<24)|(bs[1]<<16)|(bs[2]<<8)|(bs[3]<<24);
msglen=(bs[0]<<24)|(bs[1]<<16)|(bs[2]<<8)|(bs[3]);
if(bs[0]!=0){
printf("Most likely got out of sync");
}
//printf("Gotmsg%d, %d\n",red,msglen);
if(msglen<=0){
delete(type);
return NULL;
}
uint32_t vld=0;
QByteArray msgbuf =idev->read(msglen);
if(msgbuf.length()< msglen){
printf("Extread%d<%d\n",msgbuf.length(),msglen);
while(connected&&msgbuf.length()<msglen){
idev->waitForReadyRead(250);
QByteArray recv =idev->read(msglen-vld);
if(recv.length()>0)
msgbuf.append(recv);
}
}
//QByteArray msgbuf=idev->read(msglen);
//printf("Red%d\n",msgbuf.length());
parseFromByteArray(type,msgbuf);
return type;
}
/**
* Private: Main thread method
*/
void TwoWayStream::run() {
const MethodDescriptor *method=NULL;
google::protobuf::Message *request=NULL;
SimpleRpcController *controller;
CallEntry msg;
protorpc::Message *inmsg=NULL;
while (connected) {
inmsg=(protorpc::Message*)fillMessage(protorpc::Message().New());
if(inmsg==NULL){
if(idev->isOpen()){
continue;
}
}
if(inmsg==NULL||inmsg->type()==protorpc::DISCONNECT){//disconnected by stream
connected=false;
if(inmsg)
delete inmsg;
break;
}
if (inmsg->type()==protorpc::REQUEST) {
method=NULL;
if(service==NULL){//send not implemented
streamlock->lock();
protorpc::Message *respo=protorpc::Message().New();
respo->set_type(protorpc::RESPONSE_NOT_IMPLEMENTED);
respo->set_id(inmsg->id());
writeMessage(respo);
delete respo;
streamlock->unlock();
} else{
streamlock->lock();
if((method=service->GetDescriptor()->FindMethodByName(inmsg->name()))==NULL){
protorpc::Message *resp=protorpc::Message().New();
resp->set_type(protorpc::RESPONSE_NOT_IMPLEMENTED);//this fails if the program ends executing when the thread is still running
resp->set_id(inmsg->id());
writeMessage(resp);
delete resp;
}
if(method!=NULL){
request = service->GetRequestPrototype(method).New();
request->ParseFromString(inmsg->buffer());
controller = new TwoWayRpcController(this);
google::protobuf::Message *rspmsg=service->GetResponsePrototype(method).New();
StreamCallbackInfo *sci=new StreamCallbackInfo(this,controller,rspmsg,inmsg->id());
google::protobuf::Closure *rspcls=google::protobuf::NewCallback(StreamCallbackInfo::callhack,sci);
//NewCallback(this, &Handler::FooDone, response);
//void (*resp)(StreamCallbackInfo*)=response;
controller->NotifyOnCancel(rspcls);
streamlock->unlock();
service->CallMethod(method, controller, request,rspmsg,rspcls);
streamlock->lock();
}
}
}else if (inmsg->type()==protorpc::DESCRIPTOR_REQUEST) {
streamlock->lock();
protorpc::Message *resp=protorpc::Message().New();
resp->set_type(protorpc::RESPONSE_NOT_IMPLEMENTED);
resp->set_id(inmsg->id());
writeMessage(resp);
delete resp;
streamlock->unlock();
}else if (inmsg->type()==protorpc::RESPONSE) {
streamlock->lock();
if (currentCalls.contains(inmsg->id())) {
msg = (currentCalls.value(inmsg->id()));
msg.resp->ParseFromString(inmsg->buffer());//A sigsegv here most probably means that the response is deleted and has left a dangling pointer.
currentCalls.remove(inmsg->id());
streamlock->unlock();
msg.callback->Run();
}else{
streamlock->unlock();
}
}else if (inmsg->type()==protorpc::RESPONSE_CANCEL) {
if (currentCalls.contains(inmsg->id())) {
msg = (currentCalls.value(inmsg->id()));//get controller
msg.ctrl->StartCancel();
currentCalls.remove(inmsg->id());
}
}else if (inmsg->type()==protorpc::RESPONSE_FAILED) {
if (currentCalls.contains(inmsg->id())) {
msg = currentCalls.value(inmsg->id());//get controller
msg.ctrl->SetFailed(inmsg->buffer());
currentCalls.remove(inmsg->id());
}
}else if (inmsg->type()==protorpc::RESPONSE_NOT_IMPLEMENTED) {
if (currentCalls.contains(inmsg->id())) {
msg = currentCalls.value(inmsg->id());//get controller
msg.ctrl->SetFailed("Not implemented by peer");
currentCalls.remove(inmsg->id());
}
}else if (inmsg->type()==protorpc::DESCRIPTOR_RESPONSE/*&&descriptorRequestController!=NULL&&gotDescriptorCallback!=NULL*/) {
//NOT IMPLEMENTED/DON'T CARE
}else{//empty buffer
//in.skip(in.available());
}
delete inmsg;
}
cleanup();
streamlock->lock();
stopped=true;
streamlock->unlock();
}
void TwoWayStream::cleanup(){
connected=false;
//streamlock->lock();
//initcond.wakeAll();;//make sure no caller is waiting for an init signal that will never come
//streamlock->unlock();
if(shutdownCallback!=NULL)
shutdownCallback->Run();
emit channelBroken(this);
}
/**
* Shut down the server
* @param closeStreams - close the iostreams?
*/
void TwoWayStream::shutdown(bool closeStreams){
if(connected){
streamlock->lock();
protorpc::Message *resp=protorpc::Message().New();
resp->set_type(protorpc::DISCONNECT);
try{
writeMessage(resp);
}catch(const char* e){
//do nothing as it is is not able to write to a closed socket etc.
}
delete resp;
connected=false;
#if 0 //don''t
//wait for thread to stop
streamlock->lock();
while(stopped==false){
streamlock->unlock();
msleep(100);
streamlock->lock();
}
streamlock->unlock();
#endif
streamlock->unlock();
devlock.lock();
if(closeStreams){
idev->close();
if(idev!=odev)
odev->close();
}
devlock.unlock();
//wait until thread is stopped
emit channelBroken(this);//may create problems whith queue signals etc. if shutdownCallback deletes this object
if(shutdownCallback!=NULL)
shutdownCallback->Run();
}
}
/**
* Private: Called to signal that a response is recieved, may dissappear at any moment
*/
void TwoWayStream::response(StreamCallbackInfo *info){//Integer id, Object param,RpcController ctrl) {
QMutexLocker mtxlck(streamlock);
if(service==NULL){
delete info;
return;
}
uint32_t id=info->id;
if (!info->ctr->Failed()) {// response
protorpc::Message rspbld = protorpc::Message();
rspbld.set_type(protorpc::RESPONSE);
rspbld.set_id(id);
rspbld.set_buffer(info->msg->SerializeAsString());
try{
writeMessage(&rspbld);
}catch(const char* e){
shutdown(true);
}
} else {// canceled
protorpc::Message rspbld = protorpc::Message();
rspbld.set_type(protorpc::RESPONSE_CANCEL);
rspbld.set_id(id);
rspbld.set_buffer(info->ctr->ErrorText());
writeMessage(&rspbld);
}
currentCalls.remove(info->id);
delete info->msg;
delete info->ctr;
}
void TwoWayStream::setInputDevice(QIODevice *idev){
this->idev=idev;
}
void TwoWayStream::setOutputDevice(QIODevice *odev){
this->odev=odev;
}
}