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

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

Last change on this file since 7471 was 7018, checked in by mies, 15 years ago
File size: 66.5 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 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.setRegisterRelay(true);
990
991 // debug message
992 logging_info(
993 "Sending link request with"
994 << " link=" << ld->overlayId.toString()
995 << " node=" << ld->remoteNode.toString()
996 << " serv=" << ld->service.toString()
997 );
998
999 // sending message to node
1000 send_node( &msg, ld->remoteNode, ld->service );
1001
1002 return ld->overlayId;
1003}
1004
1005/// drops an established link
1006void BaseOverlay::dropLink(const LinkID& link) {
1007 logging_info( "Dropping link (initiated locally):" << link.toString() );
1008
1009 // find the link item to drop
1010 LinkDescriptor* ld = getDescriptor(link);
1011 if( ld == NULL ) {
1012 logging_warn( "Can't drop link, link is unknown!");
1013 return;
1014 }
1015
1016 // delete all queued messages
1017 if( ld->messageQueue.size() > 0 ) {
1018 logging_warn( "Dropping link " << ld->overlayId.toString() << " that has "
1019 << ld->messageQueue.size() << " waiting messages" );
1020 ld->flushQueue();
1021 }
1022
1023 // inform sideport and listener
1024 if(ld->listener != NULL)
1025 ld->listener->onLinkDown( ld->overlayId, ld->remoteNode );
1026 sideport->onLinkDown(ld->overlayId, this->nodeId, ld->remoteNode, this->spovnetId );
1027
1028 // do not drop relay links
1029 if (!ld->relaying) {
1030 // drop the link in base communication
1031 if (ld->communicationUp) bc->dropLink( ld->communicationId );
1032
1033 // erase descriptor
1034 eraseDescriptor( ld->overlayId );
1035 } else {
1036 ld->dropAfterRelaying = true;
1037 }
1038}
1039
1040// ----------------------------------------------------------------------------
1041
1042/// internal send message, always use this functions to send messages over links
1043seqnum_t BaseOverlay::sendMessage( const Message* message, const LinkID& link ) {
1044 logging_debug( "Sending data message on link " << link.toString() );
1045
1046 // get the mapping for this link
1047 LinkDescriptor* ld = getDescriptor(link);
1048 if( ld == NULL ) {
1049 logging_error("Could not send message. "
1050 << "Link not found id=" << link.toString());
1051 return -1;
1052 }
1053
1054 // check if the link is up yet, if its an auto link queue message
1055 if( !ld->up ) {
1056 ld->setAutoUsed();
1057 if( ld->autolink ) {
1058 logging_info("Auto-link " << link.toString() << " not up, queue message");
1059 Data data = data_serialize( message );
1060 const_cast<Message*>(message)->dropPayload();
1061 ld->messageQueue.push_back( new Message(data) );
1062 } else {
1063 logging_error("Link " << link.toString() << " not up, drop message");
1064 }
1065 return -1;
1066 }
1067
1068 // compile overlay message (has service and node id)
1069 OverlayMsg overmsg( OverlayMsg::typeData );
1070 overmsg.encapsulate( const_cast<Message*>(message) );
1071
1072 // send message over relay/direct/overlay
1073 return send_link( &overmsg, ld->overlayId );
1074}
1075
1076seqnum_t BaseOverlay::sendMessage(const Message* message,
1077 const NodeID& node, const ServiceID& service) {
1078
1079 // find link for node and service
1080 LinkDescriptor* ld = getAutoDescriptor( node, service );
1081
1082 // if we found no link, create an auto link
1083 if( ld == NULL ) {
1084
1085 // debug output
1086 logging_info( "No link to send message to node "
1087 << node.toString() << " found for service "
1088 << service.toString() << ". Creating auto link ..."
1089 );
1090
1091 // call base overlay to create a link
1092 LinkID link = establishLink( node, service );
1093 ld = getDescriptor( link );
1094 if( ld == NULL ) {
1095 logging_error( "Failed to establish auto-link.");
1096 return -1;
1097 }
1098 ld->autolink = true;
1099
1100 logging_debug( "Auto-link establishment in progress to node "
1101 << node.toString() << " with link id=" << link.toString() );
1102 }
1103 assert(ld != NULL);
1104
1105 // mark the link as used, as we now send a message through it
1106 ld->setAutoUsed();
1107
1108 // send / queue message
1109 return sendMessage( message, ld->overlayId );
1110}
1111
1112// ----------------------------------------------------------------------------
1113
1114const EndpointDescriptor& BaseOverlay::getEndpointDescriptor(
1115 const LinkID& link) const {
1116
1117 // return own end-point descriptor
1118 if( link.isUnspecified() )
1119 return bc->getEndpointDescriptor();
1120
1121 // find link descriptor. not found -> return unspecified
1122 const LinkDescriptor* ld = getDescriptor(link);
1123 if (ld==NULL) return EndpointDescriptor::UNSPECIFIED();
1124
1125 // return endpoint-descriptor from base communication
1126 return bc->getEndpointDescriptor( ld->communicationId );
1127}
1128
1129const EndpointDescriptor& BaseOverlay::getEndpointDescriptor(
1130 const NodeID& node) const {
1131
1132 // return own end-point descriptor
1133 if( node == nodeId || node.isUnspecified() ) {
1134 //logging_info("getEndpointDescriptor: returning self.");
1135 return bc->getEndpointDescriptor();
1136 }
1137
1138 // no joined and request remote descriptor? -> fail!
1139 if( overlayInterface == NULL ) {
1140 logging_error( "Overlay interface not set, cannot resolve end-point." );
1141 return EndpointDescriptor::UNSPECIFIED();
1142 }
1143
1144// // resolve end-point descriptor from the base-overlay routing table
1145// const EndpointDescriptor& ep = overlayInterface->resolveNode( node );
1146// if(ep.toString() != "") return ep;
1147
1148 // see if we can find the node in our own table
1149 BOOST_FOREACH(const LinkDescriptor* ld, links){
1150 if(ld->remoteNode != node) continue;
1151 if(!ld->communicationUp) continue;
1152 const EndpointDescriptor& ep =
1153 bc->getEndpointDescriptor(ld->communicationId);
1154 if(ep != EndpointDescriptor::UNSPECIFIED()) {
1155 //logging_info("getEndpointDescriptor: using " << ld->to_string());
1156 return ep;
1157 }
1158 }
1159
1160 logging_warn( "No EndpointDescriptor found for node " << node );
1161 logging_warn( const_cast<BaseOverlay*>(this)->debugInformation() );
1162
1163 return EndpointDescriptor::UNSPECIFIED();
1164}
1165
1166// ----------------------------------------------------------------------------
1167
1168bool BaseOverlay::registerSidePort(SideportListener* _sideport) {
1169 sideport = _sideport;
1170 _sideport->configure( this );
1171 return true;
1172}
1173
1174bool BaseOverlay::unregisterSidePort(SideportListener* _sideport) {
1175 sideport = &SideportListener::DEFAULT;
1176 return true;
1177}
1178
1179// ----------------------------------------------------------------------------
1180
1181bool BaseOverlay::bind(CommunicationListener* listener, const ServiceID& sid) {
1182 logging_debug( "binding communication listener " << listener
1183 << " on serviceid " << sid.toString() );
1184
1185 if( communicationListeners.contains( sid ) ) {
1186 logging_error( "some listener already registered for service id "
1187 << sid.toString() );
1188 return false;
1189 }
1190
1191 communicationListeners.registerItem( listener, sid );
1192 return true;
1193}
1194
1195
1196bool BaseOverlay::unbind(CommunicationListener* listener, const ServiceID& sid) {
1197 logging_debug( "unbinding listener " << listener << " from serviceid " << sid.toString() );
1198
1199 if( !communicationListeners.contains( sid ) ) {
1200 logging_warn( "cannot unbind listener. no listener registered on service id " << sid.toString() );
1201 return false;
1202 }
1203
1204 if( communicationListeners.get(sid) != listener ) {
1205 logging_warn( "listener bound to service id " << sid.toString()
1206 << " is different than listener trying to unbind" );
1207 return false;
1208 }
1209
1210 communicationListeners.unregisterItem( sid );
1211 return true;
1212}
1213
1214// ----------------------------------------------------------------------------
1215
1216bool BaseOverlay::bind(NodeListener* listener) {
1217 logging_debug( "Binding node listener " << listener );
1218
1219 // already bound? yes-> warning
1220 NodeListenerVector::iterator i =
1221 find( nodeListeners.begin(), nodeListeners.end(), listener );
1222 if( i != nodeListeners.end() ) {
1223 logging_warn("Node listener " << listener << " is already bound!" );
1224 return false;
1225 }
1226
1227 // no-> add
1228 nodeListeners.push_back( listener );
1229 return true;
1230}
1231
1232bool BaseOverlay::unbind(NodeListener* listener) {
1233 logging_debug( "Unbinding node listener " << listener );
1234
1235 // already unbound? yes-> warning
1236 NodeListenerVector::iterator i = find( nodeListeners.begin(), nodeListeners.end(), listener );
1237 if( i == nodeListeners.end() ) {
1238 logging_warn( "Node listener " << listener << " is not bound!" );
1239 return false;
1240 }
1241
1242 // no-> remove
1243 nodeListeners.erase( i );
1244 return true;
1245}
1246
1247// ----------------------------------------------------------------------------
1248
1249void BaseOverlay::onLinkUp(const LinkID& id,
1250 const address_v* local, const address_v* remote) {
1251 logging_debug( "Link up with base communication link id=" << id );
1252
1253 // get descriptor for link
1254 LinkDescriptor* ld = getDescriptor(id, true);
1255
1256 // handle bootstrap link we initiated
1257 if( std::find(bootstrapLinks.begin(), bootstrapLinks.end(), id) != bootstrapLinks.end() ){
1258 logging_info(
1259 "Join has been initiated by me and the link is now up. " <<
1260 "Sending out join request for SpoVNet " << spovnetId.toString()
1261 );
1262
1263 // send join request message
1264 OverlayMsg overlayMsg( OverlayMsg::typeJoinRequest,
1265 OverlayInterface::OVERLAY_SERVICE_ID, nodeId );
1266 JoinRequest joinRequest( spovnetId, nodeId );
1267 overlayMsg.encapsulate( &joinRequest );
1268 bc->sendMessage( id, &overlayMsg );
1269 return;
1270 }
1271
1272 // no link found? -> link establishment from remote, add one!
1273 if (ld == NULL) {
1274 ld = addDescriptor( id );
1275 logging_info( "onLinkUp (remote request) descriptor: " << ld );
1276
1277 // update descriptor
1278 ld->fromRemote = true;
1279 ld->communicationId = id;
1280 ld->communicationUp = true;
1281 ld->setAutoUsed();
1282 ld->setAlive();
1283
1284 // in this case, do not inform listener, since service it unknown
1285 // -> wait for update message!
1286
1287 // link mapping found? -> send update message with node-id and service id
1288 } else {
1289 logging_info( "onLinkUp descriptor (initiated locally):" << ld );
1290
1291 // update descriptor
1292 ld->setAutoUsed();
1293 ld->setAlive();
1294 ld->communicationUp = true;
1295 ld->fromRemote = false;
1296
1297 // if link is a relayed link->convert to direct link
1298 if (ld->relayed) {
1299 logging_info( "Converting to direct link: " << ld );
1300 ld->up = true;
1301 ld->relayed = false;
1302 OverlayMsg overMsg( OverlayMsg::typeLinkDirect );
1303 overMsg.setSourceLink( ld->overlayId );
1304 overMsg.setDestinationLink( ld->remoteLink );
1305 send_link( &overMsg, ld->overlayId );
1306 } else {
1307 // note: necessary to validate the link on the remote side!
1308 logging_info( "Sending out update" <<
1309 " for service " << ld->service.toString() <<
1310 " with local node id " << nodeId.toString() <<
1311 " on link " << ld->overlayId.toString() );
1312
1313 // compile and send update message
1314 OverlayMsg overlayMsg( OverlayMsg::typeLinkUpdate );
1315 overlayMsg.setSourceLink(ld->overlayId);
1316 overlayMsg.setAutoLink( ld->autolink );
1317 send_link( &overlayMsg, ld->overlayId, true );
1318 }
1319 }
1320}
1321
1322void BaseOverlay::onLinkDown(const LinkID& id,
1323 const address_v* local, const address_v* remote) {
1324
1325 // erase bootstrap links
1326 vector<LinkID>::iterator it = std::find( bootstrapLinks.begin(), bootstrapLinks.end(), id );
1327 if( it != bootstrapLinks.end() ) bootstrapLinks.erase( it );
1328
1329 // get descriptor for link
1330 LinkDescriptor* ld = getDescriptor(id, true);
1331 if ( ld == NULL ) return; // not found? ->ignore!
1332 logging_info( "onLinkDown descriptor: " << ld );
1333
1334 // removing relay link information
1335 removeRelayLink(ld->overlayId);
1336
1337 // inform listeners about link down
1338 ld->communicationUp = false;
1339 if (!ld->service.isUnspecified()) {
1340 CommunicationListener* lst = getListener(ld->service);
1341 if(lst != NULL) lst->onLinkDown( ld->overlayId, ld->remoteNode );
1342 sideport->onLinkDown( id, this->nodeId, ld->remoteNode, this->spovnetId );
1343 }
1344
1345 // delete all queued messages (auto links)
1346 if( ld->messageQueue.size() > 0 ) {
1347 logging_warn( "Dropping link " << id.toString() << " that has "
1348 << ld->messageQueue.size() << " waiting messages" );
1349 ld->flushQueue();
1350 }
1351
1352 // erase mapping
1353 eraseDescriptor(ld->overlayId);
1354}
1355
1356void BaseOverlay::onLinkChanged(const LinkID& id,
1357 const address_v* oldlocal, const address_v* newlocal,
1358 const address_v* oldremote, const address_v* newremote) {
1359
1360 // get descriptor for link
1361 LinkDescriptor* ld = getDescriptor(id, true);
1362 if ( ld == NULL ) return; // not found? ->ignore!
1363 logging_debug( "onLinkChanged descriptor: " << ld );
1364
1365 // inform listeners
1366 ld->listener->onLinkChanged( ld->overlayId, ld->remoteNode );
1367 sideport->onLinkChanged( id, this->nodeId, ld->remoteNode, this->spovnetId );
1368
1369 // autolinks: refresh timestamp
1370 ld->setAutoUsed();
1371}
1372
1373void BaseOverlay::onLinkFail(const LinkID& id,
1374 const address_v* local, const address_v* remote) {
1375 logging_debug( "Link fail with base communication link id=" << id );
1376
1377 // erase bootstrap links
1378 vector<LinkID>::iterator it = std::find( bootstrapLinks.begin(), bootstrapLinks.end(), id );
1379 if( it != bootstrapLinks.end() ) bootstrapLinks.erase( it );
1380
1381 // get descriptor for link
1382 LinkDescriptor* ld = getDescriptor(id, true);
1383 if ( ld == NULL ) return; // not found? ->ignore!
1384 logging_debug( "Link failed id=" << ld->overlayId.toString() );
1385
1386 // inform listeners
1387 ld->listener->onLinkFail( ld->overlayId, ld->remoteNode );
1388 sideport->onLinkFail( id, this->nodeId, ld->remoteNode, this->spovnetId );
1389}
1390
1391void BaseOverlay::onLinkQoSChanged(const LinkID& id, const address_v* local,
1392 const address_v* remote, const QoSParameterSet& qos) {
1393 logging_debug( "Link quality changed with base communication link id=" << id );
1394
1395 // get descriptor for link
1396 LinkDescriptor* ld = getDescriptor(id, true);
1397 if ( ld == NULL ) return; // not found? ->ignore!
1398 logging_debug( "Link quality changed id=" << ld->overlayId.toString() );
1399}
1400
1401bool BaseOverlay::onLinkRequest( const LinkID& id, const address_v* local,
1402 const address_v* remote ) {
1403 logging_debug("Accepting link request from " << remote->to_string() );
1404 return true;
1405}
1406
1407/// handles a message from base communication
1408bool BaseOverlay::receiveMessage(const Message* message,
1409 const LinkID& link, const NodeID& ) {
1410 // get descriptor for link
1411 LinkDescriptor* ld = getDescriptor( link, true );
1412 return handleMessage( message, ld, link );
1413}
1414
1415// ----------------------------------------------------------------------------
1416
1417/// Handle spovnet instance join requests
1418bool BaseOverlay::handleJoinRequest( OverlayMsg* overlayMsg, const LinkID& bcLink ) {
1419
1420 // decapsulate message
1421 JoinRequest* joinReq = overlayMsg->decapsulate<JoinRequest>();
1422 logging_info( "Received join request for spovnet " <<
1423 joinReq->getSpoVNetID().toString() );
1424
1425 // check spovnet id
1426 if( joinReq->getSpoVNetID() != spovnetId ) {
1427 logging_error(
1428 "Received join request for spovnet we don't handle " <<
1429 joinReq->getSpoVNetID().toString() );
1430 return false;
1431 }
1432
1433 // TODO: here you can implement mechanisms to deny joining of a node
1434 bool allow = true;
1435 logging_info( "Sending join reply for spovnet " <<
1436 spovnetId.toString() << " to node " <<
1437 overlayMsg->getSourceNode().toString() <<
1438 ". Result: " << (allow ? "allowed" : "denied") );
1439 joiningNodes.push_back( overlayMsg->getSourceNode() );
1440
1441 // return overlay parameters
1442 assert( overlayInterface != NULL );
1443 logging_debug( "Using bootstrap end-point "
1444 << getEndpointDescriptor().toString() )
1445 OverlayParameterSet parameters = overlayInterface->getParameters();
1446 OverlayMsg retmsg( OverlayMsg::typeJoinReply,
1447 OverlayInterface::OVERLAY_SERVICE_ID, nodeId );
1448 JoinReply replyMsg( spovnetId, parameters,
1449 allow, getEndpointDescriptor() );
1450 retmsg.encapsulate(&replyMsg);
1451 bc->sendMessage( bcLink, &retmsg );
1452
1453 return true;
1454}
1455
1456/// Handle replies to spovnet instance join requests
1457bool BaseOverlay::handleJoinReply( OverlayMsg* overlayMsg, const LinkID& bcLink ) {
1458 // decapsulate message
1459 logging_debug("received join reply message");
1460 JoinReply* replyMsg = overlayMsg->decapsulate<JoinReply>();
1461
1462 // correct spovnet?
1463 if( replyMsg->getSpoVNetID() != spovnetId ) { // no-> fail
1464 logging_error( "Received SpoVNet join reply for " <<
1465 replyMsg->getSpoVNetID().toString() <<
1466 " != " << spovnetId.toString() );
1467 delete replyMsg;
1468 return false;
1469 }
1470
1471 // access granted? no -> fail
1472 if( !replyMsg->getJoinAllowed() ) {
1473 logging_error( "Our join request has been denied" );
1474
1475 // drop initiator link
1476 if( !bcLink.isUnspecified() ){
1477 bc->dropLink( bcLink );
1478
1479 vector<LinkID>::iterator it = std::find(
1480 bootstrapLinks.begin(), bootstrapLinks.end(), bcLink);
1481 if( it != bootstrapLinks.end() )
1482 bootstrapLinks.erase(it);
1483 }
1484
1485 // inform all registered services of the event
1486 BOOST_FOREACH( NodeListener* i, nodeListeners )
1487 i->onJoinFailed( spovnetId );
1488
1489 delete replyMsg;
1490 return true;
1491 }
1492
1493 // access has been granted -> continue!
1494 logging_info("Join request has been accepted for spovnet " <<
1495 spovnetId.toString() );
1496
1497 logging_debug( "Using bootstrap end-point "
1498 << replyMsg->getBootstrapEndpoint().toString() );
1499
1500 // create overlay structure from spovnet parameter set
1501 // if we have not boostrapped yet against some other node
1502 if( overlayInterface == NULL ){
1503
1504 logging_debug("first-time bootstrapping");
1505
1506 overlayInterface = OverlayFactory::create(
1507 *this, replyMsg->getParam(), nodeId, this );
1508
1509 // overlay structure supported? no-> fail!
1510 if( overlayInterface == NULL ) {
1511 logging_error( "overlay structure not supported" );
1512
1513 if( !bcLink.isUnspecified() ){
1514 bc->dropLink( bcLink );
1515
1516 vector<LinkID>::iterator it = std::find(
1517 bootstrapLinks.begin(), bootstrapLinks.end(), bcLink);
1518 if( it != bootstrapLinks.end() )
1519 bootstrapLinks.erase(it);
1520 }
1521
1522 // inform all registered services of the event
1523 BOOST_FOREACH( NodeListener* i, nodeListeners )
1524 i->onJoinFailed( spovnetId );
1525
1526 delete replyMsg;
1527 return true;
1528 }
1529
1530 // everything ok-> join the overlay!
1531 state = BaseOverlayStateCompleted;
1532 overlayInterface->createOverlay();
1533
1534 overlayInterface->joinOverlay( replyMsg->getBootstrapEndpoint() );
1535 overlayBootstrap.recordJoin( replyMsg->getBootstrapEndpoint() );
1536
1537 // update ovlvis
1538 //ovl.visChangeNodeColor( ovlId, nodeId, OvlVis::NODE_COLORS_GREEN);
1539
1540 // inform all registered services of the event
1541 BOOST_FOREACH( NodeListener* i, nodeListeners )
1542 i->onJoinCompleted( spovnetId );
1543
1544 delete replyMsg;
1545
1546 } else {
1547
1548 // this is not the first bootstrap, just join the additional node
1549 logging_debug("not first-time bootstrapping");
1550 overlayInterface->joinOverlay( replyMsg->getBootstrapEndpoint() );
1551 overlayBootstrap.recordJoin( replyMsg->getBootstrapEndpoint() );
1552
1553 delete replyMsg;
1554
1555 } // if( overlayInterface == NULL )
1556
1557 return true;
1558}
1559
1560
1561bool BaseOverlay::handleData( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1562 // get service
1563 const ServiceID& service = overlayMsg->getService();
1564 logging_debug( "Received data for service " << service.toString()
1565 << " on link " << overlayMsg->getDestinationLink().toString() );
1566
1567 // delegate data message
1568 CommunicationListener* lst = getListener(service);
1569 if(lst != NULL){
1570 lst->onMessage(
1571 overlayMsg,
1572 overlayMsg->getSourceNode(),
1573 overlayMsg->getDestinationLink()
1574 );
1575 }
1576
1577 return true;
1578}
1579
1580
1581bool BaseOverlay::handleLinkUpdate( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1582
1583 if( ld == NULL ) {
1584 logging_warn( "received overlay update message for link for "
1585 << "which we have no mapping" );
1586 return false;
1587 }
1588 logging_info("Received type update message on link " << ld );
1589
1590 // update our link mapping information for this link
1591 bool changed =
1592 ( ld->remoteNode != overlayMsg->getSourceNode() )
1593 || ( ld->service != overlayMsg->getService() );
1594
1595 // set parameters
1596 ld->up = true;
1597 ld->remoteNode = overlayMsg->getSourceNode();
1598 ld->remoteLink = overlayMsg->getSourceLink();
1599 ld->service = overlayMsg->getService();
1600 ld->autolink = overlayMsg->isAutoLink();
1601
1602 // if our link information changed, we send out an update, too
1603 if( changed ) {
1604 overlayMsg->swapRoles();
1605 overlayMsg->setSourceNode(nodeId);
1606 overlayMsg->setSourceLink(ld->overlayId);
1607 overlayMsg->setService(ld->service);
1608 send( overlayMsg, ld );
1609 }
1610
1611 // service registered? no-> error!
1612 if( !communicationListeners.contains( ld->service ) ) {
1613 logging_warn( "Link up: event listener has not been registered" );
1614 return false;
1615 }
1616
1617 // default or no service registered?
1618 CommunicationListener* listener = communicationListeners.get( ld->service );
1619 if( listener == NULL || listener == &CommunicationListener::DEFAULT ) {
1620 logging_warn("Link up: event listener is default or null!" );
1621 return true;
1622 }
1623
1624 // update descriptor
1625 ld->listener = listener;
1626 ld->setAutoUsed();
1627 ld->setAlive();
1628
1629 // ask the service whether it wants to accept this link
1630 if( !listener->onLinkRequest(ld->remoteNode) ) {
1631
1632 logging_debug("Link id=" << ld->overlayId.toString() <<
1633 " has been denied by service " << ld->service.toString() << ", dropping link");
1634
1635 // prevent onLinkDown calls to the service
1636 ld->listener = &CommunicationListener::DEFAULT;
1637
1638 // drop the link
1639 dropLink( ld->overlayId );
1640 return true;
1641 }
1642
1643 // set link up
1644 ld->up = true;
1645 logging_info( "Link has been accepted by service and is up: " << ld );
1646
1647 // auto links: link has been accepted -> send queued messages
1648 if( ld->messageQueue.size() > 0 ) {
1649 logging_info( "Sending out queued messages on link " << ld );
1650 BOOST_FOREACH( Message* msg, ld->messageQueue ) {
1651 sendMessage( msg, ld->overlayId );
1652 delete msg;
1653 }
1654 ld->messageQueue.clear();
1655 }
1656
1657 // call the notification functions
1658 listener->onLinkUp( ld->overlayId, ld->remoteNode );
1659 sideport->onLinkUp( ld->overlayId, nodeId, ld->remoteNode, this->spovnetId );
1660
1661 return true;
1662}
1663
1664/// handle a link request and reply
1665bool BaseOverlay::handleLinkRequest( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1666 logging_info( "Link request received from node id=" << overlayMsg->getSourceNode() );
1667
1668 //TODO: Check if a request has already been sent using getSourceLink() ...
1669
1670 // create link descriptor
1671 LinkDescriptor* ldn = addDescriptor();
1672
1673 // flags
1674 ldn->up = true;
1675 ldn->fromRemote = true;
1676 ldn->relayed = true;
1677
1678 // parameters
1679 ldn->service = overlayMsg->getService();
1680 ldn->listener = getListener(ldn->service);
1681 ldn->remoteNode = overlayMsg->getSourceNode();
1682 ldn->remoteLink = overlayMsg->getSourceLink();
1683
1684 // update time-stamps
1685 ldn->setAlive();
1686 ldn->setAutoUsed();
1687
1688 // create reply message and send back!
1689 overlayMsg->swapRoles(); // swap source/destination
1690 overlayMsg->setType(OverlayMsg::typeLinkReply);
1691 overlayMsg->setSourceLink(ldn->overlayId);
1692 overlayMsg->setSourceEndpoint( bc->getEndpointDescriptor() );
1693 overlayMsg->setRelayed(true);
1694 send( overlayMsg, ld ); // send back to link
1695
1696 // inform listener
1697 if(ldn != NULL && ldn->listener != NULL)
1698 ldn->listener->onLinkUp( ldn->overlayId, ldn->remoteNode );
1699
1700 return true;
1701}
1702
1703bool BaseOverlay::handleLinkReply( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1704
1705 // find link request
1706 LinkDescriptor* ldn = getDescriptor(overlayMsg->getDestinationLink());
1707
1708 // not found? yes-> drop with error!
1709 if (ldn == NULL) {
1710 logging_error( "No link request pending for "
1711 << overlayMsg->getDestinationLink().toString() );
1712 return false;
1713 }
1714 logging_debug("Handling link reply for " << ldn )
1715
1716 // check if already up
1717 if (ldn->up) {
1718 logging_warn( "Link already up: " << ldn );
1719 return true;
1720 }
1721
1722 // debug message
1723 logging_debug( "Link request reply received. Establishing link"
1724 << " for service " << overlayMsg->getService().toString()
1725 << " with local id=" << overlayMsg->getDestinationLink()
1726 << " and remote link id=" << overlayMsg->getSourceLink()
1727 << " to " << overlayMsg->getSourceEndpoint().toString()
1728 );
1729
1730 // set local link descriptor data
1731 ldn->up = true;
1732 ldn->relayed = true;
1733 ldn->service = overlayMsg->getService();
1734 ldn->listener = getListener(ldn->service);
1735 ldn->remoteLink = overlayMsg->getSourceLink();
1736 ldn->remoteNode = overlayMsg->getSourceNode();
1737
1738 // update timestamps
1739 ldn->setAlive();
1740 ldn->setAutoUsed();
1741
1742 // auto links: link has been accepted -> send queued messages
1743 if( ldn->messageQueue.size() > 0 ) {
1744 logging_info( "Sending out queued messages on link " <<
1745 ldn->overlayId.toString() );
1746 BOOST_FOREACH( Message* msg, ldn->messageQueue ) {
1747 sendMessage( msg, ldn->overlayId );
1748 delete msg;
1749 }
1750 ldn->messageQueue.clear();
1751 }
1752
1753 // inform listeners about new link
1754 ldn->listener->onLinkUp( ldn->overlayId, ldn->remoteNode );
1755
1756 // try to replace relay link with direct link
1757 ldn->retryCounter = 3;
1758 ldn->endpoint = overlayMsg->getSourceEndpoint();
1759 ldn->communicationId = bc->establishLink( ldn->endpoint );
1760
1761 return true;
1762}
1763
1764/// handle a keep-alive message for a link
1765bool BaseOverlay::handleLinkAlive( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1766 LinkDescriptor* rld = getDescriptor(overlayMsg->getDestinationLink());
1767 if ( rld != NULL ) {
1768 logging_debug("Keep-Alive for " <<
1769 overlayMsg->getDestinationLink() );
1770 if (overlayMsg->isRouteRecord())
1771 rld->routeRecord = overlayMsg->getRouteRecord();
1772 rld->setAlive();
1773 return true;
1774 } else {
1775 logging_error("Keep-Alive for "
1776 << overlayMsg->getDestinationLink() << ": link unknown." );
1777 return false;
1778 }
1779}
1780
1781/// handle a direct link message
1782bool BaseOverlay::handleLinkDirect( OverlayMsg* overlayMsg, LinkDescriptor* ld ) {
1783 logging_debug( "Received direct link replacement request" );
1784
1785 /// get destination overlay link
1786 LinkDescriptor* rld = getDescriptor( overlayMsg->getDestinationLink() );
1787 if (rld == NULL || ld == NULL) {
1788 logging_error("Direct link replacement: Link "
1789 << overlayMsg->getDestinationLink() << "not found error." );
1790 return false;
1791 }
1792 logging_info( "Received direct link convert notification for " << rld );
1793
1794 // update information
1795 rld->communicationId = ld->communicationId;
1796 rld->communicationUp = true;
1797 rld->relayed = false;
1798
1799 // mark used and alive!
1800 rld->setAlive();
1801 rld->setAutoUsed();
1802
1803 // erase the original descriptor
1804 eraseDescriptor(ld->overlayId);
1805 return true;
1806}
1807
1808/// handles an incoming message
1809bool BaseOverlay::handleMessage( const Message* message, LinkDescriptor* ld,
1810 const LinkID bcLink ) {
1811 logging_debug( "Handling message: " << message->toString());
1812
1813 // decapsulate overlay message
1814 OverlayMsg* overlayMsg =
1815 const_cast<Message*>(message)->decapsulate<OverlayMsg>();
1816 if( overlayMsg == NULL ) return false;
1817
1818 // increase number of hops
1819 overlayMsg->increaseNumHops();
1820
1821 // refresh relay information
1822 refreshRelayInformation( overlayMsg, ld );
1823
1824 // update route record
1825 overlayMsg->addRouteRecord(nodeId);
1826
1827 // handle dht messages (do not route)
1828 if (overlayMsg->isDHTMessage())
1829 return handleDHTMessage(overlayMsg);
1830
1831 // handle signaling messages (do not route!)
1832 if (overlayMsg->getType()>=OverlayMsg::typeSignalingStart &&
1833 overlayMsg->getType()<=OverlayMsg::typeSignalingEnd ) {
1834 overlayInterface->onMessage(overlayMsg, NodeID::UNSPECIFIED, LinkID::UNSPECIFIED);
1835 delete overlayMsg;
1836 return true;
1837 }
1838
1839 // message for reached destination? no-> route message
1840 if (!overlayMsg->getDestinationNode().isUnspecified() &&
1841 overlayMsg->getDestinationNode() != nodeId ) {
1842 logging_debug("Routing message "
1843 << " from " << overlayMsg->getSourceNode()
1844 << " to " << overlayMsg->getDestinationNode()
1845 );
1846 route( overlayMsg );
1847 delete overlayMsg;
1848 return true;
1849 }
1850
1851 // handle DHT response messages
1852 if (overlayMsg->hasTypeMask( OverlayMsg::maskDHTResponse )) {
1853 bool ret = handleDHTMessage(overlayMsg);
1854 delete overlayMsg;
1855 return ret;
1856 }
1857
1858 // handle base overlay message
1859 bool ret = false; // return value
1860 switch ( overlayMsg->getType() ) {
1861
1862 // data transport messages
1863 case OverlayMsg::typeData:
1864 ret = handleData(overlayMsg, ld); break;
1865
1866 // overlay setup messages
1867 case OverlayMsg::typeJoinRequest:
1868 ret = handleJoinRequest(overlayMsg, bcLink ); break;
1869 case OverlayMsg::typeJoinReply:
1870 ret = handleJoinReply(overlayMsg, bcLink ); break;
1871
1872 // link specific messages
1873 case OverlayMsg::typeLinkRequest:
1874 ret = handleLinkRequest(overlayMsg, ld ); break;
1875 case OverlayMsg::typeLinkReply:
1876 ret = handleLinkReply(overlayMsg, ld ); break;
1877 case OverlayMsg::typeLinkUpdate:
1878 ret = handleLinkUpdate(overlayMsg, ld ); break;
1879 case OverlayMsg::typeLinkAlive:
1880 ret = handleLinkAlive(overlayMsg, ld ); break;
1881 case OverlayMsg::typeLinkDirect:
1882 ret = handleLinkDirect(overlayMsg, ld ); break;
1883
1884 // handle unknown message type
1885 default: {
1886 logging_error( "received message in invalid state! don't know " <<
1887 "what to do with this message of type " << overlayMsg->getType() );
1888 ret = false;
1889 break;
1890 }
1891 }
1892
1893 // free overlay message and return value
1894 delete overlayMsg;
1895 return ret;
1896}
1897
1898// ----------------------------------------------------------------------------
1899
1900void BaseOverlay::broadcastMessage(Message* message, const ServiceID& service) {
1901
1902 logging_debug( "broadcasting message to all known nodes " <<
1903 "in the overlay from service " + service.toString() );
1904
1905 OverlayInterface::NodeList nodes = overlayInterface->getKnownNodes(true);
1906 OverlayInterface::NodeList::iterator i = nodes.begin();
1907 for(; i != nodes.end(); i++ ) {
1908 if( *i == nodeId) continue; // don't send to ourselfs
1909 sendMessage( message, *i, service );
1910 }
1911}
1912
1913/// return the overlay neighbors
1914vector<NodeID> BaseOverlay::getOverlayNeighbors(bool deep) const {
1915 // the known nodes _can_ also include our node, so we remove ourself
1916 vector<NodeID> nodes = overlayInterface->getKnownNodes(deep);
1917 vector<NodeID>::iterator i = find( nodes.begin(), nodes.end(), this->nodeId );
1918 if( i != nodes.end() ) nodes.erase( i );
1919 return nodes;
1920}
1921
1922const NodeID& BaseOverlay::getNodeID(const LinkID& lid) const {
1923 if( lid == LinkID::UNSPECIFIED ) return nodeId;
1924 const LinkDescriptor* ld = getDescriptor(lid);
1925 if( ld == NULL ) return NodeID::UNSPECIFIED;
1926 else return ld->remoteNode;
1927}
1928
1929vector<LinkID> BaseOverlay::getLinkIDs( const NodeID& nid ) const {
1930 vector<LinkID> linkvector;
1931 BOOST_FOREACH( LinkDescriptor* ld, links ) {
1932 if( ld->remoteNode == nid || nid == NodeID::UNSPECIFIED ) {
1933 linkvector.push_back( ld->overlayId );
1934 }
1935 }
1936 return linkvector;
1937}
1938
1939
1940void BaseOverlay::onNodeJoin(const NodeID& node) {
1941 JoiningNodes::iterator i = std::find( joiningNodes.begin(), joiningNodes.end(), node );
1942 if( i == joiningNodes.end() ) return;
1943
1944 logging_info( "node has successfully joined baseoverlay and overlay structure "
1945 << node.toString() );
1946
1947 joiningNodes.erase( i );
1948}
1949
1950void BaseOverlay::eventFunction() {
1951 stabilizeRelays();
1952 stabilizeLinks();
1953 stabilizeDHT();
1954 updateVisual();
1955}
1956
1957void BaseOverlay::updateVisual(){
1958
1959 //
1960 // update base overlay structure
1961 //
1962
1963 static NodeID pre = NodeID::UNSPECIFIED;
1964 static NodeID suc = NodeID::UNSPECIFIED;
1965
1966 vector<NodeID> nodes = this->getOverlayNeighbors(false);
1967
1968 if(nodes.size() == 0){
1969
1970 if(pre != NodeID::UNSPECIFIED){
1971 visual.visDisconnect(visualIdOverlay, this->nodeId, pre, "");
1972 pre = NodeID::UNSPECIFIED;
1973 }
1974 if(suc != NodeID::UNSPECIFIED){
1975 visual.visDisconnect(visualIdOverlay, this->nodeId, suc, "");
1976 suc = NodeID::UNSPECIFIED;
1977 }
1978
1979 } // if(nodes.size() == 0)
1980
1981 if(nodes.size() == 1){
1982 // only one node, make this pre and succ
1983 // and then go into the node.size()==2 case
1984 //nodes.push_back(nodes.at(0));
1985
1986 if(pre != nodes.at(0)){
1987 pre = nodes.at(0);
1988 if(pre != NodeID::UNSPECIFIED)
1989 visual.visConnect(visualIdOverlay, this->nodeId, pre, "");
1990 }
1991 }
1992
1993 if(nodes.size() == 2){
1994
1995 // old finger
1996 if(nodes.at(0) != pre){
1997 if(pre != NodeID::UNSPECIFIED)
1998 visual.visDisconnect(visualIdOverlay, this->nodeId, pre, "");
1999 pre = NodeID::UNSPECIFIED;
2000 }
2001 if(nodes.at(1) != suc){
2002 if(suc != NodeID::UNSPECIFIED)
2003 visual.visDisconnect(visualIdOverlay, this->nodeId, suc, "");
2004 suc = NodeID::UNSPECIFIED;
2005 }
2006
2007 // connect with fingers
2008 if(pre == NodeID::UNSPECIFIED){
2009 pre = nodes.at(0);
2010 if(pre != NodeID::UNSPECIFIED)
2011 visual.visConnect(visualIdOverlay, this->nodeId, pre, "");
2012 }
2013 if(suc == NodeID::UNSPECIFIED){
2014 suc = nodes.at(1);
2015 if(suc != NodeID::UNSPECIFIED)
2016 visual.visConnect(visualIdOverlay, this->nodeId, suc, "");
2017 }
2018
2019 } //if(nodes.size() == 2)
2020
2021// {
2022// logging_error("================================");
2023// logging_error("my nodeid " << nodeId.get(MAX_KEYLENGTH-16, 16));
2024// logging_error("================================");
2025// if(nodes.size()>= 1){
2026// logging_error("real pre " << nodes.at(0).toString());
2027// logging_error("real pre " << nodes.at(0).get(MAX_KEYLENGTH-16, 16));
2028// }
2029// if(nodes.size()>= 2){
2030// logging_error("real suc " << nodes.at(1).toString());
2031// logging_error("real suc " << nodes.at(1).get(MAX_KEYLENGTH-16, 16));
2032// }
2033// logging_error("================================");
2034// if(pre == NodeID::UNSPECIFIED){
2035// logging_error("pre: unspecified");
2036// }else{
2037// unsigned int prei = pre.get(MAX_KEYLENGTH-16, 16);
2038// logging_error("pre: " << prei);
2039// }
2040// if(suc == NodeID::UNSPECIFIED){
2041// logging_error("suc: unspecified");
2042// }else{
2043// unsigned int suci = suc.get(MAX_KEYLENGTH-16, 16);
2044// logging_error("suc: " << suci);
2045// }
2046// logging_error("================================");
2047// }
2048
2049 //
2050 // update base communication links
2051 //
2052
2053 static set<NodeID> linkset;
2054 set<NodeID> remotenodes;
2055 BOOST_FOREACH( LinkDescriptor* ld, links ) {
2056 if (!ld->isVital() || ld->service != OverlayInterface::OVERLAY_SERVICE_ID)
2057 continue;
2058
2059 if (ld->routeRecord.size()>1 && ld->relayed) {
2060 for (size_t i=1; i<ld->routeRecord.size(); i++)
2061 remotenodes.insert( ld->routeRecord[ld->routeRecord.size()-i-1] );
2062 } else {
2063 remotenodes.insert(ld->remoteNode);
2064 }
2065 }
2066
2067 // which links are old and need deletion?
2068 bool changed = false;
2069
2070 do{
2071 changed = false;
2072 BOOST_FOREACH(NodeID n, linkset){
2073 if(remotenodes.find(n) == remotenodes.end()){
2074 visual.visDisconnect(visualIdBase, this->nodeId, n, "");
2075 linkset.erase(n);
2076 changed = true;
2077 break;
2078 }
2079 }
2080 }while(changed);
2081
2082 // which links are new and need creation?
2083 do{
2084 changed = false;
2085 BOOST_FOREACH(NodeID n, remotenodes){
2086 if(linkset.find(n) == linkset.end()){
2087 visual.visConnect(visualIdBase, this->nodeId, n, "");
2088 linkset.insert(n);
2089 changed = true;
2090 break;
2091 }
2092 }
2093 }while(changed);
2094
2095}
2096
2097// ----------------------------------------------------------------------------
2098
2099void BaseOverlay::initDHT() {
2100 dht = new DHT();
2101 localDHT = new DHT();
2102 republishCounter = 0;
2103}
2104
2105void BaseOverlay::destroyDHT() {
2106 delete dht;
2107 delete localDHT;
2108}
2109
2110/// stabilize DHT state
2111void BaseOverlay::stabilizeDHT() {
2112
2113 // do refresh every 2 seconds
2114 if (republishCounter < 2) {
2115 republishCounter++;
2116 return;
2117 }
2118 republishCounter = 0;
2119
2120 // remove old values from DHT
2121 BOOST_FOREACH( DHTEntry& entry, dht->entries ) {
2122 // erase old entries
2123 entry.erase_expired_entries();
2124 }
2125
2126 // re-publish values-> do not refresh locally stored values
2127 BOOST_FOREACH( DHTEntry& entry, localDHT->entries ) {
2128 BOOST_FOREACH( ValueEntry& value, entry.values )
2129 dhtPut(entry.key, value.get_value(), value.get_ttl(), false, true );
2130 }
2131}
2132
2133// handle DHT messages
2134bool BaseOverlay::handleDHTMessage( OverlayMsg* msg ) {
2135
2136 // de-capsulate message
2137 logging_debug("Received DHT message");
2138 DHTMessage* dhtMsg = msg->decapsulate<DHTMessage>();
2139
2140 // handle DHT data message
2141 if (msg->getType()==OverlayMsg::typeDHTData) {
2142 const ServiceID& service = msg->getService();
2143 logging_info( "Received DHT data for service " << service.toString() );
2144
2145 // delegate data message
2146 CommunicationListener* lst = getListener(service);
2147 if(lst != NULL) lst->onKeyValue(dhtMsg->getKey(), dhtMsg->getValues() );
2148 return true;
2149 }
2150
2151 // route message to closest node
2152 if (!overlayInterface->isClosestNodeTo(msg->getDestinationNode())) {
2153 logging_debug("Routing DHT message to closest node "
2154 << " from " << msg->getSourceNode()
2155 << " to " << msg->getDestinationNode()
2156 );
2157 route( msg );
2158 delete msg;
2159 return true;
2160 }
2161
2162 // now, we are the closest node...
2163 switch (msg->getType()) {
2164
2165 // ----------------------------------------------------------------- put ---
2166 case OverlayMsg::typeDHTPut: {
2167 logging_debug("DHT-Put: Attempt to store values for key "
2168 << dhtMsg->getKey());
2169 if (dhtMsg->doReplace()) {
2170 logging_debug("DHT-Put: Attempt to replace key: remove old values first!");
2171 dht->remove(dhtMsg->getKey());
2172 }
2173 BOOST_FOREACH( Data value, dhtMsg->getValues() ) {
2174 logging_debug("DHT-Put: Stored value: " << value );
2175 dht->put(dhtMsg->getKey(), value, dhtMsg->getTTL() );
2176 }
2177 break;
2178 }
2179
2180 // ----------------------------------------------------------------- get ---
2181 case OverlayMsg::typeDHTGet: {
2182 logging_info("DHT-Get: key=" << dhtMsg->getKey() );
2183 vector<Data> vect = dht->get(dhtMsg->getKey());
2184 BOOST_FOREACH(const Data& d, vect)
2185 logging_info("DHT-Get: value=" << d);
2186 OverlayMsg omsg(*msg);
2187 omsg.swapRoles();
2188 omsg.setType(OverlayMsg::typeDHTData);
2189 DHTMessage dhtmsg(dhtMsg->getKey(), vect);
2190 omsg.encapsulate(&dhtmsg);
2191 dhtSend(&omsg, omsg.getDestinationNode());
2192 break;
2193 }
2194
2195 // -------------------------------------------------------------- remove ---
2196 case OverlayMsg::typeDHTRemove: {
2197 if (dhtMsg->hasValues()) {
2198 BOOST_FOREACH( Data value, dhtMsg->getValues() )
2199 dht->remove(dhtMsg->getKey(), value );
2200 } else
2201 dht->remove( dhtMsg->getKey() );
2202 break;
2203 }
2204
2205 // -------------------------------------------------------------- default---
2206 default:
2207 logging_error("DHT Message type unknown.");
2208 return false;
2209 }
2210 delete msg;
2211 return true;
2212}
2213
2214/// put a value to the DHT with a ttl given in seconds
2215void BaseOverlay::dhtPut( const Data& key, const Data& value, int ttl, bool replace, bool no_local_refresh ) {
2216
2217 // log
2218 logging_info("DHT-Put:"
2219 << " key=" << key << " value=" << value
2220 << " ttl=" << ttl << " replace=" << replace
2221 );
2222
2223 if (!no_local_refresh) {
2224
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 // log: remove key
2259 logging_info("DHT-Remove: Removing key=" << key );
2260
2261 // calculate hash
2262 NodeID dest = NodeID::sha1(key.getBuffer(), key.getLength() / 8);
2263 DHTMessage dhtmsg(key);
2264
2265 // send message
2266 OverlayMsg msg(OverlayMsg::typeDHTRemove);
2267 msg.encapsulate( &dhtmsg );
2268 dhtSend(&msg, dest);
2269}
2270
2271/// requests data stored using key
2272void BaseOverlay::dhtGet( const Data& key, const ServiceID& service ) {
2273 // log: remove get
2274 logging_info("DHT-Get: Trying to resolve key=" <<
2275 key << " for service=" << service.toString() );
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::typeDHTGet);
2283 msg.setService(service);
2284 msg.encapsulate( &dhtmsg );
2285 dhtSend(&msg, dest);
2286}
2287
2288void BaseOverlay::dhtSend( OverlayMsg* msg, const NodeID& dest ) {
2289 // log: dht send
2290 logging_info("DHT-Send: Sending message with key=" << dest.toString() );
2291
2292 /// set source and destination
2293 msg->setSourceNode(this->nodeId);
2294 msg->setDestinationNode(dest);
2295
2296 // local storage? yes-> put into DHT directly
2297 if (overlayInterface->isClosestNodeTo(msg->getDestinationNode())) {
2298 Data d = data_serialize(msg);
2299 Message* m2 = new Message(d);
2300 OverlayMsg* m3 = m2->decapsulate<OverlayMsg>();
2301 handleDHTMessage(m3);
2302 delete m2;
2303 return;
2304 }
2305
2306 // send message "normally"
2307 send( msg, dest );
2308}
2309
2310std::string BaseOverlay::debugInformation() {
2311 std::stringstream s;
2312 int i=0;
2313
2314 // dump overlay information
2315 s << "Long debug info ... [see below]" << endl << endl;
2316 s << "--- overlay information ----------------------" << endl;
2317 s << overlayInterface->debugInformation() << endl;
2318
2319 // dump link state
2320 s << "--- link state -------------------------------" << endl;
2321 BOOST_FOREACH( LinkDescriptor* ld, links ) {
2322 s << "link " << i << ": " << ld << endl;
2323 i++;
2324 }
2325 s << endl << endl;
2326
2327 return s.str();
2328}
2329
2330}} // namespace ariba, overlay
Note: See TracBrowser for help on using the repository browser.