1#!@SHELL_PATH@
2# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB
3# This file is public domain and comes with NO WARRANTY of any kind
4#
5# Script to start the MySQL daemon and restart it if it dies unexpectedly
6#
7# This should be executed in the MySQL base directory if you are using a
8# binary installation that is not installed in its compile-time default
9# location
10#
11# mysql.server works by first doing a cd to the base directory and from there
12# executing mysqld_safe
13
14# Initialize script globals
15KILL_MYSQLD=1;
16MYSQLD=
17niceness=0
18mysqld_ld_preload=
19mysqld_ld_library_path=
20
21# Initial logging status: error log is not open, and not using syslog
22logging=init
23want_syslog=0
24syslog_tag=
25user='@MYSQLD_USER@'
26pid_file=
27pid_file_append=
28err_log=
29err_log_append=
30timestamp_format=UTC
31
32syslog_tag_mysqld=mysqld
33syslog_tag_mysqld_safe=mysqld_safe
34syslog_facility=daemon
35
36trap '' 1 2 3 15			# we shouldn't let anyone kill us
37trap '' 13                              # not even SIGPIPE
38
39# MySQL-specific environment variable. First off, it's not really a umask,
40# it's the desired mode. Second, it follows umask(2), not umask(3) in that
41# octal needs to be explicit. Our shell might be a proper sh without printf,
42# multiple-base arithmetic, and binary arithmetic, so this will get ugly.
43# We reject decimal values to keep things at least half-sane.
44umask 007                               # fallback
45UMASK="${UMASK-0640}"
46fmode=`echo "$UMASK" | sed -e 's/[^0246]//g'`
47octalp=`echo "$fmode"|cut -c1`
48fmlen=`echo "$fmode"|wc -c|sed -e 's/ //g'`
49if [ "x$octalp" != "x0" -o "x$UMASK" != "x$fmode" -o "x$fmlen" != "x5" ]
50then
51  fmode=0640
52  echo "UMASK must be a 3-digit mode with an additional leading 0 to indicate octal." >&2
53  echo "The first digit will be corrected to 6, the others may be 0, 2, 4, or 6." >&2
54fi
55fmode=`echo "$fmode"|cut -c3-4`
56fmode="6$fmode"
57if [ "x$UMASK" != "x0$fmode" ]
58then
59  echo "UMASK corrected from $UMASK to 0$fmode ..."
60fi
61
62defaults=
63case "$1" in
64    --no-defaults|--defaults-file=*|--defaults-extra-file=*)
65      defaults="$1"; shift
66      ;;
67esac
68
69usage () {
70        cat <<EOF
71Usage: $0 [OPTIONS]
72 The following options may be given as the first argument:
73  --no-defaults              Don't read the system defaults file
74  --defaults-file=FILE       Use the specified defaults file
75  --defaults-extra-file=FILE Also use defaults from the specified file
76
77 Other options:
78  --ledir=DIRECTORY          Look for mysqld in the specified directory
79  --open-files-limit=LIMIT   Limit the number of open files
80  --core-file-size=LIMIT     Limit core files to the specified size
81  --timezone=TZ              Set the system timezone
82  --malloc-lib=LIB           Preload shared library LIB if available
83  --mysqld=FILE              Use the specified file as mysqld
84  --mysqld-version=VERSION   Use "mysqld-VERSION" as mysqld
85  --nice=NICE                Set the scheduling priority of mysqld
86  --plugin-dir=DIR           Plugins are under DIR or DIR/VERSION, if
87                             VERSION is given
88  --skip-kill-mysqld         Don't try to kill stray mysqld processes
89  --syslog                   Log messages to syslog with 'logger'
90  --skip-syslog              Log messages to error log (default)
91  --syslog-tag=TAG           Pass -t "mysqld-TAG" to 'logger'
92  --mysqld-safe-log-         TYPE must be one of UTC (ISO 8601 UTC),
93    timestamps=TYPE          system (ISO 8601 local time), hyphen
94                             (hyphenated date a la mysqld 5.6), legacy
95                             (legacy non-ISO 8601 mysqld_safe timestamps)
96
97All other options are passed to the mysqld program.
98
99EOF
100        exit 1
101}
102
103my_which ()
104{
105  save_ifs="${IFS-UNSET}"
106  IFS=:
107  ret=0
108  for file
109  do
110    for dir in $PATH
111    do
112      if [ -f "$dir/$file" ]
113      then
114        echo "$dir/$file"
115        continue 2
116      fi
117    done
118
119	ret=1  #signal an error
120	break
121  done
122
123  if [ "$save_ifs" = UNSET ]
124  then
125    unset IFS
126  else
127    IFS="$save_ifs"
128  fi
129  return $ret  # Success
130}
131
132log_generic () {
133  priority="$1"
134  shift
135
136  msg="`eval $DATE` mysqld_safe $*"
137  echo "$msg"
138  case $logging in
139    init) ;;  # Just echo the message, don't save it anywhere
140    file)
141      if [ -w / -o "$USER" = "root" ]; then
142        true
143      else
144        echo "$msg" >> "$err_log"
145      fi
146      ;;
147    syslog) logger -t "$syslog_tag_mysqld_safe" -p "$priority" "$*" ;;
148    both)
149      if [ -w / -o "$USER" = "root" ]; then
150        true
151      else
152        echo "$msg" >> "$err_log"
153      fi
154      logger -t "$syslog_tag_mysqld_safe" -p "$priority" "$*"
155      ;;
156    *)
157      echo "Internal program error (non-fatal):" \
158           " unknown logging method '$logging'" >&2
159      ;;
160  esac
161}
162
163log_error () {
164  log_generic ${syslog_facility}.error "$@" >&2
165}
166
167log_notice () {
168  log_generic ${syslog_facility}.notice "$@"
169}
170
171eval_log_error () {
172  cmd="$1"
173  case $logging in
174    file)
175      if [ -w / -o "$USER" = "root" ]; then
176        cmd="$cmd > /dev/null 2>&1"
177      else
178        cmd="$cmd >> "`shell_quote_string "$err_log"`" 2>&1"
179      fi
180      ;;
181    syslog)
182      cmd="$cmd --log-syslog=1 --log-syslog-facility=$syslog_facility '--log-syslog-tag=$syslog_tag' > /dev/null 2>&1"
183      ;;
184    both)
185      if [ -w / -o "$USER" = "root" ]; then
186        cmd="$cmd --log-syslog=1 --log-syslog-facility=$syslog_facility '--log-syslog-tag=$syslog_tag' > /dev/null 2>&1"
187      else
188        cmd="$cmd --log-syslog=1 --log-syslog-facility=$syslog_facility '--log-syslog-tag=$syslog_tag' >> "`shell_quote_string "$err_log"`" 2>&1"
189      fi
190      ;;
191    *)
192      echo "Internal program error (non-fatal):" \
193           " unknown logging method '$logging'" >&2
194      ;;
195  esac
196
197  #echo "Running mysqld: [$cmd]"
198  eval "$cmd"
199}
200
201shell_quote_string() {
202  # This sed command makes sure that any special chars are quoted,
203  # so the arg gets passed exactly to the server.
204  echo "$1" | sed -e 's,\([^a-zA-Z0-9/_.=-]\),\\\1,g'
205}
206
207parse_arguments() {
208  # We only need to pass arguments through to the server if we don't
209  # handle them here.  So, we collect unrecognized options (passed on
210  # the command line) into the args variable.
211  pick_args=
212  if test "$1" = PICK-ARGS-FROM-ARGV
213  then
214    pick_args=1
215    shift
216  fi
217
218  for arg do
219    # the parameter after "=", or the whole $arg if no match
220    val=`echo "$arg" | sed -e 's;^--[^=]*=;;'`
221    # what's before "=", or the whole $arg if no match
222    optname=`echo "$arg" | sed -e 's/^\(--[^=]*\)=.*$/\1/'`
223    # replace "_" by "-" ; mysqld_safe must accept "_" like mysqld does.
224    optname_subst=`echo "$optname" | sed 's/_/-/g'`
225    arg=`echo $arg | sed "s/^$optname/$optname_subst/"`
226    case "$arg" in
227      # these get passed explicitly to mysqld
228      --basedir=*) MY_BASEDIR_VERSION="$val" ;;
229      --datadir=*)
230        case $val in
231          /) DATADIR=$val ;;
232          *) DATADIR="`echo $val | sed 's;/*$;;'`" ;;
233        esac
234        ;;
235      --pid-file=*) pid_file="$val" ;;
236      --plugin-dir=*) PLUGIN_DIR="$val" ;;
237      --user=*) user="$val"; SET_USER=1 ;;
238
239      # these might have been set in a [mysqld_safe] section of my.cnf
240      # they are added to mysqld command line to override settings from my.cnf
241      --log-error=*) err_log="$val" ;;
242      --port=*) mysql_tcp_port="$val" ;;
243      --socket=*) mysql_unix_port="$val" ;;
244
245      # mysqld_safe-specific options - must be set in my.cnf ([mysqld_safe])!
246      --core-file-size=*) core_file_size="$val" ;;
247      --ledir=*)
248        if [ -z "$pick_args" ]; then
249          log_error "--ledir option can only be used as command line option, found in config file"
250          exit 1
251        fi
252        ledir="$val"
253        ;;
254      --malloc-lib=*) set_malloc_lib "$val" ;;
255      --mysqld=*)
256        if [ -z "$pick_args" ]; then
257          log_error "--mysqld option can only be used as command line option, found in config file"
258          exit 1
259        fi
260        MYSQLD="$val" ;;
261      --mysqld-version=*)
262        if [ -z "$pick_args" ]; then
263          log_error "--mysqld-version option can only be used as command line option, found in config file"
264          exit 1
265        fi
266        if test -n "$val"
267        then
268          MYSQLD="mysqld-$val"
269          PLUGIN_VARIANT="/$val"
270        else
271          MYSQLD="mysqld"
272        fi
273        ;;
274      --nice=*) niceness="$val" ;;
275      --open-files-limit=*) open_files="$val" ;;
276      --open_files_limit=*) open_files="$val" ;;
277      --skip-kill-mysqld*) KILL_MYSQLD=0 ;;
278      --mysqld-safe-log-timestamps=*) timestamp_format="$val" ;;
279      --syslog) want_syslog=1 ;;
280      --skip-syslog) want_syslog=0 ;;
281      --syslog-tag=*) syslog_tag="$val" ;;
282      --timezone=*) TZ="$val"; export TZ; ;;
283
284      --help) usage ;;
285
286      *)
287        if test -n "$pick_args"
288        then
289          append_arg_to_args "$arg"
290        fi
291        ;;
292    esac
293  done
294}
295
296
297# Add a single shared library to the list of libraries which will be added to
298# LD_PRELOAD for mysqld
299#
300# Since LD_PRELOAD is a space-separated value (for historical reasons), if a
301# shared lib's path contains spaces, that path will be prepended to
302# LD_LIBRARY_PATH and stripped from the lib value.
303add_mysqld_ld_preload() {
304  lib_to_add="$1"
305  log_notice "Adding '$lib_to_add' to LD_PRELOAD for mysqld"
306
307  case "$lib_to_add" in
308    *' '*)
309      # Must strip path from lib, and add it to LD_LIBRARY_PATH
310      lib_file=`basename "$lib_to_add"`
311      case "$lib_file" in
312        *' '*)
313          # The lib file itself has a space in its name, and can't
314          # be used in LD_PRELOAD
315          log_error "library name '$lib_to_add' contains spaces and can not be used with LD_PRELOAD"
316          exit 1
317          ;;
318      esac
319      lib_path=`dirname "$lib_to_add"`
320      lib_to_add="$lib_file"
321      [ -n "$mysqld_ld_library_path" ] && mysqld_ld_library_path="$mysqld_ld_library_path:"
322      mysqld_ld_library_path="$mysqld_ld_library_path$lib_path"
323      ;;
324  esac
325
326  # LD_PRELOAD is a space-separated
327  [ -n "$mysqld_ld_preload" ] && mysqld_ld_preload="$mysqld_ld_preload "
328  mysqld_ld_preload="${mysqld_ld_preload}$lib_to_add"
329}
330
331
332# Returns LD_PRELOAD (and LD_LIBRARY_PATH, if needed) text, quoted to be
333# suitable for use in the eval that calls mysqld.
334#
335# All values in mysqld_ld_preload are prepended to LD_PRELOAD.
336mysqld_ld_preload_text() {
337  text=
338
339  if [ -n "$mysqld_ld_preload" ]; then
340    new_text="$mysqld_ld_preload"
341    [ -n "$LD_PRELOAD" ] && new_text="$new_text $LD_PRELOAD"
342    text="${text}LD_PRELOAD="`shell_quote_string "$new_text"`' '
343  fi
344
345  if [ -n "$mysqld_ld_library_path" ]; then
346    new_text="$mysqld_ld_library_path"
347    [ -n "$LD_LIBRARY_PATH" ] && new_text="$new_text:$LD_LIBRARY_PATH"
348    text="${text}LD_LIBRARY_PATH="`shell_quote_string "$new_text"`' '
349  fi
350
351  echo "$text"
352}
353
354# set_malloc_lib LIB
355# - If LIB is empty, do nothing and return
356# - If LIB is an absolute path, assume it is a malloc shared library
357#
358# Put LIB in mysqld_ld_preload, which will be added to LD_PRELOAD when
359# running mysqld.  See ld.so for details.
360set_malloc_lib() {
361  # This list is kept intentionally simple.
362  malloc_dirs="/usr/lib /usr/lib64 /usr/lib/i386-linux-gnu /usr/lib/x86_64-linux-gnu"
363  malloc_lib="$1"
364
365  # Allow --malloc-lib='' to override other settings
366  [ -z  "$malloc_lib" ] && return
367
368  case "$malloc_lib" in
369    /*)
370      if [ ! -r "$malloc_lib" ]; then
371        log_error "--malloc-lib can not be read and will not be used"
372        exit 1
373      fi
374
375      # Restrict to a the list in $malloc_dirs above
376      case "`dirname "$malloc_lib"`" in
377        /usr/lib) ;;
378        /usr/lib64) ;;
379        /usr/lib/i386-linux-gnu) ;;
380        /usr/lib/x86_64-linux-gnu) ;;
381        *)
382          log_error "--malloc-lib must be located in one of the directories: $malloc_dirs"
383          exit 1
384          ;;
385      esac
386      ;;
387    *)
388      log_error "--malloc-lib must be an absolute path ignoring value '$malloc_lib'"
389      exit 1
390      ;;
391  esac
392
393  add_mysqld_ld_preload "$malloc_lib"
394}
395
396find_basedir_from_cmdline () {
397  for arg in "$@"; do
398    case $arg in
399      --basedir=*)
400        MY_BASEDIR_VERSION="`echo "$arg" | sed -e 's;^--[^=]*=;;'`"
401        # Convert to full path
402        cd "$MY_BASEDIR_VERSION"
403        if [ $? -ne 0 ] ; then
404          log_error "--basedir set to '$MY_BASEDIR_VERSION', however could not access directory"
405          exit 1
406        fi
407        MY_BASEDIR_VERSION="`pwd`"
408        ;;
409    esac
410  done
411}
412
413#
414# First, try to find BASEDIR and ledir (where mysqld is)
415#
416
417oldpwd="`pwd`"
418
419# Args not parsed yet, check if --basedir was given on command line
420find_basedir_from_cmdline "$@"
421
422# --basedir is already overridden on command line
423if test -n "$MY_BASEDIR_VERSION" -a -d "$MY_BASEDIR_VERSION" ; then
424  # Search for mysqld and set ledir
425  for dir in @INSTALL_SBINDIR@ libexec sbin bin ; do
426    if test -x "$MY_BASEDIR_VERSION/$dir/mysqld" ; then
427      ledir="$MY_BASEDIR_VERSION/$dir"
428      break
429    fi
430  done
431
432else
433  # Basedir should be parent dir of bindir, unless some non-standard
434  # layout is used
435
436  cd "`dirname $0`"
437  if [ -h "$0" ] ; then
438    realpath="`ls -l  "$0" | awk '{print $NF}'`"
439    cd "`dirname "$realpath"`"
440  fi
441  cd ..
442  MY_PWD="`pwd`"
443
444  # Search for mysqld and set ledir and BASEDIR
445  for dir in @INSTALL_SBINDIR@ libexec sbin bin ; do
446    if test -x "$MY_PWD/$dir/mysqld" ; then
447      MY_BASEDIR_VERSION="$MY_PWD"
448      ledir="$MY_BASEDIR_VERSION/$dir"
449      break
450    fi
451  done
452
453  # If we still didn't find anything, use the compiled-in defaults
454  if test -z "$MY_BASEDIR_VERSION" ; then
455    MY_BASEDIR_VERSION='@prefix@'
456    ledir='@libexecdir@'
457  fi
458fi
459
460#
461# Second, try to find the data directory
462#
463
464# Try where the binary installs put it
465if test -d $MY_BASEDIR_VERSION/data/mysql
466then
467  DATADIR=$MY_BASEDIR_VERSION/data
468# Or just give up and use our compiled-in default
469else
470  DATADIR=@localstatedir@
471fi
472
473if test -z "$MYSQL_HOME"
474then
475  MYSQL_HOME=$MY_BASEDIR_VERSION
476fi
477export MYSQL_HOME
478
479
480# Get first arguments from the my.cnf file, groups [mysqld] and [mysqld_safe]
481# and then merge with the command line arguments
482if test -x "$MY_BASEDIR_VERSION/bin/my_print_defaults" ; then
483  print_defaults="$MY_BASEDIR_VERSION/bin/my_print_defaults"
484elif test -x "@bindir@/my_print_defaults" ; then
485  print_defaults="@bindir@/my_print_defaults"
486else
487  print_defaults="my_print_defaults"
488fi
489
490append_arg_to_args () {
491  args="$args "`shell_quote_string "$1"`
492}
493
494args=
495
496cd "$oldpwd"
497
498SET_USER=2
499parse_arguments `$print_defaults $defaults --loose-verbose mysqld server`
500if test $SET_USER -eq 2
501then
502  SET_USER=0
503fi
504
505parse_arguments `$print_defaults $defaults --loose-verbose mysqld_safe safe_mysqld`
506parse_arguments PICK-ARGS-FROM-ARGV "$@"
507
508#
509# Sort out date command from $timestamp_format early so we'll start off
510# with correct log messages.
511#
512case "$timestamp_format" in
513    UTC|utc)       DATE="date -u +%Y-%m-%dT%H:%M:%S.%06NZ";;
514    SYSTEM|system) DATE="date +%Y-%m-%dT%H:%M:%S.%06N%:z";;
515    HYPHEN|hyphen) DATE="date +'%Y-%m-%d %H:%M:%S'";;
516    LEGACY|legacy) DATE="date +'%y%m%d %H:%M:%S'";;
517    *)             DATE="date -u +%Y-%m-%dT%H:%M:%S.%06NZ";
518                   log_error "unknown data format $timestamp_format, using UTC";;
519esac
520
521#
522# Try to find the plugin directory
523#
524
525# Use user-supplied argument
526if [ -n "${PLUGIN_DIR}" ]; then
527  plugin_dir="${PLUGIN_DIR}"
528else
529  # Try to find plugin dir relative to basedir
530  for dir in lib64/mysql/plugin lib64/plugin lib/mysql/plugin lib/plugin
531  do
532    if [ -d "${MY_BASEDIR_VERSION}/${dir}" ]; then
533      plugin_dir="${MY_BASEDIR_VERSION}/${dir}"
534      break
535    fi
536  done
537  # Give up and use compiled-in default
538  if [ -z "${plugin_dir}" ]; then
539    plugin_dir='@pkgplugindir@'
540  fi
541fi
542plugin_dir="${plugin_dir}${PLUGIN_VARIANT}"
543
544# Determine what logging facility to use
545
546# Ensure that 'logger' exists, if it's requested
547if [ $want_syslog -eq 1 ]
548then
549  my_which logger > /dev/null 2>&1
550  if [ $? -ne 0 ]
551  then
552    log_error "--syslog requested, but no 'logger' program found.  Please ensure that 'logger' is in your PATH, or do not specify the --syslog option to mysqld_safe."
553    exit 1
554  fi
555fi
556
557if [ $want_syslog -eq 1 ]
558then
559  if [ -n "$syslog_tag" ]
560  then
561    # Sanitize the syslog tag
562    syslog_tag=`echo "$syslog_tag" | sed -e 's/[^a-zA-Z0-9_-]/_/g'`
563    syslog_tag_mysqld_safe="${syslog_tag_mysqld_safe}-$syslog_tag"
564    syslog_tag_mysqld="${syslog_tag_mysqld}-$syslog_tag"
565  fi
566  log_notice "Logging to syslog."
567  logging=syslog
568fi
569
570if [ -n "$err_log" -o $want_syslog -eq 0 ]
571then
572  if [ -n "$err_log" ]
573  then
574    # mysqld adds ".err" if there is no extension on the --log-error
575    # argument; must match that here, or mysqld_safe will write to a
576    # different log file than mysqld
577
578    # mysqld does not add ".err" to "--log-error=foo."; it considers a
579    # trailing "." as an extension
580
581    if expr "$err_log" : '.*\.[^/]*$' > /dev/null
582    then
583        :
584    else
585      err_log="$err_log".err
586    fi
587
588    err_log_append="$err_log"
589    case "$err_log" in
590      /* ) ;;
591      * ) err_log="$DATADIR/$err_log" ;;
592    esac
593  else
594    err_log=$DATADIR/`@HOSTNAME@`.err
595    err_log_append=`@HOSTNAME@`.err
596  fi
597
598  append_arg_to_args "--log-error=$err_log_append"
599
600  if [ $want_syslog -eq 1 ]
601  then
602    logging=both
603  else
604    logging=file
605  fi
606fi
607
608logdir=`dirname "$err_log"`
609# Change the err log to the right user, if possible and it is in use
610if [ $logging = "file" -o $logging = "both" ]; then
611  if [ ! -e "$err_log" -a ! -h "$err_log" ]; then
612    if test -w / -o "$USER" = "root"; then
613      case $logdir in
614        /var/log)
615          (
616            umask 0137
617            set -o noclobber
618            > "$err_log" && chown $user "$err_log"
619          ) ;;
620        *) ;;
621      esac
622    else
623      (
624        umask 0137
625        set -o noclobber
626        > "$err_log"
627      )
628    fi
629  fi
630
631  if [ -f "$err_log" -o -p "$err_log" ]; then        # Log to err_log file
632    log_notice "Logging to '$err_log'."
633  elif [ "x$user" = "xroot" ]; then # running as root, mysqld can create log file; continue
634    echo "Logging to '$err_log'." >&2
635  else
636    case $logdir in
637      # We can't create $err_log, however mysqld can; continue
638      /tmp|/var/tmp|/var/log/mysql|$DATADIR)
639        echo "Logging to '$err_log'." >&2
640        ;;
641      # We can't create $err_log and don't know if mysqld can; error out
642      *)
643        log_error "error: log-error set to '$err_log', however file don't exists. Create writable for user '$user'."
644        exit 1
645        ;;
646    esac
647  fi
648fi
649
650USER_OPTION=""
651if test -w / -o "$USER" = "root"
652then
653  if test "$user" != "root" -o $SET_USER = 1
654  then
655    USER_OPTION="--user=$user"
656  fi
657  if test -n "$open_files"
658  then
659    ulimit -n $open_files
660  fi
661fi
662
663if test -n "$open_files"
664then
665  append_arg_to_args "--open-files-limit=$open_files"
666fi
667
668safe_mysql_unix_port=${mysql_unix_port:-${MYSQL_UNIX_PORT:-@MYSQL_UNIX_ADDR@}}
669# Check that directory for $safe_mysql_unix_port exists
670mysql_unix_port_dir=`dirname $safe_mysql_unix_port`
671if [ ! -d $mysql_unix_port_dir ]
672then
673  log_error "Directory '$mysql_unix_port_dir' for UNIX socket file don't exists."
674  exit 1
675fi
676
677# If the user doesn't specify a binary, we assume name "mysqld"
678if test -z "$MYSQLD"
679then
680  MYSQLD=mysqld
681fi
682
683if test ! -x "$ledir/$MYSQLD"
684then
685  log_error "The file $ledir/$MYSQLD
686does not exist or is not executable. Please cd to the mysql installation
687directory and restart this script from there as follows:
688./bin/mysqld_safe&
689See http://dev.mysql.com/doc/mysql/en/mysqld-safe.html for more information"
690  exit 1
691fi
692
693if test -z "$pid_file"
694then
695  pid_file="$DATADIR/`@HOSTNAME@`.pid"
696  pid_file_append="`@HOSTNAME@`.pid"
697else
698  pid_file_append="$pid_file"
699  case "$pid_file" in
700    /* ) ;;
701    * )  pid_file="$DATADIR/$pid_file" ;;
702  esac
703fi
704append_arg_to_args "--pid-file=$pid_file_append"
705
706if test -n "$mysql_unix_port"
707then
708  append_arg_to_args "--socket=$mysql_unix_port"
709fi
710if test -n "$mysql_tcp_port"
711then
712  append_arg_to_args "--port=$mysql_tcp_port"
713fi
714
715if test $niceness -eq 0
716then
717  NOHUP_NICENESS="nohup"
718else
719  NOHUP_NICENESS="nohup nice -$niceness"
720fi
721
722# Using nice with no args to get the niceness level is GNU-specific.
723# This check could be extended for other operating systems (e.g.,
724# BSD could use "nohup sh -c 'ps -o nice -p $$' | tail -1").
725# But, it also seems that GNU nohup is the only one which messes
726# with the priority, so this is okay.
727if nohup nice > /dev/null 2>&1
728then
729    normal_niceness=`nice`
730    nohup_niceness=`nohup nice 2>/dev/null`
731
732    numeric_nice_values=1
733    for val in $normal_niceness $nohup_niceness
734    do
735        case "$val" in
736            -[0-9] | -[0-9][0-9] | -[0-9][0-9][0-9] | \
737             [0-9] |  [0-9][0-9] |  [0-9][0-9][0-9] )
738                ;;
739            * )
740                numeric_nice_values=0 ;;
741        esac
742    done
743
744    if test $numeric_nice_values -eq 1
745    then
746        nice_value_diff=`expr $nohup_niceness - $normal_niceness`
747        if test $? -eq 0 && test $nice_value_diff -gt 0 && \
748            nice --$nice_value_diff echo testing > /dev/null 2>&1
749        then
750            # nohup increases the priority (bad), and we are permitted
751            # to lower the priority with respect to the value the user
752            # might have been given
753            niceness=`expr $niceness - $nice_value_diff`
754            NOHUP_NICENESS="nice -$niceness nohup"
755        fi
756    fi
757else
758    if nohup echo testing > /dev/null 2>&1
759    then
760        :
761    else
762        # nohup doesn't work on this system
763        NOHUP_NICENESS=""
764    fi
765fi
766
767# Try to set the core file size (even if we aren't root) because many systems
768# don't specify a hard limit on core file size.
769if test -n "$core_file_size"
770then
771  ulimit -c $core_file_size
772fi
773
774#
775# If there exists an old pid file, check if the daemon is already running
776# Note: The switches to 'ps' may depend on your operating system
777if test -f "$pid_file"
778then
779  PID=`cat "$pid_file"`
780  if @CHECK_PID@
781  then
782    if @FIND_PROC@
783    then    # The pid contains a mysqld process
784      log_error "A mysqld process already exists"
785      exit 1
786    fi
787  fi
788  if [ ! -h "$pid_file" ]; then
789      rm -f "$pid_file"
790      if test -f "$pid_file"; then
791        log_error "Fatal error: Can't remove the pid file:
792$pid_file.
793Please remove the file manually and start $0 again;
794mysqld daemon not started"
795        exit 1
796      fi
797  fi
798  if [ ! -h "$safe_mysql_unix_port" ]; then
799      rm -f "$safe_mysql_unix_port"
800      if test -f "$safe_mysql_unix_port"; then
801        log_error "Fatal error: Can't remove the socket file:
802$safe_mysql_unix_port.
803Please remove the file manually and start $0 again;
804mysqld daemon not started"
805        exit 1
806      fi
807  fi
808  if [ ! -h "$pid_file.shutdown" ]; then
809      rm -f "$pid_file.shutdown"
810      if test -f "$pid_file.shutdown"; then
811        log_error "Fatal error: Can't remove the shutdown file:
812$pid_file.shutdown.
813Please remove the file manually and start $0 again;
814mysqld daemon not started"
815        exit 1
816      fi
817  fi
818fi
819
820#
821# Uncomment the following lines if you want all tables to be automatically
822# checked and repaired during startup. You should add sensible key_buffer
823# and sort_buffer values to my.cnf to improve check performance or require
824# less disk space.
825# Alternatively, you can start mysqld with the "myisam-recover" option. See
826# the manual for details.
827#
828# echo "Checking tables in $DATADIR"
829# $MY_BASEDIR_VERSION/bin/myisamchk --silent --force --fast --medium-check $DATADIR/*/*.MYI
830# $MY_BASEDIR_VERSION/bin/isamchk --silent --force $DATADIR/*/*.ISM
831
832# Does this work on all systems?
833#if type ulimit | grep "shell builtin" > /dev/null
834#then
835#  ulimit -n 256 > /dev/null 2>&1		# Fix for BSD and FreeBSD systems
836#fi
837
838cmd="`mysqld_ld_preload_text`$NOHUP_NICENESS"
839
840for i in  "$ledir/$MYSQLD" "$defaults" "--basedir=$MY_BASEDIR_VERSION" \
841  "--datadir=$DATADIR" "--plugin-dir=$plugin_dir" "$USER_OPTION"
842do
843  cmd="$cmd "`shell_quote_string "$i"`
844done
845cmd="$cmd $args"
846# Avoid 'nohup: ignoring input' warning
847test -n "$NOHUP_NICENESS" && cmd="$cmd < /dev/null"
848
849log_notice "Starting $MYSQLD daemon with databases from $DATADIR"
850
851# variable to track the current number of "fast" (a.k.a. subsecond) restarts
852fast_restart=0
853# maximum number of restarts before trottling kicks in
854max_fast_restarts=5
855# flag whether a usable sleep command exists
856have_sleep=1
857
858while true
859do
860  start_time=`date +%M%S`
861
862  eval_log_error "$cmd"
863
864  # hypothetical: log was renamed but not
865  # flushed yet. we'd recreate it with
866  # wrong owner next time we log, so set
867  # it up correctly while we can!
868
869  if [ $want_syslog -eq 0 -a ! -f "$err_log" -a ! -h "$err_log" ]; then
870    if test -w / -o "$USER" = "root"; then
871      logdir=`dirname "$err_log"`
872      case $logdir in
873        /var/log)
874          (
875            umask 0137
876            set -o noclobber
877            > "$err_log" && chown $user "$err_log"
878          ) ;;
879        *) ;;
880      esac
881    else
882      (
883        umask 0137
884        set -o noclobber
885        > "$err_log"
886      )
887    fi
888  fi
889
890  end_time=`date +%M%S`
891
892  if test ! -f "$pid_file"		# This is removed if normal shutdown
893  then
894    break
895  else                                  # self's mysqld crashed or other's mysqld running
896    PID=`cat "$pid_file"`
897    if @CHECK_PID@
898    then                                # true when above pid belongs to a running mysqld process
899      log_error "A mysqld process with pid=$PID is already running. Aborting!!"
900      exit 1
901    fi
902  fi
903
904  if test -f "$pid_file.shutdown"	# created to signal that it must stop
905  then
906    log_notice "$pid_file.shutdown present. The server will not restart."
907    break
908  fi
909
910
911  # sanity check if time reading is sane and there's sleep
912  if test $end_time -gt 0 -a $have_sleep -gt 0
913  then
914    # throttle down the fast restarts
915    if test $end_time -eq $start_time
916    then
917      fast_restart=`expr $fast_restart + 1`
918      if test $fast_restart -ge $max_fast_restarts
919      then
920        log_notice "The server is respawning too fast. Sleeping for 1 second."
921        sleep 1
922        sleep_state=$?
923        if test $sleep_state -gt 0
924        then
925          log_notice "The server is respawning too fast and no working sleep command. Turning off trottling."
926          have_sleep=0
927        fi
928
929        fast_restart=0
930      fi
931    else
932      fast_restart=0
933    fi
934  fi
935
936  if @TARGET_LINUX@ && test $KILL_MYSQLD -eq 1
937  then
938    # Test if one process was hanging.
939    # This is only a fix for Linux (running as base 3 mysqld processes)
940    # but should work for the rest of the servers.
941    # The only thing is ps x => redhat 5 gives warnings when using ps -x.
942    # kill -9 is used or the process won't react on the kill.
943    numofproces=`ps xaww | grep -v "grep" | grep "$ledir/$MYSQLD\>" | grep -c "pid-file=$pid_file"`
944
945    log_notice "Number of processes running now: $numofproces"
946    I=1
947    while test "$I" -le "$numofproces"
948    do
949      PROC=`ps xaww | grep "$ledir/$MYSQLD\>" | grep -v "grep" | grep "pid-file=$pid_file" | sed -n '$p'`
950
951      for T in $PROC
952      do
953        break
954      done
955      #    echo "TEST $I - $T **"
956      if kill -9 $T
957      then
958        log_error "$MYSQLD process hanging, pid $T - killed"
959      else
960        break
961      fi
962      I=`expr $I + 1`
963    done
964  fi
965  if [ ! -h "$pid_file" ]; then
966    rm -f "$pid_file"
967  fi
968  if [ ! -h "$safe_mysql_unix_port" ]; then
969    rm -f "$safe_mysql_unix_port"
970  fi
971  if [ ! -h "$pid_file.shutdown" ]; then
972    rm -f "$pid_file.shutdown"
973  fi
974  log_notice "mysqld restarted"
975done
976
977if [ ! -h "$pid_file.shutdown" ]; then
978  rm -f "$pid_file.shutdown"
979fi
980
981log_notice "mysqld from pid file $pid_file ended"
982
983if [ ! -h "$safe_pid" ]; then
984  rm -f "$safe_pid"                       # Some Extra Safety. File is deleted
985fi                                        # once the mysqld process ends.
986