grab the interface name from tok and not from the uninitialized array
[sahlberg/ctdb.git] / server / ctdb_takeover.c
1 /* 
2    ctdb ip takeover code
3
4    Copyright (C) Ronnie Sahlberg  2007
5    Copyright (C) Andrew Tridgell  2007
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20 #include "includes.h"
21 #include "lib/events/events.h"
22 #include "lib/tdb/include/tdb.h"
23 #include "lib/util/dlinklist.h"
24 #include "system/network.h"
25 #include "system/filesys.h"
26 #include "system/wait.h"
27 #include "../include/ctdb_private.h"
28 #include "../common/rb_tree.h"
29
30
31 #define TAKEOVER_TIMEOUT() timeval_current_ofs(ctdb->tunable.takeover_timeout,0)
32
33 #define CTDB_ARP_INTERVAL 1
34 #define CTDB_ARP_REPEAT   3
35
36 struct ctdb_takeover_arp {
37         struct ctdb_context *ctdb;
38         uint32_t count;
39         struct sockaddr_in sin;
40         struct ctdb_tcp_array *tcparray;
41         struct ctdb_vnn *vnn;
42 };
43
44
45 /*
46   lists of tcp endpoints
47  */
48 struct ctdb_tcp_list {
49         struct ctdb_tcp_list *prev, *next;
50         struct ctdb_tcp_connection connection;
51 };
52
53 /*
54   list of clients to kill on IP release
55  */
56 struct ctdb_client_ip {
57         struct ctdb_client_ip *prev, *next;
58         struct ctdb_context *ctdb;
59         struct sockaddr_in ip;
60         uint32_t client_id;
61 };
62
63
64 /*
65   send a gratuitous arp
66  */
67 static void ctdb_control_send_arp(struct event_context *ev, struct timed_event *te, 
68                                   struct timeval t, void *private_data)
69 {
70         struct ctdb_takeover_arp *arp = talloc_get_type(private_data, 
71                                                         struct ctdb_takeover_arp);
72         int i, s, ret;
73         struct ctdb_tcp_array *tcparray;
74
75
76         ret = ctdb_sys_send_arp(&arp->sin, arp->vnn->iface);
77         if (ret != 0) {
78                 DEBUG(0,(__location__ " sending of arp failed (%s)\n", strerror(errno)));
79         }
80
81         s = ctdb_sys_open_sending_socket();
82         if (s == -1) {
83                 DEBUG(0,(__location__ " failed to open raw socket for sending tickles\n"));
84                 return;
85         }
86
87         tcparray = arp->tcparray;
88         if (tcparray) {
89                 for (i=0;i<tcparray->num;i++) {
90                         DEBUG(2,("sending tcp tickle ack for %u->%s:%u\n",
91                                  (unsigned)ntohs(tcparray->connections[i].daddr.sin_port), 
92                                  inet_ntoa(tcparray->connections[i].saddr.sin_addr),
93                                  (unsigned)ntohs(tcparray->connections[i].saddr.sin_port)));
94                         ret = ctdb_sys_send_tcp(s, &tcparray->connections[i].saddr, 
95                                                 &tcparray->connections[i].daddr, 0, 0, 0);
96                         if (ret != 0) {
97                                 DEBUG(0,(__location__ " Failed to send tcp tickle ack for %s\n",
98                                          inet_ntoa(tcparray->connections[i].saddr.sin_addr)));
99                         }
100                 }
101         }
102
103         close(s);
104         arp->count++;
105
106         if (arp->count == CTDB_ARP_REPEAT) {
107                 talloc_free(arp);
108                 return;
109         }
110
111         event_add_timed(arp->ctdb->ev, arp->vnn->takeover_ctx, 
112                         timeval_current_ofs(CTDB_ARP_INTERVAL, 0), 
113                         ctdb_control_send_arp, arp);
114 }
115
116 struct takeover_callback_state {
117         struct ctdb_req_control *c;
118         struct sockaddr_in *sin;
119         struct ctdb_vnn *vnn;
120 };
121
122 /*
123   called when takeip event finishes
124  */
125 static void takeover_ip_callback(struct ctdb_context *ctdb, int status, 
126                                  void *private_data)
127 {
128         struct takeover_callback_state *state = 
129                 talloc_get_type(private_data, struct takeover_callback_state);
130         struct ctdb_takeover_arp *arp;
131         char *ip = inet_ntoa(state->sin->sin_addr);
132         struct ctdb_tcp_array *tcparray;
133
134         ctdb_start_monitoring(ctdb);
135
136         if (status != 0) {
137                 DEBUG(0,(__location__ " Failed to takeover IP %s on interface %s\n",
138                          ip, state->vnn->iface));
139                 ctdb_request_control_reply(ctdb, state->c, NULL, status, NULL);
140                 talloc_free(state);
141                 return;
142         }
143
144         if (!state->vnn->takeover_ctx) {
145                 state->vnn->takeover_ctx = talloc_new(ctdb);
146                 if (!state->vnn->takeover_ctx) {
147                         goto failed;
148                 }
149         }
150
151         arp = talloc_zero(state->vnn->takeover_ctx, struct ctdb_takeover_arp);
152         if (!arp) goto failed;
153         
154         arp->ctdb = ctdb;
155         arp->sin = *state->sin;
156         arp->vnn = state->vnn;
157
158         tcparray = state->vnn->tcp_array;
159         if (tcparray) {
160                 /* add all of the known tcp connections for this IP to the
161                    list of tcp connections to send tickle acks for */
162                 arp->tcparray = talloc_steal(arp, tcparray);
163
164                 state->vnn->tcp_array = NULL;
165                 state->vnn->tcp_update_needed = true;
166         }
167
168         event_add_timed(arp->ctdb->ev, state->vnn->takeover_ctx, 
169                         timeval_zero(), ctdb_control_send_arp, arp);
170
171         /* the control succeeded */
172         ctdb_request_control_reply(ctdb, state->c, NULL, 0, NULL);
173         talloc_free(state);
174         return;
175
176 failed:
177         ctdb_request_control_reply(ctdb, state->c, NULL, -1, NULL);
178         talloc_free(state);
179         return;
180 }
181
182 /*
183   Find the vnn of the node that has a public ip address
184   returns -1 if the address is not known as a public address
185  */
186 static struct ctdb_vnn *find_public_ip_vnn(struct ctdb_context *ctdb, struct sockaddr_in ip)
187 {
188         struct ctdb_vnn *vnn;
189
190         for (vnn=ctdb->vnn;vnn;vnn=vnn->next) {
191                 if (ctdb_same_ip(&vnn->public_address, &ip)) {
192                         return vnn;
193                 }
194         }
195
196         return NULL;
197 }
198
199
200 /*
201   take over an ip address
202  */
203 int32_t ctdb_control_takeover_ip(struct ctdb_context *ctdb, 
204                                  struct ctdb_req_control *c,
205                                  TDB_DATA indata, 
206                                  bool *async_reply)
207 {
208         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
209         int ret;
210         struct takeover_callback_state *state;
211         struct ctdb_public_ip *pip = (struct ctdb_public_ip *)indata.dptr;
212         struct ctdb_vnn *vnn;
213         bool have_ip, is_loopback;
214         char *ifname = NULL;
215
216         /* update out vnn list */
217         vnn = find_public_ip_vnn(ctdb, pip->sin);
218         if (vnn == NULL) {
219                 DEBUG(0,("takeoverip called for an ip '%s' that is not a public address\n", 
220                          inet_ntoa(pip->sin.sin_addr)));
221                 talloc_free(tmp_ctx);
222                 return 0;
223         }
224         vnn->pnn = pip->pnn;
225
226         /* if our kernel already has this IP, do nothing */
227         have_ip = ctdb_sys_have_ip(pip->sin, &is_loopback, tmp_ctx, &ifname);
228         /* if we have the ip and it is not set to a loopback address */
229         if (have_ip && !is_loopback) {
230                 talloc_free(tmp_ctx);
231                 return 0;
232         }
233
234         state = talloc(ctdb, struct takeover_callback_state);
235         CTDB_NO_MEMORY(ctdb, state);
236
237         state->c = talloc_steal(ctdb, c);
238         state->sin = talloc(ctdb, struct sockaddr_in);       
239         CTDB_NO_MEMORY(ctdb, state->sin);
240         *state->sin = pip->sin;
241
242         state->vnn = vnn;
243
244         DEBUG(0,("Takeover of IP %s/%u on interface %s\n", 
245                  inet_ntoa(pip->sin.sin_addr), vnn->public_netmask_bits, 
246                  vnn->iface));
247
248         ctdb_stop_monitoring(ctdb);
249
250         ret = ctdb_event_script_callback(ctdb, 
251                                          timeval_current_ofs(ctdb->tunable.script_timeout, 0),
252                                          state, takeover_ip_callback, state,
253                                          "takeip %s %s %u",
254                                          vnn->iface, 
255                                          inet_ntoa(pip->sin.sin_addr),
256                                          vnn->public_netmask_bits);
257         if (ret != 0) {
258                 DEBUG(0,(__location__ " Failed to takeover IP %s on interface %s\n",
259                          inet_ntoa(pip->sin.sin_addr), vnn->iface));
260                 talloc_free(tmp_ctx);
261                 talloc_free(state);
262                 return -1;
263         }
264
265         /* tell ctdb_control.c that we will be replying asynchronously */
266         *async_reply = true;
267
268         talloc_free(tmp_ctx);
269         return 0;
270 }
271
272 /*
273   kill any clients that are registered with a IP that is being released
274  */
275 static void release_kill_clients(struct ctdb_context *ctdb, struct sockaddr_in in)
276 {
277         struct ctdb_client_ip *ip;
278
279         for (ip=ctdb->client_ip_list; ip; ip=ip->next) {
280                 if (ctdb_same_ip(&ip->ip, &in)) {
281                         struct ctdb_client *client = ctdb_reqid_find(ctdb, 
282                                                                      ip->client_id, 
283                                                                      struct ctdb_client);
284                         if (client->pid != 0) {
285                                 DEBUG(0,(__location__ " Killing client pid %u for IP %s on client_id %u\n",
286                                          (unsigned)client->pid, inet_ntoa(in.sin_addr),
287                                          ip->client_id));
288                                 kill(client->pid, SIGKILL);
289                         }
290                 }
291         }
292 }
293
294 /*
295   called when releaseip event finishes
296  */
297 static void release_ip_callback(struct ctdb_context *ctdb, int status, 
298                                 void *private_data)
299 {
300         struct takeover_callback_state *state = 
301                 talloc_get_type(private_data, struct takeover_callback_state);
302         char *ip = inet_ntoa(state->sin->sin_addr);
303         TDB_DATA data;
304
305         ctdb_start_monitoring(ctdb);
306
307         /* send a message to all clients of this node telling them
308            that the cluster has been reconfigured and they should
309            release any sockets on this IP */
310         data.dptr = (uint8_t *)ip;
311         data.dsize = strlen(ip)+1;
312
313         ctdb_daemon_send_message(ctdb, ctdb->pnn, CTDB_SRVID_RELEASE_IP, data);
314
315         /* kill clients that have registered with this IP */
316         release_kill_clients(ctdb, *state->sin);
317         
318         /* the control succeeded */
319         ctdb_request_control_reply(ctdb, state->c, NULL, 0, NULL);
320         talloc_free(state);
321 }
322
323 /*
324   release an ip address
325  */
326 int32_t ctdb_control_release_ip(struct ctdb_context *ctdb, 
327                                 struct ctdb_req_control *c,
328                                 TDB_DATA indata, 
329                                 bool *async_reply)
330 {
331         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
332         int ret;
333         struct takeover_callback_state *state;
334         struct ctdb_public_ip *pip = (struct ctdb_public_ip *)indata.dptr;
335         struct ctdb_vnn *vnn;
336         bool have_ip, is_loopback;
337         char *ifname = NULL;
338
339         /* update our vnn list */
340         vnn = find_public_ip_vnn(ctdb, pip->sin);
341         if (vnn == NULL) {
342                 DEBUG(0,("releaseip called for an ip '%s' that is not a public address\n", 
343                          inet_ntoa(pip->sin.sin_addr)));
344                 talloc_free(tmp_ctx);
345                 return 0;
346         }
347         vnn->pnn = pip->pnn;
348
349         have_ip = ctdb_sys_have_ip(pip->sin, &is_loopback, tmp_ctx, &ifname);
350         if ( (!have_ip) || is_loopback) { 
351                 DEBUG(0,("Redundant release of IP %s/%u on interface %s (ip not held)\n", 
352                          inet_ntoa(pip->sin.sin_addr), vnn->public_netmask_bits, 
353                          vnn->iface));
354                 talloc_free(tmp_ctx);
355                 return 0;
356         }
357
358         DEBUG(0,("Release of IP %s/%u on interface %s\n", 
359                  inet_ntoa(pip->sin.sin_addr), vnn->public_netmask_bits, 
360                  vnn->iface));
361
362         /* stop any previous arps */
363         talloc_free(vnn->takeover_ctx);
364         vnn->takeover_ctx = NULL;
365
366         state = talloc(ctdb, struct takeover_callback_state);
367         CTDB_NO_MEMORY(ctdb, state);
368
369         state->c = talloc_steal(state, c);
370         state->sin = talloc(state, struct sockaddr_in);       
371         CTDB_NO_MEMORY(ctdb, state->sin);
372         *state->sin = pip->sin;
373
374         state->vnn = vnn;
375
376         ctdb_stop_monitoring(ctdb);
377
378         ret = ctdb_event_script_callback(ctdb, 
379                                          timeval_current_ofs(ctdb->tunable.script_timeout, 0),
380                                          state, release_ip_callback, state,
381                                          "releaseip %s %s %u",
382                                          vnn->iface, 
383                                          inet_ntoa(pip->sin.sin_addr),
384                                          vnn->public_netmask_bits);
385         if (ret != 0) {
386                 DEBUG(0,(__location__ " Failed to release IP %s on interface %s\n",
387                          inet_ntoa(pip->sin.sin_addr), vnn->iface));
388                 talloc_free(tmp_ctx);
389                 talloc_free(state);
390                 return -1;
391         }
392
393         /* tell the control that we will be reply asynchronously */
394         *async_reply = true;
395
396         talloc_free(tmp_ctx);
397         return 0;
398 }
399
400
401
402 static int add_public_address(struct ctdb_context *ctdb, struct sockaddr_in addr, unsigned mask, const char *iface)
403 {
404         struct ctdb_vnn      *vnn;
405
406         /* Verify that we dont have an entry for this ip yet */
407         for (vnn=ctdb->vnn;vnn;vnn=vnn->next) {
408                 if (ctdb_same_sockaddr(&addr, &vnn->public_address)) {
409                         DEBUG(0,("Same ip '%s' specified multiple times in the public address list \n", 
410                                  inet_ntoa(addr.sin_addr)));
411                         exit(1);
412                 }               
413         }
414
415         /* create a new vnn structure for this ip address */
416         vnn = talloc_zero(ctdb, struct ctdb_vnn);
417         CTDB_NO_MEMORY_FATAL(ctdb, vnn);
418         vnn->iface = talloc_strdup(vnn, iface);
419         vnn->public_address      = addr;
420         vnn->public_netmask_bits = mask;
421         vnn->pnn                 = -1;
422         
423         DLIST_ADD(ctdb->vnn, vnn);
424
425         return 0;
426 }
427
428
429 /*
430   setup the event script directory
431 */
432 int ctdb_set_event_script_dir(struct ctdb_context *ctdb, const char *script_dir)
433 {
434         ctdb->event_script_dir = talloc_strdup(ctdb, script_dir);
435         CTDB_NO_MEMORY(ctdb, ctdb->event_script_dir);
436         return 0;
437 }
438
439 /*
440   setup the public address lists from a file
441 */
442 int ctdb_set_public_addresses(struct ctdb_context *ctdb, const char *alist)
443 {
444         char **lines;
445         int nlines;
446         int i;
447
448         lines = file_lines_load(alist, &nlines, ctdb);
449         if (lines == NULL) {
450                 ctdb_set_error(ctdb, "Failed to load public address list '%s'\n", alist);
451                 return -1;
452         }
453         while (nlines > 0 && strcmp(lines[nlines-1], "") == 0) {
454                 nlines--;
455         }
456
457         for (i=0;i<nlines;i++) {
458                 unsigned mask;
459                 struct sockaddr_in addr;
460                 const char *iface;
461                 char *tok;
462
463                 tok = strtok(lines[i], " \t");
464                 if (!tok || !parse_ip_mask(tok, &addr, &mask)) {
465                         DEBUG(0,("Badly formed line %u in public address list\n", i+1));
466                         talloc_free(lines);
467                         return -1;
468                 }
469                 tok = strtok(NULL, " \t");
470                 if (tok == NULL) {
471                         if (NULL == ctdb->default_public_interface) {
472                                 DEBUG(0,("No default public interface and no interface specified at line %u of public address list\n",
473                                          i+1));
474                                 talloc_free(lines);
475                                 return -1;
476                         }
477                         iface = ctdb->default_public_interface;
478                 } else {
479                         iface = tok;
480                 }
481
482                 if (add_public_address(ctdb, addr, mask, iface)) {
483                         DEBUG(0,("Failed to add line %u to the public address list\n", i+1));
484                         talloc_free(lines);
485                         return -1;
486                 }
487         }
488
489         talloc_free(lines);
490         return 0;
491 }
492
493
494
495
496 struct ctdb_public_ip_list {
497         struct ctdb_public_ip_list *next;
498         uint32_t pnn;
499         struct sockaddr_in sin;
500 };
501
502
503 /* Given a physical node, return the number of
504    public addresses that is currently assigned to this node.
505 */
506 static int node_ip_coverage(struct ctdb_context *ctdb, 
507         int32_t pnn,
508         struct ctdb_public_ip_list *ips)
509 {
510         int num=0;
511
512         for (;ips;ips=ips->next) {
513                 if (ips->pnn == pnn) {
514                         num++;
515                 }
516         }
517         return num;
518 }
519
520
521 /* Check if this is a public ip known to the node, i.e. can that
522    node takeover this ip ?
523 */
524 static int can_node_serve_ip(struct ctdb_context *ctdb, int32_t pnn, 
525                 struct ctdb_public_ip_list *ip)
526 {
527         struct ctdb_all_public_ips *public_ips;
528         int i;
529
530         public_ips = ctdb->nodes[pnn]->public_ips;
531
532         if (public_ips == NULL) {
533                 return -1;
534         }
535
536         for (i=0;i<public_ips->num;i++) {
537                 if (ip->sin.sin_addr.s_addr == public_ips->ips[i].sin.sin_addr.s_addr) {
538                         /* yes, this node can serve this public ip */
539                         return 0;
540                 }
541         }
542
543         return -1;
544 }
545
546
547 /* search the node lists list for a node to takeover this ip.
548    pick the node that currently are serving the least number of ips
549    so that the ips get spread out evenly.
550 */
551 static int find_takeover_node(struct ctdb_context *ctdb, 
552                 struct ctdb_node_map *nodemap, uint32_t mask, 
553                 struct ctdb_public_ip_list *ip,
554                 struct ctdb_public_ip_list *all_ips)
555 {
556         int pnn, min=0, num;
557         int i;
558
559         pnn    = -1;
560         for (i=0;i<nodemap->num;i++) {
561                 if (nodemap->nodes[i].flags & mask) {
562                         /* This node is not healty and can not be used to serve
563                            a public address 
564                         */
565                         continue;
566                 }
567
568                 /* verify that this node can serve this ip */
569                 if (can_node_serve_ip(ctdb, i, ip)) {
570                         /* no it couldnt   so skip to the next node */
571                         continue;
572                 }
573
574                 num = node_ip_coverage(ctdb, i, all_ips);
575                 /* was this the first node we checked ? */
576                 if (pnn == -1) {
577                         pnn = i;
578                         min  = num;
579                 } else {
580                         if (num < min) {
581                                 pnn = i;
582                                 min  = num;
583                         }
584                 }
585         }       
586         if (pnn == -1) {
587                 DEBUG(0,(__location__ " Could not find node to take over public address '%s'\n", inet_ntoa(ip->sin.sin_addr)));
588                 return -1;
589         }
590
591         ip->pnn = pnn;
592         return 0;
593 }
594
595 struct ctdb_public_ip_list *
596 add_ip_to_merged_list(struct ctdb_context *ctdb,
597                         TALLOC_CTX *tmp_ctx, 
598                         struct ctdb_public_ip_list *ip_list, 
599                         struct ctdb_public_ip *ip)
600 {
601         struct ctdb_public_ip_list *tmp_ip; 
602
603         /* do we already have this ip in our merged list ?*/
604         for (tmp_ip=ip_list;tmp_ip;tmp_ip=tmp_ip->next) {
605
606                 /* we already  have this public ip in the list */
607                 if (tmp_ip->sin.sin_addr.s_addr == ip->sin.sin_addr.s_addr) {
608                         return ip_list;
609                 }
610         }
611
612         /* this is a new public ip, we must add it to the list */
613         tmp_ip = talloc_zero(tmp_ctx, struct ctdb_public_ip_list);
614         CTDB_NO_MEMORY_NULL(ctdb, tmp_ip);
615         tmp_ip->pnn  = ip->pnn;
616         tmp_ip->sin  = ip->sin;
617         tmp_ip->next = ip_list;
618
619         return tmp_ip;
620 }
621
622 struct ctdb_public_ip_list *
623 create_merged_ip_list(struct ctdb_context *ctdb, TALLOC_CTX *tmp_ctx)
624 {
625         int i, j;
626         struct ctdb_public_ip_list *ip_list = NULL;
627         struct ctdb_all_public_ips *public_ips;
628
629         for (i=0;i<ctdb->num_nodes;i++) {
630                 public_ips = ctdb->nodes[i]->public_ips;
631
632                 /* there were no public ips for this node */
633                 if (public_ips == NULL) {
634                         continue;
635                 }               
636
637                 for (j=0;j<public_ips->num;j++) {
638                         ip_list = add_ip_to_merged_list(ctdb, tmp_ctx,
639                                         ip_list, &public_ips->ips[j]);
640                 }
641         }
642
643         return ip_list;
644 }
645
646 /*
647   make any IP alias changes for public addresses that are necessary 
648  */
649 int ctdb_takeover_run(struct ctdb_context *ctdb, struct ctdb_node_map *nodemap)
650 {
651         int i, num_healthy, retries;
652         int ret;
653         struct ctdb_public_ip ip;
654         uint32_t mask;
655         struct ctdb_public_ip_list *all_ips, *tmp_ip;
656         int maxnode, maxnum=0, minnode, minnum=0, num;
657         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
658
659
660         ZERO_STRUCT(ip);
661
662         /* Count how many completely healthy nodes we have */
663         num_healthy = 0;
664         for (i=0;i<nodemap->num;i++) {
665                 if (!(nodemap->nodes[i].flags & (NODE_FLAGS_INACTIVE|NODE_FLAGS_DISABLED))) {
666                         num_healthy++;
667                 }
668         }
669
670         if (num_healthy > 0) {
671                 /* We have healthy nodes, so only consider them for 
672                    serving public addresses
673                 */
674                 mask = NODE_FLAGS_INACTIVE|NODE_FLAGS_DISABLED;
675         } else {
676                 /* We didnt have any completely healthy nodes so
677                    use "disabled" nodes as a fallback
678                 */
679                 mask = NODE_FLAGS_INACTIVE;
680         }
681
682         /* since nodes only know about those public addresses that
683            can be served by that particular node, no single node has
684            a full list of all public addresses that exist in the cluster.
685            Walk over all node structures and create a merged list of
686            all public addresses that exist in the cluster.
687         */
688         all_ips = create_merged_ip_list(ctdb, tmp_ctx);
689
690
691         /* mark all public addresses with a masked node as being served by
692            node -1
693         */
694         for (tmp_ip=all_ips;tmp_ip;tmp_ip=tmp_ip->next) {
695                 if (tmp_ip->pnn == -1) {
696                         continue;
697                 }
698                 if (nodemap->nodes[tmp_ip->pnn].flags & mask) {
699                         tmp_ip->pnn = -1;
700                 }
701         }
702
703
704         /* now we must redistribute all public addresses with takeover node
705            -1 among the nodes available
706         */
707         retries = 0;
708 try_again:
709         /* loop over all ip's and find a physical node to cover for 
710            each unassigned ip.
711         */
712         for (tmp_ip=all_ips;tmp_ip;tmp_ip=tmp_ip->next) {
713                 if (tmp_ip->pnn == -1) {
714                         if (find_takeover_node(ctdb, nodemap, mask, tmp_ip, all_ips)) {
715                                 DEBUG(0,("Failed to find node to cover ip %s\n", inet_ntoa(tmp_ip->sin.sin_addr)));
716                         }
717                 }
718         }
719
720
721         /* now, try to make sure the ip adresses are evenly distributed
722            across the node.
723            for each ip address, loop over all nodes that can serve this
724            ip and make sure that the difference between the node
725            serving the most and the node serving the least ip's are not greater
726            than 1.
727         */
728         for (tmp_ip=all_ips;tmp_ip;tmp_ip=tmp_ip->next) {
729                 if (tmp_ip->pnn == -1) {
730                         continue;
731                 }
732
733                 /* Get the highest and lowest number of ips's served by any 
734                    valid node which can serve this ip.
735                 */
736                 maxnode = -1;
737                 minnode = -1;
738                 for (i=0;i<nodemap->num;i++) {
739                         if (nodemap->nodes[i].flags & mask) {
740                                 continue;
741                         }
742
743                         /* only check nodes that can actually serve this ip */
744                         if (can_node_serve_ip(ctdb, i, tmp_ip)) {
745                                 /* no it couldnt   so skip to the next node */
746                                 continue;
747                         }
748
749                         num = node_ip_coverage(ctdb, i, all_ips);
750                         if (maxnode == -1) {
751                                 maxnode = i;
752                                 maxnum  = num;
753                         } else {
754                                 if (num > maxnum) {
755                                         maxnode = i;
756                                         maxnum  = num;
757                                 }
758                         }
759                         if (minnode == -1) {
760                                 minnode = i;
761                                 minnum  = num;
762                         } else {
763                                 if (num < minnum) {
764                                         minnode = i;
765                                         minnum  = num;
766                                 }
767                         }
768                 }
769                 if (maxnode == -1) {
770                         DEBUG(0,(__location__ " Could not find maxnode. May not be able to server ip '%s'\n", inet_ntoa(tmp_ip->sin.sin_addr)));
771                         continue;
772                 }
773
774                 /* if the spread between the smallest and largest coverage by
775                    a node is >=2 we steal one of the ips from the node with
776                    most coverage to even things out a bit.
777                    try to do this at most 5 times  since we dont want to spend
778                    too much time balancing the ip coverage.
779                 */
780                 if ( (maxnum > minnum+1)
781                   && (retries < 5) ){
782                         struct ctdb_public_ip_list *tmp;
783
784                         /* mark one of maxnode's vnn's as unassigned and try
785                            again
786                         */
787                         for (tmp=all_ips;tmp;tmp=tmp->next) {
788                                 if (tmp->pnn == maxnode) {
789                                         tmp->pnn = -1;
790                                         retries++;
791                                         goto try_again;
792                                 }
793                         }
794                 }
795         }
796
797
798
799         /* at this point ->pnn is the node which will own each IP
800            or -1 if there is no node that can cover this ip
801         */
802
803         /* now tell all nodes to delete any alias that they should not
804            have.  This will be a NOOP on nodes that don't currently
805            hold the given alias */
806         for (i=0;i<nodemap->num;i++) {
807                 /* don't talk to unconnected nodes, but do talk to banned nodes */
808                 if (nodemap->nodes[i].flags & NODE_FLAGS_DISCONNECTED) {
809                         continue;
810                 }
811
812                 for (tmp_ip=all_ips;tmp_ip;tmp_ip=tmp_ip->next) {
813                         if (tmp_ip->pnn == nodemap->nodes[i].pnn) {
814                                 /* This node should be serving this
815                                    vnn so dont tell it to release the ip
816                                 */
817                                 continue;
818                         }
819                         ip.pnn = tmp_ip->pnn;
820                         ip.sin.sin_family = AF_INET;
821                         ip.sin.sin_addr   = tmp_ip->sin.sin_addr;
822
823                         ret = ctdb_ctrl_release_ip(ctdb, TAKEOVER_TIMEOUT(),
824                                                    nodemap->nodes[i].pnn, 
825                                                    &ip);
826                         if (ret != 0) {
827                                 DEBUG(0,("Failed to tell vnn %u to release IP %s\n",
828                                          nodemap->nodes[i].pnn,
829                                          inet_ntoa(tmp_ip->sin.sin_addr)));
830                                 talloc_free(tmp_ctx);
831                                 return -1;
832                         }
833                 }
834         }
835
836
837         /* tell all nodes to get their own IPs */
838         for (tmp_ip=all_ips;tmp_ip;tmp_ip=tmp_ip->next) {
839                 if (tmp_ip->pnn == -1) {
840                         /* this IP won't be taken over */
841                         continue;
842                 }
843                 ip.pnn = tmp_ip->pnn;
844                 ip.sin.sin_family = AF_INET;
845                 ip.sin.sin_addr = tmp_ip->sin.sin_addr;
846
847                 ret = ctdb_ctrl_takeover_ip(ctdb, TAKEOVER_TIMEOUT(), 
848                                     tmp_ip->pnn, 
849                                     &ip);
850                 if (ret != 0) {
851                         DEBUG(0,("Failed asking vnn %u to take over IP %s\n",
852                                  tmp_ip->pnn, 
853                                  inet_ntoa(tmp_ip->sin.sin_addr)));
854                         talloc_free(tmp_ctx);
855                         return -1;
856                 }
857         }
858
859         talloc_free(tmp_ctx);
860         return 0;
861 }
862
863
864 /*
865   destroy a ctdb_client_ip structure
866  */
867 static int ctdb_client_ip_destructor(struct ctdb_client_ip *ip)
868 {
869         DLIST_REMOVE(ip->ctdb->client_ip_list, ip);
870         return 0;
871 }
872
873 /*
874   called by a client to inform us of a TCP connection that it is managing
875   that should tickled with an ACK when IP takeover is done
876  */
877 int32_t ctdb_control_tcp_client(struct ctdb_context *ctdb, uint32_t client_id,
878                                 TDB_DATA indata)
879 {
880         struct ctdb_client *client = ctdb_reqid_find(ctdb, client_id, struct ctdb_client);
881         struct ctdb_control_tcp *p = (struct ctdb_control_tcp *)indata.dptr;
882         struct ctdb_tcp_list *tcp;
883         struct ctdb_control_tcp_vnn t;
884         int ret;
885         TDB_DATA data;
886         struct ctdb_client_ip *ip;
887         struct ctdb_vnn *vnn;
888
889         vnn = find_public_ip_vnn(ctdb, p->dest);
890         if (vnn == NULL) {
891                 DEBUG(3,("Could not add client IP %s. This is not a public address.\n", inet_ntoa(p->dest.sin_addr))); 
892                 return 0;
893         }
894
895         ip = talloc(client, struct ctdb_client_ip);
896         CTDB_NO_MEMORY(ctdb, ip);
897
898         ip->ctdb = ctdb;
899         ip->ip = p->dest;
900         ip->client_id = client_id;
901         talloc_set_destructor(ip, ctdb_client_ip_destructor);
902         DLIST_ADD(ctdb->client_ip_list, ip);
903
904         tcp = talloc(client, struct ctdb_tcp_list);
905         CTDB_NO_MEMORY(ctdb, tcp);
906
907         tcp->connection.saddr = p->src;
908         tcp->connection.daddr = p->dest;
909
910         DLIST_ADD(client->tcp_list, tcp);
911
912         t.src  = p->src;
913         t.dest = p->dest;
914
915         data.dptr = (uint8_t *)&t;
916         data.dsize = sizeof(t);
917
918         DEBUG(2,("registered tcp client for %u->%s:%u\n",
919                  (unsigned)ntohs(p->dest.sin_port), 
920                  inet_ntoa(p->src.sin_addr),
921                  (unsigned)ntohs(p->src.sin_port)));
922
923         /* tell all nodes about this tcp connection */
924         ret = ctdb_daemon_send_control(ctdb, CTDB_BROADCAST_CONNECTED, 0, 
925                                        CTDB_CONTROL_TCP_ADD,
926                                        0, CTDB_CTRL_FLAG_NOREPLY, data, NULL, NULL);
927         if (ret != 0) {
928                 DEBUG(0,(__location__ " Failed to send CTDB_CONTROL_TCP_ADD\n"));
929                 return -1;
930         }
931
932         return 0;
933 }
934
935 /*
936   see if two sockaddr_in are the same
937  */
938 static bool same_sockaddr_in(struct sockaddr_in *in1, struct sockaddr_in *in2)
939 {
940         return in1->sin_family == in2->sin_family &&
941                 in1->sin_port == in2->sin_port &&
942                 in1->sin_addr.s_addr == in2->sin_addr.s_addr;
943 }
944
945 /*
946   find a tcp address on a list
947  */
948 static struct ctdb_tcp_connection *ctdb_tcp_find(struct ctdb_tcp_array *array, 
949                                            struct ctdb_tcp_connection *tcp)
950 {
951         int i;
952
953         if (array == NULL) {
954                 return NULL;
955         }
956
957         for (i=0;i<array->num;i++) {
958                 if (same_sockaddr_in(&array->connections[i].saddr, &tcp->saddr) &&
959                     same_sockaddr_in(&array->connections[i].daddr, &tcp->daddr)) {
960                         return &array->connections[i];
961                 }
962         }
963         return NULL;
964 }
965
966 /*
967   called by a daemon to inform us of a TCP connection that one of its
968   clients managing that should tickled with an ACK when IP takeover is
969   done
970  */
971 int32_t ctdb_control_tcp_add(struct ctdb_context *ctdb, TDB_DATA indata)
972 {
973         struct ctdb_control_tcp_vnn *p = (struct ctdb_control_tcp_vnn *)indata.dptr;
974         struct ctdb_tcp_array *tcparray;
975         struct ctdb_tcp_connection tcp;
976         struct ctdb_vnn *vnn;
977
978         vnn = find_public_ip_vnn(ctdb, p->dest);
979         if (vnn == NULL) {
980                 DEBUG(0,(__location__ " got TCP_ADD control for an address which is not a public address '%s'\n", 
981                          inet_ntoa(p->dest.sin_addr)));
982                 return-1;
983         }
984
985
986         tcparray = vnn->tcp_array;
987
988         /* If this is the first tickle */
989         if (tcparray == NULL) {
990                 tcparray = talloc_size(ctdb->nodes, 
991                         offsetof(struct ctdb_tcp_array, connections) +
992                         sizeof(struct ctdb_tcp_connection) * 1);
993                 CTDB_NO_MEMORY(ctdb, tcparray);
994                 vnn->tcp_array = tcparray;
995
996                 tcparray->num = 0;
997                 tcparray->connections = talloc_size(tcparray, sizeof(struct ctdb_tcp_connection));
998                 CTDB_NO_MEMORY(ctdb, tcparray->connections);
999
1000                 tcparray->connections[tcparray->num].saddr = p->src;
1001                 tcparray->connections[tcparray->num].daddr = p->dest;
1002                 tcparray->num++;
1003                 return 0;
1004         }
1005
1006
1007         /* Do we already have this tickle ?*/
1008         tcp.saddr = p->src;
1009         tcp.daddr = p->dest;
1010         if (ctdb_tcp_find(vnn->tcp_array, &tcp) != NULL) {
1011                 DEBUG(4,("Already had tickle info for %s:%u for vnn:%u\n",
1012                          inet_ntoa(tcp.daddr.sin_addr),
1013                          ntohs(tcp.daddr.sin_port),
1014                          vnn->pnn));
1015                 return 0;
1016         }
1017
1018         /* A new tickle, we must add it to the array */
1019         tcparray->connections = talloc_realloc(tcparray, tcparray->connections,
1020                                         struct ctdb_tcp_connection,
1021                                         tcparray->num+1);
1022         CTDB_NO_MEMORY(ctdb, tcparray->connections);
1023
1024         vnn->tcp_array = tcparray;
1025         tcparray->connections[tcparray->num].saddr = p->src;
1026         tcparray->connections[tcparray->num].daddr = p->dest;
1027         tcparray->num++;
1028                                 
1029         DEBUG(2,("Added tickle info for %s:%u from vnn %u\n",
1030                  inet_ntoa(tcp.daddr.sin_addr),
1031                  ntohs(tcp.daddr.sin_port),
1032                  vnn->pnn));
1033
1034         return 0;
1035 }
1036
1037
1038 /*
1039   called by a daemon to inform us of a TCP connection that one of its
1040   clients managing that should tickled with an ACK when IP takeover is
1041   done
1042  */
1043 static void ctdb_remove_tcp_connection(struct ctdb_context *ctdb, struct ctdb_tcp_connection *conn)
1044 {
1045         struct ctdb_tcp_connection *tcpp;
1046         struct ctdb_vnn *vnn = find_public_ip_vnn(ctdb, conn->daddr);
1047
1048         if (vnn == NULL) {
1049                 DEBUG(0,(__location__ " unable to find public address %s\n", inet_ntoa(conn->daddr.sin_addr)));
1050                 return;
1051         }
1052
1053         /* if the array is empty we cant remove it
1054            and we dont need to do anything
1055          */
1056         if (vnn->tcp_array == NULL) {
1057                 DEBUG(2,("Trying to remove tickle that doesnt exist (array is empty) %s:%u\n",
1058                          inet_ntoa(conn->daddr.sin_addr),
1059                          ntohs(conn->daddr.sin_port)));
1060                 return;
1061         }
1062
1063
1064         /* See if we know this connection
1065            if we dont know this connection  then we dont need to do anything
1066          */
1067         tcpp = ctdb_tcp_find(vnn->tcp_array, conn);
1068         if (tcpp == NULL) {
1069                 DEBUG(2,("Trying to remove tickle that doesnt exist %s:%u\n",
1070                          inet_ntoa(conn->daddr.sin_addr),
1071                          ntohs(conn->daddr.sin_port)));
1072                 return;
1073         }
1074
1075
1076         /* We need to remove this entry from the array.
1077            Instead of allocating a new array and copying data to it
1078            we cheat and just copy the last entry in the existing array
1079            to the entry that is to be removed and just shring the 
1080            ->num field
1081          */
1082         *tcpp = vnn->tcp_array->connections[vnn->tcp_array->num - 1];
1083         vnn->tcp_array->num--;
1084
1085         /* If we deleted the last entry we also need to remove the entire array
1086          */
1087         if (vnn->tcp_array->num == 0) {
1088                 talloc_free(vnn->tcp_array);
1089                 vnn->tcp_array = NULL;
1090         }               
1091
1092         vnn->tcp_update_needed = true;
1093
1094         DEBUG(2,("Removed tickle info for %s:%u\n",
1095                  inet_ntoa(conn->saddr.sin_addr),
1096                  ntohs(conn->saddr.sin_port)));
1097 }
1098
1099
1100 /*
1101   called when a daemon restarts - send all tickes for all public addresses
1102   we are serving immediately to the new node.
1103  */
1104 int32_t ctdb_control_startup(struct ctdb_context *ctdb, uint32_t vnn)
1105 {
1106 /*XXX here we should send all tickes we are serving to the new node */
1107         return 0;
1108 }
1109
1110
1111 /*
1112   called when a client structure goes away - hook to remove
1113   elements from the tcp_list in all daemons
1114  */
1115 void ctdb_takeover_client_destructor_hook(struct ctdb_client *client)
1116 {
1117         while (client->tcp_list) {
1118                 struct ctdb_tcp_list *tcp = client->tcp_list;
1119                 DLIST_REMOVE(client->tcp_list, tcp);
1120                 ctdb_remove_tcp_connection(client->ctdb, &tcp->connection);
1121         }
1122 }
1123
1124
1125 /*
1126   release all IPs on shutdown
1127  */
1128 void ctdb_release_all_ips(struct ctdb_context *ctdb)
1129 {
1130         struct ctdb_vnn *vnn;
1131         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1132         bool have_ip, is_loopback;
1133         char *ifname = NULL;
1134
1135         for (vnn=ctdb->vnn;vnn;vnn=vnn->next) {
1136                 have_ip = ctdb_sys_have_ip(vnn->public_address, &is_loopback, tmp_ctx, &ifname);
1137                 if (have_ip && !is_loopback) {
1138                         ctdb_event_script(ctdb, "releaseip %s %s %u",
1139                                           vnn->iface, 
1140                                           inet_ntoa(vnn->public_address.sin_addr),
1141                                           vnn->public_netmask_bits);
1142                         release_kill_clients(ctdb, vnn->public_address);
1143                 }
1144         }
1145         talloc_free(tmp_ctx);
1146 }
1147
1148
1149 /*
1150   get list of public IPs
1151  */
1152 int32_t ctdb_control_get_public_ips(struct ctdb_context *ctdb, 
1153                                     struct ctdb_req_control *c, TDB_DATA *outdata)
1154 {
1155         int i, num, len;
1156         struct ctdb_all_public_ips *ips;
1157         struct ctdb_vnn *vnn;
1158
1159         /* count how many public ip structures we have */
1160         num = 0;
1161         for (vnn=ctdb->vnn;vnn;vnn=vnn->next) {
1162                 num++;
1163         }
1164
1165         len = offsetof(struct ctdb_all_public_ips, ips) + 
1166                 num*sizeof(struct ctdb_public_ip);
1167         ips = talloc_zero_size(outdata, len);
1168         CTDB_NO_MEMORY(ctdb, ips);
1169
1170         outdata->dsize = len;
1171         outdata->dptr  = (uint8_t *)ips;
1172
1173         ips->num = num;
1174         i = 0;
1175         for (vnn=ctdb->vnn;vnn;vnn=vnn->next) {
1176                 ips->ips[i].pnn = vnn->pnn;
1177                 ips->ips[i].sin = vnn->public_address;
1178                 i++;
1179         }
1180
1181         return 0;
1182 }
1183
1184
1185
1186 /* 
1187    structure containing the listening socket and the list of tcp connections
1188    that the ctdb daemon is to kill
1189 */
1190 struct ctdb_kill_tcp {
1191         struct ctdb_vnn *vnn;
1192         struct ctdb_context *ctdb;
1193         int capture_fd;
1194         int sending_fd;
1195         struct fd_event *fde;
1196         trbt_tree_t *connections;
1197         void *private_data;
1198 };
1199
1200 /*
1201   a tcp connection that is to be killed
1202  */
1203 struct ctdb_killtcp_con {
1204         struct sockaddr_in src;
1205         struct sockaddr_in dst;
1206         int count;
1207         struct ctdb_kill_tcp *killtcp;
1208 };
1209
1210 /* this function is used to create a key to represent this socketpair
1211    in the killtcp tree.
1212    this key is used to insert and lookup matching socketpairs that are
1213    to be tickled and RST
1214 */
1215 #define KILLTCP_KEYLEN  4
1216 static uint32_t *killtcp_key(struct sockaddr_in *src, struct sockaddr_in *dst)
1217 {
1218         static uint32_t key[KILLTCP_KEYLEN];
1219
1220         key[0]  = dst->sin_addr.s_addr;
1221         key[1]  = src->sin_addr.s_addr;
1222         key[2]  = dst->sin_port;
1223         key[3]  = src->sin_port;
1224
1225         return key;
1226 }
1227
1228 /*
1229   called when we get a read event on the raw socket
1230  */
1231 static void capture_tcp_handler(struct event_context *ev, struct fd_event *fde, 
1232                                 uint16_t flags, void *private_data)
1233 {
1234         struct ctdb_kill_tcp *killtcp = talloc_get_type(private_data, struct ctdb_kill_tcp);
1235         struct ctdb_killtcp_con *con;
1236         struct sockaddr_in src, dst;
1237         uint32_t ack_seq, seq;
1238
1239         if (!(flags & EVENT_FD_READ)) {
1240                 return;
1241         }
1242
1243         if (ctdb_sys_read_tcp_packet(killtcp->capture_fd,
1244                                 killtcp->private_data,
1245                                 &src, &dst,
1246                                 &ack_seq, &seq) != 0) {
1247                 /* probably a non-tcp ACK packet */
1248                 return;
1249         }
1250
1251         /* check if we have this guy in our list of connections
1252            to kill
1253         */
1254         con = trbt_lookuparray32(killtcp->connections, 
1255                         KILLTCP_KEYLEN, killtcp_key(&src, &dst));
1256         if (con == NULL) {
1257                 /* no this was some other packet we can just ignore */
1258                 return;
1259         }
1260
1261         /* This one has been tickled !
1262            now reset him and remove him from the list.
1263          */
1264         DEBUG(1, ("sending a tcp reset to kill connection :%d -> %s:%d\n", ntohs(con->dst.sin_port), inet_ntoa(con->src.sin_addr), ntohs(con->src.sin_port)));
1265
1266         ctdb_sys_send_tcp(killtcp->sending_fd, &con->dst, 
1267                           &con->src, ack_seq, seq, 1);
1268         talloc_free(con);
1269 }
1270
1271
1272 /* when traversing the list of all tcp connections to send tickle acks to
1273    (so that we can capture the ack coming back and kill the connection
1274     by a RST)
1275    this callback is called for each connection we are currently trying to kill
1276 */
1277 static void tickle_connection_traverse(void *param, void *data)
1278 {
1279         struct ctdb_killtcp_con *con = talloc_get_type(data, struct ctdb_killtcp_con);
1280         struct ctdb_kill_tcp *killtcp = talloc_get_type(param, struct ctdb_kill_tcp);
1281
1282         /* have tried too many times, just give up */
1283         if (con->count >= 5) {
1284                 talloc_free(con);
1285                 return;
1286         }
1287
1288         /* othervise, try tickling it again */
1289         con->count++;
1290         ctdb_sys_send_tcp(killtcp->sending_fd, &con->dst, &con->src, 0, 0, 0);
1291 }
1292
1293
1294 /* 
1295    called every second until all sentenced connections have been reset
1296  */
1297 static void ctdb_tickle_sentenced_connections(struct event_context *ev, struct timed_event *te, 
1298                                               struct timeval t, void *private_data)
1299 {
1300         struct ctdb_kill_tcp *killtcp = talloc_get_type(private_data, struct ctdb_kill_tcp);
1301
1302
1303         /* loop over all connections sending tickle ACKs */
1304         trbt_traversearray32(killtcp->connections, KILLTCP_KEYLEN, tickle_connection_traverse, killtcp);
1305
1306
1307         /* If there are no more connections to kill we can remove the
1308            entire killtcp structure
1309          */
1310         if ( (killtcp->connections == NULL) || 
1311              (killtcp->connections->root == NULL) ) {
1312                 talloc_free(killtcp);
1313                 return;
1314         }
1315
1316         /* try tickling them again in a seconds time
1317          */
1318         event_add_timed(killtcp->ctdb->ev, killtcp, timeval_current_ofs(1, 0), 
1319                         ctdb_tickle_sentenced_connections, killtcp);
1320 }
1321
1322 /*
1323   destroy the killtcp structure
1324  */
1325 static int ctdb_killtcp_destructor(struct ctdb_kill_tcp *killtcp)
1326 {
1327         if (killtcp->sending_fd != -1) {
1328                 close(killtcp->sending_fd);
1329                 killtcp->sending_fd = -1;
1330         }
1331         killtcp->vnn->killtcp = NULL;
1332         return 0;
1333 }
1334
1335
1336 /* nothing fancy here, just unconditionally replace any existing
1337    connection structure with the new one.
1338
1339    dont even free the old one if it did exist, that one is talloc_stolen
1340    by the same node in the tree anyway and will be deleted when the new data 
1341    is deleted
1342 */
1343 static void *add_killtcp_callback(void *parm, void *data)
1344 {
1345         return parm;
1346 }
1347
1348 /*
1349   add a tcp socket to the list of connections we want to RST
1350  */
1351 static int ctdb_killtcp_add_connection(struct ctdb_context *ctdb, 
1352                                        struct sockaddr_in *src, struct sockaddr_in *dst)
1353 {
1354         struct ctdb_kill_tcp *killtcp;
1355         struct ctdb_killtcp_con *con;
1356         struct ctdb_vnn *vnn;
1357
1358         vnn = find_public_ip_vnn(ctdb, *dst);
1359         if (vnn == NULL) {
1360                 vnn = find_public_ip_vnn(ctdb, *src);
1361         }
1362         if (vnn == NULL) {
1363                 DEBUG(0,(__location__ " Could not killtcp, not a public address\n")); 
1364                 return -1;
1365         }
1366
1367         killtcp = vnn->killtcp;
1368         
1369         /* If this is the first connection to kill we must allocate
1370            a new structure
1371          */
1372         if (killtcp == NULL) {
1373                 killtcp = talloc_zero(ctdb, struct ctdb_kill_tcp);
1374                 CTDB_NO_MEMORY(ctdb, killtcp);
1375
1376                 killtcp->vnn         = vnn;
1377                 killtcp->ctdb        = ctdb;
1378                 killtcp->capture_fd  = -1;
1379                 killtcp->sending_fd  = -1;
1380                 killtcp->connections = trbt_create(killtcp, 0);
1381
1382                 vnn->killtcp         = killtcp;
1383                 talloc_set_destructor(killtcp, ctdb_killtcp_destructor);
1384         }
1385
1386
1387
1388         /* create a structure that describes this connection we want to
1389            RST and store it in killtcp->connections
1390         */
1391         con = talloc(killtcp, struct ctdb_killtcp_con);
1392         CTDB_NO_MEMORY(ctdb, con);
1393         con->src     = *src;
1394         con->dst     = *dst;
1395         con->count   = 0;
1396         con->killtcp = killtcp;
1397
1398
1399         trbt_insertarray32_callback(killtcp->connections,
1400                         KILLTCP_KEYLEN, killtcp_key(&con->dst, &con->src),
1401                         add_killtcp_callback, con);
1402
1403         /* 
1404            If we dont have a socket to send from yet we must create it
1405          */
1406         if (killtcp->sending_fd == -1) {
1407                 killtcp->sending_fd = ctdb_sys_open_sending_socket();
1408                 if (killtcp->sending_fd == -1) {
1409                         DEBUG(0,(__location__ " Failed to open sending socket for killtcp\n"));
1410                         goto failed;
1411                 }
1412         }
1413
1414         /* 
1415            If we dont have a socket to listen on yet we must create it
1416          */
1417         if (killtcp->capture_fd == -1) {
1418                 killtcp->capture_fd = ctdb_sys_open_capture_socket(vnn->iface, &killtcp->private_data);
1419                 if (killtcp->capture_fd == -1) {
1420                         DEBUG(0,(__location__ " Failed to open capturing socket for killtcp\n"));
1421                         goto failed;
1422                 }
1423         }
1424
1425
1426         if (killtcp->fde == NULL) {
1427                 killtcp->fde = event_add_fd(ctdb->ev, killtcp, killtcp->capture_fd, 
1428                                             EVENT_FD_READ | EVENT_FD_AUTOCLOSE, 
1429                                             capture_tcp_handler, killtcp);
1430
1431                 /* We also need to set up some events to tickle all these connections
1432                    until they are all reset
1433                 */
1434                 event_add_timed(ctdb->ev, killtcp, timeval_current_ofs(1, 0), 
1435                                 ctdb_tickle_sentenced_connections, killtcp);
1436         }
1437
1438         /* tickle him once now */
1439         ctdb_sys_send_tcp(killtcp->sending_fd, &con->dst, &con->src, 0, 0, 0);
1440
1441         return 0;
1442
1443 failed:
1444         talloc_free(vnn->killtcp);
1445         vnn->killtcp = NULL;
1446         return -1;
1447 }
1448
1449 /*
1450   kill a TCP connection.
1451  */
1452 int32_t ctdb_control_kill_tcp(struct ctdb_context *ctdb, TDB_DATA indata)
1453 {
1454         struct ctdb_control_killtcp *killtcp = (struct ctdb_control_killtcp *)indata.dptr;
1455
1456         return ctdb_killtcp_add_connection(ctdb, &killtcp->src, &killtcp->dst);
1457 }
1458
1459 /*
1460   called by a daemon to inform us of the entire list of TCP tickles for
1461   a particular public address.
1462   this control should only be sent by the node that is currently serving
1463   that public address.
1464  */
1465 int32_t ctdb_control_set_tcp_tickle_list(struct ctdb_context *ctdb, TDB_DATA indata)
1466 {
1467         struct ctdb_control_tcp_tickle_list *list = (struct ctdb_control_tcp_tickle_list *)indata.dptr;
1468         struct ctdb_tcp_array *tcparray;
1469         struct ctdb_vnn *vnn;
1470
1471         /* We must at least have tickles.num or else we cant verify the size
1472            of the received data blob
1473          */
1474         if (indata.dsize < offsetof(struct ctdb_control_tcp_tickle_list, 
1475                                         tickles.connections)) {
1476                 DEBUG(0,("Bad indata in ctdb_control_set_tcp_tickle_list. Not enough data for the tickle.num field\n"));
1477                 return -1;
1478         }
1479
1480         /* verify that the size of data matches what we expect */
1481         if (indata.dsize < offsetof(struct ctdb_control_tcp_tickle_list, 
1482                                 tickles.connections)
1483                          + sizeof(struct ctdb_tcp_connection)
1484                                  * list->tickles.num) {
1485                 DEBUG(0,("Bad indata in ctdb_control_set_tcp_tickle_list\n"));
1486                 return -1;
1487         }       
1488
1489         vnn = find_public_ip_vnn(ctdb, list->ip);
1490         if (vnn == NULL) {
1491                 DEBUG(0,(__location__ " Could not set tcp tickle list, '%s' is not a public address\n", 
1492                          inet_ntoa(list->ip.sin_addr))); 
1493                 return 1;
1494         }
1495
1496         /* remove any old ticklelist we might have */
1497         talloc_free(vnn->tcp_array);
1498         vnn->tcp_array = NULL;
1499
1500         tcparray = talloc(ctdb->nodes, struct ctdb_tcp_array);
1501         CTDB_NO_MEMORY(ctdb, tcparray);
1502
1503         tcparray->num = list->tickles.num;
1504
1505         tcparray->connections = talloc_array(tcparray, struct ctdb_tcp_connection, tcparray->num);
1506         CTDB_NO_MEMORY(ctdb, tcparray->connections);
1507
1508         memcpy(tcparray->connections, &list->tickles.connections[0], 
1509                sizeof(struct ctdb_tcp_connection)*tcparray->num);
1510
1511         /* We now have a new fresh tickle list array for this vnn */
1512         vnn->tcp_array = talloc_steal(vnn, tcparray);
1513         
1514         return 0;
1515 }
1516
1517 /*
1518   called to return the full list of tickles for the puclic address associated 
1519   with the provided vnn
1520  */
1521 int32_t ctdb_control_get_tcp_tickle_list(struct ctdb_context *ctdb, TDB_DATA indata, TDB_DATA *outdata)
1522 {
1523         struct sockaddr_in *ip = (struct sockaddr_in *)indata.dptr;
1524         struct ctdb_control_tcp_tickle_list *list;
1525         struct ctdb_tcp_array *tcparray;
1526         int num;
1527         struct ctdb_vnn *vnn;
1528
1529         vnn = find_public_ip_vnn(ctdb, *ip);
1530         if (vnn == NULL) {
1531                 DEBUG(0,(__location__ " Could not get tcp tickle list, '%s' is not a public address\n", 
1532                          inet_ntoa(ip->sin_addr))); 
1533                 return 1;
1534         }
1535
1536         tcparray = vnn->tcp_array;
1537         if (tcparray) {
1538                 num = tcparray->num;
1539         } else {
1540                 num = 0;
1541         }
1542
1543         outdata->dsize = offsetof(struct ctdb_control_tcp_tickle_list, 
1544                                 tickles.connections)
1545                         + sizeof(struct ctdb_tcp_connection) * num;
1546
1547         outdata->dptr  = talloc_size(outdata, outdata->dsize);
1548         CTDB_NO_MEMORY(ctdb, outdata->dptr);
1549         list = (struct ctdb_control_tcp_tickle_list *)outdata->dptr;
1550
1551         list->ip = *ip;
1552         list->tickles.num = num;
1553         if (num) {
1554                 memcpy(&list->tickles.connections[0], tcparray->connections, 
1555                         sizeof(struct ctdb_tcp_connection) * num);
1556         }
1557
1558         return 0;
1559 }
1560
1561
1562 /*
1563   set the list of all tcp tickles for a public address
1564  */
1565 static int ctdb_ctrl_set_tcp_tickles(struct ctdb_context *ctdb, 
1566                               struct timeval timeout, uint32_t destnode, 
1567                               struct sockaddr_in *ip,
1568                               struct ctdb_tcp_array *tcparray)
1569 {
1570         int ret, num;
1571         TDB_DATA data;
1572         struct ctdb_control_tcp_tickle_list *list;
1573
1574         if (tcparray) {
1575                 num = tcparray->num;
1576         } else {
1577                 num = 0;
1578         }
1579
1580         data.dsize = offsetof(struct ctdb_control_tcp_tickle_list, 
1581                                 tickles.connections) +
1582                         sizeof(struct ctdb_tcp_connection) * num;
1583         data.dptr = talloc_size(ctdb, data.dsize);
1584         CTDB_NO_MEMORY(ctdb, data.dptr);
1585
1586         list = (struct ctdb_control_tcp_tickle_list *)data.dptr;
1587         list->ip = *ip;
1588         list->tickles.num = num;
1589         if (tcparray) {
1590                 memcpy(&list->tickles.connections[0], tcparray->connections, sizeof(struct ctdb_tcp_connection) * num);
1591         }
1592
1593         ret = ctdb_daemon_send_control(ctdb, CTDB_BROADCAST_CONNECTED, 0, 
1594                                        CTDB_CONTROL_SET_TCP_TICKLE_LIST,
1595                                        0, CTDB_CTRL_FLAG_NOREPLY, data, NULL, NULL);
1596         if (ret != 0) {
1597                 DEBUG(0,(__location__ " ctdb_control for set tcp tickles failed\n"));
1598                 return -1;
1599         }
1600
1601         talloc_free(data.dptr);
1602
1603         return ret;
1604 }
1605
1606
1607 /*
1608   perform tickle updates if required
1609  */
1610 static void ctdb_update_tcp_tickles(struct event_context *ev, 
1611                                 struct timed_event *te, 
1612                                 struct timeval t, void *private_data)
1613 {
1614         struct ctdb_context *ctdb = talloc_get_type(private_data, struct ctdb_context);
1615         int ret;
1616         struct ctdb_vnn *vnn;
1617
1618         for (vnn=ctdb->vnn;vnn;vnn=vnn->next) {
1619                 /* we only send out updates for public addresses that 
1620                    we have taken over
1621                  */
1622                 if (ctdb->pnn != vnn->pnn) {
1623                         continue;
1624                 }
1625                 /* We only send out the updates if we need to */
1626                 if (!vnn->tcp_update_needed) {
1627                         continue;
1628                 }
1629                 ret = ctdb_ctrl_set_tcp_tickles(ctdb, 
1630                                 TAKEOVER_TIMEOUT(),
1631                                 CTDB_BROADCAST_CONNECTED,
1632                                 &vnn->public_address,
1633                                 vnn->tcp_array);
1634                 if (ret != 0) {
1635                         DEBUG(0,("Failed to send the tickle update for public address %s\n", 
1636                                  inet_ntoa(vnn->public_address.sin_addr)));
1637                 }
1638         }
1639
1640         event_add_timed(ctdb->ev, ctdb->tickle_update_context,
1641                              timeval_current_ofs(ctdb->tunable.tickle_update_interval, 0), 
1642                              ctdb_update_tcp_tickles, ctdb);
1643 }               
1644         
1645
1646 /*
1647   start periodic update of tcp tickles
1648  */
1649 void ctdb_start_tcp_tickle_update(struct ctdb_context *ctdb)
1650 {
1651         ctdb->tickle_update_context = talloc_new(ctdb);
1652
1653         event_add_timed(ctdb->ev, ctdb->tickle_update_context,
1654                              timeval_current_ofs(ctdb->tunable.tickle_update_interval, 0), 
1655                              ctdb_update_tcp_tickles, ctdb);
1656 }