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

Last change on this file since 10575 was 10575, checked in by Michael Tänzer, 12 years ago

When routing do not reset source NodeID

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