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

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