close Warning: Can't use blame annotator:
No changeset 2259 in the repository

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

Last change on this file since 9946 was 9946, checked in by Christoph Mayer, 13 years ago

-dht cleanup code

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