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

Last change on this file since 5944 was 5929, checked in by mies, 15 years ago
File size: 49.9 KB
Line 
1// [License]
2// The Ariba-Underlay Copyright
3//
4// Copyright (c) 2008-2009, Institute of Telematics, UniversitÀt Karlsruhe (TH)
5//
6// Institute of Telematics
7// UniversitÀt Karlsruhe (TH)
8// Zirkel 2, 76128 Karlsruhe
9// Germany
10//
11// Redistribution and use in source and binary forms, with or without
12// modification, are permitted provided that the following conditions are
13// met:
14//
15// 1. Redistributions of source code must retain the above copyright
16// notice, this list of conditions and the following disclaimer.
17// 2. Redistributions in binary form must reproduce the above copyright
18// notice, this list of conditions and the following disclaimer in the
19// documentation and/or other materials provided with the distribution.
20//
21// THIS SOFTWARE IS PROVIDED BY THE INSTITUTE OF TELEMATICS ``AS IS'' AND
22// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ARIBA PROJECT OR
25// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32//
33// The views and conclusions contained in the software and documentation
34// are those of the authors and should not be interpreted as representing
35// official policies, either expressed or implied, of the Institute of
36// Telematics.
37// [License]
38
39#include "BaseOverlay.h"
40
41#include <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 return overlayInterface->resolveNode( node );
919}
920
921// ----------------------------------------------------------------------------
922
923bool BaseOverlay::registerSidePort(SideportListener* _sideport) {
924 sideport = _sideport;
925 _sideport->configure( this );
926}
927
928bool BaseOverlay::unregisterSidePort(SideportListener* _sideport) {
929 sideport = &SideportListener::DEFAULT;
930}
931
932// ----------------------------------------------------------------------------
933
934bool BaseOverlay::bind(CommunicationListener* listener, const ServiceID& sid) {
935 logging_debug( "binding communication listener " << listener
936 << " on serviceid " << sid.toString() );
937
938 if( communicationListeners.contains( sid ) ) {
939 logging_error( "some listener already registered for service id "
940 << sid.toString() );
941 return false;
942 }
943
944 communicationListeners.registerItem( listener, sid );
945 return true;
946}
947
948
949bool BaseOverlay::unbind(CommunicationListener* listener, const ServiceID& sid) {
950 logging_debug( "unbinding listener " << listener << " from serviceid " << sid.toString() );
951
952 if( !communicationListeners.contains( sid ) ) {
953 logging_warn( "cannot unbind listener. no listener registered on service id " << sid.toString() );
954 return false;
955 }
956
957 if( communicationListeners.get(sid) != listener ) {
958 logging_warn( "listener bound to service id " << sid.toString()
959 << " is different than listener trying to unbind" );
960 return false;
961 }
962
963 communicationListeners.unregisterItem( sid );
964 return true;
965}
966
967// ----------------------------------------------------------------------------
968
969bool BaseOverlay::bind(NodeListener* listener) {
970 logging_debug( "Binding node listener " << listener );
971
972 // already bound? yes-> warning
973 NodeListenerVector::iterator i =
974 find( nodeListeners.begin(), nodeListeners.end(), listener );
975 if( i != nodeListeners.end() ) {
976 logging_warn("Node listener " << listener << " is already bound!" );
977 return false;
978 }
979
980 // no-> add
981 nodeListeners.push_back( listener );
982 return true;
983}
984
985bool BaseOverlay::unbind(NodeListener* listener) {
986 logging_debug( "Unbinding node listener " << listener );
987
988 // already unbound? yes-> warning
989 NodeListenerVector::iterator i = find( nodeListeners.begin(), nodeListeners.end(), listener );
990 if( i == nodeListeners.end() ) {
991 logging_warn( "Node listener " << listener << " is not bound!" );
992 return false;
993 }
994
995 // no-> remove
996 nodeListeners.erase( i );
997 return true;
998}
999
1000// ----------------------------------------------------------------------------
1001
1002void BaseOverlay::onLinkUp(const LinkID& id,
1003 const address_v* local, const address_v* remote) {
1004 logging_debug( "Link up with base communication link id=" << id );
1005
1006 // get descriptor for link
1007 LinkDescriptor* ld = getDescriptor(id, true);
1008
1009 // handle bootstrap link we initiated
1010 if( std::find(bootstrapLinks.begin(), bootstrapLinks.end(), id) != bootstrapLinks.end() ){
1011 logging_info(
1012 "Join has been initiated by me and the link is now up. " <<
1013 "Sending out join request for SpoVNet " << spovnetId.toString()
1014 );
1015
1016 // send join request message
1017 OverlayMsg overlayMsg( OverlayMsg::typeJoinRequest,
1018 OverlayInterface::OVERLAY_SERVICE_ID, nodeId );
1019 JoinRequest joinRequest( spovnetId, nodeId );
1020 overlayMsg.encapsulate( &joinRequest );
1021 bc->sendMessage( id, &overlayMsg );
1022 return;
1023 }
1024
1025 // no link found? -> link establishment from remote, add one!
1026 if (ld == NULL) {
1027 ld = addDescriptor( id );
1028 logging_info( "onLinkUp (remote request) descriptor: " << ld );
1029
1030 // update descriptor
1031 ld->fromRemote = true;
1032 ld->communicationId = id;
1033 ld->communicationUp = true;
1034 ld->setAutoUsed();
1035 ld->setAlive();
1036
1037 // in this case, do not inform listener, since service it unknown
1038 // -> wait for update message!
1039
1040 // link mapping found? -> send update message with node-id and service id
1041 } else {
1042 logging_info( "onLinkUp descriptor (initiated locally):" << ld );
1043
1044 // update descriptor
1045 ld->setAutoUsed();
1046 ld->setAlive();
1047 ld->communicationUp = true;
1048 ld->fromRemote = false;
1049
1050 // if link is a relayed link->convert to direct link
1051 if (ld->relayed) {
1052 logging_info( "Converting to direct link: " << ld );
1053 ld->up = true;
1054 ld->relayed = false;
1055 OverlayMsg overMsg( OverlayMsg::typeLinkDirect );
1056 overMsg.setSourceLink( ld->overlayId );
1057 overMsg.setDestinationLink( ld->remoteLink );
1058 send_link( &overMsg, ld->overlayId );
1059 } else {
1060 // note: necessary to validate the link on the remote side!
1061 logging_info( "Sending out update" <<
1062 " for service " << ld->service.toString() <<
1063 " with local node id " << nodeId.toString() <<
1064 " on link " << ld->overlayId.toString() );
1065
1066 // compile and send update message
1067 OverlayMsg overlayMsg( OverlayMsg::typeLinkUpdate );
1068 overlayMsg.setSourceLink(ld->overlayId);
1069 overlayMsg.setAutoLink( ld->autolink );
1070 send_link( &overlayMsg, ld->overlayId, true );
1071 }
1072 }
1073}
1074
1075void BaseOverlay::onLinkDown(const LinkID& id,
1076 const address_v* local, const address_v* remote) {
1077
1078 // erase bootstrap links
1079 vector<LinkID>::iterator it = std::find( bootstrapLinks.begin(), bootstrapLinks.end(), id );
1080 if( it != bootstrapLinks.end() ) bootstrapLinks.erase( it );
1081
1082 // get descriptor for link
1083 LinkDescriptor* ld = getDescriptor(id, true);
1084 if ( ld == NULL ) return; // not found? ->ignore!
1085 logging_info( "onLinkDown descriptor: " << ld );
1086
1087 // removing relay link information
1088 removeRelayLink(ld->overlayId);
1089
1090 // inform listeners about link down
1091 ld->communicationUp = false;
1092 if (!ld->service.isUnspecified()) {
1093 getListener(ld->service)->onLinkDown( ld->overlayId, ld->remoteNode );
1094 sideport->onLinkDown( id, this->nodeId, ld->remoteNode, this->spovnetId );
1095 }
1096
1097 // delete all queued messages (auto links)
1098 if( ld->messageQueue.size() > 0 ) {
1099 logging_warn( "Dropping link " << id.toString() << " that has "
1100 << ld->messageQueue.size() << " waiting messages" );
1101 ld->flushQueue();
1102 }
1103
1104 // erase mapping
1105 eraseDescriptor(ld->overlayId);
1106}
1107
1108void BaseOverlay::onLinkChanged(const LinkID& id,
1109 const address_v* oldlocal, const address_v* newlocal,
1110 const address_v* oldremote, const address_v* newremote) {
1111
1112 // get descriptor for link
1113 LinkDescriptor* ld = getDescriptor(id, true);
1114 if ( ld == NULL ) return; // not found? ->ignore!
1115 logging_debug( "onLinkChanged descriptor: " << ld );
1116
1117 // inform listeners
1118 ld->listener->onLinkChanged( ld->overlayId, ld->remoteNode );
1119 sideport->onLinkChanged( id, this->nodeId, ld->remoteNode, this->spovnetId );
1120
1121 // autolinks: refresh timestamp
1122 ld->setAutoUsed();
1123}
1124
1125void BaseOverlay::onLinkFail(const LinkID& id,
1126 const address_v* local, const address_v* remote) {
1127 logging_debug( "Link fail with base communication link id=" << id );
1128
1129 // erase bootstrap links
1130 vector<LinkID>::iterator it = std::find( bootstrapLinks.begin(), bootstrapLinks.end(), id );
1131 if( it != bootstrapLinks.end() ) bootstrapLinks.erase( it );
1132
1133 // get descriptor for link
1134 LinkDescriptor* ld = getDescriptor(id, true);
1135 if ( ld == NULL ) return; // not found? ->ignore!
1136 logging_debug( "Link failed id=" << ld->overlayId.toString() );
1137
1138 // inform listeners
1139 ld->listener->onLinkFail( ld->overlayId, ld->remoteNode );
1140 sideport->onLinkFail( id, this->nodeId, ld->remoteNode, this->spovnetId );
1141}
1142
1143void BaseOverlay::onLinkQoSChanged(const LinkID& id, const address_v* local,
1144 const address_v* remote, const QoSParameterSet& qos) {
1145 logging_debug( "Link quality changed with base communication link id=" << id );
1146
1147 // get descriptor for link
1148 LinkDescriptor* ld = getDescriptor(id, true);
1149 if ( ld == NULL ) return; // not found? ->ignore!
1150 logging_debug( "Link quality changed id=" << ld->overlayId.toString() );
1151}
1152
1153bool BaseOverlay::onLinkRequest( const LinkID& id, const address_v* local,
1154 const address_v* remote ) {
1155 logging_debug("Accepting link request from " << remote->to_string() );
1156 return true;
1157}
1158
1159/// handles a message from base communication
1160bool BaseOverlay::receiveMessage(const Message* message,
1161 const LinkID& link, const NodeID& ) {
1162 // get descriptor for link
1163 LinkDescriptor* ld = getDescriptor( link, true );
1164 return handleMessage( message, ld, link );
1165}
1166
1167// ----------------------------------------------------------------------------
1168
1169/// Handle spovnet instance join requests
1170bool BaseOverlay::handleJoinRequest( OverlayMsg* overlayMsg, const LinkID& bcLink ) {
1171
1172 // decapsulate message
1173 JoinRequest* joinReq = overlayMsg->decapsulate<JoinRequest>();
1174 logging_info( "Received join request for spovnet " <<
1175 joinReq->getSpoVNetID().toString() );
1176
1177 // check spovnet id
1178 if( joinReq->getSpoVNetID() != spovnetId ) {
1179 logging_error(
1180 "Received join request for spovnet we don't handle " <<
1181 joinReq->getSpoVNetID().toString() );
1182 return false;
1183 }
1184
1185 // TODO: here you can implement mechanisms to deny joining of a node
1186 bool allow = true;
1187 logging_info( "Sending join reply for spovnet " <<
1188 spovnetId.toString() << " to node " <<
1189 overlayMsg->getSourceNode().toString() <<
1190 ". Result: " << (allow ? "allowed" : "denied") );
1191 joiningNodes.push_back( overlayMsg->getSourceNode() );
1192
1193 // return overlay parameters
1194 assert( overlayInterface != NULL );
1195 logging_debug( "Using bootstrap end-point "
1196 << getEndpointDescriptor().toString() )
1197 OverlayParameterSet parameters = overlayInterface->getParameters();
1198 OverlayMsg retmsg( OverlayMsg::typeJoinReply,
1199 OverlayInterface::OVERLAY_SERVICE_ID, nodeId );
1200 JoinReply replyMsg( spovnetId, parameters,
1201 allow, getEndpointDescriptor() );
1202 retmsg.encapsulate(&replyMsg);
1203 bc->sendMessage( bcLink, &retmsg );
1204
1205 return true;
1206}
1207
1208/// Handle replies to spovnet instance join requests
1209bool BaseOverlay::handleJoinReply( OverlayMsg* overlayMsg, const LinkID& bcLink ) {
1210 // decapsulate message
1211 logging_debug("received join reply message");
1212 JoinReply* replyMsg = overlayMsg->decapsulate<JoinReply>();
1213
1214 // correct spovnet?
1215 if( replyMsg->getSpoVNetID() != spovnetId ) { // no-> fail
1216 logging_error( "Received SpoVNet join reply for " <<
1217 replyMsg->getSpoVNetID().toString() <<
1218 " != " << spovnetId.toString() );
1219 delete replyMsg;
1220 return false;
1221 }
1222
1223 // access granted? no -> fail
1224 if( !replyMsg->getJoinAllowed() ) {
1225 logging_error( "Our join request has been denied" );
1226
1227 // drop initiator link
1228 if( !bcLink.isUnspecified() ){
1229 bc->dropLink( bcLink );
1230
1231 vector<LinkID>::iterator it = std::find(
1232 bootstrapLinks.begin(), bootstrapLinks.end(), bcLink);
1233 if( it != bootstrapLinks.end() )
1234 bootstrapLinks.erase(it);
1235 }
1236
1237 // inform all registered services of the event
1238 BOOST_FOREACH( NodeListener* i, nodeListeners )
1239 i->onJoinFailed( spovnetId );
1240
1241 delete replyMsg;
1242 return true;
1243 }
1244
1245 // access has been granted -> continue!
1246 logging_info("Join request has been accepted for spovnet " <<
1247 spovnetId.toString() );
1248
1249 logging_debug( "Using bootstrap end-point "
1250 << replyMsg->getBootstrapEndpoint().toString() );
1251
1252 // create overlay structure from spovnet parameter set
1253 // if we have not boostrapped yet against some other node
1254 if( overlayInterface == NULL ){
1255
1256 logging_debug("first-time bootstrapping");
1257
1258 overlayInterface = OverlayFactory::create(
1259 *this, replyMsg->getParam(), nodeId, this );
1260
1261 // overlay structure supported? no-> fail!
1262 if( overlayInterface == NULL ) {
1263 logging_error( "overlay structure not supported" );
1264
1265 if( !bcLink.isUnspecified() ){
1266 bc->dropLink( bcLink );
1267
1268 vector<LinkID>::iterator it = std::find(
1269 bootstrapLinks.begin(), bootstrapLinks.end(), bcLink);
1270 if( it != bootstrapLinks.end() )
1271 bootstrapLinks.erase(it);
1272 }
1273
1274 // inform all registered services of the event
1275 BOOST_FOREACH( NodeListener* i, nodeListeners )
1276 i->onJoinFailed( spovnetId );
1277
1278 delete replyMsg;
1279 return true;
1280 }
1281
1282 // everything ok-> join the overlay!
1283 state = BaseOverlayStateCompleted;
1284 overlayInterface->createOverlay();
1285
1286 overlayInterface->joinOverlay( replyMsg->getBootstrapEndpoint() );
1287 overlayBootstrap.recordJoin( replyMsg->getBootstrapEndpoint() );
1288
1289 // update ovlvis
1290 //ovl.visChangeNodeColor( ovlId, nodeId, OvlVis::NODE_COLORS_GREEN);
1291
1292 // inform all registered services of the event
1293 BOOST_FOREACH( NodeListener* i, nodeListeners )
1294 i->onJoinCompleted( spovnetId );
1295
1296 delete replyMsg;
1297
1298 } else {
1299
1300 // this is not the first bootstrap, just join the additional node
1301 logging_debug("not first-time bootstrapping");
1302 overlayInterface->joinOverlay( replyMsg->getBootstrapEndpoint() );
1303 overlayBootstrap.recordJoin( replyMsg->getBootstrapEndpoint() );
1304
1305 delete replyMsg;
1306
1307 } // if( overlayInterface == NULL )
1308
1309 return true;
1310}
1311
1312
1313bool BaseOverlay::handleData( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1314 // get service
1315 const ServiceID& service = overlayMsg->getService();
1316 logging_debug( "Received data for service " << service.toString()
1317 << " on link " << overlayMsg->getDestinationLink().toString() );
1318
1319 // delegate data message
1320 getListener(service)->onMessage(
1321 overlayMsg,
1322 overlayMsg->getSourceNode(),
1323 overlayMsg->getDestinationLink()
1324 );
1325
1326 return true;
1327}
1328
1329
1330bool BaseOverlay::handleLinkUpdate( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1331
1332 if( ld == NULL ) {
1333 logging_warn( "received overlay update message for link for "
1334 << "which we have no mapping" );
1335 return false;
1336 }
1337 logging_info("Received type update message on link " << ld );
1338
1339 // update our link mapping information for this link
1340 bool changed =
1341 ( ld->remoteNode != overlayMsg->getSourceNode() )
1342 || ( ld->service != overlayMsg->getService() );
1343
1344 // set parameters
1345 ld->up = true;
1346 ld->remoteNode = overlayMsg->getSourceNode();
1347 ld->remoteLink = overlayMsg->getSourceLink();
1348 ld->service = overlayMsg->getService();
1349 ld->autolink = overlayMsg->isAutoLink();
1350
1351 // if our link information changed, we send out an update, too
1352 if( changed ) {
1353 overlayMsg->swapRoles();
1354 overlayMsg->setSourceNode(nodeId);
1355 overlayMsg->setSourceLink(ld->overlayId);
1356 overlayMsg->setService(ld->service);
1357 send( overlayMsg, ld );
1358 }
1359
1360 // service registered? no-> error!
1361 if( !communicationListeners.contains( ld->service ) ) {
1362 logging_warn( "Link up: event listener has not been registered" );
1363 return false;
1364 }
1365
1366 // default or no service registered?
1367 CommunicationListener* listener = communicationListeners.get( ld->service );
1368 if( listener == NULL || listener == &CommunicationListener::DEFAULT ) {
1369 logging_warn("Link up: event listener is default or null!" );
1370 return true;
1371 }
1372
1373 // update descriptor
1374 ld->listener = listener;
1375 ld->setAutoUsed();
1376 ld->setAlive();
1377
1378 // ask the service whether it wants to accept this link
1379 if( !listener->onLinkRequest(ld->remoteNode) ) {
1380
1381 logging_debug("Link id=" << ld->overlayId.toString() <<
1382 " has been denied by service " << ld->service.toString() << ", dropping link");
1383
1384 // prevent onLinkDown calls to the service
1385 ld->listener = &CommunicationListener::DEFAULT;
1386
1387 // drop the link
1388 dropLink( ld->overlayId );
1389 return true;
1390 }
1391
1392 // set link up
1393 ld->up = true;
1394 logging_info( "Link has been accepted by service and is up: " << ld );
1395
1396 // auto links: link has been accepted -> send queued messages
1397 if( ld->messageQueue.size() > 0 ) {
1398 logging_info( "Sending out queued messages on link " << ld );
1399 BOOST_FOREACH( Message* msg, ld->messageQueue ) {
1400 sendMessage( msg, ld->overlayId );
1401 delete msg;
1402 }
1403 ld->messageQueue.clear();
1404 }
1405
1406 // call the notification functions
1407 listener->onLinkUp( ld->overlayId, ld->remoteNode );
1408 sideport->onLinkUp( ld->overlayId, nodeId, ld->remoteNode, this->spovnetId );
1409
1410 return true;
1411}
1412
1413/// handle a link request and reply
1414bool BaseOverlay::handleLinkRequest( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1415 logging_info( "Link request received from node id=" << overlayMsg->getSourceNode() );
1416
1417 //TODO: Check if a request has already been sent using getSourceLink() ...
1418
1419 // create link descriptor
1420 LinkDescriptor* ldn = addDescriptor();
1421
1422 // flags
1423 ldn->up = true;
1424 ldn->fromRemote = true;
1425 ldn->relayed = true;
1426
1427 // parameters
1428 ldn->service = overlayMsg->getService();
1429 ldn->listener = getListener(ldn->service);
1430 ldn->remoteNode = overlayMsg->getSourceNode();
1431 ldn->remoteLink = overlayMsg->getSourceLink();
1432
1433 // update time-stamps
1434 ldn->setAlive();
1435 ldn->setAutoUsed();
1436
1437 // create reply message and send back!
1438 overlayMsg->swapRoles(); // swap source/destination
1439 overlayMsg->setType(OverlayMsg::typeLinkReply);
1440 overlayMsg->setSourceLink(ldn->overlayId);
1441 overlayMsg->setSourceEndpoint( bc->getEndpointDescriptor() );
1442 overlayMsg->setRelayed(true);
1443 send( overlayMsg, ld ); // send back to link
1444
1445 // inform listener
1446 ldn->listener->onLinkUp( ldn->overlayId, ldn->remoteNode );
1447
1448 return true;
1449}
1450
1451bool BaseOverlay::handleLinkReply( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1452
1453 // find link request
1454 LinkDescriptor* ldn = getDescriptor(overlayMsg->getDestinationLink());
1455
1456 // not found? yes-> drop with error!
1457 if (ldn == NULL) {
1458 logging_error( "No link request pending for "
1459 << overlayMsg->getDestinationLink().toString() );
1460 return false;
1461 }
1462 logging_debug("Handling link reply for " << ldn )
1463
1464 // check if already up
1465 if (ldn->up) {
1466 logging_warn( "Link already up: " << ldn );
1467 return true;
1468 }
1469
1470 // debug message
1471 logging_debug( "Link request reply received. Establishing link"
1472 << " for service " << overlayMsg->getService().toString()
1473 << " with local id=" << overlayMsg->getDestinationLink()
1474 << " and remote link id=" << overlayMsg->getSourceLink()
1475 << " to " << overlayMsg->getSourceEndpoint().toString()
1476 );
1477
1478 // set local link descriptor data
1479 ldn->up = true;
1480 ldn->relayed = true;
1481 ldn->service = overlayMsg->getService();
1482 ldn->listener = getListener(ldn->service);
1483 ldn->remoteLink = overlayMsg->getSourceLink();
1484 ldn->remoteNode = overlayMsg->getSourceNode();
1485
1486 // update timestamps
1487 ldn->setAlive();
1488 ldn->setAutoUsed();
1489
1490 // auto links: link has been accepted -> send queued messages
1491 if( ldn->messageQueue.size() > 0 ) {
1492 logging_info( "Sending out queued messages on link " <<
1493 ldn->overlayId.toString() );
1494 BOOST_FOREACH( Message* msg, ldn->messageQueue ) {
1495 sendMessage( msg, ldn->overlayId );
1496 delete msg;
1497 }
1498 ldn->messageQueue.clear();
1499 }
1500
1501 // inform listeners about new link
1502 ldn->listener->onLinkUp( ldn->overlayId, ldn->remoteNode );
1503
1504 // try to replace relay link with direct link
1505 ldn->communicationId =
1506 bc->establishLink( overlayMsg->getSourceEndpoint() );
1507
1508 return true;
1509}
1510
1511/// handle a keep-alive message for a link
1512bool BaseOverlay::handleLinkAlive( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1513 LinkDescriptor* rld = getDescriptor(overlayMsg->getDestinationLink());
1514 if ( rld != NULL ) {
1515 logging_debug("Keep-Alive for " <<
1516 overlayMsg->getDestinationLink() );
1517 if (overlayMsg->isRouteRecord())
1518 rld->routeRecord = overlayMsg->getRouteRecord();
1519 rld->setAlive();
1520 return true;
1521 } else {
1522 logging_error("Keep-Alive for "
1523 << overlayMsg->getDestinationLink() << ": link unknown." );
1524 return false;
1525 }
1526}
1527
1528/// handle a direct link message
1529bool BaseOverlay::handleLinkDirect( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1530 logging_debug( "Received direct link replacement request" );
1531
1532 /// get destination overlay link
1533 LinkDescriptor* rld = getDescriptor( overlayMsg->getDestinationLink() );
1534 if (rld == NULL || ld == NULL) {
1535 logging_error("Direct link replacement: Link "
1536 << overlayMsg->getDestinationLink() << "not found error." );
1537 return false;
1538 }
1539 logging_info( "Received direct link convert notification for " << rld );
1540
1541 // update information
1542 rld->communicationId = ld->communicationId;
1543 rld->communicationUp = true;
1544 rld->relayed = false;
1545
1546 // mark used and alive!
1547 rld->setAlive();
1548 rld->setAutoUsed();
1549
1550 // erase the original descriptor
1551 eraseDescriptor(ld->overlayId);
1552}
1553
1554/// handles an incoming message
1555bool BaseOverlay::handleMessage( const Message* message, LinkDescriptor* ld,
1556 const LinkID bcLink ) {
1557 logging_debug( "Handling message: " << message->toString());
1558
1559 // decapsulate overlay message
1560 OverlayMsg* overlayMsg =
1561 const_cast<Message*>(message)->decapsulate<OverlayMsg>();
1562 if( overlayMsg == NULL ) return false;
1563
1564 // increase number of hops
1565 overlayMsg->increaseNumHops();
1566
1567 // refresh relay information
1568 refreshRelayInformation( overlayMsg, ld );
1569
1570 // update route record
1571 overlayMsg->addRouteRecord(nodeId);
1572
1573 // handle signaling messages (do not route!)
1574 if (overlayMsg->getType()>=OverlayMsg::typeSignalingStart &&
1575 overlayMsg->getType()<=OverlayMsg::typeSignalingEnd ) {
1576 overlayInterface->onMessage(overlayMsg, NodeID::UNSPECIFIED, LinkID::UNSPECIFIED);
1577 delete overlayMsg;
1578 return true;
1579 }
1580
1581 // message for reached destination? no-> route message
1582 if (!overlayMsg->getDestinationNode().isUnspecified() &&
1583 overlayMsg->getDestinationNode() != nodeId ) {
1584 logging_debug("Routing message "
1585 << " from " << overlayMsg->getSourceNode()
1586 << " to " << overlayMsg->getDestinationNode()
1587 );
1588 route( overlayMsg );
1589 delete overlayMsg;
1590 return true;
1591 }
1592
1593 // handle base overlay message
1594 bool ret = false; // return value
1595 switch ( overlayMsg->getType() ) {
1596
1597 // data transport messages
1598 case OverlayMsg::typeData:
1599 ret = handleData(overlayMsg, ld); break;
1600
1601 // overlay setup messages
1602 case OverlayMsg::typeJoinRequest:
1603 ret = handleJoinRequest(overlayMsg, bcLink ); break;
1604 case OverlayMsg::typeJoinReply:
1605 ret = handleJoinReply(overlayMsg, bcLink ); break;
1606
1607 // link specific messages
1608 case OverlayMsg::typeLinkRequest:
1609 ret = handleLinkRequest(overlayMsg, ld ); break;
1610 case OverlayMsg::typeLinkReply:
1611 ret = handleLinkReply(overlayMsg, ld ); break;
1612 case OverlayMsg::typeLinkUpdate:
1613 ret = handleLinkUpdate(overlayMsg, ld ); break;
1614 case OverlayMsg::typeLinkAlive:
1615 ret = handleLinkAlive(overlayMsg, ld ); break;
1616 case OverlayMsg::typeLinkDirect:
1617 ret = handleLinkDirect(overlayMsg, ld ); break;
1618
1619 // handle unknown message type
1620 default: {
1621 logging_error( "received message in invalid state! don't know " <<
1622 "what to do with this message of type " << overlayMsg->getType() );
1623 ret = false;
1624 break;
1625 }
1626 }
1627
1628 // free overlay message and return value
1629 delete overlayMsg;
1630 return ret;
1631}
1632
1633// ----------------------------------------------------------------------------
1634
1635void BaseOverlay::broadcastMessage(Message* message, const ServiceID& service) {
1636
1637 logging_debug( "broadcasting message to all known nodes " <<
1638 "in the overlay from service " + service.toString() );
1639
1640 OverlayInterface::NodeList nodes = overlayInterface->getKnownNodes(true);
1641 OverlayInterface::NodeList::iterator i = nodes.begin();
1642 for(; i != nodes.end(); i++ ) {
1643 if( *i == nodeId) continue; // don't send to ourselfs
1644 sendMessage( message, *i, service );
1645 }
1646}
1647
1648/// return the overlay neighbors
1649vector<NodeID> BaseOverlay::getOverlayNeighbors(bool deep) const {
1650 // the known nodes _can_ also include our node, so we remove ourself
1651 vector<NodeID> nodes = overlayInterface->getKnownNodes(deep);
1652 vector<NodeID>::iterator i = find( nodes.begin(), nodes.end(), this->nodeId );
1653 if( i != nodes.end() ) nodes.erase( i );
1654 return nodes;
1655}
1656
1657const NodeID& BaseOverlay::getNodeID(const LinkID& lid) const {
1658 if( lid == LinkID::UNSPECIFIED ) return nodeId;
1659 const LinkDescriptor* ld = getDescriptor(lid);
1660 if( ld == NULL ) return NodeID::UNSPECIFIED;
1661 else return ld->remoteNode;
1662}
1663
1664vector<LinkID> BaseOverlay::getLinkIDs( const NodeID& nid ) const {
1665 vector<LinkID> linkvector;
1666 BOOST_FOREACH( LinkDescriptor* ld, links ) {
1667 if( ld->remoteNode == nid || nid == NodeID::UNSPECIFIED ) {
1668 linkvector.push_back( ld->overlayId );
1669 }
1670 }
1671 return linkvector;
1672}
1673
1674
1675void BaseOverlay::onNodeJoin(const NodeID& node) {
1676 JoiningNodes::iterator i = std::find( joiningNodes.begin(), joiningNodes.end(), node );
1677 if( i == joiningNodes.end() ) return;
1678
1679 logging_info( "node has successfully joined baseoverlay and overlay structure "
1680 << node.toString() );
1681
1682 joiningNodes.erase( i );
1683}
1684
1685void BaseOverlay::eventFunction() {
1686 stabilizeRelays();
1687 stabilizeLinks();
1688}
1689
1690}} // namespace ariba, overlay
Note: See TracBrowser for help on using the repository browser.