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