Application.cpp 33.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
40
41
#include "Server.h"
#include "StarterServerException.h"
#include "StatusEvent.h"
42
43
44
#include "PublisherEvent.h"
#include "ResultEvent.h"
#include "PortEvent.h"
45
#include "KeyEvent.h"
46
#include "CancelEvent.h"
legoc's avatar
legoc committed
47
48
49
50
51
52

using namespace std;

namespace cameo {
namespace application {

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

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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);
}

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

std::string This::getReference() {
legoc's avatar
legoc committed
118
	if (m_instance.m_impl != nullptr) {
legoc's avatar
legoc committed
119
		ostringstream os;
120
		os << getName() << "." << getId() << "@" << getEndpoint();
legoc's avatar
legoc committed
121
122
123
124
125
126
		return os.str();
	}
	return "";
}

void This::terminate() {
127
128

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

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

138
139
140
141
	// Terminate the services.
	m_instance.Services::terminate();

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

145
146

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

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

155
	Services::init();
legoc's avatar
legoc committed
156
157

	if (argc == 0) {
158
		throw InvalidArgumentException("missing info argument");
legoc's avatar
legoc committed
159
160
161
162
163
164
	}

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

	if (tokens.size() < 4) {
165
		throw InvalidArgumentException(info + " is not a valid argument");
legoc's avatar
legoc committed
166
167
168
169
170
171
172
173
	}

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

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

174
175
176
	// 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
177
178
	m_serverEndpoint = m_url + ":" + port;

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

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

legoc's avatar
legoc committed
185
186
187
	string nameId = tokens[3];

	int index = nameId.find_last_of('.');
legoc's avatar
legoc committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202

	// 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();
203
204
205
206

		if (m_id == -1) {
			throw UnmanagedApplicationException(string("Maximum number of applications ") + m_name + " reached");
		}
legoc's avatar
legoc committed
207
208
209
210
211
212
213
214
	}

	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
215
		string sid = starterNameId.substr(index + 1);
legoc's avatar
legoc committed
216
217
218
219
220
221
		{
			istringstream is(sid);
			is >> m_starterId;
		}
	}

legoc's avatar
legoc committed
222
223
	// Must be here because the server endpoint is required.
	initStatus();
legoc's avatar
legoc committed
224
225

	// Create the local server
legoc's avatar
legoc committed
226
	m_server = unique_ptr<Server>(new Server(m_serverEndpoint));
legoc's avatar
legoc committed
227
228
229

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

legoc's avatar
legoc committed
233
	m_waitingSet = unique_ptr<WaitingImplSet>(new WaitingImplSet());
234
235
236
237

	// Init listener.
	setName(m_name);
	m_server->registerEventListener(this);
238
239
240
241


	// Init com.
	m_com = unique_ptr<Com>(new Com(m_server.get(), m_id));
legoc's avatar
legoc committed
242
243
244
245
}

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

	// Terminate the unmanaged application.
legoc's avatar
legoc committed
248
	if (m_impl != nullptr && !m_managed) {
249
250
		terminateUnmanagedApplication();
	}
legoc's avatar
legoc committed
251
252
253
}

const std::string& This::getName() {
254
	return m_instance.m_name;
legoc's avatar
legoc committed
255
256
257
}

int This::getId() {
258
	return m_instance.m_id;
legoc's avatar
legoc committed
259
260
261
}

void This::setTimeout(int timeout) {
262
	m_instance.Services::setTimeout(timeout);
legoc's avatar
legoc committed
263
264
265
}

int This::getTimeout() {
266
	return m_instance.Services::getTimeout();
legoc's avatar
legoc committed
267
268
}

269
const std::string& This::getEndpoint() {
legoc's avatar
legoc committed
270
	if (m_instance.m_impl != nullptr) {
271
		return m_instance.m_serverEndpoint;
legoc's avatar
legoc committed
272
273
274
275
276
277
	}
	static string result;
	return result;
}

Server& This::getServer() {
278
	return *m_instance.m_server;
legoc's avatar
legoc committed
279
280
}

281
282
283
284
const This::Com& This::getCom() {
	return *m_instance.m_com;
}

legoc's avatar
legoc committed
285
286
Server& This::getStarterServer() {

legoc's avatar
legoc committed
287
	if (m_instance.m_starterServer.get() == nullptr) {
legoc's avatar
legoc committed
288
289
290
		throw StarterServerException();
	}

291
	return *m_instance.m_starterServer;
legoc's avatar
legoc committed
292
293
294
}

const std::string& This::getUrl() {
295
	return m_instance.Services::getUrl();
legoc's avatar
legoc committed
296
297
298
}

bool This::isAvailable(int timeout) {
299
	return m_instance.Services::isAvailable(timeout);
legoc's avatar
legoc committed
300
301
302
}

bool This::isStopping() {
303
	return m_instance.getState(m_instance.m_id) == STOPPING;
legoc's avatar
legoc committed
304
305
306
}

void This::cancelWaitings() {
307
	m_instance.m_waitingSet->cancelAll();
legoc's avatar
legoc committed
308
309
}

legoc's avatar
legoc committed
310
int This::initUnmanagedApplication() {
legoc's avatar
legoc committed
311

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

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

318
	return response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
319
320
321
322
}

void This::terminateUnmanagedApplication() {

323
	m_requestSocket->request(m_impl->createDetachUnmanagedRequest(m_id));
legoc's avatar
legoc committed
324
325
}

326
bool This::setRunning() {
legoc's avatar
legoc committed
327

328
	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
329

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

334
335
	int value = response[message::RequestResponse::VALUE].GetInt();
	if (value == -1) {
336
		return false;
legoc's avatar
legoc committed
337
	}
338
339

	return true;
legoc's avatar
legoc committed
340
341
342
343
}

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

344
	m_instance.m_requestSocket->request(m_instance.m_impl->createSetResultRequest(m_instance.m_id), data);
legoc's avatar
legoc committed
345
346
347
348
349
350
351
352
353
354
355
}

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

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

State This::getState(int id) const {

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

358
359
360
	// Get the JSON response.
	json::Object event;
	json::parse(event, reply.get());
legoc's avatar
legoc committed
361

362
	return event[message::StatusEvent::APPLICATION_STATE].GetInt();
legoc's avatar
legoc committed
363
364
365
366
}

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

367
368
369
370
371
	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
372

373
	int value = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
374
375
376
377
378
379

	return (value != -1);
}

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

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

382
383
384
385
386
	// Get the JSON response.
	json::Object response;
	json::parse(response, reply.get());

	int value = response[message::RequestResponse::VALUE].GetInt();
legoc's avatar
legoc committed
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401

	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
402
		unique_ptr<Event> event = popEvent();
legoc's avatar
legoc committed
403
404

		// The socket is canceled.
legoc's avatar
legoc committed
405
		if (event.get() == nullptr) {
legoc's avatar
legoc committed
406
407
408
409
410
411
			return UNKNOWN;
		}

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

legoc's avatar
legoc committed
412
			if (status != nullptr) {
legoc's avatar
legoc committed
413
414
415
416
417
418
419
420
421
422
423
424
425
				state = status->getState();

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

	return UNKNOWN;
}

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

legoc's avatar
legoc committed
428
429
	if (m_instance.m_starterServer.get() == nullptr) {
		return unique_ptr<Instance>(nullptr);
legoc's avatar
legoc committed
430
431
432
	}

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

	for (int i = 0; i < instances.size(); i++) {
436
		if (instances[i]->getId() == m_instance.m_starterId) {
legoc's avatar
legoc committed
437
			return unique_ptr<Instance>(std::move(instances[i]));
legoc's avatar
legoc committed
438
439
440
		}
	}

legoc's avatar
legoc committed
441
	return unique_ptr<Instance>(nullptr);
legoc's avatar
legoc committed
442
443
}

444
445
446
447
448
449
450
451
452
453
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
454
void This::handleStopImpl(StopFunctionType function) {
455
	m_stopHandler = unique_ptr<HandlerImpl>(new HandlerImpl(bind(&This::stoppingFunction, this, function)));
legoc's avatar
legoc committed
456
457
458
459
460
}

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

461
462
463
464
465
466
467
468
469
470
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);
}

471
Instance::Instance(Server * server) :
legoc's avatar
legoc committed
472
473
	m_server(server),
	m_id(-1),
474
	m_com(server),
legoc's avatar
legoc committed
475
476
477
	m_pastStates(0),
	m_initialState(UNKNOWN),
	m_lastState(UNKNOWN),
478
479
	m_hasResult(false),
	m_exitCode(-1) {
480
481

	m_waiting.reset(new GenericWaitingImpl(bind(&Instance::cancelWaitFor, this)));
legoc's avatar
legoc committed
482
483
484
}

Instance::~Instance() {
485
486
487
488
	// 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
489
490
491
492
}

void Instance::setId(int id) {
	m_id = id;
493
	m_com.m_applicationId = id;
legoc's avatar
legoc committed
494
495
}

legoc's avatar
legoc committed
496
497
498
499
const std::string& Instance::getName() const {
	return EventListener::m_name;
}

legoc's avatar
legoc committed
500
501
502
503
void Instance::setErrorMessage(const std::string& message) {
	m_errorMessage = message;
}

legoc's avatar
legoc committed
504
void Instance::setOutputStreamSocket(std::unique_ptr<OutputStreamSocket>& socket) {
505
506
507
508
	if (socket) {
		m_outputStreamSocket = std::move(socket);
		m_outputStreamSocket->setApplicationId(m_id);
	}
legoc's avatar
legoc committed
509
510
}

legoc's avatar
legoc committed
511
512
513
514
515
516
void Instance::setPastStates(State pastStates) {
	m_pastStates = pastStates;
}

void Instance::setInitialState(State state) {
	m_initialState = state;
517
518
519

	// 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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
}

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

541
542
543
544
const Instance::Com& Instance::getCom() const {
	return m_com;
}

legoc's avatar
legoc committed
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
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;
}

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

	if (!exists()) {
584
		// The application was not launched
legoc's avatar
legoc committed
585
586
587
		return m_lastState;
	}

588
	// Test the terminal state
legoc's avatar
legoc committed
589
590
591
	if (m_lastState == SUCCESS
		|| m_lastState == STOPPED
		|| m_lastState == KILLED
legoc's avatar
legoc committed
592
		|| m_lastState == FAILURE) {
593
		// The application is already terminated
legoc's avatar
legoc committed
594
595
596
		return m_lastState;
	}

597
	// Test the requested states
legoc's avatar
legoc committed
598
	if ((states & m_pastStates) != 0) {
599
		// The state is already received
legoc's avatar
legoc committed
600
601
602
603
		return m_lastState;
	}

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

607
		// The non-blocking call returns a null message.
legoc's avatar
legoc committed
608
		if (event.get() == nullptr) {
legoc's avatar
legoc committed
609
610
611
612
613
614
			return m_lastState;
		}

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

legoc's avatar
legoc committed
615
			if (status != nullptr) {
legoc's avatar
legoc committed
616
617
618
619
				State state = status->getState();
				m_pastStates = status->getPastStates();
				m_lastState = state;

620
621
622
623
624
				// Assign the exit code.
				if (status->getExitCode() != -1) {
					m_exitCode = status->getExitCode();
				}

625
				// Call the state handler.
legoc's avatar
legoc committed
626
				if (handler != nullptr) {
legoc's avatar
legoc committed
627
628
629
					handler(state);
				}

legoc's avatar
legoc committed
630
631
632
633
				// test the terminal state
				if (state == SUCCESS
					|| state == STOPPED
					|| state == KILLED
legoc's avatar
legoc committed
634
					|| state == FAILURE) {
legoc's avatar
legoc committed
635
636
637
638
639
640
641
					break;
				}

				// test the requested states
				if ((states & m_pastStates) != 0) {
					return m_lastState;
				}
642
643
			}
			else {
legoc's avatar
legoc committed
644
645
646
647

				if (ResultEvent * result = dynamic_cast<ResultEvent *>(event.get())) {
					m_hasResult = true;
					m_resultData = result->getData();
648
649
				}
				else if (PublisherEvent * publisher = dynamic_cast<PublisherEvent *>(event.get())) {
legoc's avatar
legoc committed
650
651
652
					if (publisher->getPublisherName() == eventName) {
						break;
					}
653
654
				}
				else if (PortEvent * port = dynamic_cast<PortEvent *>(event.get())) {
legoc's avatar
legoc committed
655
656
657
658
					if (port->getPortName() == eventName) {
						break;
					}
				}
659
660
661
662
663
664
665
666
667
668
669
670
671
				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;
					}
				}
672
673
674
				else if (CancelEvent * cancel = dynamic_cast<CancelEvent *>(event.get())) {
					break;
				}
legoc's avatar
legoc committed
675
676
677
678
679
680
681
			}
		}
	}

	return m_lastState;
}

legoc's avatar
legoc committed
682
State Instance::waitFor(int states, StateHandlerType handler) {
683
684
	KeyValue keyValue("");
	return waitFor(states, "", keyValue, handler, true);
legoc's avatar
legoc committed
685
686
687
}

State Instance::waitFor(StateHandlerType handler) {
688
689
	KeyValue keyValue("");
	return waitFor(0, "", keyValue, handler, true);
690
691
692
}

State Instance::waitFor(const std::string& eventName) {
693
694
695
696
697
698
	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
699
700
701
}

void Instance::cancelWaitFor() {
702
	cancel(m_id);
legoc's avatar
legoc committed
703
704
}

705
State Instance::now() {
706
707
708
709
710
711

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

State Instance::getLastState() {
712
713
	KeyValue keyValue("");
	return waitFor(0, "", keyValue, nullptr, false);
714
715
}

716
State Instance::getActualState() const {
717
718
	return m_server->getActualState(m_id);
}
719

720
721
std::set<State> Instance::getPastStates() const {
	return m_server->getPastStates(m_id);
722
723
}

724
725
726
727
int Instance::getExitCode() const {
	return m_exitCode;
}

legoc's avatar
legoc committed
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
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
745
746
747
748
std::shared_ptr<OutputStreamSocket> Instance::getOutputStreamSocket() {
	return m_outputStreamSocket;
}

legoc's avatar
legoc committed
749
750
751
752
753
754
755
756
757
758
///////////////////////////////////////////////////////////////////////////
// InstanceArray

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

InstanceArray::InstanceArray(const InstanceArray& array) :
	m_size(array.m_size),
legoc's avatar
legoc committed
759
	m_array(new unique_ptr<Instance>[m_size]) {
legoc's avatar
legoc committed
760
761
762

	// transferring pointers
	for (size_t i = 0; i < m_size; i++) {
legoc's avatar
legoc committed
763
		m_array[i] = std::move(array.m_array[i]);
legoc's avatar
legoc committed
764
765
766
767
768
769
770
771
772
	}
}

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

void InstanceArray::allocate(std::size_t size) {
	m_size = size;
legoc's avatar
legoc committed
773
	m_array = new unique_ptr<Instance>[size];
legoc's avatar
legoc committed
774
775
776
777
778
779
}

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

legoc's avatar
legoc committed
780
std::unique_ptr<Instance>& InstanceArray::operator[](std::size_t index) {
legoc's avatar
legoc committed
781
782
783
784
785
786
	return m_array[index];
}

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

legoc's avatar
legoc committed
787
Publisher::Publisher(This * application, int publisherPort, int synchronizerPort, const std::string& name, int numberOfSubscribers) :
legoc's avatar
legoc committed
788
789
790
791
792
793
794
795
796
	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
797
std::unique_ptr<Publisher> Publisher::create(const std::string& name, int numberOfSubscribers) {
legoc's avatar
legoc committed
798

799
	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
800

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

805
	int publisherPort = response[message::PublisherResponse::PUBLISHER_PORT].GetInt();
legoc's avatar
legoc committed
806
	if (publisherPort == -1) {
807
		throw PublisherCreationException(response[message::PublisherResponse::MESSAGE].GetString());
legoc's avatar
legoc committed
808
	}
809
	int synchronizerPort = response[message::PublisherResponse::SYNCHRONIZER_PORT].GetInt();;
legoc's avatar
legoc committed
810

legoc's avatar
legoc committed
811
	return unique_ptr<Publisher>(new Publisher(&This::m_instance, publisherPort, synchronizerPort, name, numberOfSubscribers));
legoc's avatar
legoc committed
812
813
814
815
816
817
818
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
845
846
}


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

847
848
849
850
void Publisher::sendTwoBinaryParts(const std::string& data1, const std::string& data2) const {
	m_impl->sendTwoBinaryParts(data1, data2);
}

legoc's avatar
legoc committed
851
bool Publisher::hasEnded() const {
852
853
854
855
856
	return m_impl->isEnded();
}

bool Publisher::isEnded() const {
	return m_impl->isEnded();
legoc's avatar
legoc committed
857
858
859
860
861
862
863
864
865
}

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

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

866
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
867
868
869
870
871
872
	m_impl(new SubscriberImpl(server, url, publisherPort, synchronizerPort, publisherName, numberOfSubscribers, instanceName, instanceId, instanceEndpoint, statusEndpoint)) {
}

Subscriber::~Subscriber() {
}

legoc's avatar
legoc committed
873
std::unique_ptr<Subscriber> Subscriber::create(Instance & instance, const std::string& publisherName) {
legoc's avatar
legoc committed
874
875
876
877
878
879
880
881
	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
882
	State lastState = instance.waitFor(publisherName);
legoc's avatar
legoc committed
883
884
885
886
887

	// 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
888
		|| lastState == FAILURE) {
legoc's avatar
legoc committed
889
		return unique_ptr<Subscriber>(nullptr);
legoc's avatar
legoc committed
890
891
892
893
894
895
896
897
898
	}

	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
899
	return unique_ptr<Subscriber>(nullptr);
legoc's avatar
legoc committed
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
}

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 {
926
927
928
929
930
931
932
933
934
	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
935
936
937
938
939
940
941
942
943
944
}

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

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

945
946
947
948
bool Subscriber::receiveTwoBinaryParts(std::string& data1, std::string& data2) const {
	return m_impl->receiveTwoBinaryParts(data1, data2);
}

legoc's avatar
legoc committed
949
950
951
952
953
954
955
void Subscriber::cancel() {
	m_waiting->cancel();
}

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

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

Request::~Request() {
}

legoc's avatar
legoc committed
963
964
965
966
967
968
969
970
971
972
973
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;
}

974
975
976
977
std::string Request::getRequesterEndpoint() const {
	return m_impl->m_requesterServerEndpoint;
}

legoc's avatar
legoc committed
978
979
void Request::setTimeout(int value) {
	m_impl->setTimeout(value);
980
981
}

982
const std::string& Request::getBinary() const {
legoc's avatar
legoc committed
983
984
985
	return m_impl->m_message;
}

986
std::string Request::get() const {
legoc's avatar
legoc committed
987
988
989
990
991
992
993

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

	return data;
}

994
995
996
997
const std::string& Request::getSecondBinaryPart() const {
	return m_impl->m_message2;
}

legoc's avatar
legoc committed
998
999
bool Request::replyBinary(const std::string& response) {
	return m_impl->replyBinary(response);
legoc's avatar
legoc committed
1000
}
For faster browsing, not all history is shown. View entire blame