Improve performance of edge updates.
[tinc] / src / graph.c
1 /*
2     graph.c -- graph algorithms
3     Copyright (C) 2001-2014 Guus Sliepen <guus@tinc-vpn.org>,
4                   2001-2005 Ivo Timmermans
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 /* We need to generate two trees from the graph:
22
23    1. A minimum spanning tree for broadcasts,
24    2. A single-source shortest path tree for unicasts.
25
26    Actually, the first one alone would suffice but would make unicast packets
27    take longer routes than necessary.
28
29    For the MST algorithm we can choose from Prim's or Kruskal's. I personally
30    favour Kruskal's, because we make an extra AVL tree of edges sorted on
31    weights (metric). That tree only has to be updated when an edge is added or
32    removed, and during the MST algorithm we just have go linearly through that
33    tree, adding safe edges until #edges = #nodes - 1. The implementation here
34    however is not so fast, because I tried to avoid having to make a forest and
35    merge trees.
36
37    For the SSSP algorithm Dijkstra's seems to be a nice choice. Currently a
38    simple breadth-first search is presented here.
39
40    The SSSP algorithm will also be used to determine whether nodes are directly,
41    indirectly or not reachable from the source. It will also set the correct
42    destination address and port of a node if possible.
43 */
44
45 #include "system.h"
46
47 #include "avl_tree.h"
48 #include "conf.h"
49 #include "connection.h"
50 #include "device.h"
51 #include "edge.h"
52 #include "graph.h"
53 #include "logger.h"
54 #include "netutl.h"
55 #include "node.h"
56 #include "process.h"
57 #include "protocol.h"
58 #include "subnet.h"
59 #include "utils.h"
60 #include "xalloc.h"
61
62 static bool graph_changed = true;
63
64 /* Implementation of Kruskal's algorithm.
65    Running time: O(EN)
66    Please note that sorting on weight is already done by add_edge().
67 */
68
69 static void mst_kruskal(void) {
70         avl_node_t *node, *next;
71         edge_t *e;
72         node_t *n;
73         connection_t *c;
74         int nodes = 0;
75         int safe_edges = 0;
76         bool skipped;
77
78         /* Clear MST status on connections */
79
80         for(node = connection_tree->head; node; node = node->next) {
81                 c = node->data;
82                 c->status.mst = false;
83         }
84
85         /* Do we have something to do at all? */
86
87         if(!edge_weight_tree->head)
88                 return;
89
90         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Running Kruskal's algorithm:");
91
92         /* Clear visited status on nodes */
93
94         for(node = node_tree->head; node; node = node->next) {
95                 n = node->data;
96                 n->status.visited = false;
97                 nodes++;
98         }
99
100         /* Starting point */
101
102         for(node = edge_weight_tree->head; node; node = node->next) {
103                 e = node->data;
104                 if(e->from->status.reachable) {
105                         e->from->status.visited = true;
106                         break;
107                 }
108         }
109
110         /* Add safe edges */
111
112         for(skipped = false, node = edge_weight_tree->head; node; node = next) {
113                 next = node->next;
114                 e = node->data;
115
116                 if(!e->reverse || e->from->status.visited == e->to->status.visited) {
117                         skipped = true;
118                         continue;
119                 }
120
121                 e->from->status.visited = true;
122                 e->to->status.visited = true;
123
124                 if(e->connection)
125                         e->connection->status.mst = true;
126
127                 if(e->reverse->connection)
128                         e->reverse->connection->status.mst = true;
129
130                 safe_edges++;
131
132                 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, " Adding edge %s - %s weight %d", e->from->name,
133                                    e->to->name, e->weight);
134
135                 if(skipped) {
136                         skipped = false;
137                         next = edge_weight_tree->head;
138                         continue;
139                 }
140         }
141
142         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Done, counted %d nodes and %d safe edges.", nodes,
143                            safe_edges);
144 }
145
146 /* Implementation of a simple breadth-first search algorithm.
147    Running time: O(E)
148 */
149
150 static void sssp_bfs(void) {
151         avl_node_t *node, *next, *to;
152         edge_t *e;
153         node_t *n;
154         list_t *todo_list;
155         list_node_t *from, *todonext;
156         bool indirect;
157         char *name;
158         char *address, *port;
159         char *envp[8] = {NULL};
160         int i;
161
162         todo_list = list_alloc(NULL);
163
164         /* Clear visited status on nodes */
165
166         for(node = node_tree->head; node; node = node->next) {
167                 n = node->data;
168                 n->status.visited = false;
169                 n->status.indirect = true;
170         }
171
172         /* Begin with myself */
173
174         myself->status.visited = true;
175         myself->status.indirect = false;
176         myself->nexthop = myself;
177         myself->prevedge = NULL;
178         myself->via = myself;
179         list_insert_head(todo_list, myself);
180
181         /* Loop while todo_list is filled */
182
183         for(from = todo_list->head; from; from = todonext) {    /* "from" is the node from which we start */
184                 n = from->data;
185
186                 for(to = n->edge_tree->head; to; to = to->next) {       /* "to" is the edge connected to "from" */
187                         e = to->data;
188
189                         if(!e->reverse)
190                                 continue;
191
192                         /* Situation:
193
194                                    /
195                                   /
196                            ----->(n)---e-->(e->to)
197                                   \
198                                    \
199
200                            Where e is an edge, (n) and (e->to) are nodes.
201                            n->address is set to the e->address of the edge left of n to n.
202                            We are currently examining the edge e right of n from n:
203
204                            - If edge e provides for better reachability of e->to, update
205                              e->to and (re)add it to the todo_list to (re)examine the reachability
206                              of nodes behind it.
207                          */
208
209                         indirect = n->status.indirect || e->options & OPTION_INDIRECT;
210
211                         if(e->to->status.visited
212                            && (!e->to->status.indirect || indirect))
213                                 continue;
214
215                         // Only update nexthop the first time we visit this node.
216
217                         if(!e->to->status.visited)
218                                 e->to->nexthop = (n->nexthop == myself) ? e->to : n->nexthop;
219
220                         e->to->status.visited = true;
221                         e->to->status.indirect = indirect;
222                         e->to->prevedge = e;
223                         e->to->via = indirect ? n->via : e->to;
224                         e->to->options = e->options;
225
226                         if(e->to->address.sa.sa_family == AF_UNSPEC && e->address.sa.sa_family != AF_UNKNOWN)
227                                 update_node_udp(e->to, &e->address);
228
229                         list_insert_tail(todo_list, e->to);
230                 }
231
232                 todonext = from->next;
233                 list_delete_node(todo_list, from);
234         }
235
236         list_free(todo_list);
237
238         /* Check reachability status. */
239
240         for(node = node_tree->head; node; node = next) {
241                 next = node->next;
242                 n = node->data;
243
244                 if(n->status.visited != n->status.reachable) {
245                         n->status.reachable = !n->status.reachable;
246
247                         if(n->status.reachable) {
248                                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Node %s (%s) became reachable",
249                                            n->name, n->hostname);
250                         } else {
251                                 ifdebug(TRAFFIC) logger(LOG_DEBUG, "Node %s (%s) became unreachable",
252                                            n->name, n->hostname);
253                         }
254
255                         /* TODO: only clear status.validkey if node is unreachable? */
256
257                         n->status.validkey = false;
258                         n->last_req_key = 0;
259
260                         n->maxmtu = MTU;
261                         n->minmtu = 0;
262                         n->mtuprobes = 0;
263
264                         if(n->mtuevent) {
265                                 event_del(n->mtuevent);
266                                 n->mtuevent = NULL;
267                         }
268
269                         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
270                         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
271                         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
272                         xasprintf(&envp[3], "NODE=%s", n->name);
273                         sockaddr2str(&n->address, &address, &port);
274                         xasprintf(&envp[4], "REMOTEADDRESS=%s", address);
275                         xasprintf(&envp[5], "REMOTEPORT=%s", port);
276                         xasprintf(&envp[6], "NAME=%s", myself->name);
277
278                         execute_script(n->status.reachable ? "host-up" : "host-down", envp);
279
280                         xasprintf(&name,
281                                          n->status.reachable ? "hosts/%s-up" : "hosts/%s-down",
282                                          n->name);
283                         execute_script(name, envp);
284
285                         free(name);
286                         free(address);
287                         free(port);
288
289                         for(i = 0; i < 7; i++)
290                                 free(envp[i]);
291
292                         subnet_update(n, NULL, n->status.reachable);
293
294                         if(!n->status.reachable) {
295                                 update_node_udp(n, NULL);
296                                 memset(&n->status, 0, sizeof n->status);
297                                 n->options = 0;
298                         } else if(n->connection) {
299                                 send_ans_key(n);
300                         }
301                 }
302         }
303 }
304
305 void graph(void) {
306         subnet_cache_flush();
307         sssp_bfs();
308         mst_kruskal();
309         graph_changed = true;
310 }
311
312
313
314 /* Dump nodes and edges to a graphviz file.
315            
316    The file can be converted to an image with
317    dot -Tpng graph_filename -o image_filename.png -Gconcentrate=true
318 */
319
320 void dump_graph(void) {
321         avl_node_t *node;
322         node_t *n;
323         edge_t *e;
324         char *filename = NULL, *tmpname = NULL;
325         FILE *file, *pipe = NULL;
326         
327         if(!graph_changed || !get_config_string(lookup_config(config_tree, "GraphDumpFile"), &filename))
328                 return;
329
330         graph_changed = false;
331
332         ifdebug(PROTOCOL) logger(LOG_NOTICE, "Dumping graph");
333         
334         if(filename[0] == '|') {
335                 file = pipe = popen(filename + 1, "w");
336         } else {
337                 xasprintf(&tmpname, "%s.new", filename);
338                 file = fopen(tmpname, "w");
339         }
340
341         if(!file) {
342                 logger(LOG_ERR, "Unable to open graph dump file %s: %s", filename, strerror(errno));
343                 free(filename);
344                 free(tmpname);
345                 return;
346         }
347
348         fprintf(file, "digraph {\n");
349         
350         /* dump all nodes first */
351         for(node = node_tree->head; node; node = node->next) {
352                 n = node->data;
353                 fprintf(file, " %s [label = \"%s\"];\n", n->name, n->name);
354         }
355
356         /* now dump all edges */
357         for(node = edge_weight_tree->head; node; node = node->next) {
358                 e = node->data;
359                 fprintf(file, " %s -> %s;\n", e->from->name, e->to->name);
360         }
361
362         fprintf(file, "}\n");   
363         
364         if(pipe) {
365                 pclose(pipe);
366         } else {
367                 fclose(file);
368 #ifdef HAVE_MINGW
369                 unlink(filename);
370 #endif
371                 if(rename(tmpname, filename))
372                         logger(LOG_ERR, "Could not rename %s to %s: %s\n", tmpname, filename, strerror(errno));
373                 free(tmpname);
374         }
375
376         free(filename);
377 }