mysqladmin.cc 39.4 KB
Newer Older
1
/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
6

unknown's avatar
unknown committed
7 8 9 10
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
unknown's avatar
unknown committed
11

unknown's avatar
unknown committed
12 13 14 15 16 17
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/* maintaince of mysql databases */

unknown's avatar
unknown committed
18
#include "client_priv.h"
unknown's avatar
unknown committed
19 20
#include <signal.h>
#include <my_pthread.h>				/* because of signal()	*/
unknown's avatar
unknown committed
21
#include <sys/stat.h>
22
#include <mysql.h>
23
#include <sql_common.h>
24
#include <welcome_copyright_notice.h>           /* ORACLE_WELCOME_COPYRIGHT_NOTICE */
unknown's avatar
unknown committed
25

26
#define ADMIN_VERSION "8.42"
27
#define MAX_MYSQL_VAR 512
unknown's avatar
unknown committed
28
#define SHUTDOWN_DEF_TIMEOUT 3600		/* Wait for shutdown */
unknown's avatar
unknown committed
29 30
#define MAX_TRUNC_LENGTH 3

31
char *host= NULL, *user= 0, *opt_password= 0,
32
     *default_charset= (char*) MYSQL_AUTODETECT_CHARSET_NAME;
unknown's avatar
unknown committed
33 34 35 36
char truncated_var_names[MAX_MYSQL_VAR][MAX_TRUNC_LENGTH];
char ex_var_names[MAX_MYSQL_VAR][FN_REFLEN];
ulonglong last_values[MAX_MYSQL_VAR];
static int interval=0;
unknown's avatar
unknown committed
37
static my_bool option_force=0,interrupted=0,new_line=0,
38
               opt_compress=0, opt_relative=0, opt_verbose=0, opt_vertical=0,
39 40 41 42
               tty_password= 0, opt_nobeep;
static my_bool debug_info_flag= 0, debug_check_flag= 0;
static uint tcp_port = 0, option_wait = 0, option_silent=0, nr_iterations;
static uint opt_count_iterations= 0, my_end_arg;
unknown's avatar
unknown committed
43
static ulong opt_connect_timeout, opt_shutdown_timeout;
44
static char * unix_port=0;
45
static char *opt_plugin_dir= 0, *opt_default_auth;
unknown's avatar
unknown committed
46

47 48 49 50
#ifdef HAVE_SMEM
static char *shared_memory_base_name=0;
#endif
static uint opt_protocol=0;
51
static myf error_flags; /* flags to pass to my_printf_error, like ME_BELL */
52

53 54 55 56 57 58
/*
  When using extended-status relatively, ex_val_max_len is the estimated
  maximum length for any relative value printed by extended-status. The
  idea is to try to keep the length of output as short as possible.
*/

unknown's avatar
unknown committed
59 60 61 62
static uint ex_val_max_len[MAX_MYSQL_VAR];
static my_bool ex_status_printed = 0; /* First output is not relative. */
static uint ex_var_count, max_var_length, max_val_length;

63
#include <sslopt-vars.h>
unknown's avatar
unknown committed
64 65 66

static void print_version(void);
static void usage(void);
67 68
extern "C" my_bool get_one_option(int optid, const struct my_option *opt,
                                  char *argument);
69
static my_bool sql_connect(MYSQL *mysql, uint wait);
70
static int execute_commands(MYSQL *mysql,int argc, char **argv);
unknown's avatar
unknown committed
71
static int drop_db(MYSQL *mysql,const char *db);
72
extern "C" sig_handler endprog(int signal_number);
unknown's avatar
unknown committed
73 74 75 76 77 78 79 80 81 82
static void nice_time(ulong sec,char *buff);
static void print_header(MYSQL_RES *result);
static void print_top(MYSQL_RES *result);
static void print_row(MYSQL_RES *result,MYSQL_ROW cur, uint row);
static void print_relative_row(MYSQL_RES *result, MYSQL_ROW cur, uint row);
static void print_relative_row_vert(MYSQL_RES *result, MYSQL_ROW cur, uint row);
static void print_relative_header();
static void print_relative_line();
static void truncate_names();
static my_bool get_pidfile(MYSQL *mysql, char *pidfile);
unknown's avatar
unknown committed
83 84
static my_bool wait_pidfile(char *pidfile, time_t last_modified,
			    struct stat *pidfile_status);
unknown's avatar
unknown committed
85 86 87 88 89 90
static void store_values(MYSQL_RES *result);

/*
  The order of commands must be the same as command_names,
  except ADMIN_ERROR
*/
91 92
enum commands {
  ADMIN_ERROR,
93
  ADMIN_CREATE,           ADMIN_DROP,            ADMIN_SHUTDOWN,
94 95 96 97 98 99
  ADMIN_RELOAD,           ADMIN_REFRESH,         ADMIN_VER,
  ADMIN_PROCESSLIST,      ADMIN_STATUS,          ADMIN_KILL,
  ADMIN_DEBUG,            ADMIN_VARIABLES,       ADMIN_FLUSH_LOGS,
  ADMIN_FLUSH_HOSTS,      ADMIN_FLUSH_TABLES,    ADMIN_PASSWORD,
  ADMIN_PING,             ADMIN_EXTENDED_STATUS, ADMIN_FLUSH_STATUS,
  ADMIN_FLUSH_PRIVILEGES, ADMIN_START_SLAVE,     ADMIN_STOP_SLAVE,
100
  ADMIN_FLUSH_THREADS,    ADMIN_OLD_PASSWORD
unknown's avatar
unknown committed
101
};
102 103 104 105 106 107 108
static const char *command_names[]= {
  "create",               "drop",                "shutdown",
  "reload",               "refresh",             "version",
  "processlist",          "status",              "kill",
  "debug",                "variables",           "flush-logs",
  "flush-hosts",          "flush-tables",        "password",
  "ping",                 "extended-status",     "flush-status",
109 110
  "flush-privileges",     "start-slave",         "stop-slave",
  "flush-threads","old-password",
111 112 113
  NullS
};

unknown's avatar
unknown committed
114
static TYPELIB command_typelib=
unknown's avatar
unknown committed
115
{ array_elements(command_names)-1,"commands", command_names, NULL};
unknown's avatar
unknown committed
116

117 118
static struct my_option my_long_options[] =
{
unknown's avatar
unknown committed
119
  {"count", 'c',
120
   "Number of iterations to make. This works with -i (--sleep) only.",
121
   &nr_iterations, &nr_iterations, 0, GET_UINT,
unknown's avatar
unknown committed
122
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
123
#ifndef DBUG_OFF
124
  {"debug", '#', "Output debug log. Often this is 'd:t:o,filename'.",
125
   0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
126
#endif
Staale Smedseng's avatar
Staale Smedseng committed
127
  {"debug-check", OPT_DEBUG_CHECK, "Check memory and open file usage at exit.",
128
   &debug_check_flag, &debug_check_flag, 0,
129 130
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"debug-info", OPT_DEBUG_INFO, "Print some debug info at exit.",
131
   &debug_info_flag, &debug_info_flag,
132
   0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
133
  {"force", 'f',
134 135
   "Don't ask for confirmation on drop database; with multiple commands, "
   "continue even if an error occurs.",
136
   &option_force, &option_force, 0, GET_BOOL, NO_ARG, 0, 0,
137
   0, 0, 0, 0},
138
  {"compress", 'C', "Use compression in server/client protocol.",
139
   &opt_compress, &opt_compress, 0, GET_BOOL, NO_ARG, 0, 0, 0,
140 141
   0, 0, 0},
  {"character-sets-dir", OPT_CHARSETS_DIR,
142 143
   "Directory for character set files.", &charsets_dir,
   &charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
144
  {"default-character-set", OPT_DEFAULT_CHARSET,
145 146
   "Set the default character set.", &default_charset,
   &default_charset, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
147 148
  {"help", '?', "Display this help and exit.", 0, 0, 0, GET_NO_ARG,
   NO_ARG, 0, 0, 0, 0, 0, 0},
149
  {"host", 'h', "Connect to host.", &host, &host, 0, GET_STR,
150
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
151 152
  {"no-beep", 'b', "Turn off beep on error.", &opt_nobeep,
   &opt_nobeep, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, 
153 154 155
  {"password", 'p',
   "Password to use when connecting to server. If password is not given it's asked from the tty.",
   0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
156
#ifdef __WIN__
157 158
  {"pipe", 'W', "Use named pipes to connect to server.", 0, 0, 0, GET_NO_ARG,
   NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
159
#endif
160 161 162 163 164 165
  {"port", 'P', "Port number to use for connection or 0 for default to, in "
   "order of preference, my.cnf, $MYSQL_TCP_PORT, "
#if MYSQL_PORT_DEFAULT == 0
   "/etc/services, "
#endif
   "built-in default (" STRINGIFY_ARG(MYSQL_PORT) ").",
166
   &tcp_port, &tcp_port, 0, GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
Staale Smedseng's avatar
Staale Smedseng committed
167
  {"protocol", OPT_MYSQL_PROTOCOL, "The protocol to use for connection (tcp, socket, pipe, memory).",
168
    0, 0, 0, GET_STR,  REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
169
  {"relative", 'r',
170 171 172
   "Show difference between current and previous values when used with -i. "
   "Currently only works with extended-status.",
   &opt_relative, &opt_relative, 0, GET_BOOL, NO_ARG, 0, 0, 0,
173
  0, 0, 0},
174
#ifdef HAVE_SMEM
175
  {"shared-memory-base-name", OPT_SHARED_MEMORY_BASE_NAME,
176
   "Base name of shared memory.", &shared_memory_base_name, &shared_memory_base_name,
177 178
   0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#endif
179
  {"silent", 's', "Silently exit if one can't connect to server.",
180
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
Staale Smedseng's avatar
Staale Smedseng committed
181
  {"socket", 'S', "The socket file to use for connection.",
182
   &unix_port, &unix_port, 0, GET_STR, REQUIRED_ARG, 0, 0, 0,
183
   0, 0, 0},
Staale Smedseng's avatar
Staale Smedseng committed
184
  {"sleep", 'i', "Execute commands repeatedly with a sleep between.",
185
   &interval, &interval, 0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0,
186
   0, 0},
187
#include <sslopt-longopts.h>
unknown's avatar
unknown committed
188
#ifndef DONT_ALLOW_USER_CHANGE
189 190
  {"user", 'u', "User for login if not current user.", &user,
   &user, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
191
#endif
192 193
  {"verbose", 'v', "Write more information.", &opt_verbose,
   &opt_verbose, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
194
  {"version", 'V', "Output version information and exit.", 0, 0, 0, GET_NO_ARG,
195
   NO_ARG, 0, 0, 0, 0, 0, 0},
196
  {"vertical", 'E',
197
   "Print output vertically. Is similar to --relative, but prints output vertically.",
198
   &opt_vertical, &opt_vertical, 0, GET_BOOL, NO_ARG, 0, 0, 0,
199
   0, 0, 0},
200
  {"wait", 'w', "Wait and retry if connection is down.", 0, 0, 0, GET_UINT,
201
   OPT_ARG, 0, 0, 0, 0, 0, 0},
202 203
  {"connect_timeout", OPT_CONNECT_TIMEOUT, "", &opt_connect_timeout,
   &opt_connect_timeout, 0, GET_ULONG, REQUIRED_ARG, 3600*12, 0,
204
   3600*12, 0, 1, 0},
205 206
  {"shutdown_timeout", OPT_SHUTDOWN_TIMEOUT, "", &opt_shutdown_timeout,
   &opt_shutdown_timeout, 0, GET_ULONG, REQUIRED_ARG,
207
   SHUTDOWN_DEF_TIMEOUT, 0, 3600*12, 0, 1, 0},
208 209 210 211 212 213 214
  {"plugin_dir", OPT_PLUGIN_DIR, "Directory for client-side plugins.",
   (uchar**) &opt_plugin_dir, (uchar**) &opt_plugin_dir, 0,
   GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"default_auth", OPT_PLUGIN_DIR,
   "Default authentication client-side plugin to use.",
   (uchar**) &opt_default_auth, (uchar**) &opt_default_auth, 0,
   GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
215
  { 0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
unknown's avatar
unknown committed
216 217
};

218

unknown's avatar
unknown committed
219 220
static const char *load_default_groups[]= { "mysqladmin","client",0 };

221
my_bool
222 223
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
	       char *argument)
unknown's avatar
unknown committed
224
{
225 226 227
  int error = 0;

  switch(optid) {
unknown's avatar
unknown committed
228 229 230
  case 'c':
    opt_count_iterations= 1;
    break;
231
  case 'p':
232 233
    if (argument == disabled_my_option)
      argument= (char*) "";			// Don't require password
234 235 236
    if (argument)
    {
      char *start=argument;
237
      my_free(opt_password);
238 239 240 241
      opt_password=my_strdup(argument,MYF(MY_FAE));
      while (*argument) *argument++= 'x';		/* Destroy argument */
      if (*start)
	start[1]=0;				/* Cut length of argument */
242
      tty_password= 0;
243 244 245 246 247 248 249 250
    }
    else
      tty_password=1;
    break;
  case 's':
    option_silent++;
    break;
  case 'W':
unknown's avatar
unknown committed
251
#ifdef __WIN__
252
    opt_protocol = MYSQL_PROTOCOL_PIPE;
unknown's avatar
unknown committed
253
#endif
254 255 256 257
    break;
  case '#':
    DBUG_PUSH(argument ? argument : "d:t:o,/tmp/mysqladmin.trace");
    break;
258
#include <sslopt-case.h>
259 260 261 262 263 264 265 266 267 268 269
  case 'V':
    print_version();
    exit(0);
    break;
  case 'w':
    if (argument)
    {
      if ((option_wait=atoi(argument)) <= 0)
	option_wait=1;
    }
    else
270
      option_wait= ~(uint)0;
271 272 273 274 275 276
    break;
  case '?':
  case 'I':					/* Info */
    error++;
    break;
  case OPT_CHARSETS_DIR:
unknown's avatar
unknown committed
277
#if MYSQL_VERSION_ID > 32300
278
    charsets_dir = argument;
unknown's avatar
unknown committed
279
#endif
280
    break;
281
  case OPT_MYSQL_PROTOCOL:
282 283
    opt_protocol= find_type_or_exit(argument, &sql_protocol_typelib,
                                    opt->name);
284 285
    break;
  }
286
  if (error)
unknown's avatar
unknown committed
287 288 289 290
  {
    usage();
    exit(1);
  }
291 292 293 294 295 296
  return 0;
}


int main(int argc,char *argv[])
{
297
  int error= 0, ho_error;
298
  MYSQL mysql;
299 300
  char **commands, **save_argv;

301 302
  MY_INIT(argv[0]);
  mysql_init(&mysql);
303 304
  if (load_defaults("my",load_default_groups,&argc,&argv))
   exit(1); 
305
  save_argv = argv;				/* Save for free_defaults */
306
  if ((ho_error=handle_options(&argc, &argv, my_long_options, get_one_option)))
307 308
  {
    free_defaults(save_argv);
309
    exit(ho_error);
310
  }
311 312 313 314
  if (debug_info_flag)
    my_end_arg= MY_CHECK_ERROR | MY_GIVE_INFO;
  if (debug_check_flag)
    my_end_arg= MY_CHECK_ERROR;
315

316 317 318 319 320 321
  if (argc == 0)
  {
    usage();
    exit(1);
  }
  commands = argv;
unknown's avatar
unknown committed
322
  if (tty_password)
323
    opt_password = get_tty_password(NullS);
unknown's avatar
unknown committed
324

Konstantin Osipov's avatar
Konstantin Osipov committed
325 326
  (void) signal(SIGINT,endprog);			/* Here if abort */
  (void) signal(SIGTERM,endprog);		/* Here if abort */
unknown's avatar
unknown committed
327 328 329

  if (opt_compress)
    mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);
330 331 332 333 334
  if (opt_connect_timeout)
  {
    uint tmp=opt_connect_timeout;
    mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT, (char*) &tmp);
  }
unknown's avatar
unknown committed
335 336 337
#ifdef HAVE_OPENSSL
  if (opt_use_ssl)
    mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
338
		  opt_ssl_capath, opt_ssl_cipher);
339 340
  mysql_options(&mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
                (char*)&opt_ssl_verify_server_cert);
unknown's avatar
unknown committed
341
#endif
342 343 344 345 346
  if (opt_protocol)
    mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
#ifdef HAVE_SMEM
  if (shared_memory_base_name)
    mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
347
#endif
348
  mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);
349 350
  error_flags= (myf)(opt_nobeep ? 0 : ME_BELL);

351 352 353 354 355 356
  if (opt_plugin_dir && *opt_plugin_dir)
    mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);

  if (opt_default_auth && *opt_default_auth)
    mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);

357
  if (sql_connect(&mysql, option_wait))
358
  {
359 360 361 362 363
    /*
      We couldn't get an initial connection and will definitely exit.
      The following just determines the exit-code we'll give.
    */

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    unsigned int err= mysql_errno(&mysql);
    if (err >= CR_MIN_ERROR && err <= CR_MAX_ERROR)
      error= 1;
    else
    {
      /* Return 0 if all commands are PING */
      for (; argc > 0; argv++, argc--)
      {
        if (find_type(argv[0], &command_typelib, 2) != ADMIN_PING)
        {
          error= 1;
          break;
        }
      }
    }
  }
unknown's avatar
unknown committed
380 381
  else
  {
382 383 384 385 386 387 388 389 390
    /*
      --count=0 aborts right here. Otherwise iff --sleep=t ("interval")
      is given a t!=0, we get an endless loop, or n iterations if --count=n
      was given an n!=0. If --sleep wasn't given, we get one iteration.

      To wit, --wait loops the connection-attempts, while --sleep loops
      the command execution (endlessly if no --count is given).
    */

unknown's avatar
unknown committed
391
    while (!interrupted && (!opt_count_iterations || nr_iterations))
unknown's avatar
unknown committed
392 393
    {
      new_line = 0;
394 395

      if ((error= execute_commands(&mysql,argc,commands)))
unknown's avatar
unknown committed
396
      {
397 398 399 400 401
        /*
          Unknown/malformed command always aborts and can't be --forced.
          If the user got confused about the syntax, proceeding would be
          dangerous ...
        */
402
	if (error > 0)
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
	  break;

        /*
          Command was well-formed, but failed on the server. Might succeed
          on retry (if conditions on server change etc.), but needs --force
          to retry.
        */
        if (!option_force)
          break;
      }                                         /* if((error= ... */

      if (interval)                             /* --sleep=interval given */
      {
        /*
          If connection was dropped (unintentionally, or due to SHUTDOWN),
          re-establish it if --wait ("retry-connect") was given and user
          didn't signal for us to die. Otherwise, signal failure.
        */

	if (mysql.net.vio == 0)
unknown's avatar
unknown committed
423
	{
424 425
	  if (option_wait && !interrupted)
	  {
426 427 428 429 430 431 432
	    sleep(1);
	    sql_connect(&mysql, option_wait);
	    /*
	      continue normally and decrease counters so that
	      "mysqladmin --count=1 --wait=1 shutdown"
	      cannot loop endlessly.
	    */
433
	  }
434 435 436 437 438 439 440 441 442 443 444
	  else
	  {
	    /*
	      connexion broke, and we have no order to re-establish it. fail.
	    */
	    if (!option_force)
	      error= 1;
	    break;
	  }
	}                                       /* lost connection */

unknown's avatar
unknown committed
445 446 447 448 449
	sleep(interval);
	if (new_line)
	  puts("");
      }
      else
450 451 452 453 454
        break;                                  /* no --sleep, done looping */
    }                                           /* command-loop */
  }                                             /* got connection */

  mysql_close(&mysql);
455 456
  my_free(opt_password);
  my_free(user);
457
#ifdef HAVE_SMEM
458
  my_free(shared_memory_base_name);
459
#endif
460
  free_defaults(save_argv);
461
  my_end(my_end_arg);
462
  exit(error ? 1 : 0);
unknown's avatar
unknown committed
463 464 465 466
  return 0;
}


467
sig_handler endprog(int signal_number __attribute__((unused)))
unknown's avatar
unknown committed
468 469 470 471
{
  interrupted=1;
}

472 473 474 475 476 477 478 479 480 481 482
/**
   @brief connect to server, optionally waiting for same to come up

   @param  mysql     connection struct
   @param  wait      wait for server to come up?
                     (0: no, ~0: forever, n: cycles)

   @return Operation result
   @retval 0         success
   @retval 1         failure
*/
unknown's avatar
unknown committed
483

484
static my_bool sql_connect(MYSQL *mysql, uint wait)
unknown's avatar
unknown committed
485 486 487 488 489
{
  my_bool info=0;

  for (;;)
  {
490
    if (mysql_real_connect(mysql,host,user,opt_password,NullS,tcp_port,
491
			   unix_port, CLIENT_REMEMBER_OPTIONS))
unknown's avatar
unknown committed
492
    {
493
      mysql->reconnect= 1;
unknown's avatar
unknown committed
494 495 496 497 498 499 500
      if (info)
      {
	fputs("\n",stderr);
	(void) fflush(stderr);
      }
      return 0;
    }
unknown's avatar
unknown committed
501

502
    if (!wait)                                  // was or reached 0, fail
unknown's avatar
unknown committed
503
    {
504
      if (!option_silent)                       // print diagnostics
unknown's avatar
unknown committed
505 506
      {
	if (!host)
507
	  host= (char*) LOCAL_HOST;
unknown's avatar
unknown committed
508
	my_printf_error(0,"connect to server at '%s' failed\nerror: '%s'",
509
			error_flags, host, mysql_error(mysql));
unknown's avatar
unknown committed
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
	if (mysql_errno(mysql) == CR_CONNECTION_ERROR)
	{
	  fprintf(stderr,
		  "Check that mysqld is running and that the socket: '%s' exists!\n",
		  unix_port ? unix_port : mysql_unix_port);
	}
	else if (mysql_errno(mysql) == CR_CONN_HOST_ERROR ||
		 mysql_errno(mysql) == CR_UNKNOWN_HOST)
	{
	  fprintf(stderr,"Check that mysqld is running on %s",host);
	  fprintf(stderr," and that the port is %d.\n",
		  tcp_port ? tcp_port: mysql_port);
	  fprintf(stderr,"You can check this by doing 'telnet %s %d'\n",
		  host, tcp_port ? tcp_port: mysql_port);
	}
      }
      return 1;
    }
528

unknown's avatar
unknown committed
529
    if (wait != (uint) ~0)
530 531
      wait--;				/* count down, one less retry */

unknown's avatar
unknown committed
532 533
    if ((mysql_errno(mysql) != CR_CONN_HOST_ERROR) &&
	(mysql_errno(mysql) != CR_CONNECTION_ERROR))
534
    {
535 536 537 538 539
      /*
        Error is worse than "server doesn't answer (yet?)";
        fail even if we still have "wait-coins" unless --force
        was also given.
      */
unknown's avatar
unknown committed
540 541 542 543
      fprintf(stderr,"Got error: %s\n", mysql_error(mysql));
      if (!option_force)
	return 1;
    }
unknown's avatar
unknown committed
544
    else if (!option_silent)
unknown's avatar
unknown committed
545
    {
unknown's avatar
unknown committed
546 547 548 549 550 551 552 553
      if (!info)
      {
	info=1;
	fputs("Waiting for MySQL server to answer",stderr);
	(void) fflush(stderr);
      }
      else
      {
554
	putc('.',stderr);
unknown's avatar
unknown committed
555 556
	(void) fflush(stderr);
      }
unknown's avatar
unknown committed
557
    }
unknown's avatar
unknown committed
558
    sleep(5);
unknown's avatar
unknown committed
559 560 561
  }
}

unknown's avatar
unknown committed
562

563 564 565 566 567 568 569 570 571 572 573 574
/**
   @brief Execute all commands

   @details We try to execute all commands we were given, in the order
            given, but return with non-zero as soon as we encounter trouble.
            By that token, individual commands can be considered a conjunction
            with boolean short-cut.

   @return success?
   @retval 0       Yes!  ALL commands worked!
   @retval 1       No, one failed and will never work (malformed): fatal error!
   @retval -1      No, one failed on the server, may work next time!
575
*/
unknown's avatar
unknown committed
576

577
static int execute_commands(MYSQL *mysql,int argc, char **argv)
unknown's avatar
unknown committed
578
{
unknown's avatar
unknown committed
579
  const char *status;
unknown's avatar
unknown committed
580 581 582 583 584 585 586
  /*
    MySQL documentation relies on the fact that mysqladmin will
    execute commands in the order specified, e.g.
    mysqladmin -u root flush-privileges password "newpassword"
    to reset a lost root password.
    If this behaviour is ever changed, Docs should be notified.
  */
587

588
  struct rand_struct rand_st;
589

unknown's avatar
unknown committed
590 591 592 593 594 595 596 597
  for (; argc > 0 ; argv++,argc--)
  {
    switch (find_type(argv[0],&command_typelib,2)) {
    case ADMIN_CREATE:
    {
      char buff[FN_REFLEN+20];
      if (argc < 2)
      {
598
	my_printf_error(0, "Too few arguments to create", error_flags);
unknown's avatar
unknown committed
599 600
	return 1;
      }
unknown's avatar
unknown committed
601
      sprintf(buff,"create database `%.*s`",FN_REFLEN,argv[1]);
unknown's avatar
unknown committed
602
      if (mysql_query(mysql,buff))
603
      {
unknown's avatar
unknown committed
604
	my_printf_error(0,"CREATE DATABASE failed; error: '%-.200s'",
605
			error_flags, mysql_error(mysql));
606
	return -1;
607
      }
unknown's avatar
unknown committed
608
      argc--; argv++;
unknown's avatar
unknown committed
609 610 611 612 613 614
      break;
    }
    case ADMIN_DROP:
    {
      if (argc < 2)
      {
615
	my_printf_error(0, "Too few arguments to drop", error_flags);
unknown's avatar
unknown committed
616 617
	return 1;
      }
618
      if (drop_db(mysql,argv[1]))
619
	return -1;
unknown's avatar
unknown committed
620
      argc--; argv++;
unknown's avatar
unknown committed
621 622 623 624 625
      break;
    }
    case ADMIN_SHUTDOWN:
    {
      char pidfile[FN_REFLEN];
626
      my_bool got_pidfile= 0;
627
      time_t last_modified= 0;
628 629
      struct stat pidfile_status;

630 631 632 633
      /*
	Only wait for pidfile on local connections
	If pidfile doesn't exist, continue without pid file checking
      */
634 635
      if (mysql->unix_socket && (got_pidfile= !get_pidfile(mysql, pidfile)) &&
	  !stat(pidfile, &pidfile_status))
636 637
	last_modified= pidfile_status.st_mtime;

638
      if (mysql_shutdown(mysql, SHUTDOWN_DEFAULT))
unknown's avatar
unknown committed
639
      {
640
	my_printf_error(0, "shutdown failed; error: '%s'", error_flags,
unknown's avatar
unknown committed
641
			mysql_error(mysql));
642
	return -1;
unknown's avatar
unknown committed
643
      }
644
      argc=1;                   /* force SHUTDOWN to be the last command    */
unknown's avatar
unknown committed
645 646 647 648
      if (got_pidfile)
      {
	if (opt_verbose)
	  printf("Shutdown signal sent to server;  Waiting for pid file to disappear\n");
649 650

	/* Wait until pid file is gone */
unknown's avatar
unknown committed
651 652
	if (wait_pidfile(pidfile, last_modified, &pidfile_status))
	  return -1;
unknown's avatar
unknown committed
653 654 655 656 657
      }
      break;
    }
    case ADMIN_FLUSH_PRIVILEGES:
    case ADMIN_RELOAD:
658
      if (mysql_query(mysql,"flush privileges"))
unknown's avatar
unknown committed
659
      {
660
	my_printf_error(0, "reload failed; error: '%s'", error_flags,
unknown's avatar
unknown committed
661
			mysql_error(mysql));
662
	return -1;
unknown's avatar
unknown committed
663 664 665 666 667
      }
      break;
    case ADMIN_REFRESH:
      if (mysql_refresh(mysql,
			(uint) ~(REFRESH_GRANT | REFRESH_STATUS |
668
				 REFRESH_READ_LOCK | REFRESH_SLAVE |
669
				 REFRESH_MASTER)))
unknown's avatar
unknown committed
670
      {
671
	my_printf_error(0, "refresh failed; error: '%s'", error_flags,
unknown's avatar
unknown committed
672
			mysql_error(mysql));
673
	return -1;
unknown's avatar
unknown committed
674 675 676
      }
      break;
    case ADMIN_FLUSH_THREADS:
677
      if (mysql_refresh(mysql,(uint) REFRESH_THREADS))
unknown's avatar
unknown committed
678
      {
679
	my_printf_error(0, "refresh failed; error: '%s'", error_flags,
unknown's avatar
unknown committed
680
			mysql_error(mysql));
681
	return -1;
unknown's avatar
unknown committed
682 683 684 685 686
      }
      break;
    case ADMIN_VER:
      new_line=1;
      print_version();
687
      puts(ORACLE_WELCOME_COPYRIGHT_NOTICE("2000, 2010"));
unknown's avatar
unknown committed
688 689 690 691 692 693 694 695 696 697 698
      printf("Server version\t\t%s\n", mysql_get_server_info(mysql));
      printf("Protocol version\t%d\n", mysql_get_proto_info(mysql));
      printf("Connection\t\t%s\n",mysql_get_host_info(mysql));
      if (mysql->unix_socket)
	printf("UNIX socket\t\t%s\n", mysql->unix_socket);
      else
	printf("TCP port\t\t%d\n", mysql->port);
      status=mysql_stat(mysql);
      {
	char *pos,buff[40];
	ulong sec;
699
	pos= (char*) strchr(status,' ');
unknown's avatar
unknown committed
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
	*pos++=0;
	printf("%s\t\t\t",status);			/* print label */
	if ((status=str2int(pos,10,0,LONG_MAX,(long*) &sec)))
	{
	  nice_time(sec,buff);
	  puts(buff);				/* print nice time */
	  while (*status == ' ') status++;	/* to next info */
	}
      }
      putc('\n',stdout);
      if (status)
	puts(status);
      break;
    case ADMIN_PROCESSLIST:
    {
      MYSQL_RES *result;
      MYSQL_ROW row;

      if (mysql_query(mysql, (opt_verbose ? "show full processlist" :
			      "show processlist")) ||
	  !(result = mysql_store_result(mysql)))
      {
722
	my_printf_error(0, "process list failed; error: '%s'", error_flags,
unknown's avatar
unknown committed
723
			mysql_error(mysql));
724
	return -1;
unknown's avatar
unknown committed
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
      }
      print_header(result);
      while ((row=mysql_fetch_row(result)))
	print_row(result,row,0);
      print_top(result);
      mysql_free_result(result);
      new_line=1;
      break;
    }
    case ADMIN_STATUS:
      status=mysql_stat(mysql);
      if (status)
	puts(status);
      break;
    case ADMIN_KILL:
      {
	uint error=0;
	char *pos;
	if (argc < 2)
	{
745
	  my_printf_error(0, "Too few arguments to 'kill'", error_flags);
unknown's avatar
unknown committed
746 747 748 749 750
	  return 1;
	}
	pos=argv[1];
	for (;;)
	{
751 752 753 754 755 756
          /* We don't use mysql_kill(), since it only handles 32-bit IDs. */
          char buff[26], *out; /* "KILL " + max 20 digs + NUL */
          out= strxmov(buff, "KILL ", NullS);
          ullstr(strtoull(pos, NULL, 0), out);

          if (mysql_query(mysql, buff))
unknown's avatar
unknown committed
757
	  {
758 759 760
            /* out still points to just the number */
	    my_printf_error(0, "kill failed on %s; error: '%s'", error_flags,
			    out, mysql_error(mysql));
unknown's avatar
unknown committed
761 762 763 764 765 766 767 768
	    error=1;
	  }
	  if (!(pos=strchr(pos,',')))
	    break;
	  pos++;
	}
	argc--; argv++;
	if (error)
769
	  return -1;
unknown's avatar
unknown committed
770 771 772 773 774
	break;
      }
    case ADMIN_DEBUG:
      if (mysql_dump_debug_info(mysql))
      {
775
	my_printf_error(0, "debug failed; error: '%s'", error_flags,
unknown's avatar
unknown committed
776
			mysql_error(mysql));
777
	return -1;
unknown's avatar
unknown committed
778 779 780 781 782 783 784 785
      }
      break;
    case ADMIN_VARIABLES:
    {
      MYSQL_RES *res;
      MYSQL_ROW row;

      new_line=1;
unknown's avatar
unknown committed
786
      if (mysql_query(mysql,"show /*!40003 GLOBAL */ variables") ||
unknown's avatar
unknown committed
787 788
	  !(res=mysql_store_result(mysql)))
      {
789
	my_printf_error(0, "unable to show variables; error: '%s'", error_flags,
unknown's avatar
unknown committed
790
			mysql_error(mysql));
791
	return -1;
unknown's avatar
unknown committed
792 793 794 795 796 797 798 799 800 801 802 803 804
      }
      print_header(res);
      while ((row=mysql_fetch_row(res)))
	print_row(res,row,0);
      print_top(res);
      mysql_free_result(res);
      break;
    }
    case ADMIN_EXTENDED_STATUS:
    {
      MYSQL_RES *res;
      MYSQL_ROW row;
      uint rownr = 0;
805
      void (*func) (MYSQL_RES*, MYSQL_ROW, uint);
unknown's avatar
unknown committed
806 807

      new_line = 1;
808
      if (mysql_query(mysql, "show /*!50002 GLOBAL */ status") ||
unknown's avatar
unknown committed
809 810
	  !(res = mysql_store_result(mysql)))
      {
811
	my_printf_error(0, "unable to show status; error: '%s'", error_flags,
unknown's avatar
unknown committed
812
			mysql_error(mysql));
813
	return -1;
unknown's avatar
unknown committed
814
      }
815 816 817

      DBUG_ASSERT(mysql_num_rows(res) < MAX_MYSQL_VAR);

unknown's avatar
unknown committed
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
      if (!opt_vertical)
	print_header(res);
      else
      {
	if (!ex_status_printed)
	{
	  store_values(res);
	  truncate_names();   /* Does some printing also */
	}
	else
	{
	  print_relative_line();
	  print_relative_header();
	  print_relative_line();
	}
      }

      /*      void (*func) (MYSQL_RES*, MYSQL_ROW, uint); */
      if (opt_relative && !opt_vertical)
	func = print_relative_row;
      else if (opt_vertical)
	func = print_relative_row_vert;
      else
	func = print_row;

      while ((row = mysql_fetch_row(res)))
	(*func)(res, row, rownr++);
      if (opt_vertical)
      {
	if (ex_status_printed)
	{
	  putchar('\n');
	  print_relative_line();
	}
      }
      else
	print_top(res);
unknown's avatar
unknown committed
855

unknown's avatar
unknown committed
856 857 858 859 860 861 862 863
      ex_status_printed = 1; /* From now on the output will be relative */
      mysql_free_result(res);
      break;
    }
    case ADMIN_FLUSH_LOGS:
    {
      if (mysql_refresh(mysql,REFRESH_LOG))
      {
864
	my_printf_error(0, "refresh failed; error: '%s'", error_flags,
unknown's avatar
unknown committed
865
			mysql_error(mysql));
866
	return -1;
unknown's avatar
unknown committed
867 868 869 870 871
      }
      break;
    }
    case ADMIN_FLUSH_HOSTS:
    {
872
      if (mysql_query(mysql,"flush hosts"))
unknown's avatar
unknown committed
873
      {
874
	my_printf_error(0, "refresh failed; error: '%s'", error_flags,
unknown's avatar
unknown committed
875
			mysql_error(mysql));
876
	return -1;
unknown's avatar
unknown committed
877 878 879 880 881
      }
      break;
    }
    case ADMIN_FLUSH_TABLES:
    {
882
      if (mysql_query(mysql,"flush tables"))
unknown's avatar
unknown committed
883
      {
884
	my_printf_error(0, "refresh failed; error: '%s'", error_flags,
unknown's avatar
unknown committed
885
			mysql_error(mysql));
886
	return -1;
unknown's avatar
unknown committed
887 888 889 890 891
      }
      break;
    }
    case ADMIN_FLUSH_STATUS:
    {
892
      if (mysql_query(mysql,"flush status"))
unknown's avatar
unknown committed
893
      {
894
	my_printf_error(0, "refresh failed; error: '%s'", error_flags,
unknown's avatar
unknown committed
895
			mysql_error(mysql));
896
	return -1;
unknown's avatar
unknown committed
897 898 899
      }
      break;
    }
900
    case ADMIN_OLD_PASSWORD:
unknown's avatar
unknown committed
901 902
    case ADMIN_PASSWORD:
    {
903 904
      char buff[128],crypted_pw[64];
      time_t start_time;
905
      char *typed_password= NULL, *verified= NULL;
906
      /* Do initialization the same way as we do in mysqld */
907
      start_time=time((time_t*) 0);
908
      randominit(&rand_st,(ulong) start_time,(ulong) start_time/2);
909

910
      if (argc < 1)
unknown's avatar
unknown committed
911
      {
912
	my_printf_error(0, "Too few arguments to change password", error_flags);
unknown's avatar
unknown committed
913 914
	return 1;
      }
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
      else if (argc == 1)
      {
        /* prompt for password */
        typed_password= get_tty_password("New password: ");
        verified= get_tty_password("Confirm new password: ");
        if (strcmp(typed_password, verified) != 0)
        {
          my_printf_error(0,"Passwords don't match",MYF(ME_BELL));
          return -1;
        }
      }
      else
        typed_password= argv[1];

      if (typed_password[0])
930
      {
unknown's avatar
unknown committed
931 932
        bool old= (find_type(argv[0], &command_typelib, 2) ==
                   ADMIN_OLD_PASSWORD);
933
#ifdef __WIN__
934
        size_t pw_len= strlen(typed_password);
935 936
        if (pw_len > 1 && typed_password[0] == '\'' &&
            typed_password[pw_len-1] == '\'')
937 938 939
          printf("Warning: single quotes were not trimmed from the password by"
                 " your command\nline client, as you might have expected.\n");
#endif
940 941 942 943
        /*
           If we don't already know to use an old-style password, see what
           the server is using
        */
unknown's avatar
unknown committed
944 945 946 947
        if (!old)
        {
          if (mysql_query(mysql, "SHOW VARIABLES LIKE 'old_passwords'"))
          {
948
            my_printf_error(0, "Could not determine old_passwords setting from server; error: '%s'",
949
                	    error_flags, mysql_error(mysql));
950
            return -1;
unknown's avatar
unknown committed
951 952 953
          }
          else
          {
954
            MYSQL_RES *res= mysql_store_result(mysql);
unknown's avatar
unknown committed
955 956 957 958 959
            if (!res)
            {
              my_printf_error(0,
                              "Could not get old_passwords setting from "
                              "server; error: '%s'",
960
        		      error_flags, mysql_error(mysql));
961 962
              return -1;
            }
unknown's avatar
unknown committed
963
            if (!mysql_num_rows(res))
964
              old= 1;
unknown's avatar
unknown committed
965 966
            else
            {
967 968 969 970 971 972 973
              MYSQL_ROW row= mysql_fetch_row(res);
              old= !strncmp(row[1], "ON", 2);
            }
            mysql_free_result(res);
          }
        }
        if (old)
974
          make_scrambled_password_323(crypted_pw, typed_password);
975
        else
976
          make_scrambled_password(crypted_pw, typed_password);
977
      }
unknown's avatar
unknown committed
978 979 980 981 982 983 984
      else
	crypted_pw[0]=0;			/* No password */
      sprintf(buff,"set password='%s',sql_log_off=0",crypted_pw);

      if (mysql_query(mysql,"set sql_log_off=1"))
      {
	my_printf_error(0, "Can't turn off logging; error: '%s'",
985
			error_flags, mysql_error(mysql));
986
	return -1;
unknown's avatar
unknown committed
987 988 989
      }
      if (mysql_query(mysql,buff))
      {
990 991 992
	if (mysql_errno(mysql)!=1290)
	{
	  my_printf_error(0,"unable to change password; error: '%s'",
993
			  error_flags, mysql_error(mysql));
994 995 996 997
	  return -1;
	}
	else
	{
998 999 1000 1001 1002 1003 1004 1005 1006
	  /*
	    We don't try to execute 'update mysql.user set..'
	    because we can't perfectly find out the host
	   */
	  my_printf_error(0,"\n"
			  "You cannot use 'password' command as mysqld runs\n"
			  " with grant tables disabled (was started with"
			  " --skip-grant-tables).\n"
			  "Use: \"mysqladmin flush-privileges password '*'\""
1007
			  " instead", error_flags);
1008
	  return -1;
1009
	}
unknown's avatar
unknown committed
1010
      }
1011 1012 1013
      /* free up memory from prompted password */
      if (typed_password != argv[1]) 
      {
1014 1015
        my_free(typed_password);
        my_free(verified);
1016
      }
unknown's avatar
unknown committed
1017 1018 1019 1020 1021
      argc--; argv++;
      break;
    }

    case ADMIN_START_SLAVE:
1022
      if (mysql_query(mysql, "START SLAVE"))
unknown's avatar
unknown committed
1023
      {
1024
	my_printf_error(0, "Error starting slave: %s", error_flags,
unknown's avatar
unknown committed
1025
			mysql_error(mysql));
1026
	return -1;
unknown's avatar
unknown committed
1027 1028 1029 1030 1031
      }
      else
	puts("Slave started");
      break;
    case ADMIN_STOP_SLAVE:
1032
      if (mysql_query(mysql, "STOP SLAVE"))
unknown's avatar
unknown committed
1033
      {
1034
	  my_printf_error(0, "Error stopping slave: %s", error_flags,
unknown's avatar
unknown committed
1035
			  mysql_error(mysql));
1036
	  return -1;
unknown's avatar
unknown committed
1037 1038 1039 1040
      }
      else
	puts("Slave stopped");
      break;
unknown's avatar
unknown committed
1041

unknown's avatar
unknown committed
1042 1043 1044
    case ADMIN_PING:
      mysql->reconnect=0;	/* We want to know of reconnects */
      if (!mysql_ping(mysql))
unknown's avatar
unknown committed
1045 1046 1047 1048
      {
	if (option_silent < 2)
	  puts("mysqld is alive");
      }
unknown's avatar
unknown committed
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
      else
      {
	if (mysql_errno(mysql) == CR_SERVER_GONE_ERROR)
	{
	  mysql->reconnect=1;
	  if (!mysql_ping(mysql))
	    puts("connection was down, but mysqld is now alive");
	}
	else
	{
	  my_printf_error(0,"mysqld doesn't answer to ping, error: '%s'",
1060
			  error_flags, mysql_error(mysql));
1061
	  return -1;
unknown's avatar
unknown committed
1062 1063 1064 1065 1066
	}
      }
      mysql->reconnect=1;	/* Automatic reconnect is default */
      break;
    default:
1067
      my_printf_error(0, "Unknown command: '%-.60s'", error_flags, argv[0]);
unknown's avatar
unknown committed
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
      return 1;
    }
  }
  return 0;
}


static void print_version(void)
{
  printf("%s  Ver %s Distrib %s, for %s on %s\n",my_progname,ADMIN_VERSION,
	 MYSQL_SERVER_VERSION,SYSTEM_TYPE,MACHINE_TYPE);
}


static void usage(void)
{
  print_version();
1085
  puts(ORACLE_WELCOME_COPYRIGHT_NOTICE("2000, 2010"));
1086
  puts("Administration program for the mysqld daemon.");
unknown's avatar
unknown committed
1087
  printf("Usage: %s [OPTIONS] command command....\n", my_progname);
1088 1089
  my_print_help(my_long_options);
  my_print_variables(my_long_options);
unknown's avatar
unknown committed
1090 1091 1092
  print_defaults("my",load_default_groups);
  puts("\nWhere command is a one or more of: (Commands may be shortened)\n\
  create databasename	Create a new database\n\
1093
  debug			Instruct server to write debug information to log\n\
unknown's avatar
unknown committed
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
  drop databasename	Delete a database and all its tables\n\
  extended-status       Gives an extended status message from the server\n\
  flush-hosts           Flush all cached hosts\n\
  flush-logs            Flush all logs\n\
  flush-status		Clear status variables\n\
  flush-tables          Flush all tables\n\
  flush-threads         Flush the thread cache\n\
  flush-privileges      Reload grant tables (same as reload)\n\
  kill id,id,...	Kill mysql threads");
#if MYSQL_VERSION_ID >= 32200
  puts("\
1105 1106
  password [new-password] Change old password to new-password in current format\n\
  old-password [new-password] Change old password to new-password in old format");
unknown's avatar
unknown committed
1107 1108 1109 1110 1111 1112 1113 1114
#endif
  puts("\
  ping			Check if mysqld is alive\n\
  processlist		Show list of active threads in server\n\
  reload		Reload grant tables\n\
  refresh		Flush all tables and close and open logfiles\n\
  shutdown		Take server down\n\
  status		Gives a short status message from the server\n\
1115 1116
  start-slave		Start slave\n\
  stop-slave		Stop slave\n\
unknown's avatar
unknown committed
1117 1118 1119 1120
  variables             Prints variables available\n\
  version		Get version info from server");
}

unknown's avatar
unknown committed
1121

unknown's avatar
unknown committed
1122 1123 1124
static int drop_db(MYSQL *mysql, const char *db)
{
  char name_buff[FN_REFLEN+20], buf[10];
1125 1126
  char *input;

unknown's avatar
unknown committed
1127 1128 1129 1130
  if (!option_force)
  {
    puts("Dropping the database is potentially a very bad thing to do.");
    puts("Any data stored in the database will be destroyed.\n");
1131 1132
    printf("Do you really want to drop the '%s' database [y/N] ",db);
    fflush(stdout);
1133 1134
    input= fgets(buf, sizeof(buf)-1, stdin);
    if (!input || ((*input != 'y') && (*input != 'Y')))
unknown's avatar
unknown committed
1135 1136 1137 1138 1139
    {
      puts("\nOK, aborting database drop!");
      return -1;
    }
  }
1140
  sprintf(name_buff,"drop database `%.*s`",FN_REFLEN,db);
unknown's avatar
unknown committed
1141 1142
  if (mysql_query(mysql,name_buff))
  {
1143
    my_printf_error(0, "DROP DATABASE %s failed;\nerror: '%s'", error_flags,
unknown's avatar
unknown committed
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
		    db,mysql_error(mysql));
    return 1;
  }
  printf("Database \"%s\" dropped\n",db);
  return 0;
}


static void nice_time(ulong sec,char *buff)
{
  ulong tmp;

  if (sec >= 3600L*24)
  {
    tmp=sec/(3600L*24);
    sec-=3600L*24*tmp;
1160
    buff=int10_to_str(tmp, buff, 10);
unknown's avatar
unknown committed
1161 1162 1163 1164 1165 1166
    buff=strmov(buff,tmp > 1 ? " days " : " day ");
  }
  if (sec >= 3600L)
  {
    tmp=sec/3600L;
    sec-=3600L*tmp;
1167
    buff=int10_to_str(tmp, buff, 10);
unknown's avatar
unknown committed
1168 1169 1170 1171 1172 1173
    buff=strmov(buff,tmp > 1 ? " hours " : " hour ");
  }
  if (sec >= 60)
  {
    tmp=sec/60;
    sec-=60*tmp;
1174
    buff=int10_to_str(tmp, buff, 10);
unknown's avatar
unknown committed
1175 1176
    buff=strmov(buff," min ");
  }
1177
  strmov(int10_to_str(sec, buff, 10)," sec");
unknown's avatar
unknown committed
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
}


static void print_header(MYSQL_RES *result)
{
  MYSQL_FIELD *field;

  print_top(result);
  mysql_field_seek(result,0);
  putchar('|');
  while ((field = mysql_fetch_field(result)))
  {
1190
    printf(" %-*s|",(int) field->max_length+1,field->name);
unknown's avatar
unknown committed
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
  }
  putchar('\n');
  print_top(result);
}


static void print_top(MYSQL_RES *result)
{
  uint i,length;
  MYSQL_FIELD *field;

  putchar('+');
  mysql_field_seek(result,0);
  while((field = mysql_fetch_field(result)))
  {
unknown's avatar
unknown committed
1206
    if ((length=(uint) strlen(field->name)) > field->max_length)
unknown's avatar
unknown committed
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
      field->max_length=length;
    else
      length=field->max_length;
    for (i=length+2 ; i--> 0 ; )
      putchar('-');
    putchar('+');
  }
  putchar('\n');
}


/* 3.rd argument, uint row, is not in use. Don't remove! */
static void print_row(MYSQL_RES *result, MYSQL_ROW cur,
		      uint row __attribute__((unused)))
{
  uint i,length;
  MYSQL_FIELD *field;

  putchar('|');
  mysql_field_seek(result,0);
  for (i=0 ; i < mysql_num_fields(result); i++)
  {
    field = mysql_fetch_field(result);
    length=field->max_length;
    printf(" %-*s|",length+1,cur[i] ? (char*) cur[i] : "");
  }
  putchar('\n');
}


static void print_relative_row(MYSQL_RES *result, MYSQL_ROW cur, uint row)
{
  ulonglong tmp;
  char buff[22];
  MYSQL_FIELD *field;

  mysql_field_seek(result, 0);
  field = mysql_fetch_field(result);
1245
  printf("| %-*s|", (int) field->max_length + 1, cur[0]);
unknown's avatar
unknown committed
1246 1247

  field = mysql_fetch_field(result);
unknown's avatar
unknown committed
1248
  tmp = cur[1] ? strtoull(cur[1], NULL, 10) : (ulonglong) 0;
1249
  printf(" %-*s|\n", (int) field->max_length + 1,
unknown's avatar
unknown committed
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	 llstr((tmp - last_values[row]), buff));
  last_values[row] = tmp;
}


static void print_relative_row_vert(MYSQL_RES *result __attribute__((unused)),
				    MYSQL_ROW cur,
				    uint row __attribute__((unused)))
{
  uint length;
  ulonglong tmp;
  char buff[22];
unknown's avatar
unknown committed
1262

unknown's avatar
unknown committed
1263 1264 1265
  if (!row)
    putchar('|');

unknown's avatar
unknown committed
1266
  tmp = cur[1] ? strtoull(cur[1], NULL, 10) : (ulonglong) 0;
1267
  printf(" %-*s|", ex_val_max_len[row] + 1,
unknown's avatar
unknown committed
1268 1269 1270
	 llstr((tmp - last_values[row]), buff));

  /* Find the minimum row length needed to output the relative value */
unknown's avatar
unknown committed
1271
  if ((length=(uint) strlen(buff) > ex_val_max_len[row]) && ex_status_printed)
unknown's avatar
unknown committed
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    ex_val_max_len[row] = length;
  last_values[row] = tmp;
}


static void store_values(MYSQL_RES *result)
{
  uint i;
  MYSQL_ROW row;
  MYSQL_FIELD *field;

  field = mysql_fetch_field(result);
  max_var_length = field->max_length;
  field = mysql_fetch_field(result);
  max_val_length = field->max_length;

  for (i = 0; (row = mysql_fetch_row(result)); i++)
  {
    strmov(ex_var_names[i], row[0]);
    last_values[i]=strtoull(row[1],NULL,10);
    ex_val_max_len[i]=2;		/* Default print width for values */
  }
  ex_var_count = i;
  return;
}


static void print_relative_header()
{
  uint i;

  putchar('|');
  for (i = 0; i < ex_var_count; i++)
    printf(" %-*s|", ex_val_max_len[i] + 1, truncated_var_names[i]);
  putchar('\n');
}


static void print_relative_line()
{
  uint i;

  putchar('+');
  for (i = 0; i < ex_var_count; i++)
  {
    uint j;
    for (j = 0; j < ex_val_max_len[i] + 2; j++)
      putchar('-');
    putchar('+');
  }
  putchar('\n');
}


static void truncate_names()
{
  uint i;
  char *ptr,top_line[MAX_TRUNC_LENGTH+4+NAME_LEN+22+1],buff[22];

  ptr=top_line;
  *ptr++='+';
  ptr=strfill(ptr,max_var_length+2,'-');
  *ptr++='+';
  ptr=strfill(ptr,MAX_TRUNC_LENGTH+2,'-');
  *ptr++='+';
  ptr=strfill(ptr,max_val_length+2,'-');
  *ptr++='+';
  *ptr=0;
  puts(top_line);
unknown's avatar
unknown committed
1341

unknown's avatar
unknown committed
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
  for (i = 0 ; i < ex_var_count; i++)
  {
    uint sfx=1,j;
    printf("| %-*s|", max_var_length + 1, ex_var_names[i]);
    ptr = ex_var_names[i];
    /* Make sure no two same truncated names will become */
    for (j = 0; j < i; j++)
      if (*truncated_var_names[j] == *ptr)
	sfx++;

    truncated_var_names[i][0]= *ptr;		/* Copy first var char */
    int10_to_str(sfx, truncated_var_names[i]+1,10);
    printf(" %-*s|", MAX_TRUNC_LENGTH + 1, truncated_var_names[i]);
    printf(" %-*s|\n", max_val_length + 1, llstr(last_values[i],buff));
  }
  puts(top_line);
  return;
}


static my_bool get_pidfile(MYSQL *mysql, char *pidfile)
{
  MYSQL_RES* result;

  if (mysql_query(mysql, "SHOW VARIABLES LIKE 'pid_file'"))
  {
1368
    my_printf_error(0, "query failed; error: '%s'", error_flags,
unknown's avatar
unknown committed
1369 1370 1371 1372 1373
		    mysql_error(mysql));
  }
  result = mysql_store_result(mysql);
  if (result)
  {
1374 1375 1376
    MYSQL_ROW row=mysql_fetch_row(result);
    if (row)
      strmov(pidfile, row[1]);
unknown's avatar
unknown committed
1377
    mysql_free_result(result);
1378
    return row == 0;				/* Error if row = 0 */
unknown's avatar
unknown committed
1379 1380 1381 1382
  }
  return 1;					/* Error */
}

unknown's avatar
unknown committed
1383 1384 1385
/*
  Return 1 if pid file didn't disappear or change
*/
unknown's avatar
unknown committed
1386

unknown's avatar
unknown committed
1387 1388
static my_bool wait_pidfile(char *pidfile, time_t last_modified,
			    struct stat *pidfile_status)
unknown's avatar
unknown committed
1389 1390
{
  char buff[FN_REFLEN];
unknown's avatar
unknown committed
1391 1392 1393
  int error= 1;
  uint count= 0;
  DBUG_ENTER("wait_pidfile");
unknown's avatar
unknown committed
1394

1395
  system_filename(buff, pidfile);
unknown's avatar
unknown committed
1396
  do
unknown's avatar
unknown committed
1397
  {
unknown's avatar
unknown committed
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
    int fd;
    if ((fd= my_open(buff, O_RDONLY, MYF(0))) < 0)
    {
      error= 0;
      break;
    }
    (void) my_close(fd,MYF(0));
    if (last_modified && !stat(pidfile, pidfile_status))
    {
      if (last_modified != pidfile_status->st_mtime)
      {
	/* File changed;  Let's assume that mysqld did restart */
	if (opt_verbose)
	  printf("pid file '%s' changed while waiting for it to disappear!\nmysqld did probably restart\n",
		 buff);
	error= 0;
	break;
      }
    }
    if (count++ == opt_shutdown_timeout)
      break;
unknown's avatar
unknown committed
1419
    sleep(1);
unknown's avatar
unknown committed
1420 1421 1422
  } while (!interrupted);

  if (error)
unknown's avatar
unknown committed
1423
  {
unknown's avatar
unknown committed
1424
    DBUG_PRINT("warning",("Pid file didn't disappear"));
unknown's avatar
unknown committed
1425 1426 1427 1428
    fprintf(stderr,
	    "Warning;  Aborted waiting on pid file: '%s' after %d seconds\n",
	    buff, count-1);
  }
unknown's avatar
unknown committed
1429
  DBUG_RETURN(error);
unknown's avatar
unknown committed
1430
}