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

Last change on this file since 6133 was 6133, checked in by Christoph Mayer, 15 years ago

remote endpoint auflösung gefixt

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