mysqladmin.c
上传用户:tsgydb
上传日期:2007-04-14
资源大小:10674k
文件大小:30k
源码类别:

MySQL数据库

开发平台:

Visual C++

  1. /* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
  2.    
  3.    This program is free software; you can redistribute it and/or modify
  4.    it under the terms of the GNU General Public License as published by
  5.    the Free Software Foundation; either version 2 of the License, or
  6.    (at your option) any later version.
  7.    
  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.
  12.    
  13.    You should have received a copy of the GNU General Public License
  14.    along with this program; if not, write to the Free Software
  15.    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
  16. /* maintaince of mysql databases */
  17. #include <global.h>
  18. #include <my_sys.h>
  19. #include <m_string.h>
  20. #include <signal.h>
  21. #include "mysql.h"
  22. #include "errmsg.h"
  23. #include <getopt.h>
  24. #ifdef THREAD
  25. #include <my_pthread.h> /* because of signal() */
  26. #endif
  27. #define ADMIN_VERSION "8.18"
  28. #define MAX_MYSQL_VAR 64
  29. #define SHUTDOWN_DEF_TIMEOUT 3600 /* Wait for shutdown */
  30. #define MAX_TRUNC_LENGTH 3
  31. char truncated_var_names[MAX_MYSQL_VAR][MAX_TRUNC_LENGTH];
  32. char ex_var_names[MAX_MYSQL_VAR][FN_REFLEN];
  33. ulonglong last_values[MAX_MYSQL_VAR];
  34. static int interval=0;
  35. static my_bool option_force=0,interrupted=0,new_line=0,
  36.                opt_compress=0, opt_relative=0, opt_verbose=0, opt_vertical=0;
  37. static uint tcp_port = 0, option_wait = 0, option_silent=0;
  38. static ulong opt_connect_timeout, opt_shutdown_timeout;
  39. static my_string unix_port=0;
  40. /* When using extended-status relatively, ex_val_max_len is the estimated
  41.    maximum length for any relative value printed by extended-status. The
  42.    idea is to try to keep the length of output as short as possible. */
  43. static uint ex_val_max_len[MAX_MYSQL_VAR];
  44. static my_bool ex_status_printed = 0; /* First output is not relative. */
  45. static uint ex_var_count, max_var_length, max_val_length;
  46. #include "sslopt-vars.h"
  47. static void print_version(void);
  48. static void usage(void);
  49. static my_bool sql_connect(MYSQL *mysql,const char *host, const char *user,
  50.    const char *password,uint wait);
  51. static my_bool execute_commands(MYSQL *mysql,int argc, char **argv);
  52. static int drop_db(MYSQL *mysql,const char *db);
  53. static sig_handler endprog(int signal_number);
  54. static void nice_time(ulong sec,char *buff);
  55. static void print_header(MYSQL_RES *result);
  56. static void print_top(MYSQL_RES *result);
  57. static void print_row(MYSQL_RES *result,MYSQL_ROW cur, uint row);
  58. static void print_relative_row(MYSQL_RES *result, MYSQL_ROW cur, uint row);
  59. static void print_relative_row_vert(MYSQL_RES *result, MYSQL_ROW cur, uint row);
  60. static void print_relative_header();
  61. static void print_relative_line();
  62. static void truncate_names();
  63. static my_bool get_pidfile(MYSQL *mysql, char *pidfile);
  64. static void wait_pidfile(char *pidfile);
  65. static void store_values(MYSQL_RES *result);
  66. /*
  67.   The order of commands must be the same as command_names,
  68.   except ADMIN_ERROR
  69. */
  70. enum commands { 
  71.   ADMIN_ERROR, 
  72.   ADMIN_CREATE,           ADMIN_DROP,            ADMIN_SHUTDOWN,
  73.   ADMIN_RELOAD,           ADMIN_REFRESH,         ADMIN_VER, 
  74.   ADMIN_PROCESSLIST,      ADMIN_STATUS,          ADMIN_KILL, 
  75.   ADMIN_DEBUG,            ADMIN_VARIABLES,       ADMIN_FLUSH_LOGS, 
  76.   ADMIN_FLUSH_HOSTS,      ADMIN_FLUSH_TABLES,    ADMIN_PASSWORD, 
  77.   ADMIN_PING,             ADMIN_EXTENDED_STATUS, ADMIN_FLUSH_STATUS, 
  78.   ADMIN_FLUSH_PRIVILEGES, ADMIN_START_SLAVE,     ADMIN_STOP_SLAVE, 
  79.   ADMIN_FLUSH_THREADS
  80. };
  81. static const char *command_names[]= {
  82.   "create",               "drop",                "shutdown",
  83.   "reload",               "refresh",             "version",
  84.   "processlist",          "status",              "kill",
  85.   "debug",                "variables",           "flush-logs",
  86.   "flush-hosts",          "flush-tables",        "password",
  87.   "ping",                 "extended-status",     "flush-status",
  88.   "flush-privileges",     "start-slave",         "stop-slave",  
  89.   "flush-threads", 
  90.   NullS
  91. };
  92. static TYPELIB command_typelib=
  93. { array_elements(command_names)-1,"commands", command_names};
  94. enum options { OPT_CHARSETS_DIR=256 };
  95. static struct option long_options[] = {
  96.   {"compress",           no_argument,       0, 'C'},
  97.   {"character-sets-dir", required_argument, 0, OPT_CHARSETS_DIR},
  98.   {"debug",              optional_argument, 0, '#'},
  99.   {"force",              no_argument,       0, 'f'},
  100.   {"help",               no_argument,       0, '?'},
  101.   {"host",               required_argument, 0, 'h'},
  102.   {"password",           optional_argument, 0, 'p'},
  103. #ifdef __WIN__
  104.   {"pipe",               no_argument,       0, 'W'},
  105. #endif
  106.   {"port",               required_argument, 0, 'P'},
  107.   {"relative",           no_argument,       0, 'r'},
  108.   {"set-variable",  required_argument, 0, 'O'},
  109.   {"silent",             no_argument,       0, 's'},
  110.   {"socket",             required_argument, 0, 'S'},
  111.   {"sleep",              required_argument, 0, 'i'},
  112. #include "sslopt-longopts.h"
  113. #ifndef DONT_ALLOW_USER_CHANGE
  114.   {"user",               required_argument, 0, 'u'},
  115. #endif
  116.   {"verbose",            no_argument,       0, 'v'},
  117.   {"version",            no_argument,       0, 'V'},
  118.   {"vertical",           no_argument,       0, 'E'},
  119.   {"wait",               optional_argument, 0, 'w'},
  120.   {0, 0, 0, 0}
  121. };
  122. CHANGEABLE_VAR changeable_vars[] = {
  123.   { "connect_timeout", (long*) &opt_connect_timeout, 0, 0, 3600*12, 0, 1},
  124.   { "shutdown_timeout", (long*) &opt_shutdown_timeout, SHUTDOWN_DEF_TIMEOUT, 0,
  125.     3600*12, 0, 1},
  126.   { 0, 0, 0, 0, 0, 0, 0}  
  127. };
  128. static const char *load_default_groups[]= { "mysqladmin","client",0 };
  129. int main(int argc,char *argv[])
  130. {
  131.   int c, error = 0,option_index=0;
  132.   MYSQL mysql;
  133.   char *host = NULL,*opt_password=0,*user=0,**commands;
  134.   my_bool tty_password=0;
  135.   MY_INIT(argv[0]);
  136.   mysql_init(&mysql);
  137.   load_defaults("my",load_default_groups,&argc,&argv);
  138.   set_all_changeable_vars( changeable_vars );
  139.   while ((c=getopt_long(argc,argv,"h:i:p::u:#::P:sS:Ct:fq?vVw::WrEO:",
  140. long_options, &option_index)) != EOF)
  141.   {
  142.     switch(c) {
  143.     case 'C':
  144.       opt_compress=1;
  145.       break;
  146.     case 'h':
  147.       host = optarg;
  148.       break;
  149.     case 'q': /* Allow old 'q' option */
  150.     case 'f':
  151.       option_force++;
  152.       break;
  153.     case 'p':
  154.       if (optarg)
  155.       {
  156. char *start=optarg;
  157. my_free(opt_password,MYF(MY_ALLOW_ZERO_PTR));
  158. opt_password=my_strdup(optarg,MYF(MY_FAE));
  159. while (*optarg) *optarg++= 'x'; /* Destroy argument */
  160. if (*start)
  161.   start[1]=0; /* Cut length of argument */
  162.       }
  163.       else
  164. tty_password=1;
  165.       break;
  166. #ifndef DONT_ALLOW_USER_CHANGE
  167.     case 'u':
  168.       user= my_strdup(optarg,MYF(0));
  169.       break;
  170. #endif
  171.     case 'i':
  172.       interval=atoi(optarg);
  173.       break;
  174.     case 'P':
  175.       tcp_port= (unsigned int) atoi(optarg);
  176.       break;
  177.     case 'r':
  178.       opt_relative = 1;
  179.       break;
  180.     case 'E':
  181.       opt_vertical = 1;
  182.       break;
  183.     case 'O':
  184.       if (set_changeable_var(optarg, changeable_vars))
  185.       {
  186. usage();
  187. return(1);
  188.       }
  189.       break;
  190.     case 's':
  191.       option_silent++;
  192.       break;
  193.     case 'S':
  194.       unix_port= optarg;
  195.       break;
  196.     case 'W':
  197. #ifdef __WIN__
  198.       unix_port=MYSQL_NAMEDPIPE;
  199. #endif
  200.       break;
  201.     case '#':
  202.       DBUG_PUSH(optarg ? optarg : "d:t:o,/tmp/mysqladmin.trace");
  203.       break;
  204.     case 'V':
  205.       print_version();
  206.       exit(0);
  207.       break;
  208.     case 'v':
  209.       opt_verbose=1;
  210.       break;
  211.     case 'w':
  212.       if (optarg)
  213.       {
  214. if ((option_wait=atoi(optarg)) <= 0)
  215.   option_wait=1;
  216.       }
  217.       else
  218. option_wait= ~0;
  219.       break;
  220. #include "sslopt-case.h"
  221.     default:
  222.       fprintf(stderr,"Illegal option character '%c'n",opterr);
  223.       /* Fall throught */
  224.     case '?':
  225.     case 'I': /* Info */
  226.       error++;
  227.       break;
  228.     case OPT_CHARSETS_DIR:
  229. #if MYSQL_VERSION_ID > 32300
  230.       charsets_dir = optarg;
  231. #endif
  232.       break;
  233.     }
  234.   }
  235.   argc -= optind;
  236.   commands = argv + optind;
  237.   if (error || argc == 0)
  238.   {
  239.     usage();
  240.     exit(1);
  241.   }
  242.   if (tty_password)
  243.     opt_password = get_tty_password(NullS);
  244.   VOID(signal(SIGINT,endprog)); /* Here if abort */
  245.   VOID(signal(SIGTERM,endprog)); /* Here if abort */
  246.   if (opt_compress)
  247.     mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);
  248.   if (opt_connect_timeout)
  249.   {
  250.     uint tmp=opt_connect_timeout;
  251.     mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT, (char*) &tmp);
  252.   }
  253. #ifdef HAVE_OPENSSL
  254.   if (opt_use_ssl)
  255.     mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
  256.   opt_ssl_capath);
  257. #endif /* HAVE_OPENSSL */
  258.   if (sql_connect(&mysql,host,user,opt_password,option_wait))
  259.     error = 1;
  260.   else
  261.   {
  262.     error = 0;
  263.     while (!interrupted)
  264.     {
  265.       new_line = 0;
  266.       if (execute_commands(&mysql,argc,commands) && !option_force)
  267.       {
  268. if (option_wait && !interrupted)
  269. {
  270.   mysql_close(&mysql);
  271.   if (!sql_connect(&mysql,host,user,opt_password,option_wait))
  272.     continue; /* Retry */
  273. }
  274. error=1;
  275. break;
  276.       }
  277.       if (interval)
  278.       {
  279. sleep(interval);
  280. if (new_line)
  281.   puts("");
  282.       }
  283.       else
  284. break;
  285.     }
  286.     mysql_close(&mysql);
  287.   }
  288.   my_free(opt_password,MYF(MY_ALLOW_ZERO_PTR));
  289.   my_free(user,MYF(MY_ALLOW_ZERO_PTR));
  290.   free_defaults(argv);
  291.   my_end(0);
  292.   exit(error);
  293.   return 0;
  294. }
  295. static sig_handler endprog(int signal_number __attribute__((unused)))
  296. {
  297.   interrupted=1;
  298. }
  299. static my_bool sql_connect(MYSQL *mysql,const char *host, const char *user,
  300. const char *password,uint wait)
  301. {
  302.   my_bool info=0;
  303.   for (;;)
  304.   {
  305.     if (mysql_real_connect(mysql,host,user,password,NullS,tcp_port,unix_port,
  306.    0))
  307.     {
  308.       if (info)
  309.       {
  310. fputs("n",stderr);
  311. (void) fflush(stderr);
  312.       }
  313.       return 0;
  314.     }
  315.   
  316.     if (!wait)
  317.     {
  318.       if (!option_silent)
  319.       {
  320. if (!host)
  321.   host=LOCAL_HOST;
  322. my_printf_error(0,"connect to server at '%s' failednerror: '%s'",
  323. MYF(ME_BELL), host, mysql_error(mysql));
  324. if (mysql_errno(mysql) == CR_CONNECTION_ERROR)
  325. {
  326.   fprintf(stderr,
  327.   "Check that mysqld is running and that the socket: '%s' exists!n",
  328.   unix_port ? unix_port : mysql_unix_port);
  329. }
  330. else if (mysql_errno(mysql) == CR_CONN_HOST_ERROR ||
  331.  mysql_errno(mysql) == CR_UNKNOWN_HOST)
  332. {
  333.   fprintf(stderr,"Check that mysqld is running on %s",host);
  334.   fprintf(stderr," and that the port is %d.n",
  335.   tcp_port ? tcp_port: mysql_port);
  336.   fprintf(stderr,"You can check this by doing 'telnet %s %d'n",
  337.   host, tcp_port ? tcp_port: mysql_port);
  338. }
  339.       }
  340.       return 1;
  341.     }
  342.     if (wait != (uint) ~0)
  343.       wait--; /* One less retry */
  344.     if ((mysql_errno(mysql) != CR_CONN_HOST_ERROR) &&
  345. (mysql_errno(mysql) != CR_CONNECTION_ERROR))
  346.     {  
  347.       fprintf(stderr,"Got error: %sn", mysql_error(mysql));
  348.       if (!option_force)
  349. return 1;
  350.     }
  351.     else if (!option_silent)
  352.     {
  353.       if (!info)
  354.       {
  355. info=1;
  356. fputs("Waiting for MySQL server to answer",stderr);
  357. (void) fflush(stderr);
  358.       }
  359.       else
  360.       {
  361. putc('.',stderr); 
  362. (void) fflush(stderr);
  363.       }
  364.     }
  365.     sleep(5);
  366.   }
  367. }
  368. static my_bool execute_commands(MYSQL *mysql,int argc, char **argv)
  369. {
  370.   char *status;
  371.   for (; argc > 0 ; argv++,argc--)
  372.   {
  373.     switch (find_type(argv[0],&command_typelib,2)) {
  374.     case ADMIN_CREATE:
  375.     {
  376.       char buff[FN_REFLEN+20];
  377.       if (argc < 2)
  378.       {
  379. my_printf_error(0,"Too few arguments to create",MYF(ME_BELL));
  380. return 1;
  381.       }
  382.       sprintf(buff,"create database `%.*s`",FN_REFLEN,argv[1]);
  383.       if (mysql_query(mysql,buff))
  384.       {
  385. my_printf_error(0,"CREATE DATABASE failed; error: '%-.200s'",
  386. MYF(ME_BELL), mysql_error(mysql));
  387. return 1;
  388.       }
  389.       argc--; argv++;
  390.       break;
  391.     }
  392.     case ADMIN_DROP:
  393.     {
  394.       char buff[FN_REFLEN+20];
  395.       if (argc < 2)
  396.       {
  397. my_printf_error(0,"Too few arguments to drop",MYF(ME_BELL));
  398. return 1;
  399.       }
  400.       sprintf(buff,"drop database `%.*s`",FN_REFLEN,argv[1]);
  401.       if (mysql_query(mysql,buff))
  402.       {
  403. my_printf_error(0,"DROP DATABASE failed; error: '%-.200s'",
  404. MYF(ME_BELL), mysql_error(mysql));
  405. return 1;
  406.       }
  407.       argc--; argv++;
  408.       break;
  409.     }
  410.     case ADMIN_SHUTDOWN:
  411.     {
  412.       char pidfile[FN_REFLEN];
  413.       my_bool got_pidfile=0;
  414.       /* Only wait for pidfile on local connections */
  415.       /* If pidfile doesn't exist, continue without pid file checking */
  416.       if (mysql->unix_socket)
  417. got_pidfile= !get_pidfile(mysql, pidfile);
  418.       if (mysql_shutdown(mysql))
  419.       {
  420. my_printf_error(0,"shutdown failed; error: '%s'",MYF(ME_BELL),
  421. mysql_error(mysql));
  422. return 1;
  423.       }
  424.       mysql_close(mysql); /* Close connection to avoid error messages */
  425.       if (got_pidfile)
  426.       {
  427. if (opt_verbose)
  428.   printf("Shutdown signal sent to server;  Waiting for pid file to disappearn");
  429. wait_pidfile(pidfile); /* Wait until pid file is gone */
  430.       }
  431.       break;
  432.     }
  433.     case ADMIN_FLUSH_PRIVILEGES:
  434.     case ADMIN_RELOAD:
  435.       if (mysql_refresh(mysql,REFRESH_GRANT) < 0)
  436.       {
  437. my_printf_error(0,"reload failed; error: '%s'",MYF(ME_BELL),
  438. mysql_error(mysql));
  439. return 1;
  440.       }
  441.       break;
  442.     case ADMIN_REFRESH:
  443.       if (mysql_refresh(mysql,
  444. (uint) ~(REFRESH_GRANT | REFRESH_STATUS |
  445.  REFRESH_READ_LOCK | REFRESH_SLAVE |
  446.  REFRESH_MASTER)) < 0)
  447.       {
  448. my_printf_error(0,"refresh failed; error: '%s'",MYF(ME_BELL),
  449. mysql_error(mysql));
  450. return 1;
  451.       }
  452.       break;
  453.     case ADMIN_FLUSH_THREADS:
  454.       if (mysql_refresh(mysql,(uint) REFRESH_THREADS) < 0)
  455.       {
  456. my_printf_error(0,"refresh failed; error: '%s'",MYF(ME_BELL),
  457. mysql_error(mysql));
  458. return 1;
  459.       }
  460.       break;
  461.     case ADMIN_VER:
  462.       new_line=1;
  463.       print_version();
  464.       puts("Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB");
  465.       puts("This software comes with ABSOLUTELY NO WARRANTY. This is free software,nand you are welcome to modify and redistribute it under the GPL licensen");
  466.       printf("Server versiontt%sn", mysql_get_server_info(mysql));
  467.       printf("Protocol versiont%dn", mysql_get_proto_info(mysql));
  468.       printf("Connectiontt%sn",mysql_get_host_info(mysql));
  469.       if (mysql->unix_socket)
  470. printf("UNIX sockettt%sn", mysql->unix_socket);
  471.       else
  472. printf("TCP porttt%dn", mysql->port);
  473.       status=mysql_stat(mysql);
  474.       {
  475. char *pos,buff[40];
  476. ulong sec;
  477. pos=strchr(status,' ');
  478. *pos++=0;
  479. printf("%sttt",status); /* print label */
  480. if ((status=str2int(pos,10,0,LONG_MAX,(long*) &sec)))
  481. {
  482.   nice_time(sec,buff);
  483.   puts(buff); /* print nice time */
  484.   while (*status == ' ') status++; /* to next info */
  485. }
  486.       }
  487.       putc('n',stdout);
  488.       if (status)
  489. puts(status);
  490.       break;
  491.     case ADMIN_PROCESSLIST:
  492.     {
  493.       MYSQL_RES *result;
  494.       MYSQL_ROW row;
  495.       if (mysql_query(mysql, (opt_verbose ? "show full processlist" :
  496.       "show processlist")) ||
  497.   !(result = mysql_store_result(mysql)))
  498.       {
  499. my_printf_error(0,"process list failed; error: '%s'",MYF(ME_BELL),
  500. mysql_error(mysql));
  501. return 1;
  502.       }
  503.       print_header(result);
  504.       while ((row=mysql_fetch_row(result)))
  505. print_row(result,row,0);
  506.       print_top(result);
  507.       mysql_free_result(result);
  508.       new_line=1;
  509.       break;
  510.     }
  511.     case ADMIN_STATUS:
  512.       status=mysql_stat(mysql);
  513.       if (status)
  514. puts(status);
  515.       break;
  516.     case ADMIN_KILL:
  517.       {
  518. uint error=0;
  519. char *pos;
  520. if (argc < 2)
  521. {
  522.   my_printf_error(0,"Too few arguments to 'kill'",MYF(ME_BELL));
  523.   return 1;
  524. }
  525. pos=argv[1];
  526. for (;;)
  527. {
  528.   if (mysql_kill(mysql,(ulong) atol(pos)))
  529.   {
  530.     my_printf_error(0,"kill failed on %ld; error: '%s'",MYF(ME_BELL),
  531.     atol(pos), mysql_error(mysql));
  532.     error=1;
  533.   }
  534.   if (!(pos=strchr(pos,',')))
  535.     break;
  536.   pos++;
  537. }
  538. argc--; argv++;
  539. if (error)
  540.   return error;
  541. break;
  542.       }
  543.     case ADMIN_DEBUG:
  544.       if (mysql_dump_debug_info(mysql))
  545.       {
  546. my_printf_error(0,"debug failed; error: '%s'",MYF(ME_BELL),
  547. mysql_error(mysql));
  548. return 1;
  549.       }
  550.       break;
  551.     case ADMIN_VARIABLES:
  552.     {
  553.       MYSQL_RES *res;
  554.       MYSQL_ROW row;
  555.       new_line=1;
  556.       if (mysql_query(mysql,"show variables") ||
  557.   !(res=mysql_store_result(mysql)))
  558.       {
  559. my_printf_error(0,"unable to show variables; error: '%s'",MYF(ME_BELL),
  560. mysql_error(mysql));
  561. return 1;
  562.       }
  563.       print_header(res);
  564.       while ((row=mysql_fetch_row(res)))
  565. print_row(res,row,0);
  566.       print_top(res);
  567.       mysql_free_result(res);
  568.       break;
  569.     }
  570.     case ADMIN_EXTENDED_STATUS:
  571.     {
  572.       MYSQL_RES *res;
  573.       MYSQL_ROW row;
  574.       uint rownr = 0;
  575.       void (*func) (MYSQL_RES*, MYSQL_ROW, uint); 
  576.       new_line = 1;
  577.       if (mysql_query(mysql, "show status") ||
  578.   !(res = mysql_store_result(mysql)))
  579.       {
  580. my_printf_error(0, "unable to show status; error: '%s'", MYF(ME_BELL),
  581. mysql_error(mysql));
  582. return 1;
  583.       }
  584.       if (!opt_vertical)
  585. print_header(res);
  586.       else
  587.       {
  588. if (!ex_status_printed)
  589. {
  590.   store_values(res);
  591.   truncate_names();   /* Does some printing also */
  592. }
  593. else
  594. {
  595.   print_relative_line();
  596.   print_relative_header();
  597.   print_relative_line();
  598. }
  599.       }
  600.       /*      void (*func) (MYSQL_RES*, MYSQL_ROW, uint); */
  601.       if (opt_relative && !opt_vertical)
  602. func = print_relative_row;
  603.       else if (opt_vertical)
  604. func = print_relative_row_vert;
  605.       else
  606. func = print_row;
  607.       while ((row = mysql_fetch_row(res)))
  608. (*func)(res, row, rownr++);
  609.       if (opt_vertical)
  610.       {
  611. if (ex_status_printed)
  612. {
  613.   putchar('n');
  614.   print_relative_line();
  615. }
  616.       }
  617.       else
  618. print_top(res);
  619.       ex_status_printed = 1; /* From now on the output will be relative */
  620.       mysql_free_result(res);
  621.       break;
  622.     }
  623.     case ADMIN_FLUSH_LOGS:
  624.     {
  625.       if (mysql_refresh(mysql,REFRESH_LOG))
  626.       {
  627. my_printf_error(0,"refresh failed; error: '%s'",MYF(ME_BELL),
  628. mysql_error(mysql));
  629. return 1;
  630.       }
  631.       break;
  632.     }
  633.     case ADMIN_FLUSH_HOSTS:
  634.     {
  635.       if (mysql_refresh(mysql,REFRESH_HOSTS))
  636.       {
  637. my_printf_error(0,"refresh failed; error: '%s'",MYF(ME_BELL),
  638. mysql_error(mysql));
  639. return 1;
  640.       }
  641.       break;
  642.     }
  643.     case ADMIN_FLUSH_TABLES:
  644.     {
  645.       if (mysql_refresh(mysql,REFRESH_TABLES))
  646.       {
  647. my_printf_error(0,"refresh failed; error: '%s'",MYF(ME_BELL),
  648. mysql_error(mysql));
  649. return 1;
  650.       }
  651.       break;
  652.     }
  653.     case ADMIN_FLUSH_STATUS:
  654.     {
  655.       if (mysql_refresh(mysql,REFRESH_STATUS))
  656.       {
  657. my_printf_error(0,"refresh failed; error: '%s'",MYF(ME_BELL),
  658. mysql_error(mysql));
  659. return 1;
  660.       }
  661.       break;
  662.     }
  663.     case ADMIN_PASSWORD:
  664.     {
  665.       char buff[128],crypted_pw[33];
  666.       if(argc < 2)
  667.       {
  668. my_printf_error(0,"Too few arguments to change password",MYF(ME_BELL));
  669. return 1;
  670.       }
  671.       if (argv[1][0])
  672. make_scrambled_password(crypted_pw,argv[1]);
  673.       else
  674. crypted_pw[0]=0; /* No password */
  675.       sprintf(buff,"set password='%s',sql_log_off=0",crypted_pw);
  676.       if (mysql_query(mysql,"set sql_log_off=1"))
  677.       {
  678. my_printf_error(0, "Can't turn off logging; error: '%s'",
  679. MYF(ME_BELL),mysql_error(mysql));
  680. return 1;
  681.       }
  682.       if (mysql_query(mysql,buff))
  683.       {
  684. my_printf_error(0,"unable to change password; error: '%s'",
  685. MYF(ME_BELL),mysql_error(mysql));
  686. return 1;
  687.       }
  688.       argc--; argv++;
  689.       break;
  690.     }
  691.     case ADMIN_START_SLAVE:
  692.       if (mysql_query(mysql, "SLAVE START"))
  693.       {
  694. my_printf_error(0, "Error starting slave: %s", MYF(ME_BELL),
  695. mysql_error(mysql));
  696. return 1;
  697.       }
  698.       else
  699. puts("Slave started");
  700.       break;
  701.     case ADMIN_STOP_SLAVE:
  702.       if (mysql_query(mysql, "SLAVE STOP"))
  703.       {
  704.   my_printf_error(0, "Error stopping slave: %s", MYF(ME_BELL),
  705.   mysql_error(mysql));
  706.   return 1;
  707.       }
  708.       else
  709. puts("Slave stopped");
  710.       break;
  711.       
  712.     case ADMIN_PING:
  713.       mysql->reconnect=0; /* We want to know of reconnects */
  714.       if (!mysql_ping(mysql))
  715.       {
  716. if (option_silent < 2)
  717.   puts("mysqld is alive");
  718.       }
  719.       else
  720.       {
  721. if (mysql_errno(mysql) == CR_SERVER_GONE_ERROR)
  722. {
  723.   mysql->reconnect=1;
  724.   if (!mysql_ping(mysql))
  725.     puts("connection was down, but mysqld is now alive");
  726. }
  727. else
  728. {
  729.   my_printf_error(0,"mysqld doesn't answer to ping, error: '%s'",
  730.   MYF(ME_BELL),mysql_error(mysql));
  731.   return 1;
  732. }
  733.       }
  734.       mysql->reconnect=1; /* Automatic reconnect is default */
  735.       break;
  736.     default:
  737.       my_printf_error(0,"Unknown command: '%-.60s'",MYF(ME_BELL),argv[0]);
  738.       return 1;
  739.     }
  740.   }
  741.   return 0;
  742. }
  743. static void print_version(void)
  744. {
  745.   printf("%s  Ver %s Distrib %s, for %s on %sn",my_progname,ADMIN_VERSION,
  746.  MYSQL_SERVER_VERSION,SYSTEM_TYPE,MACHINE_TYPE);
  747. }
  748. static void usage(void)
  749. {
  750.   uint i;
  751.   print_version();
  752.   puts("Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB");
  753.   puts("This software comes with ABSOLUTELY NO WARRANTY. This is free software,nand you are welcome to modify and redistribute it under the GPL licensen");
  754.   puts("Administration program for the mysqld daemon.");
  755.   printf("Usage: %s [OPTIONS] command command....n", my_progname);
  756.   printf("n
  757.   -#, --debug=...       Output debug log. Often this is 'd:t:o,filename`n
  758.   -f, --force Don't ask for confirmation on drop database; withn
  759. multiple commands, continue even if an error occursn
  760.   -?, --help Display this help and exitn
  761.   --character-sets-dir=...n
  762.                         Set the character set directoryn
  763.   -C, --compress        Use compression in server/client protocoln
  764.   -h, --host=# Connect to hostn
  765.   -p, --password[=...] Password to use when connecting to servern
  766. If password is not given it's asked from the ttyn");
  767. #ifdef __WIN__
  768.   puts("-W, --pipe Use named pipes to connect to server");
  769. #endif
  770.   printf("
  771.   -P  --port=... Port number to use for connectionn
  772.   -i, --sleep=sec Execute commands again and again with a sleep betweenn
  773.   -r, --relative        Show difference between current and previous valuesn
  774.                         when used with -i. Currently works only withn
  775.                         extended-statusn
  776.   -E, --vertical        Print output vertically. Is similar to --relative,n
  777.                         but prints output vertically.n
  778.   -s, --silent Silently exit if one can't connect to servern
  779.   -S, --socket=... Socket file to use for connectionn");
  780. #include "sslopt-usage.h"
  781.   printf("
  782.   -t, --timeout=... Timeout for connection to the mysqld servern");
  783. #ifndef DONT_ALLOW_USER_CHANGE
  784.   printf("
  785.   -u, --user=# User for login if not current usern");
  786. #endif
  787.   printf("
  788.   -v, --verbose         Write more informationn
  789.   -V, --version Output version information and exitn
  790.   -w, --wait[=retries]  Wait and retry if connection is downn");
  791.   print_defaults("my",load_default_groups);
  792.   printf("nPossible variables for option --set-variable (-O) are:n");
  793.   for (i=0 ; changeable_vars[i].name ; i++)
  794.     printf("%-20s  current value: %lun",
  795.    changeable_vars[i].name,
  796.    (ulong) *changeable_vars[i].varptr);
  797.   puts("nWhere command is a one or more of: (Commands may be shortened)n
  798.   create databasename Create a new databasen
  799.   drop databasename Delete a database and all its tablesn
  800.   extended-status       Gives an extended status message from the servern
  801.   flush-hosts           Flush all cached hostsn
  802.   flush-logs            Flush all logsn
  803.   flush-status Clear status variablesn
  804.   flush-tables          Flush all tablesn
  805.   flush-threads         Flush the thread cachen
  806.   flush-privileges      Reload grant tables (same as reload)n
  807.   kill id,id,... Kill mysql threads");
  808. #if MYSQL_VERSION_ID >= 32200
  809.   puts("
  810.   password new-password Change old password to new-password");
  811. #endif
  812.   puts("
  813.   ping Check if mysqld is aliven
  814.   processlist Show list of active threads in servern
  815.   reload Reload grant tablesn
  816.   refresh Flush all tables and close and open logfilesn
  817.   shutdown Take server downn
  818.   status Gives a short status message from the servern
  819.   start-slave Start slaven
  820.   stop-slave Stop slaven
  821.   variables             Prints variables availablen
  822.   version Get version info from server");
  823. }
  824. static int drop_db(MYSQL *mysql, const char *db)
  825. {
  826.   char name_buff[FN_REFLEN+20], buf[10];
  827.   if (!option_force)
  828.   {
  829.     puts("Dropping the database is potentially a very bad thing to do.");
  830.     puts("Any data stored in the database will be destroyed.n");
  831.     printf("Do you really want to drop the '%s' database [y/N]n",db);
  832.     VOID(fgets(buf,sizeof(buf)-1,stdin));
  833.     if ((*buf != 'y') && (*buf != 'Y'))
  834.     {
  835.       puts("nOK, aborting database drop!");
  836.       return -1;
  837.     }
  838.   }
  839.   sprintf(name_buff,"drop database %.*s",FN_REFLEN,db);
  840.   if (mysql_query(mysql,name_buff))
  841.   {
  842.     my_printf_error(0,"drop of '%s' failed;nerror: '%s'",MYF(ME_BELL),
  843.     db,mysql_error(mysql));
  844.     return 1;
  845.   }
  846.   printf("Database "%s" droppedn",db);
  847.   return 0;
  848. }
  849. static void nice_time(ulong sec,char *buff)
  850. {
  851.   ulong tmp;
  852.   if (sec >= 3600L*24)
  853.   {
  854.     tmp=sec/(3600L*24);
  855.     sec-=3600L*24*tmp;
  856.     buff=int2str(tmp,buff,10);
  857.     buff=strmov(buff,tmp > 1 ? " days " : " day ");
  858.   }
  859.   if (sec >= 3600L)
  860.   {
  861.     tmp=sec/3600L;
  862.     sec-=3600L*tmp;
  863.     buff=int2str(tmp,buff,10);
  864.     buff=strmov(buff,tmp > 1 ? " hours " : " hour ");
  865.   }
  866.   if (sec >= 60)
  867.   {
  868.     tmp=sec/60;
  869.     sec-=60*tmp;
  870.     buff=int2str(tmp,buff,10);
  871.     buff=strmov(buff," min ");
  872.   }
  873.   strmov(int2str(sec,buff,10)," sec");
  874. }
  875. static void print_header(MYSQL_RES *result)
  876. {
  877.   MYSQL_FIELD *field;
  878.   print_top(result);
  879.   mysql_field_seek(result,0);
  880.   putchar('|');
  881.   while ((field = mysql_fetch_field(result)))
  882.   {
  883.     printf(" %-*s|",field->max_length+1,field->name);
  884.   }
  885.   putchar('n');
  886.   print_top(result);
  887. }
  888. static void print_top(MYSQL_RES *result)
  889. {
  890.   uint i,length;
  891.   MYSQL_FIELD *field;
  892.   putchar('+');
  893.   mysql_field_seek(result,0);
  894.   while((field = mysql_fetch_field(result)))
  895.   {
  896.     if ((length=(uint) strlen(field->name)) > field->max_length)
  897.       field->max_length=length;
  898.     else
  899.       length=field->max_length;
  900.     for (i=length+2 ; i--> 0 ; )
  901.       putchar('-');
  902.     putchar('+');
  903.   }
  904.   putchar('n');
  905. }
  906. /* 3.rd argument, uint row, is not in use. Don't remove! */
  907. static void print_row(MYSQL_RES *result, MYSQL_ROW cur,
  908.       uint row __attribute__((unused)))
  909. {
  910.   uint i,length;
  911.   MYSQL_FIELD *field;
  912.   putchar('|');
  913.   mysql_field_seek(result,0);
  914.   for (i=0 ; i < mysql_num_fields(result); i++)
  915.   {
  916.     field = mysql_fetch_field(result);
  917.     length=field->max_length;
  918.     printf(" %-*s|",length+1,cur[i] ? (char*) cur[i] : "");
  919.   }
  920.   putchar('n');
  921. }
  922. static void print_relative_row(MYSQL_RES *result, MYSQL_ROW cur, uint row)
  923. {
  924.   ulonglong tmp;
  925.   char buff[22];
  926.   MYSQL_FIELD *field;
  927.   mysql_field_seek(result, 0);
  928.   field = mysql_fetch_field(result);
  929.   printf("| %-*s|", field->max_length + 1, cur[0]);
  930.   field = mysql_fetch_field(result);
  931.   tmp = cur[1] ? strtoull(cur[1], NULL, 0) : (ulonglong) 0;
  932.   printf(" %-*s|n", field->max_length + 1,
  933.  llstr((tmp - last_values[row]), buff));
  934.   last_values[row] = tmp;
  935. }
  936. static void print_relative_row_vert(MYSQL_RES *result __attribute__((unused)),
  937.     MYSQL_ROW cur,
  938.     uint row __attribute__((unused)))
  939. {
  940.   uint length;
  941.   ulonglong tmp;
  942.   char buff[22];
  943.   
  944.   if (!row)
  945.     putchar('|');
  946.   tmp = cur[1] ? strtoull(cur[1], NULL, 0) : (ulonglong) 0;
  947.   printf(" %-*s|", ex_val_max_len[row] + 1, 
  948.  llstr((tmp - last_values[row]), buff));
  949.   /* Find the minimum row length needed to output the relative value */
  950.   if ((length=(uint) strlen(buff) > ex_val_max_len[row]) && ex_status_printed)
  951.     ex_val_max_len[row] = length;
  952.   last_values[row] = tmp;
  953. }
  954. static void store_values(MYSQL_RES *result)
  955. {
  956.   uint i;
  957.   MYSQL_ROW row;
  958.   MYSQL_FIELD *field;
  959.   field = mysql_fetch_field(result);
  960.   max_var_length = field->max_length;
  961.   field = mysql_fetch_field(result);
  962.   max_val_length = field->max_length;
  963.   for (i = 0; (row = mysql_fetch_row(result)); i++)
  964.   {
  965.     strmov(ex_var_names[i], row[0]);
  966.     last_values[i]=strtoull(row[1],NULL,10);
  967.     ex_val_max_len[i]=2; /* Default print width for values */
  968.   }
  969.   ex_var_count = i;
  970.   return;
  971. }
  972. static void print_relative_header()
  973. {
  974.   uint i;
  975.   putchar('|');
  976.   for (i = 0; i < ex_var_count; i++)
  977.     printf(" %-*s|", ex_val_max_len[i] + 1, truncated_var_names[i]);
  978.   putchar('n');
  979. }
  980. static void print_relative_line()
  981. {
  982.   uint i;
  983.   putchar('+');
  984.   for (i = 0; i < ex_var_count; i++)
  985.   {
  986.     uint j;
  987.     for (j = 0; j < ex_val_max_len[i] + 2; j++)
  988.       putchar('-');
  989.     putchar('+');
  990.   }
  991.   putchar('n');
  992. }
  993. static void truncate_names()
  994. {
  995.   uint i;
  996.   char *ptr,top_line[MAX_TRUNC_LENGTH+4+NAME_LEN+22+1],buff[22];
  997.   ptr=top_line;
  998.   *ptr++='+';
  999.   ptr=strfill(ptr,max_var_length+2,'-');
  1000.   *ptr++='+';
  1001.   ptr=strfill(ptr,MAX_TRUNC_LENGTH+2,'-');
  1002.   *ptr++='+';
  1003.   ptr=strfill(ptr,max_val_length+2,'-');
  1004.   *ptr++='+';
  1005.   *ptr=0;
  1006.   puts(top_line);
  1007.   
  1008.   for (i = 0 ; i < ex_var_count; i++)
  1009.   {
  1010.     uint sfx=1,j;
  1011.     printf("| %-*s|", max_var_length + 1, ex_var_names[i]);
  1012.     ptr = ex_var_names[i];
  1013.     /* Make sure no two same truncated names will become */
  1014.     for (j = 0; j < i; j++)
  1015.       if (*truncated_var_names[j] == *ptr)
  1016. sfx++;
  1017.     truncated_var_names[i][0]= *ptr; /* Copy first var char */
  1018.     int10_to_str(sfx, truncated_var_names[i]+1,10);
  1019.     printf(" %-*s|", MAX_TRUNC_LENGTH + 1, truncated_var_names[i]);
  1020.     printf(" %-*s|n", max_val_length + 1, llstr(last_values[i],buff));
  1021.   }
  1022.   puts(top_line);
  1023.   return;
  1024. }
  1025. static my_bool get_pidfile(MYSQL *mysql, char *pidfile)
  1026. {
  1027.   MYSQL_RES* result;
  1028.   if (mysql_query(mysql, "SHOW VARIABLES LIKE 'pid_file'"))
  1029.   {
  1030.     my_printf_error(0,"query failed; error: '%s'",MYF(ME_BELL),
  1031.     mysql_error(mysql));
  1032.   }
  1033.   result = mysql_store_result(mysql);
  1034.   if (result)
  1035.   {
  1036.     MYSQL_ROW row=mysql_fetch_row(result);
  1037.     if (row)
  1038.       strmov(pidfile, row[1]);
  1039.     mysql_free_result(result);
  1040.     return row == 0; /* Error if row = 0 */
  1041.   }
  1042.   return 1; /* Error */
  1043. }
  1044. static void wait_pidfile(char *pidfile)
  1045. {
  1046.   char buff[FN_REFLEN];
  1047.   int fd;
  1048.   uint count=0;
  1049.   system_filename(buff,pidfile);
  1050.   while ((fd = open(buff, O_RDONLY)) >= 0 && count++ < opt_shutdown_timeout)
  1051.   {
  1052.     close(fd);
  1053.     sleep(1);
  1054.   }
  1055.   if (fd >= 0)
  1056.   {
  1057.     close(fd);
  1058.     fprintf(stderr,
  1059.     "Warning;  Aborted waiting on pid file: '%s' after %d secondsn",
  1060.     buff, count-1);
  1061.   }
  1062. }