Application.cpp 33.3 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include "EventStreamSocket.h"
#include "impl/ApplicationImpl.h"
#include "impl/PublisherImpl.h"
#include "impl/RequesterImpl.h"
#include "impl/RequestImpl.h"
#include "impl/ResponderImpl.h"
#include "impl/SocketImpl.h"
#include "impl/SubscriberImpl.h"
#include "impl/WaitingImpl.h"
#include "impl/WaitingImplSet.h"
#include "PortEvent.h"
#include "ProtoType.h"
#include "PublisherEvent.h"
#include "ResultEvent.h"
#include "Server.h"
#include "StarterServerException.h"
#include "StatusEvent.h"
legoc's avatar
legoc committed
41
42
43
44
45
46

using namespace std;

namespace cameo {
namespace application {

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

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

void This::terminate() {
93
94
95
96
97
98
99
100
101

	// Test if termination is already done.
	if (m_instance.m_impl == 0) {
		return;
	}

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

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

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

111
112

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

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

	m_impl = new ApplicationImpl();
	Services::setImpl(m_impl);

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

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

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

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

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

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

	string nameId = tokens[3];

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

	// 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();
165
166
167
168

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

	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
177
		string sid = starterNameId.substr(index + 1);
legoc's avatar
legoc committed
178
179
180
181
182
183
		{
			istringstream is(sid);
			is >> m_starterId;
		}
	}

legoc's avatar
legoc committed
184
185
	// Must be here because the server endpoint is required.
	initStatus();
legoc's avatar
legoc committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199

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

	// Create the starter server
	if (m_starterEndpoint != "") {
		m_starterServer = auto_ptr<Server>(new Server(m_starterEndpoint));
	}

	m_waitingSet = auto_ptr<WaitingImplSet>(new WaitingImplSet());
}

This::~This() {
	// Do not delete the impl here because there will be order trouble.
200
201
202
203
204

	// Terminate the unmanaged application.
	if (m_impl != 0 && !m_managed) {
		terminateUnmanagedApplication();
	}
legoc's avatar
legoc committed
205
206
207
}

const std::string& This::getName() {
208
	return m_instance.m_name;
legoc's avatar
legoc committed
209
210
211
}

int This::getId() {
212
	return m_instance.m_id;
legoc's avatar
legoc committed
213
214
215
}

void This::setTimeout(int timeout) {
216
	m_instance.Services::setTimeout(timeout);
legoc's avatar
legoc committed
217
218
219
}

int This::getTimeout() {
220
	return m_instance.Services::getTimeout();
legoc's avatar
legoc committed
221
222
}

223
const std::string& This::getEndpoint() {
224
225
	if (m_instance.m_impl != 0) {
		return m_instance.m_serverEndpoint;
legoc's avatar
legoc committed
226
227
228
229
230
231
	}
	static string result;
	return result;
}

Server& This::getServer() {
232
	return *m_instance.m_server;
legoc's avatar
legoc committed
233
234
235
236
}

Server& This::getStarterServer() {

237
	if (m_instance.m_starterServer.get() == 0) {
legoc's avatar
legoc committed
238
239
240
		throw StarterServerException();
	}

241
	return *m_instance.m_starterServer;
legoc's avatar
legoc committed
242
243
244
}

const std::string& This::getUrl() {
245
	return m_instance.Services::getUrl();
legoc's avatar
legoc committed
246
247
248
}

bool This::isAvailable(int timeout) {
249
	return m_instance.Services::isAvailable(timeout);
legoc's avatar
legoc committed
250
251
252
}

bool This::isStopping() {
253
	return m_instance.getState(m_instance.m_id) == STOPPING;
legoc's avatar
legoc committed
254
255
256
}

void This::cancelWaitings() {
257
	m_instance.m_waitingSet->cancelAll();
legoc's avatar
legoc committed
258
259
}

legoc's avatar
legoc committed
260
int This::initUnmanagedApplication() {
legoc's avatar
legoc committed
261

legoc's avatar
legoc committed
262
263
	string strRequestType = m_impl->createRequest(PROTO_STARTEDUNMANAGED);
	string strRequestData = m_impl->createStartedUnmanagedRequest(m_name);
264
	auto_ptr<zmq::message_t> reply = m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, m_serverEndpoint);
legoc's avatar
legoc committed
265
266
267
268
269
270
271
272
273
274
275

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

	return requestResponse.value();
}

void This::terminateUnmanagedApplication() {

	string strRequestType = m_impl->createRequest(PROTO_TERMINATEDUNMANAGED);
	string strRequestData = m_impl->createTerminatedUnmanagedRequest(m_id);
276
	auto_ptr<zmq::message_t> reply = m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, m_serverEndpoint);
legoc's avatar
legoc committed
277
278
279

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

282
bool This::setRunning() {
legoc's avatar
legoc committed
283

284
285
	string strRequestType = m_instance.m_impl->createRequest(PROTO_SETSTATUS);
	string strRequestData = m_instance.m_impl->createSetStatusRequest(m_instance.m_id, RUNNING);
286
	auto_ptr<zmq::message_t> reply = m_instance.m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, m_instance.m_serverEndpoint);
legoc's avatar
legoc committed
287
288
289
290
291

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

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

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

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

300
301
	string strRequestType = m_instance.m_impl->createRequest(PROTO_SETRESULT);
	string strRequestData = m_instance.m_impl->createSetResultRequest(m_instance.m_id, data);
legoc's avatar
legoc committed
302

303
	auto_ptr<zmq::message_t> reply = m_instance.m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, m_instance.m_serverEndpoint);
legoc's avatar
legoc committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
	proto::RequestResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());

	if (requestResponse.value() == -1) {
		//throw ?;
		// Unexpected exception
	}
}

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

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

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

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

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

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

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

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

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

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

State This::getState(int id) const {

	string strRequestType = m_impl->createRequest(PROTO_GETSTATUS);
	string strRequestData = m_impl->createGetStatusRequest(id);
352
	auto_ptr<zmq::message_t> reply = m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, m_serverEndpoint);
legoc's avatar
legoc committed
353
354
355
356
357
358
359
360
361
362
363

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

	return protoStatus.applicationstate();
}

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

	string strRequestType = m_impl->createRequest(PROTO_TERMINATEPUBLISHER);
	string strRequestData = m_impl->createTerminatePublisherRequest(m_id, name);
364
	auto_ptr<zmq::message_t> reply = m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, m_serverEndpoint);
legoc's avatar
legoc committed
365
366
367
368
369
370
371
372
373
374
375
376

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

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

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

	string strRequestType = m_impl->createRequest(PROTO_REMOVEPORT);
	string strRequestData = m_impl->createRemovePortRequest(m_id, name);
377
	auto_ptr<zmq::message_t> reply = m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, m_serverEndpoint);
legoc's avatar
legoc committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426

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

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

State This::waitForStop() {

	// open the event stream
	auto_ptr<EventStreamSocket> socket = openEventStream();
	m_impl->setEventSocket(socket);

	// 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
		auto_ptr<Event> event = m_impl->m_eventSocket->receive();

		// The socket is canceled.
		if (event.get() == 0) {
			return UNKNOWN;
		}

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

			if (status != 0) {
				state = status->getState();

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

	return UNKNOWN;
}

std::auto_ptr<Instance> This::connectToStarter() {

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

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

	for (int i = 0; i < instances.size(); i++) {
435
		if (instances[i]->getId() == m_instance.m_starterId) {
legoc's avatar
legoc committed
436
437
438
439
440
441
442
443
			return auto_ptr<Instance>(instances[i]);
		}
	}

	return auto_ptr<Instance>(0);
}

void This::handleStopImpl(StopFunctionType function) {
444
	m_impl->handleStop(&m_instance, function);
legoc's avatar
legoc committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
}

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

Instance::Instance(const Server * server, std::auto_ptr<EventStreamSocket>& socket) :
	m_server(server),
	m_eventSocket(socket),
	m_id(-1),
	m_pastStates(0),
	m_initialState(UNKNOWN),
	m_lastState(UNKNOWN),
	m_hasResult(false) {

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

Instance::~Instance() {
	// the destructor has been added to avoid blocking ZeroMQ, because the inner objects destructors were not called.
}

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

void Instance::setName(const std::string& name) {
	m_name = name;
}

void Instance::setErrorMessage(const std::string& message) {
	m_errorMessage = message;
}

void Instance::setPastStates(State pastStates) {
	m_pastStates = pastStates;
}

void Instance::setInitialState(State state) {
	m_initialState = state;
485
486
487

	// 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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
}

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

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

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

	if (!exists()) {
552
		// The application was not launched
legoc's avatar
legoc committed
553
554
555
		return m_lastState;
	}

556
	// Test the terminal state
legoc's avatar
legoc committed
557
558
559
	if (m_lastState == SUCCESS
		|| m_lastState == STOPPED
		|| m_lastState == KILLED
legoc's avatar
legoc committed
560
		|| m_lastState == FAILURE) {
561
		// The application is already terminated
legoc's avatar
legoc committed
562
563
564
		return m_lastState;
	}

565
	// Test the requested states
legoc's avatar
legoc committed
566
	if ((states & m_pastStates) != 0) {
567
		// The state is already received
legoc's avatar
legoc committed
568
569
570
571
		return m_lastState;
	}

	while (true) {
572
573
		// Waits for a new incoming status
		auto_ptr<Event> event = m_eventSocket->receive(blocking);
legoc's avatar
legoc committed
574

575
		// The socket is canceled or the non-blocking call returns a null message.
legoc's avatar
legoc committed
576
577
578
579
580
581
582
583
584
585
586
587
		if (event.get() == 0) {
			return m_lastState;
		}

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

			if (status != 0) {
				State state = status->getState();
				m_pastStates = status->getPastStates();
				m_lastState = state;

588
				// Call the state handler.
legoc's avatar
legoc committed
589
590
591
592
				if (!handler.empty()) {
					handler(state);
				}

legoc's avatar
legoc committed
593
594
595
596
				// test the terminal state
				if (state == SUCCESS
					|| state == STOPPED
					|| state == KILLED
legoc's avatar
legoc committed
597
					|| state == FAILURE) {
legoc's avatar
legoc committed
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
					break;
				}

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

			} else {

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

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

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

		}
	}

	return m_lastState;
}

630
631
632
633
State Instance::waitFor(int states, const std::string& eventName, StateHandlerType handler) {
	return waitFor(states, eventName, handler, true);
}

legoc's avatar
legoc committed
634
635
636
637
638
639
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
640
641
642
643
644
645
}

void Instance::cancelWaitFor() {
	m_waiting->cancel();
}

646
647
648
649
State Instance::now() {
	return waitFor(0, "", 0, false);
}

legoc's avatar
legoc committed
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
bool Instance::getBinaryResult(std::string& result) {

	waitFor();
	result = m_resultData;

	return m_hasResult;
}

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

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

	return m_hasResult;
}

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

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

	return m_hasResult;
}

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

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

	return m_hasResult;
}

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

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

	return m_hasResult;
}

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

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

	return m_hasResult;
}

///////////////////////////////////////////////////////////////////////////
// InstanceArray

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

InstanceArray::InstanceArray(const InstanceArray& array) :
	m_size(array.m_size),
	m_array(new auto_ptr<Instance>[m_size]) {

	// transferring pointers
	for (size_t i = 0; i < m_size; i++) {
		m_array[i] = array.m_array[i];
	}
}

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

void InstanceArray::allocate(std::size_t size) {
	m_size = size;
	m_array = new auto_ptr<Instance>[size];
}

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

std::auto_ptr<Instance>& InstanceArray::operator[](std::size_t index) {
	return m_array[index];
}

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

Publisher::Publisher(const This * application, int publisherPort, int synchronizerPort, const std::string& name, int numberOfSubscribers) :
	m_impl(new PublisherImpl(application, publisherPort, synchronizerPort, name, numberOfSubscribers)) {

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

Publisher::~Publisher() {
}

std::auto_ptr<Publisher> Publisher::create(const std::string& name, int numberOfSubscribers) {

753
754
	string strRequestType = This::m_instance.m_impl->createRequest(PROTO_CREATEPUBLISHER);
	string strRequestData = This::m_instance.m_impl->createCreatePublisherRequest(This::m_instance.m_id, name, numberOfSubscribers);
legoc's avatar
legoc committed
755

756
	auto_ptr<zmq::message_t> reply = This::m_instance.m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, This::m_instance.m_serverEndpoint);
legoc's avatar
legoc committed
757
758
759
760
761
762
763
764
765
	proto::PublisherResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());

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

766
	return auto_ptr<Publisher>(new Publisher(&This::m_instance, publisherPort, synchronizerPort, name, numberOfSubscribers));
legoc's avatar
legoc committed
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
}


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

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

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

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

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

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

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

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

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

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

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

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

818
819
820
821
void Publisher::sendTwoBinaryParts(const std::string& data1, const std::string& data2) const {
	m_impl->sendTwoBinaryParts(data1, data2);
}

legoc's avatar
legoc committed
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
847
848
849
850
851
852
853
854
bool Publisher::hasEnded() const {
	return m_impl->hasEnded();
}

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

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

Subscriber::Subscriber(const 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) :
	m_impl(new SubscriberImpl(server, url, publisherPort, synchronizerPort, publisherName, numberOfSubscribers, instanceName, instanceId, instanceEndpoint, statusEndpoint)) {
}

Subscriber::~Subscriber() {
}

std::auto_ptr<Subscriber> Subscriber::create(Instance & instance, const std::string& publisherName) {
	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
855
		|| lastState == FAILURE) {
legoc's avatar
legoc committed
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
		return auto_ptr<Subscriber>(0);
	}

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

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

	return auto_ptr<Subscriber>(0);
}

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 {
	return m_impl->hasEnded();
}

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

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

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

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

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

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

920
921
922
923
bool Subscriber::receiveTwoBinaryParts(std::string& data1, std::string& data2) const {
	return m_impl->receiveTwoBinaryParts(data1, data2);
}

legoc's avatar
legoc committed
924
925
926
927
928
929
930
931
932
933
934
935
936
937
void Subscriber::cancel() {
	m_waiting->cancel();
}

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

Request::Request(std::auto_ptr<RequestImpl> & impl) :
	m_impl(impl) {
}

Request::~Request() {
}

938
const std::string& Request::getBinary() const {
legoc's avatar
legoc committed
939
940
941
	return m_impl->m_message;
}

942
std::string Request::get() const {
legoc's avatar
legoc committed
943
944
945
946
947
948
949

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

	return data;
}

950
951
952
953
const std::string& Request::getSecondBinaryPart() const {
	return m_impl->m_message2;
}

legoc's avatar
legoc committed
954
955
void Request::replyBinary(const std::string& response) {
	m_impl->replyBinary(response);
legoc's avatar
legoc committed
956
957
}

legoc's avatar
legoc committed
958
959
void Request::reply(const std::string& response) {
	m_impl->reply(response);
legoc's avatar
legoc committed
960
961
}

962
963
std::auto_ptr<Instance> Request::connectToRequester() {

legoc's avatar
legoc committed
964
965
966
967
	// Instantiate the requester server if it does not exist.
	if (m_requesterServer.get() == 0) {
		m_requesterServer.reset(new Server(m_impl->m_requesterServerEndpoint));
	}
968
969
970
971
972
973
974
975
976
977
978
979
980
981

	// 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) {
			return auto_ptr<Instance>(instances[i]);
		}
	}

	// Not found.
	return auto_ptr<Instance>(0);
}

legoc's avatar
legoc committed
982
983
984
985
std::auto_ptr<Server> Request::getServer() {
	return m_requesterServer;
}

legoc's avatar
legoc committed
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
///////////////////////////////////////////////////////////////////////////
// Responder

Responder::Responder(const application::This * application, int responderPort, const std::string& name) :
	m_impl(new ResponderImpl(application, responderPort, name)) {

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

Responder::~Responder() {
}

std::auto_ptr<Responder> Responder::create(const std::string& name) {

	string portName = ResponderImpl::RESPONDER_PREFIX + name;

1003
1004
	string strRequestType = This::m_instance.m_impl->createRequest(PROTO_REQUESTPORT);
	string strRequestData = This::m_instance.m_impl->createRequestPortRequest(This::m_instance.m_id, portName);
legoc's avatar
legoc committed
1005

1006
	auto_ptr<zmq::message_t> reply = This::m_instance.m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, This::m_instance.m_serverEndpoint);
legoc's avatar
legoc committed
1007
1008
1009
1010
1011
1012
1013
1014
	proto::RequestResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());

	int responderPort = requestResponse.value();
	if (responderPort == -1) {
		throw ResponderCreationException(requestResponse.message());
	}

1015
	return auto_ptr<Responder>(new Responder(&This::m_instance, responderPort, name));
legoc's avatar
legoc committed
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
}

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

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

std::auto_ptr<Request> Responder::receive() {

	auto_ptr<RequestImpl> requestImpl = m_impl->receive();
	if (requestImpl.get() == 0) {
		return auto_ptr<Request>(0);
	}
	return auto_ptr<Request>(new Request(requestImpl));
}

bool Responder::hasEnded() const {
	return m_impl->m_ended;
}

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

1042
1043
Requester::Requester(const application::This * application, const std::string& url, int requesterPort, int responderPort, const std::string& name, int responderId, int requesterId) :
	m_impl(new RequesterImpl(application, url, requesterPort, responderPort, name, responderId, requesterId)) {
legoc's avatar
legoc committed
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058

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

Requester::~Requester() {
}

std::auto_ptr<Requester> Requester::create(Instance & instance, const std::string& name) {

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

	string responderPortName = ResponderImpl::RESPONDER_PREFIX + name;
1059
1060
	int requesterId = RequesterImpl::newRequesterId();
	string requesterPortName = RequesterImpl::getRequesterPortName(name, responderId, requesterId);
legoc's avatar
legoc committed
1061

1062
1063
	string strRequestType = This::m_instance.m_impl->createRequest(PROTO_CONNECTPORT);
	string strRequestData = This::m_instance.m_impl->createConnectPortRequest(responderId, responderPortName);
legoc's avatar
legoc committed
1064

1065
	auto_ptr<zmq::message_t> reply = This::m_instance.m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, responderEndpoint);
legoc's avatar
legoc committed
1066
1067
	proto::RequestResponse requestResponse;
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());
1068
	reply.reset();
legoc's avatar
legoc committed
1069
1070
1071
1072
1073
1074
1075

	int responderPort = requestResponse.value();
	if (responderPort == -1) {
		// Wait for the responder port.
		instance.waitFor(0, responderPortName);

		// Retry to connect.
1076
		reply = This::m_instance.m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, responderEndpoint);
legoc's avatar
legoc committed
1077
1078
1079
1080
1081
1082
		requestResponse.ParseFromArray((*reply).data(), (*reply).size());

		responderPort = requestResponse.value();
		if (responderPort == -1) {
			throw RequesterCreationException(requestResponse.message());
		}
1083
1084

		reply.reset();
legoc's avatar
legoc committed
1085
1086
1087
	}

	// Request a requester port
1088
1089
	strRequestType = This::m_instance.m_impl->createRequest(PROTO_REQUESTPORT);
	strRequestData = This::m_instance.m_impl->createRequestPortRequest(This::m_instance.m_id, requesterPortName);
legoc's avatar
legoc committed
1090

1091
	reply = This::m_instance.m_impl->tryRequestWithOnePartReply(strRequestType, strRequestData, This::m_instance.m_serverEndpoint);
legoc's avatar
legoc committed
1092
1093
1094
1095
1096
1097
1098
	requestResponse.ParseFromArray((*reply).data(), (*reply).size());

	int requesterPort = requestResponse.value();
	if (requesterPort == -1) {
		throw RequesterCreationException(requestResponse.message());
	}

1099
	return auto_ptr<Requester>(new Requester(&This::m_instance, responderUrl, requesterPort, responderPort, name, responderId, requesterId));
legoc's avatar
legoc committed
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
}

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

1114
1115
1116
1117
void Requester::sendTwoBinaryParts(const std::string& request1, const std::string& request2) {
	m_impl->sendTwoBinaryParts(request1, request2);
}

legoc's avatar
legoc committed
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
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
1167
1168
1169
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
1195
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
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();
}

///////////////////////////////////////////////////////////////////////////
// Configuration

Configuration::Configuration(const std::string& name, const std::string& description, bool singleInstance, bool restart, int startingTime, int retries, int stoppingTime) {

	m_name = name;
	m_description = description;
	m_singleInstance = singleInstance;
	m_restart = restart;
	m_startingTime = startingTime;
	m_retries = retries;
	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::getRetries() const {
	return m_retries;
}

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

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

Info::Info(const std::string& name, int id, State applicationState, State pastApplicationStates, const std::string& args) :
	m_id(id),
	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;
}


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
1228
	if ((applicationStates & FAILURE) != 0) {
legoc's avatar
legoc committed
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
1279
1280
1281
1282
1283
1284
1285
1286
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
		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()
1312
		<< "@" << responder.m_impl->m_application->getEndpoint();
legoc's avatar
legoc committed
1313
1314
1315
1316
1317
1318
1319

	return os;
}

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

	os << "req." << requester.getName()
1320
		<< "." << requester.m_impl->m_requesterId
legoc's avatar
legoc committed
1321
1322
		<< ":" << requester.m_impl->m_application->getName()
		<< "." << requester.m_impl->m_application->getId()
1323
		<< "@" << requester.m_impl->m_application->getEndpoint();
legoc's avatar
legoc committed
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

	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
			<< ", retries=" << info.m_retries
			<< ", 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;
}

}
}