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

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