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

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