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

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

Last change on this file since 9982 was 9971, checked in by Christoph Mayer, 13 years ago
File size: 66.9 KB
RevLine 
1// [License]
2// The Ariba-Underlay Copyright
3//
4// Copyright (c) 2008-2009, Institute of Telematics, UniversitÀt Karlsruhe (TH)
5//
6// Institute of Telematics
7// UniversitÀt Karlsruhe (TH)
8// Zirkel 2, 76128 Karlsruhe
9// Germany
10//
11// Redistribution and use in source and binary forms, with or without
12// modification, are permitted provided that the following conditions are
13// met:
14//
15// 1. Redistributions of source code must retain the above copyright
16// notice, this list of conditions and the following disclaimer.
17// 2. Redistributions in binary form must reproduce the above copyright
18// notice, this list of conditions and the following disclaimer in the
19// documentation and/or other materials provided with the distribution.
20//
21// THIS SOFTWARE IS PROVIDED BY THE INSTITUTE OF TELEMATICS ``AS IS'' AND
22// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ARIBA PROJECT OR
25// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32//
33// The views and conclusions contained in the software and documentation
34// are those of the authors and should not be interpreted as representing
35// official policies, either expressed or implied, of the Institute of
36// Telematics.
37// [License]
38
39#include "BaseOverlay.h"
40
41#include <sstream>
42#include <iostream>
43#include <string>
44#include <boost/foreach.hpp>
45
46#include "ariba/NodeListener.h"
47#include "ariba/CommunicationListener.h"
48#include "ariba/SideportListener.h"
49
50#include "ariba/overlay/LinkDescriptor.h"
51
52#include "ariba/overlay/messages/OverlayMsg.h"
53#include "ariba/overlay/messages/DHTMessage.h"
54#include "ariba/overlay/messages/JoinRequest.h"
55#include "ariba/overlay/messages/JoinReply.h"
56
57#include "ariba/utility/visual/OvlVis.h"
58#include "ariba/utility/visual/DddVis.h"
59#include "ariba/utility/visual/ServerVis.h"
60
61namespace ariba {
62namespace overlay {
63
64#define visualInstance ariba::utility::DddVis::instance()
65#define visualIdOverlay ariba::utility::ServerVis::NETWORK_ID_BASE_OVERLAY
66#define visualIdBase ariba::utility::ServerVis::NETWORK_ID_BASE_COMMUNICATION
67
68class ValueEntry {
69public:
70 ValueEntry( const Data& value ) : ttl(0), last_update(time(NULL)),
71 last_change(time(NULL)), value(value.clone()) {
72 }
73
74 ValueEntry( const ValueEntry& value ) :
75 ttl(value.ttl), last_update(value.last_update),
76 last_change(value.last_change), value(value.value.clone()) {
77 }
78
79 ~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 return handleDHTMessage(overlayMsg);
1836
1837 // handle signaling messages (do not route!)
1838 if (overlayMsg->getType()>=OverlayMsg::typeSignalingStart &&
1839 overlayMsg->getType()<=OverlayMsg::typeSignalingEnd ) {
1840 overlayInterface->onMessage(overlayMsg, NodeID::UNSPECIFIED, LinkID::UNSPECIFIED);
1841 delete overlayMsg;
1842 return true;
1843 }
1844
1845 // message for reached destination? no-> route message
1846 if (!overlayMsg->getDestinationNode().isUnspecified() &&
1847 overlayMsg->getDestinationNode() != nodeId ) {
1848 logging_debug("Routing message "
1849 << " from " << overlayMsg->getSourceNode()
1850 << " to " << overlayMsg->getDestinationNode()
1851 );
1852 route( overlayMsg );
1853 delete overlayMsg;
1854 return true;
1855 }
1856
1857 // handle DHT response messages
1858 if (overlayMsg->hasTypeMask( OverlayMsg::maskDHTResponse )) {
1859 bool ret = handleDHTMessage(overlayMsg);
1860 delete overlayMsg;
1861 return ret;
1862 }
1863
1864 // handle base overlay message
1865 bool ret = false; // return value
1866 switch ( overlayMsg->getType() ) {
1867
1868 // data transport messages
1869 case OverlayMsg::typeData:
1870 ret = handleData(overlayMsg, ld); break;
1871
1872 // overlay setup messages
1873 case OverlayMsg::typeJoinRequest:
1874 ret = handleJoinRequest(overlayMsg, bcLink ); break;
1875 case OverlayMsg::typeJoinReply:
1876 ret = handleJoinReply(overlayMsg, bcLink ); break;
1877
1878 // link specific messages
1879 case OverlayMsg::typeLinkRequest:
1880 ret = handleLinkRequest(overlayMsg, ld ); break;
1881 case OverlayMsg::typeLinkReply:
1882 ret = handleLinkReply(overlayMsg, ld ); break;
1883 case OverlayMsg::typeLinkUpdate:
1884 ret = handleLinkUpdate(overlayMsg, ld ); break;
1885 case OverlayMsg::typeLinkAlive:
1886 ret = handleLinkAlive(overlayMsg, ld ); break;
1887 case OverlayMsg::typeLinkDirect:
1888 ret = handleLinkDirect(overlayMsg, ld ); break;
1889
1890 // handle unknown message type
1891 default: {
1892 logging_error( "received message in invalid state! don't know " <<
1893 "what to do with this message of type " << overlayMsg->getType() );
1894 ret = false;
1895 break;
1896 }
1897 }
1898
1899 // free overlay message and return value
1900 delete overlayMsg;
1901 return ret;
1902}
1903
1904// ----------------------------------------------------------------------------
1905
1906void BaseOverlay::broadcastMessage(Message* message, const ServiceID& service) {
1907
1908 logging_debug( "broadcasting message to all known nodes " <<
1909 "in the overlay from service " + service.toString() );
1910
1911 if(message == NULL) return;
1912 message->setReleasePayload(false);
1913
1914 OverlayInterface::NodeList nodes = overlayInterface->getKnownNodes(true);
1915 for(size_t i=0; i<nodes.size(); i++){
1916 NodeID& id = nodes.at(i);
1917 if(id == this->nodeId) continue; // don't send to ourselfs
1918 if(i+1 == nodes.size()) message->setReleasePayload(true); // release payload on last send
1919 sendMessage( message, id, service );
1920 }
1921}
1922
1923/// return the overlay neighbors
1924vector<NodeID> BaseOverlay::getOverlayNeighbors(bool deep) const {
1925 // the known nodes _can_ also include our node, so we remove ourself
1926 vector<NodeID> nodes = overlayInterface->getKnownNodes(deep);
1927 vector<NodeID>::iterator i = find( nodes.begin(), nodes.end(), this->nodeId );
1928 if( i != nodes.end() ) nodes.erase( i );
1929 return nodes;
1930}
1931
1932const NodeID& BaseOverlay::getNodeID(const LinkID& lid) const {
1933 if( lid == LinkID::UNSPECIFIED ) return nodeId;
1934 const LinkDescriptor* ld = getDescriptor(lid);
1935 if( ld == NULL ) return NodeID::UNSPECIFIED;
1936 else return ld->remoteNode;
1937}
1938
1939vector<LinkID> BaseOverlay::getLinkIDs( const NodeID& nid ) const {
1940 vector<LinkID> linkvector;
1941 BOOST_FOREACH( LinkDescriptor* ld, links ) {
1942 if( ld->remoteNode == nid || nid == NodeID::UNSPECIFIED ) {
1943 linkvector.push_back( ld->overlayId );
1944 }
1945 }
1946 return linkvector;
1947}
1948
1949
1950void BaseOverlay::onNodeJoin(const NodeID& node) {
1951 JoiningNodes::iterator i = std::find( joiningNodes.begin(), joiningNodes.end(), node );
1952 if( i == joiningNodes.end() ) return;
1953
1954 logging_info( "node has successfully joined baseoverlay and overlay structure "
1955 << node.toString() );
1956
1957 joiningNodes.erase( i );
1958}
1959
1960void BaseOverlay::eventFunction() {
1961 stabilizeRelays();
1962 stabilizeLinks();
1963 stabilizeDHT();
1964 updateVisual();
1965}
1966
1967void BaseOverlay::updateVisual(){
1968
1969 //
1970 // update base overlay structure
1971 //
1972
1973 static NodeID pre = NodeID::UNSPECIFIED;
1974 static NodeID suc = NodeID::UNSPECIFIED;
1975
1976 vector<NodeID> nodes = this->getOverlayNeighbors(false);
1977
1978 if(nodes.size() == 0){
1979
1980 if(pre != NodeID::UNSPECIFIED){
1981 visualInstance.visDisconnect(visualIdOverlay, this->nodeId, pre, "");
1982 pre = NodeID::UNSPECIFIED;
1983 }
1984 if(suc != NodeID::UNSPECIFIED){
1985 visualInstance.visDisconnect(visualIdOverlay, this->nodeId, suc, "");
1986 suc = NodeID::UNSPECIFIED;
1987 }
1988
1989 } // if(nodes.size() == 0)
1990
1991 if(nodes.size() == 1){
1992 // only one node, make this pre and succ
1993 // and then go into the node.size()==2 case
1994 //nodes.push_back(nodes.at(0));
1995
1996 if(pre != nodes.at(0)){
1997 pre = nodes.at(0);
1998 if(pre != NodeID::UNSPECIFIED)
1999 visualInstance.visConnect(visualIdOverlay, this->nodeId, pre, "");
2000 }
2001 }
2002
2003 if(nodes.size() == 2){
2004
2005 // old finger
2006 if(nodes.at(0) != pre){
2007 if(pre != NodeID::UNSPECIFIED)
2008 visualInstance.visDisconnect(visualIdOverlay, this->nodeId, pre, "");
2009 pre = NodeID::UNSPECIFIED;
2010 }
2011 if(nodes.at(1) != suc){
2012 if(suc != NodeID::UNSPECIFIED)
2013 visualInstance.visDisconnect(visualIdOverlay, this->nodeId, suc, "");
2014 suc = NodeID::UNSPECIFIED;
2015 }
2016
2017 // connect with fingers
2018 if(pre == NodeID::UNSPECIFIED){
2019 pre = nodes.at(0);
2020 if(pre != NodeID::UNSPECIFIED)
2021 visualInstance.visConnect(visualIdOverlay, this->nodeId, pre, "");
2022 }
2023 if(suc == NodeID::UNSPECIFIED){
2024 suc = nodes.at(1);
2025 if(suc != NodeID::UNSPECIFIED)
2026 visualInstance.visConnect(visualIdOverlay, this->nodeId, suc, "");
2027 }
2028
2029 } //if(nodes.size() == 2)
2030
2031// {
2032// logging_error("================================");
2033// logging_error("my nodeid " << nodeId.get(MAX_KEYLENGTH-16, 16));
2034// logging_error("================================");
2035// if(nodes.size()>= 1){
2036// logging_error("real pre " << nodes.at(0).toString());
2037// logging_error("real pre " << nodes.at(0).get(MAX_KEYLENGTH-16, 16));
2038// }
2039// if(nodes.size()>= 2){
2040// logging_error("real suc " << nodes.at(1).toString());
2041// logging_error("real suc " << nodes.at(1).get(MAX_KEYLENGTH-16, 16));
2042// }
2043// logging_error("================================");
2044// if(pre == NodeID::UNSPECIFIED){
2045// logging_error("pre: unspecified");
2046// }else{
2047// unsigned int prei = pre.get(MAX_KEYLENGTH-16, 16);
2048// logging_error("pre: " << prei);
2049// }
2050// if(suc == NodeID::UNSPECIFIED){
2051// logging_error("suc: unspecified");
2052// }else{
2053// unsigned int suci = suc.get(MAX_KEYLENGTH-16, 16);
2054// logging_error("suc: " << suci);
2055// }
2056// logging_error("================================");
2057// }
2058
2059 //
2060 // update base communication links
2061 //
2062
2063 static set<NodeID> linkset;
2064 set<NodeID> remotenodes;
2065 BOOST_FOREACH( LinkDescriptor* ld, links ) {
2066 if (!ld->isVital() || ld->service != OverlayInterface::OVERLAY_SERVICE_ID)
2067 continue;
2068
2069 if (ld->routeRecord.size()>1 && ld->relayed) {
2070 for (size_t i=1; i<ld->routeRecord.size(); i++)
2071 remotenodes.insert( ld->routeRecord[ld->routeRecord.size()-i-1] );
2072 } else {
2073 remotenodes.insert(ld->remoteNode);
2074 }
2075 }
2076
2077 // which links are old and need deletion?
2078 bool changed = false;
2079
2080 do{
2081 changed = false;
2082 BOOST_FOREACH(NodeID n, linkset){
2083 if(remotenodes.find(n) == remotenodes.end()){
2084 visualInstance.visDisconnect(visualIdBase, this->nodeId, n, "");
2085 linkset.erase(n);
2086 changed = true;
2087 break;
2088 }
2089 }
2090 }while(changed);
2091
2092 // which links are new and need creation?
2093 do{
2094 changed = false;
2095 BOOST_FOREACH(NodeID n, remotenodes){
2096 if(linkset.find(n) == linkset.end()){
2097 visualInstance.visConnect(visualIdBase, this->nodeId, n, "");
2098 linkset.insert(n);
2099 changed = true;
2100 break;
2101 }
2102 }
2103 }while(changed);
2104
2105}
2106
2107// ----------------------------------------------------------------------------
2108
2109void BaseOverlay::initDHT() {
2110 dht = new DHT();
2111 localDHT = new DHT();
2112 republishCounter = 0;
2113}
2114
2115void BaseOverlay::destroyDHT() {
2116 delete dht;
2117 delete localDHT;
2118}
2119
2120/// stabilize DHT state
2121void BaseOverlay::stabilizeDHT() {
2122
2123 // do refresh every 2 seconds
2124 if (republishCounter < 2) {
2125 republishCounter++;
2126 return;
2127 }
2128 republishCounter = 0;
2129
2130 // remove old values from DHT
2131 BOOST_FOREACH( DHTEntry& entry, dht->entries ) {
2132 // erase old entries
2133 entry.erase_expired_entries();
2134 }
2135
2136 // re-publish values-> do not refresh locally stored values
2137 BOOST_FOREACH( DHTEntry& entry, localDHT->entries ) {
2138 BOOST_FOREACH( ValueEntry& value, entry.values )
2139 dhtPut(entry.key, value.get_value(), value.get_ttl(), false, true );
2140 }
2141}
2142
2143// handle DHT messages
2144bool BaseOverlay::handleDHTMessage( OverlayMsg* msg ) {
2145
2146 // de-capsulate message
2147 logging_debug("Received DHT message");
2148 DHTMessage* dhtMsg = msg->decapsulate<DHTMessage>();
2149
2150 // handle DHT data message
2151 if (msg->getType()==OverlayMsg::typeDHTData) {
2152 const ServiceID& service = msg->getService();
2153 logging_info( "Received DHT data for service " << service.toString() );
2154
2155 // delegate data message
2156 CommunicationListener* lst = getListener(service);
2157 if(lst != NULL) lst->onKeyValue(dhtMsg->getKey(), dhtMsg->getValues() );
2158 delete dhtMsg;
2159 return true;
2160 }
2161
2162 // route message to closest node
2163 if (!overlayInterface->isClosestNodeTo(msg->getDestinationNode())) {
2164 logging_debug("Routing DHT message to closest node "
2165 << " from " << msg->getSourceNode()
2166 << " to " << msg->getDestinationNode()
2167 );
2168 route( msg );
2169 delete msg;
2170 return true;
2171 }
2172
2173 // now, we are the closest node...
2174 switch (msg->getType()) {
2175
2176 // ----------------------------------------------------------------- put ---
2177 case OverlayMsg::typeDHTPut: {
2178 logging_debug("DHT-Put: Attempt to store values for key "
2179 << dhtMsg->getKey());
2180 if (dhtMsg->doReplace()) {
2181 logging_debug("DHT-Put: Attempt to replace key: remove old values first!");
2182 dht->remove(dhtMsg->getKey());
2183 }
2184 BOOST_FOREACH( Data value, dhtMsg->getValues() ) {
2185 logging_debug("DHT-Put: Stored value: " << value );
2186 dht->put(dhtMsg->getKey(), value, dhtMsg->getTTL() );
2187 }
2188 break;
2189 }
2190
2191 // ----------------------------------------------------------------- get ---
2192 case OverlayMsg::typeDHTGet: {
2193 logging_info("DHT-Get: key=" << dhtMsg->getKey() );
2194 vector<Data> vect = dht->get(dhtMsg->getKey());
2195 BOOST_FOREACH(const Data& d, vect)
2196 logging_info("DHT-Get: value=" << d);
2197 OverlayMsg omsg(*msg);
2198 omsg.swapRoles();
2199 omsg.setType(OverlayMsg::typeDHTData);
2200 DHTMessage dhtmsg(dhtMsg->getKey(), vect);
2201 omsg.encapsulate(&dhtmsg);
2202 dhtSend(&omsg, omsg.getDestinationNode());
2203 break;
2204 }
2205
2206 // -------------------------------------------------------------- remove ---
2207 case OverlayMsg::typeDHTRemove: {
2208 if (dhtMsg->hasValues()) {
2209 BOOST_FOREACH( Data value, dhtMsg->getValues() )
2210 dht->remove(dhtMsg->getKey(), value );
2211 } else
2212 dht->remove( dhtMsg->getKey() );
2213 break;
2214 }
2215
2216 // -------------------------------------------------------------- default---
2217 default:
2218 logging_error("DHT Message type unknown.");
2219 return false;
2220 }
2221 delete msg;
2222 return true;
2223}
2224
2225/// put a value to the DHT with a ttl given in seconds
2226void BaseOverlay::dhtPut( const Data& key, const Data& value, int ttl, bool replace, bool no_local_refresh ) {
2227
2228 // log
2229 logging_info("DHT-Put:"
2230 << " key=" << key << " value=" << value
2231 << " ttl=" << ttl << " replace=" << replace
2232 );
2233
2234 if (!no_local_refresh) {
2235
2236 // put into local data store (for refreshes)
2237 if (replace) localDHT->remove(key);
2238 localDHT->put(key, value, ttl);
2239 }
2240
2241 // calculate hash
2242 NodeID dest = NodeID::sha1(key.getBuffer(), key.getLength() / 8);
2243 DHTMessage dhtmsg( key, value );
2244 dhtmsg.setReplace( replace );
2245 dhtmsg.setTTL(ttl);
2246
2247 OverlayMsg msg( OverlayMsg::typeDHTPut );
2248 msg.encapsulate( &dhtmsg );
2249 dhtSend(&msg, dest);
2250}
2251
2252/// removes a key value pair from the DHT
2253void BaseOverlay::dhtRemove( const Data& key, const Data& value ) {
2254 // remove from local data store
2255 localDHT->remove(key,value);
2256
2257 // calculate hash
2258 NodeID dest = NodeID::sha1(key.getBuffer(), key.getLength() / 8);
2259 DHTMessage dhtmsg(key,value);
2260
2261 // send message
2262 OverlayMsg msg(OverlayMsg::typeDHTRemove);
2263 msg.encapsulate( &dhtmsg );
2264 dhtSend(&msg, dest);
2265}
2266
2267/// removes all data stored at the given key
2268void BaseOverlay::dhtRemove( const Data& key ) {
2269 // log: remove key
2270 logging_info("DHT-Remove: Removing key=" << key );
2271
2272 // calculate hash
2273 NodeID dest = NodeID::sha1(key.getBuffer(), key.getLength() / 8);
2274 DHTMessage dhtmsg(key);
2275
2276 // send message
2277 OverlayMsg msg(OverlayMsg::typeDHTRemove);
2278 msg.encapsulate( &dhtmsg );
2279 dhtSend(&msg, dest);
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 // calculate hash
2289 NodeID dest = NodeID::sha1(key.getBuffer(), key.getLength() / 8);
2290 DHTMessage dhtmsg(key);
2291
2292 // send message
2293 OverlayMsg msg(OverlayMsg::typeDHTGet);
2294 msg.setService(service);
2295 msg.encapsulate( &dhtmsg );
2296 dhtSend(&msg, dest);
2297}
2298
2299void BaseOverlay::dhtSend( OverlayMsg* msg, const NodeID& dest ) {
2300 // log: dht send
2301 logging_info("DHT-Send: Sending message with key=" << dest.toString() );
2302
2303 /// set source and destination
2304 msg->setSourceNode(this->nodeId);
2305 msg->setDestinationNode(dest);
2306
2307 // local storage? yes-> put into DHT directly
2308 if (overlayInterface->isClosestNodeTo(msg->getDestinationNode())) {
2309 Data d = data_serialize(msg);
2310 Message* m2 = new Message(d);
2311 OverlayMsg* m3 = m2->decapsulate<OverlayMsg>();
2312 handleDHTMessage(m3);
2313 delete m2;
2314 return;
2315 }
2316
2317 // send message "normally"
2318 send( msg, dest );
2319}
2320
2321std::string BaseOverlay::debugInformation() {
2322 std::stringstream s;
2323 int i=0;
2324
2325 // dump overlay information
2326 s << "Long debug info ... [see below]" << endl << endl;
2327 s << "--- overlay information ----------------------" << endl;
2328 s << overlayInterface->debugInformation() << endl;
2329
2330 // dump link state
2331 s << "--- link state -------------------------------" << endl;
2332 BOOST_FOREACH( LinkDescriptor* ld, links ) {
2333 s << "link " << i << ": " << ld << endl;
2334 i++;
2335 }
2336 s << endl << endl;
2337
2338 return s.str();
2339}
2340
2341}} // namespace ariba, overlay
Note: See TracBrowser for help on using the repository browser.