An Overlay-based
Virtual Network Substrate
SpoVNet

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

Last change on this file since 4762 was 4762, checked in by Christoph Mayer, 14 years ago

avahi optional

File size: 34.9 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 "ariba/utility/misc/OvlVis.h"
42#include "ariba/NodeListener.h"
43#include "ariba/CommunicationListener.h"
44#include "ariba/SideportListener.h"
45
46#include "ariba/overlay/messages/OverlayMsg.h"
47#include "ariba/overlay/messages/JoinRequest.h"
48#include "ariba/overlay/messages/JoinReply.h"
49#include "ariba/overlay/messages/LinkRequest.h"
50
51namespace ariba {
52namespace overlay {
53
54use_logging_cpp(BaseOverlay);
55
56BaseOverlay::BaseOverlay()
57        : bc(NULL), overlayInterface(NULL), nodeId(NodeID::UNSPECIFIED),
58                spovnetId(SpoVNetID::UNSPECIFIED), initiatorLink(LinkID::UNSPECIFIED),
59                state(BaseOverlayStateInvalid), sideport(&SideportListener::DEFAULT){
60}
61
62BaseOverlay::~BaseOverlay(){
63}
64
65void BaseOverlay::start( BaseCommunication& _basecomm, const NodeID& _nodeid ){
66
67        bc = &_basecomm;
68        nodeId = _nodeid;
69
70        logging_info("creating base overlay");
71
72        bc->registerMessageReceiver( this );
73        bc->registerEventListener( this );
74
75        ovl.visCreate( ovlId, nodeId, string(""), string("") );
76        ovl.visChangeNodeColor(ovlId, nodeId, OvlVis::NODE_COLORS_GREY);
77
78//      if (Identifier(Configuration::instance().read<unsigned long>("BASE_nodeid")) ==
79//          Identifier(Configuration::instance().read<unsigned long>("SOURCE"))) {
80//              ovl.visChangeNodeIcon(ovlId, nodeId, OvlVis::ICON_ID_CAMERA);
81//      } else if (Identifier(Configuration::instance().read<unsigned long>("BASE_nodeid")) ==
82//          Identifier(Configuration::instance().read<unsigned long>("MR_A"))) {
83//              ovl.visChangeNodeIcon(ovlId, nodeId, OvlVis::ICON_ID_CHARACTER_A);
84//      } else if (Identifier(Configuration::instance().read<unsigned long>("BASE_nodeid")) ==
85//          Identifier(Configuration::instance().read<unsigned long>("MR_W"))) {
86//              ovl.visChangeNodeIcon(ovlId, nodeId, OvlVis::ICON_ID_CHARACTER_W);
87//      }
88
89        // timer for auto link management
90        Timer::setInterval( 5000 );
91        Timer::start();
92}
93
94void BaseOverlay::stop() {
95
96        logging_info("deleting base overlay");
97
98        Timer::stop();
99        bc->unregisterMessageReceiver( this );
100        bc->unregisterEventListener( this );
101
102        if(overlayInterface != NULL){
103                delete overlayInterface;
104                overlayInterface = NULL;
105        }
106}
107
108void BaseOverlay::joinSpoVNet(const SpoVNetID& id, const EndpointDescriptor& bootstrapEp){
109
110        ovl.visShowNodeBubble ( ovlId, nodeId, "joining..." );
111        logging_info( "starting to join spovnet " << id.toString() <<
112                        " with nodeid " << nodeId.toString());
113
114        //
115        // contact the spovnet initiator and request
116        // to join. if the join is granted we will
117        // receive further information on the structure
118        // of the overlay that is used in the spovnet
119        //
120        // but first, we have to establish a link to the initiator...
121        //
122
123        spovnetId = id;
124        state = BaseOverlayStateJoinInitiated;
125
126        initiatorLink = bc->establishLink( bootstrapEp );
127        logging_info("join process initiated for " << id.toString() << "...");
128}
129
130void BaseOverlay::leaveSpoVNet(){
131
132        logging_info( "leaving spovnet " << spovnetId );
133        bool ret = ( state != this->BaseOverlayStateInvalid );
134
135        logging_debug( "dropping all auto-links ..." );
136
137        // now we start leaving the spovnet: fist delete all links
138        // that we still have in the baseoverlay initiated by
139        // some services, the leave the actual overlay structure,
140        // then leave the spovnet
141
142        // --> drop all service links
143
144        vector<LinkID> servicelinks;
145        BOOST_FOREACH( LinkPair item, linkMapping ){
146                if( item.second.service != OverlayInterface::OVERLAY_SERVICE_ID )
147                        servicelinks.push_back( item.first );
148        }
149        BOOST_FOREACH( LinkID lnk, servicelinks ){
150                // the dropLink function will remove
151                // the item from the linkMapping
152                dropLink( lnk );
153        }
154
155        // --> leave overlay structure
156
157        logging_debug( "leaving overlay" );
158        // first, leave the overlay interface
159        if( overlayInterface != NULL )
160                overlayInterface->leaveOverlay();
161
162        // --> leave spovnet
163
164        if( state != BaseOverlayStateInitiator ){
165
166                // then, leave the spovnet baseoverlay
167                OverlayMsg overMsg( OverlayMsg::OverlayMessageTypeBye, nodeId );
168                bc->sendMessage( initiatorLink, &overMsg );
169
170                // drop the link and set to correct state
171                bc->dropLink( initiatorLink );
172                initiatorLink = LinkID::UNSPECIFIED;
173        }
174
175        state = BaseOverlayStateInvalid;
176        ovl.visShutdown( ovlId, nodeId, string("") );
177
178        // inform all registered services of the event
179        BOOST_FOREACH( NodeListener* i, nodeListeners ){
180                if( ret ) i->onLeaveCompleted( spovnetId );
181                else      i->onLeaveFailed( spovnetId );
182        }
183}
184
185void BaseOverlay::createSpoVNet(const SpoVNetID& id, const OverlayParameterSet& param, const SecurityParameterSet& sec, const QoSParameterSet& qos){
186
187        // set the state that we are an initiator, this way incoming messages are
188        // handled correctly
189        logging_info( "creating spovnet " + id.toString() <<
190                        " with nodeid " << nodeId.toString() );
191
192        spovnetId = id;
193        state = BaseOverlayStateInitiator;
194
195        overlayInterface = OverlayFactory::create( *this, param, nodeId, this );
196        if( overlayInterface == NULL ){
197                logging_fatal( "overlay structure not supported" );
198                state = BaseOverlayStateInvalid;
199                return;
200        }
201
202        // bootstrap against ourselfs
203        overlayInterface->joinOverlay();
204        BOOST_FOREACH( NodeListener* i, nodeListeners )
205                i->onJoinCompleted( spovnetId );
206
207        ovl.visChangeNodeIcon ( ovlId, nodeId, OvlVis::ICON_ID_CAMERA );
208        ovl.visChangeNodeColor( ovlId, nodeId, OvlVis::NODE_COLORS_GREEN);
209}
210
211
212/// establishes a link between two arbitrary nodes
213const LinkID BaseOverlay::establishLink( const NodeID& node,
214                const ServiceID& service, const LinkID& link_id ) {
215
216        if( !communicationListeners.contains( service ) ){
217                logging_error( "no registered listener on serviceid " << service.toString() );
218                return LinkID::UNSPECIFIED;
219        }
220
221        // copy link id
222        LinkID linkid = link_id;
223
224        // create link id if necessary
225        if (linkid.isUnspecified()) linkid = LinkID::create();
226
227        // debug message
228        logging_debug( "BaseOverlay called to establish link between node " <<
229                        node.toString() << " for service " << service.toString() );
230
231        // create link request message with own link id
232        OverlayMsg overlay_msg( OverlayMsg::OverlayMessageTypeLinkRequest, service, nodeId );
233        uint32_t nonce = (uint32_t)(rand() ^ (rand() << 16) ^ time(NULL));
234        LinkRequest link_request_msg( nonce, &bc->getEndpointDescriptor() );
235        overlay_msg.encapsulate( &link_request_msg );
236        pendingLinks.insert( make_pair(nonce, linkid) );
237
238        // debug message
239        logging_debug( "BaseOverlay routes LinkRequest message to node " << node.toString() );
240
241        // route message to overlay node
242        overlayInterface->routeMessage( node, &overlay_msg );
243
244        CommunicationListener* receiver = communicationListeners.get( service );
245        assert( receiver != NULL );
246
247        LinkItem item (linkid, NodeID::UNSPECIFIED, service, receiver);
248        linkMapping.insert( make_pair(linkid, item) );
249
250        return linkid;
251}
252
253const LinkID BaseOverlay::establishLink( const EndpointDescriptor& ep,
254                const ServiceID& service, const LinkID& linkid  ){
255
256        if( !communicationListeners.contains( service ) ){
257                logging_error( "no registered listener on serviceid " << service.toString() );
258                return LinkID::UNSPECIFIED;
259        }
260
261        const LinkID link = bc->establishLink( ep, linkid );
262
263        CommunicationListener* receiver = communicationListeners.get( service );
264        assert( receiver != NULL );
265
266        LinkItem item (link, NodeID::UNSPECIFIED, service, receiver);
267        linkMapping.insert( make_pair(link, item) );
268
269        return link;
270}
271
272void BaseOverlay::dropLink(const LinkID& link){
273
274        logging_debug( "baseoverlay dropping link " << link.toString() );
275        LinkMapping::iterator i = linkMapping.find( link );
276
277        // find the link item to drop
278        if( i == linkMapping.end() ){
279                logging_warn( "can't drop link, mapping unknown " << link.toString() );
280                return;
281        }
282
283        LinkItem item = i->second;
284
285        // delete all queued messages
286        if( item.waitingmsg.size() > 0 ){
287
288                logging_warn( "dropping link " << link.toString() <<
289                        " that has " << item.waitingmsg.size() << " waiting messages" );
290
291                item.deleteWaiting();
292        }
293
294        // erase the mapping and drop the link
295        linkMapping.erase( i );
296        bc->dropLink( link );
297
298        // tell sideports and listeners of the drop
299        item.interface->onLinkDown( link, item.node );
300        sideport->onLinkDown(link, this->nodeId, item.node, this->spovnetId );
301}
302
303seqnum_t BaseOverlay::sendMessage(const Message* message, const LinkID& link ){
304
305        logging_debug( "baseoverlay is sending data message on link " << link.toString() );
306
307        //
308        // get the mapping for this link
309        //
310
311        LinkMapping::iterator i = linkMapping.find( link );
312        if( i == linkMapping.end() ){
313                logging_error( "could not send message. link not found " << link.toString() );
314                return -1;
315        }
316
317        i->second.markused();
318
319        //
320        // check if the link is up yet, if its an autlink queue message
321        //
322
323        if( !i->second.linkup ){
324
325                if( i->second.autolink ){
326                        logging_info( "auto link " << link.toString() << " is not up yet, queueing message" );
327                        Data data = data_serialize( message );
328                        const_cast<Message*>(message)->dropPayload();
329                        i->second.waitingmsg.push_back( new Message(data) );
330                } else {
331                        logging_error("link " << link.toString() << " is not up yet, dropping message" );
332                }
333
334                return -1;
335        }
336
337        //
338        // send the message through the basecomm
339        //
340
341        OverlayMsg overmsg( OverlayMsg::OverlayMessageTypeData, i->second.service, nodeId );
342        overmsg.encapsulate( const_cast<Message*>(message) );
343
344        return bc->sendMessage( link, &overmsg );
345}
346
347seqnum_t BaseOverlay::sendMessage(const Message* message, const NodeID& node, const ServiceID& service){
348
349        LinkID link = LinkID::UNSPECIFIED;
350
351        LinkMapping::iterator i = linkMapping.begin();
352        LinkMapping::iterator iend = linkMapping.end();
353
354        //
355        // see if we find a link for this node and service destination
356        //
357
358        for( ; i != iend; i++ ){
359                if( i->second.node == node && i->second.service == service ){
360                        link = i->second.link;
361                        break;
362                }
363        }
364
365        //
366        // if we found no link, create an auto link
367        //
368
369        if( link == LinkID::UNSPECIFIED ){
370
371                logging_info( "no link could be found to send message to node " <<
372                                node.toString() << " for service " << service.toString() <<
373                                ". creating auto link ...");
374
375                // call basecomm to create a link
376                link = establishLink( node, service );
377
378                // this will call onlinkup on us, if everything worked we now have a mapping
379                LinkMapping::iterator i = linkMapping.find( link );
380                i->second.autolink = true;
381
382                if( i == linkMapping.end() || link == LinkID::UNSPECIFIED ){
383                        logging_error( "failed to establish auto link to node " << node.toString() <<
384                                        " for service " << service.toString() );
385                        return -1;
386                }
387
388                logging_debug( "establishing autolink in progress to node "
389                                << node.toString() << " with new link-id " << link.toString() );
390
391        } // if( link != LinkID::UNSPECIFIED )
392
393        assert( link != LinkID::UNSPECIFIED );
394
395        // mark the link as used, as we
396        // now send a message through it
397        i->second.markused();
398
399        // send the message through the new link. the link may not be functional,
400        // but for us there is a link-id so we can send messages through it. if
401        // the link is not yet up and the message needs to be cached, this is the
402        // task of the BaseCommunication, it will cache and send it later.
403        return sendMessage( message, link );
404}
405
406const EndpointDescriptor& BaseOverlay::getEndpointDescriptor(const LinkID& link) const {
407
408        return bc->getEndpointDescriptor( link );
409}
410
411const EndpointDescriptor& BaseOverlay::getEndpointDescriptor(const NodeID& node) const {
412
413        if( node == nodeId || node == NodeID::UNSPECIFIED )
414                return bc->getEndpointDescriptor();
415
416        if( overlayInterface == NULL ){
417                logging_error( "overlay interface not set, cannot resolve endpoint" );
418                return EndpointDescriptor::UNSPECIFIED;
419        }
420
421        // TODO: if this is not a onehop overlay the operation will go asynchronously
422        return overlayInterface->resolveNode( node );
423}
424
425
426bool BaseOverlay::bind(CommunicationListener* listener, const ServiceID& sid){
427        logging_debug( "binding communication listener " << listener
428                << " on serviceid " << sid.toString() );
429
430        if( communicationListeners.contains( sid ) ){
431                logging_error( "some listener already registered for service id "
432                        << sid.toString() );
433                return false;
434        }
435
436        communicationListeners.registerItem( listener, sid );
437        return true;
438}
439
440bool BaseOverlay::registerSidePort(SideportListener* _sideport){
441        sideport = _sideport;
442        _sideport->configure( this );
443}
444
445bool BaseOverlay::unregisterSidePort(SideportListener* _sideport){
446        sideport = &SideportListener::DEFAULT;
447}
448
449bool BaseOverlay::unbind(CommunicationListener* listener, const ServiceID& sid){
450        logging_debug( "unbinding listener " << listener
451                << " from serviceid " << sid.toString() );
452
453        if( !communicationListeners.contains( sid ) ){
454                logging_warn( "cannot unbind listener. no listener registered on service id " << sid.toString() );
455                return false;
456        }
457
458        if( communicationListeners.get(sid) != listener ){
459                logging_warn( "listener bound to service id " << sid.toString()
460                        << " is different than listener trying to unbind" );
461                return false;
462        }
463
464        communicationListeners.unregisterItem( sid );
465        return true;
466}
467
468bool BaseOverlay::bind(NodeListener* listener){
469        logging_debug( "binding node listener " << listener );
470
471        NodeListenerVector::iterator i = find( nodeListeners.begin(), nodeListeners.end(), listener );
472        if( i != nodeListeners.end() ){
473                logging_warn( "node listener " << listener << " is already bound, cannot bind" );
474                return false;
475        }
476
477        nodeListeners.push_back( listener );
478        return true;
479}
480
481bool BaseOverlay::unbind(NodeListener* listener){
482        logging_debug( "unbinding node listener " << listener );
483
484        NodeListenerVector::iterator i = find( nodeListeners.begin(), nodeListeners.end(), listener );
485        if( i == nodeListeners.end() ){
486                logging_warn( "node listener " << listener << " is not bound, cannot unbind" );
487                return false;
488        }
489
490        nodeListeners.erase( i );
491        return true;
492}
493
494void BaseOverlay::onLinkUp(const LinkID& id, const NetworkLocator* local, const NetworkLocator* remote){
495
496        logging_debug( "base overlay received linkup event " + id.toString() );
497        // TODO: updateOvlVis( getNodeID(id) );
498
499        //
500        // if we get up a link while we are in the
501        // join phase and this is the link that
502        // we have initiated towards the spovnet owner
503        // continue the join process by sending
504        // a join request message through the link
505        //
506
507        if( state == BaseOverlayStateJoinInitiated && id == initiatorLink){
508
509                logging_info(
510                        "Join has been initiated by me and the link is now up. " <<
511                        "sending out join request for SpoVNet " << spovnetId.toString()
512                );
513
514                OverlayMsg overMsg( OverlayMsg::OverlayMessageTypeJoinRequest, nodeId );
515                JoinRequest joinmsg( spovnetId, nodeId );
516                overMsg.encapsulate( &joinmsg );
517
518                state = BaseOverlayStateJoinInitiated; // state remains in JoinInitiated
519                bc->sendMessage( id, &overMsg );
520
521                return;
522
523        } // if( state == BaseOverlayStateJoinInitiated && id == initiatorLink)
524
525        //
526        // otherwise this is a link initiated by a service
527        // then we exchange update messages to exchange the
528        // service id and node id for the link. in this case
529        // we should have a link mapping for this link. if
530        // we have no link mapping this link was initiated by
531        // the remote side.
532        //
533
534        LinkMapping::iterator i = linkMapping.find( id );
535
536        if( i == linkMapping.end() ){
537
538                LinkItem item (id, NodeID::UNSPECIFIED, ServiceID::UNSPECIFIED, &CommunicationListener::DEFAULT );
539                linkMapping.insert( make_pair(id, item) );
540
541        } else {
542
543                logging_debug( "sending out OverlayMessageTypeUpdate" <<
544                                " for service " << i->second.service.toString() <<
545                                " with local node id " << nodeId.toString() <<
546                                " on link " << id.toString() );
547
548                OverlayMsg overMsg(
549                        OverlayMsg::OverlayMessageTypeUpdate,
550                        i->second.service,
551                        nodeId
552                        );
553
554                bc->sendMessage( id, &overMsg );
555                i->second.markused();
556
557        } // if( i == linkMapping.end() )
558
559        // the link is only valid for the service when we receive
560        // the OverlayMessageTypeUpdate from the remote node and
561        // have the nodeid and serviceid for the link!
562}
563
564void BaseOverlay::onLinkDown(const LinkID& id, const NetworkLocator* local, const NetworkLocator* remote){
565
566        logging_debug( "link went down " << id.toString() );
567
568        //
569        // tell the service that the link went
570        // down and remove the mapping
571        //
572
573        LinkMapping::iterator i = linkMapping.find( id );
574        if( i == linkMapping.end() ) {
575                // this can also be one of the baseoverlay links that
576                // no mapping is stored for. therefore we issue no warning.
577                // it can also be a link that has been dropped and the
578                // mapping is already deleted in the dropLink function.
579                // also, the service notification is issued then in dropLink
580                return;
581        }
582
583        i->second.interface->onLinkDown( id, i->second.node );
584        sideport->onLinkDown( id, this->nodeId, i->second.node, this->spovnetId );
585
586        // delete all queued messages
587        if( i->second.waitingmsg.size() > 0 ){
588
589                logging_warn( "dropping link " << id.toString() <<
590                        " that has " << i->second.waitingmsg.size() << " waiting messages" );
591
592                i->second.deleteWaiting();
593        }
594
595        linkMapping.erase( i );
596}
597
598void BaseOverlay::onLinkChanged(const LinkID& id, const NetworkLocator* oldlocal, const NetworkLocator* newlocal, const NetworkLocator* oldremote, const NetworkLocator* newremote){
599
600        logging_debug( "link changed " << id.toString() );
601
602        //
603        // tell the service that the link changed
604        //
605
606        LinkMapping::iterator i = linkMapping.find( id );
607        if( i == linkMapping.end() ) return;
608
609        i->second.interface->onLinkChanged( id, i->second.node );
610        sideport->onLinkChanged( id, this->nodeId, i->second.node, this->spovnetId );
611
612        // TODO call onLinkQoSChanged?
613
614        i->second.markused();
615}
616
617void BaseOverlay::onLinkFail(const LinkID& id, const NetworkLocator* local, const NetworkLocator* remote){
618
619        logging_debug( "link failed " << id.toString() );
620
621        //
622        // tell the service that the link failed
623        //
624
625        LinkMapping::iterator i = linkMapping.find( id );
626        if( i == linkMapping.end() ) return;
627
628        i->second.interface->onLinkFail( id, i->second.node );
629        sideport->onLinkFail( id, this->nodeId, i->second.node, this->spovnetId );
630
631        i->second.markused();
632}
633
634void BaseOverlay::onLinkQoSChanged(const LinkID& id, const NetworkLocator* local, const NetworkLocator* remote, const QoSParameterSet& qos) {
635
636        logging_debug( "link qos changed " << id.toString() );
637
638        //
639        // tell the service that the link qos has changed
640        //
641
642        LinkMapping::iterator i = linkMapping.find( id );
643        if( i == linkMapping.end() ) return;
644
645        // TODO: convert QoSParameterSet to the LinkProperties properties
646        // TODO: currently not in the interface: i->second.interface->onLinkQoSChanged( id, i->second.node, LinkProperties::DEFAULT );
647
648        i->second.markused();
649}
650
651bool BaseOverlay::onLinkRequest( const LinkID& id, const NetworkLocator* local, const NetworkLocator* remote ){
652
653        // also see in the receiveMessage function. there the higher layer service
654        // is asked whether to accept link requests, but there a basic link association is
655        // already built up, so we know the node id
656        logging_debug("received link request from " << remote->toString() << ", accepting");
657        return true;
658}
659
660
661bool BaseOverlay::receiveMessage(const Message* message,
662        const LinkID& link, const NodeID&
663        /*the nodeid is invalid in this case! removed var to prevent errors*/ ){
664
665        // decapsulate overlay message
666        logging_debug( "receiveMessage: " << message->toString());
667        OverlayMsg* overlayMsg = const_cast<Message*>(message)->decapsulate<OverlayMsg>();
668        if( overlayMsg == NULL ) return false;
669
670        // mark the link as in action
671        LinkMapping::iterator item = linkMapping.find( link );
672        if( item != linkMapping.end() ) item->second.markused();
673
674        /* ************************************************************************
675        /* handle user date that we forward to the appropriate service using the
676         * service id in the message. as we don't know the class of message that
677         * the service handles, we forward it as a pure Message
678         */
679        if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeData) ) {
680
681                logging_debug( "baseoverlay received message of type OverlayMessageTypeData" );
682
683                const ServiceID& service = overlayMsg->getService();
684                CommunicationListener* serviceListener = communicationListeners.get( service );
685
686                logging_debug( "received data for service " << service.toString() );
687
688                if( serviceListener != NULL )
689                        serviceListener->onMessage( overlayMsg, overlayMsg->getSourceNode(), link );
690
691                return true;
692
693        } // if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeData) )
694
695        /* ************************************************************************
696        /* Handle spovnet instance join requests
697         */
698        else if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeJoinRequest) ){
699
700                logging_debug(
701                        "baseoverlay received message of type OverlayMessageTypeJoinRequest"
702                );
703
704                JoinRequest* joinReq = overlayMsg->decapsulate<JoinRequest>();
705                logging_info( "received join request for spovnet " <<
706                                         joinReq->getSpoVNetID().toString() );
707
708                /* make sure that the node actually wants to join
709                 * the correct spovnet id that we administrate */
710                if( joinReq->getSpoVNetID() != spovnetId ){
711                        logging_error( "received join request for spovnet we don't handle " <<
712                                        joinReq->getSpoVNetID().toString() );
713                        return false;
714                }
715
716                //
717                // only if all services allow the node to join it is allowed
718                // using the isJoinAllowed interface security policies can be
719                // implemented by higher layer services
720                //
721
722                // TODO: here you can implement mechanisms to deny joining of a node
723                bool allow = true;
724
725                logging_info( "sending back join reply for spovnet " <<
726                                spovnetId.toString() << " to node " <<
727                                overlayMsg->getSourceNode().toString() <<
728                                ". result: " << (allow ? "allowed" : "denied") );
729
730                joiningNodes.push_back( overlayMsg->getSourceNode() );
731
732                //
733                // send back our spovnetid, default overlay parameters, join allow
734                // result, and ourself as the end-point to bootstrap the overlay against
735                //
736
737                assert( overlayInterface != NULL );
738                OverlayParameterSet parameters = overlayInterface->getParameters();
739
740                OverlayMsg retmsg( OverlayMsg::OverlayMessageTypeJoinReply, nodeId );
741                JoinReply replyMsg( spovnetId, parameters,
742                                        allow, getEndpointDescriptor() );
743
744                retmsg.encapsulate(&replyMsg);
745                bc->sendMessage( link, &retmsg );
746
747                return true;
748
749        } // else if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeJoinRequest))
750
751        /* ************************************************************************
752         * handle replies to spovnet instance join requests
753         */
754        else if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeJoinReply) &&
755                                                state == BaseOverlayStateJoinInitiated){
756
757                logging_debug(
758                        "baseoverlay received message of type OverlayMessageTypeJoinReply");
759
760                JoinReply* replyMsg = overlayMsg->decapsulate<JoinReply>();
761                logging_info( "received spovnet join reply" );
762
763                // ensure that we actually wanted to get into the spovnet whose id is
764                // in the message
765                if( replyMsg->getSpoVNetID() != spovnetId ){
766                        logging_error( "received spovnet join reply for spovnet " <<
767                                        replyMsg->getSpoVNetID().toString() <<
768                                        " but we wanted to join spovnet " <<
769                                        spovnetId.toString() );
770
771                        // state does not change here, maybe the reply does come in later
772                        return false;
773                }
774
775                // if we did not get access to the spovnet notify of the failure and
776                // close the link to the initiator
777                if( ! replyMsg->getJoinAllowed() ){
778
779                        logging_error( "our join request has been denied" );
780
781                        bc->dropLink( initiatorLink );
782                        initiatorLink = LinkID::UNSPECIFIED;
783                        state = BaseOverlayStateInvalid;
784
785                        // inform all registered services of the event
786                        BOOST_FOREACH( NodeListener* i, nodeListeners ){
787                                i->onJoinFailed( spovnetId );
788                        }
789
790                        return true;
791                }
792
793                logging_info( "join request has been accepted for spovnet " <<
794                                spovnetId.toString() );
795
796                // if we did get access to the spovnet we try to create the overlay
797                // structure as given in the reply message
798                overlayInterface = OverlayFactory::create( *this,
799                                replyMsg->getParam(), nodeId, this );
800
801                if( overlayInterface == NULL ){
802                        logging_error( "overlay structure not supported" );
803
804                        bc->dropLink( initiatorLink );
805                        initiatorLink = LinkID::UNSPECIFIED;
806                        state = BaseOverlayStateInvalid;
807
808                        // inform all registered services of the event
809                        BOOST_FOREACH( NodeListener* i, nodeListeners )
810                                i->onJoinFailed( spovnetId );
811
812                        return true;
813                }
814
815                /* now start the join process for the overlay. the join process for the
816                 * spovnet baseoverlay is now complete. we use the endpoint for overlay
817                 * structure bootstrapping that the initiator provided in his reply
818                 * message */
819                state = BaseOverlayStateCompleted;
820                ovl.visChangeNodeColor( ovlId, nodeId, OvlVis::NODE_COLORS_GREEN);
821
822                overlayInterface->createOverlay();
823                overlayInterface->joinOverlay( replyMsg->getBootstrapEndpoint() );
824
825                // inform all registered services of the event
826                BOOST_FOREACH( NodeListener* i, nodeListeners ){
827                        i->onJoinCompleted( spovnetId );
828                }
829
830                return true;
831
832        } // else if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeJoinReply) && state == BaseOverlayStateJoinInitiated)
833
834
835        /* ************************************************************************
836     * handle update messages for link establishment
837     */
838        else if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeUpdate) ){
839
840                logging_debug(
841                        "baseoverlay received message of type OverlayMessageTypeUpdate"
842                );
843
844                const NodeID& sourcenode = overlayMsg->getSourceNode();
845                const ServiceID& service = overlayMsg->getService();
846
847                // linkmapping for the link available? no-> ignore
848                LinkMapping::iterator i = linkMapping.find( link );
849                if( i == linkMapping.end() ) {
850                        logging_warn( "received overlay update message for link " <<
851                                        link.toString() << " for which we have no mapping" );
852                        return false;
853                }
854
855                // update our link mapping information for this link
856                bool changed = ( i->second.node != sourcenode ) || ( i->second.service != service );
857                i->second.node = sourcenode;
858                i->second.service = service;
859
860                // if our link information changed, we send out an update, too
861                if( changed ){
862                        OverlayMsg overMsg( OverlayMsg::OverlayMessageTypeUpdate, i->second.service, nodeId );
863                        bc->sendMessage( link, &overMsg );
864                }
865
866                // set the correct listener service for the linkitem
867                // now we can tell the registered service of the linkup event
868                if( !communicationListeners.contains( service ) ){
869                        logging_warn( "linkup event for service that has not been registered" );
870                        return false;
871                }
872
873                CommunicationListener* iface = communicationListeners.get( service );
874                if( iface == NULL || iface == &CommunicationListener::DEFAULT ){
875                        logging_warn( "linkup event for service that has been registered "
876                                "with a NULL interface" );
877                        return true;
878                }
879
880                i->second.interface = iface;
881                i->second.markused();
882
883                // ask the service whether it wants to accept this link
884                if( !iface->onLinkRequest(sourcenode) ){
885
886                        logging_debug("link " << link.toString() <<
887                                                                " has been denied by service " << service.toString() << ", dropping link");
888
889                        // prevent onLinkDown calls to the service
890                        i->second.interface = &CommunicationListener::DEFAULT;
891                        // drop the link
892                        dropLink( link );
893
894                        return true;
895                }
896
897                //
898                // link has been accepted, link is now up, send messages out first
899                //
900
901                i->second.linkup = true;
902                logging_debug("link " << link.toString() <<
903                                                " has been accepted by service " << service.toString() << " and is now up");
904
905                if( i->second.waitingmsg.size() > 0 ){
906                        logging_info( "sending out queued messages on link " << link.toString() );
907
908                        BOOST_FOREACH( Message* msg, i->second.waitingmsg ){
909                                sendMessage( msg, link );
910                                delete msg;
911                        }
912
913                        i->second.waitingmsg.clear();
914                }
915
916                // call the notification functions
917                iface->onLinkUp( link, sourcenode );
918                sideport->onLinkUp( link, nodeId, sourcenode, this->spovnetId );
919
920                return true;
921
922        } // else if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeUpdate) )
923
924        /* ************************************************************************
925         * handle bye messages
926         */
927        else if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeBye) ) {
928
929                logging_debug( "BaseOverlay received message of type OverlayMessageTypeBye" );
930                logging_debug( "Received bye message from " <<
931                                overlayMsg->getSourceNode().toString() );
932
933                /* if we are the initiator and receive a bye from a node
934                 * the node just left. if we are a node and receive a bye
935                 * from the initiator, we have to close, too.
936                 */
937                if( overlayMsg->getSourceNode() == spovnetInitiator ){
938
939                        bc->dropLink( initiatorLink );
940                        initiatorLink = LinkID::UNSPECIFIED;
941                        state = BaseOverlayStateInvalid;
942
943                        logging_fatal( "initiator ended spovnet" );
944
945                        // inform all registered services of the event
946                        BOOST_FOREACH( NodeListener* i, nodeListeners ){
947                                i->onLeaveFailed( spovnetId );
948                        }
949
950                } else {
951                        // a node that said goodbye and we are the initiator don't have to
952                        // do much here, as the node also will go out of the overlay
953                        // structure
954                        logging_info( "node left " << overlayMsg->getSourceNode() );
955                }
956
957                return true;
958
959        } // else if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeBye))
960
961        /* ************************************************************************
962         * handle link request forwarded through the overlay
963         */
964        else if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeLinkRequest)) {
965                LinkRequest* linkReq = overlayMsg->decapsulate<LinkRequest>();
966                const ServiceID& service = overlayMsg->getService();
967                if (linkReq->isReply()) {
968
969                        // find link
970                        PendingLinkMap::iterator i = pendingLinks.find( linkReq->getNonce() );
971                        if ( i == pendingLinks.end() ) {
972                                logging_error( "Nonce not found in link request" );
973                                return true;
974                        }
975
976                        // debug message
977                        logging_debug( "LinkRequest reply received. Establishing link "
978                                << i->second << " to " << (linkReq->getEndpoint()->toString())
979                                << " for service " << service.toString()
980                                << " with nonce " << linkReq->getNonce()
981                        );
982
983                        // establishing link
984                        bc->establishLink( *linkReq->getEndpoint(), i->second );
985                } else {
986                        OverlayMsg overlay_msg( OverlayMsg::OverlayMessageTypeLinkRequest, service, nodeId );
987                        LinkRequest link_request_msg(
988                                        linkReq->getNonce(), &bc->getEndpointDescriptor(), true );
989                        overlay_msg.encapsulate( &link_request_msg );
990
991                        // debug message
992                        logging_debug( "Sending LinkRequest reply for link with nonce " <<
993                                        linkReq->getNonce()     );
994
995                        // route message back over overlay
996                        overlayInterface->routeMessage(
997                                overlayMsg->getSourceNode(), &overlay_msg
998                        );
999                }
1000        } // if( overlayMsg->isType(OverlayMsg::OverlayMessageTypeLinkRequest))
1001
1002        /* ************************************************************************
1003         * unknown message type ... error!
1004         */
1005        else {
1006
1007                logging_error( "received message in invalid state! don't know " <<
1008                                "what to do with this message of type " <<
1009                                overlayMsg->getType() );
1010                return false;
1011
1012        } // else
1013
1014        return false;
1015}
1016
1017void BaseOverlay::broadcastMessage(Message* message, const ServiceID& service){
1018
1019        logging_debug( "broadcasting message to all known nodes " <<
1020                        "in the overlay from service " + service.toString() );
1021
1022        OverlayInterface::NodeList nodes = overlayInterface->getKnownNodes();
1023
1024        OverlayInterface::NodeList::iterator i = nodes.begin();
1025        OverlayInterface::NodeList::iterator iend = nodes.end();
1026
1027        for( ; i != iend; i++ ){
1028                if( *i == nodeId) continue; // don't send to ourselfs
1029                sendMessage( message, *i, service );
1030        }
1031}
1032
1033vector<NodeID> BaseOverlay::getOverlayNeighbors() const {
1034        // the known nodes _can_ also include our
1035        // node, so we remove ourselfs
1036
1037        vector<NodeID> nodes = overlayInterface->getKnownNodes();
1038        vector<NodeID>::iterator i = find( nodes.begin(), nodes.end(), this->nodeId );
1039        if( i != nodes.end() ) nodes.erase( i );
1040
1041        return nodes;
1042}
1043
1044void BaseOverlay::updateOvlVis( const NodeID& n ) {
1045        NodeID node = n;
1046/*      void visShowNodeBubble (
1047        NETWORK_ID network,
1048        NodeID& node,
1049        string label
1050        );
1051*/
1052        using namespace std;
1053
1054        if (node == nodeId || node.isUnspecified()) return;
1055
1056        // min/max
1057        if ( node < min || min.isUnspecified() ) min = node;
1058        if ( node > max || max.isUnspecified() ) max = node;
1059
1060        // successor
1061        if ( succ.isUnspecified() || (node > nodeId && (succ < nodeId || (node-nodeId) < (succ-nodeId))) ) {
1062                if (!succ.isUnspecified() && node != succ)
1063                        ovl.visDisconnect(ovlId, nodeId, succ, string(""));
1064                succ = node;
1065                ovl.visConnect(ovlId, nodeId, succ, string(""));
1066        }
1067
1068        // set successor (circle-wrap)
1069        if (succ.isUnspecified() && !min.isUnspecified()) {
1070                succ = min;
1071                ovl.visConnect(ovlId, nodeId, succ, string(""));
1072        }
1073}
1074
1075const NodeID& BaseOverlay::getNodeID(const LinkID& lid) const {
1076
1077        if( lid == LinkID::UNSPECIFIED ) return nodeId;
1078
1079        LinkMapping::const_iterator i = linkMapping.find( lid );
1080        if( i == linkMapping.end() ) return NodeID::UNSPECIFIED;
1081        else return i->second.node;
1082}
1083
1084vector<LinkID> BaseOverlay::getLinkIDs( const NodeID& nid ) const {
1085
1086        vector<LinkID> linkvector;
1087
1088        BOOST_FOREACH( LinkPair item, linkMapping ){
1089                if( item.second.node == nid || nid == NodeID::UNSPECIFIED ){
1090                        linkvector.push_back( item.second.link );
1091                }
1092        }
1093
1094        return linkvector;
1095}
1096
1097void BaseOverlay::incomingRouteMessage(Message* msg){
1098        // gets handled as normal data message
1099        receiveMessage( msg, LinkID::UNSPECIFIED, NodeID::UNSPECIFIED );
1100}
1101
1102void BaseOverlay::onNodeJoin(const NodeID& node){
1103
1104        JoiningNodes::iterator i = std::find( joiningNodes.begin(), joiningNodes.end(), node );
1105        if( i == joiningNodes.end() ) return;
1106
1107        logging_info( "node has successfully joined baseoverlay and overlay structure "
1108                                << node.toString() );
1109
1110        joiningNodes.erase( i );
1111}
1112
1113void BaseOverlay::eventFunction(){
1114
1115        list<LinkID> oldlinks;
1116        time_t now = time(NULL);
1117
1118        // first gather all the links from linkMapping that need droppin
1119        // don't directly drop, as the dropLink function affects the
1120        // linkMapping structure that we are traversing here.
1121        // drop links after a timeout of 30s
1122
1123        BOOST_FOREACH( LinkPair item, linkMapping ){
1124                if( item.second.autolink && difftime(now, item.second.lastuse) > 30)
1125                        oldlinks.push_back( item.first );
1126        }
1127
1128        BOOST_FOREACH( const LinkID lnk, oldlinks ) {
1129                logging_debug( "auto-link " << lnk.toString() << " timed out and is getting dropped" );
1130                dropLink( lnk );
1131        }
1132}
1133
1134}} // namespace ariba, overlay
Note: See TracBrowser for help on using the repository browser.