listener.cc 9.49 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
#include "priv.h"
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 79
/*
  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()
80
{
unknown's avatar
unknown committed
81
  enum { LISTEN_BACK_LOG_SIZE = 5 };            // standard backlog size
82
  int flags;
unknown's avatar
unknown committed
83
  int arg= 1;                             /* value to be set by setsockopt */
84 85
  int unix_socket;
  uint im_port;
86 87 88 89 90 91
  /* we use this var to check whether we are running on LinuxThreads */
  pid_t thread_pid;

  thread_pid= getpid();
  /* set global variable */
  linuxthreads= (thread_pid != manager_pid);
92 93 94

  thread_registry.register_thread(&thread_info);

95 96
  my_thread_init();

97
  /* I. prepare 'listen' sockets */
98

99 100
  int ip_socket= socket(AF_INET, SOCK_STREAM, 0);
  if (ip_socket == INVALID_SOCKET)
101
  {
102 103
    log_error("Listener_thead::run(): socket(AF_INET) failed, %s",
              strerror(errno));
104
    goto err;
105 106
  }

107
  struct sockaddr_in ip_socket_address;
unknown's avatar
unknown committed
108
  bzero(&ip_socket_address, sizeof(ip_socket_address));
109 110 111 112 113 114 115

  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
116 117
  else
    im_bind_addr= htonl(INADDR_ANY);
118
  im_port= options.port_number;
119 120 121 122 123 124 125 126 127 128 129 130 131 132

  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));
133
   goto err;
134 135 136 137 138 139
  }

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

  log_info("accepting connections on ip socket");

  /*--------------------------------------------------------------*/
152
  unix_socket= socket(AF_UNIX, SOCK_STREAM, 0);
153 154 155 156
  if (unix_socket == INVALID_SOCKET)
  {
    log_error("Listener_thead::run(): socket(AF_UNIX) failed, %s",
              strerror(errno));
157
    goto err;
158 159 160
  }

  struct sockaddr_un unix_socket_address;
unknown's avatar
unknown committed
161
  bzero(&unix_socket_address, sizeof(unix_socket_address));
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

  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));
180
      goto err;
181 182 183 184 185 186 187
    }
    umask(old_mask);

    if (listen(unix_socket, LISTEN_BACK_LOG_SIZE))
    {
      log_error("Listener_thread::run(): listen(unix socket) failed, %s",
                strerror(errno));
188
      goto err;
189 190 191 192 193
    }

      /* set the socket nonblocking */
    flags= fcntl(unix_socket, F_GETFL, 0);
    fcntl(unix_socket, F_SETFL, flags | O_NONBLOCK);
unknown's avatar
unknown committed
194
      /* make sure that instances won't be listening our sockets */
unknown's avatar
unknown committed
195 196
    flags= fcntl(unix_socket, F_GETFD, 0);
    fcntl(unix_socket, F_SETFD, flags | FD_CLOEXEC);
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  }
  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;
214 215 216 217 218 219

      /*
        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.
      */
220
      int rc= select(n, &read_fds_arg, 0, 0, 0);
221 222


223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
      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);
            }
          }
        }
unknown's avatar
unknown committed
244 245 246 247 248
        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
249
          {
unknown's avatar
unknown committed
250 251 252
            if (Vio *vio= vio_new(client_fd, VIO_TYPE_TCPIP, 0))
              handle_new_mysql_connection(vio);
            else
253
            {
unknown's avatar
unknown committed
254 255
              shutdown(client_fd, SHUT_RDWR);
              close(client_fd);
256
            }
unknown's avatar
unknown committed
257
          }
258 259 260 261 262 263 264 265 266 267
        }
      }
    }
  }

  /* III. Release all resources and exit */

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

  close(unix_socket);
unknown's avatar
unknown committed
268
  close(ip_socket);
269
  unlink(unix_socket_address.sun_path);
270 271

  thread_registry.unregister_thread(&thread_info);
272
  my_thread_end();
273 274 275 276 277
  return;

err:
  thread_registry.unregister_thread(&thread_info);
  thread_registry.request_shutdown();
278
  my_thread_end();
279
  return;
280 281 282
}


283 284 285 286 287 288 289 290 291 292 293 294 295 296
/*
  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)
      )
297
  {
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    /*
      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);
314
  }
315 316 317 318 319 320 321 322 323 324 325 326 327
  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();
328
  /*
329 330
    args is a stack variable because listener thread lives as long as the
    manager process itself
331
  */
332 333 334 335 336
  return 0;
}


C_MODE_END
337