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