Statistics
| Branch: | Revision:

streamers / topology.c @ 45733714

History | View | Annotate | Download (25.1 KB)

1
/*
2
 *  Copyright (c) 2010 Csaba Kiraly
3
 *  Copyright (c) 2010 Luca Abeni
4
 *
5
 *  This is free software; see gpl-3.0.txt
6
 */
7
#include <stdint.h>
8
#include <stdio.h>
9
#include <sys/time.h>
10
#include <time.h>
11
#include <stdlib.h>
12
#include <string.h>
13

    
14
#include <math.h>
15
#include <net_helper.h>
16
#include <peerset.h>
17
#include <peer.h>
18
#include <grapes_msg_types.h>
19
#include <topmanager.h>
20
#include <tman.h>
21

    
22
#include "compatibility/timer.h"
23

    
24
#include "topology.h"
25
#include "nodeid_set.h"
26
#include "streaming.h"
27
#include "dbg.h"
28
#include "measures.h"
29
#include "streamer.h"
30
#include "hrc.h"
31
#include "blacklist.h"
32

    
33
#define MIN(A,B) (((A) < (B)) ? (A) : (B))
34
#define MAX(A,B) (((A) > (B)) ? (A) : (B))
35

    
36
#define UPDATE_PEERS_TIMEOUT 5
37

    
38
double desired_bw = 0;
39
double desired_rtt = 0.2;
40
double alpha_target = 0.5;
41
double topo_mem = 0;
42

    
43
bool topo_out = true; //peer selects out-neighbours
44
bool topo_in = false; //peer selects in-neighbours (combined means bidirectional)
45

    
46
bool topo_keep_best = false;
47
bool topo_add_best = false;
48
bool topo_black_list = false;
49

    
50
const char* topo_keep_best_policy = "";
51
const char* topo_add_best_policy = "";
52
const char* topo_black_list_policy = "";
53

    
54
int NEIGHBORHOOD_TARGET_SIZE = 30;
55
#define TMAN_MAX_IDLE 10
56
#define TMAN_LOG_EVERY 1000
57

    
58
#define STREAMER_TOPOLOGY_MSG_ADD 0
59
#define STREAMER_TOPOLOGY_MSG_REMOVE 1
60

    
61
static struct peerset *pset_outgoing;
62
static struct peerset *pset_incoming;
63
static struct timeval tout_bmap = {20, 0};
64
static int counter = 0;
65
static int counter2 = 0;
66
static int simpleRanker (const void *tin, const void *p1in, const void *p2in);
67
static tmanRankingFunction rankFunct = simpleRanker;
68

    
69
struct metadata {
70
  uint16_t cb_size;
71
  uint16_t cps;
72
  double capacity;
73
  double recv_delay;
74
} __attribute__((packed));
75

    
76
static struct metadata my_metadata;
77
static int cnt = 0;
78
static struct nodeID *me = NULL;
79
static unsigned char mTypes[] = {MSG_TYPE_TOPOLOGY,MSG_TYPE_TMAN,MSG_TYPE_STREAMER_TOPOLOGY};
80
static struct nodeID ** neighbors;
81
static struct timeval last_time_updated_peers;
82

    
83
struct nodeID **newids;
84
int newids_size;
85
struct metadata *metas;
86

    
87
static void update_metadata(void) {
88
        my_metadata.cb_size = am_i_source() ? 0 : get_cb_size();
89
        my_metadata.cps =  (uint16_t) get_running_offer_threads();
90
        my_metadata.recv_delay = (double) get_receive_delay();
91
        my_metadata.capacity = (double) get_capacity();
92
}
93

    
94
static struct metadata get_metadata_for_peer(struct nodeID *id){
95
        int i = 0;
96
        struct metadata to_return;
97
        to_return.cb_size = NAN;
98
        to_return.cps =  NAN;
99
        to_return.recv_delay = NAN;
100
        to_return.capacity = NAN;
101

    
102
        if (newids_size > 0 && id != NULL) {
103
                for (i = 0 ; i < newids_size; i++) {
104
                        if (newids[i] != NULL) {
105
                                if (nodeid_equal(newids[i],id)){
106
                                        to_return.cb_size = metas[i].cb_size;
107
                                        to_return.cps = metas[i].cps;
108
                                        to_return.recv_delay = metas[i].recv_delay;
109
                                        to_return.capacity = metas[i].capacity;
110
                                        return to_return;
111
                                }
112
                        }
113
                }
114
        return to_return;
115
        }
116
}
117

    
118
static int simpleRanker (const void *tin, const void *p1in, const void *p2in) {
119

    
120
        double t,p1,p2;
121
        t = *((const double *)tin);
122
        p1 = *((const double *)p1in);
123
        p2 = *((const double *)p2in);
124

    
125
        if (isnan(t) || (isnan(p1) && isnan(p2))) return 0;
126
        else if (isnan(p1)) return 2;
127
        else if (isnan(p2)) return 1;
128
        else return (fabs(t-p1) == fabs(t-p2))?0:(fabs(t-p1) < fabs(t-p2))?1:2;
129

    
130
}
131

    
132
int topologyInit(struct nodeID *myID, const char *config)
133
{
134
        int i;
135
        for (i=0;i<sizeof(mTypes)/sizeof(mTypes[0]);i++)
136
                bind_msg_type(mTypes[i]);
137
        update_metadata();
138
        me = myID;
139
        struct timeval tnow;
140
        gettimeofday(&tnow, NULL);
141
        gettimeofday(&last_time_updated_peers, NULL);
142
        last_time_updated_peers.tv_sec -= UPDATE_PEERS_TIMEOUT;
143
        return (topInit(myID, &my_metadata, sizeof(my_metadata), config) && tmanInit(myID,&my_metadata, sizeof(my_metadata),rankFunct,0));
144
}
145

    
146
void topologyShutdown(void)
147
{
148
}
149

    
150
int topoAddNeighbour(struct nodeID *neighbour, void *metadata, int metadata_size)
151
{
152
        // TODO: check this!! Just to use this function to bootstrap ncast...
153
        struct metadata m = {0};        //TODO: check what metadata option should mean
154

    
155
        if (counter < TMAN_MAX_IDLE)
156
                return topAddNeighbour(neighbour,&m,sizeof(m));
157
        else return tmanAddNeighbour(neighbour,&m,sizeof(m));
158
}
159

    
160
static int topoParseData(const uint8_t *buff, int len)
161
{
162
        int res = -1,ncs = 0,msize;
163
        const struct nodeID **n; const void *m;
164
        if (!buff || buff[0] == MSG_TYPE_TOPOLOGY) {
165
                res = topParseData(buff,len);
166
//                 if (counter <= TMAN_MAX_IDLE)
167
//                         counter++;
168
        }
169
        if (counter >= TMAN_MAX_IDLE && (!buff || buff[0] == MSG_TYPE_TMAN))
170
        {
171
                n = topGetNeighbourhood(&ncs);
172
                if (ncs) {
173
                m = topGetMetadata(&msize);
174
                res = tmanParseData(buff,len,n,ncs,m,msize);
175
                }
176
        }
177
  return res;
178
}
179

    
180
static const struct nodeID **topoGetNeighbourhood(int *n)
181
{
182
        int i; double d;
183
        if (counter > TMAN_MAX_IDLE) {
184
                uint8_t *mdata; int msize;
185
                *n = tmanGetNeighbourhoodSize();
186
                if (neighbors) free(neighbors);
187
                neighbors = calloc(*n,sizeof(struct nodeID *));
188
                tmanGetMetadata(&msize);
189
                mdata = calloc(*n,msize);
190
                tmanGivePeers(*n,neighbors,(void *)mdata);
191

    
192
                if (cnt % TMAN_LOG_EVERY == 0) {
193
                        fprintf(stderr,"abouttopublish,%s,%s,,Tman_chunk_delay,%f\n",node_addr(me),node_addr(me),my_metadata.recv_delay);
194
                        for (i=0;i<(*n) && i<NEIGHBORHOOD_TARGET_SIZE;i++) {
195
                                d = *((double *)(mdata+i*msize));
196
                                fprintf(stderr,"abouttopublish,%s,",node_addr(me));
197
                                fprintf(stderr,"%s,,Tman_chunk_delay,%f\n",node_addr(neighbors[i]),d);
198
                        }
199
                        fprintf(stderr,"abouttopublish,%s,%s,,Tman_neighborhood_size,%d\n\n",node_addr(me),node_addr(me),*n);
200
                }
201

    
202
                free(mdata);
203
                return (const struct nodeID **)neighbors;
204
        }
205
        else
206
                return topGetNeighbourhood(n);
207
}
208

    
209
static void topoAddToBL (struct nodeID *id)
210
{
211
        if (counter >= TMAN_MAX_IDLE)
212
                tmanAddToBlackList(id);
213
        topAddToBlackList(id);
214
}
215

    
216
//TODO: send metadata as well
217
static int send_topo_msg(struct nodeID *dst, uint8_t type)
218
{
219
  char msg[2];
220
  msg[0] = MSG_TYPE_STREAMER_TOPOLOGY;
221
  msg[1] = type;
222
  
223
  return send_to_peer(me, dst, msg, 2);
224
}
225

    
226
static void add_peer(const struct nodeID *id, const struct metadata *m, bool outgoing, bool incoming)
227
{
228
  if (outgoing) {
229
      dtprintf("Adding %s to outgoing neighbourhood! cb_size:%d\n", node_addr(id), m?m->cb_size:-1);
230
      peerset_add_peer(pset_outgoing, id);
231
      if (m) peerset_get_peer(pset_outgoing, id)->cb_size = m->cb_size;
232
      if (m) peerset_get_peer(pset_outgoing, id)->capacity = m->capacity;
233
      /* add measures here */
234
      add_measures(id);
235
      send_bmap(id);
236
  }
237
  if (incoming) {
238
      dtprintf("Topo: explicit add message sent!!! to %s (peers:%d)\n", node_addr(id));
239
      peerset_add_peer(pset_incoming, id);
240
      if (m) peerset_get_peer(pset_incoming, id)->cb_size = m->cb_size;
241
      if (m) peerset_get_peer(pset_incoming, id)->capacity = m->capacity;
242
      send_topo_msg(id, STREAMER_TOPOLOGY_MSG_ADD);
243
  }
244
}
245

    
246
static void remove_peer(const struct nodeID *id, bool outgoing, bool incoming)
247
{
248
  if (outgoing) {
249
      dtprintf("Removing %s from outgoing neighbourhood!\n", node_addr(id));
250
      /* delete measures here */
251
      delete_measures(id);
252
      peerset_remove_peer(pset_outgoing, id);
253
  }
254
  if (incoming) {
255
      dtprintf("Topo: explicit remove message sent!!! to %s (peers:%d)\n", node_addr(id));
256
      peerset_remove_peer(pset_incoming, id);
257
      send_topo_msg(id, STREAMER_TOPOLOGY_MSG_REMOVE);
258
  }
259
}
260

    
261
//get the rtt. Currenly only MONL version is supported
262
static double get_rtt_of(const struct nodeID* n){
263
#ifdef MONL
264
  return get_rtt(n);
265
#else
266
  return NAN;
267
#endif
268
}
269

    
270
//get the declared capacity of a node
271
static double get_capacity_of(const struct nodeID* n){
272
  struct peer *p = peerset_get_peer(pset_incoming, n);
273
  if (p) {
274
    return p->capacity;
275
  } 
276
  p = peerset_get_peer(pset_outgoing, n);
277
  if (p) {
278
    return p->capacity;
279
  } 
280
  return NAN;
281
}
282

    
283
// //get the declared capacity of a node
284
// static double get_capacity_of_newid(const struct nodeID* n){
285
//   int i = 0;
286
//   for (i = 0; i < newids_size; i++){
287
//           if (strcmp(node_addr(n), node_addr(newids[i]))) {
288
//                   return metas[i].capacity;
289
//           }
290
//   }
291
//   return NAN;
292
// }
293

    
294

    
295
// FF//get the declared capacity of a node
296
// static double get_offers_threads_of(const struct nodeID* n){
297
//   struct peer *p = peerset_get_peer(pset, n);
298
//   if (p) {
299
//     return p->offers_threads;
300
//   }
301
// 
302
//   return NAN;
303
// }
304

    
305

    
306
static double get_rx_bytes_chunks_of(const struct nodeID* n){
307
#ifdef MONL
308
  return get_rx_bytes_chunks(n);
309
#else
310
  return NAN;
311
#endif
312
}
313

    
314
static double get_transmitter_lossrate_of(const struct nodeID* n){
315
#ifdef MONL
316
  return get_transmitter_lossrate_of(n);
317
#else
318
  return NAN;
319
#endif
320
}
321

    
322
//returns: 1:yes 0:no -1:unknown
323
int desiredness(const struct nodeID* n) {
324
  double rtt = get_rtt_of(n);
325
  double bw = 0.0;
326
  bw =  get_metadata_for_peer(n).capacity;
327
  
328
  if ((isnan(rtt) && finite(desired_rtt)) || (isnan(bw) && desired_bw > 0)) {
329
    return -1;
330
  } else if ((isnan(rtt) || rtt <= desired_rtt) && (isnan(bw) || bw >= desired_bw)) {
331
    return 1;
332
  }
333

    
334
  return 0;
335
}
336

    
337
// equal to desiredness, but considers blacklist
338
//returns: 1:yes 0:no -1:unknown
339
int desiredness_unbled(const struct nodeID* n) {
340
  bool bled = black_listed(node_addr(n));
341

    
342
  if (!bled) {
343
    return 1;
344
  }
345
  return 0;
346
}
347

    
348
//returns: 1:yes 0:no -1:unknown
349
int blacklistness_lossrate(const struct nodeID* n) {
350
  double loss_rate = get_transmitter_lossrate(n);
351
  
352
  dprintf("BLACKLIST: father loss %s rate is %f\n", node_addr(n), loss_rate);
353
  
354
  if (isnan(loss_rate)) {
355
    return -1;
356
  } else if (loss_rate > 0.10) {
357
    return 1;
358
  }
359

    
360
  return 0;
361
}
362

    
363
bool is_desired(const struct nodeID* n) {
364
  return (desiredness(n) == 1);
365
}
366

    
367
bool is_desired_unbled(const struct nodeID* n) {
368
  return (desiredness_unbled(n) == 1);
369
}
370

    
371
bool is_to_blacklist(const struct nodeID* n) {
372
  return (blacklistness_lossrate(n) == 1);
373
}
374

    
375
double add_alpha_noise(double to_return) {
376
        double uniform = rand()/(RAND_MAX + 1.0);
377
        return (double) (((1-alpha_target) + (2*alpha_target*uniform)) * to_return) ; 
378
        }
379

    
380
int cmp_rtt(const struct nodeID** a, const struct nodeID** b) {
381
  double ra, rb;
382
  ra = add_alpha_noise(get_rtt_of(*a));
383
  rb = add_alpha_noise(get_rtt_of(*b));
384
  
385
  fprintf(stderr, "RTTS: %s %f %s %f\n", node_addr(*a), ra, node_addr(*b), rb );
386
  if ((isnan(ra) && isnan(rb)) || ra == rb) return 0;
387
  else if (isnan(rb) || ra < rb) return -1;
388
  else return 1;
389
}
390

    
391
int vcmp_rtt(const void* a, const void* b) {
392
  return cmp_rtt((const struct nodeID**) a, (const struct nodeID**) b);
393
}
394

    
395
int cmp_bw(const struct nodeID** a, const struct nodeID** b) {
396
  double ra, rb;
397
  ra = -( add_alpha_noise(get_metadata_for_peer(*a).capacity));
398
  rb = -( add_alpha_noise(get_metadata_for_peer(*b).capacity));
399

    
400
  if ((isnan(ra) && isnan(rb)) || ra == rb) return 0;
401
  else if (isnan(rb) || ra < rb) return -1;
402
  else return 1;
403
}
404

    
405
int vcmp_bw(const void* a, const void* b) {
406
  return cmp_bw((const struct nodeID**)a, (const struct nodeID**)b);
407
}
408

    
409
int cmp_rtt_bw(const struct nodeID** a, const struct nodeID** b) {
410
  double ra, rb;
411
  ra = -( add_alpha_noise(get_metadata_for_peer(*a).capacity * get_rtt_of(*a)));
412
  rb = -( add_alpha_noise(get_metadata_for_peer(*b).capacity * get_rtt_of(*b)));
413

    
414
  if ((isnan(ra) && isnan(rb)) || ra == rb) return 0;
415
  else if (isnan(rb) || ra < rb) return -1;
416
  else return 1;
417
}
418

    
419
int vcmp_rtt_bw(const void* a, const void* b) {
420
  return cmp_rtt_bw((const struct nodeID**)a, (const struct nodeID**)b);
421
}
422

    
423
int cmp_offers(const struct nodeID** a, const struct nodeID** b) {
424
  double ra, rb;
425
  ra = -( add_alpha_noise(get_metadata_for_peer(*a).cps) );
426
  rb = -( add_alpha_noise(get_metadata_for_peer(*b).cps) );
427
  if ((isnan(ra) && isnan(rb)) || ra == rb) return 0;
428
  else if (isnan(rb) || ra < rb) return -1;
429
  else return 1;
430
}
431

    
432
int vcmp_offers(const void* a, const void* b) {
433
  return cmp_offers((const struct nodeID**)a, (const struct nodeID**)b);
434
}
435

    
436
int cmp_rx_bytes_chunks(const struct nodeID** a, const struct nodeID** b) {
437
  double ra, rb;
438
  ra = -(add_alpha_noise(get_rx_bytes_chunks_of(*a)));
439
  rb = -(add_alpha_noise(get_rx_bytes_chunks_of(*b)));
440
//   fprintf(stderr, "RX_BYTES_CHUNKS: %s %f %s %f\n", node_addr(*a), ra, node_addr(*b), rb );
441
  if ((isnan(ra) && isnan(rb)) || ra == rb) 
442
        return 0;
443
  else if (isnan(rb) || ra < rb) 
444
        return -1;
445
  else 
446
        return 1;
447
}
448

    
449
int vcmp_rx_bytes_chunks(const void* a, const void* b) {
450
  return cmp_rx_bytes_chunks((const struct nodeID**) a, (const struct nodeID**) b);
451
}
452

    
453
int cmp_packet_loss(const struct nodeID** a, const struct nodeID** b) {
454
  double ra, rb;
455
  ra = add_alpha_noise(get_transmitter_lossrate(*a));
456
  rb = add_alpha_noise(get_transmitter_lossrate(*b));
457
//   fprintf(stderr, "PACKET_LOSS: %s %f %s %f\n", node_addr(*a), ra, node_addr(*b), rb );
458
  if ((isnan(ra) && isnan(rb)) || ra == rb) 
459
        return 0;
460
  else if (isnan(rb) || ra < rb) 
461
        return -1;
462
  else 
463
        return 1;
464
}
465

    
466
int vcmp_packet_loss(const void* a, const void* b) {
467
  return cmp_packet_loss((const struct nodeID**) a, (const struct nodeID**) b);
468
}
469

    
470
// Use add best policy specified at command line
471
int vcmp_add_best(const void* a, const void* b) {
472
  if (strcmp(topo_add_best_policy, "OFFERS") == 0) {
473
          return vcmp_offers(a, b);
474
  } else if (strcmp(topo_add_best_policy, "BW") == 0) {
475
          return vcmp_bw(a, b);
476
  } else if (strcmp(topo_add_best_policy, "RTT") == 0) {
477
          return vcmp_rtt( a,  b);
478
  } else if (strcmp(topo_add_best_policy, "BW_RTT") == 0) {
479
          return vcmp_rtt_bw( a,  b);
480
  } else if (strcmp(topo_add_best_policy, "") == 0){ // defualt behaviuor
481
          return vcmp_rtt_bw( a, b);
482
  } else {
483
    fprintf(stderr, "Error: unknown add best policy %s\n", topo_add_best_policy);
484
    return 1;
485
  }  
486
}
487

    
488
// Use keep best policy specified at command line
489
int vcmp_keep_best(const void* a, const void* b) {
490
  if (strcmp(topo_keep_best_policy, "RTT") == 0) {
491
          return vcmp_rtt(a, b);
492
  }  else if (strcmp(topo_keep_best_policy, "BW") == 0) {
493
          return vcmp_bw(a, b);
494
  }  else if (strcmp(topo_keep_best_policy, "RX_CHUNKS") == 0) {
495
          return vcmp_rx_bytes_chunks(a, b);
496
  } else if (strcmp(topo_keep_best_policy, "PACKET_LOSS") == 0) {
497
          return vcmp_packet_loss( a, b);
498
  } else if (strcmp(topo_keep_best_policy, "") == 0) { // Default behaviuor
499
          return vcmp_rx_bytes_chunks( a, b);
500
  } else {
501
    fprintf(stderr, "Error: unknown keep best policy %s\n", topo_add_best_policy);
502
    return 1;
503
  }  
504
}
505

    
506
// currently it just makes the peerset grow
507
void update_peers(struct nodeID *from, const uint8_t *buff, int len)
508
{
509
  int n_ids, metasize, i, max_ids;
510
  
511
  struct peer *peers;
512
  struct timeval tnow, told;
513
  static const struct nodeID **savedids;
514
  static int savedids_size;
515
  
516
  if timerisset(&tout_bmap) {
517
    gettimeofday(&tnow, NULL);
518
    timersub(&tnow, &tout_bmap, &told);
519
    peers = peerset_get_peers(pset_incoming);
520
    // Prune incoming inactive peers
521
    for (i = 0; i < peerset_size(pset_incoming); i++) {
522
      if ( (!timerisset(&peers[i].bmap_timestamp) && timercmp(&peers[i].creation_timestamp, &told, <) ) ||
523
           ( timerisset(&peers[i].bmap_timestamp) && timercmp(&peers[i].bmap_timestamp, &told, <)     )   ) {
524
        ftprintf(stderr,"Topo: dropping incoming inactive %s (peers:%d)\n", node_addr(peers[i].id), peerset_size(pset_incoming));
525
        //if (peerset_size(pset) > 1) {        // avoid dropping our last link to the world
526
        topoAddToBL(peers[i].id);
527
        remove_peer(peers[i--].id, topo_out, topo_in);
528
        //}
529
      }
530
    }
531
  }
532

    
533
  //handle explicit add/remove messages
534
//   if (topo_in && buff && buff[0] == MSG_TYPE_STREAMER_TOPOLOGY) {
535
    if (buff && buff[0] == MSG_TYPE_STREAMER_TOPOLOGY) {
536
    fprintf(stderr,"Topo: explicit topo message received!!!from %s (peers:%d)\n", node_addr(from), peerset_size(pset_outgoing));
537
    if (len != 2) {
538
      fprintf(stderr, "Bad streamer topo message received, len:%d!\n", len);
539
      return;
540
    }
541
    switch (buff[1]) {
542
      case STREAMER_TOPOLOGY_MSG_ADD:
543
        // I have to add this peer to my outgoing neighbourood
544
        ftprintf(stderr,"Topo: adding on request %s (peers:%d)\n", node_addr(from), peerset_size(pset_outgoing));
545
        if (!peerset_get_peer(pset_outgoing, from)) {
546
                counter2++;
547
                add_peer(from, NULL, true, false);
548
                }
549
//         if (black_listed(node_addr(from)) && (peerset_get_peer(pset_outgoing, from)))
550
//                 remove_peer(from, topo_in, topo_out);
551
//         else if ((black_listed(node_addr(from))) && (peerset_get_peer(pset_outgoing, from) == NULL))
552
//                 send_topo_msg(from, STREAMER_TOPOLOGY_MSG_REMOVE);
553
        break;
554
      case STREAMER_TOPOLOGY_MSG_REMOVE:
555
        // Neighbour ask me to remove him from my outgoing neighbourhood
556
        if (peerset_get_peer(pset_outgoing, from) != NULL) {
557
                ftprintf(stderr,"Topo: removing on request %s (peers:%d)\n", node_addr(from), peerset_size(pset_outgoing));
558
                remove_peer(from, true, false);
559
                }
560
        break;
561
      default:
562
        fprintf(stderr, "Bad streamer topo message received!\n");
563
    }
564
    reg_outgoing_neigh_size(peerset_size(pset_outgoing));
565
    reg_incoming_neigh_size(peerset_size(pset_incoming));
566
    return;
567
  }
568

    
569
  int res_topo_parse_data = topoParseData(buff, len);
570

    
571
  // Exit if a gossiping message has been received
572
  if (res_topo_parse_data > 0) {
573
    reg_outgoing_neigh_size(peerset_size(pset_outgoing));
574
    reg_incoming_neigh_size(peerset_size(pset_incoming));
575
    return;
576
  }
577

    
578
  // Look for peers which can be removed from blacklist
579
  check_black_list_timeouts();
580
  update_metadata();
581
  topChangeMetadata(&my_metadata, sizeof(struct metadata));
582

    
583
  double time_difference = (tnow.tv_sec + tnow.tv_usec*1e-6) - (last_time_updated_peers.tv_sec + last_time_updated_peers.tv_usec*1e-6);
584

    
585
  // Check if it's time to update the neighbourhood
586
  if (time_difference > UPDATE_PEERS_TIMEOUT) {
587
    
588
    // If I have to control my sons (--topo_in)
589
    if (topo_in && !topo_out) {
590
        peers = peerset_get_peers(pset_outgoing);
591
        n_ids = peerset_size(pset_outgoing);
592
    } else if (!topo_in && topo_out) { // If I have to control my fathers (--topo_out)
593
        peers = peerset_get_peers(pset_incoming);
594
        n_ids = peerset_size(pset_incoming);
595
    } else if (topo_in && topo_out) { // If topo_bidir, no distinction between sons and fathers, then incoming or outgoing doesn't matter
596
        peers = peerset_get_peers(pset_incoming);
597
        n_ids = peerset_size(pset_incoming);
598
    }
599

    
600
    newids = topGetNeighbourhood(&newids_size);    //TODO handle both tman and topo
601
    metas = topGetMetadata(&metasize);
602
    int index = 0;
603
    for (index = 0; index < newids_size; index++) {
604
            dprintf("METAS node %s, capacity %f, cps %d, buffer %d\n", node_addr(newids[index]), metas[index].capacity, metas[index].cps, metas[index].cb_size);
605
    }
606
    dprintf("METAS my %f END\n", my_metadata.capacity);
607
    max_ids = n_ids + savedids_size + newids_size;
608
    ftprintf(stderr,"Topo modify start peers:%d candidates:%d\n", n_ids, newids_size);
609

    
610
    int desired_part;
611
    const struct nodeID *oldids[max_ids], *nodeids[max_ids], *candidates[max_ids], *desireds[max_ids], *selecteds[max_ids], *others[max_ids], *toadds[max_ids], *toremoves[max_ids];
612
    int oldids_size, nodeids_size, candidates_size, desireds_size, selecteds_size, others_size, toadds_size, toremoves_size, keep_size, random_size;
613
    nodeids_size = candidates_size = desireds_size = selecteds_size = others_size = toadds_size = toremoves_size = max_ids;
614

    
615
    if (topo_out) {
616
      for (i = 0, oldids_size = 0; i < peerset_size(pset_incoming); i++) {
617
        oldids[oldids_size++] = peers[i].id;
618
        fprintf(stderr," %s - RTT: %f, loss_rate %f\n", node_addr(peers[i].id) , get_rtt_of(peers[i].id), get_transmitter_lossrate(peers[i].id));
619
      }
620
    } else {
621
      for (i = 0, oldids_size = 0; i < savedids_size; i++) {
622
        oldids[oldids_size++] = savedids[i];
623
        fprintf(stderr," %s - RTT: %f, RX_CHUNKS: %f\n", node_addr(oldids[i]) , get_rtt_of(oldids[i]), get_rx_bytes_chunks(oldids[i]));
624
      }
625
      savedids_size = 0;
626
      free(savedids);
627
    }
628

    
629
    // select the topo_mem portion of peers to be kept (uniform random)
630
    if ((topo_keep_best) && (strcmp(topo_keep_best_policy, "RND") != 0)) {
631
      qsort(oldids, oldids_size, sizeof(oldids[0]), vcmp_keep_best);
632
    } else {
633
      nidset_shuffle(oldids, oldids_size);
634
    }
635
    for (i = 0; i < oldids_size; i++) {
636
        dprintf("QSORT KEEP BEST %s - RTT: %f, RX_CHUNKS %f, PACKET_LOSS %f, BW %f\n", node_addr(oldids[i]) , get_rtt_of(oldids[i]), get_rx_bytes_chunks(oldids[i]), get_transmitter_lossrate(oldids[i]), get_capacity_of(oldids[i]));
637
      }
638
    dprintf("QSORT KEEP BEST END\n");
639
    
640
    keep_size = selecteds_size = (int) (topo_mem * oldids_size);
641
    memcpy(selecteds, oldids, selecteds_size * sizeof(selecteds[0]));
642

    
643
    // compose list of known nodeids
644
    nidset_add(nodeids, &nodeids_size, oldids, oldids_size, newids, newids_size);
645
  
646
    // compose list of candidate nodeids
647
    nidset_complement(candidates, &candidates_size, nodeids, nodeids_size, selecteds, selecteds_size);
648

    
649
    // select the alpha_target portion of desired peers
650
    desired_part = (NEIGHBORHOOD_TARGET_SIZE ? (MAX (NEIGHBORHOOD_TARGET_SIZE - selecteds_size, 0)) : 0);
651
    
652
    
653
    // Filter out blacklisted ones    
654
    nidset_filter(desireds, &desireds_size, candidates, candidates_size, is_desired_unbled);
655
    
656
    if ((topo_add_best) && (strcmp(topo_add_best_policy, "RND") != 0)) {
657
      qsort(desireds, desireds_size, sizeof(desireds[0]), vcmp_add_best);
658
    } else {
659
      nidset_shuffle(desireds, desireds_size);
660
    }
661
    for (i = 0; i < desireds_size; i++) {
662
        dprintf("QSORT ADD BEST %s - RTT: %f, BW %f, BW*RTT %f, OFFERS %d\n", node_addr(desireds[i]) , get_rtt_of(desireds[i]), (get_metadata_for_peer(desireds[i])).capacity, (double) ((get_metadata_for_peer(desireds[i])).capacity*get_rtt_of(desireds[i])), (get_metadata_for_peer(desireds[i])).cps);
663
      }
664
    dprintf("QSORT ADD BEST END\n");
665
    nidset_add_i(selecteds, &selecteds_size, max_ids, desireds, MIN(desireds_size,desired_part));
666

    
667
    // random from the rest
668
    nidset_complement(others, &others_size, candidates, candidates_size, selecteds, selecteds_size);
669
    nidset_shuffle(others, others_size);
670
    random_size = NEIGHBORHOOD_TARGET_SIZE ? MIN(others_size, MAX(NEIGHBORHOOD_TARGET_SIZE - selecteds_size, 0)) : others_size;
671
    nidset_add_i(selecteds, &selecteds_size, max_ids, others, random_size);
672

    
673
    fprintf(stderr,"Topo modify sel:%d (from:%d) = keep: %d (of old:%d) + desired: %d (from %d of %d; target:%d) + random: %d (from %d)\n",
674
        selecteds_size, nodeids_size,
675
        keep_size, oldids_size,
676
        MIN(desireds_size,desired_part), desireds_size, candidates_size, desired_part,
677
        random_size, others_size);
678
    // add new ones
679
    nidset_complement(toadds, &toadds_size, selecteds, selecteds_size, oldids, oldids_size);
680
    for (i = 0; i < toadds_size; i++) {
681
      int j;
682
      //searching for the metadata
683
      if (nidset_find(&j, newids, newids_size, toadds[i])) {
684
        fprintf(stderr," adding %s\n", node_addr(toadds[i]));
685
        counter2++;
686
        add_peer(newids[j], &metas[j], topo_out, topo_in);
687
      } else {
688
        fprintf(stderr," Error: missing metadata for %s\n", node_addr(toadds[i]));
689
      }
690
    }
691

    
692
    // finally, remove those not needed
693
    fprintf(stderr,"Topo remove start (peers:%d)\n", n_ids);
694
        
695
    nidset_complement(toremoves, &toremoves_size, oldids, oldids_size, selecteds, selecteds_size);
696
    for (i = 0; i < toremoves_size; i++) {
697
       // Check that it has not been removed already
698
       bool removed_already = false;
699
       if (topo_in && !topo_out) {
700
               removed_already = (peerset_get_peer(pset_incoming, toremoves[i])!=NULL) ? false : true;
701
       } else if (!topo_in && topo_out) {
702
               removed_already = (peerset_get_peer(pset_outgoing, toremoves[i])!=NULL) ? false : true;
703
       } else if (topo_in && topo_out) {
704
               removed_already = (peerset_get_peer(pset_incoming, toremoves[i])!=NULL) ? false : true;
705
       }
706
       // Counter2 is used to inhibit blacklisting at startup. TEST: maybe useless
707
       if (is_to_blacklist(toremoves[i]) && !black_listed(node_addr(toremoves[i])) && topo_black_list && counter2 > (NEIGHBORHOOD_TARGET_SIZE*2)) {
708
          fprintf(stderr," blacklisting and removing %s\n", node_addr(toremoves[i]));
709
          add_to_blacklist(node_addr(toremoves[i]));
710
          }
711
       fprintf(stderr," removing %s\n", node_addr(toremoves[i]));
712
       if (!removed_already) {
713
          remove_peer(toremoves[i], topo_out, topo_in);
714
          }
715
    }
716
    fprintf(stderr,"Topo remove end\n");
717

    
718
    if (!topo_out) {
719
      savedids = malloc(selecteds_size * sizeof(savedids[0])); //TODO: handle errors
720
      for (i = 0, savedids_size = 0; i < selecteds_size; i++) {
721
        savedids[savedids_size++] = nodeid_dup(selecteds[i]);
722
      }
723
      for (i = 0; i < oldids_size; i++) {
724
        nodeid_free(oldids[i]);
725
      }
726
    }
727
    gettimeofday(&last_time_updated_peers, NULL); 
728
  } 
729
  reg_outgoing_neigh_size(peerset_size(pset_outgoing));
730
  reg_incoming_neigh_size(peerset_size(pset_incoming));
731
}
732

    
733
struct peer *nodeid_to_peer(const struct nodeID* id, int reg)
734
{
735
  struct peer *p = peerset_get_peer(pset_incoming, id);
736
  if (!p) {
737
    //fprintf(stderr,"warning: received message from unknown peer: %s!%s\n",node_addr(id), reg ? " Adding it to pset." : "");
738
    if (reg) {
739
      add_peer(id,NULL, false, true);
740
      fprintf(stderr,"Topo: ext adding %s (peers:%d)\n", node_addr(id), peerset_size(pset_incoming));
741
      p = peerset_get_peer(pset_incoming,id);
742
    }
743
  }
744

    
745
  return p;
746
}
747

    
748
int peers_init(void)
749
{
750
  fprintf(stderr,"peers_init\n");
751
  pset_incoming = peerset_init(0);
752
  pset_outgoing = peerset_init(0);
753
  return pset_incoming && pset_outgoing ? 1 : 0;
754
}
755

    
756
struct peerset *get_peers(void)
757
{
758
  return pset_outgoing;
759
}
760

    
761
struct peerset *get_outgoing_peers(void)
762
{
763
  return pset_outgoing;
764
}
765

    
766
struct peerset *get_incoming_peers(void)
767
{
768
  return pset_incoming;
769
}