Application.cpp 34.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
25

#include "JSON.h"
26
#include "EventStreamSocket.h"
27
#include "impl/ServicesImpl.h"
28
29
30
31
32
33
34
#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"
35
#include "impl/HandlerImpl.h"
36
#include "impl/StreamSocketImpl.h"
legoc's avatar
legoc committed
37
#include "impl/RequestSocketImpl.h"
38
#include "message/Message.h"
39
#include "Strings.h"
40
41
42
#include "Server.h"
#include "StarterServerException.h"
#include "StatusEvent.h"
43
44
45
#include "PublisherEvent.h"
#include "ResultEvent.h"
#include "PortEvent.h"
46
#include "KeyEvent.h"
47
#include "CancelEvent.h"
legoc's avatar
legoc committed
48
49
50
51
52
53

using namespace std;

namespace cameo {
namespace application {

54
This This::m_instance;
legoc's avatar
legoc committed
55
56
const std::string This::RUNNING_STATE = "RUNNING";

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
This::Com::Com(Server * server, int applicationId) :
	m_server(server),
	m_applicationId(applicationId) {
}

void This::Com::storeKeyValue(const std::string& key, const std::string& value) const {
	m_server->storeKeyValue(m_applicationId, key, value);
}
std::string This::Com::getKeyValue(const std::string& key) const {
	return m_server->getKeyValue(m_applicationId, key);
}

void This::Com::removeKey(const std::string& key) const {
	m_server->removeKey(m_applicationId, key);
}

73
74
75
76
77
78
79
80
81
82
83
84
int This::Com::requestPort() const {
	return m_server->requestPort(m_applicationId);
}

void This::Com::setPortUnavailable(int port) const {
	m_server->setPortUnavailable(m_applicationId, port);
}

void This::Com::releasePort(int port) const {
	m_server->releasePort(m_applicationId, port);
}

legoc's avatar
legoc committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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
100
		return FAILURE;
legoc's avatar
legoc committed
101
102
103
104
105
106
107
108
109
110
111
112
	} 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
113
	if (m_instance.m_impl == nullptr) {
114
		m_instance.initApplication(argc, argv);
legoc's avatar
legoc committed
115
116
117
	}
}

118
119
120
121
122
123
void This::init(const std::string& name, const std::string& endpoint) {
	if (m_instance.m_impl == nullptr) {
		m_instance.initApplication(name, endpoint);
	}
}

legoc's avatar
legoc committed
124
void This::terminate() {
125
126

	// Test if termination is already done.
legoc's avatar
legoc committed
127
	if (m_instance.m_impl == nullptr) {
128
129
130
131
132
133
		return;
	}

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

136
137
138
139
	// Terminate the services.
	m_instance.Services::terminate();

	// Ensure that it won't be done twice.
legoc's avatar
legoc committed
140
	m_instance.m_impl = nullptr;
legoc's avatar
legoc committed
141
142
}

143
144

This::This() :
legoc's avatar
legoc committed
145
	Services(),
legoc's avatar
legoc committed
146
147
148
	m_id(-1),
	m_managed(false),
	m_starterId(0) {
149
150
151
}

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

153
	Services::init();
legoc's avatar
legoc committed
154
155

	if (argc == 0) {
156
		throw InvalidArgumentException("Missing info argument");
legoc's avatar
legoc committed
157
158
159
160
	}

	string info(argv[argc - 1]);

legoc's avatar
legoc committed
161
	// Get the info object.
162
	json::Object infoObject;
163
164
165
	if (!json::parse(infoObject, info)) {
		throw InvalidArgumentException("Bad format for info argument");
	}
legoc's avatar
legoc committed
166

167
	m_serverEndpoint = Endpoint::parse(infoObject[message::ApplicationIdentity::SERVER].GetString());
legoc's avatar
legoc committed
168

169
170
171
	// Create the request socket. The server endpoint has been defined.
	Services::initRequestSocket();

172
173
174
	// Retrieve the server version.
	Services::retrieveServerVersion();

legoc's avatar
legoc committed
175
	// Get the name.
176
	m_name = infoObject[message::ApplicationIdentity::NAME].GetString();
legoc's avatar
legoc committed
177

legoc's avatar
legoc committed
178
	// Managed apps have the id key.
179
	if (infoObject.HasMember(message::ApplicationIdentity::ID)) {
legoc's avatar
legoc committed
180
		m_managed = true;
181
		m_id = infoObject[message::ApplicationIdentity::ID].GetInt();
legoc's avatar
legoc committed
182
183
184
	}
	else {
		m_managed = false;
legoc's avatar
legoc committed
185
186
		int id = initUnmanagedApplication();
		if (id == -1) {
187
188
			throw UnmanagedApplicationException(string("Maximum number of applications ") + m_name + " reached");
		}
legoc's avatar
legoc committed
189
		m_id = id;
legoc's avatar
legoc committed
190
191
	}

legoc's avatar
legoc committed
192
193
194
195
196
197
198
	// Get the starter info if it is present.
	if (infoObject.HasMember(message::ApplicationIdentity::STARTER)) {
		json::Value& starterValue = infoObject[message::ApplicationIdentity::STARTER];
		m_starterEndpoint = Endpoint::parse(starterValue[message::ApplicationIdentity::SERVER].GetString());
		m_starterName = starterValue[message::ApplicationIdentity::NAME].GetString();
		m_starterId = starterValue[message::ApplicationIdentity::ID].GetInt();
	}
legoc's avatar
legoc committed
199

legoc's avatar
legoc committed
200
201
	// Must be here because the server endpoint is required.
	initStatus();
legoc's avatar
legoc committed
202

legoc's avatar
legoc committed
203
	// Create the local server.
legoc's avatar
legoc committed
204
	m_server = unique_ptr<Server>(new Server(m_serverEndpoint));
legoc's avatar
legoc committed
205

legoc's avatar
legoc committed
206
207
	// Create the starter server.
	if (m_starterEndpoint.getAddress() != "") {
legoc's avatar
legoc committed
208
		m_starterServer = unique_ptr<Server>(new Server(m_starterEndpoint));
legoc's avatar
legoc committed
209
210
	}

legoc's avatar
legoc committed
211
	m_waitingSet = unique_ptr<WaitingImplSet>(new WaitingImplSet());
212
213
214
215

	// Init listener.
	setName(m_name);
	m_server->registerEventListener(this);
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
	// Init com.
	m_com = unique_ptr<Com>(new Com(m_server.get(), m_id));
}

void This::initApplication(const std::string& name, const std::string& endpoint) {

	Services::init();

	// Get the server endpoint.
	m_serverEndpoint = Endpoint::parse(endpoint);

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

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

	// Get the name.
	m_name = name;

	// The application is de-facto unmanaged.
	m_managed = false;

	int id = initUnmanagedApplication();
	if (id == -1) {
		throw UnmanagedApplicationException(string("Maximum number of applications ") + m_name + " reached");
	}
	m_id = id;

	// Must be here because the server endpoint is required.
	initStatus();

	// Create the local server.
	m_server = unique_ptr<Server>(new Server(m_serverEndpoint));

	// Create the waiting set.
	m_waitingSet = unique_ptr<WaitingImplSet>(new WaitingImplSet());

	// Init listener.
	setName(m_name);
	m_server->registerEventListener(this);
258
259
260

	// Init com.
	m_com = unique_ptr<Com>(new Com(m_server.get(), m_id));
legoc's avatar
legoc committed
261
262
263
264
}

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

	// Terminate the unmanaged application.
legoc's avatar
legoc committed
267
	if (m_impl != nullptr && !m_managed) {
268
269
		terminateUnmanagedApplication();
	}
legoc's avatar
legoc committed
270
271
272
}

const std::string& This::getName() {
273
	return m_instance.m_name;
legoc's avatar
legoc committed
274
275
276
}

int This::getId() {
277
	return m_instance.m_id;
legoc's avatar
legoc committed
278
279
280
}

void This::setTimeout(int timeout) {
281
	m_instance.Services::setTimeout(timeout);
legoc's avatar
legoc committed
282
283
284
}

int This::getTimeout() {
285
	return m_instance.Services::getTimeout();
legoc's avatar
legoc committed
286
287
}

288
const Endpoint& This::getEndpoint() {
legoc's avatar
legoc committed
289
	if (m_instance.m_impl != nullptr) {
290
		return m_instance.m_serverEndpoint;
legoc's avatar
legoc committed
291
	}
292
	static Endpoint result;
legoc's avatar
legoc committed
293
294
295
296
	return result;
}

Server& This::getServer() {
297
	return *m_instance.m_server;
legoc's avatar
legoc committed
298
299
}

300
301
302
303
const This::Com& This::getCom() {
	return *m_instance.m_com;
}

legoc's avatar
legoc committed
304
305
Server& This::getStarterServer() {

legoc's avatar
legoc committed
306
	if (m_instance.m_starterServer.get() == nullptr) {
legoc's avatar
legoc committed
307
308
309
		throw StarterServerException();
	}

310
	return *m_instance.m_starterServer;
legoc's avatar
legoc committed
311
312
313
}

bool This::isAvailable(int timeout) {
314
	return m_instance.Services::isAvailable(timeout);
legoc's avatar
legoc committed
315
316
317
}

bool This::isStopping() {
318
	return m_instance.getState(m_instance.m_id) == STOPPING;
legoc's avatar
legoc committed
319
320
321
}

void This::cancelWaitings() {
322
	m_instance.m_waitingSet->cancelAll();
legoc's avatar
legoc committed
323
324
}

legoc's avatar
legoc committed
325
int This::initUnmanagedApplication() {
legoc's avatar
legoc committed
326

327
	unique_ptr<zmq::message_t> reply = m_requestSocket->request(m_impl->createAttachUnmanagedRequest(m_name));
legoc's avatar
legoc committed
328

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

333
	return response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
334
335
336
337
}

void This::terminateUnmanagedApplication() {

338
	m_requestSocket->request(m_impl->createDetachUnmanagedRequest(m_id));
legoc's avatar
legoc committed
339
340
}

341
bool This::setRunning() {
legoc's avatar
legoc committed
342

343
	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
344

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

349
350
	int value = response[message::RequestResponse::VALUE].GetInt();
	if (value == -1) {
351
		return false;
legoc's avatar
legoc committed
352
	}
353
354

	return true;
legoc's avatar
legoc committed
355
356
357
358
}

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

359
	m_instance.m_requestSocket->request(m_instance.m_impl->createSetResultRequest(m_instance.m_id), data);
legoc's avatar
legoc committed
360
361
362
363
364
365
366
367
368
369
370
}

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

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

State This::getState(int id) const {

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

373
374
375
	// Get the JSON response.
	json::Object event;
	json::parse(event, reply.get());
legoc's avatar
legoc committed
376

377
	return event[message::StatusEvent::APPLICATION_STATE].GetInt();
legoc's avatar
legoc committed
378
379
380
381
}

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

382
383
384
385
386
	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
387

388
	int value = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
389
390
391
392
393
394

	return (value != -1);
}

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

395
	unique_ptr<zmq::message_t> reply = m_requestSocket->request(m_impl->createRemovePortV0Request(m_id, name));
legoc's avatar
legoc committed
396

397
398
399
400
401
	// Get the JSON response.
	json::Object response;
	json::parse(response, reply.get());

	int value = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
402
403
404
405
406
407

	return (value != -1);
}

State This::waitForStop() {

408
409
410
	// The function is executed in a thread in parallel.
	// Do not parallelize the calls to the request socket.
	State state = UNKNOWN;
legoc's avatar
legoc committed
411
412
413

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

		// The socket is canceled.
legoc's avatar
legoc committed
417
		if (event.get() == nullptr) {
legoc's avatar
legoc committed
418
419
420
421
422
423
			return UNKNOWN;
		}

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

legoc's avatar
legoc committed
424
			if (status != nullptr) {
legoc's avatar
legoc committed
425
426
427
428
429
430
431
432
433
434
435
436
437
				state = status->getState();

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

	return UNKNOWN;
}

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

legoc's avatar
legoc committed
440
441
	if (m_instance.m_starterServer.get() == nullptr) {
		return unique_ptr<Instance>(nullptr);
legoc's avatar
legoc committed
442
443
444
	}

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

	for (int i = 0; i < instances.size(); i++) {
448
		if (instances[i]->getId() == m_instance.m_starterId) {
legoc's avatar
legoc committed
449
			return unique_ptr<Instance>(std::move(instances[i]));
legoc's avatar
legoc committed
450
451
452
		}
	}

legoc's avatar
legoc committed
453
	return unique_ptr<Instance>(nullptr);
legoc's avatar
legoc committed
454
455
}

456
457
458
459
460
461
462
463
464
465
void This::stoppingFunction(StopFunctionType stop) {

	application::State state = waitForStop();

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

466
467
468
469
470
471
void This::handleStopImpl(StopFunctionType function, int stoppingTime) {

	// Notify the server.
	m_requestSocket->request(m_impl->createSetStopHandlerRequest(m_id, stoppingTime));

	// Create the handler.
472
	m_stopHandler = unique_ptr<HandlerImpl>(new HandlerImpl(bind(&This::stoppingFunction, this, function)));
legoc's avatar
legoc committed
473
474
475
476
477
}

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

478
479
480
481
482
483
484
485
486
487
Instance::Com::Com(Server * server) :
	m_server(server),
	m_applicationId(-1) {
}

std::string Instance::Com::getKeyValue(const std::string& key) const {
	// TODO catch exceptions and rethrow an exception: TerminatedException?
	return m_server->getKeyValue(m_applicationId, key);
}

488
Instance::Instance(Server * server) :
legoc's avatar
legoc committed
489
490
	m_server(server),
	m_id(-1),
491
	m_com(server),
legoc's avatar
legoc committed
492
493
494
	m_pastStates(0),
	m_initialState(UNKNOWN),
	m_lastState(UNKNOWN),
495
496
	m_hasResult(false),
	m_exitCode(-1) {
497
498

	m_waiting.reset(new GenericWaitingImpl(bind(&Instance::cancelWaitFor, this)));
legoc's avatar
legoc committed
499
500
501
}

Instance::~Instance() {
502
503
504
505
	// 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
506
507
508
509
}

void Instance::setId(int id) {
	m_id = id;
510
	m_com.m_applicationId = id;
legoc's avatar
legoc committed
511
512
}

legoc's avatar
legoc committed
513
514
515
516
const std::string& Instance::getName() const {
	return EventListener::m_name;
}

legoc's avatar
legoc committed
517
518
519
520
void Instance::setErrorMessage(const std::string& message) {
	m_errorMessage = message;
}

legoc's avatar
legoc committed
521
void Instance::setOutputStreamSocket(std::unique_ptr<OutputStreamSocket>& socket) {
522
523
524
525
	if (socket) {
		m_outputStreamSocket = std::move(socket);
		m_outputStreamSocket->setApplicationId(m_id);
	}
legoc's avatar
legoc committed
526
527
}

legoc's avatar
legoc committed
528
529
530
531
532
533
void Instance::setPastStates(State pastStates) {
	m_pastStates = pastStates;
}

void Instance::setInitialState(State state) {
	m_initialState = state;
534
535
536

	// 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
537
538
539
540
541
542
}

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

543
const Endpoint& Instance::getEndpoint() const {
legoc's avatar
legoc committed
544
545
546
547
548
549
550
551
552
553
	return m_server->getEndpoint();
}

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

	return os.str();
}

554
555
556
557
const Instance::Com& Instance::getCom() const {
	return m_com;
}

legoc's avatar
legoc committed
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
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;
}

594
State Instance::waitFor(int states, const std::string& eventName, KeyValue& keyValue, StateHandlerType handler, bool blocking) {
legoc's avatar
legoc committed
595
596

	if (!exists()) {
597
		// The application was not launched
legoc's avatar
legoc committed
598
599
600
		return m_lastState;
	}

601
	// Test the terminal state
legoc's avatar
legoc committed
602
603
604
	if (m_lastState == SUCCESS
		|| m_lastState == STOPPED
		|| m_lastState == KILLED
legoc's avatar
legoc committed
605
		|| m_lastState == FAILURE) {
606
		// The application is already terminated
legoc's avatar
legoc committed
607
608
609
		return m_lastState;
	}

610
	// Test the requested states
legoc's avatar
legoc committed
611
	if ((states & m_pastStates) != 0) {
612
		// The state is already received
legoc's avatar
legoc committed
613
614
615
616
		return m_lastState;
	}

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

620
		// The non-blocking call returns a null message.
legoc's avatar
legoc committed
621
		if (event.get() == nullptr) {
legoc's avatar
legoc committed
622
623
624
625
626
627
			return m_lastState;
		}

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

legoc's avatar
legoc committed
628
			if (status != nullptr) {
legoc's avatar
legoc committed
629
630
631
632
				State state = status->getState();
				m_pastStates = status->getPastStates();
				m_lastState = state;

633
634
635
636
637
				// Assign the exit code.
				if (status->getExitCode() != -1) {
					m_exitCode = status->getExitCode();
				}

638
				// Call the state handler.
legoc's avatar
legoc committed
639
				if (handler != nullptr) {
legoc's avatar
legoc committed
640
641
642
					handler(state);
				}

legoc's avatar
legoc committed
643
644
645
646
				// test the terminal state
				if (state == SUCCESS
					|| state == STOPPED
					|| state == KILLED
legoc's avatar
legoc committed
647
					|| state == FAILURE) {
legoc's avatar
legoc committed
648
649
650
651
652
653
654
					break;
				}

				// test the requested states
				if ((states & m_pastStates) != 0) {
					return m_lastState;
				}
655
656
			}
			else {
legoc's avatar
legoc committed
657
658
659
660

				if (ResultEvent * result = dynamic_cast<ResultEvent *>(event.get())) {
					m_hasResult = true;
					m_resultData = result->getData();
661
662
				}
				else if (PublisherEvent * publisher = dynamic_cast<PublisherEvent *>(event.get())) {
legoc's avatar
legoc committed
663
664
665
					if (publisher->getPublisherName() == eventName) {
						break;
					}
666
667
				}
				else if (PortEvent * port = dynamic_cast<PortEvent *>(event.get())) {
legoc's avatar
legoc committed
668
669
670
671
					if (port->getPortName() == eventName) {
						break;
					}
				}
672
673
674
675
676
677
678
679
680
681
682
683
684
				else if (KeyEvent * keyEvent = dynamic_cast<KeyEvent *>(event.get())) {
					if (keyEvent->getKey() == keyValue.getKey()) {
						// Set the status and value.
						if (keyEvent->getStatus() == KeyEvent::Status::STORED) {
							keyValue.setStatus(KeyValue::Status::STORED);
						}
						else {
							keyValue.setStatus(KeyValue::Status::REMOVED);
						}
						keyValue.setValue(keyEvent->getValue());
						break;
					}
				}
685
686
687
				else if (CancelEvent * cancel = dynamic_cast<CancelEvent *>(event.get())) {
					break;
				}
legoc's avatar
legoc committed
688
689
690
691
692
693
694
			}
		}
	}

	return m_lastState;
}

legoc's avatar
legoc committed
695
State Instance::waitFor(int states, StateHandlerType handler) {
696
697
	KeyValue keyValue("");
	return waitFor(states, "", keyValue, handler, true);
legoc's avatar
legoc committed
698
699
}

700
701
702
703
704
State Instance::waitFor(int states) {
	KeyValue keyValue("");
	return waitFor(states, "", keyValue, nullptr, true);
}

legoc's avatar
legoc committed
705
State Instance::waitFor(StateHandlerType handler) {
706
707
	KeyValue keyValue("");
	return waitFor(0, "", keyValue, handler, true);
708
709
}

710
711
712
713
714
State Instance::waitFor() {
	KeyValue keyValue("");
	return waitFor(0, "", keyValue, nullptr, true);
}

715
State Instance::waitFor(const std::string& eventName) {
716
717
718
719
720
721
	KeyValue keyValue("");
	return waitFor(0, eventName, keyValue, nullptr, true);
}

State Instance::waitFor(KeyValue& keyValue) {
	return waitFor(0, "", keyValue, nullptr, true);
legoc's avatar
legoc committed
722
723
724
}

void Instance::cancelWaitFor() {
725
	cancel(m_id);
legoc's avatar
legoc committed
726
727
}

728
State Instance::now() {
729
730
731
732
733
734

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

State Instance::getLastState() {
735
736
	KeyValue keyValue("");
	return waitFor(0, "", keyValue, nullptr, false);
737
738
}

739
State Instance::getActualState() const {
740
741
	return m_server->getActualState(m_id);
}
742

743
744
std::set<State> Instance::getPastStates() const {
	return m_server->getPastStates(m_id);
745
746
}

747
748
749
750
int Instance::getExitCode() const {
	return m_exitCode;
}

legoc's avatar
legoc committed
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
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
768
769
770
771
std::shared_ptr<OutputStreamSocket> Instance::getOutputStreamSocket() {
	return m_outputStreamSocket;
}

legoc's avatar
legoc committed
772
773
774
///////////////////////////////////////////////////////////////////////////////
// Publisher

legoc's avatar
legoc committed
775
Publisher::Publisher(This * application, int publisherPort, int synchronizerPort, const std::string& name, int numberOfSubscribers) :
legoc's avatar
legoc committed
776
777
778
779
780
781
782
783
784
	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
785
std::unique_ptr<Publisher> Publisher::create(const std::string& name, int numberOfSubscribers) {
legoc's avatar
legoc committed
786

787
	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
788

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

793
	int publisherPort = response[message::PublisherResponse::PUBLISHER_PORT].GetInt();
legoc's avatar
legoc committed
794
	if (publisherPort == -1) {
795
		throw PublisherCreationException(response[message::PublisherResponse::MESSAGE].GetString());
legoc's avatar
legoc committed
796
	}
797
	int synchronizerPort = response[message::PublisherResponse::SYNCHRONIZER_PORT].GetInt();;
legoc's avatar
legoc committed
798

legoc's avatar
legoc committed
799
	return unique_ptr<Publisher>(new Publisher(&This::m_instance, publisherPort, synchronizerPort, name, numberOfSubscribers));
legoc's avatar
legoc committed
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
}


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

815
std::string Publisher::getApplicationEndpoint() const {
legoc's avatar
legoc committed
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
	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);
}

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

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

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

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

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

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

Subscriber::~Subscriber() {
}

legoc's avatar
legoc committed
861
std::unique_ptr<Subscriber> Subscriber::create(Instance & instance, const std::string& publisherName) {
legoc's avatar
legoc committed
862
863
864
865
866
867
868
869
	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
870
	State lastState = instance.waitFor(publisherName);
legoc's avatar
legoc committed
871
872
873
874
875

	// 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
876
		|| lastState == FAILURE) {
legoc's avatar
legoc committed
877
		return unique_ptr<Subscriber>(nullptr);
legoc's avatar
legoc committed
878
879
880
881
882
883
884
885
886
	}

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

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 {
914
915
916
917
918
919
920
921
922
	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
923
924
}

925
926
std::optional<std::string> Subscriber::receiveBinary() const {
	return m_impl->receiveBinary();
legoc's avatar
legoc committed
927
928
}

929
930
std::optional<std::string> Subscriber::receive() const {
	return m_impl->receive();
legoc's avatar
legoc committed
931
932
}

933
934
std::optional<std::tuple<std::string, std::string>> Subscriber::receiveTwoBinaryParts() const {
	return m_impl->receiveTwoBinaryParts();
935
936
}

legoc's avatar
legoc committed
937
938
939
940
941
942
943
void Subscriber::cancel() {
	m_waiting->cancel();
}

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

legoc's avatar
legoc committed
944
945
Request::Request(std::unique_ptr<RequestImpl> & impl) :
	m_impl(std::move(impl)) {
legoc's avatar
legoc committed
946
947
948
949
950
}

Request::~Request() {
}

legoc's avatar
legoc committed
951
952
953
954
955
956
957
958
959
960
961
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;
}

962
963
964
965
std::string Request::getRequesterEndpoint() const {
	return m_impl->m_requesterServerEndpoint;
}

legoc's avatar
legoc committed
966
967
void Request::setTimeout(int value) {
	m_impl->setTimeout(value);
968
969
}

970
const std::string& Request::getBinary() const {
legoc's avatar
legoc committed
971
972
973
	return m_impl->m_message;
}

974
std::string Request::get() const {
legoc's avatar
legoc committed
975
976
977
978
979
980
981

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

	return data;
}

982
983
984
985
const std::string& Request::getSecondBinaryPart() const {
	return m_impl->m_message2;
}

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

legoc's avatar
legoc committed
990
991
bool Request::reply(const std::string& response) {
	return m_impl->reply(response);
legoc's avatar
legoc committed
992
993
}

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

legoc's avatar
legoc committed
996
	// Instantiate the requester server if it does not exist.
legoc's avatar
legoc committed
997
	if (m_requesterServer.get() == nullptr) {
998
		m_requesterServer.reset(new Server(m_impl->m_requesterServerEndpoint, m_impl->m_timeout));
legoc's avatar
legoc committed
999
	}
1000
1001
1002
1003
1004
1005

	// 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
1006
			return unique_ptr<Instance>(std::move(instances[i]));
1007
1008
1009
1010
		}
	}

	// Not found.
legoc's avatar
legoc committed
1011
	return unique_ptr<Instance>(nullptr);
1012
1013
}

legoc's avatar
legoc committed
1014
1015
std::unique_ptr<Server> Request::getServer() {
	return std::move(m_requesterServer);
legoc's avatar
legoc committed
1016
1017
}

legoc's avatar
legoc committed
1018
1019
1020
///////////////////////////////////////////////////////////////////////////
// Responder

legoc's avatar
legoc committed
1021
Responder::Responder(application::This * application, int responderPort, const std::string& name) :
legoc's avatar
legoc committed
1022
1023
1024
1025
1026
1027
1028
1029
1030
	m_impl(new ResponderImpl(application, responderPort, name)) {

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

Responder::~Responder() {
}

legoc's avatar
legoc committed
1031
std::unique_ptr<Responder> Responder::create(const std::string& name) {
legoc's avatar
legoc committed
1032
1033
1034

	string portName = ResponderImpl::RESPONDER_PREFIX + name;

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

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

1041
	int responderPort = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
1042
	if (responderPort == -1) {
1043
		throw ResponderCreationException(response[message::RequestResponse::MESSAGE].GetString());
legoc's avatar
legoc committed
1044
1045
	}

legoc's avatar
legoc committed
1046
	return unique_ptr<Responder>(new Responder(&This::m_instance, responderPort, name));
legoc's avatar
legoc committed
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
}

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

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

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

legoc's avatar
legoc committed
1059
1060
1061
	unique_ptr<RequestImpl> requestImpl = m_impl->receive();
	if (requestImpl.get() == nullptr) {
		return unique_ptr<Request>(nullptr);
legoc's avatar
legoc committed
1062
	}
legoc's avatar
legoc committed
1063
	return unique_ptr<Request>(new Request(requestImpl));
legoc's avatar
legoc committed
1064
1065
}

1066
1067
bool Responder::isCanceled() const {
	return m_impl->m_canceled;
legoc's avatar
legoc committed
1068
1069
1070
1071
1072
}

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

legoc's avatar
legoc committed
1073
Requester::Requester(application::This * application, const std::string& url, int requesterPort, int responderPort, const std::string& name, int responderId, int requesterId) :
1074
	m_impl(new RequesterImpl(application, url, requesterPort, responderPort, name, responderId, requesterId)) {
legoc's avatar
legoc committed
1075
1076
1077
1078
1079
1080
1081
1082

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

Requester::~Requester() {
}

legoc's avatar
legoc committed
1083
std::unique_ptr<Requester> Requester::create(Instance & instance, const std::string& name) {
legoc's avatar
legoc committed
1084
1085

	int responderId = instance.getId();
1086
	string responderUrl = instance.getEndpoint().getProtocol() + "://" + instance.getEndpoint().getAddress();
1087
	string responderEndpoint = instance.getEndpoint().toString();
legoc's avatar
legoc committed
1088

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

legoc's avatar
legoc committed
1092
	string responderPortName = ResponderImpl::RESPONDER_PREFIX + name;
1093
1094
	int requesterId = RequesterImpl::newRequesterId();
	string requesterPortName = RequesterImpl::getRequesterPortName(name, responderId, requesterId);
legoc's avatar
legoc committed
1095

1096
	string request = This::m_instance.m_impl->createConnectPortV0Request(responderId, responderPortName);
1097
1098

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

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

1104
	reply.reset();
legoc's avatar
legoc committed
1105

1106
	int responderPort = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
1107
1108
	if (responderPort == -1) {
		// Wait for the responder port.
1109
		instance.waitFor(responderPortName);
legoc's avatar
legoc committed
1110
1111

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

1115
		responderPort = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
1116
		if (responderPort == -1) {
1117
			throw RequesterCreationException(response[message::RequestResponse::MESSAGE].GetString());
legoc's avatar
legoc committed
1118
		}
1119
1120

		reply.reset();
legoc's avatar
legoc committed
1121
1122
	}

1123
	// Request a requester port.
1124
	reply = This::m_instance.m_requestSocket->request(This::m_instance.m_impl->createRequestPortV0Request(This::m_instance.m_id, requesterPortName));
1125
	json::parse(response, reply.get());
legoc's avatar
legoc committed
1126

1127
	int requesterPort = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
1128
	if (requesterPort == -1) {
1129
		throw RequesterCreationException(response[message::RequestResponse::MESSAGE].GetString());
legoc's avatar
legoc committed
1130
1131
	}

legoc's avatar
legoc committed
1132
	// TODO simplify the use of some variables: responderUrl.
legoc's avatar
legoc committed
1133
	return unique_ptr<Requester>(new Requester(&This::m_instance, responderUrl, requesterPort, responderPort, name, responderId, requesterId));
legoc's avatar
legoc committed
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
}

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

1148
1149
1150
1151
void Requester::sendTwoBinaryParts(const std::string& request1, const std::string& request2) {
	m_impl->sendTwoBinaryParts(request1, request2);
}

1152
1153
std::optional<std::string> Requester::receiveBinary() {
	return m_impl->receiveBinary();
legoc's avatar
legoc committed
1154
1155
}

1156
1157
std::optional<std::string> Requester::receive() {
	return m_impl->receive();
legoc's avatar
legoc committed
1158
1159
1160
1161
1162
1163
}

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

1164
1165
1166
1167
bool Requester::isCanceled() const {
	return m_impl->m_canceled;
}

legoc's avatar
legoc committed
1168
1169
1170
///////////////////////////////////////////////////////////////////////////
// Configuration

1171
Configuration::Configuration(const std::string& name, const std::string& description, bool singleInstance, bool restart, int startingTime, int stoppingTime) {
legoc's avatar
legoc committed
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207

	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
1208
Info::Info(const std::string& name, int id, int pid, State applicationState, State pastApplicationStates, const std::string& args) :
legoc's avatar
legoc committed
1209
	m_id(id),
legoc's avatar
legoc committed
1210
	m_pid(pid),
legoc's avatar
legoc committed
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
	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
1237
1238
1239
int Info::getPid() const {
	return m_pid;
}
legoc's avatar
legoc committed
1240

1241
1242
1243
///////////////////////////////////////////////////////////////////////////
// Port

legoc's avatar
legoc committed
1244
Port::Port(int port, const std::string& status, const std::string& owner) :
1245
1246
	m_port(port),
	m_status(status),
legoc's avatar
legoc committed
1247
	m_owner(owner) {
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
}

int Port::getPort() const {
	return m_port;
}

const std::string& Port::getStatus() const {
	return m_status;
}

legoc's avatar
legoc committed
1258
1259
const std::string& Port::getOwner() const {
	return m_owner;
1260
1261
}

legoc's avatar
legoc committed
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
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
1286
	if ((applicationStates & FAILURE) != 0) {
legoc's avatar
legoc committed
1287
1288
1289
1290
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
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
		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<<