An Overlay-based
Virtual Network Substrate
SpoVNet

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

Last change on this file since 3690 was 3690, checked in by mies, 14 years ago

Merged 20090512-mies-connectors changes r3472:r3689 into trunk.

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