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

Last change on this file since 7533 was 7532, checked in by Christoph Mayer, 15 years ago

-von außen konfigurierbare bootstrap module, -periodicbroadcast crash fix

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