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