ServicesImpl.cpp 13.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"
legoc's avatar
legoc committed
23

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

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


legoc's avatar
legoc committed
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
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";

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;
}

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;
}

std::string ServicesImpl::createRequest(ProtoType type) const {
	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;
}

96
std::auto_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
97
98

	zmq::socket_t socket(m_context, ZMQ_REQ);
99
100
101
102
103
104
105
106
107
108
109
	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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

	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
128
		items[0].socket = static_cast<void *>(socket);
legoc's avatar
legoc committed
129
130
131
132
133
134
135
136
137
138
139
140
		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();
		}
	}

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

	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;
}

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;
}

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
324
std::string ServicesImpl::createStartedUnmanagedRequest(const std::string& name) const {
325
326
327
328

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

legoc's avatar
legoc committed
329
330
	proto::StartedUnmanagedCommand command;
	command.set_name(name);
331
	command.set_pid(pid);
legoc's avatar
legoc committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
	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
347
348
349
bool ServicesImpl::isAvailable(const std::string& strRequestType, const std::string& strRequestData, const std::string& endpoint, int timeout) {

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

352
		if (reply.get() != 0) {
legoc's avatar
legoc committed
353
354
355
356
357
358
359
360
361
362
363
364
365
366
			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
367
	items[0].socket = static_cast<void *>(*subscriber);
legoc's avatar
legoc committed
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
	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) {
385

legoc's avatar
legoc committed
386
387
	string strRequestType = createRequest(PROTO_SUBSCRIBEPUBLISHER);
	string strRequestData = createSubscribePublisherRequest();
388
389

	auto_ptr<zmq::message_t> reply = tryRequestWithOnePartReply(strRequestType, strRequestData, endpoint);
legoc's avatar
legoc committed
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
	proto::RequestResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());
}

/**
 * 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;
legoc's avatar
legoc committed
446
447
448
449
	} else if (type == PROTO_STARTEDUNMANAGED) {
		return proto::MessageType_Type_STARTEDUNMANAGED;
	} else if (type == PROTO_TERMINATEDUNMANAGED) {
		return proto::MessageType_Type_TERMINATEDUNMANAGED;
legoc's avatar
legoc committed
450
451
452
453
454
455
456
457
	} else {
		cerr << "unsupported proto type" << endl;
		return proto::MessageType_Type(0);
	}

}

}