An Overlay-based
Virtual Network Substrate
SpoVNet

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

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