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

Last change on this file since 6916 was 6916, checked in by Christoph Mayer, 15 years ago
File size: 65.4 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/DHTMessage.h"
54#include "ariba/overlay/messages/JoinRequest.h"
55#include "ariba/overlay/messages/JoinReply.h"
56
57#include "ariba/utility/visual/OvlVis.h"
58#include "ariba/utility/visual/DddVis.h"
59#include "ariba/utility/visual/ServerVis.h"
60
61namespace ariba {
62namespace overlay {
63
64#define visual ariba::utility::DddVis::instance()
65#define visualIdOverlay ariba::utility::ServerVis::NETWORK_ID_BASE_OVERLAY
66#define visualIdBase ariba::utility::ServerVis::NETWORK_ID_BASE_COMMUNICATION
67
68class ValueEntry {
69public:
70 ValueEntry( const Data& value ) : ttl(0), last_update(time(NULL)),
71 last_change(time(NULL)), value(value.clone()) {
72 }
73
74 ValueEntry( const ValueEntry& value ) :
75 ttl(value.ttl), last_update(value.last_update),
76 last_change(value.last_change), value(value.value.clone()) {
77
78 }
79
80 ~ValueEntry() {
81 value.release();
82 }
83
84 void refresh() {
85 last_update = time(NULL);
86 }
87
88 void set_value( const Data& value ) {
89 this->value.release();
90 this->value = value.clone();
91 this->last_change = time(NULL);
92 this->last_update = time(NULL);
93 }
94
95 Data get_value() const {
96 return value;
97 }
98
99 uint16_t get_ttl() const {
100 return ttl;
101 }
102
103 void set_ttl( uint16_t ttl ) {
104 this->ttl = ttl;
105 }
106
107 bool is_ttl_elapsed() const {
108 // is persistent? yes-> always return false
109 if (ttl==0) return false;
110
111 // return true, if ttl is elapsed
112 return ( difftime( time(NULL), this->last_update ) >= ttl );
113 }
114
115private:
116 uint16_t ttl;
117 time_t last_update;
118 time_t last_change;
119 Data value;
120};
121
122class DHTEntry {
123public:
124 Data key;
125 vector<ValueEntry> values;
126
127 vector<Data> get_values() {
128 vector<Data> vect;
129 BOOST_FOREACH( ValueEntry& e, values )
130 vect.push_back( e.get_value() );
131 return vect;
132 }
133
134 void erase_expired_entries() {
135 for (vector<ValueEntry>::iterator i = values.begin();
136 i != values.end(); i++ )
137 if (i->is_ttl_elapsed()) i = values.erase(i);
138 }
139};
140
141class DHT {
142public:
143 typedef vector<DHTEntry> Entries;
144 typedef vector<ValueEntry> Values;
145 Entries entries;
146 static const bool verbose = false;
147
148 static bool equals( const Data& lhs, const Data& rhs ) {
149 if (rhs.getLength()!=lhs.getLength()) return false;
150 for (int i=0; i<lhs.getLength()/8; i++)
151 if (lhs.getBuffer()[i] != rhs.getBuffer()[i]) return false;
152 return true;
153 }
154
155 void put( const Data& key, const Data& value, uint16_t ttl = 0 ) {
156
157 // find entry
158 for (size_t i=0; i<entries.size(); i++) {
159 DHTEntry& entry = entries.at(i);
160
161 // check if key is already known
162 if ( equals(entry.key, key) ) {
163
164 // check if value is already in values list
165 for (size_t j=0; j<entry.values.size(); j++) {
166 // found value already? yes-> refresh ttl
167 if ( equals(entry.values[j].get_value(), value) ) {
168 entry.values[j].refresh();
169 if (verbose)
170 std::cout << "DHT: Republished value. Refreshing value timestamp."
171 << std::endl;
172 return;
173 }
174 }
175
176 // new value-> add to entry
177 if (verbose)
178 std::cout << "DHT: Added value to "
179 << " key=" << key << " with value=" << value << std::endl;
180 entry.values.push_back( ValueEntry( value ) );
181 entry.values.back().set_ttl(ttl);
182 return;
183 }
184 }
185
186 // key is unknown-> add key value pair
187 if (verbose)
188 std::cout << "DHT: New key value pair "
189 << " key=" << key << " with value=" << value << std::endl;
190
191 // add new entry
192 entries.push_back( DHTEntry() );
193 DHTEntry& entry = entries.back();
194 entry.key = key.clone();
195 entry.values.push_back( ValueEntry(value) );
196 entry.values.back().set_ttl(ttl);
197 }
198
199 vector<Data> get( const Data& key ) {
200 // find entry
201 for (size_t i=0; i<entries.size(); i++) {
202 DHTEntry& entry = entries.at(i);
203 if ( equals(entry.key,key) )
204 return entry.get_values();
205 }
206 return vector<Data>();
207 }
208
209 bool remove( const Data& key ) {
210 // find entry
211 for (Entries::iterator i = entries.begin(); i != entries.end(); i++) {
212 DHTEntry& entry = *i;
213
214 // found? yes-> delete entry
215 if ( equals(entry.key, key) ) {
216 i = entries.erase(i);
217 return true;
218 }
219 }
220 return false;
221 }
222
223 bool remove( const Data& key, const Data& value ) {
224 // find entry
225 for (Entries::iterator i = entries.begin(); i != entries.end(); i++) {
226 DHTEntry& entry = *i;
227
228 // found? yes-> try to find value
229 if ( equals(entry.key, key) ) {
230 for (Values::iterator j = entry.values.begin();
231 j != entry.values.end(); j++) {
232
233 // value found? yes-> delete
234 if (equals(j->get_value(), value)) {
235 j = entry.values.erase(j);
236 return true;
237 }
238 }
239 }
240 }
241 return false;
242 }
243
244 void cleanup() {
245 // find entry
246 for (Entries::iterator i = entries.begin(); i != entries.end(); i++) {
247 DHTEntry& entry = *i;
248
249 for (Values::iterator j = entry.values.begin();
250 j != entry.values.end(); j++) {
251
252 // value found? yes-> delete
253 if (j->is_ttl_elapsed())
254 j = entry.values.erase(j);
255 }
256
257 if (entry.values.size()==0) i = entries.erase(i);
258 }
259 }
260};
261
262// ----------------------------------------------------------------------------
263
264/* *****************************************************************************
265 * PREREQUESITES
266 * ****************************************************************************/
267
268CommunicationListener* BaseOverlay::getListener( const ServiceID& service ) {
269 if( !communicationListeners.contains( service ) ) {
270 logging_error( "No listener found for service " << service.toString() );
271 return NULL;
272 }
273 CommunicationListener* listener = communicationListeners.get( service );
274 assert( listener != NULL );
275 return listener;
276}
277
278// link descriptor handling ----------------------------------------------------
279
280LinkDescriptor* BaseOverlay::getDescriptor( const LinkID& link, bool communication ) {
281 BOOST_FOREACH( LinkDescriptor* lp, links )
282 if ((communication ? lp->communicationId : lp->overlayId) == link)
283 return lp;
284 return NULL;
285}
286
287const LinkDescriptor* BaseOverlay::getDescriptor( const LinkID& link, bool communication ) const {
288 BOOST_FOREACH( const LinkDescriptor* lp, links )
289 if ((communication ? lp->communicationId : lp->overlayId) == link)
290 return lp;
291 return NULL;
292}
293
294/// erases a link descriptor
295void BaseOverlay::eraseDescriptor( const LinkID& link, bool communication ) {
296 for ( vector<LinkDescriptor*>::iterator i = links.begin(); i!= links.end(); i++) {
297 LinkDescriptor* ld = *i;
298 if ((communication ? ld->communicationId : ld->overlayId) == link) {
299 delete ld;
300 links.erase(i);
301 break;
302 }
303 }
304}
305
306/// adds a link descriptor
307LinkDescriptor* BaseOverlay::addDescriptor( const LinkID& link ) {
308 LinkDescriptor* desc = getDescriptor( link );
309 if ( desc == NULL ) {
310 desc = new LinkDescriptor();
311 if (!link.isUnspecified()) desc->overlayId = link;
312 links.push_back(desc);
313 }
314 return desc;
315}
316
317/// returns a auto-link descriptor
318LinkDescriptor* BaseOverlay::getAutoDescriptor( const NodeID& node, const ServiceID& service ) {
319 // search for a descriptor that is already up
320 BOOST_FOREACH( LinkDescriptor* lp, links )
321 if (lp->autolink && lp->remoteNode == node && lp->service == service && lp->up && lp->keepAliveMissed == 0)
322 return lp;
323 // if not found, search for one that is about to come up...
324 BOOST_FOREACH( LinkDescriptor* lp, links )
325 if (lp->autolink && lp->remoteNode == node && lp->service == service && lp->keepAliveMissed == 0 )
326 return lp;
327 return NULL;
328}
329
330/// stabilizes link information
331void BaseOverlay::stabilizeLinks() {
332 // send keep-alive messages over established links
333 BOOST_FOREACH( LinkDescriptor* ld, links ) {
334 if (!ld->up) continue;
335 OverlayMsg msg( OverlayMsg::typeLinkAlive,
336 OverlayInterface::OVERLAY_SERVICE_ID, nodeId, ld->remoteNode );
337 if (ld->relayed) msg.setRouteRecord(true);
338 send_link( &msg, ld->overlayId );
339 }
340
341 // iterate over all links and check for time boundaries
342 vector<LinkDescriptor*> oldlinks;
343 time_t now = time(NULL);
344 BOOST_FOREACH( LinkDescriptor* ld, links ) {
345
346 // keep alives and not up? yes-> link connection request is stale!
347 if ( !ld->up && difftime( now, ld->keepAliveTime ) >= 2 ) {
348
349 // increase counter
350 ld->keepAliveMissed++;
351
352 // missed more than four keep-alive messages (10 sec)? -> drop link
353 if (ld->keepAliveMissed > 4) {
354 logging_info( "Link connection request is stale, closing: " << ld );
355 oldlinks.push_back( ld );
356 continue;
357 }
358 }
359
360 if (!ld->up) continue;
361
362 // remote used as relay flag
363 if ( ld->relaying && difftime( now, ld->timeRelaying ) > 10)
364 ld->relaying = false;
365
366 // drop links that are dropped and not used as relay
367 if (ld->dropAfterRelaying && !ld->relaying && !ld->autolink) {
368 oldlinks.push_back( ld );
369 continue;
370 }
371
372 // auto-link time exceeded?
373 if ( ld->autolink && difftime( now, ld->lastuse ) > 30 ) {
374 oldlinks.push_back( ld );
375 continue;
376 }
377
378 // keep alives missed? yes->
379 if ( difftime( now, ld->keepAliveTime ) > 2 ) {
380
381 // increase counter
382 ld->keepAliveMissed++;
383
384 // missed more than four keep-alive messages (4 sec)? -> drop link
385 if (ld->keepAliveMissed >= 4) {
386 logging_info( "Link is stale, closing: " << ld );
387 oldlinks.push_back( ld );
388 continue;
389 }
390 }
391 }
392
393 // drop links
394 BOOST_FOREACH( LinkDescriptor* ld, oldlinks ) {
395 logging_info( "Link timed out. Dropping " << ld );
396 ld->relaying = false;
397 dropLink( ld->overlayId );
398 }
399
400 // show link state
401 counter++;
402 if (counter>=4) showLinks();
403 if (counter>=4 || counter<0) counter = 0;
404}
405
406
407std::string BaseOverlay::getLinkHTMLInfo() {
408 std::ostringstream s;
409 vector<NodeID> nodes;
410 if (links.size()==0) {
411 s << "<h2 style=\"color=#606060\">No links established!</h2>";
412 } else {
413 s << "<h2 style=\"color=#606060\">Links</h2>";
414 s << "<table width=\"100%\" cellpadding=\"0\" border=\"0\" cellspacing=\"0\">";
415 s << "<tr style=\"background-color=#ffe0e0\">";
416 s << "<td><b>Link ID</b></td><td><b>Remote ID</b></td><td><b>Relay path</b></td>";
417 s << "</tr>";
418
419 int i=0;
420 BOOST_FOREACH( LinkDescriptor* ld, links ) {
421 if (!ld->isVital() || ld->service != OverlayInterface::OVERLAY_SERVICE_ID) continue;
422 bool found = false;
423 BOOST_FOREACH(NodeID& id, nodes)
424 if (id == ld->remoteNode) found = true;
425 if (found) continue;
426 i++;
427 nodes.push_back(ld->remoteNode);
428 if ((i%1) == 1) s << "<tr style=\"background-color=#f0f0f0;\">";
429 else s << "<tr>";
430 s << "<td>" << ld->overlayId.toString().substr(0,4) << "..</td>";
431 s << "<td>" << ld->remoteNode.toString().substr(0,4) << "..</td>";
432 s << "<td>";
433 if (ld->routeRecord.size()>1 && ld->relayed) {
434 for (size_t i=1; i<ld->routeRecord.size(); i++)
435 s << ld->routeRecord[ld->routeRecord.size()-i-1].toString().substr(0,4) << ".. ";
436 } else {
437 s << "Direct";
438 }
439 s << "</td>";
440 s << "</tr>";
441 }
442 s << "</table>";
443 }
444 return s.str();
445}
446
447/// shows the current link state
448void BaseOverlay::showLinks() {
449 int i=0;
450 logging_info("--- link state -------------------------------");
451 BOOST_FOREACH( LinkDescriptor* ld, links ) {
452 logging_info("link " << i << ": " << ld);
453 i++;
454 }
455 logging_info("----------------------------------------------");
456}
457
458/// compares two arbitrary links to the same node
459int BaseOverlay::compare( const LinkID& lhs, const LinkID& rhs ) {
460 LinkDescriptor* lhsld = getDescriptor(lhs);
461 LinkDescriptor* rhsld = getDescriptor(rhs);
462 if (lhsld==NULL || rhsld==NULL
463 || !lhsld->up || !rhsld->up
464 || lhsld->remoteNode != rhsld->remoteNode) return -1;
465
466 if ((lhsld->remoteLink^lhsld->overlayId)<(rhsld->remoteLink^lhsld->overlayId) )
467 return -1;
468
469 return 1;
470}
471
472
473// internal message delivery ---------------------------------------------------
474
475/// routes a message to its destination node
476void BaseOverlay::route( OverlayMsg* message ) {
477
478 // exceeded time-to-live? yes-> drop message
479 if (message->getNumHops() > message->getTimeToLive()) {
480 logging_warn("Message exceeded TTL. Dropping message and relay routes"
481 "for recovery.");
482 removeRelayNode(message->getDestinationNode());
483 return;
484 }
485
486 // no-> forward message
487 else {
488 // destinastion myself? yes-> handle message
489 if (message->getDestinationNode() == nodeId) {
490 logging_warn("Usually I should not route messages to myself!");
491 Message msg;
492 msg.encapsulate(message);
493 handleMessage( &msg, NULL );
494 } else {
495 // no->send message to next hop
496 send( message, message->getDestinationNode() );
497 }
498 }
499}
500
501/// sends a message to another node, delivers it to the base overlay class
502seqnum_t BaseOverlay::send( OverlayMsg* message, const NodeID& destination ) {
503 LinkDescriptor* next_link = NULL;
504
505 // drop messages to unspecified destinations
506 if (destination.isUnspecified()) return -1;
507
508 // send messages to myself -> handle message and drop warning!
509 if (destination == nodeId) {
510 logging_warn("Sent message to myself. Handling message.")
511 Message msg;
512 msg.encapsulate(message);
513 handleMessage( &msg, NULL );
514 return -1;
515 }
516
517 // use relay path?
518 if (message->isRelayed()) {
519 next_link = getRelayLinkTo( destination );
520 if (next_link != NULL) {
521 next_link->setRelaying();
522 return bc->sendMessage(next_link->communicationId, message);
523 } else {
524 logging_warn("Could not send message. No relay hop found to "
525 << destination << " -- trying to route over overlay paths ...")
526// logging_error("ERROR: " << debugInformation() );
527 // return -1;
528 }
529 }
530
531 // last resort -> route over overlay path
532 LinkID next_id = overlayInterface->getNextLinkId( destination );
533 if (next_id.isUnspecified()) {
534 logging_warn("Could not send message. No next hop found to " <<
535 destination );
536 logging_error("ERROR: " << debugInformation() );
537 return -1;
538 }
539
540 // get link descriptor, up and running? yes-> send message
541 next_link = getDescriptor(next_id);
542 if (next_link != NULL && next_link->up) {
543 // send message over relayed link
544 return send(message, next_link);
545 }
546
547 // no-> error, dropping message
548 else {
549 logging_warn("Could not send message. Link not known or up");
550 logging_error("ERROR: " << debugInformation() );
551 return -1;
552 }
553
554 // not reached-> fail
555 return -1;
556}
557
558/// send a message using a link descriptor, delivers it to the base overlay class
559seqnum_t BaseOverlay::send( OverlayMsg* message, LinkDescriptor* ldr, bool ignore_down ) {
560 // check if null
561 if (ldr == NULL) {
562 logging_error("Can not send message to " << message->getDestinationAddress());
563 return -1;
564 }
565
566 // check if up
567 if (!ldr->up && !ignore_down) {
568 logging_error("Can not send message. Link not up:" << ldr );
569 logging_error("DEBUG_INFO: " << debugInformation() );
570 return -1;
571 }
572 LinkDescriptor* ld = NULL;
573
574 // handle relayed link
575 if (ldr->relayed) {
576 logging_debug("Resolving direct link for relayed link to "
577 << ldr->remoteNode);
578 ld = getRelayLinkTo( ldr->remoteNode );
579 if (ld==NULL) {
580 logging_error("No relay path found to link " << ldr );
581 logging_error("DEBUG_INFO: " << debugInformation() );
582 return -1;
583 }
584 ld->setRelaying();
585 message->setRelayed(true);
586 } else
587 ld = ldr;
588
589 // handle direct link
590 if (ld->communicationUp) {
591 logging_debug("send(): Sending message over direct link.");
592 return bc->sendMessage( ld->communicationId, message );
593 } else {
594 logging_error("send(): Could not send message. "
595 "Not a relayed link and direct link is not up.");
596 return -1;
597 }
598 return -1;
599}
600
601seqnum_t BaseOverlay::send_node( OverlayMsg* message, const NodeID& remote,
602 const ServiceID& service) {
603 message->setSourceNode(nodeId);
604 message->setDestinationNode(remote);
605 message->setService(service);
606 send( message, remote );
607}
608
609seqnum_t BaseOverlay::send_link( OverlayMsg* message, const LinkID& link,bool ignore_down ) {
610 LinkDescriptor* ld = getDescriptor(link);
611 if (ld==NULL) {
612 logging_error("Cannot find descriptor to link id=" << link.toString());
613 return -1;
614 }
615 message->setSourceNode(nodeId);
616 message->setDestinationNode(ld->remoteNode);
617
618 message->setSourceLink(ld->overlayId);
619 message->setDestinationLink(ld->remoteLink);
620
621 message->setService(ld->service);
622 message->setRelayed(ld->relayed);
623 return send( message, ld, ignore_down );
624}
625
626// relay route management ------------------------------------------------------
627
628/// stabilize relay information
629void BaseOverlay::stabilizeRelays() {
630 vector<relay_route>::iterator i = relay_routes.begin();
631 while (i!=relay_routes.end() ) {
632 relay_route& route = *i;
633 LinkDescriptor* ld = getDescriptor(route.link);
634
635 // relay link still used and alive?
636 if (ld==NULL
637 || !ld->isDirectVital()
638 || difftime(route.used, time(NULL)) > 8) {
639 logging_info("Forgetting relay information to node "
640 << route.node.toString() );
641 i = relay_routes.erase(i);
642 } else
643 i++;
644 }
645}
646
647void BaseOverlay::removeRelayLink( const LinkID& link ) {
648 vector<relay_route>::iterator i = relay_routes.begin();
649 while (i!=relay_routes.end() ) {
650 relay_route& route = *i;
651 if (route.link == link ) i = relay_routes.erase(i); else i++;
652 }
653}
654
655void BaseOverlay::removeRelayNode( const NodeID& remote ) {
656 vector<relay_route>::iterator i = relay_routes.begin();
657 while (i!=relay_routes.end() ) {
658 relay_route& route = *i;
659 if (route.node == remote ) i = relay_routes.erase(i); else i++;
660 }
661}
662
663/// refreshes relay information
664void BaseOverlay::refreshRelayInformation( const OverlayMsg* message, LinkDescriptor* ld ) {
665
666 // handle relayed messages from real links only
667 if (ld == NULL
668 || ld->relayed
669 || message->getSourceNode()==nodeId ) return;
670
671 // update usage information
672 if (message->isRelayed()) {
673 // try to find source node
674 BOOST_FOREACH( relay_route& route, relay_routes ) {
675 // relay route found? yes->
676 if ( route.node == message->getDestinationNode() ) {
677 ld->setRelaying();
678 route.used = time(NULL);
679 }
680 }
681
682 }
683
684 // register relay path
685 if (message->isRegisterRelay()) {
686 // set relaying
687 ld->setRelaying();
688
689 // try to find source node
690 BOOST_FOREACH( relay_route& route, relay_routes ) {
691
692 // relay route found? yes->
693 if ( route.node == message->getSourceNode() ) {
694
695 // refresh timer
696 route.used = time(NULL);
697 LinkDescriptor* rld = getDescriptor(route.link);
698
699 // route has a shorter hop count or old link is dead? yes-> replace
700 if (route.hops > message->getNumHops()
701 || rld == NULL
702 || !rld->isDirectVital()) {
703 logging_info("Updating relay information to node "
704 << route.node.toString()
705 << " reducing to " << message->getNumHops() << " hops.");
706 route.hops = message->getNumHops();
707 route.link = ld->overlayId;
708 }
709 return;
710 }
711 }
712
713 // not found-> add new entry
714 relay_route route;
715 route.hops = message->getNumHops();
716 route.link = ld->overlayId;
717 route.node = message->getSourceNode();
718 route.used = time(NULL);
719 logging_info("Remembering relay information to node "
720 << route.node.toString());
721 relay_routes.push_back(route);
722 }
723}
724
725/// returns a known "vital" relay link which is up and running
726LinkDescriptor* BaseOverlay::getRelayLinkTo( const NodeID& remote ) {
727 // try to find source node
728 BOOST_FOREACH( relay_route& route, relay_routes ) {
729 if (route.node == remote ) {
730 LinkDescriptor* ld = getDescriptor( route.link );
731 if (ld==NULL || !ld->isDirectVital()) return NULL; else {
732 route.used = time(NULL);
733 return ld;
734 }
735 }
736 }
737 return NULL;
738}
739
740/* *****************************************************************************
741 * PUBLIC MEMBERS
742 * ****************************************************************************/
743
744use_logging_cpp(BaseOverlay);
745
746// ----------------------------------------------------------------------------
747
748BaseOverlay::BaseOverlay() :
749 bc(NULL), overlayInterface(NULL), nodeId(NodeID::UNSPECIFIED),
750 spovnetId(SpoVNetID::UNSPECIFIED), state(BaseOverlayStateInvalid),
751 sideport(&SideportListener::DEFAULT), started(false), counter(0) {
752 dht = new DHT();
753 localDHT = new DHT();
754}
755
756BaseOverlay::~BaseOverlay() {
757 delete dht;
758}
759
760// ----------------------------------------------------------------------------
761
762void BaseOverlay::start( BaseCommunication& _basecomm, const NodeID& _nodeid ) {
763 logging_info("Starting...");
764
765 // set parameters
766 bc = &_basecomm;
767 nodeId = _nodeid;
768
769 // register at base communication
770 bc->registerMessageReceiver( this );
771 bc->registerEventListener( this );
772
773 // timer for auto link management
774 Timer::setInterval( 1000 );
775 Timer::start();
776
777 started = true;
778 state = BaseOverlayStateInvalid;
779}
780
781void BaseOverlay::stop() {
782 logging_info("Stopping...");
783
784 // stop timer
785 Timer::stop();
786
787 // delete oberlay interface
788 if(overlayInterface != NULL) {
789 delete overlayInterface;
790 overlayInterface = NULL;
791 }
792
793 // unregister at base communication
794 bc->unregisterMessageReceiver( this );
795 bc->unregisterEventListener( this );
796
797 started = false;
798 state = BaseOverlayStateInvalid;
799}
800
801bool BaseOverlay::isStarted(){
802 return started;
803}
804
805// ----------------------------------------------------------------------------
806
807void BaseOverlay::joinSpoVNet(const SpoVNetID& id,
808 const EndpointDescriptor& bootstrapEp) {
809
810 if(id != spovnetId){
811 logging_error("attempt to join against invalid spovnet, call initiate first");
812 return;
813 }
814
815
816 //ovl.visShowNodeBubble ( ovlId, nodeId, "joining..." );
817 logging_info( "Starting to join spovnet " << id.toString() <<
818 " with nodeid " << nodeId.toString());
819
820 if(bootstrapEp.isUnspecified() && state == BaseOverlayStateInvalid){
821
822 // bootstrap against ourselfs
823 logging_info("joining spovnet locally");
824
825 overlayInterface->joinOverlay();
826 state = BaseOverlayStateCompleted;
827 BOOST_FOREACH( NodeListener* i, nodeListeners )
828 i->onJoinCompleted( spovnetId );
829
830 //ovl.visChangeNodeIcon ( ovlId, nodeId, OvlVis::ICON_ID_CAMERA );
831 //ovl.visChangeNodeColor( ovlId, nodeId, OvlVis::NODE_COLORS_GREEN );
832
833 logging_debug("starting overlay bootstrap module");
834 overlayBootstrap.start(this, spovnetId, nodeId);
835 overlayBootstrap.publish(bc->getEndpointDescriptor());
836
837 } else {
838
839 // bootstrap against another node
840 logging_info("joining spovnet remotely against " << bootstrapEp.toString());
841
842 const LinkID& lnk = bc->establishLink( bootstrapEp );
843 bootstrapLinks.push_back(lnk);
844 logging_info("join process initiated for " << id.toString() << "...");
845 }
846}
847
848void BaseOverlay::leaveSpoVNet() {
849
850 logging_info( "Leaving spovnet " << spovnetId );
851 bool ret = ( state != this->BaseOverlayStateInvalid );
852
853 logging_debug("stopping overlay bootstrap module");
854 overlayBootstrap.stop();
855 overlayBootstrap.revoke();
856
857 logging_debug( "Dropping all auto-links" );
858
859 // gather all service links
860 vector<LinkID> servicelinks;
861 BOOST_FOREACH( LinkDescriptor* ld, links ) {
862 if( ld->service != OverlayInterface::OVERLAY_SERVICE_ID )
863 servicelinks.push_back( ld->overlayId );
864 }
865
866 // drop all service links
867 BOOST_FOREACH( LinkID lnk, servicelinks )
868 dropLink( lnk );
869
870 // let the node leave the spovnet overlay interface
871 logging_debug( "Leaving overlay" );
872 if( overlayInterface != NULL )
873 overlayInterface->leaveOverlay();
874
875 // drop still open bootstrap links
876 BOOST_FOREACH( LinkID lnk, bootstrapLinks )
877 bc->dropLink( lnk );
878
879 // change to inalid state
880 state = BaseOverlayStateInvalid;
881 //ovl.visShutdown( ovlId, nodeId, string("") );
882
883 visual.visShutdown(visualIdOverlay, nodeId, "");
884 visual.visShutdown(visualIdBase, nodeId, "");
885
886 // inform all registered services of the event
887 BOOST_FOREACH( NodeListener* i, nodeListeners ) {
888 if( ret ) i->onLeaveCompleted( spovnetId );
889 else i->onLeaveFailed( spovnetId );
890 }
891}
892
893void BaseOverlay::createSpoVNet(const SpoVNetID& id,
894 const OverlayParameterSet& param,
895 const SecurityParameterSet& sec,
896 const QoSParameterSet& qos) {
897
898 // set the state that we are an initiator, this way incoming messages are
899 // handled correctly
900 logging_info( "creating spovnet " + id.toString() <<
901 " with nodeid " << nodeId.toString() );
902
903 spovnetId = id;
904
905 overlayInterface = OverlayFactory::create( *this, param, nodeId, this );
906 if( overlayInterface == NULL ) {
907 logging_fatal( "overlay structure not supported" );
908 state = BaseOverlayStateInvalid;
909
910 BOOST_FOREACH( NodeListener* i, nodeListeners )
911 i->onJoinFailed( spovnetId );
912
913 return;
914 }
915
916 visual.visCreate(visualIdBase, nodeId, "", "");
917 visual.visCreate(visualIdOverlay, nodeId, "", "");
918}
919
920// ----------------------------------------------------------------------------
921
922const LinkID BaseOverlay::establishLink( const EndpointDescriptor& remoteEp,
923 const NodeID& remoteId, const ServiceID& service ) {
924
925 // establish link via overlay
926 if (!remoteId.isUnspecified())
927 return establishLink( remoteId, service );
928 else
929
930 // establish link directly if only ep is known
931 if (remoteId.isUnspecified())
932 return establishDirectLink(remoteEp, service );
933
934}
935
936/// call base communication's establish link and add link mapping
937const LinkID BaseOverlay::establishDirectLink( const EndpointDescriptor& ep,
938 const ServiceID& service ) {
939
940 /// find a service listener
941 if( !communicationListeners.contains( service ) ) {
942 logging_error( "No listener registered for service id=" << service.toString() );
943 return LinkID::UNSPECIFIED;
944 }
945 CommunicationListener* listener = communicationListeners.get( service );
946 assert( listener != NULL );
947
948 // create descriptor
949 LinkDescriptor* ld = addDescriptor();
950 ld->relayed = false;
951 ld->listener = listener;
952 ld->service = service;
953 ld->communicationId = bc->establishLink( ep );
954
955 /// establish link and add mapping
956 logging_info("Establishing direct link " << ld->communicationId.toString()
957 << " using " << ep.toString());
958
959 return ld->communicationId;
960}
961
962/// establishes a link between two arbitrary nodes
963const LinkID BaseOverlay::establishLink( const NodeID& remote,
964 const ServiceID& service ) {
965
966 // do not establish a link to myself!
967 if (remote == nodeId) return LinkID::UNSPECIFIED;
968
969 // create a link descriptor
970 LinkDescriptor* ld = addDescriptor();
971 ld->relayed = true;
972 ld->remoteNode = remote;
973 ld->service = service;
974 ld->listener = getListener(ld->service);
975
976 // create link request message
977 OverlayMsg msg(OverlayMsg::typeLinkRequest, service, nodeId, remote );
978 msg.setSourceLink(ld->overlayId);
979
980 // send over relayed link
981 msg.setRelayed(true);
982 //msg.setRelayed(false);
983 //msg.setRegisterRelay(true);
984
985 // debug message
986 logging_info(
987 "Sending link request with"
988 << " link=" << ld->overlayId.toString()
989 << " node=" << ld->remoteNode.toString()
990 << " serv=" << ld->service.toString()
991 );
992
993 // sending message to node
994 send_node( &msg, ld->remoteNode, ld->service );
995
996 return ld->overlayId;
997}
998
999/// drops an established link
1000void BaseOverlay::dropLink(const LinkID& link) {
1001 logging_info( "Dropping link (initiated locally):" << link.toString() );
1002
1003 // find the link item to drop
1004 LinkDescriptor* ld = getDescriptor(link);
1005 if( ld == NULL ) {
1006 logging_warn( "Can't drop link, link is unknown!");
1007 return;
1008 }
1009
1010 // delete all queued messages
1011 if( ld->messageQueue.size() > 0 ) {
1012 logging_warn( "Dropping link " << ld->overlayId.toString() << " that has "
1013 << ld->messageQueue.size() << " waiting messages" );
1014 ld->flushQueue();
1015 }
1016
1017 // inform sideport and listener
1018 if(ld->listener != NULL)
1019 ld->listener->onLinkDown( ld->overlayId, ld->remoteNode );
1020 sideport->onLinkDown(ld->overlayId, this->nodeId, ld->remoteNode, this->spovnetId );
1021
1022 // do not drop relay links
1023 if (!ld->relaying) {
1024 // drop the link in base communication
1025 if (ld->communicationUp) bc->dropLink( ld->communicationId );
1026
1027 // erase descriptor
1028 eraseDescriptor( ld->overlayId );
1029 } else {
1030 ld->dropAfterRelaying = true;
1031 }
1032}
1033
1034// ----------------------------------------------------------------------------
1035
1036/// internal send message, always use this functions to send messages over links
1037seqnum_t BaseOverlay::sendMessage( const Message* message, const LinkID& link ) {
1038 logging_debug( "Sending data message on link " << link.toString() );
1039
1040 // get the mapping for this link
1041 LinkDescriptor* ld = getDescriptor(link);
1042 if( ld == NULL ) {
1043 logging_error("Could not send message. "
1044 << "Link not found id=" << link.toString());
1045 return -1;
1046 }
1047
1048 // check if the link is up yet, if its an auto link queue message
1049 if( !ld->up ) {
1050 ld->setAutoUsed();
1051 if( ld->autolink ) {
1052 logging_info("Auto-link " << link.toString() << " not up, queue message");
1053 Data data = data_serialize( message );
1054 const_cast<Message*>(message)->dropPayload();
1055 ld->messageQueue.push_back( new Message(data) );
1056 } else {
1057 logging_error("Link " << link.toString() << " not up, drop message");
1058 }
1059 return -1;
1060 }
1061
1062 // compile overlay message (has service and node id)
1063 OverlayMsg overmsg( OverlayMsg::typeData );
1064 overmsg.encapsulate( const_cast<Message*>(message) );
1065
1066 // send message over relay/direct/overlay
1067 return send_link( &overmsg, ld->overlayId );
1068}
1069
1070seqnum_t BaseOverlay::sendMessage(const Message* message,
1071 const NodeID& node, const ServiceID& service) {
1072
1073 // find link for node and service
1074 LinkDescriptor* ld = getAutoDescriptor( node, service );
1075
1076 // if we found no link, create an auto link
1077 if( ld == NULL ) {
1078
1079 // debug output
1080 logging_info( "No link to send message to node "
1081 << node.toString() << " found for service "
1082 << service.toString() << ". Creating auto link ..."
1083 );
1084
1085 // call base overlay to create a link
1086 LinkID link = establishLink( node, service );
1087 ld = getDescriptor( link );
1088 if( ld == NULL ) {
1089 logging_error( "Failed to establish auto-link.");
1090 return -1;
1091 }
1092 ld->autolink = true;
1093
1094 logging_debug( "Auto-link establishment in progress to node "
1095 << node.toString() << " with link id=" << link.toString() );
1096 }
1097 assert(ld != NULL);
1098
1099 // mark the link as used, as we now send a message through it
1100 ld->setAutoUsed();
1101
1102 // send / queue message
1103 return sendMessage( message, ld->overlayId );
1104}
1105
1106// ----------------------------------------------------------------------------
1107
1108const EndpointDescriptor& BaseOverlay::getEndpointDescriptor(
1109 const LinkID& link) const {
1110
1111 // return own end-point descriptor
1112 if( link.isUnspecified() )
1113 return bc->getEndpointDescriptor();
1114
1115 // find link descriptor. not found -> return unspecified
1116 const LinkDescriptor* ld = getDescriptor(link);
1117 if (ld==NULL) return EndpointDescriptor::UNSPECIFIED();
1118
1119 // return endpoint-descriptor from base communication
1120 return bc->getEndpointDescriptor( ld->communicationId );
1121}
1122
1123const EndpointDescriptor& BaseOverlay::getEndpointDescriptor(
1124 const NodeID& node) const {
1125
1126 // return own end-point descriptor
1127 if( node == nodeId || node == NodeID::UNSPECIFIED )
1128 return bc->getEndpointDescriptor();
1129
1130 // no joined and request remote descriptor? -> fail!
1131 if( overlayInterface == NULL ) {
1132 logging_error( "Overlay interface not set, cannot resolve end-point." );
1133 return EndpointDescriptor::UNSPECIFIED();
1134 }
1135
1136// // resolve end-point descriptor from the base-overlay routing table
1137// const EndpointDescriptor& ep = overlayInterface->resolveNode( node );
1138// if(ep.toString() != "") return ep;
1139
1140 // see if we can find the node in our own table
1141 BOOST_FOREACH(const LinkDescriptor* ld, links){
1142 if(ld->remoteNode != node) continue;
1143 const EndpointDescriptor& ep =
1144 bc->getEndpointDescriptor(ld->communicationId);
1145 if(ep.toString() == "") continue;
1146 if(ep != EndpointDescriptor::UNSPECIFIED()) return ep;
1147 }
1148
1149 logging_warn( "No EndpointDescriptor found for node " << node );
1150 logging_warn( const_cast<BaseOverlay*>(this)->debugInformation() );
1151
1152 return EndpointDescriptor::UNSPECIFIED();
1153}
1154
1155// ----------------------------------------------------------------------------
1156
1157bool BaseOverlay::registerSidePort(SideportListener* _sideport) {
1158 sideport = _sideport;
1159 _sideport->configure( this );
1160}
1161
1162bool BaseOverlay::unregisterSidePort(SideportListener* _sideport) {
1163 sideport = &SideportListener::DEFAULT;
1164}
1165
1166// ----------------------------------------------------------------------------
1167
1168bool BaseOverlay::bind(CommunicationListener* listener, const ServiceID& sid) {
1169 logging_debug( "binding communication listener " << listener
1170 << " on serviceid " << sid.toString() );
1171
1172 if( communicationListeners.contains( sid ) ) {
1173 logging_error( "some listener already registered for service id "
1174 << sid.toString() );
1175 return false;
1176 }
1177
1178 communicationListeners.registerItem( listener, sid );
1179 return true;
1180}
1181
1182
1183bool BaseOverlay::unbind(CommunicationListener* listener, const ServiceID& sid) {
1184 logging_debug( "unbinding listener " << listener << " from serviceid " << sid.toString() );
1185
1186 if( !communicationListeners.contains( sid ) ) {
1187 logging_warn( "cannot unbind listener. no listener registered on service id " << sid.toString() );
1188 return false;
1189 }
1190
1191 if( communicationListeners.get(sid) != listener ) {
1192 logging_warn( "listener bound to service id " << sid.toString()
1193 << " is different than listener trying to unbind" );
1194 return false;
1195 }
1196
1197 communicationListeners.unregisterItem( sid );
1198 return true;
1199}
1200
1201// ----------------------------------------------------------------------------
1202
1203bool BaseOverlay::bind(NodeListener* listener) {
1204 logging_debug( "Binding node listener " << listener );
1205
1206 // already bound? yes-> warning
1207 NodeListenerVector::iterator i =
1208 find( nodeListeners.begin(), nodeListeners.end(), listener );
1209 if( i != nodeListeners.end() ) {
1210 logging_warn("Node listener " << listener << " is already bound!" );
1211 return false;
1212 }
1213
1214 // no-> add
1215 nodeListeners.push_back( listener );
1216 return true;
1217}
1218
1219bool BaseOverlay::unbind(NodeListener* listener) {
1220 logging_debug( "Unbinding node listener " << listener );
1221
1222 // already unbound? yes-> warning
1223 NodeListenerVector::iterator i = find( nodeListeners.begin(), nodeListeners.end(), listener );
1224 if( i == nodeListeners.end() ) {
1225 logging_warn( "Node listener " << listener << " is not bound!" );
1226 return false;
1227 }
1228
1229 // no-> remove
1230 nodeListeners.erase( i );
1231 return true;
1232}
1233
1234// ----------------------------------------------------------------------------
1235
1236void BaseOverlay::onLinkUp(const LinkID& id,
1237 const address_v* local, const address_v* remote) {
1238 logging_debug( "Link up with base communication link id=" << id );
1239
1240 // get descriptor for link
1241 LinkDescriptor* ld = getDescriptor(id, true);
1242
1243 // handle bootstrap link we initiated
1244 if( std::find(bootstrapLinks.begin(), bootstrapLinks.end(), id) != bootstrapLinks.end() ){
1245 logging_info(
1246 "Join has been initiated by me and the link is now up. " <<
1247 "Sending out join request for SpoVNet " << spovnetId.toString()
1248 );
1249
1250 // send join request message
1251 OverlayMsg overlayMsg( OverlayMsg::typeJoinRequest,
1252 OverlayInterface::OVERLAY_SERVICE_ID, nodeId );
1253 JoinRequest joinRequest( spovnetId, nodeId );
1254 overlayMsg.encapsulate( &joinRequest );
1255 bc->sendMessage( id, &overlayMsg );
1256 return;
1257 }
1258
1259 // no link found? -> link establishment from remote, add one!
1260 if (ld == NULL) {
1261 ld = addDescriptor( id );
1262 logging_info( "onLinkUp (remote request) descriptor: " << ld );
1263
1264 // update descriptor
1265 ld->fromRemote = true;
1266 ld->communicationId = id;
1267 ld->communicationUp = true;
1268 ld->setAutoUsed();
1269 ld->setAlive();
1270
1271 // in this case, do not inform listener, since service it unknown
1272 // -> wait for update message!
1273
1274 // link mapping found? -> send update message with node-id and service id
1275 } else {
1276 logging_info( "onLinkUp descriptor (initiated locally):" << ld );
1277
1278 // update descriptor
1279 ld->setAutoUsed();
1280 ld->setAlive();
1281 ld->communicationUp = true;
1282 ld->fromRemote = false;
1283
1284 // if link is a relayed link->convert to direct link
1285 if (ld->relayed) {
1286 logging_info( "Converting to direct link: " << ld );
1287 ld->up = true;
1288 ld->relayed = false;
1289 OverlayMsg overMsg( OverlayMsg::typeLinkDirect );
1290 overMsg.setSourceLink( ld->overlayId );
1291 overMsg.setDestinationLink( ld->remoteLink );
1292 send_link( &overMsg, ld->overlayId );
1293 } else {
1294 // note: necessary to validate the link on the remote side!
1295 logging_info( "Sending out update" <<
1296 " for service " << ld->service.toString() <<
1297 " with local node id " << nodeId.toString() <<
1298 " on link " << ld->overlayId.toString() );
1299
1300 // compile and send update message
1301 OverlayMsg overlayMsg( OverlayMsg::typeLinkUpdate );
1302 overlayMsg.setSourceLink(ld->overlayId);
1303 overlayMsg.setAutoLink( ld->autolink );
1304 send_link( &overlayMsg, ld->overlayId, true );
1305 }
1306 }
1307}
1308
1309void BaseOverlay::onLinkDown(const LinkID& id,
1310 const address_v* local, const address_v* remote) {
1311
1312 // erase bootstrap links
1313 vector<LinkID>::iterator it = std::find( bootstrapLinks.begin(), bootstrapLinks.end(), id );
1314 if( it != bootstrapLinks.end() ) bootstrapLinks.erase( it );
1315
1316 // get descriptor for link
1317 LinkDescriptor* ld = getDescriptor(id, true);
1318 if ( ld == NULL ) return; // not found? ->ignore!
1319 logging_info( "onLinkDown descriptor: " << ld );
1320
1321 // removing relay link information
1322 removeRelayLink(ld->overlayId);
1323
1324 // inform listeners about link down
1325 ld->communicationUp = false;
1326 if (!ld->service.isUnspecified()) {
1327 CommunicationListener* lst = getListener(ld->service);
1328 if(lst != NULL) lst->onLinkDown( ld->overlayId, ld->remoteNode );
1329 sideport->onLinkDown( id, this->nodeId, ld->remoteNode, this->spovnetId );
1330 }
1331
1332 // delete all queued messages (auto links)
1333 if( ld->messageQueue.size() > 0 ) {
1334 logging_warn( "Dropping link " << id.toString() << " that has "
1335 << ld->messageQueue.size() << " waiting messages" );
1336 ld->flushQueue();
1337 }
1338
1339 // erase mapping
1340 eraseDescriptor(ld->overlayId);
1341}
1342
1343void BaseOverlay::onLinkChanged(const LinkID& id,
1344 const address_v* oldlocal, const address_v* newlocal,
1345 const address_v* oldremote, const address_v* newremote) {
1346
1347 // get descriptor for link
1348 LinkDescriptor* ld = getDescriptor(id, true);
1349 if ( ld == NULL ) return; // not found? ->ignore!
1350 logging_debug( "onLinkChanged descriptor: " << ld );
1351
1352 // inform listeners
1353 ld->listener->onLinkChanged( ld->overlayId, ld->remoteNode );
1354 sideport->onLinkChanged( id, this->nodeId, ld->remoteNode, this->spovnetId );
1355
1356 // autolinks: refresh timestamp
1357 ld->setAutoUsed();
1358}
1359
1360void BaseOverlay::onLinkFail(const LinkID& id,
1361 const address_v* local, const address_v* remote) {
1362 logging_debug( "Link fail with base communication link id=" << id );
1363
1364 // erase bootstrap links
1365 vector<LinkID>::iterator it = std::find( bootstrapLinks.begin(), bootstrapLinks.end(), id );
1366 if( it != bootstrapLinks.end() ) bootstrapLinks.erase( it );
1367
1368 // get descriptor for link
1369 LinkDescriptor* ld = getDescriptor(id, true);
1370 if ( ld == NULL ) return; // not found? ->ignore!
1371 logging_debug( "Link failed id=" << ld->overlayId.toString() );
1372
1373 // inform listeners
1374 ld->listener->onLinkFail( ld->overlayId, ld->remoteNode );
1375 sideport->onLinkFail( id, this->nodeId, ld->remoteNode, this->spovnetId );
1376}
1377
1378void BaseOverlay::onLinkQoSChanged(const LinkID& id, const address_v* local,
1379 const address_v* remote, const QoSParameterSet& qos) {
1380 logging_debug( "Link quality changed with base communication link id=" << id );
1381
1382 // get descriptor for link
1383 LinkDescriptor* ld = getDescriptor(id, true);
1384 if ( ld == NULL ) return; // not found? ->ignore!
1385 logging_debug( "Link quality changed id=" << ld->overlayId.toString() );
1386}
1387
1388bool BaseOverlay::onLinkRequest( const LinkID& id, const address_v* local,
1389 const address_v* remote ) {
1390 logging_debug("Accepting link request from " << remote->to_string() );
1391 return true;
1392}
1393
1394/// handles a message from base communication
1395bool BaseOverlay::receiveMessage(const Message* message,
1396 const LinkID& link, const NodeID& ) {
1397 // get descriptor for link
1398 LinkDescriptor* ld = getDescriptor( link, true );
1399 return handleMessage( message, ld, link );
1400}
1401
1402// ----------------------------------------------------------------------------
1403
1404/// Handle spovnet instance join requests
1405bool BaseOverlay::handleJoinRequest( OverlayMsg* overlayMsg, const LinkID& bcLink ) {
1406
1407 // decapsulate message
1408 JoinRequest* joinReq = overlayMsg->decapsulate<JoinRequest>();
1409 logging_info( "Received join request for spovnet " <<
1410 joinReq->getSpoVNetID().toString() );
1411
1412 // check spovnet id
1413 if( joinReq->getSpoVNetID() != spovnetId ) {
1414 logging_error(
1415 "Received join request for spovnet we don't handle " <<
1416 joinReq->getSpoVNetID().toString() );
1417 return false;
1418 }
1419
1420 // TODO: here you can implement mechanisms to deny joining of a node
1421 bool allow = true;
1422 logging_info( "Sending join reply for spovnet " <<
1423 spovnetId.toString() << " to node " <<
1424 overlayMsg->getSourceNode().toString() <<
1425 ". Result: " << (allow ? "allowed" : "denied") );
1426 joiningNodes.push_back( overlayMsg->getSourceNode() );
1427
1428 // return overlay parameters
1429 assert( overlayInterface != NULL );
1430 logging_debug( "Using bootstrap end-point "
1431 << getEndpointDescriptor().toString() )
1432 OverlayParameterSet parameters = overlayInterface->getParameters();
1433 OverlayMsg retmsg( OverlayMsg::typeJoinReply,
1434 OverlayInterface::OVERLAY_SERVICE_ID, nodeId );
1435 JoinReply replyMsg( spovnetId, parameters,
1436 allow, getEndpointDescriptor() );
1437 retmsg.encapsulate(&replyMsg);
1438 bc->sendMessage( bcLink, &retmsg );
1439
1440 return true;
1441}
1442
1443/// Handle replies to spovnet instance join requests
1444bool BaseOverlay::handleJoinReply( OverlayMsg* overlayMsg, const LinkID& bcLink ) {
1445 // decapsulate message
1446 logging_debug("received join reply message");
1447 JoinReply* replyMsg = overlayMsg->decapsulate<JoinReply>();
1448
1449 // correct spovnet?
1450 if( replyMsg->getSpoVNetID() != spovnetId ) { // no-> fail
1451 logging_error( "Received SpoVNet join reply for " <<
1452 replyMsg->getSpoVNetID().toString() <<
1453 " != " << spovnetId.toString() );
1454 delete replyMsg;
1455 return false;
1456 }
1457
1458 // access granted? no -> fail
1459 if( !replyMsg->getJoinAllowed() ) {
1460 logging_error( "Our join request has been denied" );
1461
1462 // drop initiator link
1463 if( !bcLink.isUnspecified() ){
1464 bc->dropLink( bcLink );
1465
1466 vector<LinkID>::iterator it = std::find(
1467 bootstrapLinks.begin(), bootstrapLinks.end(), bcLink);
1468 if( it != bootstrapLinks.end() )
1469 bootstrapLinks.erase(it);
1470 }
1471
1472 // inform all registered services of the event
1473 BOOST_FOREACH( NodeListener* i, nodeListeners )
1474 i->onJoinFailed( spovnetId );
1475
1476 delete replyMsg;
1477 return true;
1478 }
1479
1480 // access has been granted -> continue!
1481 logging_info("Join request has been accepted for spovnet " <<
1482 spovnetId.toString() );
1483
1484 logging_debug( "Using bootstrap end-point "
1485 << replyMsg->getBootstrapEndpoint().toString() );
1486
1487 // create overlay structure from spovnet parameter set
1488 // if we have not boostrapped yet against some other node
1489 if( overlayInterface == NULL ){
1490
1491 logging_debug("first-time bootstrapping");
1492
1493 overlayInterface = OverlayFactory::create(
1494 *this, replyMsg->getParam(), nodeId, this );
1495
1496 // overlay structure supported? no-> fail!
1497 if( overlayInterface == NULL ) {
1498 logging_error( "overlay structure not supported" );
1499
1500 if( !bcLink.isUnspecified() ){
1501 bc->dropLink( bcLink );
1502
1503 vector<LinkID>::iterator it = std::find(
1504 bootstrapLinks.begin(), bootstrapLinks.end(), bcLink);
1505 if( it != bootstrapLinks.end() )
1506 bootstrapLinks.erase(it);
1507 }
1508
1509 // inform all registered services of the event
1510 BOOST_FOREACH( NodeListener* i, nodeListeners )
1511 i->onJoinFailed( spovnetId );
1512
1513 delete replyMsg;
1514 return true;
1515 }
1516
1517 // everything ok-> join the overlay!
1518 state = BaseOverlayStateCompleted;
1519 overlayInterface->createOverlay();
1520
1521 overlayInterface->joinOverlay( replyMsg->getBootstrapEndpoint() );
1522 overlayBootstrap.recordJoin( replyMsg->getBootstrapEndpoint() );
1523
1524 // update ovlvis
1525 //ovl.visChangeNodeColor( ovlId, nodeId, OvlVis::NODE_COLORS_GREEN);
1526
1527 // inform all registered services of the event
1528 BOOST_FOREACH( NodeListener* i, nodeListeners )
1529 i->onJoinCompleted( spovnetId );
1530
1531 delete replyMsg;
1532
1533 } else {
1534
1535 // this is not the first bootstrap, just join the additional node
1536 logging_debug("not first-time bootstrapping");
1537 overlayInterface->joinOverlay( replyMsg->getBootstrapEndpoint() );
1538 overlayBootstrap.recordJoin( replyMsg->getBootstrapEndpoint() );
1539
1540 delete replyMsg;
1541
1542 } // if( overlayInterface == NULL )
1543
1544 return true;
1545}
1546
1547
1548bool BaseOverlay::handleData( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1549 // get service
1550 const ServiceID& service = overlayMsg->getService();
1551 logging_debug( "Received data for service " << service.toString()
1552 << " on link " << overlayMsg->getDestinationLink().toString() );
1553
1554 // delegate data message
1555 CommunicationListener* lst = getListener(service);
1556 if(lst != NULL){
1557 lst->onMessage(
1558 overlayMsg,
1559 overlayMsg->getSourceNode(),
1560 overlayMsg->getDestinationLink()
1561 );
1562 }
1563
1564 return true;
1565}
1566
1567
1568bool BaseOverlay::handleLinkUpdate( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1569
1570 if( ld == NULL ) {
1571 logging_warn( "received overlay update message for link for "
1572 << "which we have no mapping" );
1573 return false;
1574 }
1575 logging_info("Received type update message on link " << ld );
1576
1577 // update our link mapping information for this link
1578 bool changed =
1579 ( ld->remoteNode != overlayMsg->getSourceNode() )
1580 || ( ld->service != overlayMsg->getService() );
1581
1582 // set parameters
1583 ld->up = true;
1584 ld->remoteNode = overlayMsg->getSourceNode();
1585 ld->remoteLink = overlayMsg->getSourceLink();
1586 ld->service = overlayMsg->getService();
1587 ld->autolink = overlayMsg->isAutoLink();
1588
1589 // if our link information changed, we send out an update, too
1590 if( changed ) {
1591 overlayMsg->swapRoles();
1592 overlayMsg->setSourceNode(nodeId);
1593 overlayMsg->setSourceLink(ld->overlayId);
1594 overlayMsg->setService(ld->service);
1595 send( overlayMsg, ld );
1596 }
1597
1598 // service registered? no-> error!
1599 if( !communicationListeners.contains( ld->service ) ) {
1600 logging_warn( "Link up: event listener has not been registered" );
1601 return false;
1602 }
1603
1604 // default or no service registered?
1605 CommunicationListener* listener = communicationListeners.get( ld->service );
1606 if( listener == NULL || listener == &CommunicationListener::DEFAULT ) {
1607 logging_warn("Link up: event listener is default or null!" );
1608 return true;
1609 }
1610
1611 // update descriptor
1612 ld->listener = listener;
1613 ld->setAutoUsed();
1614 ld->setAlive();
1615
1616 // ask the service whether it wants to accept this link
1617 if( !listener->onLinkRequest(ld->remoteNode) ) {
1618
1619 logging_debug("Link id=" << ld->overlayId.toString() <<
1620 " has been denied by service " << ld->service.toString() << ", dropping link");
1621
1622 // prevent onLinkDown calls to the service
1623 ld->listener = &CommunicationListener::DEFAULT;
1624
1625 // drop the link
1626 dropLink( ld->overlayId );
1627 return true;
1628 }
1629
1630 // set link up
1631 ld->up = true;
1632 logging_info( "Link has been accepted by service and is up: " << ld );
1633
1634 // auto links: link has been accepted -> send queued messages
1635 if( ld->messageQueue.size() > 0 ) {
1636 logging_info( "Sending out queued messages on link " << ld );
1637 BOOST_FOREACH( Message* msg, ld->messageQueue ) {
1638 sendMessage( msg, ld->overlayId );
1639 delete msg;
1640 }
1641 ld->messageQueue.clear();
1642 }
1643
1644 // call the notification functions
1645 listener->onLinkUp( ld->overlayId, ld->remoteNode );
1646 sideport->onLinkUp( ld->overlayId, nodeId, ld->remoteNode, this->spovnetId );
1647
1648 return true;
1649}
1650
1651/// handle a link request and reply
1652bool BaseOverlay::handleLinkRequest( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1653 logging_info( "Link request received from node id=" << overlayMsg->getSourceNode() );
1654
1655 //TODO: Check if a request has already been sent using getSourceLink() ...
1656
1657 // create link descriptor
1658 LinkDescriptor* ldn = addDescriptor();
1659
1660 // flags
1661 ldn->up = true;
1662 ldn->fromRemote = true;
1663 ldn->relayed = true;
1664
1665 // parameters
1666 ldn->service = overlayMsg->getService();
1667 ldn->listener = getListener(ldn->service);
1668 ldn->remoteNode = overlayMsg->getSourceNode();
1669 ldn->remoteLink = overlayMsg->getSourceLink();
1670
1671 // update time-stamps
1672 ldn->setAlive();
1673 ldn->setAutoUsed();
1674
1675 // create reply message and send back!
1676 overlayMsg->swapRoles(); // swap source/destination
1677 overlayMsg->setType(OverlayMsg::typeLinkReply);
1678 overlayMsg->setSourceLink(ldn->overlayId);
1679 overlayMsg->setSourceEndpoint( bc->getEndpointDescriptor() );
1680 overlayMsg->setRelayed(true);
1681 send( overlayMsg, ld ); // send back to link
1682
1683 // inform listener
1684 if(ldn != NULL && ldn->listener != NULL)
1685 ldn->listener->onLinkUp( ldn->overlayId, ldn->remoteNode );
1686
1687 return true;
1688}
1689
1690bool BaseOverlay::handleLinkReply( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1691
1692 // find link request
1693 LinkDescriptor* ldn = getDescriptor(overlayMsg->getDestinationLink());
1694
1695 // not found? yes-> drop with error!
1696 if (ldn == NULL) {
1697 logging_error( "No link request pending for "
1698 << overlayMsg->getDestinationLink().toString() );
1699 return false;
1700 }
1701 logging_debug("Handling link reply for " << ldn )
1702
1703 // check if already up
1704 if (ldn->up) {
1705 logging_warn( "Link already up: " << ldn );
1706 return true;
1707 }
1708
1709 // debug message
1710 logging_debug( "Link request reply received. Establishing link"
1711 << " for service " << overlayMsg->getService().toString()
1712 << " with local id=" << overlayMsg->getDestinationLink()
1713 << " and remote link id=" << overlayMsg->getSourceLink()
1714 << " to " << overlayMsg->getSourceEndpoint().toString()
1715 );
1716
1717 // set local link descriptor data
1718 ldn->up = true;
1719 ldn->relayed = true;
1720 ldn->service = overlayMsg->getService();
1721 ldn->listener = getListener(ldn->service);
1722 ldn->remoteLink = overlayMsg->getSourceLink();
1723 ldn->remoteNode = overlayMsg->getSourceNode();
1724
1725 // update timestamps
1726 ldn->setAlive();
1727 ldn->setAutoUsed();
1728
1729 // auto links: link has been accepted -> send queued messages
1730 if( ldn->messageQueue.size() > 0 ) {
1731 logging_info( "Sending out queued messages on link " <<
1732 ldn->overlayId.toString() );
1733 BOOST_FOREACH( Message* msg, ldn->messageQueue ) {
1734 sendMessage( msg, ldn->overlayId );
1735 delete msg;
1736 }
1737 ldn->messageQueue.clear();
1738 }
1739
1740 // inform listeners about new link
1741 ldn->listener->onLinkUp( ldn->overlayId, ldn->remoteNode );
1742
1743 // try to replace relay link with direct link
1744 ldn->communicationId =
1745 bc->establishLink( overlayMsg->getSourceEndpoint() );
1746
1747 return true;
1748}
1749
1750/// handle a keep-alive message for a link
1751bool BaseOverlay::handleLinkAlive( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1752 LinkDescriptor* rld = getDescriptor(overlayMsg->getDestinationLink());
1753 if ( rld != NULL ) {
1754 logging_debug("Keep-Alive for " <<
1755 overlayMsg->getDestinationLink() );
1756 if (overlayMsg->isRouteRecord())
1757 rld->routeRecord = overlayMsg->getRouteRecord();
1758 rld->setAlive();
1759 return true;
1760 } else {
1761 logging_error("Keep-Alive for "
1762 << overlayMsg->getDestinationLink() << ": link unknown." );
1763 return false;
1764 }
1765}
1766
1767/// handle a direct link message
1768bool BaseOverlay::handleLinkDirect( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1769 logging_debug( "Received direct link replacement request" );
1770
1771 /// get destination overlay link
1772 LinkDescriptor* rld = getDescriptor( overlayMsg->getDestinationLink() );
1773 if (rld == NULL || ld == NULL) {
1774 logging_error("Direct link replacement: Link "
1775 << overlayMsg->getDestinationLink() << "not found error." );
1776 return false;
1777 }
1778 logging_info( "Received direct link convert notification for " << rld );
1779
1780 // update information
1781 rld->communicationId = ld->communicationId;
1782 rld->communicationUp = true;
1783 rld->relayed = false;
1784
1785 // mark used and alive!
1786 rld->setAlive();
1787 rld->setAutoUsed();
1788
1789 // erase the original descriptor
1790 eraseDescriptor(ld->overlayId);
1791}
1792
1793/// handles an incoming message
1794bool BaseOverlay::handleMessage( const Message* message, LinkDescriptor* ld,
1795 const LinkID bcLink ) {
1796 logging_debug( "Handling message: " << message->toString());
1797
1798 // decapsulate overlay message
1799 OverlayMsg* overlayMsg =
1800 const_cast<Message*>(message)->decapsulate<OverlayMsg>();
1801 if( overlayMsg == NULL ) return false;
1802
1803 // increase number of hops
1804 overlayMsg->increaseNumHops();
1805
1806 // refresh relay information
1807 refreshRelayInformation( overlayMsg, ld );
1808
1809 // update route record
1810 overlayMsg->addRouteRecord(nodeId);
1811
1812 // handle dht messages (do not route)
1813 if (overlayMsg->isDHTMessage())
1814 return handleDHTMessage(overlayMsg);
1815
1816 // handle signaling messages (do not route!)
1817 if (overlayMsg->getType()>=OverlayMsg::typeSignalingStart &&
1818 overlayMsg->getType()<=OverlayMsg::typeSignalingEnd ) {
1819 overlayInterface->onMessage(overlayMsg, NodeID::UNSPECIFIED, LinkID::UNSPECIFIED);
1820 delete overlayMsg;
1821 return true;
1822 }
1823
1824 // message for reached destination? no-> route message
1825 if (!overlayMsg->getDestinationNode().isUnspecified() &&
1826 overlayMsg->getDestinationNode() != nodeId ) {
1827 logging_debug("Routing message "
1828 << " from " << overlayMsg->getSourceNode()
1829 << " to " << overlayMsg->getDestinationNode()
1830 );
1831 route( overlayMsg );
1832 delete overlayMsg;
1833 return true;
1834 }
1835
1836 // handle DHT response messages
1837 if (overlayMsg->hasTypeMask( OverlayMsg::maskDHTResponse )) {
1838 bool ret = handleDHTMessage(overlayMsg);
1839 delete overlayMsg;
1840 return ret;
1841 }
1842
1843 // handle base overlay message
1844 bool ret = false; // return value
1845 switch ( overlayMsg->getType() ) {
1846
1847 // data transport messages
1848 case OverlayMsg::typeData:
1849 ret = handleData(overlayMsg, ld); break;
1850
1851 // overlay setup messages
1852 case OverlayMsg::typeJoinRequest:
1853 ret = handleJoinRequest(overlayMsg, bcLink ); break;
1854 case OverlayMsg::typeJoinReply:
1855 ret = handleJoinReply(overlayMsg, bcLink ); break;
1856
1857 // link specific messages
1858 case OverlayMsg::typeLinkRequest:
1859 ret = handleLinkRequest(overlayMsg, ld ); break;
1860 case OverlayMsg::typeLinkReply:
1861 ret = handleLinkReply(overlayMsg, ld ); break;
1862 case OverlayMsg::typeLinkUpdate:
1863 ret = handleLinkUpdate(overlayMsg, ld ); break;
1864 case OverlayMsg::typeLinkAlive:
1865 ret = handleLinkAlive(overlayMsg, ld ); break;
1866 case OverlayMsg::typeLinkDirect:
1867 ret = handleLinkDirect(overlayMsg, ld ); break;
1868
1869 // handle unknown message type
1870 default: {
1871 logging_error( "received message in invalid state! don't know " <<
1872 "what to do with this message of type " << overlayMsg->getType() );
1873 ret = false;
1874 break;
1875 }
1876 }
1877
1878 // free overlay message and return value
1879 delete overlayMsg;
1880 return ret;
1881}
1882
1883// ----------------------------------------------------------------------------
1884
1885void BaseOverlay::broadcastMessage(Message* message, const ServiceID& service) {
1886
1887 logging_debug( "broadcasting message to all known nodes " <<
1888 "in the overlay from service " + service.toString() );
1889
1890 OverlayInterface::NodeList nodes = overlayInterface->getKnownNodes(true);
1891 OverlayInterface::NodeList::iterator i = nodes.begin();
1892 for(; i != nodes.end(); i++ ) {
1893 if( *i == nodeId) continue; // don't send to ourselfs
1894 sendMessage( message, *i, service );
1895 }
1896}
1897
1898/// return the overlay neighbors
1899vector<NodeID> BaseOverlay::getOverlayNeighbors(bool deep) const {
1900 // the known nodes _can_ also include our node, so we remove ourself
1901 vector<NodeID> nodes = overlayInterface->getKnownNodes(deep);
1902 vector<NodeID>::iterator i = find( nodes.begin(), nodes.end(), this->nodeId );
1903 if( i != nodes.end() ) nodes.erase( i );
1904 return nodes;
1905}
1906
1907const NodeID& BaseOverlay::getNodeID(const LinkID& lid) const {
1908 if( lid == LinkID::UNSPECIFIED ) return nodeId;
1909 const LinkDescriptor* ld = getDescriptor(lid);
1910 if( ld == NULL ) return NodeID::UNSPECIFIED;
1911 else return ld->remoteNode;
1912}
1913
1914vector<LinkID> BaseOverlay::getLinkIDs( const NodeID& nid ) const {
1915 vector<LinkID> linkvector;
1916 BOOST_FOREACH( LinkDescriptor* ld, links ) {
1917 if( ld->remoteNode == nid || nid == NodeID::UNSPECIFIED ) {
1918 linkvector.push_back( ld->overlayId );
1919 }
1920 }
1921 return linkvector;
1922}
1923
1924
1925void BaseOverlay::onNodeJoin(const NodeID& node) {
1926 JoiningNodes::iterator i = std::find( joiningNodes.begin(), joiningNodes.end(), node );
1927 if( i == joiningNodes.end() ) return;
1928
1929 logging_info( "node has successfully joined baseoverlay and overlay structure "
1930 << node.toString() );
1931
1932 joiningNodes.erase( i );
1933}
1934
1935void BaseOverlay::eventFunction() {
1936 stabilizeRelays();
1937 stabilizeLinks();
1938 stabilizeDHT();
1939 updateVisual();
1940}
1941
1942void BaseOverlay::updateVisual(){
1943
1944 //
1945 // update base overlay structure
1946 //
1947
1948 static NodeID pre = NodeID::UNSPECIFIED;
1949 static NodeID suc = NodeID::UNSPECIFIED;
1950
1951 vector<NodeID> nodes = this->getOverlayNeighbors(false);
1952
1953 if(nodes.size() == 0){
1954
1955 if(pre != NodeID::UNSPECIFIED){
1956 visual.visDisconnect(visualIdOverlay, this->nodeId, pre, "");
1957 pre = NodeID::UNSPECIFIED;
1958 }
1959 if(suc != NodeID::UNSPECIFIED){
1960 visual.visDisconnect(visualIdOverlay, this->nodeId, suc, "");
1961 suc = NodeID::UNSPECIFIED;
1962 }
1963
1964 } // if(nodes.size() == 0)
1965
1966 if(nodes.size() == 1){
1967 // only one node, make this pre and succ
1968 // and then go into the node.size()==2 case
1969 //nodes.push_back(nodes.at(0));
1970
1971 if(pre != nodes.at(0)){
1972 pre = nodes.at(0);
1973 if(pre != NodeID::UNSPECIFIED)
1974 visual.visConnect(visualIdOverlay, this->nodeId, pre, "");
1975 }
1976 }
1977
1978 if(nodes.size() == 2){
1979
1980 // old finger
1981 if(nodes.at(0) != pre){
1982 if(pre != NodeID::UNSPECIFIED)
1983 visual.visDisconnect(visualIdOverlay, this->nodeId, pre, "");
1984 pre = NodeID::UNSPECIFIED;
1985 }
1986 if(nodes.at(1) != suc){
1987 if(suc != NodeID::UNSPECIFIED)
1988 visual.visDisconnect(visualIdOverlay, this->nodeId, suc, "");
1989 suc = NodeID::UNSPECIFIED;
1990 }
1991
1992 // connect with fingers
1993 if(pre == NodeID::UNSPECIFIED){
1994 pre = nodes.at(0);
1995 if(pre != NodeID::UNSPECIFIED)
1996 visual.visConnect(visualIdOverlay, this->nodeId, pre, "");
1997 }
1998 if(suc == NodeID::UNSPECIFIED){
1999 suc = nodes.at(1);
2000 if(suc != NodeID::UNSPECIFIED)
2001 visual.visConnect(visualIdOverlay, this->nodeId, suc, "");
2002 }
2003
2004 } //if(nodes.size() == 2)
2005
2006// {
2007// logging_error("================================");
2008// logging_error("my nodeid " << nodeId.get(MAX_KEYLENGTH-16, 16));
2009// logging_error("================================");
2010// if(nodes.size()>= 1){
2011// logging_error("real pre " << nodes.at(0).toString());
2012// logging_error("real pre " << nodes.at(0).get(MAX_KEYLENGTH-16, 16));
2013// }
2014// if(nodes.size()>= 2){
2015// logging_error("real suc " << nodes.at(1).toString());
2016// logging_error("real suc " << nodes.at(1).get(MAX_KEYLENGTH-16, 16));
2017// }
2018// logging_error("================================");
2019// if(pre == NodeID::UNSPECIFIED){
2020// logging_error("pre: unspecified");
2021// }else{
2022// unsigned int prei = pre.get(MAX_KEYLENGTH-16, 16);
2023// logging_error("pre: " << prei);
2024// }
2025// if(suc == NodeID::UNSPECIFIED){
2026// logging_error("suc: unspecified");
2027// }else{
2028// unsigned int suci = suc.get(MAX_KEYLENGTH-16, 16);
2029// logging_error("suc: " << suci);
2030// }
2031// logging_error("================================");
2032// }
2033
2034 //
2035 // update base communication links
2036 //
2037
2038 static set<NodeID> linkset;
2039 set<NodeID> remotenodes;
2040 BOOST_FOREACH( LinkDescriptor* ld, links ) {
2041 if (!ld->isVital() || ld->service != OverlayInterface::OVERLAY_SERVICE_ID)
2042 continue;
2043
2044 if (ld->routeRecord.size()>1 && ld->relayed) {
2045 for (size_t i=1; i<ld->routeRecord.size(); i++)
2046 remotenodes.insert( ld->routeRecord[ld->routeRecord.size()-i-1] );
2047 } else {
2048 remotenodes.insert(ld->remoteNode);
2049 }
2050 }
2051
2052 // which links are old and need deletion?
2053 bool changed = false;
2054
2055 do{
2056 changed = false;
2057 BOOST_FOREACH(NodeID n, linkset){
2058 if(remotenodes.find(n) == remotenodes.end()){
2059 visual.visDisconnect(visualIdBase, this->nodeId, n, "");
2060 linkset.erase(n);
2061 changed = true;
2062 break;
2063 }
2064 }
2065 }while(changed);
2066
2067 // which links are new and need creation?
2068 do{
2069 changed = false;
2070 BOOST_FOREACH(NodeID n, remotenodes){
2071 if(linkset.find(n) == linkset.end()){
2072 visual.visConnect(visualIdBase, this->nodeId, n, "");
2073 linkset.insert(n);
2074 changed = true;
2075 break;
2076 }
2077 }
2078 }while(changed);
2079
2080}
2081
2082// ----------------------------------------------------------------------------
2083
2084/// stabilize DHT state
2085void BaseOverlay::stabilizeDHT() {
2086 // remove old values from DHT
2087 BOOST_FOREACH( DHTEntry& entry, dht->entries ) {
2088 // erase old entries
2089 entry.erase_expired_entries();
2090 }
2091
2092 // erase old values from local DHT
2093 BOOST_FOREACH( DHTEntry& entry, localDHT->entries ) {
2094 // erase old entries
2095 entry.erase_expired_entries();
2096 }
2097
2098 // re-publish values
2099 BOOST_FOREACH( DHTEntry& entry, localDHT->entries ) {
2100 BOOST_FOREACH( ValueEntry& value, entry.values )
2101 dhtPut(entry.key, value.get_value(), 0, false, true );
2102 }
2103}
2104
2105// handle DHT messages
2106bool BaseOverlay::handleDHTMessage( OverlayMsg* msg ) {
2107
2108 // decapsulate message
2109 logging_debug("received DHT message");
2110 DHTMessage* dhtMsg = msg->decapsulate<DHTMessage>();
2111
2112 // handle DHT data message
2113 if (msg->getType()==OverlayMsg::typeDHTData) {
2114 const ServiceID& service = msg->getService();
2115 logging_info( "Received DHT data for service " << service.toString() );
2116
2117 // delegate data message
2118 CommunicationListener* lst = getListener(service);
2119 if(lst != NULL) lst->onKeyValue(dhtMsg->getKey(), dhtMsg->getValues() );
2120 return true;
2121 }
2122
2123 // route message to closest node
2124 if (!overlayInterface->isClosestNodeTo(msg->getDestinationNode())) {
2125 logging_debug("Routing DHT message to closest node "
2126 << " from " << msg->getSourceNode()
2127 << " to " << msg->getDestinationNode()
2128 );
2129 route( msg );
2130 delete msg;
2131 return true;
2132 }
2133
2134 // now, we are the closest node...
2135 switch (msg->getType()) {
2136 case OverlayMsg::typeDHTPut: {
2137 logging_debug("DHT: Attempt to store values for key "
2138 << dhtMsg->getKey());
2139 if (dhtMsg->doReplace()) {
2140 logging_debug("DHT: Attempt to replace key: remove old values first!");
2141 dht->remove(dhtMsg->getKey());
2142 }
2143 BOOST_FOREACH( Data value, dhtMsg->getValues() ) {
2144 logging_debug("DHT: Stored value: " << value );
2145 dht->put(dhtMsg->getKey(), value, dhtMsg->getTTL() );
2146 }
2147 break;
2148 }
2149
2150 case OverlayMsg::typeDHTGet: {
2151 logging_info("DHT-Get: key=" << dhtMsg->getKey() );
2152 vector<Data> vect = dht->get(dhtMsg->getKey());
2153 BOOST_FOREACH(const Data& d, vect)
2154 logging_info("DHT-Get: value=" << d);
2155 OverlayMsg omsg(*msg);
2156 omsg.swapRoles();
2157 omsg.setType(OverlayMsg::typeDHTData);
2158 DHTMessage dhtmsg(dhtMsg->getKey(), vect);
2159 omsg.encapsulate(&dhtmsg);
2160 dhtSend(&omsg, omsg.getDestinationNode());
2161 break;
2162 }
2163
2164 case OverlayMsg::typeDHTRemove: {
2165 if (dhtMsg->hasValues()) {
2166 BOOST_FOREACH( Data value, dhtMsg->getValues() )
2167 dht->remove(dhtMsg->getKey(), value );
2168 } else
2169 dht->remove( dhtMsg->getKey() );
2170 break;
2171 }
2172
2173 default:
2174 logging_error("DHT Message type unknown.");
2175 return false;
2176 }
2177 delete msg;
2178 return true;
2179}
2180
2181/// put a value to the DHT with a ttl given in seconds
2182void BaseOverlay::dhtPut( const Data& key, const Data& value, int ttl, bool replace, bool no_local_refresh ) {
2183
2184 logging_info("DHT: putting key=" << key
2185 << " value=" << value
2186 << " ttl=" << ttl
2187 << " replace=" << replace
2188 );
2189
2190
2191 if (!no_local_refresh) {
2192 // put into local data store (for refreshes)
2193 if (replace) localDHT->remove(key);
2194 localDHT->put(key, value, ttl);
2195 }
2196
2197 // calculate hash
2198 NodeID dest = NodeID::sha1(key.getBuffer(), key.getLength() / 8);
2199 DHTMessage dhtmsg( key, value );
2200 dhtmsg.setReplace( replace );
2201 dhtmsg.setTTL(ttl);
2202
2203 OverlayMsg msg( OverlayMsg::typeDHTPut );
2204 msg.encapsulate( &dhtmsg );
2205 dhtSend(&msg, dest);
2206}
2207
2208/// removes a key value pair from the DHT
2209void BaseOverlay::dhtRemove( const Data& key, const Data& value ) {
2210 // remove from local data store
2211 localDHT->remove(key,value);
2212
2213 // calculate hash
2214 NodeID dest = NodeID::sha1(key.getBuffer(), key.getLength() / 8);
2215 DHTMessage dhtmsg(key,value);
2216
2217 // send message
2218 OverlayMsg msg(OverlayMsg::typeDHTRemove);
2219 msg.encapsulate( &dhtmsg );
2220 dhtSend(&msg, dest);
2221}
2222
2223/// removes all data stored at the given key
2224void BaseOverlay::dhtRemove( const Data& key ) {
2225 // calculate hash
2226 NodeID dest = NodeID::sha1(key.getBuffer(), key.getLength() / 8);
2227 DHTMessage dhtmsg(key);
2228
2229 // send message
2230 OverlayMsg msg(OverlayMsg::typeDHTRemove);
2231 msg.encapsulate( &dhtmsg );
2232 dhtSend(&msg, dest);
2233}
2234
2235/// requests data stored using key
2236void BaseOverlay::dhtGet( const Data& key, const ServiceID& service ) {
2237 logging_info("DHT: trying to resolve key=" <<
2238 key << " for service=" << service.toString() );
2239
2240 // calculate hash
2241 NodeID dest = NodeID::sha1(key.getBuffer(), key.getLength() / 8);
2242 DHTMessage dhtmsg(key);
2243
2244 // send message
2245 OverlayMsg msg(OverlayMsg::typeDHTGet);
2246 msg.setService(service);
2247 msg.encapsulate( &dhtmsg );
2248 dhtSend(&msg, dest);
2249}
2250
2251void BaseOverlay::dhtSend( OverlayMsg* msg, const NodeID& dest ) {
2252 logging_info("DHT: sending message with key=" << dest.toString() );
2253 msg->setSourceNode(this->nodeId);
2254 msg->setDestinationNode(dest);
2255
2256 // local storage? yes-> put into DHT directly
2257 if (overlayInterface->isClosestNodeTo(msg->getDestinationNode())) {
2258 Data d = data_serialize(msg);
2259 Message* m2 = new Message(d);
2260 OverlayMsg* m3 = m2->decapsulate<OverlayMsg>();
2261 handleDHTMessage(m3);
2262 delete m2;
2263 return;
2264 }
2265
2266 // send message "normally"
2267 send(msg, dest);
2268}
2269
2270std::string BaseOverlay::debugInformation() {
2271 std::stringstream s;
2272 int i=0;
2273
2274 // dump overlay information
2275 s << "Long debug info ... [see below]" << endl << endl;
2276 s << "--- overlay information ----------------------" << endl;
2277 s << overlayInterface->debugInformation() << endl;
2278
2279 // dump link state
2280 s << "--- link state -------------------------------" << endl;
2281 BOOST_FOREACH( LinkDescriptor* ld, links ) {
2282 s << "link " << i << ": " << ld << endl;
2283 i++;
2284 }
2285 s << endl << endl;
2286
2287 return s.str();
2288}
2289
2290}} // namespace ariba, overlay
Note: See TracBrowser for help on using the repository browser.