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

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

#ifdef __GNUC__
#pragma implementation
#endif

21
#include "listener.h"
22 23 24 25 26

#include <m_string.h>
#include <mysql.h>
#include <violite.h>
#include <sys/un.h>
unknown's avatar
unknown committed
27
#include <sys/stat.h>
28 29 30 31

#include "thread_registry.h"
#include "options.h"
#include "instance_map.h"
32
#include "log.h"
33
#include "mysql_connection.h"
34 35


36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
/*
  Listener_thread - incapsulates listening functionality
*/

class Listener_thread: public Listener_thread_args
{
public:
  Listener_thread(const Listener_thread_args &args);
  ~Listener_thread();
  void run();
private:
  ulong total_connection_count;
  Thread_info thread_info;
private:
  void handle_new_mysql_connection(Vio *vio);
};


Listener_thread::Listener_thread(const Listener_thread_args &args) :
  Listener_thread_args(args.thread_registry, args.options, args.user_map,
                       args.instance_map)
  ,total_connection_count(0)
  ,thread_info(pthread_self())
{
}


Listener_thread::~Listener_thread()
{
}


/*
  Listener_thread::run() - listen all supported sockets and spawn a thread
  to handle incoming connection.
  Using 'die' in case of syscall failure is OK now - we don't hold any
  resources and 'die' kills the signal thread automatically. To be rewritten
  one day.
  See also comments in mysqlmanager.cc to picture general Instance Manager
  architecture.
*/

void Listener_thread::run()
79
{
unknown's avatar
unknown committed
80
  enum { LISTEN_BACK_LOG_SIZE = 5 };            // standard backlog size
81
  int flags;
unknown's avatar
unknown committed
82
  int arg= 1;                             /* value to be set by setsockopt */
83 84 85 86 87
  int unix_socket;
  uint im_port;

  thread_registry.register_thread(&thread_info);

88 89
  my_thread_init();

90
  /* I. prepare 'listen' sockets */
91

92 93
  int ip_socket= socket(AF_INET, SOCK_STREAM, 0);
  if (ip_socket == INVALID_SOCKET)
94
  {
95 96
    log_error("Listener_thead::run(): socket(AF_INET) failed, %s",
              strerror(errno));
97
    goto err;
98 99
  }

100
  struct sockaddr_in ip_socket_address;
unknown's avatar
unknown committed
101
  bzero(&ip_socket_address, sizeof(ip_socket_address));
102 103 104 105 106 107 108

  ulong im_bind_addr;
  if (options.bind_address != 0)
  {
    if ((im_bind_addr= (ulong) inet_addr(options.bind_address)) == INADDR_NONE)
      im_bind_addr= htonl(INADDR_ANY);
  }
unknown's avatar
unknown committed
109 110
  else
    im_bind_addr= htonl(INADDR_ANY);
111
  im_port= options.port_number;
112 113 114 115 116 117 118 119 120 121 122 123 124 125

  ip_socket_address.sin_family= AF_INET;
  ip_socket_address.sin_addr.s_addr = im_bind_addr;


  ip_socket_address.sin_port= (unsigned short)
                              htons((unsigned short) im_port);

  setsockopt(ip_socket, SOL_SOCKET, SO_REUSEADDR, (char*) &arg, sizeof(arg));
  if (bind(ip_socket, (struct sockaddr *) &ip_socket_address,
           sizeof(ip_socket_address)))
  {
    log_error("Listener_thread::run(): bind(ip socket) failed, '%s'",
              strerror(errno));
126
   goto err;
127 128 129 130 131 132
  }

  if (listen(ip_socket, LISTEN_BACK_LOG_SIZE))
  {
    log_error("Listener_thread::run(): listen(ip socket) failed, %s",
              strerror(errno));
133
    goto err;
134
  }
unknown's avatar
unknown committed
135
      /* set the socket nonblocking */
136 137
  flags= fcntl(ip_socket, F_GETFL, 0);
  fcntl(ip_socket, F_SETFL, flags | O_NONBLOCK);
unknown's avatar
unknown committed
138
    /* make sure that instances won't be listening our sockets */
unknown's avatar
unknown committed
139 140
  flags= fcntl(ip_socket, F_GETFD, 0);
  fcntl(ip_socket, F_SETFD, flags | FD_CLOEXEC);
141 142 143 144

  log_info("accepting connections on ip socket");

  /*--------------------------------------------------------------*/
145
  unix_socket= socket(AF_UNIX, SOCK_STREAM, 0);
146 147 148 149
  if (unix_socket == INVALID_SOCKET)
  {
    log_error("Listener_thead::run(): socket(AF_UNIX) failed, %s",
              strerror(errno));
150
    goto err;
151 152 153
  }

  struct sockaddr_un unix_socket_address;
unknown's avatar
unknown committed
154
  bzero(&unix_socket_address, sizeof(unix_socket_address));
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

  unix_socket_address.sun_family= AF_UNIX;
  strmake(unix_socket_address.sun_path, options.socket_file_name,
          sizeof(unix_socket_address.sun_path));
  unlink(unix_socket_address.sun_path); // in case we have stale socket file

  {
    /*
      POSIX specifies default permissions for a pathname created by bind
      to be 0777. We need everybody to have access to the socket.
    */
    mode_t old_mask= umask(0);
    if (bind(unix_socket, (struct sockaddr *) &unix_socket_address,
             sizeof(unix_socket_address)))
    {
      log_error("Listener_thread::run(): bind(unix socket) failed, "
                "socket file name is '%s', error '%s'",
                unix_socket_address.sun_path, strerror(errno));
173
      goto err;
174 175 176 177 178 179 180
    }
    umask(old_mask);

    if (listen(unix_socket, LISTEN_BACK_LOG_SIZE))
    {
      log_error("Listener_thread::run(): listen(unix socket) failed, %s",
                strerror(errno));
181
      goto err;
182 183 184 185 186
    }

      /* set the socket nonblocking */
    flags= fcntl(unix_socket, F_GETFL, 0);
    fcntl(unix_socket, F_SETFL, flags | O_NONBLOCK);
unknown's avatar
unknown committed
187
      /* make sure that instances won't be listening our sockets */
unknown's avatar
unknown committed
188 189
    flags= fcntl(unix_socket, F_GETFD, 0);
    fcntl(unix_socket, F_SETFD, flags | FD_CLOEXEC);
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
  }
  log_info("accepting connections on unix socket %s",
           unix_socket_address.sun_path);

  /* II. Listen sockets and spawn childs */

  {
    int n= max(unix_socket, ip_socket) + 1;
    fd_set read_fds;

    FD_ZERO(&read_fds);
    FD_SET(unix_socket, &read_fds);
    FD_SET(ip_socket, &read_fds);

    while (thread_registry.is_shutdown() == false)
    {
      fd_set read_fds_arg= read_fds;
207 208 209 210 211 212

      /*
        When using valgrind 2.0 this syscall doesn't get kicked off by a
        signal during shutdown. This results in failing assert
        (Thread_registry::~Thread_registry). Valgrind 2.2 works fine.
      */
213
      int rc= select(n, &read_fds_arg, 0, 0, 0);
214 215


216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
      if (rc == -1 && errno != EINTR)
        log_error("Listener_thread::run(): select() failed, %s",
                  strerror(errno));
      else
      {
        /* Assuming that rc > 0 as we asked to wait forever */
        if (FD_ISSET(unix_socket, &read_fds_arg))
        {
          int client_fd= accept(unix_socket, 0, 0);
          /* accept may return -1 (failure or spurious wakeup) */
          if (client_fd >= 0)                    // connection established
          {
            if (Vio *vio= vio_new(client_fd, VIO_TYPE_SOCKET, 1))
              handle_new_mysql_connection(vio);
            else
            {
              shutdown(client_fd, SHUT_RDWR);
              close(client_fd);
            }
          }
        }
        else
          if (FD_ISSET(ip_socket, &read_fds_arg))
          {
            int client_fd= accept(ip_socket, 0, 0);
            /* accept may return -1 (failure or spurious wakeup) */
            if (client_fd >= 0)                    // connection established
            {
              if (Vio *vio= vio_new(client_fd, VIO_TYPE_TCPIP, 0))
              {
                handle_new_mysql_connection(vio);
              }
              else
              {
                shutdown(client_fd, SHUT_RDWR);
                close(client_fd);
              }
            }
        }
      }
    }
  }

  /* III. Release all resources and exit */

  log_info("Listener_thread::run(): shutdown requested, exiting...");

  close(unix_socket);
unknown's avatar
unknown committed
264
  close(ip_socket);
265
  unlink(unix_socket_address.sun_path);
266 267

  thread_registry.unregister_thread(&thread_info);
268
  my_thread_end();
269 270 271 272 273
  return;

err:
  thread_registry.unregister_thread(&thread_info);
  thread_registry.request_shutdown();
274
  my_thread_end();
275
  return;
276 277 278
}


279 280 281 282 283 284 285 286 287 288 289 290 291 292
/*
  Create new mysql connection. Created thread is responsible for deletion of
  the Mysql_connection_thread_args and Vio instances passed to it.
  SYNOPSYS
    handle_new_mysql_connection()
*/

void Listener_thread::handle_new_mysql_connection(Vio *vio)
{
  if (Mysql_connection_thread_args *mysql_thread_args=
      new Mysql_connection_thread_args(vio, thread_registry, user_map,
                                       ++total_connection_count,
                                       instance_map)
      )
293
  {
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    /*
      Initialize thread attributes to create detached thread; it seems
      easier to do it ad-hoc than have a global variable for attributes.
    */
    pthread_t mysql_thd_id;
    pthread_attr_t mysql_thd_attr;
    pthread_attr_init(&mysql_thd_attr);
    pthread_attr_setdetachstate(&mysql_thd_attr, PTHREAD_CREATE_DETACHED);
    if (pthread_create(&mysql_thd_id, &mysql_thd_attr, mysql_connection,
                       mysql_thread_args))
    {
      delete mysql_thread_args;
      vio_delete(vio);
      log_error("handle_one_mysql_connection(): pthread_create(mysql) failed");
    }
    pthread_attr_destroy(&mysql_thd_attr);
310
  }
311 312 313 314 315 316 317 318 319 320 321 322 323
  else
    vio_delete(vio);
}


C_MODE_START


pthread_handler_decl(listener, arg)
{
  Listener_thread_args *args= (Listener_thread_args *) arg;
  Listener_thread listener(*args);
  listener.run();
324
  /*
325 326
    args is a stack variable because listener thread lives as long as the
    manager process itself
327
  */
328 329 330 331 332
  return 0;
}


C_MODE_END
333