Revision 8f765069 daemons/ganeti-noded

b/daemons/ganeti-noded
26 26

  
27 27
import os
28 28
import sys
29
import resource
30 29
import traceback
31 30
import BaseHTTPServer
32 31
import simplejson
......
554 553

  
555 554
  # become a daemon
556 555
  if options.fork:
557
    createDaemon()
556
    utils.Daemonize(logfile=constants.LOG_NODESERVER)
558 557

  
559 558
  logger.SetupLogging(twisted_workaround=True, debug=options.debug,
560 559
                      program="ganeti-noded")
......
563 562
  httpd.serve_forever()
564 563

  
565 564

  
566
def createDaemon():
567
  """Detach a process from the controlling terminal and run it in the
568
  background as a daemon.
569

  
570
  """
571
  UMASK = 077
572
  WORKDIR = "/"
573
  # Default maximum for the number of available file descriptors.
574
  if 'SC_OPEN_MAX' in os.sysconf_names:
575
    try:
576
      MAXFD = os.sysconf('SC_OPEN_MAX')
577
      if MAXFD < 0:
578
        MAXFD = 1024
579
    except OSError:
580
      MAXFD = 1024
581
  else:
582
    MAXFD = 1024
583
  # The standard I/O file descriptors are redirected to /dev/null by default.
584
  #REDIRECT_TO = getattr(os, "devnull", "/dev/null")
585
  REDIRECT_TO = constants.LOG_NODESERVER
586
  try:
587
    pid = os.fork()
588
  except OSError, e:
589
    raise Exception("%s [%d]" % (e.strerror, e.errno))
590
  if (pid == 0):  # The first child.
591
    os.setsid()
592
    try:
593
      pid = os.fork() # Fork a second child.
594
    except OSError, e:
595
      raise Exception("%s [%d]" % (e.strerror, e.errno))
596
    if (pid == 0):  # The second child.
597
      os.chdir(WORKDIR)
598
      os.umask(UMASK)
599
    else:
600
      # exit() or _exit()?  See below.
601
      os._exit(0) # Exit parent (the first child) of the second child.
602
  else:
603
    os._exit(0) # Exit parent of the first child.
604
  maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
605
  if (maxfd == resource.RLIM_INFINITY):
606
    maxfd = MAXFD
607

  
608
  # Iterate through and close all file descriptors.
609
  for fd in range(0, maxfd):
610
    try:
611
      os.close(fd)
612
    except OSError: # ERROR, fd wasn't open to begin with (ignored)
613
      pass
614
  os.open(REDIRECT_TO, os.O_RDWR|os.O_CREAT|os.O_APPEND, 0600)
615
  # Duplicate standard input to standard output and standard error.
616
  os.dup2(0, 1)     # standard output (1)
617
  os.dup2(0, 2)     # standard error (2)
618
  return(0)
619

  
620

  
621 565
if __name__ == '__main__':
622 566
  main()

Also available in: Unified diff