Application.cpp 33.6 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 "Application.h"
legoc's avatar
legoc committed
18
19
20
21
22
23

#include <sstream>
#include <iostream>
#include <iostream>
#include <stdexcept>
#include <vector>
24
#include "EventStreamSocket.h"
25
#include "impl/ServicesImpl.h"
26
27
28
29
30
31
32
#include "impl/PublisherImpl.h"
#include "impl/RequesterImpl.h"
#include "impl/RequestImpl.h"
#include "impl/ResponderImpl.h"
#include "impl/SubscriberImpl.h"
#include "impl/WaitingImpl.h"
#include "impl/WaitingImplSet.h"
33
#include "impl/HandlerImpl.h"
34
#include "impl/StreamSocketImpl.h"
legoc's avatar
legoc committed
35
#include "impl/RequestSocketImpl.h"
36
37
38
39
40
41
42
#include "PortEvent.h"
#include "ProtoType.h"
#include "PublisherEvent.h"
#include "ResultEvent.h"
#include "Server.h"
#include "StarterServerException.h"
#include "StatusEvent.h"
legoc's avatar
legoc committed
43
44
45
46
47
48

using namespace std;

namespace cameo {
namespace application {

49
This This::m_instance;
legoc's avatar
legoc committed
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const std::string This::RUNNING_STATE = "RUNNING";

State This::parseState(const std::string& value) {

	if (value == "UNKNOWN") {
		return UNKNOWN;
	} else if (value == "STARTING") {
		return STARTING;
	} else if (value == "RUNNING") {
		return RUNNING;
	} else if (value == "STOPPING") {
		return STOPPING;
	} else if (value == "KILLING") {
		return KILLING;
	} else if (value == "PROCESSING_ERROR") {
		return PROCESSING_ERROR;
	} else if (value == "ERROR") {
legoc's avatar
legoc committed
67
		return FAILURE;
legoc's avatar
legoc committed
68
69
70
71
72
73
74
75
76
77
78
79
	} else if (value == "SUCCESS") {
		return SUCCESS;
	} else if (value == "STOPPED") {
		return STOPPED;
	} else if (value == "KILLED") {
		return KILLED;
	}

	return UNKNOWN;
}

void This::init(int argc, char *argv[]) {
legoc's avatar
legoc committed
80
	if (m_instance.m_impl == nullptr) {
81
		m_instance.initApplication(argc, argv);
legoc's avatar
legoc committed
82
83
84
85
	}
}

std::string This::getReference() {
legoc's avatar
legoc committed
86
	if (m_instance.m_impl != nullptr) {
legoc's avatar
legoc committed
87
		ostringstream os;
88
		os << getName() << "." << getId() << "@" << getEndpoint();
legoc's avatar
legoc committed
89
90
91
92
93
94
		return os.str();
	}
	return "";
}

void This::terminate() {
95
96

	// Test if termination is already done.
legoc's avatar
legoc committed
97
	if (m_instance.m_impl == nullptr) {
98
99
100
101
102
103
		return;
	}

	// Terminate the unmanaged application.
	if (!m_instance.m_managed) {
		m_instance.terminateUnmanagedApplication();
legoc's avatar
legoc committed
104
105
	}

106
107
108
109
	// Terminate the services.
	m_instance.Services::terminate();

	// Ensure that it won't be done twice.
legoc's avatar
legoc committed
110
	m_instance.m_impl = nullptr;
legoc's avatar
legoc committed
111
112
}

113
114

This::This() :
legoc's avatar
legoc committed
115
	Services(),
legoc's avatar
legoc committed
116
117
118
	m_id(-1),
	m_managed(false),
	m_starterId(0) {
119
120
121
}

void This::initApplication(int argc, char *argv[]) {
legoc's avatar
legoc committed
122

123
	Services::init();
legoc's avatar
legoc committed
124
125

	if (argc == 0) {
126
		throw InvalidArgumentException("missing info argument");
legoc's avatar
legoc committed
127
128
129
130
131
132
	}

	string info(argv[argc - 1]);
	vector<string> tokens = split(info);

	if (tokens.size() < 4) {
133
		throw InvalidArgumentException(info + " is not a valid argument");
legoc's avatar
legoc committed
134
135
136
137
138
139
140
141
	}

	m_url = tokens[0] + ":" + tokens[1];

	string port = tokens[2];
	istringstream is(port);
	is >> m_port;

142
143
144
	// We separated host endpoint and server in the past (server being tcp://localhost)
	// but that generates troubles when two applications communicate remotely.
	// However leave the same value seems to be ok.
legoc's avatar
legoc committed
145
146
	m_serverEndpoint = m_url + ":" + port;

147
148
149
	// Create the request socket. The server endpoint has been defined.
	Services::initRequestSocket();

legoc's avatar
legoc committed
150
151
152
	string nameId = tokens[3];

	int index = nameId.find_last_of('.');
legoc's avatar
legoc committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167

	// Search for the . character meaning that the application is managed and already has an id.
	if (index != string::npos) {
		m_managed = true;
		m_name = nameId.substr(0, index);
		string sid = nameId.substr(index + 1);
		{
			istringstream is(sid);
			is >> m_id;
		}
	}
	else {
		m_managed = false;
		m_name = nameId;
		m_id = initUnmanagedApplication();
168
169
170
171

		if (m_id == -1) {
			throw UnmanagedApplicationException(string("Maximum number of applications ") + m_name + " reached");
		}
legoc's avatar
legoc committed
172
173
174
175
176
177
178
179
	}

	if (tokens.size() >= 7) {
		index = tokens[4].find_last_of('@');
		m_starterEndpoint = tokens[4].substr(index + 1) + ":" + tokens[5] + ":" + tokens[6];
		string starterNameId = tokens[4].substr(0, index);
		index = starterNameId.find_last_of('.');
		m_starterName = starterNameId.substr(0, index);
legoc's avatar
legoc committed
180
		string sid = starterNameId.substr(index + 1);
legoc's avatar
legoc committed
181
182
183
184
185
186
		{
			istringstream is(sid);
			is >> m_starterId;
		}
	}

legoc's avatar
legoc committed
187
188
	// Must be here because the server endpoint is required.
	initStatus();
legoc's avatar
legoc committed
189
190

	// Create the local server
legoc's avatar
legoc committed
191
	m_server = unique_ptr<Server>(new Server(m_serverEndpoint));
legoc's avatar
legoc committed
192
193
194

	// Create the starter server
	if (m_starterEndpoint != "") {
legoc's avatar
legoc committed
195
		m_starterServer = unique_ptr<Server>(new Server(m_starterEndpoint));
legoc's avatar
legoc committed
196
197
	}

legoc's avatar
legoc committed
198
	m_waitingSet = unique_ptr<WaitingImplSet>(new WaitingImplSet());
199
200
201
202

	// Init listener.
	setName(m_name);
	m_server->registerEventListener(this);
legoc's avatar
legoc committed
203
204
205
206
}

This::~This() {
	// Do not delete the impl here because there will be order trouble.
207
208

	// Terminate the unmanaged application.
legoc's avatar
legoc committed
209
	if (m_impl != nullptr && !m_managed) {
210
211
		terminateUnmanagedApplication();
	}
legoc's avatar
legoc committed
212
213
214
}

const std::string& This::getName() {
215
	return m_instance.m_name;
legoc's avatar
legoc committed
216
217
218
}

int This::getId() {
219
	return m_instance.m_id;
legoc's avatar
legoc committed
220
221
222
}

void This::setTimeout(int timeout) {
223
	m_instance.Services::setTimeout(timeout);
legoc's avatar
legoc committed
224
225
226
}

int This::getTimeout() {
227
	return m_instance.Services::getTimeout();
legoc's avatar
legoc committed
228
229
}

230
const std::string& This::getEndpoint() {
legoc's avatar
legoc committed
231
	if (m_instance.m_impl != nullptr) {
232
		return m_instance.m_serverEndpoint;
legoc's avatar
legoc committed
233
234
235
236
237
238
	}
	static string result;
	return result;
}

Server& This::getServer() {
239
	return *m_instance.m_server;
legoc's avatar
legoc committed
240
241
242
243
}

Server& This::getStarterServer() {

legoc's avatar
legoc committed
244
	if (m_instance.m_starterServer.get() == nullptr) {
legoc's avatar
legoc committed
245
246
247
		throw StarterServerException();
	}

248
	return *m_instance.m_starterServer;
legoc's avatar
legoc committed
249
250
251
}

const std::string& This::getUrl() {
252
	return m_instance.Services::getUrl();
legoc's avatar
legoc committed
253
254
255
}

bool This::isAvailable(int timeout) {
256
	return m_instance.Services::isAvailable(timeout);
legoc's avatar
legoc committed
257
258
259
}

bool This::isStopping() {
260
	return m_instance.getState(m_instance.m_id) == STOPPING;
legoc's avatar
legoc committed
261
262
263
}

void This::cancelWaitings() {
264
	m_instance.m_waitingSet->cancelAll();
legoc's avatar
legoc committed
265
266
}

legoc's avatar
legoc committed
267
int This::initUnmanagedApplication() {
legoc's avatar
legoc committed
268

legoc's avatar
legoc committed
269
	unique_ptr<zmq::message_t> reply = m_requestSocket->request(m_impl->createRequestType(PROTO_STARTEDUNMANAGED), m_impl->createStartedUnmanagedRequest(m_name));
legoc's avatar
legoc committed
270
271
272
273
274
275
276
277
278

	proto::RequestResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());

	return requestResponse.value();
}

void This::terminateUnmanagedApplication() {

legoc's avatar
legoc committed
279
	unique_ptr<zmq::message_t> reply = m_requestSocket->request(m_impl->createRequestType(PROTO_TERMINATEDUNMANAGED), m_impl->createTerminatedUnmanagedRequest(m_id));
legoc's avatar
legoc committed
280
281
282

	proto::RequestResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());
legoc's avatar
legoc committed
283
284
}

285
bool This::setRunning() {
legoc's avatar
legoc committed
286

legoc's avatar
legoc committed
287
	unique_ptr<zmq::message_t> reply = m_instance.m_requestSocket->request(m_instance.m_impl->createRequestType(PROTO_SETSTATUS), m_instance.m_impl->createSetStatusRequest(m_instance.m_id, RUNNING));
legoc's avatar
legoc committed
288
289
290
291
292

	proto::RequestResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());

	if (requestResponse.value() == -1) {
293
		return false;
legoc's avatar
legoc committed
294
	}
295
296

	return true;
legoc's avatar
legoc committed
297
298
299
300
}

void This::setBinaryResult(const std::string& data) {

legoc's avatar
legoc committed
301
	unique_ptr<zmq::message_t> reply = m_instance.m_requestSocket->request(m_instance.m_impl->createRequestType(PROTO_SETRESULT), m_instance.m_impl->createSetResultRequest(m_instance.m_id, data));
legoc's avatar
legoc committed
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

	proto::RequestResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());
}

void This::setResult(const std::string& data) {

	string resultData;
	serialize(data, resultData);
	setBinaryResult(resultData);
}

void This::setResult(const int32_t* data, std::size_t size) {

	string resultData;
	serialize(data, size, resultData);
	setBinaryResult(resultData);
}

void This::setResult(const int64_t* data, std::size_t size) {

	string resultData;
	serialize(data, size, resultData);
	setBinaryResult(resultData);
}

void This::setResult(const float* data, std::size_t size) {

	string resultData;
	serialize(data, size, resultData);
	setBinaryResult(resultData);
}

void This::setResult(const double* data, std::size_t size) {

	string resultData;
	serialize(data, size, resultData);
	setBinaryResult(resultData);
}

State This::getState(int id) const {

legoc's avatar
legoc committed
344
	unique_ptr<zmq::message_t> reply = m_requestSocket->request(m_impl->createRequestType(PROTO_GETSTATUS), m_impl->createGetStatusRequest(id));
legoc's avatar
legoc committed
345
346
347
348
349
350
351
352
353

	proto::StatusEvent protoStatus;
	protoStatus.ParseFromArray((*reply).data(), (*reply).size());

	return protoStatus.applicationstate();
}

bool This::destroyPublisher(const std::string& name) const {

legoc's avatar
legoc committed
354
	unique_ptr<zmq::message_t> reply = m_requestSocket->request(m_impl->createRequestType(PROTO_TERMINATEPUBLISHER), m_impl->createTerminatePublisherRequest(m_id, name));
legoc's avatar
legoc committed
355
356
357
358
359
360
361
362
363
364

	proto::RequestResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());

	int value = requestResponse.value();
	return (value != -1);
}

bool This::removePort(const std::string& name) const {

legoc's avatar
legoc committed
365
	unique_ptr<zmq::message_t> reply = m_requestSocket->request(m_impl->createRequestType(PROTO_REMOVEPORT), m_impl->createRemovePortRequest(m_id, name));
legoc's avatar
legoc committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384

	proto::RequestResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());

	int value = requestResponse.value();
	return (value != -1);
}

State This::waitForStop() {

	// test if stop was requested elsewhere
	State state = getState(m_id);
	if (state == STOPPING
		|| state == KILLING) {
		return state;
	}

	while (true) {
		// waits for a new incoming status
385
		unique_ptr<Event> event = popEvent();
legoc's avatar
legoc committed
386
387

		// The socket is canceled.
legoc's avatar
legoc committed
388
		if (event.get() == nullptr) {
legoc's avatar
legoc committed
389
390
391
392
393
394
			return UNKNOWN;
		}

		if (event->getId() == m_id) {
			StatusEvent * status = dynamic_cast<StatusEvent *>(event.get());

legoc's avatar
legoc committed
395
			if (status != nullptr) {
legoc's avatar
legoc committed
396
397
398
399
400
401
402
403
404
405
406
407
408
				state = status->getState();

				if (state == STOPPING
					|| state == KILLING) {
					return state;
				}
			}
		}
	}

	return UNKNOWN;
}

legoc's avatar
legoc committed
409
std::unique_ptr<Instance> This::connectToStarter() {
legoc's avatar
legoc committed
410

legoc's avatar
legoc committed
411
412
	if (m_instance.m_starterServer.get() == nullptr) {
		return unique_ptr<Instance>(nullptr);
legoc's avatar
legoc committed
413
414
415
	}

	// Iterate the instances to find the id
416
	InstanceArray instances = m_instance.m_starterServer->connectAll(m_instance.m_starterName);
legoc's avatar
legoc committed
417
418

	for (int i = 0; i < instances.size(); i++) {
419
		if (instances[i]->getId() == m_instance.m_starterId) {
legoc's avatar
legoc committed
420
			return unique_ptr<Instance>(std::move(instances[i]));
legoc's avatar
legoc committed
421
422
423
		}
	}

legoc's avatar
legoc committed
424
	return unique_ptr<Instance>(nullptr);
legoc's avatar
legoc committed
425
426
}

427
428
429
430
431
432
433
434
435
436
void This::stoppingFunction(StopFunctionType stop) {

	application::State state = waitForStop();

	// Only stop in case of STOPPING.
	if (state == application::STOPPING) {
		stop();
	}
}

legoc's avatar
legoc committed
437
void This::handleStopImpl(StopFunctionType function) {
438
	m_stopHandler = unique_ptr<HandlerImpl>(new HandlerImpl(bind(&This::stoppingFunction, this, function)));
legoc's avatar
legoc committed
439
440
441
442
443
}

///////////////////////////////////////////////////////////////////////////////
// Instance

444
Instance::Instance(Server * server) :
legoc's avatar
legoc committed
445
446
447
448
449
450
451
452
453
	m_server(server),
	m_id(-1),
	m_pastStates(0),
	m_initialState(UNKNOWN),
	m_lastState(UNKNOWN),
	m_hasResult(false) {
}

Instance::~Instance() {
454
455
456
457
	// Unregister the instance.
	m_server->unregisterEventListener(this);

	// The destructor has been added to avoid blocking ZeroMQ, because the inner objects destructors were not called.
legoc's avatar
legoc committed
458
459
460
461
462
463
}

void Instance::setId(int id) {
	m_id = id;
}

legoc's avatar
legoc committed
464
465
466
467
const std::string& Instance::getName() const {
	return EventListener::m_name;
}

legoc's avatar
legoc committed
468
469
470
471
void Instance::setErrorMessage(const std::string& message) {
	m_errorMessage = message;
}

legoc's avatar
legoc committed
472
473
474
475
void Instance::setOutputStreamSocket(std::unique_ptr<OutputStreamSocket>& socket) {
	m_outputStreamSocket = std::move(socket);
}

legoc's avatar
legoc committed
476
477
478
479
480
481
void Instance::setPastStates(State pastStates) {
	m_pastStates = pastStates;
}

void Instance::setInitialState(State state) {
	m_initialState = state;
482
483
484

	// It is important to set the last state, because in case of a call to the function now without any incoming state.
	m_lastState = state;
legoc's avatar
legoc committed
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
}

int Instance::getId() const {
	return m_id;
}

const std::string& Instance::getUrl() const {
	return m_server->getUrl();
}

const std::string& Instance::getEndpoint() const {
	return m_server->getEndpoint();
}

std::string Instance::getNameId() const {
	stringstream os;
	os << m_name << "." << m_id;

	return os.str();
}

bool Instance::hasResult() const {
	return m_hasResult;
}

bool Instance::exists() const {
	return (m_id != -1);
}

const std::string& Instance::getErrorMessage() const {
	return m_errorMessage;
}

bool Instance::stop() {
	try {
		Response response = m_server->stopApplicationAsynchronously(m_id, false);

	} catch (const ConnectionTimeout& e) {
		m_errorMessage = e.what();
		return false;
	}

	return true;
}

bool Instance::kill() {
	try {
		Response response = m_server->stopApplicationAsynchronously(m_id, true);

	} catch (const ConnectionTimeout& e) {
		m_errorMessage = e.what();
		return false;
	}

	return true;
}

542
State Instance::waitFor(int states, const std::string& eventName, StateHandlerType handler, bool blocking) {
legoc's avatar
legoc committed
543
544

	if (!exists()) {
545
		// The application was not launched
legoc's avatar
legoc committed
546
547
548
		return m_lastState;
	}

549
	// Test the terminal state
legoc's avatar
legoc committed
550
551
552
	if (m_lastState == SUCCESS
		|| m_lastState == STOPPED
		|| m_lastState == KILLED
legoc's avatar
legoc committed
553
		|| m_lastState == FAILURE) {
554
		// The application is already terminated
legoc's avatar
legoc committed
555
556
557
		return m_lastState;
	}

558
	// Test the requested states
legoc's avatar
legoc committed
559
	if ((states & m_pastStates) != 0) {
560
		// The state is already received
legoc's avatar
legoc committed
561
562
563
564
		return m_lastState;
	}

	while (true) {
565
		// Waits for a new incoming status
566
		unique_ptr<Event> event = popEvent(blocking);
legoc's avatar
legoc committed
567

568
		// The socket is canceled or the non-blocking call returns a null message.
legoc's avatar
legoc committed
569
		if (event.get() == nullptr) {
legoc's avatar
legoc committed
570
571
572
573
574
575
			return m_lastState;
		}

		if (event->getId() == m_id) {
			StatusEvent * status = dynamic_cast<StatusEvent *>(event.get());

legoc's avatar
legoc committed
576
			if (status != nullptr) {
legoc's avatar
legoc committed
577
578
579
580
				State state = status->getState();
				m_pastStates = status->getPastStates();
				m_lastState = state;

581
				// Call the state handler.
legoc's avatar
legoc committed
582
				if (handler != nullptr) {
legoc's avatar
legoc committed
583
584
585
					handler(state);
				}

legoc's avatar
legoc committed
586
587
588
589
				// test the terminal state
				if (state == SUCCESS
					|| state == STOPPED
					|| state == KILLED
legoc's avatar
legoc committed
590
					|| state == FAILURE) {
legoc's avatar
legoc committed
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
					break;
				}

				// test the requested states
				if ((states & m_pastStates) != 0) {
					return m_lastState;
				}

			} else {

				if (ResultEvent * result = dynamic_cast<ResultEvent *>(event.get())) {
					m_hasResult = true;
					m_resultData = result->getData();

				} else if (PublisherEvent * publisher = dynamic_cast<PublisherEvent *>(event.get())) {
					if (publisher->getPublisherName() == eventName) {
						break;
					}

				} else if (PortEvent * port = dynamic_cast<PortEvent *>(event.get())) {
					if (port->getPortName() == eventName) {
						break;
					}
				}
			}

		}
	}

	return m_lastState;
}

623
624
625
626
State Instance::waitFor(int states, const std::string& eventName, StateHandlerType handler) {
	return waitFor(states, eventName, handler, true);
}

legoc's avatar
legoc committed
627
628
629
630
631
632
State Instance::waitFor(int states, StateHandlerType handler) {
	return waitFor(states, "", handler);
}

State Instance::waitFor(StateHandlerType handler) {
	return waitFor(0, "", handler);
legoc's avatar
legoc committed
633
634
635
}

void Instance::cancelWaitFor() {
636
	cancel(m_id);
legoc's avatar
legoc committed
637
638
}

639
State Instance::now() {
640
641
642
643
644
645
646

	// First implementation used getLastState().
	return getActualState();
}

State Instance::getLastState() {

legoc's avatar
legoc committed
647
	return waitFor(0, "", nullptr, false);
648
649
}

650
651
652
653
654
655
656
657
658
659
660
661
662
663
State Instance::getActualState() const {

	vector<application::Info> infos = m_server->getApplicationInfos();

	for (vector<application::Info>::const_iterator i = infos.begin(); i != infos.end(); ++i) {
		application::Info const & info = *i;
		if (info.getId() == m_id) {
			return info.getState();
		}
	}

	return UNKNOWN;
}

legoc's avatar
legoc committed
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
bool Instance::getBinaryResult(std::string& result) {

	waitFor();
	result = m_resultData;

	return m_hasResult;
}

bool Instance::getResult(std::string& result) {

	string bytes;
	getBinaryResult(bytes);
	parse(bytes, result);

	return m_hasResult;
}

bool Instance::getResult(std::vector<int32_t>& result) {

	string bytes;
	getBinaryResult(bytes);
	parse(bytes, result);

	return m_hasResult;
}

bool Instance::getResult(std::vector<int64_t>& result) {

	string bytes;
	getBinaryResult(bytes);
	parse(bytes, result);

	return m_hasResult;
}

bool Instance::getResult(std::vector<float>& result) {

	string bytes;
	getBinaryResult(bytes);
	parse(bytes, result);

	return m_hasResult;
}

bool Instance::getResult(std::vector<double>& result) {

	string bytes;
	getBinaryResult(bytes);
	parse(bytes, result);

	return m_hasResult;
}

legoc's avatar
legoc committed
717
718
719
720
std::shared_ptr<OutputStreamSocket> Instance::getOutputStreamSocket() {
	return m_outputStreamSocket;
}

legoc's avatar
legoc committed
721
722
723
724
725
726
727
728
729
730
///////////////////////////////////////////////////////////////////////////
// InstanceArray

InstanceArray::InstanceArray() :
	m_size(0),
	m_array(0) {
}

InstanceArray::InstanceArray(const InstanceArray& array) :
	m_size(array.m_size),
legoc's avatar
legoc committed
731
	m_array(new unique_ptr<Instance>[m_size]) {
legoc's avatar
legoc committed
732
733
734

	// transferring pointers
	for (size_t i = 0; i < m_size; i++) {
legoc's avatar
legoc committed
735
		m_array[i] = std::move(array.m_array[i]);
legoc's avatar
legoc committed
736
737
738
739
740
741
742
743
744
	}
}

InstanceArray::~InstanceArray() {
	delete [] m_array;
}

void InstanceArray::allocate(std::size_t size) {
	m_size = size;
legoc's avatar
legoc committed
745
	m_array = new unique_ptr<Instance>[size];
legoc's avatar
legoc committed
746
747
748
749
750
751
}

std::size_t InstanceArray::size() const {
	return m_size;
}

legoc's avatar
legoc committed
752
std::unique_ptr<Instance>& InstanceArray::operator[](std::size_t index) {
legoc's avatar
legoc committed
753
754
755
756
757
758
	return m_array[index];
}

///////////////////////////////////////////////////////////////////////////////
// Publisher

legoc's avatar
legoc committed
759
Publisher::Publisher(This * application, int publisherPort, int synchronizerPort, const std::string& name, int numberOfSubscribers) :
legoc's avatar
legoc committed
760
761
762
763
764
765
766
767
768
	m_impl(new PublisherImpl(application, publisherPort, synchronizerPort, name, numberOfSubscribers)) {

	// Create the waiting here.
	m_waiting.reset(m_impl->waiting());
}

Publisher::~Publisher() {
}

legoc's avatar
legoc committed
769
std::unique_ptr<Publisher> Publisher::create(const std::string& name, int numberOfSubscribers) {
legoc's avatar
legoc committed
770

771
	unique_ptr<zmq::message_t> reply = This::m_instance.m_requestSocket->request(This::m_instance.m_impl->createRequestType(PROTO_CREATEPUBLISHER), This::m_instance.m_impl->createCreatePublisherRequest(This::m_instance.m_id, name, numberOfSubscribers));
legoc's avatar
legoc committed
772
773
774
775
776
777
778
779
780
781

	proto::PublisherResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());

	int publisherPort = requestResponse.publisherport();
	if (publisherPort == -1) {
		throw PublisherCreationException(requestResponse.message());
	}
	int synchronizerPort = requestResponse.synchronizerport();

legoc's avatar
legoc committed
782
	return unique_ptr<Publisher>(new Publisher(&This::m_instance, publisherPort, synchronizerPort, name, numberOfSubscribers));
legoc's avatar
legoc committed
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
}


const std::string& Publisher::getName() const {
	return m_impl->getName();
}

const std::string& Publisher::getApplicationName() const {
	return m_impl->getApplicationName();
}

int Publisher::getApplicationId() const {
	return m_impl->getApplicationId();
}

const std::string& Publisher::getApplicationEndpoint() const {
	return m_impl->getApplicationEndpoint();
}

bool Publisher::waitForSubscribers() const {
	return m_impl->waitForSubscribers();
}

void Publisher::cancelWaitForSubscribers() {
	m_waiting->cancel();
}

void Publisher::sendBinary(const std::string& data) const {
	m_impl->sendBinary(data);
}

void Publisher::send(const std::string& data) const {
	m_impl->send(data);
}

void Publisher::send(const int32_t* data, std::size_t size) const {
	m_impl->send(data, size);
}

void Publisher::send(const int64_t* data, std::size_t size) const {
	m_impl->send(data, size);
}

void Publisher::send(const float* data, std::size_t size) const {
	m_impl->send(data, size);
}

void Publisher::send(const double* data, std::size_t size) const {
	m_impl->send(data, size);
}

834
835
836
837
void Publisher::sendTwoBinaryParts(const std::string& data1, const std::string& data2) const {
	m_impl->sendTwoBinaryParts(data1, data2);
}

legoc's avatar
legoc committed
838
bool Publisher::hasEnded() const {
839
840
841
842
843
	return m_impl->isEnded();
}

bool Publisher::isEnded() const {
	return m_impl->isEnded();
legoc's avatar
legoc committed
844
845
846
847
848
849
850
851
852
}

void Publisher::sendEnd() const {
	m_impl->setEnd();
}

///////////////////////////////////////////////////////////////////////////
// Subscriber

853
Subscriber::Subscriber(Server * server, const std::string & url, int publisherPort, int synchronizerPort, const std::string & publisherName, int numberOfSubscribers, const std::string& instanceName, int instanceId, const std::string& instanceEndpoint, const std::string& statusEndpoint) :
legoc's avatar
legoc committed
854
855
856
857
858
859
	m_impl(new SubscriberImpl(server, url, publisherPort, synchronizerPort, publisherName, numberOfSubscribers, instanceName, instanceId, instanceEndpoint, statusEndpoint)) {
}

Subscriber::~Subscriber() {
}

legoc's avatar
legoc committed
860
std::unique_ptr<Subscriber> Subscriber::create(Instance & instance, const std::string& publisherName) {
legoc's avatar
legoc committed
861
862
863
864
865
866
867
868
869
870
871
872
873
874
	try {
		return instance.m_server->createSubscriber(instance.m_id, publisherName, instance.m_name);

	} catch (const SubscriberCreationException& e) {
		// the publisher does not exist, so we are waiting for it
	}

	// waiting for the publisher
	State lastState = instance.waitFor(0, publisherName);

	// state cannot be terminal or it means that the application has terminated that is not planned.
	if (lastState == SUCCESS
		|| lastState == STOPPED
		|| lastState == KILLED
legoc's avatar
legoc committed
875
		|| lastState == FAILURE) {
legoc's avatar
legoc committed
876
		return unique_ptr<Subscriber>(nullptr);
legoc's avatar
legoc committed
877
878
879
880
881
882
883
884
885
	}

	try {
		return instance.m_server->createSubscriber(instance.m_id, publisherName, instance.m_name);

	} catch (const SubscriberCreationException& e) {
		// that should not happen
	}

legoc's avatar
legoc committed
886
	return unique_ptr<Subscriber>(nullptr);
legoc's avatar
legoc committed
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
}

void Subscriber::init() {
	m_impl->init();

	// Create the waiting here.
	m_waiting.reset(m_impl->waiting());
}

const std::string& Subscriber::getPublisherName() const {
	return m_impl->m_publisherName;
}

const std::string& Subscriber::getInstanceName() const {
	return m_impl->m_instanceName;
}

int Subscriber::getInstanceId() const {
	return m_impl->m_instanceId;
}

const std::string& Subscriber::getInstanceEndpoint() const {
	return m_impl->m_instanceEndpoint;
}

bool Subscriber::hasEnded() const {
913
914
915
916
917
918
919
920
921
	return m_impl->isEnded();
}

bool Subscriber::isEnded() const {
	return m_impl->isEnded();
}

bool Subscriber::isCanceled() const {
	return m_impl->isCanceled();
legoc's avatar
legoc committed
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
}

bool Subscriber::receiveBinary(std::string& data) const {
	return m_impl->receiveBinary(data);
}

bool Subscriber::receive(std::string& data) const {
	return m_impl->receive(data);
}

bool Subscriber::receive(std::vector<int32_t>& data) const {
	return m_impl->receive(data);
}

bool Subscriber::receive(std::vector<int64_t>& data) const {
	return m_impl->receive(data);
}

bool Subscriber::receive(std::vector<float>& data) const {
	return m_impl->receive(data);
}

bool Subscriber::receive(std::vector<double>& data) const {
	return m_impl->receive(data);
}

948
949
950
951
bool Subscriber::receiveTwoBinaryParts(std::string& data1, std::string& data2) const {
	return m_impl->receiveTwoBinaryParts(data1, data2);
}

legoc's avatar
legoc committed
952
953
954
955
956
957
958
void Subscriber::cancel() {
	m_waiting->cancel();
}

///////////////////////////////////////////////////////////////////////////
// Request

legoc's avatar
legoc committed
959
960
Request::Request(std::unique_ptr<RequestImpl> & impl) :
	m_impl(std::move(impl)) {
legoc's avatar
legoc committed
961
962
963
964
965
}

Request::~Request() {
}

966
const std::string& Request::getBinary() const {
legoc's avatar
legoc committed
967
968
969
	return m_impl->m_message;
}

970
std::string Request::get() const {
legoc's avatar
legoc committed
971
972
973
974
975
976
977

	string data;
	parse(m_impl->m_message, data);

	return data;
}

978
979
980
981
const std::string& Request::getSecondBinaryPart() const {
	return m_impl->m_message2;
}

legoc's avatar
legoc committed
982
983
void Request::replyBinary(const std::string& response) {
	m_impl->replyBinary(response);
legoc's avatar
legoc committed
984
985
}

legoc's avatar
legoc committed
986
987
void Request::reply(const std::string& response) {
	m_impl->reply(response);
legoc's avatar
legoc committed
988
989
}

legoc's avatar
legoc committed
990
std::unique_ptr<Instance> Request::connectToRequester() {
991

legoc's avatar
legoc committed
992
	// Instantiate the requester server if it does not exist.
legoc's avatar
legoc committed
993
	if (m_requesterServer.get() == nullptr) {
legoc's avatar
legoc committed
994
995
		m_requesterServer.reset(new Server(m_impl->m_requesterServerEndpoint));
	}
996
997
998
999
1000

	// Connect and find the instance.
	InstanceArray instances = m_requesterServer->connectAll(m_impl->m_requesterApplicationName);

	for (int i = 0; i < instances.size(); i++) {
For faster browsing, not all history is shown. View entire blame