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

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