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

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