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