3ff141b81c5a2b71407ffbc9be203c80d35c7245
[sahlberg/ctdb.git] / tools / ctdb.c
1 /* 
2    ctdb control tool
3
4    Copyright (C) Andrew Tridgell  2007
5    Copyright (C) Ronnie Sahlberg  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
21 #include "includes.h"
22 #include "lib/tevent/tevent.h"
23 #include "system/time.h"
24 #include "system/filesys.h"
25 #include "system/network.h"
26 #include "system/locale.h"
27 #include "popt.h"
28 #include "cmdline.h"
29 #include "../include/ctdb.h"
30 #include "../include/ctdb_client.h"
31 #include "../include/ctdb_private.h"
32 #include "../common/rb_tree.h"
33 #include "db_wrap.h"
34
35 #define ERR_TIMEOUT     20      /* timed out trying to reach node */
36 #define ERR_NONODE      21      /* node does not exist */
37 #define ERR_DISNODE     22      /* node is disconnected */
38
39 struct ctdb_connection *ctdb_connection;
40
41 static void usage(void);
42
43 static struct {
44         int timelimit;
45         uint32_t pnn;
46         int machinereadable;
47         int verbose;
48         int maxruntime;
49 } options;
50
51 #define TIMELIMIT() timeval_current_ofs(options.timelimit, 0)
52 #define LONGTIMELIMIT() timeval_current_ofs(options.timelimit*10, 0)
53
54 #ifdef CTDB_VERS
55 static int control_version(struct ctdb_context *ctdb, int argc, const char **argv)
56 {
57 #define STR(x) #x
58 #define XSTR(x) STR(x)
59         printf("CTDB version: %s\n", XSTR(CTDB_VERS));
60         return 0;
61 }
62 #endif
63
64
65 /*
66   verify that a node exists and is reachable
67  */
68 static void verify_node(struct ctdb_context *ctdb)
69 {
70         int ret;
71         struct ctdb_node_map *nodemap=NULL;
72
73         if (options.pnn == CTDB_CURRENT_NODE) {
74                 return;
75         }
76         if (options.pnn == CTDB_BROADCAST_ALL) {
77                 return;
78         }
79
80         /* verify the node exists */
81         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
82                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
83                 exit(10);
84         }
85         if (options.pnn >= nodemap->num) {
86                 DEBUG(DEBUG_ERR, ("Node %u does not exist\n", options.pnn));
87                 exit(ERR_NONODE);
88         }
89         if (nodemap->nodes[options.pnn].flags & NODE_FLAGS_DELETED) {
90                 DEBUG(DEBUG_ERR, ("Node %u is DELETED\n", options.pnn));
91                 exit(ERR_DISNODE);
92         }
93         if (nodemap->nodes[options.pnn].flags & NODE_FLAGS_DISCONNECTED) {
94                 DEBUG(DEBUG_ERR, ("Node %u is DISCONNECTED\n", options.pnn));
95                 exit(ERR_DISNODE);
96         }
97
98         /* verify we can access the node */
99         ret = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), options.pnn);
100         if (ret == -1) {
101                 DEBUG(DEBUG_ERR,("Can not access node. Node is not operational.\n"));
102                 exit(10);
103         }
104 }
105
106 /*
107  check if a database exists
108 */
109 static int db_exists(struct ctdb_context *ctdb, const char *db_name)
110 {
111         int i, ret;
112         struct ctdb_dbid_map *dbmap=NULL;
113
114         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, ctdb, &dbmap);
115         if (ret != 0) {
116                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n", options.pnn));
117                 return -1;
118         }
119
120         for(i=0;i<dbmap->num;i++){
121                 const char *name;
122
123                 ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &name);
124                 if (!strcmp(name, db_name)) {
125                         return 0;
126                 }
127         }
128
129         return -1;
130 }
131
132 /*
133   see if a process exists
134  */
135 static int control_process_exists(struct ctdb_context *ctdb, int argc, const char **argv)
136 {
137         uint32_t pnn, pid;
138         int ret;
139         if (argc < 1) {
140                 usage();
141         }
142
143         if (sscanf(argv[0], "%u:%u", &pnn, &pid) != 2) {
144                 DEBUG(DEBUG_ERR, ("Badly formed pnn:pid\n"));
145                 return -1;
146         }
147
148         ret = ctdb_ctrl_process_exists(ctdb, pnn, pid);
149         if (ret == 0) {
150                 printf("%u:%u exists\n", pnn, pid);
151         } else {
152                 printf("%u:%u does not exist\n", pnn, pid);
153         }
154         return ret;
155 }
156
157 /*
158   display statistics structure
159  */
160 static void show_statistics(struct ctdb_statistics *s, int show_header)
161 {
162         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
163         int i;
164         const char *prefix=NULL;
165         int preflen=0;
166         int tmp, days, hours, minutes, seconds;
167         const struct {
168                 const char *name;
169                 uint32_t offset;
170         } fields[] = {
171 #define STATISTICS_FIELD(n) { #n, offsetof(struct ctdb_statistics, n) }
172                 STATISTICS_FIELD(num_clients),
173                 STATISTICS_FIELD(frozen),
174                 STATISTICS_FIELD(recovering),
175                 STATISTICS_FIELD(num_recoveries),
176                 STATISTICS_FIELD(client_packets_sent),
177                 STATISTICS_FIELD(client_packets_recv),
178                 STATISTICS_FIELD(node_packets_sent),
179                 STATISTICS_FIELD(node_packets_recv),
180                 STATISTICS_FIELD(keepalive_packets_sent),
181                 STATISTICS_FIELD(keepalive_packets_recv),
182                 STATISTICS_FIELD(node.req_call),
183                 STATISTICS_FIELD(node.reply_call),
184                 STATISTICS_FIELD(node.req_dmaster),
185                 STATISTICS_FIELD(node.reply_dmaster),
186                 STATISTICS_FIELD(node.reply_error),
187                 STATISTICS_FIELD(node.req_message),
188                 STATISTICS_FIELD(node.req_control),
189                 STATISTICS_FIELD(node.reply_control),
190                 STATISTICS_FIELD(client.req_call),
191                 STATISTICS_FIELD(client.req_message),
192                 STATISTICS_FIELD(client.req_control),
193                 STATISTICS_FIELD(timeouts.call),
194                 STATISTICS_FIELD(timeouts.control),
195                 STATISTICS_FIELD(timeouts.traverse),
196                 STATISTICS_FIELD(total_calls),
197                 STATISTICS_FIELD(pending_calls),
198                 STATISTICS_FIELD(lockwait_calls),
199                 STATISTICS_FIELD(pending_lockwait_calls),
200                 STATISTICS_FIELD(childwrite_calls),
201                 STATISTICS_FIELD(pending_childwrite_calls),
202                 STATISTICS_FIELD(memory_used),
203                 STATISTICS_FIELD(max_hop_count),
204         };
205         tmp = s->statistics_current_time.tv_sec - s->statistics_start_time.tv_sec;
206         seconds = tmp%60;
207         tmp    /= 60;
208         minutes = tmp%60;
209         tmp    /= 60;
210         hours   = tmp%24;
211         tmp    /= 24;
212         days    = tmp;
213
214         if (options.machinereadable){
215                 if (show_header) {
216                         printf("CTDB version:");
217                         printf("Current time of statistics:");
218                         printf("Statistics collected since:");
219                         for (i=0;i<ARRAY_SIZE(fields);i++) {
220                                 printf("%s:", fields[i].name);
221                         }
222                         printf("num_reclock_ctdbd_latency:");
223                         printf("min_reclock_ctdbd_latency:");
224                         printf("avg_reclock_ctdbd_latency:");
225                         printf("max_reclock_ctdbd_latency:");
226
227                         printf("num_reclock_recd_latency:");
228                         printf("min_reclock_recd_latency:");
229                         printf("avg_reclock_recd_latency:");
230                         printf("max_reclock_recd_latency:");
231
232                         printf("num_call_latency:");
233                         printf("min_call_latency:");
234                         printf("avg_call_latency:");
235                         printf("max_call_latency:");
236
237                         printf("num_lockwait_latency:");
238                         printf("min_lockwait_latency:");
239                         printf("avg_lockwait_latency:");
240                         printf("max_lockwait_latency:");
241
242                         printf("num_childwrite_latency:");
243                         printf("min_childwrite_latency:");
244                         printf("avg_childwrite_latency:");
245                         printf("max_childwrite_latency:");
246                         printf("\n");
247                 }
248                 printf("%d:", CTDB_VERSION);
249                 printf("%d:", (int)s->statistics_current_time.tv_sec);
250                 printf("%d:", (int)s->statistics_start_time.tv_sec);
251                 for (i=0;i<ARRAY_SIZE(fields);i++) {
252                         printf("%d:", *(uint32_t *)(fields[i].offset+(uint8_t *)s));
253                 }
254                 printf("%d:", s->reclock.ctdbd.num);
255                 printf("%.6f:", s->reclock.ctdbd.min);
256                 printf("%.6f:", s->reclock.ctdbd.num?s->reclock.ctdbd.total/s->reclock.ctdbd.num:0.0);
257                 printf("%.6f:", s->reclock.ctdbd.max);
258
259                 printf("%d:", s->reclock.recd.num);
260                 printf("%.6f:", s->reclock.recd.min);
261                 printf("%.6f:", s->reclock.recd.num?s->reclock.recd.total/s->reclock.recd.num:0.0);
262                 printf("%.6f:", s->reclock.recd.max);
263
264                 printf("%d:", s->call_latency.num);
265                 printf("%.6f:", s->call_latency.min);
266                 printf("%.6f:", s->call_latency.num?s->call_latency.total/s->call_latency.num:0.0);
267                 printf("%.6f:", s->call_latency.max);
268
269                 printf("%d:", s->lockwait_latency.num);
270                 printf("%.6f:", s->lockwait_latency.min);
271                 printf("%.6f:", s->lockwait_latency.num?s->lockwait_latency.total/s->lockwait_latency.num:0.0);
272                 printf("%.6f:", s->lockwait_latency.max);
273
274                 printf("%d:", s->childwrite_latency.num);
275                 printf("%.6f:", s->childwrite_latency.min);
276                 printf("%.6f:", s->childwrite_latency.num?s->childwrite_latency.total/s->childwrite_latency.num:0.0);
277                 printf("%.6f:", s->childwrite_latency.max);
278                 printf("\n");
279         } else {
280                 printf("CTDB version %u\n", CTDB_VERSION);
281                 printf("Current time of statistics  :                %s", ctime(&s->statistics_current_time.tv_sec));
282                 printf("Statistics collected since  : (%03d %02d:%02d:%02d) %s", days, hours, minutes, seconds, ctime(&s->statistics_start_time.tv_sec));
283
284                 for (i=0;i<ARRAY_SIZE(fields);i++) {
285                         if (strchr(fields[i].name, '.')) {
286                                 preflen = strcspn(fields[i].name, ".")+1;
287                                 if (!prefix || strncmp(prefix, fields[i].name, preflen) != 0) {
288                                         prefix = fields[i].name;
289                                         printf(" %*.*s\n", preflen-1, preflen-1, fields[i].name);
290                                 }
291                         } else {
292                                 preflen = 0;
293                         }
294                         printf(" %*s%-22s%*s%10u\n", 
295                                preflen?4:0, "",
296                                fields[i].name+preflen, 
297                                preflen?0:4, "",
298                                *(uint32_t *)(fields[i].offset+(uint8_t *)s));
299                 }
300                 printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n", "reclock_ctdbd       MIN/AVG/MAX", s->reclock.ctdbd.min, s->reclock.ctdbd.num?s->reclock.ctdbd.total/s->reclock.ctdbd.num:0.0, s->reclock.ctdbd.max, s->reclock.ctdbd.num);
301
302                 printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n", "reclock_recd       MIN/AVG/MAX", s->reclock.recd.min, s->reclock.recd.num?s->reclock.recd.total/s->reclock.recd.num:0.0, s->reclock.recd.max, s->reclock.recd.num);
303
304                 printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n", "call_latency       MIN/AVG/MAX", s->call_latency.min, s->call_latency.num?s->call_latency.total/s->call_latency.num:0.0, s->call_latency.max, s->call_latency.num);
305                 printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n", "lockwait_latency   MIN/AVG/MAX", s->lockwait_latency.min, s->lockwait_latency.num?s->lockwait_latency.total/s->lockwait_latency.num:0.0, s->lockwait_latency.max, s->lockwait_latency.num);
306                 printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n", "childwrite_latency MIN/AVG/MAX", s->childwrite_latency.min, s->childwrite_latency.num?s->childwrite_latency.total/s->childwrite_latency.num:0.0, s->childwrite_latency.max, s->childwrite_latency.num);
307         }
308
309         talloc_free(tmp_ctx);
310 }
311
312 /*
313   display remote ctdb statistics combined from all nodes
314  */
315 static int control_statistics_all(struct ctdb_context *ctdb)
316 {
317         int ret, i;
318         struct ctdb_statistics statistics;
319         uint32_t *nodes;
320         uint32_t num_nodes;
321
322         nodes = ctdb_get_connected_nodes(ctdb, TIMELIMIT(), ctdb, &num_nodes);
323         CTDB_NO_MEMORY(ctdb, nodes);
324         
325         ZERO_STRUCT(statistics);
326
327         for (i=0;i<num_nodes;i++) {
328                 struct ctdb_statistics s1;
329                 int j;
330                 uint32_t *v1 = (uint32_t *)&s1;
331                 uint32_t *v2 = (uint32_t *)&statistics;
332                 uint32_t num_ints = 
333                         offsetof(struct ctdb_statistics, __last_counter) / sizeof(uint32_t);
334                 ret = ctdb_ctrl_statistics(ctdb, nodes[i], &s1);
335                 if (ret != 0) {
336                         DEBUG(DEBUG_ERR, ("Unable to get statistics from node %u\n", nodes[i]));
337                         return ret;
338                 }
339                 for (j=0;j<num_ints;j++) {
340                         v2[j] += v1[j];
341                 }
342                 statistics.max_hop_count = 
343                         MAX(statistics.max_hop_count, s1.max_hop_count);
344                 statistics.call_latency.max = 
345                         MAX(statistics.call_latency.max, s1.call_latency.max);
346                 statistics.lockwait_latency.max = 
347                         MAX(statistics.lockwait_latency.max, s1.lockwait_latency.max);
348         }
349         talloc_free(nodes);
350         printf("Gathered statistics for %u nodes\n", num_nodes);
351         show_statistics(&statistics, 1);
352         return 0;
353 }
354
355 /*
356   display remote ctdb statistics
357  */
358 static int control_statistics(struct ctdb_context *ctdb, int argc, const char **argv)
359 {
360         int ret;
361         struct ctdb_statistics statistics;
362
363         if (options.pnn == CTDB_BROADCAST_ALL) {
364                 return control_statistics_all(ctdb);
365         }
366
367         ret = ctdb_ctrl_statistics(ctdb, options.pnn, &statistics);
368         if (ret != 0) {
369                 DEBUG(DEBUG_ERR, ("Unable to get statistics from node %u\n", options.pnn));
370                 return ret;
371         }
372         show_statistics(&statistics, 1);
373         return 0;
374 }
375
376
377 /*
378   reset remote ctdb statistics
379  */
380 static int control_statistics_reset(struct ctdb_context *ctdb, int argc, const char **argv)
381 {
382         int ret;
383
384         ret = ctdb_statistics_reset(ctdb, options.pnn);
385         if (ret != 0) {
386                 DEBUG(DEBUG_ERR, ("Unable to reset statistics on node %u\n", options.pnn));
387                 return ret;
388         }
389         return 0;
390 }
391
392
393 /*
394   display remote ctdb rolling statistics
395  */
396 static int control_stats(struct ctdb_context *ctdb, int argc, const char **argv)
397 {
398         int ret;
399         struct ctdb_statistics_wire *stats;
400         int i, num_records = -1;
401
402         if (argc ==1) {
403                 num_records = atoi(argv[0]) - 1;
404         }
405
406         ret = ctdb_ctrl_getstathistory(ctdb, TIMELIMIT(), options.pnn, ctdb, &stats);
407         if (ret != 0) {
408                 DEBUG(DEBUG_ERR, ("Unable to get rolling statistics from node %u\n", options.pnn));
409                 return ret;
410         }
411         for (i=0;i<stats->num;i++) {
412                 if (stats->stats[i].statistics_start_time.tv_sec == 0) {
413                         continue;
414                 }
415                 show_statistics(&stats->stats[i], i==0);
416                 if (i == num_records) {
417                         break;
418                 }
419         }
420         return 0;
421 }
422
423
424 /*
425   display uptime of remote node
426  */
427 static int control_uptime(struct ctdb_context *ctdb, int argc, const char **argv)
428 {
429         int ret;
430         struct ctdb_uptime *uptime = NULL;
431         int tmp, days, hours, minutes, seconds;
432
433         ret = ctdb_ctrl_uptime(ctdb, ctdb, TIMELIMIT(), options.pnn, &uptime);
434         if (ret != 0) {
435                 DEBUG(DEBUG_ERR, ("Unable to get uptime from node %u\n", options.pnn));
436                 return ret;
437         }
438
439         if (options.machinereadable){
440                 printf(":Current Node Time:Ctdb Start Time:Last Recovery/Failover Time:Last Recovery/IPFailover Duration:\n");
441                 printf(":%u:%u:%u:%lf\n",
442                         (unsigned int)uptime->current_time.tv_sec,
443                         (unsigned int)uptime->ctdbd_start_time.tv_sec,
444                         (unsigned int)uptime->last_recovery_finished.tv_sec,
445                         timeval_delta(&uptime->last_recovery_finished,
446                                       &uptime->last_recovery_started)
447                 );
448                 return 0;
449         }
450
451         printf("Current time of node          :                %s", ctime(&uptime->current_time.tv_sec));
452
453         tmp = uptime->current_time.tv_sec - uptime->ctdbd_start_time.tv_sec;
454         seconds = tmp%60;
455         tmp    /= 60;
456         minutes = tmp%60;
457         tmp    /= 60;
458         hours   = tmp%24;
459         tmp    /= 24;
460         days    = tmp;
461         printf("Ctdbd start time              : (%03d %02d:%02d:%02d) %s", days, hours, minutes, seconds, ctime(&uptime->ctdbd_start_time.tv_sec));
462
463         tmp = uptime->current_time.tv_sec - uptime->last_recovery_finished.tv_sec;
464         seconds = tmp%60;
465         tmp    /= 60;
466         minutes = tmp%60;
467         tmp    /= 60;
468         hours   = tmp%24;
469         tmp    /= 24;
470         days    = tmp;
471         printf("Time of last recovery/failover: (%03d %02d:%02d:%02d) %s", days, hours, minutes, seconds, ctime(&uptime->last_recovery_finished.tv_sec));
472         
473         printf("Duration of last recovery/failover: %lf seconds\n",
474                 timeval_delta(&uptime->last_recovery_finished,
475                               &uptime->last_recovery_started));
476
477         return 0;
478 }
479
480 /*
481   show the PNN of the current node
482  */
483 static int control_pnn(struct ctdb_context *ctdb, int argc, const char **argv)
484 {
485         uint32_t mypnn;
486         bool ret;
487
488         ret = ctdb_getpnn(ctdb_connection, options.pnn, &mypnn);
489         if (!ret) {
490                 DEBUG(DEBUG_ERR, ("Unable to get pnn from node."));
491                 return -1;
492         }
493
494         printf("PNN:%d\n", mypnn);
495         return 0;
496 }
497
498
499 struct pnn_node {
500         struct pnn_node *next;
501         const char *addr;
502         int pnn;
503 };
504
505 static struct pnn_node *read_nodes_file(TALLOC_CTX *mem_ctx)
506 {
507         const char *nodes_list;
508         int nlines;
509         char **lines;
510         int i, pnn;
511         struct pnn_node *pnn_nodes = NULL;
512         struct pnn_node *pnn_node;
513         struct pnn_node *tmp_node;
514
515         /* read the nodes file */
516         nodes_list = getenv("CTDB_NODES");
517         if (nodes_list == NULL) {
518                 nodes_list = "/etc/ctdb/nodes";
519         }
520         lines = file_lines_load(nodes_list, &nlines, mem_ctx);
521         if (lines == NULL) {
522                 return NULL;
523         }
524         while (nlines > 0 && strcmp(lines[nlines-1], "") == 0) {
525                 nlines--;
526         }
527         for (i=0, pnn=0; i<nlines; i++) {
528                 char *node;
529
530                 node = lines[i];
531                 /* strip leading spaces */
532                 while((*node == ' ') || (*node == '\t')) {
533                         node++;
534                 }
535                 if (*node == '#') {
536                         pnn++;
537                         continue;
538                 }
539                 if (strcmp(node, "") == 0) {
540                         continue;
541                 }
542                 pnn_node = talloc(mem_ctx, struct pnn_node);
543                 pnn_node->pnn = pnn++;
544                 pnn_node->addr = talloc_strdup(pnn_node, node);
545                 pnn_node->next = pnn_nodes;
546                 pnn_nodes = pnn_node;
547         }
548
549         /* swap them around so we return them in incrementing order */
550         pnn_node = pnn_nodes;
551         pnn_nodes = NULL;
552         while (pnn_node) {
553                 tmp_node = pnn_node;
554                 pnn_node = pnn_node->next;
555
556                 tmp_node->next = pnn_nodes;
557                 pnn_nodes = tmp_node;
558         }
559
560         return pnn_nodes;
561 }
562
563 /*
564   show the PNN of the current node
565   discover the pnn by loading the nodes file and try to bind to all
566   addresses one at a time until the ip address is found.
567  */
568 static int control_xpnn(struct ctdb_context *ctdb, int argc, const char **argv)
569 {
570         TALLOC_CTX *mem_ctx = talloc_new(NULL);
571         struct pnn_node *pnn_nodes;
572         struct pnn_node *pnn_node;
573
574         pnn_nodes = read_nodes_file(mem_ctx);
575         if (pnn_nodes == NULL) {
576                 DEBUG(DEBUG_ERR,("Failed to read nodes file\n"));
577                 talloc_free(mem_ctx);
578                 return -1;
579         }
580
581         for(pnn_node=pnn_nodes;pnn_node;pnn_node=pnn_node->next) {
582                 ctdb_sock_addr addr;
583
584                 if (parse_ip(pnn_node->addr, NULL, 63999, &addr) == 0) {
585                         DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s' in nodes file\n", pnn_node->addr));
586                         talloc_free(mem_ctx);
587                         return -1;
588                 }
589
590                 if (ctdb_sys_have_ip(&addr)) {
591                         printf("PNN:%d\n", pnn_node->pnn);
592                         talloc_free(mem_ctx);
593                         return 0;
594                 }
595         }
596
597         printf("Failed to detect which PNN this node is\n");
598         talloc_free(mem_ctx);
599         return -1;
600 }
601
602 /*
603   display remote ctdb status
604  */
605 static int control_status(struct ctdb_context *ctdb, int argc, const char **argv)
606 {
607         int i, ret;
608         struct ctdb_vnn_map *vnnmap=NULL;
609         struct ctdb_node_map *nodemap=NULL;
610         uint32_t recmode, recmaster;
611         int mypnn;
612
613         mypnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), options.pnn);
614         if (mypnn == -1) {
615                 return -1;
616         }
617
618         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb, &nodemap);
619         if (ret != 0) {
620                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
621                 return ret;
622         }
623
624         if(options.machinereadable){
625                 printf(":Node:IP:Disconnected:Banned:Disabled:Unhealthy:Stopped:Inactive:\n");
626                 for(i=0;i<nodemap->num;i++){
627                         if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
628                                 continue;
629                         }
630                         printf(":%d:%s:%d:%d:%d:%d:%d:%d:\n", nodemap->nodes[i].pnn,
631                                 ctdb_addr_to_str(&nodemap->nodes[i].addr),
632                                !!(nodemap->nodes[i].flags&NODE_FLAGS_DISCONNECTED),
633                                !!(nodemap->nodes[i].flags&NODE_FLAGS_BANNED),
634                                !!(nodemap->nodes[i].flags&NODE_FLAGS_PERMANENTLY_DISABLED),
635                                !!(nodemap->nodes[i].flags&NODE_FLAGS_UNHEALTHY),
636                                !!(nodemap->nodes[i].flags&NODE_FLAGS_STOPPED),
637                                !!(nodemap->nodes[i].flags&NODE_FLAGS_INACTIVE));
638                 }
639                 return 0;
640         }
641
642         printf("Number of nodes:%d\n", nodemap->num);
643         for(i=0;i<nodemap->num;i++){
644                 static const struct {
645                         uint32_t flag;
646                         const char *name;
647                 } flag_names[] = {
648                         { NODE_FLAGS_DISCONNECTED,          "DISCONNECTED" },
649                         { NODE_FLAGS_PERMANENTLY_DISABLED,  "DISABLED" },
650                         { NODE_FLAGS_BANNED,                "BANNED" },
651                         { NODE_FLAGS_UNHEALTHY,             "UNHEALTHY" },
652                         { NODE_FLAGS_DELETED,               "DELETED" },
653                         { NODE_FLAGS_STOPPED,               "STOPPED" },
654                         { NODE_FLAGS_INACTIVE,              "INACTIVE" },
655                 };
656                 char *flags_str = NULL;
657                 int j;
658
659                 if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
660                         continue;
661                 }
662                 for (j=0;j<ARRAY_SIZE(flag_names);j++) {
663                         if (nodemap->nodes[i].flags & flag_names[j].flag) {
664                                 if (flags_str == NULL) {
665                                         flags_str = talloc_strdup(ctdb, flag_names[j].name);
666                                 } else {
667                                         flags_str = talloc_asprintf_append(flags_str, "|%s",
668                                                                            flag_names[j].name);
669                                 }
670                                 CTDB_NO_MEMORY_FATAL(ctdb, flags_str);
671                         }
672                 }
673                 if (flags_str == NULL) {
674                         flags_str = talloc_strdup(ctdb, "OK");
675                         CTDB_NO_MEMORY_FATAL(ctdb, flags_str);
676                 }
677                 printf("pnn:%d %-16s %s%s\n", nodemap->nodes[i].pnn,
678                        ctdb_addr_to_str(&nodemap->nodes[i].addr),
679                        flags_str,
680                        nodemap->nodes[i].pnn == mypnn?" (THIS NODE)":"");
681                 talloc_free(flags_str);
682         }
683
684         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn, ctdb, &vnnmap);
685         if (ret != 0) {
686                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n", options.pnn));
687                 return ret;
688         }
689         if (vnnmap->generation == INVALID_GENERATION) {
690                 printf("Generation:INVALID\n");
691         } else {
692                 printf("Generation:%d\n",vnnmap->generation);
693         }
694         printf("Size:%d\n",vnnmap->size);
695         for(i=0;i<vnnmap->size;i++){
696                 printf("hash:%d lmaster:%d\n", i, vnnmap->map[i]);
697         }
698
699         ret = ctdb_ctrl_getrecmode(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmode);
700         if (ret != 0) {
701                 DEBUG(DEBUG_ERR, ("Unable to get recmode from node %u\n", options.pnn));
702                 return ret;
703         }
704         printf("Recovery mode:%s (%d)\n",recmode==CTDB_RECOVERY_NORMAL?"NORMAL":"RECOVERY",recmode);
705
706         ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmaster);
707         if (ret != 0) {
708                 DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
709                 return ret;
710         }
711         printf("Recovery master:%d\n",recmaster);
712
713         return 0;
714 }
715
716
717 struct natgw_node {
718         struct natgw_node *next;
719         const char *addr;
720 };
721
722 /*
723   display the list of nodes belonging to this natgw configuration
724  */
725 static int control_natgwlist(struct ctdb_context *ctdb, int argc, const char **argv)
726 {
727         int i, ret;
728         uint32_t capabilities;
729         const char *natgw_list;
730         int nlines;
731         char **lines;
732         struct natgw_node *natgw_nodes = NULL;
733         struct natgw_node *natgw_node;
734         struct ctdb_node_map *nodemap=NULL;
735
736
737         /* read the natgw nodes file into a linked list */
738         natgw_list = getenv("NATGW_NODES");
739         if (natgw_list == NULL) {
740                 natgw_list = "/etc/ctdb/natgw_nodes";
741         }
742         lines = file_lines_load(natgw_list, &nlines, ctdb);
743         if (lines == NULL) {
744                 ctdb_set_error(ctdb, "Failed to load natgw node list '%s'\n", natgw_list);
745                 return -1;
746         }
747         while (nlines > 0 && strcmp(lines[nlines-1], "") == 0) {
748                 nlines--;
749         }
750         for (i=0;i<nlines;i++) {
751                 char *node;
752
753                 node = lines[i];
754                 /* strip leading spaces */
755                 while((*node == ' ') || (*node == '\t')) {
756                         node++;
757                 }
758                 if (*node == '#') {
759                         continue;
760                 }
761                 if (strcmp(node, "") == 0) {
762                         continue;
763                 }
764                 natgw_node = talloc(ctdb, struct natgw_node);
765                 natgw_node->addr = talloc_strdup(natgw_node, node);
766                 CTDB_NO_MEMORY(ctdb, natgw_node->addr);
767                 natgw_node->next = natgw_nodes;
768                 natgw_nodes = natgw_node;
769         }
770
771         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
772         if (ret != 0) {
773                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node.\n"));
774                 return ret;
775         }
776
777         i=0;
778         while(i<nodemap->num) {
779                 for(natgw_node=natgw_nodes;natgw_node;natgw_node=natgw_node->next) {
780                         if (!strcmp(natgw_node->addr, ctdb_addr_to_str(&nodemap->nodes[i].addr))) {
781                                 break;
782                         }
783                 }
784
785                 /* this node was not in the natgw so we just remove it from
786                  * the list
787                  */
788                 if ((natgw_node == NULL) 
789                 ||  (nodemap->nodes[i].flags & NODE_FLAGS_DISCONNECTED) ) {
790                         int j;
791
792                         for (j=i+1; j<nodemap->num; j++) {
793                                 nodemap->nodes[j-1] = nodemap->nodes[j];
794                         }
795                         nodemap->num--;
796                         continue;
797                 }
798
799                 i++;
800         }               
801
802         /* pick a node to be natgwmaster
803          * we dont allow STOPPED, DELETED, BANNED or UNHEALTHY nodes to become the natgwmaster
804          */
805         for(i=0;i<nodemap->num;i++){
806                 if (!(nodemap->nodes[i].flags & (NODE_FLAGS_DISCONNECTED|NODE_FLAGS_STOPPED|NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_UNHEALTHY))) {
807                         ret = ctdb_ctrl_getcapabilities(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, &capabilities);
808                         if (ret != 0) {
809                                 DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", nodemap->nodes[i].pnn));
810                                 return ret;
811                         }
812                         if (!(capabilities&CTDB_CAP_NATGW)) {
813                                 continue;
814                         }
815                         printf("%d %s\n", nodemap->nodes[i].pnn,ctdb_addr_to_str(&nodemap->nodes[i].addr));
816                         break;
817                 }
818         }
819         /* we couldnt find any healthy node, try unhealthy ones */
820         if (i == nodemap->num) {
821                 for(i=0;i<nodemap->num;i++){
822                         if (!(nodemap->nodes[i].flags & (NODE_FLAGS_DISCONNECTED|NODE_FLAGS_STOPPED|NODE_FLAGS_DELETED))) {
823                                 ret = ctdb_ctrl_getcapabilities(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, &capabilities);
824                                 if (ret != 0) {
825                                         DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", nodemap->nodes[i].pnn));
826                                         return ret;
827                                 }
828                                 if (!(capabilities&CTDB_CAP_NATGW)) {
829                                         continue;
830                                 }
831                                 printf("%d %s\n", nodemap->nodes[i].pnn,ctdb_addr_to_str(&nodemap->nodes[i].addr));
832                                 break;
833                         }
834                 }
835         }
836         /* unless all nodes are STOPPED, when we pick one anyway */
837         if (i == nodemap->num) {
838                 for(i=0;i<nodemap->num;i++){
839                         if (!(nodemap->nodes[i].flags & (NODE_FLAGS_DISCONNECTED|NODE_FLAGS_DELETED))) {
840                                 ret = ctdb_ctrl_getcapabilities(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, &capabilities);
841                                 if (ret != 0) {
842                                         DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", nodemap->nodes[i].pnn));
843                                         return ret;
844                                 }
845                                 if (!(capabilities&CTDB_CAP_NATGW)) {
846                                         continue;
847                                 }
848                                 printf("%d %s\n", nodemap->nodes[i].pnn, ctdb_addr_to_str(&nodemap->nodes[i].addr));
849                                 break;
850                         }
851                 }
852                 /* or if we still can not find any */
853                 if (i == nodemap->num) {
854                         printf("-1 0.0.0.0\n");
855                 }
856         }
857
858         /* print the pruned list of nodes belonging to this natgw list */
859         for(i=0;i<nodemap->num;i++){
860                 if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
861                         continue;
862                 }
863                 printf(":%d:%s:%d:%d:%d:%d:%d\n", nodemap->nodes[i].pnn,
864                         ctdb_addr_to_str(&nodemap->nodes[i].addr),
865                        !!(nodemap->nodes[i].flags&NODE_FLAGS_DISCONNECTED),
866                        !!(nodemap->nodes[i].flags&NODE_FLAGS_BANNED),
867                        !!(nodemap->nodes[i].flags&NODE_FLAGS_PERMANENTLY_DISABLED),
868                        !!(nodemap->nodes[i].flags&NODE_FLAGS_UNHEALTHY),
869                        !!(nodemap->nodes[i].flags&NODE_FLAGS_STOPPED));
870         }
871
872         return 0;
873 }
874
875 /*
876   display the status of the scripts for monitoring (or other events)
877  */
878 static int control_one_scriptstatus(struct ctdb_context *ctdb,
879                                     enum ctdb_eventscript_call type)
880 {
881         struct ctdb_scripts_wire *script_status;
882         int ret, i;
883
884         ret = ctdb_ctrl_getscriptstatus(ctdb, TIMELIMIT(), options.pnn, ctdb, type, &script_status);
885         if (ret != 0) {
886                 DEBUG(DEBUG_ERR, ("Unable to get script status from node %u\n", options.pnn));
887                 return ret;
888         }
889
890         if (script_status == NULL) {
891                 if (!options.machinereadable) {
892                         printf("%s cycle never run\n",
893                                ctdb_eventscript_call_names[type]);
894                 }
895                 return 0;
896         }
897
898         if (!options.machinereadable) {
899                 printf("%d scripts were executed last %s cycle\n",
900                        script_status->num_scripts,
901                        ctdb_eventscript_call_names[type]);
902         }
903         for (i=0; i<script_status->num_scripts; i++) {
904                 const char *status = NULL;
905
906                 switch (script_status->scripts[i].status) {
907                 case -ETIME:
908                         status = "TIMEDOUT";
909                         break;
910                 case -ENOEXEC:
911                         status = "DISABLED";
912                         break;
913                 case 0:
914                         status = "OK";
915                         break;
916                 default:
917                         if (script_status->scripts[i].status > 0)
918                                 status = "ERROR";
919                         break;
920                 }
921                 if (options.machinereadable) {
922                         printf("%s:%s:%i:%s:%lu.%06lu:%lu.%06lu:%s:\n",
923                                ctdb_eventscript_call_names[type],
924                                script_status->scripts[i].name,
925                                script_status->scripts[i].status,
926                                status,
927                                (long)script_status->scripts[i].start.tv_sec,
928                                (long)script_status->scripts[i].start.tv_usec,
929                                (long)script_status->scripts[i].finished.tv_sec,
930                                (long)script_status->scripts[i].finished.tv_usec,
931                                script_status->scripts[i].output);
932                         continue;
933                 }
934                 if (status)
935                         printf("%-20s Status:%s    ",
936                                script_status->scripts[i].name, status);
937                 else
938                         /* Some other error, eg from stat. */
939                         printf("%-20s Status:CANNOT RUN (%s)",
940                                script_status->scripts[i].name,
941                                strerror(-script_status->scripts[i].status));
942
943                 if (script_status->scripts[i].status >= 0) {
944                         printf("Duration:%.3lf ",
945                         timeval_delta(&script_status->scripts[i].finished,
946                               &script_status->scripts[i].start));
947                 }
948                 if (script_status->scripts[i].status != -ENOEXEC) {
949                         printf("%s",
950                                ctime(&script_status->scripts[i].start.tv_sec));
951                         if (script_status->scripts[i].status != 0) {
952                                 printf("   OUTPUT:%s\n",
953                                        script_status->scripts[i].output);
954                         }
955                 } else {
956                         printf("\n");
957                 }
958         }
959         return 0;
960 }
961
962
963 static int control_scriptstatus(struct ctdb_context *ctdb,
964                                 int argc, const char **argv)
965 {
966         int ret;
967         enum ctdb_eventscript_call type, min, max;
968         const char *arg;
969
970         if (argc > 1) {
971                 DEBUG(DEBUG_ERR, ("Unknown arguments to scriptstatus\n"));
972                 return -1;
973         }
974
975         if (argc == 0)
976                 arg = ctdb_eventscript_call_names[CTDB_EVENT_MONITOR];
977         else
978                 arg = argv[0];
979
980         for (type = 0; type < CTDB_EVENT_MAX; type++) {
981                 if (strcmp(arg, ctdb_eventscript_call_names[type]) == 0) {
982                         min = type;
983                         max = type+1;
984                         break;
985                 }
986         }
987         if (type == CTDB_EVENT_MAX) {
988                 if (strcmp(arg, "all") == 0) {
989                         min = 0;
990                         max = CTDB_EVENT_MAX;
991                 } else {
992                         DEBUG(DEBUG_ERR, ("Unknown event type %s\n", argv[0]));
993                         return -1;
994                 }
995         }
996
997         if (options.machinereadable) {
998                 printf(":Type:Name:Code:Status:Start:End:Error Output...:\n");
999         }
1000
1001         for (type = min; type < max; type++) {
1002                 ret = control_one_scriptstatus(ctdb, type);
1003                 if (ret != 0) {
1004                         return ret;
1005                 }
1006         }
1007
1008         return 0;
1009 }
1010
1011 /*
1012   enable an eventscript
1013  */
1014 static int control_enablescript(struct ctdb_context *ctdb, int argc, const char **argv)
1015 {
1016         int ret;
1017
1018         if (argc < 1) {
1019                 usage();
1020         }
1021
1022         ret = ctdb_ctrl_enablescript(ctdb, TIMELIMIT(), options.pnn, argv[0]);
1023         if (ret != 0) {
1024           DEBUG(DEBUG_ERR, ("Unable to enable script %s on node %u\n", argv[0], options.pnn));
1025                 return ret;
1026         }
1027
1028         return 0;
1029 }
1030
1031 /*
1032   disable an eventscript
1033  */
1034 static int control_disablescript(struct ctdb_context *ctdb, int argc, const char **argv)
1035 {
1036         int ret;
1037
1038         if (argc < 1) {
1039                 usage();
1040         }
1041
1042         ret = ctdb_ctrl_disablescript(ctdb, TIMELIMIT(), options.pnn, argv[0]);
1043         if (ret != 0) {
1044           DEBUG(DEBUG_ERR, ("Unable to disable script %s on node %u\n", argv[0], options.pnn));
1045                 return ret;
1046         }
1047
1048         return 0;
1049 }
1050
1051 /*
1052   display the pnn of the recovery master
1053  */
1054 static int control_recmaster(struct ctdb_context *ctdb, int argc, const char **argv)
1055 {
1056         int ret;
1057         uint32_t recmaster;
1058
1059         ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmaster);
1060         if (ret != 0) {
1061                 DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
1062                 return ret;
1063         }
1064         printf("%d\n",recmaster);
1065
1066         return 0;
1067 }
1068
1069 /*
1070   add a tickle to a public address
1071  */
1072 static int control_add_tickle(struct ctdb_context *ctdb, int argc, const char **argv)
1073 {
1074         struct ctdb_tcp_connection t;
1075         TDB_DATA data;
1076         int ret;
1077
1078         if (argc < 2) {
1079                 usage();
1080         }
1081
1082         if (parse_ip_port(argv[0], &t.src_addr) == 0) {
1083                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1084                 return -1;
1085         }
1086         if (parse_ip_port(argv[1], &t.dst_addr) == 0) {
1087                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[1]));
1088                 return -1;
1089         }
1090
1091         data.dptr = (uint8_t *)&t;
1092         data.dsize = sizeof(t);
1093
1094         /* tell all nodes about this tcp connection */
1095         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_TCP_ADD_DELAYED_UPDATE,
1096                            0, data, ctdb, NULL, NULL, NULL, NULL);
1097         if (ret != 0) {
1098                 DEBUG(DEBUG_ERR,("Failed to add tickle\n"));
1099                 return -1;
1100         }
1101         
1102         return 0;
1103 }
1104
1105
1106 /*
1107   delete a tickle from a node
1108  */
1109 static int control_del_tickle(struct ctdb_context *ctdb, int argc, const char **argv)
1110 {
1111         struct ctdb_tcp_connection t;
1112         TDB_DATA data;
1113         int ret;
1114
1115         if (argc < 2) {
1116                 usage();
1117         }
1118
1119         if (parse_ip_port(argv[0], &t.src_addr) == 0) {
1120                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1121                 return -1;
1122         }
1123         if (parse_ip_port(argv[1], &t.dst_addr) == 0) {
1124                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[1]));
1125                 return -1;
1126         }
1127
1128         data.dptr = (uint8_t *)&t;
1129         data.dsize = sizeof(t);
1130
1131         /* tell all nodes about this tcp connection */
1132         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_TCP_REMOVE,
1133                            0, data, ctdb, NULL, NULL, NULL, NULL);
1134         if (ret != 0) {
1135                 DEBUG(DEBUG_ERR,("Failed to remove tickle\n"));
1136                 return -1;
1137         }
1138         
1139         return 0;
1140 }
1141
1142
1143 /*
1144   get a list of all tickles for this pnn
1145  */
1146 static int control_get_tickles(struct ctdb_context *ctdb, int argc, const char **argv)
1147 {
1148         struct ctdb_control_tcp_tickle_list *list;
1149         ctdb_sock_addr addr;
1150         int i, ret;
1151         unsigned port = 0;
1152
1153         if (argc < 1) {
1154                 usage();
1155         }
1156
1157         if (argc == 2) {
1158                 port = atoi(argv[1]);
1159         }
1160
1161         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
1162                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1163                 return -1;
1164         }
1165
1166         ret = ctdb_ctrl_get_tcp_tickles(ctdb, TIMELIMIT(), options.pnn, ctdb, &addr, &list);
1167         if (ret == -1) {
1168                 DEBUG(DEBUG_ERR, ("Unable to list tickles\n"));
1169                 return -1;
1170         }
1171
1172         if (options.machinereadable){
1173                 printf(":source ip:port:destination ip:port:\n");
1174                 for (i=0;i<list->tickles.num;i++) {
1175                         if (port && port != ntohs(list->tickles.connections[i].dst_addr.ip.sin_port)) {
1176                                 continue;
1177                         }
1178                         printf(":%s:%u", ctdb_addr_to_str(&list->tickles.connections[i].src_addr), ntohs(list->tickles.connections[i].src_addr.ip.sin_port));
1179                         printf(":%s:%u:\n", ctdb_addr_to_str(&list->tickles.connections[i].dst_addr), ntohs(list->tickles.connections[i].dst_addr.ip.sin_port));
1180                 }
1181         } else {
1182                 printf("Tickles for ip:%s\n", ctdb_addr_to_str(&list->addr));
1183                 printf("Num tickles:%u\n", list->tickles.num);
1184                 for (i=0;i<list->tickles.num;i++) {
1185                         if (port && port != ntohs(list->tickles.connections[i].dst_addr.ip.sin_port)) {
1186                                 continue;
1187                         }
1188                         printf("SRC: %s:%u   ", ctdb_addr_to_str(&list->tickles.connections[i].src_addr), ntohs(list->tickles.connections[i].src_addr.ip.sin_port));
1189                         printf("DST: %s:%u\n", ctdb_addr_to_str(&list->tickles.connections[i].dst_addr), ntohs(list->tickles.connections[i].dst_addr.ip.sin_port));
1190                 }
1191         }
1192
1193         talloc_free(list);
1194         
1195         return 0;
1196 }
1197
1198
1199 static int move_ip(struct ctdb_context *ctdb, ctdb_sock_addr *addr, uint32_t pnn)
1200 {
1201         struct ctdb_all_public_ips *ips;
1202         struct ctdb_public_ip ip;
1203         int i, ret;
1204         uint32_t *nodes;
1205         uint32_t disable_time;
1206         TDB_DATA data;
1207         struct ctdb_node_map *nodemap=NULL;
1208         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1209
1210         disable_time = 30;
1211         data.dptr  = (uint8_t*)&disable_time;
1212         data.dsize = sizeof(disable_time);
1213         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, CTDB_SRVID_DISABLE_IP_CHECK, data);
1214         if (ret != 0) {
1215                 DEBUG(DEBUG_ERR,("Failed to send message to disable ipcheck\n"));
1216                 return -1;
1217         }
1218
1219
1220
1221         /* read the public ip list from the node */
1222         ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), pnn, ctdb, &ips);
1223         if (ret != 0) {
1224                 DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", pnn));
1225                 talloc_free(tmp_ctx);
1226                 return -1;
1227         }
1228
1229         for (i=0;i<ips->num;i++) {
1230                 if (ctdb_same_ip(addr, &ips->ips[i].addr)) {
1231                         break;
1232                 }
1233         }
1234         if (i==ips->num) {
1235                 DEBUG(DEBUG_ERR, ("Node %u can not host ip address '%s'\n",
1236                         pnn, ctdb_addr_to_str(addr)));
1237                 talloc_free(tmp_ctx);
1238                 return -1;
1239         }
1240
1241         ip.pnn  = pnn;
1242         ip.addr = *addr;
1243
1244         data.dptr  = (uint8_t *)&ip;
1245         data.dsize = sizeof(ip);
1246
1247         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &nodemap);
1248         if (ret != 0) {
1249                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1250                 talloc_free(tmp_ctx);
1251                 return ret;
1252         }
1253
1254         nodes = list_of_active_nodes_except_pnn(ctdb, nodemap, tmp_ctx, pnn);
1255         ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_RELEASE_IP,
1256                                         nodes, 0,
1257                                         LONGTIMELIMIT(),
1258                                         false, data,
1259                                         NULL, NULL,
1260                                         NULL);
1261         if (ret != 0) {
1262                 DEBUG(DEBUG_ERR,("Failed to release IP on nodes\n"));
1263                 talloc_free(tmp_ctx);
1264                 return -1;
1265         }
1266
1267         ret = ctdb_ctrl_takeover_ip(ctdb, LONGTIMELIMIT(), pnn, &ip);
1268         if (ret != 0) {
1269                 DEBUG(DEBUG_ERR,("Failed to take over IP on node %d\n", pnn));
1270                 talloc_free(tmp_ctx);
1271                 return -1;
1272         }
1273
1274         /* update the recovery daemon so it now knows to expect the new
1275            node assignment for this ip.
1276         */
1277         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, CTDB_SRVID_RECD_UPDATE_IP, data);
1278         if (ret != 0) {
1279                 DEBUG(DEBUG_ERR,("Failed to send message to update the ip on the recovery master.\n"));
1280                 return -1;
1281         }
1282
1283         talloc_free(tmp_ctx);
1284         return 0;
1285 }
1286
1287 /*
1288   move/failover an ip address to a specific node
1289  */
1290 static int control_moveip(struct ctdb_context *ctdb, int argc, const char **argv)
1291 {
1292         uint32_t pnn;
1293         ctdb_sock_addr addr;
1294
1295         if (argc < 2) {
1296                 usage();
1297                 return -1;
1298         }
1299
1300         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
1301                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1302                 return -1;
1303         }
1304
1305
1306         if (sscanf(argv[1], "%u", &pnn) != 1) {
1307                 DEBUG(DEBUG_ERR, ("Badly formed pnn\n"));
1308                 return -1;
1309         }
1310
1311         if (move_ip(ctdb, &addr, pnn) != 0) {
1312                 DEBUG(DEBUG_ERR,("Failed to move ip to node %d\n", pnn));
1313                 return -1;
1314         }
1315
1316         return 0;
1317 }
1318
1319 void getips_store_callback(void *param, void *data)
1320 {
1321         struct ctdb_public_ip *node_ip = (struct ctdb_public_ip *)data;
1322         struct ctdb_all_public_ips *ips = param;
1323         int i;
1324
1325         i = ips->num++;
1326         ips->ips[i].pnn  = node_ip->pnn;
1327         ips->ips[i].addr = node_ip->addr;
1328 }
1329
1330 void getips_count_callback(void *param, void *data)
1331 {
1332         uint32_t *count = param;
1333
1334         (*count)++;
1335 }
1336
1337 #define IP_KEYLEN       4
1338 static uint32_t *ip_key(ctdb_sock_addr *ip)
1339 {
1340         static uint32_t key[IP_KEYLEN];
1341
1342         bzero(key, sizeof(key));
1343
1344         switch (ip->sa.sa_family) {
1345         case AF_INET:
1346                 key[0]  = ip->ip.sin_addr.s_addr;
1347                 break;
1348         case AF_INET6:
1349                 key[0]  = ip->ip6.sin6_addr.s6_addr32[3];
1350                 key[1]  = ip->ip6.sin6_addr.s6_addr32[2];
1351                 key[2]  = ip->ip6.sin6_addr.s6_addr32[1];
1352                 key[3]  = ip->ip6.sin6_addr.s6_addr32[0];
1353                 break;
1354         default:
1355                 DEBUG(DEBUG_ERR, (__location__ " ERROR, unknown family passed :%u\n", ip->sa.sa_family));
1356                 return key;
1357         }
1358
1359         return key;
1360 }
1361
1362 static void *add_ip_callback(void *parm, void *data)
1363 {
1364         return parm;
1365 }
1366
1367 static int
1368 control_get_all_public_ips(struct ctdb_context *ctdb, TALLOC_CTX *tmp_ctx, struct ctdb_all_public_ips **ips)
1369 {
1370         struct ctdb_all_public_ips *tmp_ips;
1371         struct ctdb_node_map *nodemap=NULL;
1372         trbt_tree_t *ip_tree;
1373         int i, j, len, ret;
1374         uint32_t count;
1375
1376         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, tmp_ctx, &nodemap);
1377         if (ret != 0) {
1378                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1379                 return ret;
1380         }
1381
1382         ip_tree = trbt_create(tmp_ctx, 0);
1383
1384         for(i=0;i<nodemap->num;i++){
1385                 if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
1386                         continue;
1387                 }
1388                 if (nodemap->nodes[i].flags & NODE_FLAGS_DISCONNECTED) {
1389                         continue;
1390                 }
1391
1392                 /* read the public ip list from this node */
1393                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &tmp_ips);
1394                 if (ret != 0) {
1395                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", nodemap->nodes[i].pnn));
1396                         return -1;
1397                 }
1398         
1399                 for (j=0; j<tmp_ips->num;j++) {
1400                         struct ctdb_public_ip *node_ip;
1401
1402                         node_ip = talloc(tmp_ctx, struct ctdb_public_ip);
1403                         node_ip->pnn  = tmp_ips->ips[j].pnn;
1404                         node_ip->addr = tmp_ips->ips[j].addr;
1405
1406                         trbt_insertarray32_callback(ip_tree,
1407                                 IP_KEYLEN, ip_key(&tmp_ips->ips[j].addr),
1408                                 add_ip_callback,
1409                                 node_ip);
1410                 }
1411                 talloc_free(tmp_ips);
1412         }
1413
1414         /* traverse */
1415         count = 0;
1416         trbt_traversearray32(ip_tree, IP_KEYLEN, getips_count_callback, &count);
1417
1418         len = offsetof(struct ctdb_all_public_ips, ips) + 
1419                 count*sizeof(struct ctdb_public_ip);
1420         tmp_ips = talloc_zero_size(tmp_ctx, len);
1421         trbt_traversearray32(ip_tree, IP_KEYLEN, getips_store_callback, tmp_ips);
1422
1423         *ips = tmp_ips;
1424
1425         return 0;
1426 }
1427
1428
1429 /* 
1430  * scans all other nodes and returns a pnn for another node that can host this 
1431  * ip address or -1
1432  */
1433 static int
1434 find_other_host_for_public_ip(struct ctdb_context *ctdb, ctdb_sock_addr *addr)
1435 {
1436         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1437         struct ctdb_all_public_ips *ips;
1438         struct ctdb_node_map *nodemap=NULL;
1439         int i, j, ret;
1440
1441         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, tmp_ctx, &nodemap);
1442         if (ret != 0) {
1443                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1444                 talloc_free(tmp_ctx);
1445                 return ret;
1446         }
1447
1448         for(i=0;i<nodemap->num;i++){
1449                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
1450                         continue;
1451                 }
1452                 if (nodemap->nodes[i].pnn == options.pnn) {
1453                         continue;
1454                 }
1455
1456                 /* read the public ip list from this node */
1457                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &ips);
1458                 if (ret != 0) {
1459                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", nodemap->nodes[i].pnn));
1460                         return -1;
1461                 }
1462
1463                 for (j=0;j<ips->num;j++) {
1464                         if (ctdb_same_ip(addr, &ips->ips[j].addr)) {
1465                                 talloc_free(tmp_ctx);
1466                                 return nodemap->nodes[i].pnn;
1467                         }
1468                 }
1469                 talloc_free(ips);
1470         }
1471
1472         talloc_free(tmp_ctx);
1473         return -1;
1474 }
1475
1476 /*
1477   add a public ip address to a node
1478  */
1479 static int control_addip(struct ctdb_context *ctdb, int argc, const char **argv)
1480 {
1481         int i, ret;
1482         int len;
1483         uint32_t pnn;
1484         unsigned mask;
1485         ctdb_sock_addr addr;
1486         struct ctdb_control_ip_iface *pub;
1487         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1488         struct ctdb_all_public_ips *ips;
1489
1490
1491         if (argc != 2) {
1492                 talloc_free(tmp_ctx);
1493                 usage();
1494         }
1495
1496         if (!parse_ip_mask(argv[0], argv[1], &addr, &mask)) {
1497                 DEBUG(DEBUG_ERR, ("Badly formed ip/mask : %s\n", argv[0]));
1498                 talloc_free(tmp_ctx);
1499                 return -1;
1500         }
1501
1502         ret = control_get_all_public_ips(ctdb, tmp_ctx, &ips);
1503         if (ret != 0) {
1504                 DEBUG(DEBUG_ERR, ("Unable to get public ip list from cluster\n"));
1505                 talloc_free(tmp_ctx);
1506                 return ret;
1507         }
1508
1509
1510         /* check if some other node is already serving this ip, if not,
1511          * we will claim it
1512          */
1513         for (i=0;i<ips->num;i++) {
1514                 if (ctdb_same_ip(&addr, &ips->ips[i].addr)) {
1515                         break;
1516                 }
1517         }
1518
1519         len = offsetof(struct ctdb_control_ip_iface, iface) + strlen(argv[1]) + 1;
1520         pub = talloc_size(tmp_ctx, len); 
1521         CTDB_NO_MEMORY(ctdb, pub);
1522
1523         pub->addr  = addr;
1524         pub->mask  = mask;
1525         pub->len   = strlen(argv[1])+1;
1526         memcpy(&pub->iface[0], argv[1], strlen(argv[1])+1);
1527
1528         ret = ctdb_ctrl_add_public_ip(ctdb, TIMELIMIT(), options.pnn, pub);
1529         if (ret != 0) {
1530                 DEBUG(DEBUG_ERR, ("Unable to add public ip to node %u\n", options.pnn));
1531                 talloc_free(tmp_ctx);
1532                 return ret;
1533         }
1534
1535         if (i == ips->num) {
1536                 /* no one has this ip so we claim it */
1537                 pnn  = options.pnn;
1538         } else {
1539                 pnn  = ips->ips[i].pnn;
1540         }
1541
1542         if (move_ip(ctdb, &addr, pnn) != 0) {
1543                 DEBUG(DEBUG_ERR,("Failed to move ip to node %d\n", pnn));
1544                 return -1;
1545         }
1546
1547         talloc_free(tmp_ctx);
1548         return 0;
1549 }
1550
1551 static int control_delip(struct ctdb_context *ctdb, int argc, const char **argv);
1552
1553 static int control_delip_all(struct ctdb_context *ctdb, int argc, const char **argv, ctdb_sock_addr *addr)
1554 {
1555         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1556         struct ctdb_node_map *nodemap=NULL;
1557         struct ctdb_all_public_ips *ips;
1558         int ret, i, j;
1559
1560         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, tmp_ctx, &nodemap);
1561         if (ret != 0) {
1562                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from current node\n"));
1563                 return ret;
1564         }
1565
1566         /* remove it from the nodes that are not hosting the ip currently */
1567         for(i=0;i<nodemap->num;i++){
1568                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
1569                         continue;
1570                 }
1571                 if (ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &ips) != 0) {
1572                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %d\n", nodemap->nodes[i].pnn));
1573                         continue;
1574                 }
1575
1576                 for (j=0;j<ips->num;j++) {
1577                         if (ctdb_same_ip(addr, &ips->ips[j].addr)) {
1578                                 break;
1579                         }
1580                 }
1581                 if (j==ips->num) {
1582                         continue;
1583                 }
1584
1585                 if (ips->ips[j].pnn == nodemap->nodes[i].pnn) {
1586                         continue;
1587                 }
1588
1589                 options.pnn = nodemap->nodes[i].pnn;
1590                 control_delip(ctdb, argc, argv);
1591         }
1592
1593
1594         /* remove it from every node (also the one hosting it) */
1595         for(i=0;i<nodemap->num;i++){
1596                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
1597                         continue;
1598                 }
1599                 if (ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &ips) != 0) {
1600                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %d\n", nodemap->nodes[i].pnn));
1601                         continue;
1602                 }
1603
1604                 for (j=0;j<ips->num;j++) {
1605                         if (ctdb_same_ip(addr, &ips->ips[j].addr)) {
1606                                 break;
1607                         }
1608                 }
1609                 if (j==ips->num) {
1610                         continue;
1611                 }
1612
1613                 options.pnn = nodemap->nodes[i].pnn;
1614                 control_delip(ctdb, argc, argv);
1615         }
1616
1617         talloc_free(tmp_ctx);
1618         return 0;
1619 }
1620         
1621 /*
1622   delete a public ip address from a node
1623  */
1624 static int control_delip(struct ctdb_context *ctdb, int argc, const char **argv)
1625 {
1626         int i, ret;
1627         ctdb_sock_addr addr;
1628         struct ctdb_control_ip_iface pub;
1629         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1630         struct ctdb_all_public_ips *ips;
1631
1632         if (argc != 1) {
1633                 talloc_free(tmp_ctx);
1634                 usage();
1635         }
1636
1637         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
1638                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1639                 return -1;
1640         }
1641
1642         if (options.pnn == CTDB_BROADCAST_ALL) {
1643                 return control_delip_all(ctdb, argc, argv, &addr);
1644         }
1645
1646         pub.addr  = addr;
1647         pub.mask  = 0;
1648         pub.len   = 0;
1649
1650         ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ips);
1651         if (ret != 0) {
1652                 DEBUG(DEBUG_ERR, ("Unable to get public ip list from cluster\n"));
1653                 talloc_free(tmp_ctx);
1654                 return ret;
1655         }
1656         
1657         for (i=0;i<ips->num;i++) {
1658                 if (ctdb_same_ip(&addr, &ips->ips[i].addr)) {
1659                         break;
1660                 }
1661         }
1662
1663         if (i==ips->num) {
1664                 DEBUG(DEBUG_ERR, ("This node does not support this public address '%s'\n",
1665                         ctdb_addr_to_str(&addr)));
1666                 talloc_free(tmp_ctx);
1667                 return -1;
1668         }
1669
1670         if (ips->ips[i].pnn == options.pnn) {
1671                 ret = find_other_host_for_public_ip(ctdb, &addr);
1672                 if (ret != -1) {
1673                         if (move_ip(ctdb, &addr, ret) != 0) {
1674                                 DEBUG(DEBUG_ERR,("Failed to move ip to node %d\n", ret));
1675                                 return -1;
1676                         }
1677                 }
1678         }
1679
1680         ret = ctdb_ctrl_del_public_ip(ctdb, TIMELIMIT(), options.pnn, &pub);
1681         if (ret != 0) {
1682                 DEBUG(DEBUG_ERR, ("Unable to del public ip from node %u\n", options.pnn));
1683                 talloc_free(tmp_ctx);
1684                 return ret;
1685         }
1686
1687         talloc_free(tmp_ctx);
1688         return 0;
1689 }
1690
1691 /*
1692   kill a tcp connection
1693  */
1694 static int kill_tcp(struct ctdb_context *ctdb, int argc, const char **argv)
1695 {
1696         int ret;
1697         struct ctdb_control_killtcp killtcp;
1698
1699         if (argc < 2) {
1700                 usage();
1701         }
1702
1703         if (!parse_ip_port(argv[0], &killtcp.src_addr)) {
1704                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[0]));
1705                 return -1;
1706         }
1707
1708         if (!parse_ip_port(argv[1], &killtcp.dst_addr)) {
1709                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[1]));
1710                 return -1;
1711         }
1712
1713         ret = ctdb_ctrl_killtcp(ctdb, TIMELIMIT(), options.pnn, &killtcp);
1714         if (ret != 0) {
1715                 DEBUG(DEBUG_ERR, ("Unable to killtcp from node %u\n", options.pnn));
1716                 return ret;
1717         }
1718
1719         return 0;
1720 }
1721
1722
1723 /*
1724   send a gratious arp
1725  */
1726 static int control_gratious_arp(struct ctdb_context *ctdb, int argc, const char **argv)
1727 {
1728         int ret;
1729         ctdb_sock_addr addr;
1730
1731         if (argc < 2) {
1732                 usage();
1733         }
1734
1735         if (!parse_ip(argv[0], NULL, 0, &addr)) {
1736                 DEBUG(DEBUG_ERR, ("Bad IP '%s'\n", argv[0]));
1737                 return -1;
1738         }
1739
1740         ret = ctdb_ctrl_gratious_arp(ctdb, TIMELIMIT(), options.pnn, &addr, argv[1]);
1741         if (ret != 0) {
1742                 DEBUG(DEBUG_ERR, ("Unable to send gratious_arp from node %u\n", options.pnn));
1743                 return ret;
1744         }
1745
1746         return 0;
1747 }
1748
1749 /*
1750   register a server id
1751  */
1752 static int regsrvid(struct ctdb_context *ctdb, int argc, const char **argv)
1753 {
1754         int ret;
1755         struct ctdb_server_id server_id;
1756
1757         if (argc < 3) {
1758                 usage();
1759         }
1760
1761         server_id.pnn       = strtoul(argv[0], NULL, 0);
1762         server_id.type      = strtoul(argv[1], NULL, 0);
1763         server_id.server_id = strtoul(argv[2], NULL, 0);
1764
1765         ret = ctdb_ctrl_register_server_id(ctdb, TIMELIMIT(), &server_id);
1766         if (ret != 0) {
1767                 DEBUG(DEBUG_ERR, ("Unable to register server_id from node %u\n", options.pnn));
1768                 return ret;
1769         }
1770         DEBUG(DEBUG_ERR,("Srvid registered. Sleeping for 999 seconds\n"));
1771         sleep(999);
1772         return -1;
1773 }
1774
1775 /*
1776   unregister a server id
1777  */
1778 static int unregsrvid(struct ctdb_context *ctdb, int argc, const char **argv)
1779 {
1780         int ret;
1781         struct ctdb_server_id server_id;
1782
1783         if (argc < 3) {
1784                 usage();
1785         }
1786
1787         server_id.pnn       = strtoul(argv[0], NULL, 0);
1788         server_id.type      = strtoul(argv[1], NULL, 0);
1789         server_id.server_id = strtoul(argv[2], NULL, 0);
1790
1791         ret = ctdb_ctrl_unregister_server_id(ctdb, TIMELIMIT(), &server_id);
1792         if (ret != 0) {
1793                 DEBUG(DEBUG_ERR, ("Unable to unregister server_id from node %u\n", options.pnn));
1794                 return ret;
1795         }
1796         return -1;
1797 }
1798
1799 /*
1800   check if a server id exists
1801  */
1802 static int chksrvid(struct ctdb_context *ctdb, int argc, const char **argv)
1803 {
1804         uint32_t status;
1805         int ret;
1806         struct ctdb_server_id server_id;
1807
1808         if (argc < 3) {
1809                 usage();
1810         }
1811
1812         server_id.pnn       = strtoul(argv[0], NULL, 0);
1813         server_id.type      = strtoul(argv[1], NULL, 0);
1814         server_id.server_id = strtoul(argv[2], NULL, 0);
1815
1816         ret = ctdb_ctrl_check_server_id(ctdb, TIMELIMIT(), options.pnn, &server_id, &status);
1817         if (ret != 0) {
1818                 DEBUG(DEBUG_ERR, ("Unable to check server_id from node %u\n", options.pnn));
1819                 return ret;
1820         }
1821
1822         if (status) {
1823                 printf("Server id %d:%d:%d EXISTS\n", server_id.pnn, server_id.type, server_id.server_id);
1824         } else {
1825                 printf("Server id %d:%d:%d does NOT exist\n", server_id.pnn, server_id.type, server_id.server_id);
1826         }
1827         return 0;
1828 }
1829
1830 /*
1831   get a list of all server ids that are registered on a node
1832  */
1833 static int getsrvids(struct ctdb_context *ctdb, int argc, const char **argv)
1834 {
1835         int i, ret;
1836         struct ctdb_server_id_list *server_ids;
1837
1838         ret = ctdb_ctrl_get_server_id_list(ctdb, ctdb, TIMELIMIT(), options.pnn, &server_ids);
1839         if (ret != 0) {
1840                 DEBUG(DEBUG_ERR, ("Unable to get server_id list from node %u\n", options.pnn));
1841                 return ret;
1842         }
1843
1844         for (i=0; i<server_ids->num; i++) {
1845                 printf("Server id %d:%d:%d\n", 
1846                         server_ids->server_ids[i].pnn, 
1847                         server_ids->server_ids[i].type, 
1848                         server_ids->server_ids[i].server_id); 
1849         }
1850
1851         return -1;
1852 }
1853
1854 /*
1855   send a tcp tickle ack
1856  */
1857 static int tickle_tcp(struct ctdb_context *ctdb, int argc, const char **argv)
1858 {
1859         int ret;
1860         ctdb_sock_addr  src, dst;
1861
1862         if (argc < 2) {
1863                 usage();
1864         }
1865
1866         if (!parse_ip_port(argv[0], &src)) {
1867                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[0]));
1868                 return -1;
1869         }
1870
1871         if (!parse_ip_port(argv[1], &dst)) {
1872                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[1]));
1873                 return -1;
1874         }
1875
1876         ret = ctdb_sys_send_tcp(&src, &dst, 0, 0, 0);
1877         if (ret==0) {
1878                 return 0;
1879         }
1880         DEBUG(DEBUG_ERR, ("Error while sending tickle ack\n"));
1881
1882         return -1;
1883 }
1884
1885
1886 /*
1887   display public ip status
1888  */
1889 static int control_ip(struct ctdb_context *ctdb, int argc, const char **argv)
1890 {
1891         int i, ret;
1892         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1893         struct ctdb_all_public_ips *ips;
1894
1895         if (options.pnn == CTDB_BROADCAST_ALL) {
1896                 /* read the list of public ips from all nodes */
1897                 ret = control_get_all_public_ips(ctdb, tmp_ctx, &ips);
1898         } else {
1899                 /* read the public ip list from this node */
1900                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ips);
1901         }
1902         if (ret != 0) {
1903                 DEBUG(DEBUG_ERR, ("Unable to get public ips from node %u\n", options.pnn));
1904                 talloc_free(tmp_ctx);
1905                 return ret;
1906         }
1907
1908         if (options.machinereadable){
1909                 printf(":Public IP:Node:");
1910                 if (options.verbose){
1911                         printf("ActiveInterface:AvailableInterfaces:ConfiguredInterfaces:");
1912                 }
1913                 printf("\n");
1914         } else {
1915                 if (options.pnn == CTDB_BROADCAST_ALL) {
1916                         printf("Public IPs on ALL nodes\n");
1917                 } else {
1918                         printf("Public IPs on node %u\n", options.pnn);
1919                 }
1920         }
1921
1922         for (i=1;i<=ips->num;i++) {
1923                 struct ctdb_control_public_ip_info *info = NULL;
1924                 int32_t pnn;
1925                 char *aciface = NULL;
1926                 char *avifaces = NULL;
1927                 char *cifaces = NULL;
1928
1929                 if (options.pnn == CTDB_BROADCAST_ALL) {
1930                         pnn = ips->ips[ips->num-i].pnn;
1931                 } else {
1932                         pnn = options.pnn;
1933                 }
1934
1935                 if (pnn != -1) {
1936                         ret = ctdb_ctrl_get_public_ip_info(ctdb, TIMELIMIT(), pnn, ctdb,
1937                                                    &ips->ips[ips->num-i].addr, &info);
1938                 } else {
1939                         ret = -1;
1940                 }
1941
1942                 if (ret == 0) {
1943                         int j;
1944                         for (j=0; j < info->num; j++) {
1945                                 if (cifaces == NULL) {
1946                                         cifaces = talloc_strdup(info,
1947                                                                 info->ifaces[j].name);
1948                                 } else {
1949                                         cifaces = talloc_asprintf_append(cifaces,
1950                                                                          ",%s",
1951                                                                          info->ifaces[j].name);
1952                                 }
1953
1954                                 if (info->active_idx == j) {
1955                                         aciface = info->ifaces[j].name;
1956                                 }
1957
1958                                 if (info->ifaces[j].link_state == 0) {
1959                                         continue;
1960                                 }
1961
1962                                 if (avifaces == NULL) {
1963                                         avifaces = talloc_strdup(info, info->ifaces[j].name);
1964                                 } else {
1965                                         avifaces = talloc_asprintf_append(avifaces,
1966                                                                           ",%s",
1967                                                                           info->ifaces[j].name);
1968                                 }
1969                         }
1970                 }
1971
1972                 if (options.machinereadable){
1973                         printf(":%s:%d:",
1974                                 ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
1975                                 ips->ips[ips->num-i].pnn);
1976                         if (options.verbose){
1977                                 printf("%s:%s:%s:",
1978                                         aciface?aciface:"",
1979                                         avifaces?avifaces:"",
1980                                         cifaces?cifaces:"");
1981                         }
1982                         printf("\n");
1983                 } else {
1984                         if (options.verbose) {
1985                                 printf("%s node[%d] active[%s] available[%s] configured[%s]\n",
1986                                         ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
1987                                         ips->ips[ips->num-i].pnn,
1988                                         aciface?aciface:"",
1989                                         avifaces?avifaces:"",
1990                                         cifaces?cifaces:"");
1991                         } else {
1992                                 printf("%s %d\n",
1993                                         ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
1994                                         ips->ips[ips->num-i].pnn);
1995                         }
1996                 }
1997                 talloc_free(info);
1998         }
1999
2000         talloc_free(tmp_ctx);
2001         return 0;
2002 }
2003
2004 /*
2005   public ip info
2006  */
2007 static int control_ipinfo(struct ctdb_context *ctdb, int argc, const char **argv)
2008 {
2009         int i, ret;
2010         ctdb_sock_addr addr;
2011         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2012         struct ctdb_control_public_ip_info *info;
2013
2014         if (argc != 1) {
2015                 talloc_free(tmp_ctx);
2016                 usage();
2017         }
2018
2019         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
2020                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
2021                 return -1;
2022         }
2023
2024         /* read the public ip info from this node */
2025         ret = ctdb_ctrl_get_public_ip_info(ctdb, TIMELIMIT(), options.pnn,
2026                                            tmp_ctx, &addr, &info);
2027         if (ret != 0) {
2028                 DEBUG(DEBUG_ERR, ("Unable to get public ip[%s]info from node %u\n",
2029                                   argv[0], options.pnn));
2030                 talloc_free(tmp_ctx);
2031                 return ret;
2032         }
2033
2034         printf("Public IP[%s] info on node %u\n",
2035                ctdb_addr_to_str(&info->ip.addr),
2036                options.pnn);
2037
2038         printf("IP:%s\nCurrentNode:%d\nNumInterfaces:%u\n",
2039                ctdb_addr_to_str(&info->ip.addr),
2040                info->ip.pnn, info->num);
2041
2042         for (i=0; i<info->num; i++) {
2043                 info->ifaces[i].name[CTDB_IFACE_SIZE] = '\0';
2044
2045                 printf("Interface[%u]: Name:%s Link:%s References:%u%s\n",
2046                        i+1, info->ifaces[i].name,
2047                        info->ifaces[i].link_state?"up":"down",
2048                        (unsigned int)info->ifaces[i].references,
2049                        (i==info->active_idx)?" (active)":"");
2050         }
2051
2052         talloc_free(tmp_ctx);
2053         return 0;
2054 }
2055
2056 /*
2057   display interfaces status
2058  */
2059 static int control_ifaces(struct ctdb_context *ctdb, int argc, const char **argv)
2060 {
2061         int i, ret;
2062         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2063         struct ctdb_control_get_ifaces *ifaces;
2064
2065         /* read the public ip list from this node */
2066         ret = ctdb_ctrl_get_ifaces(ctdb, TIMELIMIT(), options.pnn,
2067                                    tmp_ctx, &ifaces);
2068         if (ret != 0) {
2069                 DEBUG(DEBUG_ERR, ("Unable to get interfaces from node %u\n",
2070                                   options.pnn));
2071                 talloc_free(tmp_ctx);
2072                 return ret;
2073         }
2074
2075         if (options.machinereadable){
2076                 printf(":Name:LinkStatus:References:\n");
2077         } else {
2078                 printf("Interfaces on node %u\n", options.pnn);
2079         }
2080
2081         for (i=0; i<ifaces->num; i++) {
2082                 if (options.machinereadable){
2083                         printf(":%s:%s:%u\n",
2084                                ifaces->ifaces[i].name,
2085                                ifaces->ifaces[i].link_state?"1":"0",
2086                                (unsigned int)ifaces->ifaces[i].references);
2087                 } else {
2088                         printf("name:%s link:%s references:%u\n",
2089                                ifaces->ifaces[i].name,
2090                                ifaces->ifaces[i].link_state?"up":"down",
2091                                (unsigned int)ifaces->ifaces[i].references);
2092                 }
2093         }
2094
2095         talloc_free(tmp_ctx);
2096         return 0;
2097 }
2098
2099
2100 /*
2101   set link status of an interface
2102  */
2103 static int control_setifacelink(struct ctdb_context *ctdb, int argc, const char **argv)
2104 {
2105         int ret;
2106         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2107         struct ctdb_control_iface_info info;
2108
2109         ZERO_STRUCT(info);
2110
2111         if (argc != 2) {
2112                 usage();
2113         }
2114
2115         if (strlen(argv[0]) > CTDB_IFACE_SIZE) {
2116                 DEBUG(DEBUG_ERR, ("interfaces name '%s' too long\n",
2117                                   argv[0]));
2118                 talloc_free(tmp_ctx);
2119                 return -1;
2120         }
2121         strcpy(info.name, argv[0]);
2122
2123         if (strcmp(argv[1], "up") == 0) {
2124                 info.link_state = 1;
2125         } else if (strcmp(argv[1], "down") == 0) {
2126                 info.link_state = 0;
2127         } else {
2128                 DEBUG(DEBUG_ERR, ("link state invalid '%s' should be 'up' or 'down'\n",
2129                                   argv[1]));
2130                 talloc_free(tmp_ctx);
2131                 return -1;
2132         }
2133
2134         /* read the public ip list from this node */
2135         ret = ctdb_ctrl_set_iface_link(ctdb, TIMELIMIT(), options.pnn,
2136                                    tmp_ctx, &info);
2137         if (ret != 0) {
2138                 DEBUG(DEBUG_ERR, ("Unable to set link state for interfaces %s node %u\n",
2139                                   argv[0], options.pnn));
2140                 talloc_free(tmp_ctx);
2141                 return ret;
2142         }
2143
2144         talloc_free(tmp_ctx);
2145         return 0;
2146 }
2147
2148 /*
2149   display pid of a ctdb daemon
2150  */
2151 static int control_getpid(struct ctdb_context *ctdb, int argc, const char **argv)
2152 {
2153         uint32_t pid;
2154         int ret;
2155
2156         ret = ctdb_ctrl_getpid(ctdb, TIMELIMIT(), options.pnn, &pid);
2157         if (ret != 0) {
2158                 DEBUG(DEBUG_ERR, ("Unable to get daemon pid from node %u\n", options.pnn));
2159                 return ret;
2160         }
2161         printf("Pid:%d\n", pid);
2162
2163         return 0;
2164 }
2165
2166 static uint32_t ipreallocate_finished;
2167
2168 /*
2169   handler for receiving the response to ipreallocate
2170 */
2171 static void ip_reallocate_handler(struct ctdb_context *ctdb, uint64_t srvid, 
2172                              TDB_DATA data, void *private_data)
2173 {
2174         ipreallocate_finished = 1;
2175 }
2176
2177 static void ctdb_every_second(struct event_context *ev, struct timed_event *te, struct timeval t, void *p)
2178 {
2179         struct ctdb_context *ctdb = talloc_get_type(p, struct ctdb_context);
2180
2181         event_add_timed(ctdb->ev, ctdb, 
2182                                 timeval_current_ofs(1, 0),
2183                                 ctdb_every_second, ctdb);
2184 }
2185
2186 /*
2187   ask the recovery daemon on the recovery master to perform a ip reallocation
2188  */
2189 static int control_ipreallocate(struct ctdb_context *ctdb, int argc, const char **argv)
2190 {
2191         int i, ret;
2192         TDB_DATA data;
2193         struct takeover_run_reply rd;
2194         uint32_t recmaster;
2195         struct ctdb_node_map *nodemap=NULL;
2196         int retries=0;
2197         struct timeval tv = timeval_current();
2198
2199         /* we need some events to trigger so we can timeout and restart
2200            the loop
2201         */
2202         event_add_timed(ctdb->ev, ctdb, 
2203                                 timeval_current_ofs(1, 0),
2204                                 ctdb_every_second, ctdb);
2205
2206         rd.pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
2207         if (rd.pnn == -1) {
2208                 DEBUG(DEBUG_ERR, ("Failed to get pnn of local node\n"));
2209                 return -1;
2210         }
2211         rd.srvid = getpid();
2212
2213         /* register a message port for receiveing the reply so that we
2214            can receive the reply
2215         */
2216         ctdb_client_set_message_handler(ctdb, rd.srvid, ip_reallocate_handler, NULL);
2217
2218         data.dptr = (uint8_t *)&rd;
2219         data.dsize = sizeof(rd);
2220
2221 again:
2222         /* check that there are valid nodes available */
2223         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb, &nodemap) != 0) {
2224                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2225                 return -1;
2226         }
2227         for (i=0; i<nodemap->num;i++) {
2228                 if ((nodemap->nodes[i].flags & (NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_STOPPED)) == 0) {
2229                         break;
2230                 }
2231         }
2232         if (i==nodemap->num) {
2233                 DEBUG(DEBUG_ERR,("No recmaster available, no need to wait for cluster convergence\n"));
2234                 return 0;
2235         }
2236
2237
2238         ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmaster);
2239         if (ret != 0) {
2240                 DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
2241                 return ret;
2242         }
2243
2244         /* verify the node exists */
2245         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), recmaster, ctdb, &nodemap) != 0) {
2246                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2247                 return -1;
2248         }
2249
2250
2251         /* check tha there are nodes available that can act as a recmaster */
2252         for (i=0; i<nodemap->num; i++) {
2253                 if (nodemap->nodes[i].flags & (NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_STOPPED)) {
2254                         continue;
2255                 }
2256                 break;
2257         }
2258         if (i == nodemap->num) {
2259                 DEBUG(DEBUG_ERR,("No possible nodes to host addresses.\n"));
2260                 return 0;
2261         }
2262
2263         /* verify the recovery master is not STOPPED, nor BANNED */
2264         if (nodemap->nodes[recmaster].flags & (NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_STOPPED)) {
2265                 DEBUG(DEBUG_ERR,("No suitable recmaster found. Try again\n"));
2266                 retries++;
2267                 sleep(1);
2268                 goto again;
2269         } 
2270
2271         
2272         /* verify the recovery master is not STOPPED, nor BANNED */
2273         if (nodemap->nodes[recmaster].flags & (NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_STOPPED)) {
2274                 DEBUG(DEBUG_ERR,("No suitable recmaster found. Try again\n"));
2275                 retries++;
2276                 sleep(1);
2277                 goto again;
2278         } 
2279
2280         ipreallocate_finished = 0;
2281         ret = ctdb_client_send_message(ctdb, recmaster, CTDB_SRVID_TAKEOVER_RUN, data);
2282         if (ret != 0) {
2283                 DEBUG(DEBUG_ERR,("Failed to send ip takeover run request message to %u\n", options.pnn));
2284                 return -1;
2285         }
2286
2287         tv = timeval_current();
2288         /* this loop will terminate when we have received the reply */
2289         while (timeval_elapsed(&tv) < 3.0) {
2290                 event_loop_once(ctdb->ev);
2291         }
2292         if (ipreallocate_finished == 1) {
2293                 return 0;
2294         }
2295
2296         retries++;
2297         sleep(1);
2298         goto again;
2299
2300         return 0;
2301 }
2302
2303
2304 /*
2305   disable a remote node
2306  */
2307 static int control_disable(struct ctdb_context *ctdb, int argc, const char **argv)
2308 {
2309         int ret;
2310         struct ctdb_node_map *nodemap=NULL;
2311
2312         /* check if the node is already disabled */
2313         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2314                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2315                 exit(10);
2316         }
2317         if (nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
2318                 DEBUG(DEBUG_ERR,("Node %d is already disabled.\n", options.pnn));
2319                 return 0;
2320         }
2321
2322         do {
2323                 ret = ctdb_ctrl_modflags(ctdb, TIMELIMIT(), options.pnn, NODE_FLAGS_PERMANENTLY_DISABLED, 0);
2324                 if (ret != 0) {
2325                         DEBUG(DEBUG_ERR, ("Unable to disable node %u\n", options.pnn));
2326                         return ret;
2327                 }
2328
2329                 sleep(1);
2330
2331                 /* read the nodemap and verify the change took effect */
2332                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2333                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2334                         exit(10);
2335                 }
2336
2337         } while (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED));
2338         ret = control_ipreallocate(ctdb, argc, argv);
2339         if (ret != 0) {
2340                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2341                 return ret;
2342         }
2343
2344         return 0;
2345 }
2346
2347 /*
2348   enable a disabled remote node
2349  */
2350 static int control_enable(struct ctdb_context *ctdb, int argc, const char **argv)
2351 {
2352         int ret;
2353
2354         struct ctdb_node_map *nodemap=NULL;
2355
2356
2357         /* check if the node is already enabled */
2358         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2359                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2360                 exit(10);
2361         }
2362         if (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED)) {
2363                 DEBUG(DEBUG_ERR,("Node %d is already enabled.\n", options.pnn));
2364                 return 0;
2365         }
2366
2367         do {
2368                 ret = ctdb_ctrl_modflags(ctdb, TIMELIMIT(), options.pnn, 0, NODE_FLAGS_PERMANENTLY_DISABLED);
2369                 if (ret != 0) {
2370                         DEBUG(DEBUG_ERR, ("Unable to enable node %u\n", options.pnn));
2371                         return ret;
2372                 }
2373
2374                 sleep(1);
2375
2376                 /* read the nodemap and verify the change took effect */
2377                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2378                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2379                         exit(10);
2380                 }
2381
2382         } while (nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED);
2383
2384         ret = control_ipreallocate(ctdb, argc, argv);
2385         if (ret != 0) {
2386                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2387                 return ret;
2388         }
2389
2390         return 0;
2391 }
2392
2393 /*
2394   stop a remote node
2395  */
2396 static int control_stop(struct ctdb_context *ctdb, int argc, const char **argv)
2397 {
2398         int ret;
2399         struct ctdb_node_map *nodemap=NULL;
2400
2401         do {
2402                 ret = ctdb_ctrl_stop_node(ctdb, TIMELIMIT(), options.pnn);
2403                 if (ret != 0) {
2404                         DEBUG(DEBUG_ERR, ("Unable to stop node %u   try again\n", options.pnn));
2405                 }
2406         
2407                 sleep(1);
2408
2409                 /* read the nodemap and verify the change took effect */
2410                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2411                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2412                         exit(10);
2413                 }
2414
2415         } while (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_STOPPED));
2416         ret = control_ipreallocate(ctdb, argc, argv);
2417         if (ret != 0) {
2418                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2419                 return ret;
2420         }
2421
2422         return 0;
2423 }
2424
2425 /*
2426   restart a stopped remote node
2427  */
2428 static int control_continue(struct ctdb_context *ctdb, int argc, const char **argv)
2429 {
2430         int ret;
2431
2432         struct ctdb_node_map *nodemap=NULL;
2433
2434         do {
2435                 ret = ctdb_ctrl_continue_node(ctdb, TIMELIMIT(), options.pnn);
2436                 if (ret != 0) {
2437                         DEBUG(DEBUG_ERR, ("Unable to continue node %u\n", options.pnn));
2438                         return ret;
2439                 }
2440         
2441                 sleep(1);
2442
2443                 /* read the nodemap and verify the change took effect */
2444                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2445                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2446                         exit(10);
2447                 }
2448
2449         } while (nodemap->nodes[options.pnn].flags & NODE_FLAGS_STOPPED);
2450         ret = control_ipreallocate(ctdb, argc, argv);
2451         if (ret != 0) {
2452                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2453                 return ret;
2454         }
2455
2456         return 0;
2457 }
2458
2459 static uint32_t get_generation(struct ctdb_context *ctdb)
2460 {
2461         struct ctdb_vnn_map *vnnmap=NULL;
2462         int ret;
2463
2464         /* wait until the recmaster is not in recovery mode */
2465         while (1) {
2466                 uint32_t recmode, recmaster;
2467                 
2468                 if (vnnmap != NULL) {
2469                         talloc_free(vnnmap);
2470                         vnnmap = NULL;
2471                 }
2472
2473                 /* get the recmaster */
2474                 ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, &recmaster);
2475                 if (ret != 0) {
2476                         DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
2477                         exit(10);
2478                 }
2479
2480                 /* get recovery mode */
2481                 ret = ctdb_ctrl_getrecmode(ctdb, ctdb, TIMELIMIT(), recmaster, &recmode);
2482                 if (ret != 0) {
2483                         DEBUG(DEBUG_ERR, ("Unable to get recmode from node %u\n", options.pnn));
2484                         exit(10);
2485                 }
2486
2487                 /* get the current generation number */
2488                 ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), recmaster, ctdb, &vnnmap);
2489                 if (ret != 0) {
2490                         DEBUG(DEBUG_ERR, ("Unable to get vnnmap from recmaster (%u)\n", recmaster));
2491                         exit(10);
2492                 }
2493
2494                 if ((recmode == CTDB_RECOVERY_NORMAL)
2495                 &&  (vnnmap->generation != 1)){
2496                         return vnnmap->generation;
2497                 }
2498                 sleep(1);
2499         }
2500 }
2501
2502 /*
2503   ban a node from the cluster
2504  */
2505 static int control_ban(struct ctdb_context *ctdb, int argc, const char **argv)
2506 {
2507         int ret;
2508         struct ctdb_node_map *nodemap=NULL;
2509         struct ctdb_ban_time bantime;
2510
2511         if (argc < 1) {
2512                 usage();
2513         }
2514         
2515         /* verify the node exists */
2516         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
2517         if (ret != 0) {
2518                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2519                 return ret;
2520         }
2521
2522         if (nodemap->nodes[options.pnn].flags & NODE_FLAGS_BANNED) {
2523                 DEBUG(DEBUG_ERR,("Node %u is already banned.\n", options.pnn));
2524                 return -1;
2525         }
2526
2527         bantime.pnn  = options.pnn;
2528         bantime.time = strtoul(argv[0], NULL, 0);
2529
2530         ret = ctdb_ctrl_set_ban(ctdb, TIMELIMIT(), options.pnn, &bantime);
2531         if (ret != 0) {
2532                 DEBUG(DEBUG_ERR,("Banning node %d for %d seconds failed.\n", bantime.pnn, bantime.time));
2533                 return -1;
2534         }       
2535
2536         ret = control_ipreallocate(ctdb, argc, argv);
2537         if (ret != 0) {
2538                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2539                 return ret;
2540         }
2541
2542         return 0;
2543 }
2544
2545
2546 /*
2547   unban a node from the cluster
2548  */
2549 static int control_unban(struct ctdb_context *ctdb, int argc, const char **argv)
2550 {
2551         int ret;
2552         struct ctdb_node_map *nodemap=NULL;
2553         struct ctdb_ban_time bantime;
2554
2555         /* verify the node exists */
2556         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
2557         if (ret != 0) {
2558                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2559                 return ret;
2560         }
2561
2562         if (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_BANNED)) {
2563                 DEBUG(DEBUG_ERR,("Node %u is not banned.\n", options.pnn));
2564                 return -1;
2565         }
2566
2567         bantime.pnn  = options.pnn;
2568         bantime.time = 0;
2569
2570         ret = ctdb_ctrl_set_ban(ctdb, TIMELIMIT(), options.pnn, &bantime);
2571         if (ret != 0) {
2572                 DEBUG(DEBUG_ERR,("Unbanning node %d failed.\n", bantime.pnn));
2573                 return -1;
2574         }       
2575
2576         ret = control_ipreallocate(ctdb, argc, argv);
2577         if (ret != 0) {
2578                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2579                 return ret;
2580         }
2581
2582         return 0;
2583 }
2584
2585
2586 /*
2587   show ban information for a node
2588  */
2589 static int control_showban(struct ctdb_context *ctdb, int argc, const char **argv)
2590 {
2591         int ret;
2592         struct ctdb_node_map *nodemap=NULL;
2593         struct ctdb_ban_time *bantime;
2594
2595         /* verify the node exists */
2596         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
2597         if (ret != 0) {
2598                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2599                 return ret;
2600         }
2601
2602         ret = ctdb_ctrl_get_ban(ctdb, TIMELIMIT(), options.pnn, ctdb, &bantime);
2603         if (ret != 0) {
2604                 DEBUG(DEBUG_ERR,("Showing ban info for node %d failed.\n", options.pnn));
2605                 return -1;
2606         }       
2607
2608         if (bantime->time == 0) {
2609                 printf("Node %u is not banned\n", bantime->pnn);
2610         } else {
2611                 printf("Node %u is banned banned for %d seconds\n", bantime->pnn, bantime->time);
2612         }
2613
2614         return 0;
2615 }
2616
2617 /*
2618   shutdown a daemon
2619  */
2620 static int control_shutdown(struct ctdb_context *ctdb, int argc, const char **argv)
2621 {
2622         int ret;
2623
2624         ret = ctdb_ctrl_shutdown(ctdb, TIMELIMIT(), options.pnn);
2625         if (ret != 0) {
2626                 DEBUG(DEBUG_ERR, ("Unable to shutdown node %u\n", options.pnn));
2627                 return ret;
2628         }
2629
2630         return 0;
2631 }
2632
2633 /*
2634   trigger a recovery
2635  */
2636 static int control_recover(struct ctdb_context *ctdb, int argc, const char **argv)
2637 {
2638         int ret;
2639         uint32_t generation, next_generation;
2640
2641         /* record the current generation number */
2642         generation = get_generation(ctdb);
2643
2644         ret = ctdb_ctrl_freeze_priority(ctdb, TIMELIMIT(), options.pnn, 1);
2645         if (ret != 0) {
2646                 DEBUG(DEBUG_ERR, ("Unable to freeze node\n"));
2647                 return ret;
2648         }
2649
2650         ret = ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
2651         if (ret != 0) {
2652                 DEBUG(DEBUG_ERR, ("Unable to set recovery mode\n"));
2653                 return ret;
2654         }
2655
2656         /* wait until we are in a new generation */
2657         while (1) {
2658                 next_generation = get_generation(ctdb);
2659                 if (next_generation != generation) {
2660                         return 0;
2661                 }
2662                 sleep(1);
2663         }
2664
2665         return 0;
2666 }
2667
2668
2669 /*
2670   display monitoring mode of a remote node
2671  */
2672 static int control_getmonmode(struct ctdb_context *ctdb, int argc, const char **argv)
2673 {
2674         uint32_t monmode;
2675         int ret;
2676
2677         ret = ctdb_ctrl_getmonmode(ctdb, TIMELIMIT(), options.pnn, &monmode);
2678         if (ret != 0) {
2679                 DEBUG(DEBUG_ERR, ("Unable to get monmode from node %u\n", options.pnn));
2680                 return ret;
2681         }
2682         if (!options.machinereadable){
2683                 printf("Monitoring mode:%s (%d)\n",monmode==CTDB_MONITORING_ACTIVE?"ACTIVE":"DISABLED",monmode);
2684         } else {
2685                 printf(":mode:\n");
2686                 printf(":%d:\n",monmode);
2687         }
2688         return 0;
2689 }
2690
2691
2692 /*
2693   display capabilities of a remote node
2694  */
2695 static int control_getcapabilities(struct ctdb_context *ctdb, int argc, const char **argv)
2696 {
2697         uint32_t capabilities;
2698         int ret;
2699
2700         ret = ctdb_ctrl_getcapabilities(ctdb, TIMELIMIT(), options.pnn, &capabilities);
2701         if (ret != 0) {
2702                 DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", options.pnn));
2703                 return ret;
2704         }
2705         
2706         if (!options.machinereadable){
2707                 printf("RECMASTER: %s\n", (capabilities&CTDB_CAP_RECMASTER)?"YES":"NO");
2708                 printf("LMASTER: %s\n", (capabilities&CTDB_CAP_LMASTER)?"YES":"NO");
2709                 printf("LVS: %s\n", (capabilities&CTDB_CAP_LVS)?"YES":"NO");
2710                 printf("NATGW: %s\n", (capabilities&CTDB_CAP_NATGW)?"YES":"NO");
2711         } else {
2712                 printf(":RECMASTER:LMASTER:LVS:NATGW:\n");
2713                 printf(":%d:%d:%d:%d:\n",
2714                         !!(capabilities&CTDB_CAP_RECMASTER),
2715                         !!(capabilities&CTDB_CAP_LMASTER),
2716                         !!(capabilities&CTDB_CAP_LVS),
2717                         !!(capabilities&CTDB_CAP_NATGW));
2718         }
2719         return 0;
2720 }
2721
2722 /*
2723   display lvs configuration
2724  */
2725 static int control_lvs(struct ctdb_context *ctdb, int argc, const char **argv)
2726 {
2727         uint32_t *capabilities;
2728         struct ctdb_node_map *nodemap=NULL;
2729         int i, ret;
2730         int healthy_count = 0;
2731
2732         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb, &nodemap);
2733         if (ret != 0) {
2734                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
2735                 return ret;
2736         }
2737
2738         capabilities = talloc_array(ctdb, uint32_t, nodemap->num);
2739         CTDB_NO_MEMORY(ctdb, capabilities);
2740         
2741         /* collect capabilities for all connected nodes */
2742         for (i=0; i<nodemap->num; i++) {
2743                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2744                         continue;
2745                 }
2746                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
2747                         continue;
2748                 }
2749         
2750                 ret = ctdb_ctrl_getcapabilities(ctdb, TIMELIMIT(), i, &capabilities[i]);
2751                 if (ret != 0) {
2752                         DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", i));
2753                         return ret;
2754                 }
2755
2756                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
2757                         continue;
2758                 }
2759
2760                 if (!(nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY)) {
2761                         healthy_count++;
2762                 }
2763         }
2764
2765         /* Print all LVS nodes */
2766         for (i=0; i<nodemap->num; i++) {
2767                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2768                         continue;
2769                 }
2770                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
2771                         continue;
2772                 }
2773                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
2774                         continue;
2775                 }
2776
2777                 if (healthy_count != 0) {
2778                         if (nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY) {
2779                                 continue;
2780                         }
2781                 }
2782
2783                 printf("%d:%s\n", i, 
2784                         ctdb_addr_to_str(&nodemap->nodes[i].addr));
2785         }
2786
2787         return 0;
2788 }
2789
2790 /*
2791   display who is the lvs master
2792  */
2793 static int control_lvsmaster(struct ctdb_context *ctdb, int argc, const char **argv)
2794 {
2795         uint32_t *capabilities;
2796         struct ctdb_node_map *nodemap=NULL;
2797         int i, ret;
2798         int healthy_count = 0;
2799
2800         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb, &nodemap);
2801         if (ret != 0) {
2802                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
2803                 return ret;
2804         }
2805
2806         capabilities = talloc_array(ctdb, uint32_t, nodemap->num);
2807         CTDB_NO_MEMORY(ctdb, capabilities);
2808         
2809         /* collect capabilities for all connected nodes */
2810         for (i=0; i<nodemap->num; i++) {
2811                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2812                         continue;
2813                 }
2814                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
2815                         continue;
2816                 }
2817         
2818                 ret = ctdb_ctrl_getcapabilities(ctdb, TIMELIMIT(), i, &capabilities[i]);
2819                 if (ret != 0) {
2820                         DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", i));
2821                         return ret;
2822                 }
2823
2824                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
2825                         continue;
2826                 }
2827
2828                 if (!(nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY)) {
2829                         healthy_count++;
2830                 }
2831         }
2832
2833         /* find and show the lvsmaster */
2834         for (i=0; i<nodemap->num; i++) {
2835                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2836                         continue;
2837                 }
2838                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
2839                         continue;
2840                 }
2841                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
2842                         continue;
2843                 }
2844
2845                 if (healthy_count != 0) {
2846                         if (nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY) {
2847                                 continue;
2848                         }
2849                 }
2850
2851                 if (options.machinereadable){
2852                         printf("%d\n", i);
2853                 } else {
2854                         printf("Node %d is LVS master\n", i);
2855                 }
2856                 return 0;
2857         }
2858
2859         printf("There is no LVS master\n");
2860         return -1;
2861 }
2862
2863 /*
2864   disable monitoring on a  node
2865  */
2866 static int control_disable_monmode(struct ctdb_context *ctdb, int argc, const char **argv)
2867 {
2868         
2869         int ret;
2870
2871         ret = ctdb_ctrl_disable_monmode(ctdb, TIMELIMIT(), options.pnn);
2872         if (ret != 0) {
2873                 DEBUG(DEBUG_ERR, ("Unable to disable monmode on node %u\n", options.pnn));
2874                 return ret;
2875         }
2876         printf("Monitoring mode:%s\n","DISABLED");
2877
2878         return 0;
2879 }
2880
2881 /*
2882   enable monitoring on a  node
2883  */
2884 static int control_enable_monmode(struct ctdb_context *ctdb, int argc, const char **argv)
2885 {
2886         
2887         int ret;
2888
2889         ret = ctdb_ctrl_enable_monmode(ctdb, TIMELIMIT(), options.pnn);
2890         if (ret != 0) {
2891                 DEBUG(DEBUG_ERR, ("Unable to enable monmode on node %u\n", options.pnn));
2892                 return ret;
2893         }
2894         printf("Monitoring mode:%s\n","ACTIVE");
2895
2896         return 0;
2897 }
2898
2899 /*
2900   display remote list of keys/data for a db
2901  */
2902 static int control_catdb(struct ctdb_context *ctdb, int argc, const char **argv)
2903 {
2904         const char *db_name;
2905         struct ctdb_db_context *ctdb_db;
2906         int ret;
2907
2908         if (argc < 1) {
2909                 usage();
2910         }
2911
2912         db_name = argv[0];
2913
2914
2915         if (db_exists(ctdb, db_name)) {
2916                 DEBUG(DEBUG_ERR,("Database '%s' does not exist\n", db_name));
2917                 return -1;
2918         }
2919
2920         ctdb_db = ctdb_attach(ctdb, db_name, false, 0);
2921
2922         if (ctdb_db == NULL) {
2923                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
2924                 return -1;
2925         }
2926
2927         /* traverse and dump the cluster tdb */
2928         ret = ctdb_dump_db(ctdb_db, stdout);
2929         if (ret == -1) {
2930                 DEBUG(DEBUG_ERR, ("Unable to dump database\n"));
2931                 DEBUG(DEBUG_ERR, ("Maybe try 'ctdb getdbstatus %s'"
2932                                   " and 'ctdb getvar AllowUnhealthyDBRead'\n",
2933                                   db_name));
2934                 return -1;
2935         }
2936         talloc_free(ctdb_db);
2937
2938         printf("Dumped %d records\n", ret);
2939         return 0;
2940 }
2941
2942
2943 /*
2944   fetch a record from a persistent database
2945  */
2946 static int control_pfetch(struct ctdb_context *ctdb, int argc, const char **argv)
2947 {
2948         const char *db_name;
2949         struct ctdb_db_context *ctdb_db;
2950         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2951         struct ctdb_transaction_handle *h;
2952         TDB_DATA key, data;
2953         int fd, ret;
2954
2955         if (argc < 2) {
2956                 talloc_free(tmp_ctx);
2957                 usage();
2958         }
2959
2960         db_name = argv[0];
2961
2962
2963         if (db_exists(ctdb, db_name)) {
2964                 DEBUG(DEBUG_ERR,("Database '%s' does not exist\n", db_name));
2965                 talloc_free(tmp_ctx);
2966                 return -1;
2967         }
2968
2969         ctdb_db = ctdb_attach(ctdb, db_name, true, 0);
2970
2971         if (ctdb_db == NULL) {
2972                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
2973                 talloc_free(tmp_ctx);
2974                 return -1;
2975         }
2976
2977         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
2978         if (h == NULL) {
2979                 DEBUG(DEBUG_ERR,("Failed to start transaction on database %s\n", db_name));
2980                 talloc_free(tmp_ctx);
2981                 return -1;
2982         }
2983
2984         key.dptr  = discard_const(argv[1]);
2985         key.dsize = strlen(argv[1]);
2986         ret = ctdb_transaction_fetch(h, tmp_ctx, key, &data);
2987         if (ret != 0) {
2988                 DEBUG(DEBUG_ERR,("Failed to fetch record\n"));
2989                 talloc_free(tmp_ctx);
2990                 return -1;
2991         }
2992
2993         if (data.dsize == 0 || data.dptr == NULL) {
2994                 DEBUG(DEBUG_ERR,("Record is empty\n"));
2995                 talloc_free(tmp_ctx);
2996                 return -1;
2997         }
2998
2999         if (argc == 3) {
3000           fd = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0600);
3001                 if (fd == -1) {
3002                         DEBUG(DEBUG_ERR,("Failed to open output file %s\n", argv[2]));
3003                         talloc_free(tmp_ctx);
3004                         return -1;
3005                 }
3006                 write(fd, data.dptr, data.dsize);
3007                 close(fd);
3008         } else {
3009                 write(1, data.dptr, data.dsize);
3010         }
3011
3012         /* abort the transaction */
3013         talloc_free(h);
3014
3015
3016         talloc_free(tmp_ctx);
3017         return 0;
3018 }
3019
3020 /*
3021   fetch a record from a tdb-file
3022  */
3023 static int control_tfetch(struct ctdb_context *ctdb, int argc, const char **argv)
3024 {
3025         const char *tdb_file;
3026         TDB_CONTEXT *tdb;
3027         TDB_DATA key, data;
3028         int fd;
3029
3030         if (argc < 2) {
3031                 usage();
3032         }
3033
3034         tdb_file = argv[0];
3035
3036         tdb = tdb_open(tdb_file, 0, 0, O_RDONLY, 0);
3037         if (tdb == NULL) {
3038                 DEBUG(DEBUG_ERR,("Failed to open TDB file %s\n", tdb_file));
3039                 return -1;
3040         }
3041
3042         key.dptr  = discard_const(argv[1]);
3043         key.dsize = strlen(argv[1]);
3044         data = tdb_fetch(tdb, key);
3045         if (data.dptr == NULL || data.dsize < sizeof(struct ctdb_ltdb_header)) {
3046                 DEBUG(DEBUG_ERR,("Failed to read record %s from tdb %s\n", argv[1], tdb_file));
3047                 tdb_close(tdb);
3048                 return -1;
3049         }
3050
3051         tdb_close(tdb);
3052
3053         if (argc == 3) {
3054           fd = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0600);
3055                 if (fd == -1) {
3056                         DEBUG(DEBUG_ERR,("Failed to open output file %s\n", argv[2]));
3057                         return -1;
3058                 }
3059                 write(fd, data.dptr+sizeof(struct ctdb_ltdb_header), data.dsize-sizeof(struct ctdb_ltdb_header));
3060                 close(fd);
3061         } else {
3062                 write(1, data.dptr+sizeof(struct ctdb_ltdb_header), data.dsize-sizeof(struct ctdb_ltdb_header));
3063         }
3064
3065         return 0;
3066 }
3067
3068 /*
3069   write a record to a persistent database
3070  */
3071 static int control_pstore(struct ctdb_context *ctdb, int argc, const char **argv)
3072 {
3073         const char *db_name;
3074         struct ctdb_db_context *ctdb_db;
3075         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3076         struct ctdb_transaction_handle *h;
3077         struct stat st;
3078         TDB_DATA key, data;
3079         int fd, ret;
3080
3081         if (argc < 3) {
3082                 talloc_free(tmp_ctx);
3083                 usage();
3084         }
3085
3086         fd = open(argv[2], O_RDONLY);
3087         if (fd == -1) {
3088                 DEBUG(DEBUG_ERR,("Failed to open file containing record data : %s  %s\n", argv[2], strerror(errno)));
3089                 talloc_free(tmp_ctx);
3090                 return -1;
3091         }
3092         
3093         ret = fstat(fd, &st);
3094         if (ret == -1) {
3095                 DEBUG(DEBUG_ERR,("fstat of file %s failed: %s\n", argv[2], strerror(errno)));
3096                 close(fd);
3097                 talloc_free(tmp_ctx);
3098                 return -1;
3099         }
3100
3101         if (!S_ISREG(st.st_mode)) {
3102                 DEBUG(DEBUG_ERR,("Not a regular file %s\n", argv[2]));
3103                 close(fd);
3104                 talloc_free(tmp_ctx);
3105                 return -1;
3106         }
3107
3108         data.dsize = st.st_size;
3109         if (data.dsize == 0) {
3110                 data.dptr  = NULL;
3111         } else {
3112                 data.dptr = talloc_size(tmp_ctx, data.dsize);
3113                 if (data.dptr == NULL) {
3114                         DEBUG(DEBUG_ERR,("Failed to talloc %d of memory to store record data\n", (int)data.dsize));
3115                         close(fd);
3116                         talloc_free(tmp_ctx);
3117                         return -1;
3118                 }
3119                 ret = read(fd, data.dptr, data.dsize);
3120                 if (ret != data.dsize) {
3121                         DEBUG(DEBUG_ERR,("Failed to read %d bytes of record data\n", (int)data.dsize));
3122                         close(fd);
3123                         talloc_free(tmp_ctx);
3124                         return -1;
3125                 }
3126         }
3127         close(fd);
3128
3129
3130         db_name = argv[0];
3131
3132         ctdb_db = ctdb_attach(ctdb, db_name, true, 0);
3133
3134         if (ctdb_db == NULL) {
3135                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3136                 talloc_free(tmp_ctx);
3137                 return -1;
3138         }
3139
3140         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
3141         if (h == NULL) {
3142                 DEBUG(DEBUG_ERR,("Failed to start transaction on database %s\n", db_name));
3143                 talloc_free(tmp_ctx);
3144                 return -1;
3145         }
3146
3147         key.dptr  = discard_const(argv[1]);
3148         key.dsize = strlen(argv[1]);
3149         ret = ctdb_transaction_store(h, key, data);
3150         if (ret != 0) {
3151                 DEBUG(DEBUG_ERR,("Failed to store record\n"));
3152                 talloc_free(tmp_ctx);
3153                 return -1;
3154         }
3155
3156         ret = ctdb_transaction_commit(h);
3157         if (ret != 0) {
3158                 DEBUG(DEBUG_ERR,("Failed to commit transaction\n"));
3159                 talloc_free(tmp_ctx);
3160                 return -1;
3161         }
3162
3163
3164         talloc_free(tmp_ctx);
3165         return 0;
3166 }
3167
3168 static void log_handler(struct ctdb_context *ctdb, uint64_t srvid, 
3169                              TDB_DATA data, void *private_data)
3170 {
3171         DEBUG(DEBUG_ERR,("Log data received\n"));
3172         if (data.dsize > 0) {
3173                 printf("%s", data.dptr);
3174         }
3175
3176         exit(0);
3177 }
3178
3179 /*
3180   display a list of log messages from the in memory ringbuffer
3181  */
3182 static int control_getlog(struct ctdb_context *ctdb, int argc, const char **argv)
3183 {
3184         int ret;
3185         int32_t res;
3186         struct ctdb_get_log_addr log_addr;
3187         TDB_DATA data;
3188         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3189         char *errmsg;
3190         struct timeval tv;
3191
3192         if (argc != 1) {
3193                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
3194                 talloc_free(tmp_ctx);
3195                 return -1;
3196         }
3197
3198         log_addr.pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
3199         log_addr.srvid = getpid();
3200         if (isalpha(argv[0][0]) || argv[0][0] == '-') { 
3201                 log_addr.level = get_debug_by_desc(argv[0]);
3202         } else {
3203                 log_addr.level = strtol(argv[0], NULL, 0);
3204         }
3205
3206
3207         data.dptr = (unsigned char *)&log_addr;
3208         data.dsize = sizeof(log_addr);
3209
3210         DEBUG(DEBUG_ERR, ("Pulling logs from node %u\n", options.pnn));
3211
3212         ctdb_client_set_message_handler(ctdb, log_addr.srvid, log_handler, NULL);
3213         sleep(1);
3214
3215         DEBUG(DEBUG_ERR,("Listen for response on %d\n", (int)log_addr.srvid));
3216
3217         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_GET_LOG,
3218                            0, data, tmp_ctx, NULL, &res, NULL, &errmsg);
3219         if (ret != 0 || res != 0) {
3220                 DEBUG(DEBUG_ERR,("Failed to get logs - %s\n", errmsg));
3221                 talloc_free(tmp_ctx);
3222                 return -1;
3223         }
3224
3225
3226         tv = timeval_current();
3227         /* this loop will terminate when we have received the reply */
3228         while (timeval_elapsed(&tv) < 3.0) {    
3229                 event_loop_once(ctdb->ev);
3230         }
3231
3232         DEBUG(DEBUG_INFO,("Timed out waiting for log data.\n"));
3233
3234         talloc_free(tmp_ctx);
3235         return 0;
3236 }
3237
3238 /*
3239   clear the in memory log area
3240  */
3241 static int control_clearlog(struct ctdb_context *ctdb, int argc, const char **argv)
3242 {
3243         int ret;
3244         int32_t res;
3245         char *errmsg;
3246         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3247
3248         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_CLEAR_LOG,
3249                            0, tdb_null, tmp_ctx, NULL, &res, NULL, &errmsg);
3250         if (ret != 0 || res != 0) {
3251                 DEBUG(DEBUG_ERR,("Failed to clear logs\n"));
3252                 talloc_free(tmp_ctx);
3253                 return -1;
3254         }
3255
3256         talloc_free(tmp_ctx);
3257         return 0;
3258 }
3259
3260
3261
3262 /*
3263   display a list of the databases on a remote ctdb
3264  */
3265 static int control_getdbmap(struct ctdb_context *ctdb, int argc, const char **argv)
3266 {
3267         int i, ret;
3268         struct ctdb_dbid_map *dbmap=NULL;
3269
3270         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, ctdb, &dbmap);
3271         if (ret != 0) {
3272                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n", options.pnn));
3273                 return ret;
3274         }
3275
3276         if(options.machinereadable){
3277                 printf(":ID:Name:Path:Persistent:Unhealthy:\n");
3278                 for(i=0;i<dbmap->num;i++){
3279                         const char *path;
3280                         const char *name;
3281                         const char *health;
3282                         bool persistent;
3283
3284                         ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn,
3285                                             dbmap->dbs[i].dbid, ctdb, &path);
3286                         ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn,
3287                                             dbmap->dbs[i].dbid, ctdb, &name);
3288                         ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn,
3289                                               dbmap->dbs[i].dbid, ctdb, &health);
3290                         persistent = dbmap->dbs[i].persistent;
3291                         printf(":0x%08X:%s:%s:%d:%d:\n",
3292                                dbmap->dbs[i].dbid, name, path,
3293                                !!(persistent), !!(health));
3294                 }
3295                 return 0;
3296         }
3297
3298         printf("Number of databases:%d\n", dbmap->num);
3299         for(i=0;i<dbmap->num;i++){
3300                 const char *path;
3301                 const char *name;
3302                 const char *health;
3303                 bool persistent;
3304
3305                 ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &path);
3306                 ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &name);
3307                 ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &health);
3308                 persistent = dbmap->dbs[i].persistent;
3309                 printf("dbid:0x%08x name:%s path:%s%s%s\n",
3310                        dbmap->dbs[i].dbid, name, path,
3311                        persistent?" PERSISTENT":"",
3312                        health?" UNHEALTHY":"");
3313         }
3314
3315         return 0;
3316 }
3317
3318 /*
3319   display the status of a database on a remote ctdb
3320  */
3321 static int control_getdbstatus(struct ctdb_context *ctdb, int argc, const char **argv)
3322 {
3323         int i, ret;
3324         struct ctdb_dbid_map *dbmap=NULL;
3325         const char *db_name;
3326
3327         if (argc < 1) {
3328                 usage();
3329         }
3330
3331         db_name = argv[0];
3332
3333         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, ctdb, &dbmap);
3334         if (ret != 0) {
3335                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n", options.pnn));
3336                 return ret;
3337         }
3338
3339         for(i=0;i<dbmap->num;i++){
3340                 const char *path;
3341                 const char *name;
3342                 const char *health;
3343                 bool persistent;
3344
3345                 ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &name);
3346                 if (strcmp(name, db_name) != 0) {
3347                         continue;
3348                 }
3349
3350                 ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &path);
3351                 ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &health);
3352                 persistent = dbmap->dbs[i].persistent;
3353                 printf("dbid: 0x%08x\nname: %s\npath: %s\nPERSISTENT: %s\nHEALTH: %s\n",
3354                        dbmap->dbs[i].dbid, name, path,
3355                        persistent?"yes":"no",
3356                        health?health:"OK");
3357                 return 0;
3358         }
3359
3360         DEBUG(DEBUG_ERR, ("db %s doesn't exist on node %u\n", db_name, options.pnn));
3361         return 0;
3362 }
3363
3364 /*
3365   check if the local node is recmaster or not
3366   it will return 1 if this node is the recmaster and 0 if it is not
3367   or if the local ctdb daemon could not be contacted
3368  */
3369 static int control_isnotrecmaster(struct ctdb_context *ctdb, int argc, const char **argv)
3370 {
3371         uint32_t mypnn, recmaster;
3372         int ret;
3373
3374         mypnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), options.pnn);
3375         if (mypnn == -1) {
3376                 printf("Failed to get pnn of node\n");
3377                 return 1;
3378         }
3379
3380         ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmaster);
3381         if (ret != 0) {
3382                 printf("Failed to get the recmaster\n");
3383                 return 1;
3384         }
3385
3386         if (recmaster != mypnn) {
3387                 printf("this node is not the recmaster\n");
3388                 return 1;
3389         }
3390
3391         printf("this node is the recmaster\n");
3392         return 0;
3393 }
3394
3395 /*
3396   ping a node
3397  */
3398 static int control_ping(struct ctdb_context *ctdb, int argc, const char **argv)
3399 {
3400         int ret;
3401         struct timeval tv = timeval_current();
3402         ret = ctdb_ctrl_ping(ctdb, options.pnn);
3403         if (ret == -1) {
3404                 printf("Unable to get ping response from node %u\n", options.pnn);
3405                 return -1;
3406         } else {
3407                 printf("response from %u time=%.6f sec  (%d clients)\n", 
3408                        options.pnn, timeval_elapsed(&tv), ret);
3409         }
3410         return 0;
3411 }
3412
3413
3414 /*
3415   get a tunable
3416  */
3417 static int control_getvar(struct ctdb_context *ctdb, int argc, const char **argv)
3418 {
3419         const char *name;
3420         uint32_t value;
3421         int ret;
3422
3423         if (argc < 1) {
3424                 usage();
3425         }
3426
3427         name = argv[0];
3428         ret = ctdb_ctrl_get_tunable(ctdb, TIMELIMIT(), options.pnn, name, &value);
3429         if (ret == -1) {
3430                 DEBUG(DEBUG_ERR, ("Unable to get tunable variable '%s'\n", name));
3431                 return -1;
3432         }
3433
3434         printf("%-19s = %u\n", name, value);
3435         return 0;
3436 }
3437
3438 /*
3439   set a tunable
3440  */
3441 static int control_setvar(struct ctdb_context *ctdb, int argc, const char **argv)
3442 {
3443         const char *name;
3444         uint32_t value;
3445         int ret;
3446
3447         if (argc < 2) {
3448                 usage();
3449         }
3450
3451         name = argv[0];
3452         value = strtoul(argv[1], NULL, 0);
3453
3454         ret = ctdb_ctrl_set_tunable(ctdb, TIMELIMIT(), options.pnn, name, value);
3455         if (ret == -1) {
3456                 DEBUG(DEBUG_ERR, ("Unable to set tunable variable '%s'\n", name));
3457                 return -1;
3458         }
3459         return 0;
3460 }
3461
3462 /*
3463   list all tunables
3464  */
3465 static int control_listvars(struct ctdb_context *ctdb, int argc, const char **argv)
3466 {
3467         uint32_t count;
3468         const char **list;
3469         int ret, i;
3470
3471         ret = ctdb_ctrl_list_tunables(ctdb, TIMELIMIT(), options.pnn, ctdb, &list, &count);
3472         if (ret == -1) {
3473                 DEBUG(DEBUG_ERR, ("Unable to list tunable variables\n"));
3474                 return -1;
3475         }
3476
3477         for (i=0;i<count;i++) {
3478                 control_getvar(ctdb, 1, &list[i]);
3479         }
3480
3481         talloc_free(list);
3482         
3483         return 0;
3484 }
3485
3486 /*
3487   display debug level on a node
3488  */
3489 static int control_getdebug(struct ctdb_context *ctdb, int argc, const char **argv)
3490 {
3491         int ret;
3492         int32_t level;
3493
3494         ret = ctdb_ctrl_get_debuglevel(ctdb, options.pnn, &level);
3495         if (ret != 0) {
3496                 DEBUG(DEBUG_ERR, ("Unable to get debuglevel response from node %u\n", options.pnn));
3497                 return ret;
3498         } else {
3499                 if (options.machinereadable){
3500                         printf(":Name:Level:\n");
3501                         printf(":%s:%d:\n",get_debug_by_level(level),level);
3502                 } else {
3503                         printf("Node %u is at debug level %s (%d)\n", options.pnn, get_debug_by_level(level), level);
3504                 }
3505         }
3506         return 0;
3507 }
3508
3509 /*
3510   display reclock file of a node
3511  */
3512 static int control_getreclock(struct ctdb_context *ctdb, int argc, const char **argv)
3513 {
3514         int ret;
3515         const char *reclock;
3516
3517         ret = ctdb_ctrl_getreclock(ctdb, TIMELIMIT(), options.pnn, ctdb, &reclock);
3518         if (ret != 0) {
3519                 DEBUG(DEBUG_ERR, ("Unable to get reclock file from node %u\n", options.pnn));
3520                 return ret;
3521         } else {
3522                 if (options.machinereadable){
3523                         if (reclock != NULL) {
3524                                 printf("%s", reclock);
3525                         }
3526                 } else {
3527                         if (reclock == NULL) {
3528                                 printf("No reclock file used.\n");
3529                         } else {
3530                                 printf("Reclock file:%s\n", reclock);
3531                         }
3532                 }
3533         }
3534         return 0;
3535 }
3536
3537 /*
3538   set the reclock file of a node
3539  */
3540 static int control_setreclock(struct ctdb_context *ctdb, int argc, const char **argv)
3541 {
3542         int ret;
3543         const char *reclock;
3544
3545         if (argc == 0) {
3546                 reclock = NULL;
3547         } else if (argc == 1) {
3548                 reclock = argv[0];
3549         } else {
3550                 usage();
3551         }
3552
3553         ret = ctdb_ctrl_setreclock(ctdb, TIMELIMIT(), options.pnn, reclock);
3554         if (ret != 0) {
3555                 DEBUG(DEBUG_ERR, ("Unable to get reclock file from node %u\n", options.pnn));
3556                 return ret;
3557         }
3558         return 0;
3559 }
3560
3561 /*
3562   set the natgw state on/off
3563  */
3564 static int control_setnatgwstate(struct ctdb_context *ctdb, int argc, const char **argv)
3565 {
3566         int ret;
3567         uint32_t natgwstate;
3568
3569         if (argc == 0) {
3570                 usage();
3571         }
3572
3573         if (!strcmp(argv[0], "on")) {
3574                 natgwstate = 1;
3575         } else if (!strcmp(argv[0], "off")) {
3576                 natgwstate = 0;
3577         } else {
3578                 usage();
3579         }
3580
3581         ret = ctdb_ctrl_setnatgwstate(ctdb, TIMELIMIT(), options.pnn, natgwstate);
3582         if (ret != 0) {
3583                 DEBUG(DEBUG_ERR, ("Unable to set the natgw state for node %u\n", options.pnn));
3584                 return ret;
3585         }
3586
3587         return 0;
3588 }
3589
3590 /*
3591   set the lmaster role on/off
3592  */
3593 static int control_setlmasterrole(struct ctdb_context *ctdb, int argc, const char **argv)
3594 {
3595         int ret;
3596         uint32_t lmasterrole;
3597
3598         if (argc == 0) {
3599                 usage();
3600         }
3601
3602         if (!strcmp(argv[0], "on")) {
3603                 lmasterrole = 1;
3604         } else if (!strcmp(argv[0], "off")) {
3605                 lmasterrole = 0;
3606         } else {
3607                 usage();
3608         }
3609
3610         ret = ctdb_ctrl_setlmasterrole(ctdb, TIMELIMIT(), options.pnn, lmasterrole);
3611         if (ret != 0) {
3612                 DEBUG(DEBUG_ERR, ("Unable to set the lmaster role for node %u\n", options.pnn));
3613                 return ret;
3614         }
3615
3616         return 0;
3617 }
3618
3619 /*
3620   set the recmaster role on/off
3621  */
3622 static int control_setrecmasterrole(struct ctdb_context *ctdb, int argc, const char **argv)
3623 {
3624         int ret;
3625         uint32_t recmasterrole;
3626
3627         if (argc == 0) {
3628                 usage();
3629         }
3630
3631         if (!strcmp(argv[0], "on")) {
3632                 recmasterrole = 1;
3633         } else if (!strcmp(argv[0], "off")) {
3634                 recmasterrole = 0;
3635         } else {
3636                 usage();
3637         }
3638
3639         ret = ctdb_ctrl_setrecmasterrole(ctdb, TIMELIMIT(), options.pnn, recmasterrole);
3640         if (ret != 0) {
3641                 DEBUG(DEBUG_ERR, ("Unable to set the recmaster role for node %u\n", options.pnn));
3642                 return ret;
3643         }
3644
3645         return 0;
3646 }
3647
3648 /*
3649   set debug level on a node or all nodes
3650  */
3651 static int control_setdebug(struct ctdb_context *ctdb, int argc, const char **argv)
3652 {
3653         int i, ret;
3654         int32_t level;
3655
3656         if (argc == 0) {
3657                 printf("You must specify the debug level. Valid levels are:\n");
3658                 for (i=0; debug_levels[i].description != NULL; i++) {
3659                         printf("%s (%d)\n", debug_levels[i].description, debug_levels[i].level);
3660                 }
3661
3662                 return 0;
3663         }
3664
3665         if (isalpha(argv[0][0]) || argv[0][0] == '-') { 
3666                 level = get_debug_by_desc(argv[0]);
3667         } else {
3668                 level = strtol(argv[0], NULL, 0);
3669         }
3670
3671         for (i=0; debug_levels[i].description != NULL; i++) {
3672                 if (level == debug_levels[i].level) {
3673                         break;
3674                 }
3675         }
3676         if (debug_levels[i].description == NULL) {
3677                 printf("Invalid debug level, must be one of\n");
3678                 for (i=0; debug_levels[i].description != NULL; i++) {
3679                         printf("%s (%d)\n", debug_levels[i].description, debug_levels[i].level);
3680                 }
3681                 return -1;
3682         }
3683
3684         ret = ctdb_ctrl_set_debuglevel(ctdb, options.pnn, level);
3685         if (ret != 0) {
3686                 DEBUG(DEBUG_ERR, ("Unable to set debug level on node %u\n", options.pnn));
3687         }
3688         return 0;
3689 }
3690
3691
3692 /*
3693   thaw a node
3694  */
3695 static int control_thaw(struct ctdb_context *ctdb, int argc, const char **argv)
3696 {
3697         int ret;
3698         uint32_t priority;
3699         
3700         if (argc == 1) {
3701                 priority = strtol(argv[0], NULL, 0);
3702         } else {
3703                 priority = 0;
3704         }
3705         DEBUG(DEBUG_ERR,("Thaw by priority %u\n", priority));
3706
3707         ret = ctdb_ctrl_thaw_priority(ctdb, TIMELIMIT(), options.pnn, priority);
3708         if (ret != 0) {
3709                 DEBUG(DEBUG_ERR, ("Unable to thaw node %u\n", options.pnn));
3710         }               
3711         return 0;
3712 }
3713
3714
3715 /*
3716   attach to a database
3717  */
3718 static int control_attach(struct ctdb_context *ctdb, int argc, const char **argv)
3719 {
3720         const char *db_name;
3721         struct ctdb_db_context *ctdb_db;
3722
3723         if (argc < 1) {
3724                 usage();
3725         }
3726         db_name = argv[0];
3727
3728         ctdb_db = ctdb_attach(ctdb, db_name, false, 0);
3729         if (ctdb_db == NULL) {
3730                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3731                 return -1;
3732         }
3733
3734         return 0;
3735 }
3736
3737 /*
3738   set db priority
3739  */
3740 static int control_setdbprio(struct ctdb_context *ctdb, int argc, const char **argv)
3741 {
3742         struct ctdb_db_priority db_prio;
3743         int ret;
3744
3745         if (argc < 2) {
3746                 usage();
3747         }
3748
3749         db_prio.db_id    = strtoul(argv[0], NULL, 0);
3750         db_prio.priority = strtoul(argv[1], NULL, 0);
3751
3752         ret = ctdb_ctrl_set_db_priority(ctdb, TIMELIMIT(), options.pnn, &db_prio);
3753         if (ret != 0) {
3754                 DEBUG(DEBUG_ERR,("Unable to set db prio\n"));
3755                 return -1;
3756         }
3757
3758         return 0;
3759 }
3760
3761 /*
3762   get db priority
3763  */
3764 static int control_getdbprio(struct ctdb_context *ctdb, int argc, const char **argv)
3765 {
3766         uint32_t db_id, priority;
3767         int ret;
3768
3769         if (argc < 1) {
3770                 usage();
3771         }
3772
3773         db_id = strtoul(argv[0], NULL, 0);
3774
3775         ret = ctdb_ctrl_get_db_priority(ctdb, TIMELIMIT(), options.pnn, db_id, &priority);
3776         if (ret != 0) {
3777                 DEBUG(DEBUG_ERR,("Unable to get db prio\n"));
3778                 return -1;
3779         }
3780
3781         DEBUG(DEBUG_ERR,("Priority:%u\n", priority));
3782
3783         return 0;
3784 }
3785
3786 /*
3787   run an eventscript on a node
3788  */
3789 static int control_eventscript(struct ctdb_context *ctdb, int argc, const char **argv)
3790 {
3791         TDB_DATA data;
3792         int ret;
3793         int32_t res;
3794         char *errmsg;
3795         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3796
3797         if (argc != 1) {
3798                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
3799                 return -1;
3800         }
3801
3802         data.dptr = (unsigned char *)discard_const(argv[0]);
3803         data.dsize = strlen((char *)data.dptr) + 1;
3804
3805         DEBUG(DEBUG_ERR, ("Running eventscripts with arguments \"%s\" on node %u\n", data.dptr, options.pnn));
3806
3807         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_RUN_EVENTSCRIPTS,
3808                            0, data, tmp_ctx, NULL, &res, NULL, &errmsg);
3809         if (ret != 0 || res != 0) {
3810                 DEBUG(DEBUG_ERR,("Failed to run eventscripts - %s\n", errmsg));
3811                 talloc_free(tmp_ctx);
3812                 return -1;
3813         }
3814         talloc_free(tmp_ctx);
3815         return 0;
3816 }
3817
3818 #define DB_VERSION 1
3819 #define MAX_DB_NAME 64
3820 struct db_file_header {
3821         unsigned long version;
3822         time_t timestamp;
3823         unsigned long persistent;
3824         unsigned long size;
3825         const char name[MAX_DB_NAME];
3826 };
3827
3828 struct backup_data {
3829         struct ctdb_marshall_buffer *records;
3830         uint32_t len;
3831         uint32_t total;
3832         bool traverse_error;
3833 };
3834
3835 static int backup_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
3836 {
3837         struct backup_data *bd = talloc_get_type(private, struct backup_data);
3838         struct ctdb_rec_data *rec;
3839
3840         /* add the record */
3841         rec = ctdb_marshall_record(bd->records, 0, key, NULL, data);
3842         if (rec == NULL) {
3843                 bd->traverse_error = true;
3844                 DEBUG(DEBUG_ERR,("Failed to marshall record\n"));
3845                 return -1;
3846         }
3847         bd->records = talloc_realloc_size(NULL, bd->records, rec->length + bd->len);
3848         if (bd->records == NULL) {
3849                 DEBUG(DEBUG_ERR,("Failed to expand marshalling buffer\n"));
3850                 bd->traverse_error = true;
3851                 return -1;
3852         }
3853         bd->records->count++;
3854         memcpy(bd->len+(uint8_t *)bd->records, rec, rec->length);
3855         bd->len += rec->length;
3856         talloc_free(rec);
3857
3858         bd->total++;
3859         return 0;
3860 }
3861
3862 /*
3863  * backup a database to a file 
3864  */
3865 static int control_backupdb(struct ctdb_context *ctdb, int argc, const char **argv)
3866 {
3867         int i, ret;
3868         struct ctdb_dbid_map *dbmap=NULL;
3869         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3870         struct db_file_header dbhdr;
3871         struct ctdb_db_context *ctdb_db;
3872         struct backup_data *bd;
3873         int fh = -1;
3874         int status = -1;
3875         const char *reason = NULL;
3876
3877         if (argc != 2) {
3878                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
3879                 return -1;
3880         }
3881
3882         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &dbmap);
3883         if (ret != 0) {
3884                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n", options.pnn));
3885                 return ret;
3886         }
3887
3888         for(i=0;i<dbmap->num;i++){
3889                 const char *name;
3890
3891                 ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, tmp_ctx, &name);
3892                 if(!strcmp(argv[0], name)){
3893                         talloc_free(discard_const(name));
3894                         break;
3895                 }
3896                 talloc_free(discard_const(name));
3897         }
3898         if (i == dbmap->num) {
3899                 DEBUG(DEBUG_ERR,("No database with name '%s' found\n", argv[0]));
3900                 talloc_free(tmp_ctx);
3901                 return -1;
3902         }
3903
3904         ret = ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn,
3905                                     dbmap->dbs[i].dbid, tmp_ctx, &reason);
3906         if (ret != 0) {
3907                 DEBUG(DEBUG_ERR,("Unable to get dbhealth for database '%s'\n",
3908                                  argv[0]));
3909                 talloc_free(tmp_ctx);
3910                 return -1;
3911         }
3912         if (reason) {
3913                 uint32_t allow_unhealthy = 0;
3914
3915                 ctdb_ctrl_get_tunable(ctdb, TIMELIMIT(), options.pnn,
3916                                       "AllowUnhealthyDBRead",
3917                                       &allow_unhealthy);
3918
3919                 if (allow_unhealthy != 1) {
3920                         DEBUG(DEBUG_ERR,("database '%s' is unhealthy: %s\n",
3921                                          argv[0], reason));
3922
3923                         DEBUG(DEBUG_ERR,("disallow backup : tunnable AllowUnhealthyDBRead = %u\n",
3924                                          allow_unhealthy));
3925                         talloc_free(tmp_ctx);
3926                         return -1;
3927                 }
3928
3929                 DEBUG(DEBUG_WARNING,("WARNING database '%s' is unhealthy - see 'ctdb getdbstatus %s'\n",
3930                                      argv[0], argv[0]));
3931                 DEBUG(DEBUG_WARNING,("WARNING! allow backup of unhealthy database: "
3932                                      "tunnable AllowUnhealthyDBRead = %u\n",
3933                                      allow_unhealthy));
3934         }
3935
3936         ctdb_db = ctdb_attach(ctdb, argv[0], dbmap->dbs[i].persistent, 0);
3937         if (ctdb_db == NULL) {
3938                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", argv[0]));
3939                 talloc_free(tmp_ctx);
3940                 return -1;
3941         }
3942
3943
3944         ret = tdb_transaction_start(ctdb_db->ltdb->tdb);
3945         if (ret == -1) {
3946                 DEBUG(DEBUG_ERR,("Failed to start transaction\n"));
3947                 talloc_free(tmp_ctx);
3948                 return -1;
3949         }
3950
3951
3952         bd = talloc_zero(tmp_ctx, struct backup_data);
3953         if (bd == NULL) {
3954                 DEBUG(DEBUG_ERR,("Failed to allocate backup_data\n"));
3955                 talloc_free(tmp_ctx);
3956                 return -1;
3957         }
3958
3959         bd->records = talloc_zero(bd, struct ctdb_marshall_buffer);
3960         if (bd->records == NULL) {
3961                 DEBUG(DEBUG_ERR,("Failed to allocate ctdb_marshall_buffer\n"));
3962                 talloc_free(tmp_ctx);
3963                 return -1;
3964         }
3965
3966         bd->len = offsetof(struct ctdb_marshall_buffer, data);
3967         bd->records->db_id = ctdb_db->db_id;
3968         /* traverse the database collecting all records */
3969         if (tdb_traverse_read(ctdb_db->ltdb->tdb, backup_traverse, bd) == -1 ||
3970             bd->traverse_error) {
3971                 DEBUG(DEBUG_ERR,("Traverse error\n"));
3972                 talloc_free(tmp_ctx);
3973                 return -1;              
3974         }
3975
3976         tdb_transaction_cancel(ctdb_db->ltdb->tdb);
3977
3978
3979         fh = open(argv[1], O_RDWR|O_CREAT, 0600);
3980         if (fh == -1) {
3981                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[1]));
3982                 talloc_free(tmp_ctx);
3983                 return -1;
3984         }
3985
3986         dbhdr.version = DB_VERSION;
3987         dbhdr.timestamp = time(NULL);
3988         dbhdr.persistent = dbmap->dbs[i].persistent;
3989         dbhdr.size = bd->len;
3990         if (strlen(argv[0]) >= MAX_DB_NAME) {
3991                 DEBUG(DEBUG_ERR,("Too long dbname\n"));
3992                 goto done;
3993         }
3994         strncpy(discard_const(dbhdr.name), argv[0], MAX_DB_NAME);
3995         ret = write(fh, &dbhdr, sizeof(dbhdr));
3996         if (ret == -1) {
3997                 DEBUG(DEBUG_ERR,("write failed: %s\n", strerror(errno)));
3998                 goto done;
3999         }
4000         ret = write(fh, bd->records, bd->len);
4001         if (ret == -1) {
4002                 DEBUG(DEBUG_ERR,("write failed: %s\n", strerror(errno)));
4003                 goto done;
4004         }
4005
4006         status = 0;
4007 done:
4008         if (fh != -1) {
4009                 ret = close(fh);
4010                 if (ret == -1) {
4011                         DEBUG(DEBUG_ERR,("close failed: %s\n", strerror(errno)));
4012                 }
4013         }
4014         talloc_free(tmp_ctx);
4015         return status;
4016 }
4017
4018 /*
4019  * restore a database from a file 
4020  */
4021 static int control_restoredb(struct ctdb_context *ctdb, int argc, const char **argv)
4022 {
4023         int ret;
4024         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4025         TDB_DATA outdata;
4026         TDB_DATA data;
4027         struct db_file_header dbhdr;
4028         struct ctdb_db_context *ctdb_db;
4029         struct ctdb_node_map *nodemap=NULL;
4030         struct ctdb_vnn_map *vnnmap=NULL;
4031         int i, fh;
4032         struct ctdb_control_wipe_database w;
4033         uint32_t *nodes;
4034         uint32_t generation;
4035         struct tm *tm;
4036         char tbuf[100];
4037         char *dbname;
4038
4039         if (argc < 1 || argc > 2) {
4040                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
4041                 return -1;
4042         }
4043
4044         fh = open(argv[0], O_RDONLY);
4045         if (fh == -1) {
4046                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[0]));
4047                 talloc_free(tmp_ctx);
4048                 return -1;
4049         }
4050
4051         read(fh, &dbhdr, sizeof(dbhdr));
4052         if (dbhdr.version != DB_VERSION) {
4053                 DEBUG(DEBUG_ERR,("Invalid version of database dump. File is version %lu but expected version was %u\n", dbhdr.version, DB_VERSION));
4054                 talloc_free(tmp_ctx);
4055                 return -1;
4056         }
4057
4058         dbname = discard_const(dbhdr.name);
4059         if (argc == 2) {
4060                 dbname = discard_const(argv[1]);
4061         }
4062
4063         outdata.dsize = dbhdr.size;
4064         outdata.dptr = talloc_size(tmp_ctx, outdata.dsize);
4065         if (outdata.dptr == NULL) {
4066                 DEBUG(DEBUG_ERR,("Failed to allocate data of size '%lu'\n", dbhdr.size));
4067                 close(fh);
4068                 talloc_free(tmp_ctx);
4069                 return -1;
4070         }               
4071         read(fh, outdata.dptr, outdata.dsize);
4072         close(fh);
4073
4074         tm = localtime(&dbhdr.timestamp);
4075         strftime(tbuf,sizeof(tbuf)-1,"%Y/%m/%d %H:%M:%S", tm);
4076         printf("Restoring database '%s' from backup @ %s\n",
4077                 dbname, tbuf);
4078
4079
4080         ctdb_db = ctdb_attach(ctdb, dbname, dbhdr.persistent, 0);
4081         if (ctdb_db == NULL) {
4082                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", dbname));
4083                 talloc_free(tmp_ctx);
4084                 return -1;
4085         }
4086
4087         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb, &nodemap);
4088         if (ret != 0) {
4089                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
4090                 talloc_free(tmp_ctx);
4091                 return ret;
4092         }
4093
4094
4095         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &vnnmap);
4096         if (ret != 0) {
4097                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n", options.pnn));
4098                 talloc_free(tmp_ctx);
4099                 return ret;
4100         }
4101
4102         /* freeze all nodes */
4103         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4104         for (i=1; i<=NUM_DB_PRIORITIES; i++) {
4105                 if (ctdb_client_async_control(ctdb, CTDB_CONTROL_FREEZE,
4106                                         nodes, i,
4107                                         TIMELIMIT(),
4108                                         false, tdb_null,
4109                                         NULL, NULL,
4110                                         NULL) != 0) {
4111                         DEBUG(DEBUG_ERR, ("Unable to freeze nodes.\n"));
4112                         ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4113                         talloc_free(tmp_ctx);
4114                         return -1;
4115                 }
4116         }
4117
4118         generation = vnnmap->generation;
4119         data.dptr = (void *)&generation;
4120         data.dsize = sizeof(generation);
4121
4122         /* start a cluster wide transaction */
4123         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4124         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_START,
4125                                         nodes, 0,
4126                                         TIMELIMIT(), false, data,
4127                                         NULL, NULL,
4128                                         NULL) != 0) {
4129                 DEBUG(DEBUG_ERR, ("Unable to start cluster wide transactions.\n"));
4130                 return -1;
4131         }
4132
4133
4134         w.db_id = ctdb_db->db_id;
4135         w.transaction_id = generation;
4136
4137         data.dptr = (void *)&w;
4138         data.dsize = sizeof(w);
4139
4140         /* wipe all the remote databases. */
4141         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4142         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_WIPE_DATABASE,
4143                                         nodes, 0,
4144                                         TIMELIMIT(), false, data,
4145                                         NULL, NULL,
4146                                         NULL) != 0) {
4147                 DEBUG(DEBUG_ERR, ("Unable to wipe database.\n"));
4148                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4149                 talloc_free(tmp_ctx);
4150                 return -1;
4151         }
4152         
4153         /* push the database */
4154         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4155         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_PUSH_DB,
4156                                         nodes, 0,
4157                                         TIMELIMIT(), false, outdata,
4158                                         NULL, NULL,
4159                                         NULL) != 0) {
4160                 DEBUG(DEBUG_ERR, ("Failed to push database.\n"));
4161                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4162                 talloc_free(tmp_ctx);
4163                 return -1;
4164         }
4165
4166         data.dptr = (void *)&ctdb_db->db_id;
4167         data.dsize = sizeof(ctdb_db->db_id);
4168
4169         /* mark the database as healthy */
4170         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4171         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_DB_SET_HEALTHY,
4172                                         nodes, 0,
4173                                         TIMELIMIT(), false, data,
4174                                         NULL, NULL,
4175                                         NULL) != 0) {
4176                 DEBUG(DEBUG_ERR, ("Failed to mark database as healthy.\n"));
4177                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4178                 talloc_free(tmp_ctx);
4179                 return -1;
4180         }
4181
4182         data.dptr = (void *)&generation;
4183         data.dsize = sizeof(generation);
4184
4185         /* commit all the changes */
4186         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_COMMIT,
4187                                         nodes, 0,
4188                                         TIMELIMIT(), false, data,
4189                                         NULL, NULL,
4190                                         NULL) != 0) {
4191                 DEBUG(DEBUG_ERR, ("Unable to commit databases.\n"));
4192                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4193                 talloc_free(tmp_ctx);
4194                 return -1;
4195         }
4196
4197
4198         /* thaw all nodes */
4199         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4200         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_THAW,
4201                                         nodes, 0,
4202                                         TIMELIMIT(),
4203                                         false, tdb_null,
4204                                         NULL, NULL,
4205                                         NULL) != 0) {
4206                 DEBUG(DEBUG_ERR, ("Unable to thaw nodes.\n"));
4207                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4208                 talloc_free(tmp_ctx);
4209                 return -1;
4210         }
4211
4212
4213         talloc_free(tmp_ctx);
4214         return 0;
4215 }
4216
4217 /*
4218  * dump a database backup from a file
4219  */
4220 static int control_dumpdbbackup(struct ctdb_context *ctdb, int argc, const char **argv)
4221 {
4222         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4223         TDB_DATA outdata;
4224         struct db_file_header dbhdr;
4225         int i, fh;
4226         struct tm *tm;
4227         char tbuf[100];
4228         struct ctdb_rec_data *rec = NULL;
4229         struct ctdb_marshall_buffer *m;
4230
4231         if (argc != 1) {
4232                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
4233                 return -1;
4234         }
4235
4236         fh = open(argv[0], O_RDONLY);
4237         if (fh == -1) {
4238                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[0]));
4239                 talloc_free(tmp_ctx);
4240                 return -1;
4241         }
4242
4243         read(fh, &dbhdr, sizeof(dbhdr));
4244         if (dbhdr.version != DB_VERSION) {
4245                 DEBUG(DEBUG_ERR,("Invalid version of database dump. File is version %lu but expected version was %u\n", dbhdr.version, DB_VERSION));
4246                 talloc_free(tmp_ctx);
4247                 return -1;
4248         }
4249
4250         outdata.dsize = dbhdr.size;
4251         outdata.dptr = talloc_size(tmp_ctx, outdata.dsize);
4252         if (outdata.dptr == NULL) {
4253                 DEBUG(DEBUG_ERR,("Failed to allocate data of size '%lu'\n", dbhdr.size));
4254                 close(fh);
4255                 talloc_free(tmp_ctx);
4256                 return -1;
4257         }
4258         read(fh, outdata.dptr, outdata.dsize);
4259         close(fh);
4260         m = (struct ctdb_marshall_buffer *)outdata.dptr;
4261
4262         tm = localtime(&dbhdr.timestamp);
4263         strftime(tbuf,sizeof(tbuf)-1,"%Y/%m/%d %H:%M:%S", tm);
4264         printf("Backup of database name:'%s' dbid:0x%x08x from @ %s\n",
4265                 dbhdr.name, m->db_id, tbuf);
4266
4267         for (i=0; i < m->count; i++) {
4268                 uint32_t reqid = 0;
4269                 TDB_DATA key, data;
4270
4271                 /* we do not want the header splitted, so we pass NULL*/
4272                 rec = ctdb_marshall_loop_next(m, rec, &reqid,
4273                                               NULL, &key, &data);
4274
4275                 ctdb_dumpdb_record(ctdb, key, data, stdout);
4276         }
4277
4278         printf("Dumped %d records\n", i);
4279         talloc_free(tmp_ctx);
4280         return 0;
4281 }
4282
4283 /*
4284  * wipe a database from a file
4285  */
4286 static int control_wipedb(struct ctdb_context *ctdb, int argc,
4287                           const char **argv)
4288 {
4289         int ret;
4290         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4291         TDB_DATA data;
4292         struct ctdb_db_context *ctdb_db;
4293         struct ctdb_node_map *nodemap = NULL;
4294         struct ctdb_vnn_map *vnnmap = NULL;
4295         int i;
4296         struct ctdb_control_wipe_database w;
4297         uint32_t *nodes;
4298         uint32_t generation;
4299         struct ctdb_dbid_map *dbmap = NULL;
4300
4301         if (argc != 1) {
4302                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
4303                 return -1;
4304         }
4305
4306         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx,
4307                                  &dbmap);
4308         if (ret != 0) {
4309                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n",
4310                                   options.pnn));
4311                 return ret;
4312         }
4313
4314         for(i=0;i<dbmap->num;i++){
4315                 const char *name;
4316
4317                 ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn,
4318                                     dbmap->dbs[i].dbid, tmp_ctx, &name);
4319                 if(!strcmp(argv[0], name)){
4320                         talloc_free(discard_const(name));
4321                         break;
4322                 }
4323                 talloc_free(discard_const(name));
4324         }
4325         if (i == dbmap->num) {
4326                 DEBUG(DEBUG_ERR, ("No database with name '%s' found\n",
4327                                   argv[0]));
4328                 talloc_free(tmp_ctx);
4329                 return -1;
4330         }
4331
4332         ctdb_db = ctdb_attach(ctdb, argv[0], dbmap->dbs[i].persistent, 0);
4333         if (ctdb_db == NULL) {
4334                 DEBUG(DEBUG_ERR, ("Unable to attach to database '%s'\n",
4335                                   argv[0]));
4336                 talloc_free(tmp_ctx);
4337                 return -1;
4338         }
4339
4340         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb,
4341                                    &nodemap);
4342         if (ret != 0) {
4343                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n",
4344                                   options.pnn));
4345                 talloc_free(tmp_ctx);
4346                 return ret;
4347         }
4348
4349         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx,
4350                                   &vnnmap);
4351         if (ret != 0) {
4352                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n",
4353                                   options.pnn));
4354                 talloc_free(tmp_ctx);
4355                 return ret;
4356         }
4357
4358         /* freeze all nodes */
4359         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4360         for (i=1; i<=NUM_DB_PRIORITIES; i++) {
4361                 ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_FREEZE,
4362                                                 nodes, i,
4363                                                 TIMELIMIT(),
4364                                                 false, tdb_null,
4365                                                 NULL, NULL,
4366                                                 NULL);
4367                 if (ret != 0) {
4368                         DEBUG(DEBUG_ERR, ("Unable to freeze nodes.\n"));
4369                         ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn,
4370                                              CTDB_RECOVERY_ACTIVE);
4371                         talloc_free(tmp_ctx);
4372                         return -1;
4373                 }
4374         }
4375
4376         generation = vnnmap->generation;
4377         data.dptr = (void *)&generation;
4378         data.dsize = sizeof(generation);
4379
4380         /* start a cluster wide transaction */
4381         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4382         ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_START,
4383                                         nodes, 0,
4384                                         TIMELIMIT(), false, data,
4385                                         NULL, NULL,
4386                                         NULL);
4387         if (ret!= 0) {
4388                 DEBUG(DEBUG_ERR, ("Unable to start cluster wide "
4389                                   "transactions.\n"));
4390                 return -1;
4391         }
4392
4393         w.db_id = ctdb_db->db_id;
4394         w.transaction_id = generation;
4395
4396         data.dptr = (void *)&w;
4397         data.dsize = sizeof(w);
4398
4399         /* wipe all the remote databases. */
4400         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4401         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_WIPE_DATABASE,
4402                                         nodes, 0,
4403                                         TIMELIMIT(), false, data,
4404                                         NULL, NULL,
4405                                         NULL) != 0) {
4406                 DEBUG(DEBUG_ERR, ("Unable to wipe database.\n"));
4407                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4408                 talloc_free(tmp_ctx);
4409                 return -1;
4410         }
4411
4412         data.dptr = (void *)&ctdb_db->db_id;
4413         data.dsize = sizeof(ctdb_db->db_id);
4414
4415         /* mark the database as healthy */
4416         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4417         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_DB_SET_HEALTHY,
4418                                         nodes, 0,
4419                                         TIMELIMIT(), false, data,
4420                                         NULL, NULL,
4421                                         NULL) != 0) {
4422                 DEBUG(DEBUG_ERR, ("Failed to mark database as healthy.\n"));
4423                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4424                 talloc_free(tmp_ctx);
4425                 return -1;
4426         }
4427
4428         data.dptr = (void *)&generation;
4429         data.dsize = sizeof(generation);
4430
4431         /* commit all the changes */
4432         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_COMMIT,
4433                                         nodes, 0,
4434                                         TIMELIMIT(), false, data,
4435                                         NULL, NULL,
4436                                         NULL) != 0) {
4437                 DEBUG(DEBUG_ERR, ("Unable to commit databases.\n"));
4438                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4439                 talloc_free(tmp_ctx);
4440                 return -1;
4441         }
4442
4443         /* thaw all nodes */
4444         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4445         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_THAW,
4446                                         nodes, 0,
4447                                         TIMELIMIT(),
4448                                         false, tdb_null,
4449                                         NULL, NULL,
4450                                         NULL) != 0) {
4451                 DEBUG(DEBUG_ERR, ("Unable to thaw nodes.\n"));
4452                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4453                 talloc_free(tmp_ctx);
4454                 return -1;
4455         }
4456
4457         talloc_free(tmp_ctx);
4458         return 0;
4459 }
4460
4461 /*
4462   dump memory usage
4463  */
4464 static int control_dumpmemory(struct ctdb_context *ctdb, int argc, const char **argv)
4465 {
4466         TDB_DATA data;
4467         int ret;
4468         int32_t res;
4469         char *errmsg;
4470         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4471         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_DUMP_MEMORY,
4472                            0, tdb_null, tmp_ctx, &data, &res, NULL, &errmsg);
4473         if (ret != 0 || res != 0) {
4474                 DEBUG(DEBUG_ERR,("Failed to dump memory - %s\n", errmsg));
4475                 talloc_free(tmp_ctx);
4476                 return -1;
4477         }
4478         write(1, data.dptr, data.dsize);
4479         talloc_free(tmp_ctx);
4480         return 0;
4481 }
4482
4483 /*
4484   handler for memory dumps
4485 */
4486 static void mem_dump_handler(struct ctdb_context *ctdb, uint64_t srvid, 
4487                              TDB_DATA data, void *private_data)
4488 {
4489         write(1, data.dptr, data.dsize);
4490         exit(0);
4491 }
4492
4493 /*
4494   dump memory usage on the recovery daemon
4495  */
4496 static int control_rddumpmemory(struct ctdb_context *ctdb, int argc, const char **argv)
4497 {
4498         int ret;
4499         TDB_DATA data;
4500         struct rd_memdump_reply rd;
4501
4502         rd.pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
4503         if (rd.pnn == -1) {
4504                 DEBUG(DEBUG_ERR, ("Failed to get pnn of local node\n"));
4505                 return -1;
4506         }
4507         rd.srvid = getpid();
4508
4509         /* register a message port for receiveing the reply so that we
4510            can receive the reply
4511         */
4512         ctdb_client_set_message_handler(ctdb, rd.srvid, mem_dump_handler, NULL);
4513
4514
4515         data.dptr = (uint8_t *)&rd;
4516         data.dsize = sizeof(rd);
4517
4518         ret = ctdb_client_send_message(ctdb, options.pnn, CTDB_SRVID_MEM_DUMP, data);
4519         if (ret != 0) {
4520                 DEBUG(DEBUG_ERR,("Failed to send memdump request message to %u\n", options.pnn));
4521                 return -1;
4522         }
4523
4524         /* this loop will terminate when we have received the reply */
4525         while (1) {     
4526                 event_loop_once(ctdb->ev);
4527         }
4528
4529         return 0;
4530 }
4531
4532 /*
4533   send a message to a srvid
4534  */
4535 static int control_msgsend(struct ctdb_context *ctdb, int argc, const char **argv)
4536 {
4537         unsigned long srvid;
4538         int ret;
4539         TDB_DATA data;
4540
4541         if (argc < 2) {
4542                 usage();
4543         }
4544
4545         srvid      = strtoul(argv[0], NULL, 0);
4546
4547         data.dptr = (uint8_t *)discard_const(argv[1]);
4548         data.dsize= strlen(argv[1]);
4549
4550         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, srvid, data);
4551         if (ret != 0) {
4552                 DEBUG(DEBUG_ERR,("Failed to send memdump request message to %u\n", options.pnn));
4553                 return -1;
4554         }
4555
4556         return 0;
4557 }
4558
4559 /*
4560   handler for msglisten
4561 */
4562 static void msglisten_handler(struct ctdb_context *ctdb, uint64_t srvid, 
4563                              TDB_DATA data, void *private_data)
4564 {
4565         int i;
4566
4567         printf("Message received: ");
4568         for (i=0;i<data.dsize;i++) {
4569                 printf("%c", data.dptr[i]);
4570         }
4571         printf("\n");
4572 }
4573
4574 /*
4575   listen for messages on a messageport
4576  */
4577 static int control_msglisten(struct ctdb_context *ctdb, int argc, const char **argv)
4578 {
4579         uint64_t srvid;
4580
4581         srvid = getpid();
4582
4583         /* register a message port and listen for messages
4584         */
4585         ctdb_client_set_message_handler(ctdb, srvid, msglisten_handler, NULL);
4586         printf("Listening for messages on srvid:%d\n", (int)srvid);
4587
4588         while (1) {     
4589                 event_loop_once(ctdb->ev);
4590         }
4591
4592         return 0;
4593 }
4594
4595 /*
4596   list all nodes in the cluster
4597   we parse the nodes file directly
4598  */
4599 static int control_listnodes(struct ctdb_context *ctdb, int argc, const char **argv)
4600 {
4601         TALLOC_CTX *mem_ctx = talloc_new(NULL);
4602         struct pnn_node *pnn_nodes;
4603         struct pnn_node *pnn_node;
4604
4605         pnn_nodes = read_nodes_file(mem_ctx);
4606         if (pnn_nodes == NULL) {
4607                 DEBUG(DEBUG_ERR,("Failed to read nodes file\n"));
4608                 talloc_free(mem_ctx);
4609                 return -1;
4610         }
4611
4612         for(pnn_node=pnn_nodes;pnn_node;pnn_node=pnn_node->next) {
4613                 ctdb_sock_addr addr;
4614                 if (parse_ip(pnn_node->addr, NULL, 63999, &addr) == 0) {
4615                         DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s' in nodes file\n", pnn_node->addr));
4616                         talloc_free(mem_ctx);
4617                         return -1;
4618                 }
4619                 if (options.machinereadable){
4620                         printf(":%d:%s:\n", pnn_node->pnn, pnn_node->addr);
4621                 } else {
4622                         printf("%s\n", pnn_node->addr);
4623                 }
4624         }
4625         talloc_free(mem_ctx);
4626
4627         return 0;
4628 }
4629
4630 /*
4631   reload the nodes file on the local node
4632  */
4633 static int control_reload_nodes_file(struct ctdb_context *ctdb, int argc, const char **argv)
4634 {
4635         int i, ret;
4636         int mypnn;
4637         struct ctdb_node_map *nodemap=NULL;
4638
4639         mypnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
4640         if (mypnn == -1) {
4641                 DEBUG(DEBUG_ERR, ("Failed to read pnn of local node\n"));
4642                 return -1;
4643         }
4644
4645         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
4646         if (ret != 0) {
4647                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
4648                 return ret;
4649         }
4650
4651         /* reload the nodes file on all remote nodes */
4652         for (i=0;i<nodemap->num;i++) {
4653                 if (nodemap->nodes[i].pnn == mypnn) {
4654                         continue;
4655                 }
4656                 DEBUG(DEBUG_NOTICE, ("Reloading nodes file on node %u\n", nodemap->nodes[i].pnn));
4657                 ret = ctdb_ctrl_reload_nodes_file(ctdb, TIMELIMIT(),
4658                         nodemap->nodes[i].pnn);
4659                 if (ret != 0) {
4660                         DEBUG(DEBUG_ERR, ("ERROR: Failed to reload nodes file on node %u. You MUST fix that node manually!\n", nodemap->nodes[i].pnn));
4661                 }
4662         }
4663
4664         /* reload the nodes file on the local node */
4665         DEBUG(DEBUG_NOTICE, ("Reloading nodes file on node %u\n", mypnn));
4666         ret = ctdb_ctrl_reload_nodes_file(ctdb, TIMELIMIT(), mypnn);
4667         if (ret != 0) {
4668                 DEBUG(DEBUG_ERR, ("ERROR: Failed to reload nodes file on node %u. You MUST fix that node manually!\n", mypnn));
4669         }
4670
4671         /* initiate a recovery */
4672         control_recover(ctdb, argc, argv);
4673
4674         return 0;
4675 }
4676
4677
4678 static const struct {
4679         const char *name;
4680         int (*fn)(struct ctdb_context *, int, const char **);
4681         bool auto_all;
4682         bool without_daemon; /* can be run without daemon running ? */
4683         const char *msg;
4684         const char *args;
4685 } ctdb_commands[] = {
4686 #ifdef CTDB_VERS
4687         { "version",         control_version,           true,   false,  "show version of ctdb" },
4688 #endif
4689         { "status",          control_status,            true,   false,  "show node status" },
4690         { "uptime",          control_uptime,            true,   false,  "show node uptime" },
4691         { "ping",            control_ping,              true,   false,  "ping all nodes" },
4692         { "getvar",          control_getvar,            true,   false,  "get a tunable variable",               "<name>"},
4693         { "setvar",          control_setvar,            true,   false,  "set a tunable variable",               "<name> <value>"},
4694         { "listvars",        control_listvars,          true,   false,  "list tunable variables"},
4695         { "statistics",      control_statistics,        false,  false, "show statistics" },
4696         { "statisticsreset", control_statistics_reset,  true,   false,  "reset statistics"},
4697         { "stats",           control_stats,             false,  false,  "show rolling statistics", "[number of history records]" },
4698         { "ip",              control_ip,                false,  false,  "show which public ip's that ctdb manages" },
4699         { "ipinfo",          control_ipinfo,            true,   false,  "show details about a public ip that ctdb manages", "<ip>" },
4700         { "ifaces",          control_ifaces,            true,   false,  "show which interfaces that ctdb manages" },
4701         { "setifacelink",    control_setifacelink,      true,   false,  "set interface link status", "<iface> <status>" },
4702         { "process-exists",  control_process_exists,    true,   false,  "check if a process exists on a node",  "<pid>"},
4703         { "getdbmap",        control_getdbmap,          true,   false,  "show the database map" },
4704         { "getdbstatus",     control_getdbstatus,       true,   false,  "show the status of a database", "<dbname>" },
4705         { "catdb",           control_catdb,             true,   false,  "dump a database" ,                     "<dbname>"},
4706         { "getmonmode",      control_getmonmode,        true,   false,  "show monitoring mode" },
4707         { "getcapabilities", control_getcapabilities,   true,   false,  "show node capabilities" },
4708         { "pnn",             control_pnn,               true,   false,  "show the pnn of the currnet node" },
4709         { "lvs",             control_lvs,               true,   false,  "show lvs configuration" },
4710         { "lvsmaster",       control_lvsmaster,         true,   false,  "show which node is the lvs master" },
4711         { "disablemonitor",      control_disable_monmode,true,  false,  "set monitoring mode to DISABLE" },
4712         { "enablemonitor",      control_enable_monmode, true,   false,  "set monitoring mode to ACTIVE" },
4713         { "setdebug",        control_setdebug,          true,   false,  "set debug level",                      "<EMERG|ALERT|CRIT|ERR|WARNING|NOTICE|INFO|DEBUG>" },
4714         { "getdebug",        control_getdebug,          true,   false,  "get debug level" },
4715         { "getlog",          control_getlog,            true,   false,  "get the log data from the in memory ringbuffer", "<level>" },
4716         { "clearlog",          control_clearlog,        true,   false,  "clear the log data from the in memory ringbuffer" },
4717         { "attach",          control_attach,            true,   false,  "attach to a database",                 "<dbname>" },
4718         { "dumpmemory",      control_dumpmemory,        true,   false,  "dump memory map to stdout" },
4719         { "rddumpmemory",    control_rddumpmemory,      true,   false,  "dump memory map from the recovery daemon to stdout" },
4720         { "getpid",          control_getpid,            true,   false,  "get ctdbd process ID" },
4721         { "disable",         control_disable,           true,   false,  "disable a nodes public IP" },
4722         { "enable",          control_enable,            true,   false,  "enable a nodes public IP" },
4723         { "stop",            control_stop,              true,   false,  "stop a node" },
4724         { "continue",        control_continue,          true,   false,  "re-start a stopped node" },
4725         { "ban",             control_ban,               true,   false,  "ban a node from the cluster",          "<bantime|0>"},
4726         { "unban",           control_unban,             true,   false,  "unban a node" },
4727         { "showban",         control_showban,           true,   false,  "show ban information"},
4728         { "shutdown",        control_shutdown,          true,   false,  "shutdown ctdbd" },
4729         { "recover",         control_recover,           true,   false,  "force recovery" },
4730         { "sync",            control_ipreallocate,      true,   false,  "wait until ctdbd has synced all state changes" },
4731         { "ipreallocate",    control_ipreallocate,      true,   false,  "force the recovery daemon to perform a ip reallocation procedure" },
4732         { "thaw",            control_thaw,              true,   false,  "thaw databases", "[priority:1-3]" },
4733         { "isnotrecmaster",  control_isnotrecmaster,    false,  false,  "check if the local node is recmaster or not" },
4734         { "killtcp",         kill_tcp,                  false,  false, "kill a tcp connection.", "<srcip:port> <dstip:port>" },
4735         { "gratiousarp",     control_gratious_arp,      false,  false, "send a gratious arp", "<ip> <interface>" },
4736         { "tickle",          tickle_tcp,                false,  false, "send a tcp tickle ack", "<srcip:port> <dstip:port>" },
4737         { "gettickles",      control_get_tickles,       false,  false, "get the list of tickles registered for this ip", "<ip> [<port>]" },
4738         { "addtickle",       control_add_tickle,        false,  false, "add a tickle for this ip", "<ip>:<port> <ip>:<port>" },
4739
4740         { "deltickle",       control_del_tickle,        false,  false, "delete a tickle from this ip", "<ip>:<port> <ip>:<port>" },
4741
4742         { "regsrvid",        regsrvid,                  false,  false, "register a server id", "<pnn> <type> <id>" },
4743         { "unregsrvid",      unregsrvid,                false,  false, "unregister a server id", "<pnn> <type> <id>" },
4744         { "chksrvid",        chksrvid,                  false,  false, "check if a server id exists", "<pnn> <type> <id>" },
4745         { "getsrvids",       getsrvids,                 false,  false, "get a list of all server ids"},
4746         { "vacuum",          ctdb_vacuum,               false,  false, "vacuum the databases of empty records", "[max_records]"},
4747         { "repack",          ctdb_repack,               false,  false, "repack all databases", "[max_freelist]"},
4748         { "listnodes",       control_listnodes,         false,  true, "list all nodes in the cluster"},
4749         { "reloadnodes",     control_reload_nodes_file, false,  false, "reload the nodes file and restart the transport on all nodes"},
4750         { "moveip",          control_moveip,            false,  false, "move/failover an ip address to another node", "<ip> <node>"},
4751         { "addip",           control_addip,             true,   false, "add a ip address to a node", "<ip/mask> <iface>"},
4752         { "delip",           control_delip,             false,  false, "delete an ip address from a node", "<ip>"},
4753         { "eventscript",     control_eventscript,       true,   false, "run the eventscript with the given parameters on a node", "<arguments>"},
4754         { "backupdb",        control_backupdb,          false,  false, "backup the database into a file.", "<database> <file>"},
4755         { "restoredb",        control_restoredb,        false,  false, "restore the database from a file.", "<file> [dbname]"},
4756         { "dumpdbbackup",    control_dumpdbbackup,      false,  true,  "dump database backup from a file.", "<file>"},
4757         { "wipedb",           control_wipedb,        false,     false, "wipe the contents of a database.", "<dbname>"},
4758         { "recmaster",        control_recmaster,        false,  false, "show the pnn for the recovery master."},
4759         { "scriptstatus",    control_scriptstatus,  false,      false, "show the status of the monitoring scripts (or all scripts)", "[all]"},
4760         { "enablescript",     control_enablescript,  false,     false, "enable an eventscript", "<script>"},
4761         { "disablescript",    control_disablescript,  false,    false, "disable an eventscript", "<script>"},
4762         { "natgwlist",        control_natgwlist,        false,  false, "show the nodes belonging to this natgw configuration"},
4763         { "xpnn",             control_xpnn,             true,   true,  "find the pnn of the local node without talking to the daemon (unreliable)" },
4764         { "getreclock",       control_getreclock,       false,  false, "Show the reclock file of a node"},
4765         { "setreclock",       control_setreclock,       false,  false, "Set/clear the reclock file of a node", "[filename]"},
4766         { "setnatgwstate",    control_setnatgwstate,    false,  false, "Set NATGW state to on/off", "{on|off}"},
4767         { "setlmasterrole",   control_setlmasterrole,   false,  false, "Set LMASTER role to on/off", "{on|off}"},
4768         { "setrecmasterrole", control_setrecmasterrole, false,  false, "Set RECMASTER role to on/off", "{on|off}"},
4769         { "setdbprio",        control_setdbprio,        false,  false, "Set DB priority", "<dbid> <prio:1-3>"},
4770         { "getdbprio",        control_getdbprio,        false,  false, "Get DB priority", "<dbid>"},
4771         { "msglisten",        control_msglisten,        false,  false, "Listen on a srvid port for messages", "<msg srvid>"},
4772         { "msgsend",          control_msgsend,  false,  false, "Send a message to srvid", "<srvid> <message>"},
4773         { "sync",            control_ipreallocate,      false,  false,  "wait until ctdbd has synced all state changes" },
4774         { "pfetch",          control_pfetch,            false,  false,  "fetch a record from a persistent database", "<db> <key> [<file>]" },
4775         { "pstore",          control_pstore,            false,  false,  "write a record to a persistent database", "<db> <key> <file containing record>" },
4776         { "tfetch",          control_tfetch,            false,  true,  "fetch a record from a [c]tdb-file", "<tdb-file> <key> [<file>]" },
4777 };
4778
4779 /*
4780   show usage message
4781  */
4782 static void usage(void)
4783 {
4784         int i;
4785         printf(
4786 "Usage: ctdb [options] <control>\n" \
4787 "Options:\n" \
4788 "   -n <node>          choose node number, or 'all' (defaults to local node)\n"
4789 "   -Y                 generate machinereadable output\n"
4790 "   -v                 generate verbose output\n"
4791 "   -t <timelimit>     set timelimit for control in seconds (default %u)\n", options.timelimit);
4792         printf("Controls:\n");
4793         for (i=0;i<ARRAY_SIZE(ctdb_commands);i++) {
4794                 printf("  %-15s %-27s  %s\n", 
4795                        ctdb_commands[i].name, 
4796                        ctdb_commands[i].args?ctdb_commands[i].args:"",
4797                        ctdb_commands[i].msg);
4798         }
4799         exit(1);
4800 }
4801
4802
4803 static void ctdb_alarm(int sig)
4804 {
4805         printf("Maximum runtime exceeded - exiting\n");
4806         _exit(ERR_TIMEOUT);
4807 }
4808
4809 /*
4810   main program
4811 */
4812 int main(int argc, const char *argv[])
4813 {
4814         struct ctdb_context *ctdb;
4815         char *nodestring = NULL;
4816         struct poptOption popt_options[] = {
4817                 POPT_AUTOHELP
4818                 POPT_CTDB_CMDLINE
4819                 { "timelimit", 't', POPT_ARG_INT, &options.timelimit, 0, "timelimit", "integer" },
4820                 { "node",      'n', POPT_ARG_STRING, &nodestring, 0, "node", "integer|all" },
4821                 { "machinereadable", 'Y', POPT_ARG_NONE, &options.machinereadable, 0, "enable machinereadable output", NULL },
4822                 { "verbose",    'v', POPT_ARG_NONE, &options.verbose, 0, "enable verbose output", NULL },
4823                 { "maxruntime", 'T', POPT_ARG_INT, &options.maxruntime, 0, "die if runtime exceeds this limit (in seconds)", "integer" },
4824                 POPT_TABLEEND
4825         };
4826         int opt;
4827         const char **extra_argv;
4828         int extra_argc = 0;
4829         int ret=-1, i;
4830         poptContext pc;
4831         struct event_context *ev;
4832         const char *control;
4833
4834         setlinebuf(stdout);
4835         
4836         /* set some defaults */
4837         options.maxruntime = 0;
4838         options.timelimit = 3;
4839         options.pnn = CTDB_CURRENT_NODE;
4840
4841         pc = poptGetContext(argv[0], argc, argv, popt_options, POPT_CONTEXT_KEEP_FIRST);
4842
4843         while ((opt = poptGetNextOpt(pc)) != -1) {
4844                 switch (opt) {
4845                 default:
4846                         DEBUG(DEBUG_ERR, ("Invalid option %s: %s\n", 
4847                                 poptBadOption(pc, 0), poptStrerror(opt)));
4848                         exit(1);
4849                 }
4850         }
4851
4852         /* setup the remaining options for the main program to use */
4853         extra_argv = poptGetArgs(pc);
4854         if (extra_argv) {
4855                 extra_argv++;
4856                 while (extra_argv[extra_argc]) extra_argc++;
4857         }
4858
4859         if (extra_argc < 1) {
4860                 usage();
4861         }
4862
4863         if (options.maxruntime == 0) {
4864                 const char *ctdb_timeout;
4865                 ctdb_timeout = getenv("CTDB_TIMEOUT");
4866                 if (ctdb_timeout != NULL) {
4867                         options.maxruntime = strtoul(ctdb_timeout, NULL, 0);
4868                 } else {
4869                         /* default timeout is 120 seconds */
4870                         options.maxruntime = 120;
4871                 }
4872         }
4873
4874         signal(SIGALRM, ctdb_alarm);
4875         alarm(options.maxruntime);
4876
4877         /* setup the node number to contact */
4878         if (nodestring != NULL) {
4879                 if (strcmp(nodestring, "all") == 0) {
4880                         options.pnn = CTDB_BROADCAST_ALL;
4881                 } else {
4882                         options.pnn = strtoul(nodestring, NULL, 0);
4883                 }
4884         }
4885
4886         control = extra_argv[0];
4887
4888         ev = event_context_init(NULL);
4889         if (!ev) {
4890                 DEBUG(DEBUG_ERR, ("Failed to initialize event system\n"));
4891                 exit(1);
4892         }
4893         tevent_loop_allow_nesting(ev);
4894
4895         for (i=0;i<ARRAY_SIZE(ctdb_commands);i++) {
4896                 if (strcmp(control, ctdb_commands[i].name) == 0) {
4897                         int j;
4898
4899                         if (ctdb_commands[i].without_daemon == true) {
4900                                 close(2);
4901                         }
4902
4903                         if (ctdb_commands[i].without_daemon == false) {
4904                                 const char *socket_name;
4905
4906                                 /* initialise ctdb */
4907                                 ctdb = ctdb_cmdline_client(ev);
4908
4909                                 if (ctdb == NULL) {
4910                                         DEBUG(DEBUG_ERR, ("Failed to init ctdb\n"));
4911                                         exit(1);
4912                                 }
4913
4914                                 /* initialize a libctdb connection as well */
4915                                 socket_name = ctdb_get_socketname(ctdb);
4916                                 ctdb_connection = ctdb_connect(socket_name,
4917                                                        ctdb_log_file, stderr);
4918                                 if (ctdb_connection == NULL) {
4919                                         fprintf(stderr, "Failed to connect to daemon from libctdb\n");
4920                                         exit(1);
4921                                 }                               
4922                         
4923                                 /* verify the node exists */
4924                                 verify_node(ctdb);
4925
4926                                 if (options.pnn == CTDB_CURRENT_NODE) {
4927                                         int pnn;
4928                                         pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), options.pnn);         
4929                                         if (pnn == -1) {
4930                                                 return -1;
4931                                         }
4932                                         options.pnn = pnn;
4933                                 }
4934                         }
4935
4936                         if (ctdb_commands[i].auto_all && 
4937                             options.pnn == CTDB_BROADCAST_ALL) {
4938                                 uint32_t *nodes;
4939                                 uint32_t num_nodes;
4940                                 ret = 0;
4941
4942                                 nodes = ctdb_get_connected_nodes(ctdb, TIMELIMIT(), ctdb, &num_nodes);
4943                                 CTDB_NO_MEMORY(ctdb, nodes);
4944         
4945                                 for (j=0;j<num_nodes;j++) {
4946                                         options.pnn = nodes[j];
4947                                         ret |= ctdb_commands[i].fn(ctdb, extra_argc-1, extra_argv+1);
4948                                 }
4949                                 talloc_free(nodes);
4950                         } else {
4951                                 ret = ctdb_commands[i].fn(ctdb, extra_argc-1, extra_argv+1);
4952                         }
4953                         break;
4954                 }
4955         }
4956
4957         if (i == ARRAY_SIZE(ctdb_commands)) {
4958                 DEBUG(DEBUG_ERR, ("Unknown control '%s'\n", control));
4959                 exit(1);
4960         }
4961
4962         return ret;
4963 }