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