ServicesImpl.cpp 15.5 KB
Newer Older
legoc's avatar
legoc committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
 * Copyright 2015 Institut Laue-Langevin
 *
 * Licensed under the EUPL, Version 1.1 only (the "License");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 */

17
#include "ServicesImpl.h"
legoc's avatar
legoc committed
18
19
20

#include <iostream>
#include <sstream>
21
#include "../SocketException.h"
22
#include "../ConnectionTimeout.h"
23
#include "RequestSocketImpl.h"
legoc's avatar
legoc committed
24

25
26
27
28
// Using Visual Studio preprocessor.
// It must be improved in case of other compilers.
#ifdef _WIN32
	#define GET_PROCESS_PID() GetCurrentProcessId()
29
30
31
32
33
34
35
#else
	#include <unistd.h>

	#define GET_PROCESS_PID() ::getpid()
#endif


legoc's avatar
legoc committed
36
37
38
39
40
41
42
43
44
using namespace std;

namespace cameo {

const std::string ServicesImpl::STATUS = "STATUS";
const std::string ServicesImpl::RESULT = "RESULT";
const std::string ServicesImpl::PUBLISHER = "PUBLISHER";
const std::string ServicesImpl::PORT = "PORT";
const std::string ServicesImpl::CANCEL = "CANCEL";
legoc's avatar
legoc committed
45
46
const std::string ServicesImpl::STREAM = "STREAM";
const std::string ServicesImpl::ENDSTREAM = "ENDSTREAM";
legoc's avatar
legoc committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

ServicesImpl::ServicesImpl() :
	m_context(1), m_timeout(0) {
}

ServicesImpl::~ServicesImpl() {
}

void ServicesImpl::setTimeout(int timeout) {
	m_timeout = timeout;
}

int ServicesImpl::getTimeout() const {
	return m_timeout;
}

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
/**
 * convert enum type into Proto type
 */
proto::MessageType_Type ServicesImpl::convertToProtoType(ProtoType type) const {
	if (type == PROTO_INIT) {
		return proto::MessageType_Type_INIT;
	} else if (type == PROTO_ISALIVE) {
		return proto::MessageType_Type_ISALIVE;
	} else if (type == PROTO_SENDPARAMETERS) {
		return proto::MessageType_Type_SENDPARAMETERS;
	} else if (type == PROTO_SHOW) {
		return proto::MessageType_Type_SHOW;
	} else if (type == PROTO_STATUS) {
		return proto::MessageType_Type_STATUS;
	} else if (type == PROTO_SHOWALL) {
		return proto::MessageType_Type_SHOWALL;
	} else if (type == PROTO_START) {
		return proto::MessageType_Type_START;
	} else if (type == PROTO_STOP) {
		return proto::MessageType_Type_STOP;
	} else if (type == PROTO_KILL) {
		return proto::MessageType_Type_KILL;
	} else if (type == PROTO_CONNECT) {
		return proto::MessageType_Type_CONNECT;
	} else if (type == PROTO_ALLAVAILABLE) {
		return proto::MessageType_Type_ALLAVAILABLE;
	} else if (type == PROTO_SETSTATUS) {
		return proto::MessageType_Type_SETSTATUS;
	} else if (type == PROTO_GETSTATUS) {
		return proto::MessageType_Type_GETSTATUS;
	} else if (type == PROTO_SETRESULT) {
		return proto::MessageType_Type_SETRESULT;
	} else if (type == PROTO_CREATEPUBLISHER) {
		return proto::MessageType_Type_CREATEPUBLISHER;
	} else if (type == PROTO_CONNECTPUBLISHER) {
		return proto::MessageType_Type_CONNECTPUBLISHER;
	} else if (type == PROTO_SUBSCRIBEPUBLISHER) {
		return proto::MessageType_Type_SUBSCRIBEPUBLISHER;
	} else if (type == PROTO_TERMINATEPUBLISHER) {
		return proto::MessageType_Type_TERMINATEPUBLISHER;
	} else if (type == PROTO_REQUESTPORT) {
		return proto::MessageType_Type_REQUESTPORT;
	} else if (type == PROTO_CONNECTPORT) {
		return proto::MessageType_Type_CONNECTPORT;
	} else if (type == PROTO_REMOVEPORT) {
		return proto::MessageType_Type_REMOVEPORT;
	} else if (type == PROTO_REQUEST) {
		return proto::MessageType_Type_REQUEST;
	} else if (type == PROTO_RESPONSE) {
		return proto::MessageType_Type_RESPONSE;
	} else if (type == PROTO_CANCEL) {
		return proto::MessageType_Type_CANCEL;
	} else if (type == PROTO_STARTEDUNMANAGED) {
		return proto::MessageType_Type_STARTEDUNMANAGED;
	} else if (type == PROTO_TERMINATEDUNMANAGED) {
		return proto::MessageType_Type_TERMINATEDUNMANAGED;
	} else if (type == PROTO_OUTPUT) {
		return proto::MessageType_Type_OUTPUT;
	} else {
		cerr << "unsupported proto type" << endl;
		return proto::MessageType_Type(0);
	}

}

legoc's avatar
legoc committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
std::string ServicesImpl::createIsAliveRequest(int id) const {
	proto::IsAliveCommand isAliveCommand;
	isAliveCommand.set_id(id);
	std::string strRequestoIsAlive;
	isAliveCommand.SerializeToString(&strRequestoIsAlive);
	return strRequestoIsAlive;
}

std::string ServicesImpl::createInitRequest() const {
	std::string strRequestData;
	proto::Init initType;
	initType.SerializeToString(&strRequestData);
	return strRequestData;
}

143
std::string ServicesImpl::createRequestType(ProtoType type) const {
legoc's avatar
legoc committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
	proto::MessageType messageType;
	messageType.set_type(convertToProtoType(type));
	std::string strRequestType;
	messageType.SerializeToString(&strRequestType);
	return strRequestType;

}

std::string ServicesImpl::createStartRequest(const std::string& name, const std::vector<std::string> & args, const std::string& instanceReference) const {
	proto::StartCommand startCommand;
	startCommand.set_name(name);
	for (unsigned int j = 0; j < args.size(); j++) {
		startCommand.add_args(args[j]);
	}
	startCommand.set_instancereference(instanceReference);
	std::string strRequestStart;
	startCommand.SerializeToString(&strRequestStart);
	return strRequestStart;
}

legoc's avatar
legoc committed
164
std::unique_ptr<zmq::message_t> ServicesImpl::tryRequestWithOnePartReply(const std::string& strRequestType, const std::string& strRequestData, const std::string& endpoint, int overrideTimeout) {
legoc's avatar
legoc committed
165
166

	zmq::socket_t socket(m_context, ZMQ_REQ);
167
168
169
170
171
172
173
174
175
176
177
	try {
		// Set the linger value to 0 to ensure that pending requests are destroyed in case of timeout.
		int value = 0;
		socket.setsockopt(ZMQ_LINGER, &value, sizeof(int));

		// Connect to the endpoint.
		socket.connect(endpoint.c_str());
	}
	catch (exception const & e) {
		throw SocketException(e.what());
	}
legoc's avatar
legoc committed
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195

	int requestTypeSize = strRequestType.length();
	int requestDataSize = strRequestData.length();
	zmq::message_t requestType(requestTypeSize);
	zmq::message_t requestData(requestDataSize);
	memcpy((void *) requestType.data(), strRequestType.c_str(), requestTypeSize);
	memcpy((void *) requestData.data(), strRequestData.c_str(), requestDataSize);
	socket.send(requestType, ZMQ_SNDMORE);
	socket.send(requestData);

	int timeout = m_timeout;
	if (overrideTimeout > -1) {
		timeout = overrideTimeout;
	}

	if (timeout > 0) {
		// polling
		zmq_pollitem_t items[1];
legoc's avatar
legoc committed
196
		items[0].socket = static_cast<void *>(socket);
legoc's avatar
legoc committed
197
198
199
200
201
202
203
204
205
206
207
208
		items[0].fd = 0;
		items[0].events = ZMQ_POLLIN;
		items[0].revents = 0;

		int rc = zmq::poll(items, 1, timeout);
		if (rc == 0) {
			// timeout
			socket.close();
			throw ConnectionTimeout();
		}
	}

legoc's avatar
legoc committed
209
	unique_ptr<zmq::message_t> reply(new zmq::message_t());
210
	socket.recv(reply.get(), 0);
legoc's avatar
legoc committed
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

	return reply;
}

std::string ServicesImpl::createStopRequest(int id) const {
	proto::StopCommand stopCommand;
	stopCommand.set_id(id);
	std::string strRequestStop;
	stopCommand.SerializeToString(&strRequestStop);
	return strRequestStop;
}

std::string ServicesImpl::createKillRequest(int id) const {
	proto::KillCommand killCommand;
	killCommand.set_id(id);
	std::string strRequestKill;
	killCommand.SerializeToString(&strRequestKill);
	return strRequestKill;
}

std::string ServicesImpl::createConnectRequest(const std::string& name) const {
	proto::ConnectCommand connectCommand;
	connectCommand.set_name(name);
	std::string strConnect;
	connectCommand.SerializeToString(&strConnect);
	return strConnect;
}

std::string ServicesImpl::createAllAvailableRequest() const {
	proto::AllAvailableCommand allAvailableCommand;
	std::string strRequestAllAvailable;
	allAvailableCommand.SerializeToString(&strRequestAllAvailable);
	return strRequestAllAvailable;
}

std::string ServicesImpl::createShowAllRequest() const {
	proto::ShowAllCommand showAllCommand;
	std::string strRequestShowAll;
	showAllCommand.SerializeToString(&strRequestShowAll);
	return strRequestShowAll;
}

std::string ServicesImpl::createShowStatusRequest() const {
	return "status";
}

zmq::socket_t * ServicesImpl::createEventSubscriber(const std::string& endpoint, const std::string& cancelEndpoint) {

	zmq::socket_t * subscriber = new zmq::socket_t(m_context, ZMQ_SUB);

	vector<string> streamList;
	streamList.push_back(STATUS);
	streamList.push_back(RESULT);
	streamList.push_back(PUBLISHER);
	streamList.push_back(PORT);
	streamList.push_back(CANCEL);

	for (vector<string>::const_iterator s = streamList.begin(); s != streamList.end(); ++s) {
		subscriber->setsockopt(ZMQ_SUBSCRIBE, s->c_str(), s->length());
	}

	subscriber->connect(endpoint.c_str());
	subscriber->connect(cancelEndpoint.c_str());

	return subscriber;
}

278
zmq::socket_t * ServicesImpl::createOutputStreamSubscriber(const std::string& endpoint, const std::string& cancelEndpoint) {
legoc's avatar
legoc committed
279
280
281
282
283
284

	zmq::socket_t * subscriber = new zmq::socket_t(m_context, ZMQ_SUB);

	vector<string> streamList;
	streamList.push_back(STREAM);
	streamList.push_back(ENDSTREAM);
285
	streamList.push_back(CANCEL);
legoc's avatar
legoc committed
286
287
288
289
290
291

	for (vector<string>::const_iterator s = streamList.begin(); s != streamList.end(); ++s) {
		subscriber->setsockopt(ZMQ_SUBSCRIBE, s->c_str(), s->length());
	}

	subscriber->connect(endpoint.c_str());
292
	subscriber->connect(cancelEndpoint.c_str());
legoc's avatar
legoc committed
293
294
295
296

	return subscriber;
}

legoc's avatar
legoc committed
297
298
299
300
301
302
303
304
zmq::socket_t * ServicesImpl::createCancelPublisher(const std::string& endpoint) {

	zmq::socket_t * publisher = new zmq::socket_t(m_context, ZMQ_PUB);
	publisher->bind(endpoint.c_str());

	return publisher;
}

305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
zmq::socket_t * ServicesImpl::createRequestSocket(const std::string& endpoint) {

	zmq::socket_t* socket = new zmq::socket_t(m_context, ZMQ_REQ);

	try {
		// Set the linger value to 0 to ensure that pending requests are destroyed in case of timeout.
		int value = 0;
		socket->setsockopt(ZMQ_LINGER, &value, sizeof(int));

		// Connect to the endpoint.
		socket->connect(endpoint.c_str());
	}
	catch (exception const & e) {
		throw SocketException(e.what());
	}

	return socket;
}

legoc's avatar
legoc committed
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
std::string ServicesImpl::createShowStreamRequest(int id) const {
	proto::ShowStreamCommand showStreamCommand;
	showStreamCommand.set_id(id);
	std::string strRequestShowStream;
	showStreamCommand.SerializeToString(&strRequestShowStream);
	return strRequestShowStream;
}

std::string ServicesImpl::createSetStatusRequest(int id, int32_t state) const {
	proto::SetStatusCommand setStatusCommand;
	setStatusCommand.set_id(id);
	setStatusCommand.set_applicationstate(state);
	std::string strSetStatus;
	setStatusCommand.SerializeToString(&strSetStatus);

	return strSetStatus;
}

std::string ServicesImpl::createGetStatusRequest(int id) const {
	proto::GetStatusCommand getStatusCommand;
	getStatusCommand.set_id(id);
	std::string strGetStatus;
	getStatusCommand.SerializeToString(&strGetStatus);

	return strGetStatus;
}

std::string ServicesImpl::createSetResultRequest(int id, const std::string& data) const {
	proto::SetResultCommand setResultCommand;
	setResultCommand.set_id(id);
	setResultCommand.set_data(data);
	std::string strSetResult;
	setResultCommand.SerializeToString(&strSetResult);

	return strSetResult;
}

std::string ServicesImpl::createSubscribePublisherRequest() const {
	proto::SubscribePublisherCommand subscribePublisherCommand;
	std::string result;
	subscribePublisherCommand.SerializeToString(&result);

	return result;
}

std::string ServicesImpl::createCreatePublisherRequest(int id, const std::string& name, int numberOfSubscribers) const {
	proto::CreatePublisherCommand createPublisherCommand;
	createPublisherCommand.set_id(id);
	createPublisherCommand.set_name(name);
	createPublisherCommand.set_numberofsubscribers(numberOfSubscribers);
	std::string result;
	createPublisherCommand.SerializeToString(&result);

	return result;
}

std::string ServicesImpl::createConnectPublisherRequest(int id, const std::string& publisherName) const {
	proto::ConnectPublisherCommand connectPublisherCommand;
	connectPublisherCommand.set_applicationid(id);
	connectPublisherCommand.set_publishername(publisherName);
	std::string result;
	connectPublisherCommand.SerializeToString(&result);

	return result;
}

std::string ServicesImpl::createTerminatePublisherRequest(int id, const std::string& name) const {
	proto::TerminatePublisherCommand terminatePublisherCommand;
	terminatePublisherCommand.set_id(id);
	terminatePublisherCommand.set_name(name);
	std::string result;
	terminatePublisherCommand.SerializeToString(&result);

	return result;
}

std::string ServicesImpl::createRequestPortRequest(int id, const std::string& name) const {
	proto::RequestPortCommand requestPortCommand;
	requestPortCommand.set_id(id);
	requestPortCommand.set_name(name);
	std::string result;
	requestPortCommand.SerializeToString(&result);

	return result;
}

std::string ServicesImpl::createConnectPortRequest(int id, const std::string& name) const {
	proto::ConnectPortCommand connectPortCommand;
	connectPortCommand.set_id(id);
	connectPortCommand.set_name(name);
	std::string result;
	connectPortCommand.SerializeToString(&result);

	return result;
}

std::string ServicesImpl::createRemovePortRequest(int id, const std::string& name) const {
	proto::RemovePortCommand removePortCommand;
	removePortCommand.set_id(id);
	removePortCommand.set_name(name);
	std::string result;
	removePortCommand.SerializeToString(&result);

	return result;
}

legoc's avatar
legoc committed
430
std::string ServicesImpl::createStartedUnmanagedRequest(const std::string& name) const {
431
432
433
434

	// Get the pid.
	long pid = GET_PROCESS_PID();

legoc's avatar
legoc committed
435
436
	proto::StartedUnmanagedCommand command;
	command.set_name(name);
437
	command.set_pid(pid);
legoc's avatar
legoc committed
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
	std::string result;
	command.SerializeToString(&result);

	return result;
}

std::string ServicesImpl::createTerminatedUnmanagedRequest(int id) const {
	proto::TerminatedUnmanagedCommand command;
	command.set_id(id);
	std::string result;
	command.SerializeToString(&result);

	return result;
}

legoc's avatar
legoc committed
453
454
455
456
457
458
459
460
461
std::string ServicesImpl::createOutputRequest(const std::string& name) const {
	proto::OutputCommand command;
	command.set_name(name);
	std::string result;
	command.SerializeToString(&result);

	return result;
}

legoc's avatar
legoc committed
462
463
464
bool ServicesImpl::isAvailable(const std::string& strRequestType, const std::string& strRequestData, const std::string& endpoint, int timeout) {

	try {
legoc's avatar
legoc committed
465
		unique_ptr<zmq::message_t> reply = tryRequestWithOnePartReply(strRequestType, strRequestData, endpoint.c_str(), timeout);
legoc's avatar
legoc committed
466

legoc's avatar
legoc committed
467
		if (reply.get() != nullptr) {
legoc's avatar
legoc committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
			return true;
		}

	} catch (const ConnectionTimeout&) {
		// do nothing, timeout
	}

	return false;
}

void ServicesImpl::waitForSubscriber(zmq::socket_t * subscriber, const std::string& strRequestType, const std::string& strRequestData, const std::string& endpoint) {

	// polling subscriber
	zmq_pollitem_t items[1];
legoc's avatar
legoc committed
482
	items[0].socket = static_cast<void *>(*subscriber);
legoc's avatar
legoc committed
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
	items[0].fd = 0;
	items[0].events = ZMQ_POLLIN;
	items[0].revents = 0;

	bool ready = false;
	while (!ready) {
		isAvailable(strRequestType, strRequestData, endpoint, 100);

		// wait for 100ms ?
		int rc = zmq::poll(items, 1, 100);
		if (rc != 0) {
			ready = true;
		}
	}
}

void ServicesImpl::subscribeToPublisher(const std::string& endpoint) {
500

501
	string strRequestType = createRequestType(PROTO_SUBSCRIBEPUBLISHER);
legoc's avatar
legoc committed
502
	string strRequestData = createSubscribePublisherRequest();
503

legoc's avatar
legoc committed
504
	unique_ptr<zmq::message_t> reply = tryRequestWithOnePartReply(strRequestType, strRequestData, endpoint);
legoc's avatar
legoc committed
505
506
507
508
	proto::RequestResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());
}

509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
bool ServicesImpl::isAvailable(RequestSocketImpl * socket, int timeout) {

	string requestTypePart = createRequestType(PROTO_INIT);
	string requestDataPart = createInitRequest();

	try {
		unique_ptr<zmq::message_t> reply = socket->request(requestTypePart, requestDataPart, timeout);

		if (reply.get() != nullptr) {
			return true;
		}

	} catch (const ConnectionTimeout&) {
		// The server is not accessible.
	}

	return false;
}

legoc's avatar
legoc committed
528
}