source: source/ariba/overlay/BaseOverlay.cpp@ 5920

Last change on this file since 5920 was 5916, checked in by mies, 15 years ago
File size: 49.4 KB
Line 
1// [License]
2// The Ariba-Underlay Copyright
3//
4// Copyright (c) 2008-2009, Institute of Telematics, UniversitÀt Karlsruhe (TH)
5//
6// Institute of Telematics
7// UniversitÀt Karlsruhe (TH)
8// Zirkel 2, 76128 Karlsruhe
9// Germany
10//
11// Redistribution and use in source and binary forms, with or without
12// modification, are permitted provided that the following conditions are
13// met:
14//
15// 1. Redistributions of source code must retain the above copyright
16// notice, this list of conditions and the following disclaimer.
17// 2. Redistributions in binary form must reproduce the above copyright
18// notice, this list of conditions and the following disclaimer in the
19// documentation and/or other materials provided with the distribution.
20//
21// THIS SOFTWARE IS PROVIDED BY THE INSTITUTE OF TELEMATICS ``AS IS'' AND
22// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ARIBA PROJECT OR
25// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32//
33// The views and conclusions contained in the software and documentation
34// are those of the authors and should not be interpreted as representing
35// official policies, either expressed or implied, of the Institute of
36// Telematics.
37// [License]
38
39#include "BaseOverlay.h"
40
41#include <sstream>
42#include <iostream>
43#include <string>
44#include <boost/foreach.hpp>
45
46#include "ariba/NodeListener.h"
47#include "ariba/CommunicationListener.h"
48#include "ariba/SideportListener.h"
49
50#include "ariba/overlay/LinkDescriptor.h"
51
52#include "ariba/overlay/messages/OverlayMsg.h"
53#include "ariba/overlay/messages/JoinRequest.h"
54#include "ariba/overlay/messages/JoinReply.h"
55
56#include "ariba/utility/misc/OvlVis.h"
57
58namespace ariba {
59namespace overlay {
60
61/* *****************************************************************************
62 * PREREQUESITES
63 * ****************************************************************************/
64
65CommunicationListener* BaseOverlay::getListener( const ServiceID& service ) {
66 if( !communicationListeners.contains( service ) ) {
67 logging_error( "No listener found for service " << service.toString() );
68 return NULL;
69 }
70 CommunicationListener* listener = communicationListeners.get( service );
71 assert( listener != NULL );
72 return listener;
73}
74
75// link descriptor handling ----------------------------------------------------
76
77LinkDescriptor* BaseOverlay::getDescriptor( const LinkID& link, bool communication ) {
78 BOOST_FOREACH( LinkDescriptor* lp, links )
79 if ((communication ? lp->communicationId : lp->overlayId) == link)
80 return lp;
81 return NULL;
82}
83
84const LinkDescriptor* BaseOverlay::getDescriptor( const LinkID& link, bool communication ) const {
85 BOOST_FOREACH( const LinkDescriptor* lp, links )
86 if ((communication ? lp->communicationId : lp->overlayId) == link)
87 return lp;
88 return NULL;
89}
90
91/// erases a link descriptor
92void BaseOverlay::eraseDescriptor( const LinkID& link, bool communication ) {
93 for ( vector<LinkDescriptor*>::iterator i = links.begin(); i!= links.end(); i++) {
94 LinkDescriptor* ld = *i;
95 if ((communication ? ld->communicationId : ld->overlayId) == link) {
96 delete ld;
97 links.erase(i);
98 break;
99 }
100 }
101}
102
103/// adds a link descriptor
104LinkDescriptor* BaseOverlay::addDescriptor( const LinkID& link ) {
105 LinkDescriptor* desc = getDescriptor( link );
106 if ( desc == NULL ) {
107 desc = new LinkDescriptor();
108 if (!link.isUnspecified()) desc->overlayId = link;
109 links.push_back(desc);
110 }
111 return desc;
112}
113
114/// returns a auto-link descriptor
115LinkDescriptor* BaseOverlay::getAutoDescriptor( const NodeID& node, const ServiceID& service ) {
116 // search for a descriptor that is already up
117 BOOST_FOREACH( LinkDescriptor* lp, links )
118 if (lp->autolink && lp->remoteNode == node && lp->service == service && lp->up && lp->keepAliveMissed == 0)
119 return lp;
120 // if not found, search for one that is about to come up...
121 BOOST_FOREACH( LinkDescriptor* lp, links )
122 if (lp->autolink && lp->remoteNode == node && lp->service == service && lp->keepAliveMissed == 0 )
123 return lp;
124 return NULL;
125}
126
127/// stabilizes link information
128void BaseOverlay::stabilizeLinks() {
129 // send keep-alive messages over established links
130 BOOST_FOREACH( LinkDescriptor* ld, links ) {
131 if (!ld->up) continue;
132 OverlayMsg msg( OverlayMsg::typeLinkAlive,
133 OverlayInterface::OVERLAY_SERVICE_ID, nodeId, ld->remoteNode );
134 if (ld->relayed) msg.setRouteRecord(true);
135 send_link( &msg, ld->overlayId );
136 }
137
138 // iterate over all links and check for time boundaries
139 vector<LinkDescriptor*> oldlinks;
140 time_t now = time(NULL);
141 BOOST_FOREACH( LinkDescriptor* ld, links ) {
142
143 // keep alives and not up? yes-> link connection request is stale!
144 if ( !ld->up && difftime( now, ld->keepAliveTime ) >= 2 ) {
145
146 // increase counter
147 ld->keepAliveMissed++;
148
149 // missed more than four keep-alive messages (10 sec)? -> drop link
150 if (ld->keepAliveMissed > 4) {
151 logging_info( "Link connection request is stale, closing: " << ld );
152 oldlinks.push_back( ld );
153 continue;
154 }
155 }
156
157 if (!ld->up) continue;
158
159 // remote used as relay flag
160 if ( ld->relaying && difftime( now, ld->timeRelaying ) > 10)
161 ld->relaying = false;
162
163 // drop links that are dropped and not used as relay
164 if (ld->dropAfterRelaying && !ld->relaying && !ld->autolink) {
165 oldlinks.push_back( ld );
166 continue;
167 }
168
169 // auto-link time exceeded?
170 if ( ld->autolink && difftime( now, ld->lastuse ) > 30 ) {
171 oldlinks.push_back( ld );
172 continue;
173 }
174
175 // keep alives missed? yes->
176 if ( difftime( now, ld->keepAliveTime ) > 2 ) {
177
178 // increase counter
179 ld->keepAliveMissed++;
180
181 // missed more than four keep-alive messages (4 sec)? -> drop link
182 if (ld->keepAliveMissed >= 4) {
183 logging_info( "Link is stale, closing: " << ld );
184 oldlinks.push_back( ld );
185 continue;
186 }
187 }
188 }
189
190 // drop links
191 BOOST_FOREACH( LinkDescriptor* ld, oldlinks ) {
192 logging_info( "Link timed out. Dropping " << ld );
193 ld->relaying = false;
194 dropLink( ld->overlayId );
195 }
196
197 // show link state
198 counter++;
199 if (counter>=4) showLinks();
200 if (counter>=4 || counter<0) counter = 0;
201}
202
203
204std::string BaseOverlay::getLinkHTMLInfo() {
205 std::ostringstream s;
206
207 s << "<h2 color=\"#606060\">Links</h2>";
208 s << "<table cellpadding=\"0\" border=\"0\" cellspacing=\"0\">";
209 s << "<tr background=\"#e0e0e0\">";
210 s << "<td>Id</td><td>Remote</td><td>Path</td>";
211 s << "</tr>";
212
213 BOOST_FOREACH( LinkDescriptor* ld, links ) {
214 if (!ld->isVital() || ld->service != OverlayInterface::OVERLAY_SERVICE_ID) continue;
215 s << "<tr>";
216 s << "<td>" << ld->overlayId.toString().substr(0,4) << "..</td>";
217 s << "<td>" << ld->remoteNode.toString().substr(0,4) << "..</td>";
218 s << "<td>";
219 if (ld->routeRecord.size()>0) {
220 for (size_t i=0; i<ld->routeRecord.size(); i++)
221 s << ld->routeRecord[i].toString().substr(0,4) << ".. ";
222 }
223 s << "</td>";
224 s << "</tr>";
225 }
226 s << "</table>";
227
228 return s.str();
229}
230
231/// shows the current link state
232void BaseOverlay::showLinks() {
233 int i=0;
234 logging_info("--- link state -------------------------------");
235 BOOST_FOREACH( LinkDescriptor* ld, links ) {
236 logging_info("link " << i << ": " << ld);
237 i++;
238 }
239 logging_info("----------------------------------------------");
240}
241
242/// compares two arbitrary links to the same node
243int BaseOverlay::compare( const LinkID& lhs, const LinkID& rhs ) {
244 LinkDescriptor* lhsld = getDescriptor(lhs);
245 LinkDescriptor* rhsld = getDescriptor(rhs);
246 if (lhsld==NULL || rhsld==NULL
247 || !lhsld->up || !rhsld->up
248 || lhsld->remoteNode != rhsld->remoteNode) return -1;
249
250 if ((lhsld->remoteLink^lhsld->overlayId)<(rhsld->remoteLink^lhsld->overlayId) )
251 return -1;
252
253 return 1;
254}
255
256
257// internal message delivery ---------------------------------------------------
258
259/// routes a message to its destination node
260void BaseOverlay::route( OverlayMsg* message ) {
261
262 // exceeded time-to-live? yes-> drop message
263 if (message->getNumHops() > message->getTimeToLive()) {
264 logging_warn("Message exceeded TTL. Dropping message and relay routes"
265 "for recovery.");
266 removeRelayNode(message->getDestinationNode());
267 return;
268 }
269
270 // no-> forward message
271 else {
272 // destinastion myself? yes-> handle message
273 if (message->getDestinationNode() == nodeId) {
274 logging_warn("Usually I should not route messages to myself!");
275 Message msg;
276 msg.encapsulate(message);
277 handleMessage( &msg, NULL );
278 } else {
279 // no->send message to next hop
280 send( message, message->getDestinationNode() );
281 }
282 }
283}
284
285/// sends a message to another node, delivers it to the base overlay class
286seqnum_t BaseOverlay::send( OverlayMsg* message, const NodeID& destination ) {
287 LinkDescriptor* next_link = NULL;
288
289 // drop messages to unspecified destinations
290 if (destination.isUnspecified()) return -1;
291
292 // send messages to myself -> handle message and drop warning!
293 if (destination == nodeId) {
294 logging_warn("Sent message to myself. Handling message.")
295 Message msg;
296 msg.encapsulate(message);
297 handleMessage( &msg, NULL );
298 return -1;
299 }
300
301 // use relay path?
302 if (message->isRelayed()) {
303 next_link = getRelayLinkTo( destination );
304 if (next_link != NULL) {
305 next_link->setRelaying();
306 return bc->sendMessage(next_link->communicationId, message);
307 } else {
308 logging_warn("Could not send message. No relay hop found to "
309 << destination)
310 return -1;
311 }
312 }
313
314 // routed message
315 else {
316 // no-> relay path! route over overlay path
317 LinkID next_id = overlayInterface->getNextLinkId( destination );
318 if (next_id.isUnspecified()) {
319 logging_warn("Could not send message. No next hop found to " <<
320 destination );
321 return -1;
322 }
323
324 // get link descriptor, up and running? yes-> send message
325 next_link = getDescriptor(next_id);
326 if (next_link != NULL && next_link->up) {
327 // send message over relayed link
328 return send(message, next_link);
329 }
330
331 // no-> error, dropping message
332 else {
333 logging_warn("Could not send message. Link not known or up");
334 return -1;
335 }
336 }
337
338 // not reached-> fail
339 return -1;
340}
341
342/// send a message using a link descriptor, delivers it to the base overlay class
343seqnum_t BaseOverlay::send( OverlayMsg* message, LinkDescriptor* ldr, bool ignore_down ) {
344 // check if null
345 if (ldr == NULL) {
346 logging_error("Can not send message to " << message->getDestinationAddress());
347 return -1;
348 }
349
350 // check if up
351 if (!ldr->up && !ignore_down) {
352 logging_error("Can not send message. Link not up:" << ldr );
353 return -1;
354 }
355 LinkDescriptor* ld = NULL;
356
357 // handle relayed link
358 if (ldr->relayed) {
359 logging_debug("Resolving direct link for relayed link to "
360 << ldr->remoteNode);
361 ld = getRelayLinkTo( ldr->remoteNode );
362 if (ld==NULL) {
363 logging_error("No relay path found to link " << ldr );
364 return -1;
365 }
366 ld->setRelaying();
367 message->setRelayed(true);
368 } else
369 ld = ldr;
370
371 // handle direct link
372 if (ld->communicationUp) {
373 logging_debug("send(): Sending message over direct link.");
374 return bc->sendMessage( ld->communicationId, message );
375 } else {
376 logging_error("send(): Could not send message. "
377 "Not a relayed link and direct link is not up.");
378 return -1;
379 }
380 return -1;
381}
382
383seqnum_t BaseOverlay::send_node( OverlayMsg* message, const NodeID& remote,
384 const ServiceID& service) {
385 message->setSourceNode(nodeId);
386 message->setDestinationNode(remote);
387 message->setService(service);
388 send( message, remote );
389}
390
391seqnum_t BaseOverlay::send_link( OverlayMsg* message, const LinkID& link,bool ignore_down ) {
392 LinkDescriptor* ld = getDescriptor(link);
393 if (ld==NULL) {
394 logging_error("Cannot find descriptor to link id=" << link.toString());
395 return -1;
396 }
397 message->setSourceNode(nodeId);
398 message->setDestinationNode(ld->remoteNode);
399
400 message->setSourceLink(ld->overlayId);
401 message->setDestinationLink(ld->remoteLink);
402
403 message->setService(ld->service);
404 message->setRelayed(ld->relayed);
405 return send( message, ld, ignore_down );
406}
407
408// relay route management ------------------------------------------------------
409
410/// stabilize relay information
411void BaseOverlay::stabilizeRelays() {
412 vector<relay_route>::iterator i = relay_routes.begin();
413 while (i!=relay_routes.end() ) {
414 relay_route& route = *i;
415 LinkDescriptor* ld = getDescriptor(route.link);
416
417 // relay link still used and alive?
418 if (ld==NULL
419 || !ld->isDirectVital()
420 || difftime(route.used, time(NULL)) > 8) {
421 logging_info("Forgetting relay information to node "
422 << route.node.toString() );
423 i = relay_routes.erase(i);
424 } else
425 i++;
426 }
427}
428
429void BaseOverlay::removeRelayLink( const LinkID& link ) {
430 vector<relay_route>::iterator i = relay_routes.begin();
431 while (i!=relay_routes.end() ) {
432 relay_route& route = *i;
433 if (route.link == link ) i = relay_routes.erase(i); else i++;
434 }
435}
436
437void BaseOverlay::removeRelayNode( const NodeID& remote ) {
438 vector<relay_route>::iterator i = relay_routes.begin();
439 while (i!=relay_routes.end() ) {
440 relay_route& route = *i;
441 if (route.node == remote ) i = relay_routes.erase(i); else i++;
442 }
443}
444
445/// refreshes relay information
446void BaseOverlay::refreshRelayInformation( const OverlayMsg* message, LinkDescriptor* ld ) {
447
448 // handle relayed messages from real links only
449 if (ld == NULL
450 || ld->relayed
451 || message->getSourceNode()==nodeId ) return;
452
453 // update usage information
454 if (message->isRelayed()) {
455 // try to find source node
456 BOOST_FOREACH( relay_route& route, relay_routes ) {
457 // relay route found? yes->
458 if ( route.node == message->getDestinationNode() ) {
459 ld->setRelaying();
460 route.used = time(NULL);
461 }
462 }
463
464 }
465
466 // register relay path
467 if (message->isRegisterRelay()) {
468 // set relaying
469 ld->setRelaying();
470
471 // try to find source node
472 BOOST_FOREACH( relay_route& route, relay_routes ) {
473
474 // relay route found? yes->
475 if ( route.node == message->getSourceNode() ) {
476
477 // refresh timer
478 route.used = time(NULL);
479 LinkDescriptor* rld = getDescriptor(route.link);
480
481 // route has a shorter hop count or old link is dead? yes-> replace
482 if (route.hops > message->getNumHops()
483 || rld == NULL
484 || !rld->isDirectVital()) {
485 logging_info("Updating relay information to node "
486 << route.node.toString()
487 << " reducing to " << message->getNumHops() << " hops.");
488 route.hops = message->getNumHops();
489 route.link = ld->overlayId;
490 }
491 return;
492 }
493 }
494
495 // not found-> add new entry
496 relay_route route;
497 route.hops = message->getNumHops();
498 route.link = ld->overlayId;
499 route.node = message->getSourceNode();
500 route.used = time(NULL);
501 logging_info("Remembering relay information to node "
502 << route.node.toString());
503 relay_routes.push_back(route);
504 }
505}
506
507/// returns a known "vital" relay link which is up and running
508LinkDescriptor* BaseOverlay::getRelayLinkTo( const NodeID& remote ) {
509 // try to find source node
510 BOOST_FOREACH( relay_route& route, relay_routes ) {
511 if (route.node == remote ) {
512 LinkDescriptor* ld = getDescriptor( route.link );
513 if (ld==NULL || !ld->isDirectVital()) return NULL; else {
514 route.used = time(NULL);
515 return ld;
516 }
517 }
518 }
519 return NULL;
520}
521
522/* *****************************************************************************
523 * PUBLIC MEMBERS
524 * ****************************************************************************/
525
526use_logging_cpp(BaseOverlay);
527
528// ----------------------------------------------------------------------------
529
530BaseOverlay::BaseOverlay() :
531 bc(NULL), overlayInterface(NULL), nodeId(NodeID::UNSPECIFIED),
532 spovnetId(SpoVNetID::UNSPECIFIED), state(BaseOverlayStateInvalid),
533 sideport(&SideportListener::DEFAULT), started(false), counter(0) {
534}
535
536BaseOverlay::~BaseOverlay() {
537}
538
539// ----------------------------------------------------------------------------
540
541void BaseOverlay::start( BaseCommunication& _basecomm, const NodeID& _nodeid ) {
542 logging_info("Starting...");
543
544 // set parameters
545 bc = &_basecomm;
546 nodeId = _nodeid;
547
548 // register at base communication
549 bc->registerMessageReceiver( this );
550 bc->registerEventListener( this );
551
552 // timer for auto link management
553 Timer::setInterval( 1000 );
554 Timer::start();
555
556 started = true;
557 state = BaseOverlayStateInvalid;
558}
559
560void BaseOverlay::stop() {
561 logging_info("Stopping...");
562
563 // stop timer
564 Timer::stop();
565
566 // delete oberlay interface
567 if(overlayInterface != NULL) {
568 delete overlayInterface;
569 overlayInterface = NULL;
570 }
571
572 // unregister at base communication
573 bc->unregisterMessageReceiver( this );
574 bc->unregisterEventListener( this );
575
576 started = false;
577 state = BaseOverlayStateInvalid;
578}
579
580bool BaseOverlay::isStarted(){
581 return started;
582}
583
584// ----------------------------------------------------------------------------
585
586void BaseOverlay::joinSpoVNet(const SpoVNetID& id,
587 const EndpointDescriptor& bootstrapEp) {
588
589 if(id != spovnetId){
590 logging_error("attempt to join against invalid spovnet, call initiate first");
591 return;
592 }
593
594
595 //ovl.visShowNodeBubble ( ovlId, nodeId, "joining..." );
596 logging_info( "Starting to join spovnet " << id.toString() <<
597 " with nodeid " << nodeId.toString());
598
599 if(bootstrapEp.isUnspecified() && state == BaseOverlayStateInvalid){
600
601 // bootstrap against ourselfs
602 logging_debug("joining spovnet locally");
603
604 overlayInterface->joinOverlay();
605 state = BaseOverlayStateCompleted;
606 BOOST_FOREACH( NodeListener* i, nodeListeners )
607 i->onJoinCompleted( spovnetId );
608
609 //ovl.visChangeNodeIcon ( ovlId, nodeId, OvlVis::ICON_ID_CAMERA );
610 //ovl.visChangeNodeColor( ovlId, nodeId, OvlVis::NODE_COLORS_GREEN );
611
612 logging_debug("starting overlay bootstrap module");
613 overlayBootstrap.start(this, spovnetId, nodeId);
614 overlayBootstrap.publish(bc->getEndpointDescriptor());
615
616 } else {
617
618 // bootstrap against another node
619 logging_debug("joining spovnet remotely against " << bootstrapEp.toString());
620
621 const LinkID& lnk = bc->establishLink( bootstrapEp );
622 bootstrapLinks.push_back(lnk);
623 logging_info("join process initiated for " << id.toString() << "...");
624 }
625}
626
627void BaseOverlay::leaveSpoVNet() {
628
629 logging_info( "Leaving spovnet " << spovnetId );
630 bool ret = ( state != this->BaseOverlayStateInvalid );
631
632 logging_debug("stopping overlay bootstrap module");
633 overlayBootstrap.stop();
634 overlayBootstrap.revoke();
635
636 logging_debug( "Dropping all auto-links" );
637
638 // gather all service links
639 vector<LinkID> servicelinks;
640 BOOST_FOREACH( LinkDescriptor* ld, links ) {
641 if( ld->service != OverlayInterface::OVERLAY_SERVICE_ID )
642 servicelinks.push_back( ld->overlayId );
643 }
644
645 // drop all service links
646 BOOST_FOREACH( LinkID lnk, servicelinks )
647 dropLink( lnk );
648
649 // let the node leave the spovnet overlay interface
650 logging_debug( "Leaving overlay" );
651 if( overlayInterface != NULL )
652 overlayInterface->leaveOverlay();
653
654 // drop still open bootstrap links
655 BOOST_FOREACH( LinkID lnk, bootstrapLinks )
656 bc->dropLink( lnk );
657
658 // change to inalid state
659 state = BaseOverlayStateInvalid;
660 //ovl.visShutdown( ovlId, nodeId, string("") );
661
662 // inform all registered services of the event
663 BOOST_FOREACH( NodeListener* i, nodeListeners ) {
664 if( ret ) i->onLeaveCompleted( spovnetId );
665 else i->onLeaveFailed( spovnetId );
666 }
667}
668
669void BaseOverlay::createSpoVNet(const SpoVNetID& id,
670 const OverlayParameterSet& param,
671 const SecurityParameterSet& sec,
672 const QoSParameterSet& qos) {
673
674 // set the state that we are an initiator, this way incoming messages are
675 // handled correctly
676 logging_info( "creating spovnet " + id.toString() <<
677 " with nodeid " << nodeId.toString() );
678
679 spovnetId = id;
680
681 overlayInterface = OverlayFactory::create( *this, param, nodeId, this );
682 if( overlayInterface == NULL ) {
683 logging_fatal( "overlay structure not supported" );
684 state = BaseOverlayStateInvalid;
685
686 BOOST_FOREACH( NodeListener* i, nodeListeners )
687 i->onJoinFailed( spovnetId );
688
689 return;
690 }
691}
692
693// ----------------------------------------------------------------------------
694
695const LinkID BaseOverlay::establishLink( const EndpointDescriptor& remoteEp,
696 const NodeID& remoteId, const ServiceID& service ) {
697
698 // establish link via overlay
699 if (!remoteId.isUnspecified())
700 return establishLink( remoteId, service );
701 else
702
703 // establish link directly if only ep is known
704 if (remoteId.isUnspecified())
705 return establishDirectLink(remoteEp, service );
706
707}
708
709/// call base communication's establish link and add link mapping
710const LinkID BaseOverlay::establishDirectLink( const EndpointDescriptor& ep,
711 const ServiceID& service ) {
712
713 /// find a service listener
714 if( !communicationListeners.contains( service ) ) {
715 logging_error( "No listener registered for service id=" << service.toString() );
716 return LinkID::UNSPECIFIED;
717 }
718 CommunicationListener* listener = communicationListeners.get( service );
719 assert( listener != NULL );
720
721 // create descriptor
722 LinkDescriptor* ld = addDescriptor();
723 ld->relayed = false;
724 ld->listener = listener;
725 ld->service = service;
726 ld->communicationId = bc->establishLink( ep );
727
728 /// establish link and add mapping
729 logging_info("Establishing direct link " << ld->communicationId.toString()
730 << " using " << ep.toString());
731
732 return ld->communicationId;
733}
734
735/// establishes a link between two arbitrary nodes
736const LinkID BaseOverlay::establishLink( const NodeID& remote,
737 const ServiceID& service ) {
738
739 // do not establish a link to myself!
740 if (remote == nodeId) return LinkID::UNSPECIFIED;
741
742 // create a link descriptor
743 LinkDescriptor* ld = addDescriptor();
744 ld->relayed = true;
745 ld->remoteNode = remote;
746 ld->service = service;
747 ld->listener = getListener(ld->service);
748
749 // create link request message
750 OverlayMsg msg(OverlayMsg::typeLinkRequest, service, nodeId, remote );
751 msg.setSourceLink(ld->overlayId);
752 msg.setRelayed(true);
753
754 // debug message
755 logging_info(
756 "Sending link request with"
757 << " link=" << ld->overlayId.toString()
758 << " node=" << ld->remoteNode.toString()
759 << " serv=" << ld->service.toString()
760 );
761
762 // sending message to node
763 send_node( &msg, ld->remoteNode, ld->service );
764
765 return ld->overlayId;
766}
767
768/// drops an established link
769void BaseOverlay::dropLink(const LinkID& link) {
770 logging_info( "Dropping link (initiated locally):" << link.toString() );
771
772 // find the link item to drop
773 LinkDescriptor* ld = getDescriptor(link);
774 if( ld == NULL ) {
775 logging_warn( "Can't drop link, link is unknown!");
776 return;
777 }
778
779 // delete all queued messages
780 if( ld->messageQueue.size() > 0 ) {
781 logging_warn( "Dropping link " << ld->overlayId.toString() << " that has "
782 << ld->messageQueue.size() << " waiting messages" );
783 ld->flushQueue();
784 }
785
786 // inform sideport and listener
787 ld->listener->onLinkDown( ld->overlayId, ld->remoteNode );
788 sideport->onLinkDown(ld->overlayId, this->nodeId, ld->remoteNode, this->spovnetId );
789
790 // do not drop relay links
791 if (!ld->relaying) {
792 // drop the link in base communication
793 if (ld->communicationUp) bc->dropLink( ld->communicationId );
794
795 // erase descriptor
796 eraseDescriptor( ld->overlayId );
797 } else {
798 ld->dropAfterRelaying = true;
799 }
800}
801
802// ----------------------------------------------------------------------------
803
804/// internal send message, always use this functions to send messages over links
805seqnum_t BaseOverlay::sendMessage( const Message* message, const LinkID& link ) {
806 logging_debug( "Sending data message on link " << link.toString() );
807
808 // get the mapping for this link
809 LinkDescriptor* ld = getDescriptor(link);
810 if( ld == NULL ) {
811 logging_error("Could not send message. "
812 << "Link not found id=" << link.toString());
813 return -1;
814 }
815
816 // check if the link is up yet, if its an auto link queue message
817 if( !ld->up ) {
818 ld->setAutoUsed();
819 if( ld->autolink ) {
820 logging_info("Auto-link " << link.toString() << " not up, queue message");
821 Data data = data_serialize( message );
822 const_cast<Message*>(message)->dropPayload();
823 ld->messageQueue.push_back( new Message(data) );
824 } else {
825 logging_error("Link " << link.toString() << " not up, drop message");
826 }
827 return -1;
828 }
829
830 // compile overlay message (has service and node id)
831 OverlayMsg overmsg( OverlayMsg::typeData );
832 overmsg.encapsulate( const_cast<Message*>(message) );
833
834 // send message over relay/direct/overlay
835 return send_link( &overmsg, ld->overlayId );
836}
837
838seqnum_t BaseOverlay::sendMessage(const Message* message,
839 const NodeID& node, const ServiceID& service) {
840
841 // find link for node and service
842 LinkDescriptor* ld = getAutoDescriptor( node, service );
843
844 // if we found no link, create an auto link
845 if( ld == NULL ) {
846
847 // debug output
848 logging_info( "No link to send message to node "
849 << node.toString() << " found for service "
850 << service.toString() << ". Creating auto link ..."
851 );
852
853 // call base overlay to create a link
854 LinkID link = establishLink( node, service );
855 ld = getDescriptor( link );
856 if( ld == NULL ) {
857 logging_error( "Failed to establish auto-link.");
858 return -1;
859 }
860 ld->autolink = true;
861
862 logging_debug( "Auto-link establishment in progress to node "
863 << node.toString() << " with link id=" << link.toString() );
864 }
865 assert(ld != NULL);
866
867 // mark the link as used, as we now send a message through it
868 ld->setAutoUsed();
869
870 // send / queue message
871 return sendMessage( message, ld->overlayId );
872}
873
874// ----------------------------------------------------------------------------
875
876const EndpointDescriptor& BaseOverlay::getEndpointDescriptor(
877 const LinkID& link) const {
878
879 // return own end-point descriptor
880 if( link == LinkID::UNSPECIFIED )
881 return bc->getEndpointDescriptor();
882
883 // find link descriptor. not found -> return unspecified
884 const LinkDescriptor* ld = getDescriptor(link);
885 if (ld==NULL) return EndpointDescriptor::UNSPECIFIED();
886
887 // return endpoint-descriptor from base communication
888 return bc->getEndpointDescriptor( ld->communicationId );
889}
890
891const EndpointDescriptor& BaseOverlay::getEndpointDescriptor(
892 const NodeID& node) const {
893
894 // return own end-point descriptor
895 if( node == nodeId || node == NodeID::UNSPECIFIED )
896 return bc->getEndpointDescriptor();
897
898 // no joined and request remote descriptor? -> fail!
899 if( overlayInterface == NULL ) {
900 logging_error( "overlay interface not set, cannot resolve endpoint" );
901 return EndpointDescriptor::UNSPECIFIED();
902 }
903
904 // resolve end-point descriptor from the base-overlay routing table
905 return overlayInterface->resolveNode( node );
906}
907
908// ----------------------------------------------------------------------------
909
910bool BaseOverlay::registerSidePort(SideportListener* _sideport) {
911 sideport = _sideport;
912 _sideport->configure( this );
913}
914
915bool BaseOverlay::unregisterSidePort(SideportListener* _sideport) {
916 sideport = &SideportListener::DEFAULT;
917}
918
919// ----------------------------------------------------------------------------
920
921bool BaseOverlay::bind(CommunicationListener* listener, const ServiceID& sid) {
922 logging_debug( "binding communication listener " << listener
923 << " on serviceid " << sid.toString() );
924
925 if( communicationListeners.contains( sid ) ) {
926 logging_error( "some listener already registered for service id "
927 << sid.toString() );
928 return false;
929 }
930
931 communicationListeners.registerItem( listener, sid );
932 return true;
933}
934
935
936bool BaseOverlay::unbind(CommunicationListener* listener, const ServiceID& sid) {
937 logging_debug( "unbinding listener " << listener << " from serviceid " << sid.toString() );
938
939 if( !communicationListeners.contains( sid ) ) {
940 logging_warn( "cannot unbind listener. no listener registered on service id " << sid.toString() );
941 return false;
942 }
943
944 if( communicationListeners.get(sid) != listener ) {
945 logging_warn( "listener bound to service id " << sid.toString()
946 << " is different than listener trying to unbind" );
947 return false;
948 }
949
950 communicationListeners.unregisterItem( sid );
951 return true;
952}
953
954// ----------------------------------------------------------------------------
955
956bool BaseOverlay::bind(NodeListener* listener) {
957 logging_debug( "Binding node listener " << listener );
958
959 // already bound? yes-> warning
960 NodeListenerVector::iterator i =
961 find( nodeListeners.begin(), nodeListeners.end(), listener );
962 if( i != nodeListeners.end() ) {
963 logging_warn("Node listener " << listener << " is already bound!" );
964 return false;
965 }
966
967 // no-> add
968 nodeListeners.push_back( listener );
969 return true;
970}
971
972bool BaseOverlay::unbind(NodeListener* listener) {
973 logging_debug( "Unbinding node listener " << listener );
974
975 // already unbound? yes-> warning
976 NodeListenerVector::iterator i = find( nodeListeners.begin(), nodeListeners.end(), listener );
977 if( i == nodeListeners.end() ) {
978 logging_warn( "Node listener " << listener << " is not bound!" );
979 return false;
980 }
981
982 // no-> remove
983 nodeListeners.erase( i );
984 return true;
985}
986
987// ----------------------------------------------------------------------------
988
989void BaseOverlay::onLinkUp(const LinkID& id,
990 const address_v* local, const address_v* remote) {
991 logging_debug( "Link up with base communication link id=" << id );
992
993 // get descriptor for link
994 LinkDescriptor* ld = getDescriptor(id, true);
995
996 // handle bootstrap link we initiated
997 if( std::find(bootstrapLinks.begin(), bootstrapLinks.end(), id) != bootstrapLinks.end() ){
998 logging_info(
999 "Join has been initiated by me and the link is now up. " <<
1000 "Sending out join request for SpoVNet " << spovnetId.toString()
1001 );
1002
1003 // send join request message
1004 OverlayMsg overlayMsg( OverlayMsg::typeJoinRequest,
1005 OverlayInterface::OVERLAY_SERVICE_ID, nodeId );
1006 JoinRequest joinRequest( spovnetId, nodeId );
1007 overlayMsg.encapsulate( &joinRequest );
1008 bc->sendMessage( id, &overlayMsg );
1009 return;
1010 }
1011
1012 // no link found? -> link establishment from remote, add one!
1013 if (ld == NULL) {
1014 ld = addDescriptor( id );
1015 logging_info( "onLinkUp (remote request) descriptor: " << ld );
1016
1017 // update descriptor
1018 ld->fromRemote = true;
1019 ld->communicationId = id;
1020 ld->communicationUp = true;
1021 ld->setAutoUsed();
1022 ld->setAlive();
1023
1024 // in this case, do not inform listener, since service it unknown
1025 // -> wait for update message!
1026
1027 // link mapping found? -> send update message with node-id and service id
1028 } else {
1029 logging_info( "onLinkUp descriptor (initiated locally):" << ld );
1030
1031 // update descriptor
1032 ld->setAutoUsed();
1033 ld->setAlive();
1034 ld->communicationUp = true;
1035 ld->fromRemote = false;
1036
1037 // if link is a relayed link->convert to direct link
1038 if (ld->relayed) {
1039 logging_info( "Converting to direct link: " << ld );
1040 ld->up = true;
1041 ld->relayed = false;
1042 OverlayMsg overMsg( OverlayMsg::typeLinkDirect );
1043 overMsg.setSourceLink( ld->overlayId );
1044 overMsg.setDestinationLink( ld->remoteLink );
1045 send_link( &overMsg, ld->overlayId );
1046 } else {
1047 // note: necessary to validate the link on the remote side!
1048 logging_info( "Sending out update" <<
1049 " for service " << ld->service.toString() <<
1050 " with local node id " << nodeId.toString() <<
1051 " on link " << ld->overlayId.toString() );
1052
1053 // compile and send update message
1054 OverlayMsg overlayMsg( OverlayMsg::typeLinkUpdate );
1055 overlayMsg.setSourceLink(ld->overlayId);
1056 overlayMsg.setAutoLink( ld->autolink );
1057 send_link( &overlayMsg, ld->overlayId, true );
1058 }
1059 }
1060}
1061
1062void BaseOverlay::onLinkDown(const LinkID& id,
1063 const address_v* local, const address_v* remote) {
1064
1065 // erase bootstrap links
1066 vector<LinkID>::iterator it = std::find( bootstrapLinks.begin(), bootstrapLinks.end(), id );
1067 if( it != bootstrapLinks.end() ) bootstrapLinks.erase( it );
1068
1069 // get descriptor for link
1070 LinkDescriptor* ld = getDescriptor(id, true);
1071 if ( ld == NULL ) return; // not found? ->ignore!
1072 logging_info( "onLinkDown descriptor: " << ld );
1073
1074 // removing relay link information
1075 removeRelayLink(ld->overlayId);
1076
1077 // inform listeners about link down
1078 ld->communicationUp = false;
1079 if (!ld->service.isUnspecified()) {
1080 getListener(ld->service)->onLinkDown( ld->overlayId, ld->remoteNode );
1081 sideport->onLinkDown( id, this->nodeId, ld->remoteNode, this->spovnetId );
1082 }
1083
1084 // delete all queued messages (auto links)
1085 if( ld->messageQueue.size() > 0 ) {
1086 logging_warn( "Dropping link " << id.toString() << " that has "
1087 << ld->messageQueue.size() << " waiting messages" );
1088 ld->flushQueue();
1089 }
1090
1091 // erase mapping
1092 eraseDescriptor(ld->overlayId);
1093}
1094
1095void BaseOverlay::onLinkChanged(const LinkID& id,
1096 const address_v* oldlocal, const address_v* newlocal,
1097 const address_v* oldremote, const address_v* newremote) {
1098
1099 // get descriptor for link
1100 LinkDescriptor* ld = getDescriptor(id, true);
1101 if ( ld == NULL ) return; // not found? ->ignore!
1102 logging_debug( "onLinkChanged descriptor: " << ld );
1103
1104 // inform listeners
1105 ld->listener->onLinkChanged( ld->overlayId, ld->remoteNode );
1106 sideport->onLinkChanged( id, this->nodeId, ld->remoteNode, this->spovnetId );
1107
1108 // autolinks: refresh timestamp
1109 ld->setAutoUsed();
1110}
1111
1112void BaseOverlay::onLinkFail(const LinkID& id,
1113 const address_v* local, const address_v* remote) {
1114 logging_debug( "Link fail with base communication link id=" << id );
1115
1116 // erase bootstrap links
1117 vector<LinkID>::iterator it = std::find( bootstrapLinks.begin(), bootstrapLinks.end(), id );
1118 if( it != bootstrapLinks.end() ) bootstrapLinks.erase( it );
1119
1120 // get descriptor for link
1121 LinkDescriptor* ld = getDescriptor(id, true);
1122 if ( ld == NULL ) return; // not found? ->ignore!
1123 logging_debug( "Link failed id=" << ld->overlayId.toString() );
1124
1125 // inform listeners
1126 ld->listener->onLinkFail( ld->overlayId, ld->remoteNode );
1127 sideport->onLinkFail( id, this->nodeId, ld->remoteNode, this->spovnetId );
1128}
1129
1130void BaseOverlay::onLinkQoSChanged(const LinkID& id, const address_v* local,
1131 const address_v* remote, const QoSParameterSet& qos) {
1132 logging_debug( "Link quality changed with base communication link id=" << id );
1133
1134 // get descriptor for link
1135 LinkDescriptor* ld = getDescriptor(id, true);
1136 if ( ld == NULL ) return; // not found? ->ignore!
1137 logging_debug( "Link quality changed id=" << ld->overlayId.toString() );
1138}
1139
1140bool BaseOverlay::onLinkRequest( const LinkID& id, const address_v* local,
1141 const address_v* remote ) {
1142 logging_debug("Accepting link request from " << remote->to_string() );
1143 return true;
1144}
1145
1146/// handles a message from base communication
1147bool BaseOverlay::receiveMessage(const Message* message,
1148 const LinkID& link, const NodeID& ) {
1149 // get descriptor for link
1150 LinkDescriptor* ld = getDescriptor( link, true );
1151 return handleMessage( message, ld, link );
1152}
1153
1154// ----------------------------------------------------------------------------
1155
1156/// Handle spovnet instance join requests
1157bool BaseOverlay::handleJoinRequest( OverlayMsg* overlayMsg, const LinkID& bcLink ) {
1158
1159 // decapsulate message
1160 JoinRequest* joinReq = overlayMsg->decapsulate<JoinRequest>();
1161 logging_info( "Received join request for spovnet " <<
1162 joinReq->getSpoVNetID().toString() );
1163
1164 // check spovnet id
1165 if( joinReq->getSpoVNetID() != spovnetId ) {
1166 logging_error(
1167 "Received join request for spovnet we don't handle " <<
1168 joinReq->getSpoVNetID().toString() );
1169 return false;
1170 }
1171
1172 // TODO: here you can implement mechanisms to deny joining of a node
1173 bool allow = true;
1174 logging_info( "Sending join reply for spovnet " <<
1175 spovnetId.toString() << " to node " <<
1176 overlayMsg->getSourceNode().toString() <<
1177 ". Result: " << (allow ? "allowed" : "denied") );
1178 joiningNodes.push_back( overlayMsg->getSourceNode() );
1179
1180 // return overlay parameters
1181 assert( overlayInterface != NULL );
1182 logging_debug( "Using bootstrap end-point "
1183 << getEndpointDescriptor().toString() )
1184 OverlayParameterSet parameters = overlayInterface->getParameters();
1185 OverlayMsg retmsg( OverlayMsg::typeJoinReply,
1186 OverlayInterface::OVERLAY_SERVICE_ID, nodeId );
1187 JoinReply replyMsg( spovnetId, parameters,
1188 allow, getEndpointDescriptor() );
1189 retmsg.encapsulate(&replyMsg);
1190 bc->sendMessage( bcLink, &retmsg );
1191
1192 return true;
1193}
1194
1195/// Handle replies to spovnet instance join requests
1196bool BaseOverlay::handleJoinReply( OverlayMsg* overlayMsg, const LinkID& bcLink ) {
1197 // decapsulate message
1198 logging_debug("received join reply message");
1199 JoinReply* replyMsg = overlayMsg->decapsulate<JoinReply>();
1200
1201 // correct spovnet?
1202 if( replyMsg->getSpoVNetID() != spovnetId ) { // no-> fail
1203 logging_error( "Received SpoVNet join reply for " <<
1204 replyMsg->getSpoVNetID().toString() <<
1205 " != " << spovnetId.toString() );
1206 delete replyMsg;
1207 return false;
1208 }
1209
1210 // access granted? no -> fail
1211 if( !replyMsg->getJoinAllowed() ) {
1212 logging_error( "Our join request has been denied" );
1213
1214 // drop initiator link
1215 if( !bcLink.isUnspecified() ){
1216 bc->dropLink( bcLink );
1217
1218 vector<LinkID>::iterator it = std::find(
1219 bootstrapLinks.begin(), bootstrapLinks.end(), bcLink);
1220 if( it != bootstrapLinks.end() )
1221 bootstrapLinks.erase(it);
1222 }
1223
1224 // inform all registered services of the event
1225 BOOST_FOREACH( NodeListener* i, nodeListeners )
1226 i->onJoinFailed( spovnetId );
1227
1228 delete replyMsg;
1229 return true;
1230 }
1231
1232 // access has been granted -> continue!
1233 logging_info("Join request has been accepted for spovnet " <<
1234 spovnetId.toString() );
1235
1236 logging_debug( "Using bootstrap end-point "
1237 << replyMsg->getBootstrapEndpoint().toString() );
1238
1239 // create overlay structure from spovnet parameter set
1240 // if we have not boostrapped yet against some other node
1241 if( overlayInterface == NULL ){
1242
1243 logging_debug("first-time bootstrapping");
1244
1245 overlayInterface = OverlayFactory::create(
1246 *this, replyMsg->getParam(), nodeId, this );
1247
1248 // overlay structure supported? no-> fail!
1249 if( overlayInterface == NULL ) {
1250 logging_error( "overlay structure not supported" );
1251
1252 if( !bcLink.isUnspecified() ){
1253 bc->dropLink( bcLink );
1254
1255 vector<LinkID>::iterator it = std::find(
1256 bootstrapLinks.begin(), bootstrapLinks.end(), bcLink);
1257 if( it != bootstrapLinks.end() )
1258 bootstrapLinks.erase(it);
1259 }
1260
1261 // inform all registered services of the event
1262 BOOST_FOREACH( NodeListener* i, nodeListeners )
1263 i->onJoinFailed( spovnetId );
1264
1265 delete replyMsg;
1266 return true;
1267 }
1268
1269 // everything ok-> join the overlay!
1270 state = BaseOverlayStateCompleted;
1271 overlayInterface->createOverlay();
1272
1273 overlayInterface->joinOverlay( replyMsg->getBootstrapEndpoint() );
1274 overlayBootstrap.recordJoin( replyMsg->getBootstrapEndpoint() );
1275
1276 // update ovlvis
1277 //ovl.visChangeNodeColor( ovlId, nodeId, OvlVis::NODE_COLORS_GREEN);
1278
1279 // inform all registered services of the event
1280 BOOST_FOREACH( NodeListener* i, nodeListeners )
1281 i->onJoinCompleted( spovnetId );
1282
1283 delete replyMsg;
1284
1285 } else {
1286
1287 // this is not the first bootstrap, just join the additional node
1288 logging_debug("not first-time bootstrapping");
1289 overlayInterface->joinOverlay( replyMsg->getBootstrapEndpoint() );
1290 overlayBootstrap.recordJoin( replyMsg->getBootstrapEndpoint() );
1291
1292 delete replyMsg;
1293
1294 } // if( overlayInterface == NULL )
1295
1296 return true;
1297}
1298
1299
1300bool BaseOverlay::handleData( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1301 // get service
1302 const ServiceID& service = overlayMsg->getService();
1303 logging_debug( "Received data for service " << service.toString()
1304 << " on link " << overlayMsg->getDestinationLink().toString() );
1305
1306 // delegate data message
1307 getListener(service)->onMessage(
1308 overlayMsg,
1309 overlayMsg->getSourceNode(),
1310 overlayMsg->getDestinationLink()
1311 );
1312
1313 return true;
1314}
1315
1316
1317bool BaseOverlay::handleLinkUpdate( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1318
1319 if( ld == NULL ) {
1320 logging_warn( "received overlay update message for link for "
1321 << "which we have no mapping" );
1322 return false;
1323 }
1324 logging_info("Received type update message on link " << ld );
1325
1326 // update our link mapping information for this link
1327 bool changed =
1328 ( ld->remoteNode != overlayMsg->getSourceNode() )
1329 || ( ld->service != overlayMsg->getService() );
1330
1331 // set parameters
1332 ld->up = true;
1333 ld->remoteNode = overlayMsg->getSourceNode();
1334 ld->remoteLink = overlayMsg->getSourceLink();
1335 ld->service = overlayMsg->getService();
1336 ld->autolink = overlayMsg->isAutoLink();
1337
1338 // if our link information changed, we send out an update, too
1339 if( changed ) {
1340 overlayMsg->swapRoles();
1341 overlayMsg->setSourceNode(nodeId);
1342 overlayMsg->setSourceLink(ld->overlayId);
1343 overlayMsg->setService(ld->service);
1344 send( overlayMsg, ld );
1345 }
1346
1347 // service registered? no-> error!
1348 if( !communicationListeners.contains( ld->service ) ) {
1349 logging_warn( "Link up: event listener has not been registered" );
1350 return false;
1351 }
1352
1353 // default or no service registered?
1354 CommunicationListener* listener = communicationListeners.get( ld->service );
1355 if( listener == NULL || listener == &CommunicationListener::DEFAULT ) {
1356 logging_warn("Link up: event listener is default or null!" );
1357 return true;
1358 }
1359
1360 // update descriptor
1361 ld->listener = listener;
1362 ld->setAutoUsed();
1363 ld->setAlive();
1364
1365 // ask the service whether it wants to accept this link
1366 if( !listener->onLinkRequest(ld->remoteNode) ) {
1367
1368 logging_debug("Link id=" << ld->overlayId.toString() <<
1369 " has been denied by service " << ld->service.toString() << ", dropping link");
1370
1371 // prevent onLinkDown calls to the service
1372 ld->listener = &CommunicationListener::DEFAULT;
1373
1374 // drop the link
1375 dropLink( ld->overlayId );
1376 return true;
1377 }
1378
1379 // set link up
1380 ld->up = true;
1381 logging_info( "Link has been accepted by service and is up: " << ld );
1382
1383 // auto links: link has been accepted -> send queued messages
1384 if( ld->messageQueue.size() > 0 ) {
1385 logging_info( "Sending out queued messages on link " << ld );
1386 BOOST_FOREACH( Message* msg, ld->messageQueue ) {
1387 sendMessage( msg, ld->overlayId );
1388 delete msg;
1389 }
1390 ld->messageQueue.clear();
1391 }
1392
1393 // call the notification functions
1394 listener->onLinkUp( ld->overlayId, ld->remoteNode );
1395 sideport->onLinkUp( ld->overlayId, nodeId, ld->remoteNode, this->spovnetId );
1396
1397 return true;
1398}
1399
1400/// handle a link request and reply
1401bool BaseOverlay::handleLinkRequest( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1402 logging_info( "Link request received from node id=" << overlayMsg->getSourceNode() );
1403
1404 //TODO: Check if a request has already been sent using getSourceLink() ...
1405
1406 // create link descriptor
1407 LinkDescriptor* ldn = addDescriptor();
1408
1409 // flags
1410 ldn->up = true;
1411 ldn->fromRemote = true;
1412 ldn->relayed = true;
1413
1414 // parameters
1415 ldn->service = overlayMsg->getService();
1416 ldn->listener = getListener(ldn->service);
1417 ldn->remoteNode = overlayMsg->getSourceNode();
1418 ldn->remoteLink = overlayMsg->getSourceLink();
1419
1420 // update time-stamps
1421 ldn->setAlive();
1422 ldn->setAutoUsed();
1423
1424 // create reply message and send back!
1425 overlayMsg->swapRoles(); // swap source/destination
1426 overlayMsg->setType(OverlayMsg::typeLinkReply);
1427 overlayMsg->setSourceLink(ldn->overlayId);
1428 overlayMsg->setSourceEndpoint( bc->getEndpointDescriptor() );
1429 overlayMsg->setRelayed(true);
1430 send( overlayMsg, ld ); // send back to link
1431
1432 // inform listener
1433 ldn->listener->onLinkUp( ldn->overlayId, ldn->remoteNode );
1434
1435 return true;
1436}
1437
1438bool BaseOverlay::handleLinkReply( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1439
1440 // find link request
1441 LinkDescriptor* ldn = getDescriptor(overlayMsg->getDestinationLink());
1442
1443 // not found? yes-> drop with error!
1444 if (ldn == NULL) {
1445 logging_error( "No link request pending for "
1446 << overlayMsg->getDestinationLink().toString() );
1447 return false;
1448 }
1449 logging_debug("Handling link reply for " << ldn )
1450
1451 // check if already up
1452 if (ldn->up) {
1453 logging_warn( "Link already up: " << ldn );
1454 return true;
1455 }
1456
1457 // debug message
1458 logging_debug( "Link request reply received. Establishing link"
1459 << " for service " << overlayMsg->getService().toString()
1460 << " with local id=" << overlayMsg->getDestinationLink()
1461 << " and remote link id=" << overlayMsg->getSourceLink()
1462 << " to " << overlayMsg->getSourceEndpoint().toString()
1463 );
1464
1465 // set local link descriptor data
1466 ldn->up = true;
1467 ldn->relayed = true;
1468 ldn->service = overlayMsg->getService();
1469 ldn->listener = getListener(ldn->service);
1470 ldn->remoteLink = overlayMsg->getSourceLink();
1471 ldn->remoteNode = overlayMsg->getSourceNode();
1472
1473 // update timestamps
1474 ldn->setAlive();
1475 ldn->setAutoUsed();
1476
1477 // auto links: link has been accepted -> send queued messages
1478 if( ldn->messageQueue.size() > 0 ) {
1479 logging_info( "Sending out queued messages on link " <<
1480 ldn->overlayId.toString() );
1481 BOOST_FOREACH( Message* msg, ldn->messageQueue ) {
1482 sendMessage( msg, ldn->overlayId );
1483 delete msg;
1484 }
1485 ldn->messageQueue.clear();
1486 }
1487
1488 // inform listeners about new link
1489 ldn->listener->onLinkUp( ldn->overlayId, ldn->remoteNode );
1490
1491 // try to replace relay link with direct link
1492 ldn->communicationId =
1493 bc->establishLink( overlayMsg->getSourceEndpoint() );
1494
1495 return true;
1496}
1497
1498/// handle a keep-alive message for a link
1499bool BaseOverlay::handleLinkAlive( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1500 LinkDescriptor* rld = getDescriptor(overlayMsg->getDestinationLink());
1501 if ( rld != NULL ) {
1502 logging_debug("Keep-Alive for " <<
1503 overlayMsg->getDestinationLink() );
1504 if (overlayMsg->isRouteRecord())
1505 rld->routeRecord = overlayMsg->getRouteRecord();
1506 rld->setAlive();
1507 return true;
1508 } else {
1509 logging_error("Keep-Alive for "
1510 << overlayMsg->getDestinationLink() << ": link unknown." );
1511 return false;
1512 }
1513}
1514
1515/// handle a direct link message
1516bool BaseOverlay::handleLinkDirect( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1517 logging_debug( "Received direct link replacement request" );
1518
1519 /// get destination overlay link
1520 LinkDescriptor* rld = getDescriptor( overlayMsg->getDestinationLink() );
1521 if (rld == NULL || ld == NULL) {
1522 logging_error("Direct link replacement: Link "
1523 << overlayMsg->getDestinationLink() << "not found error." );
1524 return false;
1525 }
1526 logging_info( "Received direct link convert notification for " << rld );
1527
1528 // update information
1529 rld->communicationId = ld->communicationId;
1530 rld->communicationUp = true;
1531 rld->relayed = false;
1532
1533 // mark used and alive!
1534 rld->setAlive();
1535 rld->setAutoUsed();
1536
1537 // erase the original descriptor
1538 eraseDescriptor(ld->overlayId);
1539}
1540
1541/// handles an incoming message
1542bool BaseOverlay::handleMessage( const Message* message, LinkDescriptor* ld,
1543 const LinkID bcLink ) {
1544 logging_debug( "Handling message: " << message->toString());
1545
1546 // decapsulate overlay message
1547 OverlayMsg* overlayMsg =
1548 const_cast<Message*>(message)->decapsulate<OverlayMsg>();
1549 if( overlayMsg == NULL ) return false;
1550
1551 // increase number of hops
1552 overlayMsg->increaseNumHops();
1553
1554 // refresh relay information
1555 refreshRelayInformation( overlayMsg, ld );
1556
1557 // update route record
1558 overlayMsg->addRouteRecord(nodeId);
1559
1560 // handle signaling messages (do not route!)
1561 if (overlayMsg->getType()>=OverlayMsg::typeSignalingStart &&
1562 overlayMsg->getType()<=OverlayMsg::typeSignalingEnd ) {
1563 overlayInterface->onMessage(overlayMsg, NodeID::UNSPECIFIED, LinkID::UNSPECIFIED);
1564 delete overlayMsg;
1565 return true;
1566 }
1567
1568 // message for reached destination? no-> route message
1569 if (!overlayMsg->getDestinationNode().isUnspecified() &&
1570 overlayMsg->getDestinationNode() != nodeId ) {
1571 logging_debug("Routing message "
1572 << " from " << overlayMsg->getSourceNode()
1573 << " to " << overlayMsg->getDestinationNode()
1574 );
1575 route( overlayMsg );
1576 delete overlayMsg;
1577 return true;
1578 }
1579
1580 // handle base overlay message
1581 bool ret = false; // return value
1582 switch ( overlayMsg->getType() ) {
1583
1584 // data transport messages
1585 case OverlayMsg::typeData:
1586 ret = handleData(overlayMsg, ld); break;
1587
1588 // overlay setup messages
1589 case OverlayMsg::typeJoinRequest:
1590 ret = handleJoinRequest(overlayMsg, bcLink ); break;
1591 case OverlayMsg::typeJoinReply:
1592 ret = handleJoinReply(overlayMsg, bcLink ); break;
1593
1594 // link specific messages
1595 case OverlayMsg::typeLinkRequest:
1596 ret = handleLinkRequest(overlayMsg, ld ); break;
1597 case OverlayMsg::typeLinkReply:
1598 ret = handleLinkReply(overlayMsg, ld ); break;
1599 case OverlayMsg::typeLinkUpdate:
1600 ret = handleLinkUpdate(overlayMsg, ld ); break;
1601 case OverlayMsg::typeLinkAlive:
1602 ret = handleLinkAlive(overlayMsg, ld ); break;
1603 case OverlayMsg::typeLinkDirect:
1604 ret = handleLinkDirect(overlayMsg, ld ); break;
1605
1606 // handle unknown message type
1607 default: {
1608 logging_error( "received message in invalid state! don't know " <<
1609 "what to do with this message of type " << overlayMsg->getType() );
1610 ret = false;
1611 break;
1612 }
1613 }
1614
1615 // free overlay message and return value
1616 delete overlayMsg;
1617 return ret;
1618}
1619
1620// ----------------------------------------------------------------------------
1621
1622void BaseOverlay::broadcastMessage(Message* message, const ServiceID& service) {
1623
1624 logging_debug( "broadcasting message to all known nodes " <<
1625 "in the overlay from service " + service.toString() );
1626
1627 OverlayInterface::NodeList nodes = overlayInterface->getKnownNodes(true);
1628 OverlayInterface::NodeList::iterator i = nodes.begin();
1629 for(; i != nodes.end(); i++ ) {
1630 if( *i == nodeId) continue; // don't send to ourselfs
1631 sendMessage( message, *i, service );
1632 }
1633}
1634
1635/// return the overlay neighbors
1636vector<NodeID> BaseOverlay::getOverlayNeighbors(bool deep) const {
1637 // the known nodes _can_ also include our node, so we remove ourself
1638 vector<NodeID> nodes = overlayInterface->getKnownNodes(deep);
1639 vector<NodeID>::iterator i = find( nodes.begin(), nodes.end(), this->nodeId );
1640 if( i != nodes.end() ) nodes.erase( i );
1641 return nodes;
1642}
1643
1644const NodeID& BaseOverlay::getNodeID(const LinkID& lid) const {
1645 if( lid == LinkID::UNSPECIFIED ) return nodeId;
1646 const LinkDescriptor* ld = getDescriptor(lid);
1647 if( ld == NULL ) return NodeID::UNSPECIFIED;
1648 else return ld->remoteNode;
1649}
1650
1651vector<LinkID> BaseOverlay::getLinkIDs( const NodeID& nid ) const {
1652 vector<LinkID> linkvector;
1653 BOOST_FOREACH( LinkDescriptor* ld, links ) {
1654 if( ld->remoteNode == nid || nid == NodeID::UNSPECIFIED ) {
1655 linkvector.push_back( ld->overlayId );
1656 }
1657 }
1658 return linkvector;
1659}
1660
1661
1662void BaseOverlay::onNodeJoin(const NodeID& node) {
1663 JoiningNodes::iterator i = std::find( joiningNodes.begin(), joiningNodes.end(), node );
1664 if( i == joiningNodes.end() ) return;
1665
1666 logging_info( "node has successfully joined baseoverlay and overlay structure "
1667 << node.toString() );
1668
1669 joiningNodes.erase( i );
1670}
1671
1672void BaseOverlay::eventFunction() {
1673 stabilizeRelays();
1674 stabilizeLinks();
1675}
1676
1677}} // namespace ariba, overlay
Note: See TracBrowser for help on using the repository browser.