Application.cpp 31.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 "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
#include "message/JSON.h"
#include "message/Message.h"
38
39
40
#include "Server.h"
#include "StarterServerException.h"
#include "StatusEvent.h"
41
42
43
44
#include "PublisherEvent.h"
#include "ResultEvent.h"
#include "PortEvent.h"
#include "CancelEvent.h"
legoc's avatar
legoc committed
45
46
47
48
49
50

using namespace std;

namespace cameo {
namespace application {

51
This This::m_instance;
legoc's avatar
legoc committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
69
		return FAILURE;
legoc's avatar
legoc committed
70
71
72
73
74
75
76
77
78
79
80
81
	} 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
82
	if (m_instance.m_impl == nullptr) {
83
		m_instance.initApplication(argc, argv);
legoc's avatar
legoc committed
84
85
86
87
	}
}

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

void This::terminate() {
97
98

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

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

108
109
110
111
	// Terminate the services.
	m_instance.Services::terminate();

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

115
116

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

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

125
	Services::init();
legoc's avatar
legoc committed
126
127

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

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

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

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

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

144
145
146
	// 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
147
148
	m_serverEndpoint = m_url + ":" + port;

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

152
153
154
	// Retrieve the server version.
	Services::retrieveServerVersion();

legoc's avatar
legoc committed
155
156
157
	string nameId = tokens[3];

	int index = nameId.find_last_of('.');
legoc's avatar
legoc committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172

	// 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();
173
174
175
176

		if (m_id == -1) {
			throw UnmanagedApplicationException(string("Maximum number of applications ") + m_name + " reached");
		}
legoc's avatar
legoc committed
177
178
179
180
181
182
183
184
	}

	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
185
		string sid = starterNameId.substr(index + 1);
legoc's avatar
legoc committed
186
187
188
189
190
191
		{
			istringstream is(sid);
			is >> m_starterId;
		}
	}

legoc's avatar
legoc committed
192
193
	// Must be here because the server endpoint is required.
	initStatus();
legoc's avatar
legoc committed
194
195

	// Create the local server
legoc's avatar
legoc committed
196
	m_server = unique_ptr<Server>(new Server(m_serverEndpoint));
legoc's avatar
legoc committed
197
198
199

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

legoc's avatar
legoc committed
203
	m_waitingSet = unique_ptr<WaitingImplSet>(new WaitingImplSet());
204
205
206
207

	// Init listener.
	setName(m_name);
	m_server->registerEventListener(this);
legoc's avatar
legoc committed
208
209
210
211
}

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

	// Terminate the unmanaged application.
legoc's avatar
legoc committed
214
	if (m_impl != nullptr && !m_managed) {
215
216
		terminateUnmanagedApplication();
	}
legoc's avatar
legoc committed
217
218
219
}

const std::string& This::getName() {
220
	return m_instance.m_name;
legoc's avatar
legoc committed
221
222
223
}

int This::getId() {
224
	return m_instance.m_id;
legoc's avatar
legoc committed
225
226
227
}

void This::setTimeout(int timeout) {
228
	m_instance.Services::setTimeout(timeout);
legoc's avatar
legoc committed
229
230
231
}

int This::getTimeout() {
232
	return m_instance.Services::getTimeout();
legoc's avatar
legoc committed
233
234
}

235
const std::string& This::getEndpoint() {
legoc's avatar
legoc committed
236
	if (m_instance.m_impl != nullptr) {
237
		return m_instance.m_serverEndpoint;
legoc's avatar
legoc committed
238
239
240
241
242
243
	}
	static string result;
	return result;
}

Server& This::getServer() {
244
	return *m_instance.m_server;
legoc's avatar
legoc committed
245
246
247
248
}

Server& This::getStarterServer() {

legoc's avatar
legoc committed
249
	if (m_instance.m_starterServer.get() == nullptr) {
legoc's avatar
legoc committed
250
251
252
		throw StarterServerException();
	}

253
	return *m_instance.m_starterServer;
legoc's avatar
legoc committed
254
255
256
}

const std::string& This::getUrl() {
257
	return m_instance.Services::getUrl();
legoc's avatar
legoc committed
258
259
260
}

bool This::isAvailable(int timeout) {
261
	return m_instance.Services::isAvailable(timeout);
legoc's avatar
legoc committed
262
263
264
}

bool This::isStopping() {
265
	return m_instance.getState(m_instance.m_id) == STOPPING;
legoc's avatar
legoc committed
266
267
268
}

void This::cancelWaitings() {
269
	m_instance.m_waitingSet->cancelAll();
legoc's avatar
legoc committed
270
271
}

legoc's avatar
legoc committed
272
int This::initUnmanagedApplication() {
legoc's avatar
legoc committed
273

274
	unique_ptr<zmq::message_t> reply = m_requestSocket->request(m_impl->createStartedUnmanagedRequest(m_name));
legoc's avatar
legoc committed
275

276
277
278
	// Get the JSON response.
	json::Object response;
	json::parse(response, reply.get());
legoc's avatar
legoc committed
279

280
	return response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
281
282
283
284
}

void This::terminateUnmanagedApplication() {

285
	m_requestSocket->request(m_impl->createTerminatedUnmanagedRequest(m_id));
legoc's avatar
legoc committed
286
287
}

288
bool This::setRunning() {
legoc's avatar
legoc committed
289

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

292
293
294
	// Get the JSON response.
	json::Object response;
	json::parse(response, reply.get());
legoc's avatar
legoc committed
295

296
297
	int value = response[message::RequestResponse::VALUE].GetInt();
	if (value == -1) {
298
		return false;
legoc's avatar
legoc committed
299
	}
300
301

	return true;
legoc's avatar
legoc committed
302
303
304
305
}

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

306
	m_instance.m_requestSocket->request(m_instance.m_impl->createSetResultRequest(m_instance.m_id), data);
legoc's avatar
legoc committed
307
308
309
310
311
312
313
314
315
316
317
}

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

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

State This::getState(int id) const {

318
	unique_ptr<zmq::message_t> reply = m_requestSocket->request(m_impl->createGetStatusRequest(id));
legoc's avatar
legoc committed
319

320
321
322
	// Get the JSON response.
	json::Object event;
	json::parse(event, reply.get());
legoc's avatar
legoc committed
323

324
	return event[message::StatusEvent::APPLICATION_STATE].GetInt();
legoc's avatar
legoc committed
325
326
327
328
}

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

329
330
331
332
333
	unique_ptr<zmq::message_t> reply = m_requestSocket->request(m_impl->createTerminatePublisherRequest(m_id, name));

	// Get the JSON response.
	json::Object response;
	json::parse(response, reply.get());
legoc's avatar
legoc committed
334

335
	int value = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
336
337
338
339
340
341

	return (value != -1);
}

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

342
	unique_ptr<zmq::message_t> reply = m_requestSocket->request(m_impl->createRemovePortRequest(m_id, name));
legoc's avatar
legoc committed
343

344
345
346
347
348
	// Get the JSON response.
	json::Object response;
	json::parse(response, reply.get());

	int value = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363

	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
364
		unique_ptr<Event> event = popEvent();
legoc's avatar
legoc committed
365
366

		// The socket is canceled.
legoc's avatar
legoc committed
367
		if (event.get() == nullptr) {
legoc's avatar
legoc committed
368
369
370
371
372
373
			return UNKNOWN;
		}

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

legoc's avatar
legoc committed
374
			if (status != nullptr) {
legoc's avatar
legoc committed
375
376
377
378
379
380
381
382
383
384
385
386
387
				state = status->getState();

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

	return UNKNOWN;
}

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

legoc's avatar
legoc committed
390
391
	if (m_instance.m_starterServer.get() == nullptr) {
		return unique_ptr<Instance>(nullptr);
legoc's avatar
legoc committed
392
393
394
	}

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

	for (int i = 0; i < instances.size(); i++) {
398
		if (instances[i]->getId() == m_instance.m_starterId) {
legoc's avatar
legoc committed
399
			return unique_ptr<Instance>(std::move(instances[i]));
legoc's avatar
legoc committed
400
401
402
		}
	}

legoc's avatar
legoc committed
403
	return unique_ptr<Instance>(nullptr);
legoc's avatar
legoc committed
404
405
}

406
407
408
409
410
411
412
413
414
415
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
416
void This::handleStopImpl(StopFunctionType function) {
417
	m_stopHandler = unique_ptr<HandlerImpl>(new HandlerImpl(bind(&This::stoppingFunction, this, function)));
legoc's avatar
legoc committed
418
419
420
421
422
}

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

423
Instance::Instance(Server * server) :
legoc's avatar
legoc committed
424
425
426
427
428
429
	m_server(server),
	m_id(-1),
	m_pastStates(0),
	m_initialState(UNKNOWN),
	m_lastState(UNKNOWN),
	m_hasResult(false) {
430
431

	m_waiting.reset(new GenericWaitingImpl(bind(&Instance::cancelWaitFor, this)));
legoc's avatar
legoc committed
432
433
434
}

Instance::~Instance() {
435
436
437
438
	// 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
439
440
441
442
443
444
}

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

legoc's avatar
legoc committed
445
446
447
448
const std::string& Instance::getName() const {
	return EventListener::m_name;
}

legoc's avatar
legoc committed
449
450
451
452
void Instance::setErrorMessage(const std::string& message) {
	m_errorMessage = message;
}

legoc's avatar
legoc committed
453
454
455
456
void Instance::setOutputStreamSocket(std::unique_ptr<OutputStreamSocket>& socket) {
	m_outputStreamSocket = std::move(socket);
}

legoc's avatar
legoc committed
457
458
459
460
461
462
void Instance::setPastStates(State pastStates) {
	m_pastStates = pastStates;
}

void Instance::setInitialState(State state) {
	m_initialState = state;
463
464
465

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

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

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

	if (!exists()) {
526
		// The application was not launched
legoc's avatar
legoc committed
527
528
529
		return m_lastState;
	}

530
	// Test the terminal state
legoc's avatar
legoc committed
531
532
533
	if (m_lastState == SUCCESS
		|| m_lastState == STOPPED
		|| m_lastState == KILLED
legoc's avatar
legoc committed
534
		|| m_lastState == FAILURE) {
535
		// The application is already terminated
legoc's avatar
legoc committed
536
537
538
		return m_lastState;
	}

539
	// Test the requested states
legoc's avatar
legoc committed
540
	if ((states & m_pastStates) != 0) {
541
		// The state is already received
legoc's avatar
legoc committed
542
543
544
545
		return m_lastState;
	}

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

549
		// The non-blocking call returns a null message.
legoc's avatar
legoc committed
550
		if (event.get() == nullptr) {
legoc's avatar
legoc committed
551
552
553
554
555
556
			return m_lastState;
		}

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

legoc's avatar
legoc committed
557
			if (status != nullptr) {
legoc's avatar
legoc committed
558
559
560
561
				State state = status->getState();
				m_pastStates = status->getPastStates();
				m_lastState = state;

562
				// Call the state handler.
legoc's avatar
legoc committed
563
				if (handler != nullptr) {
legoc's avatar
legoc committed
564
565
566
					handler(state);
				}

legoc's avatar
legoc committed
567
568
569
570
				// test the terminal state
				if (state == SUCCESS
					|| state == STOPPED
					|| state == KILLED
legoc's avatar
legoc committed
571
					|| state == FAILURE) {
legoc's avatar
legoc committed
572
573
574
575
576
577
578
					break;
				}

				// test the requested states
				if ((states & m_pastStates) != 0) {
					return m_lastState;
				}
579
580
			}
			else {
legoc's avatar
legoc committed
581
582
583
584

				if (ResultEvent * result = dynamic_cast<ResultEvent *>(event.get())) {
					m_hasResult = true;
					m_resultData = result->getData();
585
586
				}
				else if (PublisherEvent * publisher = dynamic_cast<PublisherEvent *>(event.get())) {
legoc's avatar
legoc committed
587
588
589
					if (publisher->getPublisherName() == eventName) {
						break;
					}
590
591
				}
				else if (PortEvent * port = dynamic_cast<PortEvent *>(event.get())) {
legoc's avatar
legoc committed
592
593
594
595
					if (port->getPortName() == eventName) {
						break;
					}
				}
596
597
598
				else if (CancelEvent * cancel = dynamic_cast<CancelEvent *>(event.get())) {
					break;
				}
legoc's avatar
legoc committed
599
600
601
602
603
604
605
			}
		}
	}

	return m_lastState;
}

606
607
608
609
State Instance::waitFor(int states, const std::string& eventName, StateHandlerType handler) {
	return waitFor(states, eventName, handler, true);
}

legoc's avatar
legoc committed
610
611
612
613
614
615
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
616
617
618
}

void Instance::cancelWaitFor() {
619
	cancel(m_id);
legoc's avatar
legoc committed
620
621
}

622
State Instance::now() {
623
624
625
626
627
628
629

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

State Instance::getLastState() {

legoc's avatar
legoc committed
630
	return waitFor(0, "", nullptr, false);
631
632
}

633
634
635
636
637
638
639
640
641
642
643
644
645
646
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
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;
}

legoc's avatar
legoc committed
664
665
666
667
std::shared_ptr<OutputStreamSocket> Instance::getOutputStreamSocket() {
	return m_outputStreamSocket;
}

legoc's avatar
legoc committed
668
669
670
671
672
673
674
675
676
677
///////////////////////////////////////////////////////////////////////////
// InstanceArray

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

InstanceArray::InstanceArray(const InstanceArray& array) :
	m_size(array.m_size),
legoc's avatar
legoc committed
678
	m_array(new unique_ptr<Instance>[m_size]) {
legoc's avatar
legoc committed
679
680
681

	// transferring pointers
	for (size_t i = 0; i < m_size; i++) {
legoc's avatar
legoc committed
682
		m_array[i] = std::move(array.m_array[i]);
legoc's avatar
legoc committed
683
684
685
686
687
688
689
690
691
	}
}

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

void InstanceArray::allocate(std::size_t size) {
	m_size = size;
legoc's avatar
legoc committed
692
	m_array = new unique_ptr<Instance>[size];
legoc's avatar
legoc committed
693
694
695
696
697
698
}

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

legoc's avatar
legoc committed
699
std::unique_ptr<Instance>& InstanceArray::operator[](std::size_t index) {
legoc's avatar
legoc committed
700
701
702
703
704
705
	return m_array[index];
}

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

legoc's avatar
legoc committed
706
Publisher::Publisher(This * application, int publisherPort, int synchronizerPort, const std::string& name, int numberOfSubscribers) :
legoc's avatar
legoc committed
707
708
709
710
711
712
713
714
715
	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
716
std::unique_ptr<Publisher> Publisher::create(const std::string& name, int numberOfSubscribers) {
legoc's avatar
legoc committed
717

718
	unique_ptr<zmq::message_t> reply = This::m_instance.m_requestSocket->request(This::m_instance.m_impl->createCreatePublisherRequest(This::m_instance.m_id, name, numberOfSubscribers));
legoc's avatar
legoc committed
719

720
721
722
	// Get the JSON response.
	json::Object response;
	json::parse(response, reply.get());
legoc's avatar
legoc committed
723

724
	int publisherPort = response[message::PublisherResponse::PUBLISHER_PORT].GetInt();
legoc's avatar
legoc committed
725
	if (publisherPort == -1) {
726
		throw PublisherCreationException(response[message::PublisherResponse::MESSAGE].GetString());
legoc's avatar
legoc committed
727
	}
728
	int synchronizerPort = response[message::PublisherResponse::SYNCHRONIZER_PORT].GetInt();;
legoc's avatar
legoc committed
729

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


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

766
767
768
769
void Publisher::sendTwoBinaryParts(const std::string& data1, const std::string& data2) const {
	m_impl->sendTwoBinaryParts(data1, data2);
}

legoc's avatar
legoc committed
770
bool Publisher::hasEnded() const {
771
772
773
774
775
	return m_impl->isEnded();
}

bool Publisher::isEnded() const {
	return m_impl->isEnded();
legoc's avatar
legoc committed
776
777
778
779
780
781
782
783
784
}

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

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

785
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
786
787
788
789
790
791
	m_impl(new SubscriberImpl(server, url, publisherPort, synchronizerPort, publisherName, numberOfSubscribers, instanceName, instanceId, instanceEndpoint, statusEndpoint)) {
}

Subscriber::~Subscriber() {
}

legoc's avatar
legoc committed
792
std::unique_ptr<Subscriber> Subscriber::create(Instance & instance, const std::string& publisherName) {
legoc's avatar
legoc committed
793
794
795
796
797
798
799
800
801
802
803
804
805
806
	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
807
		|| lastState == FAILURE) {
legoc's avatar
legoc committed
808
		return unique_ptr<Subscriber>(nullptr);
legoc's avatar
legoc committed
809
810
811
812
813
814
815
816
817
	}

	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
818
	return unique_ptr<Subscriber>(nullptr);
legoc's avatar
legoc committed
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
}

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 {
845
846
847
848
849
850
851
852
853
	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
854
855
856
857
858
859
860
861
862
863
}

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

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

864
865
866
867
bool Subscriber::receiveTwoBinaryParts(std::string& data1, std::string& data2) const {
	return m_impl->receiveTwoBinaryParts(data1, data2);
}

legoc's avatar
legoc committed
868
869
870
871
872
873
874
void Subscriber::cancel() {
	m_waiting->cancel();
}

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

legoc's avatar
legoc committed
875
876
Request::Request(std::unique_ptr<RequestImpl> & impl) :
	m_impl(std::move(impl)) {
legoc's avatar
legoc committed
877
878
879
880
881
}

Request::~Request() {
}

legoc's avatar
legoc committed
882
883
884
885
886
887
888
889
890
891
892
std::string Request::getObjectId() const {

	// Local id is missing.
	return "request:"
		+ m_impl->m_requesterApplicationName
		+ "."
		+ to_string(m_impl->m_requesterApplicationId)
		+ "@"
		+ m_impl->m_requesterServerEndpoint;
}

893
894
895
896
std::string Request::getRequesterEndpoint() const {
	return m_impl->m_requesterServerEndpoint;
}

legoc's avatar
legoc committed
897
898
void Request::setTimeout(int value) {
	m_impl->setTimeout(value);
899
900
}

901
const std::string& Request::getBinary() const {
legoc's avatar
legoc committed
902
903
904
	return m_impl->m_message;
}

905
std::string Request::get() const {
legoc's avatar
legoc committed
906
907
908
909
910
911
912

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

	return data;
}

913
914
915
916
const std::string& Request::getSecondBinaryPart() const {
	return m_impl->m_message2;
}

legoc's avatar
legoc committed
917
918
bool Request::replyBinary(const std::string& response) {
	return m_impl->replyBinary(response);
legoc's avatar
legoc committed
919
920
}

legoc's avatar
legoc committed
921
922
bool Request::reply(const std::string& response) {
	return m_impl->reply(response);
legoc's avatar
legoc committed
923
924
}

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

legoc's avatar
legoc committed
927
	// Instantiate the requester server if it does not exist.
legoc's avatar
legoc committed
928
	if (m_requesterServer.get() == nullptr) {
929
		m_requesterServer.reset(new Server(m_impl->m_requesterServerEndpoint, m_impl->m_timeout));
legoc's avatar
legoc committed
930
	}
931
932
933
934
935
936

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

	for (int i = 0; i < instances.size(); i++) {
		if (instances[i]->getId() == m_impl->m_requesterApplicationId) {
legoc's avatar
legoc committed
937
			return unique_ptr<Instance>(std::move(instances[i]));
938
939
940
941
		}
	}

	// Not found.
legoc's avatar
legoc committed
942
	return unique_ptr<Instance>(nullptr);
943
944
}

legoc's avatar
legoc committed
945
946
std::unique_ptr<Server> Request::getServer() {
	return std::move(m_requesterServer);
legoc's avatar
legoc committed
947
948
}

legoc's avatar
legoc committed
949
950
951
///////////////////////////////////////////////////////////////////////////
// Responder

legoc's avatar
legoc committed
952
Responder::Responder(application::This * application, int responderPort, const std::string& name) :
legoc's avatar
legoc committed
953
954
955
956
957
958
959
960
961
	m_impl(new ResponderImpl(application, responderPort, name)) {

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

Responder::~Responder() {
}

legoc's avatar
legoc committed
962
std::unique_ptr<Responder> Responder::create(const std::string& name) {
legoc's avatar
legoc committed
963
964
965

	string portName = ResponderImpl::RESPONDER_PREFIX + name;

966
	unique_ptr<zmq::message_t> reply = This::m_instance.m_requestSocket->request(This::m_instance.m_impl->createRequestPortRequest(This::m_instance.m_id, portName));
legoc's avatar
legoc committed
967

968
969
970
	// Get the JSON response.
	json::Object response;
	json::parse(response, reply.get());
legoc's avatar
legoc committed
971

972
	int responderPort = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
973
	if (responderPort == -1) {
974
		throw ResponderCreationException(response[message::RequestResponse::MESSAGE].GetString());
legoc's avatar
legoc committed
975
976
	}

legoc's avatar
legoc committed
977
	return unique_ptr<Responder>(new Responder(&This::m_instance, responderPort, name));
legoc's avatar
legoc committed
978
979
980
981
982
983
984
985
986
987
}

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

void Responder::cancel() {
	m_impl->cancel();
}

legoc's avatar
legoc committed
988
std::unique_ptr<Request> Responder::receive() {
legoc's avatar
legoc committed
989

legoc's avatar
legoc committed
990
991
992
	unique_ptr<RequestImpl> requestImpl = m_impl->receive();
	if (requestImpl.get() == nullptr) {
		return unique_ptr<Request>(nullptr);
legoc's avatar
legoc committed
993
	}
legoc's avatar
legoc committed
994
	return unique_ptr<Request>(new Request(requestImpl));
legoc's avatar
legoc committed
995
996
}

997
998
bool Responder::isCanceled() const {
	return m_impl->m_canceled;
legoc's avatar
legoc committed
999
1000
1001
1002
1003
}

///////////////////////////////////////////////////////////////////////////
// Requester

legoc's avatar
legoc committed
1004
Requester::Requester(application::This * application, const std::string& url, int requesterPort, int responderPort, const std::string& name, int responderId, int requesterId) :
1005
	m_impl(new RequesterImpl(application, url, requesterPort, responderPort, name, responderId, requesterId)) {
legoc's avatar
legoc committed
1006
1007
1008
1009
1010
1011
1012
1013

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

Requester::~Requester() {
}

legoc's avatar
legoc committed
1014
std::unique_ptr<Requester> Requester::create(Instance & instance, const std::string& name) {
legoc's avatar
legoc committed
1015
1016
1017
1018
1019

	int responderId = instance.getId();
	string responderUrl = instance.getUrl();
	string responderEndpoint = instance.getEndpoint();

legoc's avatar
legoc committed
1020
1021
1022
	// Create a request socket to the server of the instance.
	unique_ptr<RequestSocketImpl> instanceRequestSocket = This::m_instance.createRequestSocket(responderEndpoint);

legoc's avatar
legoc committed
1023
	string responderPortName = ResponderImpl::RESPONDER_PREFIX + name;
1024
1025
	int requesterId = RequesterImpl::newRequesterId();
	string requesterPortName = RequesterImpl::getRequesterPortName(name, responderId, requesterId);
legoc's avatar
legoc committed
1026

1027
1028
1029
	string request = This::m_instance.m_impl->createConnectPortRequest(responderId, responderPortName);

	unique_ptr<zmq::message_t> reply = instanceRequestSocket->request(request);
legoc's avatar
legoc committed
1030

1031
1032
1033
	// Get the JSON response.
	json::Object response;
	json::parse(response, reply.get());
legoc's avatar
legoc committed
1034

1035
	reply.reset();
legoc's avatar
legoc committed
1036

1037
	int responderPort = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
1038
1039
1040
1041
1042
	if (responderPort == -1) {
		// Wait for the responder port.
		instance.waitFor(0, responderPortName);

		// Retry to connect.
1043
1044
		reply = instanceRequestSocket->request(request);
		json::parse(response, reply.get());
legoc's avatar
legoc committed
1045

1046
		responderPort = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
1047
		if (responderPort == -1) {
1048
			throw RequesterCreationException(response[message::RequestResponse::MESSAGE].GetString());
legoc's avatar
legoc committed
1049
		}
1050
1051

		reply.reset();
legoc's avatar
legoc committed
1052
1053
	}

1054
	// Request a requester port.
1055
1056
	reply = This::m_instance.m_requestSocket->request(This::m_instance.m_impl->createRequestPortRequest(This::m_instance.m_id, requesterPortName));
	json::parse(response, reply.get());
legoc's avatar
legoc committed
1057

1058
	int requesterPort = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
1059
	if (requesterPort == -1) {
1060
		throw RequesterCreationException(response[message::RequestResponse::MESSAGE].GetString());
legoc's avatar
legoc committed
1061
1062
	}

legoc's avatar
legoc committed
1063
	return unique_ptr<Requester>(new Requester(&This::m_instance, responderUrl, requesterPort, responderPort, name, responderId, requesterId));
legoc's avatar
legoc committed
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
}

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

void Requester::sendBinary(const std::string& request) {
	m_impl->sendBinary(request);
}

void Requester::send(const std::string& request) {
	m_impl->send(request);
}

1078
1079
1080
1081
void Requester::sendTwoBinaryParts(const std::string& request1, const std::string& request2) {
	m_impl->sendTwoBinaryParts(request1, request2);
}

legoc's avatar
legoc committed
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
bool Requester::receiveBinary(std::string& response) {
	return m_impl->receiveBinary(response);
}

bool Requester::receive(std::string& response) {
	return m_impl->receive(response);
}

void Requester::cancel() {
	m_impl->cancel();
}

1094
1095
1096
1097
bool Requester::isCanceled() const {
	return m_impl->m_canceled;
}

legoc's avatar
legoc committed
1098
1099
1100
///////////////////////////////////////////////////////////////////////////
// Configuration

1101
Configuration::Configuration(const std::string& name, const std::string& description, bool singleInstance, bool restart, int startingTime, int stoppingTime) {
legoc's avatar
legoc committed
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137

	m_name = name;
	m_description = description;
	m_singleInstance = singleInstance;
	m_restart = restart;
	m_startingTime = startingTime;
	m_stoppingTime = stoppingTime;
}

const std::string& Configuration::getName() const {
	return m_name;
}

const std::string& Configuration::getDescription() const {
	return m_description;
}

bool Configuration::hasSingleInstance() const {
	return m_singleInstance;
}

bool Configuration::canRestart() const {
	return m_restart;
}

int Configuration::getStartingTime() const {
	return m_startingTime;
}

int Configuration::getStoppingTime() const {
	return m_stoppingTime;
}

///////////////////////////////////////////////////////////////////////////
// Info

legoc's avatar
legoc committed
1138
Info::Info(const std::string& name, int id, int pid, State applicationState, State pastApplicationStates, const std::string& args) :
legoc's avatar
legoc committed
1139
	m_id(id),
legoc's avatar
legoc committed
1140
	m_pid(pid),
legoc's avatar
legoc committed
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
	m_applicationState(applicationState),
	m_pastApplicationStates(pastApplicationStates),
	m_args(args),
	m_name(name) {
}

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

State Info::getState() const {
	return m_applicationState;
}

State Info::getPastStates() const {
	return m_pastApplicationStates;
}

const std::string& Info::getArgs() const {
	return m_args;
}

const std::string& Info::getName() const {
	return m_name;
}

legoc's avatar
legoc committed
1167
1168
1169
int Info::getPid() const {
	return m_pid;
}
legoc's avatar
legoc committed
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194

std::string toString(cameo::application::State applicationStates) {

	vector<string> states;

	if ((applicationStates & STARTING) != 0) {
		states.push_back("STARTING");
	}

	if ((applicationStates & RUNNING) != 0) {
		states.push_back("RUNNING");
	}

	if ((applicationStates & STOPPING) != 0) {
		states.push_back("STOPPING");
	}

	if ((applicationStates & KILLING) != 0) {
		states.push_back("KILLING");
	}

	if ((applicationStates & PROCESSING_ERROR) != 0) {
		states.push_back("PROCESSING_ERROR");
	}

legoc's avatar
legoc committed
1195
	if ((applicationStates & FAILURE) != 0) {
legoc's avatar
legoc committed
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
		states.push_back("ERROR");
	}

	if ((applicationStates & SUCCESS) != 0) {
		states.push_back("SUCCESS");
	}

	if ((applicationStates & STOPPED) != 0) {
		states.push_back("STOPPED");
	}

	if ((applicationStates & KILLED) != 0) {
		states.push_back("KILLED");
	}

	if (states.size() == 0) {
		return "UNKNOWN";
	}

	if (states.size() == 1) {
		return states.front();
	}

	ostringstream result;

	for (int i = 0; i < states.size() - 1; i++) {
		result << states[i] << ", ";
	}
	result << states.back();

	return result.str();
}

///////////////////////////////////////////////////////////////////////////////
// operator<<

std::ostream& operator<<(std::ostream& os, const cameo::application::This& application) {

	os << application.m_name << "." << application.m_id << "@" << application.m_serverEndpoint;

	return os;
}

std::ostream& operator<<(std::ostream& os, const application::Instance& instance) {

	os << instance.m_name << "." << instance.m_id << "@" << instance.m_server->getEndpoint();

	return os;
}

std::ostream& operator<<(std::ostream& os, const application::Publisher& publisher) {

	os << "pub." << publisher.getName()
		<< ":" << publisher.getApplicationName()
		<< "." << publisher.getApplicationId()
		<< "@" << publisher.getApplicationEndpoint();

	return os;
}

std::ostream& operator<<(std::ostream& os, const application::Subscriber& subscriber) {

	os << "sub." << subscriber.getPublisherName()
		<< ":" << subscriber.getInstanceName()
		<< "." << subscriber.getInstanceId()
		<< "@" << subscriber.getInstanceEndpoint();

	return os;
}

std::ostream& operator<<(std::ostream& os, const application::Request& request) {

	os << "[endpoint=" << request.m_impl->m_requesterEndpoint
			<< ", id=" << request.m_impl->m_requesterApplicationId << "]";

	return os;
}

std::ostream& operator<<(std::ostream& os, const application::Responder& responder) {

	os << "rep." << responder.getName()
		<< ":" << responder.m_impl->m_application->getName()
		<< "." << responder.m_impl->m_application->getId()
1279
		<< "@" << responder.m_impl->m_application->getEndpoint();
legoc's avatar
legoc committed
1280
1281
1282
1283
1284
1285
1286

	return os;
}

std::ostream& operator<<(std::ostream& os, const application::Requester& requester) {

	os << "req." << requester.getName()
1287
		<< "." << requester.m_impl->m_requesterId
legoc's avatar
legoc committed
1288
1289
		<< ":" << requester.m_impl->m_application->getName()
		<< "." << requester.m_impl->m_application->getId()
1290
		<< "@" << requester.m_impl->m_application->getEndpoint();
legoc's avatar
legoc committed
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318

	return os;
}

std::ostream& operator<<(std::ostream& os, const application::Configuration& info) {

	os << "[name=" << info.m_name
			<< ", description=" << info.m_description
			<< ", single instance=" << info.m_singleInstance
			<< ", restart=" << info.m_restart
			<< ", starting time=" << info.m_startingTime
			<< ", stopping time=" << info.m_stoppingTime << "]";

	return os;
}

std::ostream& operator<<(std::ostream& os, const application::Info& info) {

	os << "[name=" << info.m_name
			<< ", id=" << info.m_id
			<< ", state=" << info.m_applicationState
			<< ", args=" << info.m_args << "]";

	return os;
}

}
}