mysqlmanager.cc 9.41 KB
Newer Older
1
/* Copyright (C) 2003 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

   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
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   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.

   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 */

17
#include <my_global.h>
18
#include "manager.h"
19

20 21 22
#include "options.h"
#include "log.h"

23 24 25
#include <my_sys.h>
#include <string.h>
#include <signal.h>
26 27
#include <pwd.h>
#include <grp.h>
28
#include <sys/wait.h>
29
#include <sys/types.h>
30
#include <sys/stat.h>
31 32 33


/*
34
  Few notes about Instance Manager architecture:
35 36 37 38 39 40 41
  Instance Manager consisits of two processes: the angel process, and the
  instance manager process. Responsibilities of the angel process is to
  monitor the instance manager process, and restart it in case of
  failure/shutdown. The angel process is started only if startup option
  '--run-as-service' is provided.
  The Instance Manager process consists of several
  subsystems (thread sets):
42
  - the signal handling thread: it's responsibilities are to handle
43
    user signals and propogate them to the other threads. All other threads
44 45
    are accounted in the signal handler thread Thread Registry.
  - the listener: listens all sockets. There is a listening
46 47
    socket for each (mysql, http, snmp, rendezvous (?)) subsystem.
  - mysql subsystem: Instance Manager acts like an ordinary MySQL Server,
48
    but with very restricted command set. Each MySQL client connection is
49 50
    handled in a separate thread. All MySQL client connections threads
    constitute mysql subsystem.
51
  - http subsystem: it is also possible to talk with Instance Manager via
52 53
    http. One thread per http connection is used. Threads are pooled.
  - 'snmp' connections (FIXME: I know nothing about it yet)
54
  - rendezvous threads
55 56 57 58 59
*/

static void init_environment(char *progname);
static void daemonize(const char *log_file_name);
static void angel(const Options &options);
60 61
static struct passwd *check_user(const char *user);
static int set_user(const char *user, struct passwd *user_info);
62 63 64 65 66 67 68 69 70 71 72 73 74 75


/*
  main, entry point
  - init environment
  - handle options
  - daemonize and run angel process (if necessary)
  - run manager process
*/

int main(int argc, char *argv[])
{
  init_environment(argv[0]);
  Options options;
76 77
  struct passwd *user_info;

78 79
  if (options.load(argc, argv))
    goto err;
80 81 82 83 84 85

  if ((user_info= check_user(options.user)))
  {
      if (set_user(options.user, user_info))
      {
        options.cleanup();
86
        goto err;
87 88 89
      }
  }

90 91
  if (options.run_as_service)
  {
92
    /* forks, and returns only in child */
93
    daemonize(options.log_file_name);
94
    /* forks again, and returns only in child: parent becomes angel */
95 96
    angel(options);
  }
97
  manager(options);
98 99
  options.cleanup();
  my_end(0);
100
  return 0;
101 102 103
err:
  my_end(0);
  return 1;
104 105 106 107
}

/******************* Auxilary functions implementation **********************/

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
/* Change to run as another user if started with --user */

static struct passwd *check_user(const char *user)
{
#if !defined(__WIN__) && !defined(OS2) && !defined(__NETWARE__)
  struct passwd *user_info;
  uid_t user_id= geteuid();

  /* Don't bother if we aren't superuser */
  if (user_id)
  {
    if (user)
    {
      /* Don't give a warning, if real user is same as given with --user */
      user_info= getpwnam(user);
      if ((!user_info || user_id != user_info->pw_uid))
        log_info("One can only use the --user switch if running as root\n");
    }
    return NULL;
  }
  if (!user)
  {
    log_info("You are running mysqlmanager as root! This might introduce security problems. It is safer to use --user option istead.\n");
    return NULL;
  }
  if (!strcmp(user, "root"))
    return NULL;                 /* Avoid problem with dynamic libraries */
 if (!(user_info= getpwnam(user)))
  {
    /* Allow a numeric uid to be used */
    const char *pos;
petr@mysql.com's avatar
petr@mysql.com committed
139 140
    for (pos= user; my_isdigit(default_charset_info, *pos); pos++)
    {}
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    if (*pos)                                   /* Not numeric id */
      goto err;
    if (!(user_info= getpwuid(atoi(user))))
      goto err;
    else
      return user_info;
  }
  else
    return user_info;

err:
  log_error("Fatal error: Can't change to run as user '%s' ;  Please check that the user exists!\n", user);
#endif
  return NULL;
}

static int set_user(const char *user, struct passwd *user_info)
{
  DBUG_ASSERT(user_info);
#ifdef HAVE_INITGROUPS
  initgroups((char*) user,user_info->pw_gid);
#endif
  if (setgid(user_info->pw_gid) == -1)
  {
    log_error("setgid() failed");
    return 1;
  }
  if (setuid(user_info->pw_uid) == -1)
  {
    log_error("setuid() failed");
    return 1;
  }
  return 0;
}


177 178 179 180 181 182 183 184 185 186

/*
  Init environment, common for daemon and non-daemon
*/

static void init_environment(char *progname)
{
  MY_INIT(progname);
  log_init();
  umask(0117);
187
  srand(time(0));
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
}


/*
  Become a UNIX service
  SYNOPSYS
    daemonize()
*/

static void daemonize(const char *log_file_name)
{
  pid_t pid= fork();
  switch (pid) {
  case -1:                                      // parent, fork error
    die("daemonize(): fork failed, %s", strerror(errno));
  case 0:                                       // child, fork ok
    int fd;
    /*
206
      Become a session leader: setsid must succeed because child is
207 208
      guaranteed not to be a process group leader (it belongs to the
      process group of the parent.)
209 210
      The goal is not to have a controlling terminal.
    */
211
    setsid();
212 213 214 215 216 217 218
    /*
      As we now don't have a controlling terminal we will not receive
      tty-related signals - no need to ignore them.
    */

    close(STDIN_FILENO);

219
    fd= open(log_file_name, O_WRONLY | O_CREAT | O_APPEND | O_NOCTTY,
220 221 222 223 224 225 226 227 228 229 230
                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
    if (fd < 0)
      die("daemonize(): failed to open log file %s, %s", log_file_name,
          strerror(errno));
    dup2(fd, STDOUT_FILENO);
    dup2(fd, STDERR_FILENO);
    if (fd != STDOUT_FILENO && fd != STDERR_FILENO)
      close(fd);

    /* TODO: chroot() and/or chdir() here */
    break;
231
  default:
232 233 234 235 236 237 238 239 240 241
    /* successfully exit from parent */
    exit(0);
  }
}


enum { CHILD_OK= 0, CHILD_NEED_RESPAWN, CHILD_EXIT_ANGEL };

static volatile sig_atomic_t child_status= CHILD_OK;

242
/*
243 244 245 246 247
  Signal handler for SIGCHLD: reap child, analyze child exit status, and set
  child_status appropriately.
*/

void reap_child(int __attribute__((unused)) signo)
248
{
249 250 251 252 253 254 255 256
  int child_exit_status;
  /* As we have only one child, no need to cycle waitpid */
  if (waitpid(0, &child_exit_status, WNOHANG) > 0)
  {
    if (WIFSIGNALED(child_exit_status))
      child_status= CHILD_NEED_RESPAWN;
    else
      /*
257
        As reap_child is not called for SIGSTOP, we should be here only
258 259 260 261 262 263
        if the child exited normally.
      */
      child_status= CHILD_EXIT_ANGEL;
  }
}

264
static volatile sig_atomic_t is_terminated= 0;
265 266 267 268 269 270 271 272 273

/*
  Signal handler for terminate signals - SIGTERM, SIGHUP, SIGINT.
  Set termination status and return.
  (q) do we need to handle SIGQUIT?
*/

void terminate(int signo)
{
petr@mysql.com's avatar
petr@mysql.com committed
274
  is_terminated= signo;
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
}


/*
  Fork a child and monitor it.
  User can explicitly kill the angel process with SIGTERM/SIGHUP/SIGINT.
  Angel process will exit silently if mysqlmanager exits normally.
*/

static void angel(const Options &options)
{
  /* install signal handlers */
  sigset_t zeromask;                            // to sigsuspend in parent
  struct sigaction sa_chld, sa_term;
  struct sigaction sa_chld_out, sa_term_out, sa_int_out, sa_hup_out;
290 291 292 293 294

  sigemptyset(&zeromask);
  sigemptyset(&sa_chld.sa_mask);
  sigemptyset(&sa_term.sa_mask);

295 296 297 298
  sa_chld.sa_handler= reap_child;
  sa_chld.sa_flags= SA_NOCLDSTOP;
  sa_term.sa_handler= terminate;
  sa_term.sa_flags= 0;
299 300 301 302 303 304

  /* sigaction can fail only on wrong arguments */
  sigaction(SIGCHLD, &sa_chld, &sa_chld_out);
  sigaction(SIGTERM, &sa_term, &sa_term_out);
  sigaction(SIGINT, &sa_term, &sa_int_out);
  sigaction(SIGHUP, &sa_term, &sa_hup_out);
305 306 307 308 309 310

  /* spawn a child */
spawn:
  pid_t pid= fork();
  switch (pid) {
  case -1:
311
    die("angel(): fork failed, %s", strerror(errno));
312 313 314 315
  case 0:                                     // child, success
    /*
      restore default actions for signals to let the manager work with
      signals as he wishes
316
    */
317 318 319 320
    sigaction(SIGCHLD, &sa_chld_out, 0);
    sigaction(SIGTERM, &sa_term_out, 0);
    sigaction(SIGINT, &sa_int_out, 0);
    sigaction(SIGHUP, &sa_hup_out, 0);
321 322
    /* Here we return to main, and fall into manager */
    break;
323 324 325
  default:                                    // parent, success
    while (child_status == CHILD_OK && is_terminated == 0)
      sigsuspend(&zeromask);
326

327
    if (is_terminated)
petr@mysql.com's avatar
petr@mysql.com committed
328
      log_info("angel got signal %d, exiting", is_terminated);
329
    else if (child_status == CHILD_NEED_RESPAWN)
330
    {
331 332 333 334 335
      child_status= CHILD_OK;
      log_error("angel(): mysqlmanager exited abnormally: respawning...");
      sleep(1); /* don't respawn too fast */
      goto spawn;
    }
336 337 338 339 340 341
    /*
      mysqlmanager successfully exited, let's silently evaporate
      If we return to main we fall into the manager() function, so let's
      simply exit().
    */
    exit(0);
342 343
  }
}
344