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