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