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