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

Last change on this file since 6796 was 6796, checked in by mies, 14 years ago

DHTTest working with 2 nodes

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