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

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