Commit e854a718 authored by mitshel's avatar mitshel
Browse files

Произведене доработка демона sopdsd.py

изменено несколько конфигурационных параметров
parent 2e1b6589
Loading
Loading
Loading
Loading
+19 −7
Original line number Diff line number Diff line
@@ -120,11 +120,15 @@ new_period = 7
book_shelf = yes

# Настройка логов
# Параметр logfile задает имя файла, куда будут складываться логи (путь задавать не нужно - логи будут находится в папке logs)
# По умолчанию logfile = sopds.log
# Параметр logfile задает имя файла, куда будут складываться логи выполнения скрипта sopds-scan.py 
# (путь задавать не нужно - логи будут находится в папке logs)
# По умолчанию logfile = scan.log
# loglevel может быть одним из следующих значений: debug, info, warning, error, critical, none. 
# По умолчанию loglevel=info
logfile=scan.log

# loglevel может быть одним из следующих значений: debug, info, warning, error, critical, none.
# По умолчанию loglevel=info
logfile=sopds-scan.log
loglevel=info

[scand]
@@ -132,6 +136,10 @@ loglevel=info
# по умолчанию pid_file=/tmp/sopds.pid
pid_file = /tmp/sopds-scan.pid

# Если daemon = yes, то демон sopdsd.py запустит встроенный SCAN-cервер
# по умолчнию daemon = yes
daemon = yes

# scan_day_of_week содержит день недели (1=пн, 7=вс, 0=каждый день) когда должен запускаться процесс сканирования
# по умолчанию scan_day_of_week=0
scan_day_of_week = 0
@@ -152,14 +160,18 @@ scan_interval = 360
# по умолчанию scan_on_start = yes
scan_on_start = yes

# Параметр logfile задает имя файла, куда будут складываться логи от SCAND-демона (путь задавать не нужно - логи будут находится в папке logs)
# По умолчанию logfile = sopds-scand.log
logfile = sopds-scand.log

[httpd]
# pid_file должен содержать путь к pid-файлу процесса OPDS-сервера. Для демона sopdsd.py по указанному пути должен быть доступ на запись
# по умолчанию pid_file=/tmp/sopds-http.pid
pid_file = /tmp/sopds-http.pid

# Если server = yes, то демон sopdsd.py запустит встроенный HTTP-OPDS-сервер
# по умолчнию server = yes
server = yes
# Если daemon = yes, то демон sopdsd.py запустит встроенный HTTP-OPDS-сервер
# по умолчнию daemon = yes
daemon = yes

# Номер TCP порта на котором будет работать OPDS-сервер
# по умолчанию port = 8081
@@ -180,7 +192,7 @@ accounts = user:pass user1:pass1

# Параметр logfile задает имя файла, куда будут складываться логи от HTTP-демона (путь задавать не нужно - логи будут находится в папке logs)
# По умолчанию logfile = access.log
logfile = sopds-http.log
logfile = sopds-httpd.log

[site]
id=http://sopds.ru/

logs/sopds.log

deleted100644 → 0
+0 −2477

File deleted.

Preview size limit exceeded, changes collapsed.

+12 −9
Original line number Diff line number Diff line
@@ -81,7 +81,7 @@ class cfgreader:
       self.TEMP_DIR=config.getdefault(CFG_S_GLOBAL,'temp_dir','/tmp')
       self.TEMP_DIR=os.path.normpath(self.TEMP_DIR)
       
       logfile=config.getdefault(CFG_S_GLOBAL,'logfile','sopds.log')
       logfile=config.getdefault(CFG_S_GLOBAL,'logfile','scan.log')
       self.LOGFILE=os.path.join(LOG_PATH,logfile)
       loglevel=config.getdefault(CFG_S_GLOBAL,'loglevel','info')
       if loglevel.lower() in loglevels:
@@ -131,12 +131,15 @@ class cfgreader:
       self.SITE_EMAIL=config.get(CFG_S_SITE,'email')
       self.SITE_MAINTITLE=config.get(CFG_S_SITE,'main_title')

       CFG_S_DAEMON='scand'
       self.SCAN_ON_START=config.getdefault_bool(CFG_S_DAEMON,'scan_on_start',True)
       self.PID_FILE=config.getdefault(CFG_S_DAEMON,'pid_file',r'/tmp/sopds.pid')
       self.DAY_OF_WEEK=config.getdefault_int(CFG_S_DAEMON,'scan_day_of_week',0)
       self.SCAN_INTERVAL=config.getdefault_int(CFG_S_DAEMON,'scan_interval',0)
       self.SCAN_TIME=config.getdefault(CFG_S_DAEMON,'scan_time','00:00')
       CFG_S_SCAND='scand'
       self.SCAN_ON_START=config.getdefault_bool(CFG_S_SCAND,'scan_on_start',True)
       self.PID_FILE=config.getdefault(CFG_S_SCAND,'pid_file',r'/tmp/sopds.pid')
       self.SCAN_DAEMON=config.getdefault_bool(CFG_S_SCAND,'daemon',True)
       self.DAY_OF_WEEK=config.getdefault_int(CFG_S_SCAND,'scan_day_of_week',0)
       self.SCAN_INTERVAL=config.getdefault_int(CFG_S_SCAND,'scan_interval',0)
       self.SCAN_TIME=config.getdefault(CFG_S_SCAND,'scan_time','00:00')
       scand_logfile=config.getdefault(CFG_S_SCAND,'logfile','sopds-scand.log')
       self.SCAND_LOGFILE=os.path.join(LOG_PATH,scand_logfile)
       try:
          (scan_hour,scan_min)=self.SCAN_TIME.split(':')
          scan_hour=scan_hour.strip()
@@ -158,11 +161,11 @@ class cfgreader:

       CFG_S_HTTPD='httpd'
       self.HTTPD_PID_FILE=config.getdefault(CFG_S_HTTPD,'pid_file',r'/tmp/sopds-http.pid')
       self.SERVER=config.getdefault_bool(CFG_S_HTTPD,'server',True)
       self.HTTP_DAEMON=config.getdefault_bool(CFG_S_HTTPD,'daemon',True)
       self.PORT=config.getdefault_int(CFG_S_HTTPD,'port',8081)
       self.BIND_ADDRESS=config.getdefault(CFG_S_HTTPD,'bind_address','0.0.0.0')
       self.AUTH=config.getdefault_bool(CFG_S_HTTPD,'auth',False)
       self.ACCOUNTS=config.getdefault(CFG_S_HTTPD,'accounts','')
       httpd_logfile=config.getdefault(CFG_S_HTTPD,'logfile','access.log')
       httpd_logfile=config.getdefault(CFG_S_HTTPD,'logfile','sopds-httpd.log')
       self.HTTPD_LOGFILE=os.path.join(LOG_PATH,httpd_logfile)
+141 −116
Original line number Diff line number Diff line
@@ -16,7 +16,7 @@ class Daemon(object):
    """
    Subclass Daemon class and override the run() method.
    """
    def __init__(self, scan_pidfile, http_pidfile, stdin='/dev/null', scan_stdout='/dev/null', http_stdout='/dev/null', scan_stderr='/dev/null', http_stderr='/dev/null'):
    def __init__(self, scan_pidfile, http_pidfile, stdin='/dev/null', scan_stdout='/dev/null', http_stdout='/dev/null', scan_stderr='/dev/null', http_stderr='/dev/null', enable_scand=True, enable_httpd=True):
        self.stdin = stdin
        self.scan_stdout = scan_stdout
        self.scan_stderr = scan_stderr
@@ -24,6 +24,8 @@ class Daemon(object):
        self.http_stderr = http_stderr
        self.scan_pidfile  = scan_pidfile
        self.http_pidfile  = http_pidfile
        self.enable_httpd = enable_httpd
        self.enable_scand = enable_scand
        self.daemon_type = 0
 
    def daemonize(self):
@@ -46,6 +48,7 @@ class Daemon(object):
        os.umask(0)
 
        # Do second fork (SCAN DAEMON)
        if self.enable_scand:
           try:
               pid = os.fork()
               if pid > 0:
@@ -57,15 +60,19 @@ class Daemon(object):
               sys.exit(1)

        # Do third fork (HTTPD DAEMON)
        if self.enable_httpd:
           try: 
               pid = os.fork()
               if pid>0 and not self.enable_scand:
                   # Exit from second parent.
                   sys.exit(0)
           except OSError as e:
               message = "Fork #3 (httpd) failed: {}. Exitting\n".format(e)
               sys.stderr.write(message)
               sys.exit(1)

 
        if pid>0:
        if (pid>0 and self.enable_httpd) or (self.enable_httpd and not self.enable_scand):
           print('SOPDS HTTP Daemon going to background, PID: {}'.format(os.getpid(),end="\r"))
           self.daemon_type=typeHTTPD
           self.pidfile=self.http_pidfile
@@ -103,6 +110,10 @@ class Daemon(object):
        Start daemon.
        """
        # Check pidfile to see if the daemon already runs.
        scan_pid=None
        http_pid=None
 
        if self.enable_scand:
           try:
               pf = open(self.scan_pidfile,'r')
               scan_pid = int(pf.read().strip())
@@ -110,6 +121,12 @@ class Daemon(object):
           except IOError:
               scan_pid = None

           if scan_pid:
               message = "Pidfile {} for SOPDS SCAN daemon already exist. Daemon already running?\n".format(self.scan_pidfile)
               sys.stderr.write(message)


        if self.enable_httpd:
           try:
               pf = open(self.http_pidfile,'r')
               http_pid = int(pf.read().strip())
@@ -117,19 +134,13 @@ class Daemon(object):
           except IOError:
               http_pid = None
 
 
        if scan_pid:
            message = "Pidfile {} for SOPDS SCAN daemon already exist. Daemon already running?\n".format(self.scan_pidfile)
            sys.stderr.write(message)

           if http_pid:
               message = "Pidfile {} for SOPDS HTTP daemon already exist. Daemon already running?\n".format(self.http_pidfile)
               sys.stderr.write(message)

        if scan_pid or http_pid:
        if (scan_pid and self.enable_scand) or (http_pid and self.enable_httpd):
             sys.exit(1)
 
 
        # Start daemon.
        self.daemonize()
        self.run()
@@ -138,6 +149,10 @@ class Daemon(object):
        """
        Get status of daemon.
        """
        scan_pid = None
        http_pid = None

        if self.enable_scand:
           try:
               pf = open(self.scan_pidfile,'r')
               scan_pid = int(pf.read().strip())
@@ -147,6 +162,7 @@ class Daemon(object):
               sys.stderr.write(message)
               scan_pid = None

        if self.enable_httpd:
           try:
               pf = open(self.http_pidfile,'r')
               http_pid = int(pf.read().strip())
@@ -156,9 +172,10 @@ class Daemon(object):
               sys.stderr.write(message)
               http_pid=None

        if not (scan_pid and http_pid):
        if not ((scan_pid or not self.enable_scand) and (http_pid or not self.enable_httpd)):
            sys.exit(1)
 
        if self.enable_scand:
           try:
               procfile = open("/proc/{}/status".format(scan_pid), 'r')
               procfile.close()
@@ -168,6 +185,7 @@ class Daemon(object):
               message = "There is not a SOPDS SCAN process with the PID {}\n".format(self.scan_pid)
               sys.stdout.write(message)

        if self.enable_httpd:
           try:
               procfile = open("/proc/{}/status".format(http_pid), 'r')
               procfile.close()
@@ -183,6 +201,10 @@ class Daemon(object):
        Stop the daemon.
        """
        # Get the pid from pidfile.
        scan_pid=None
        http_pid=None
 
        if self.enable_scand:
           try:
               pf = open(self.scan_pidfile,'r')
               scan_pid = int(pf.read().strip())
@@ -192,6 +214,21 @@ class Daemon(object):
               sys.stderr.write(message)
               scan_pid = None

           if scan_pid:
              try:
                  os.kill(scan_pid, SIGTERM)
                  time.sleep(1)
              except OSError as e:
                  print(str(e))

           try:
               if os.path.exists(self.scan_pidfile):
                   os.remove(self.scan_pidfile)
           except IOError as e:
               message = str(e) + "\nCan not remove pid file {}".format(self.scan_pidfile)
               sys.stderr.write(message)

        if self.enable_httpd:
           try:
               pf = open(self.http_pidfile,'r')
               http_pid = int(pf.read().strip())
@@ -201,14 +238,6 @@ class Daemon(object):
               sys.stderr.write(message)
               http_pid = None

        # Try killing daemon process.
        if scan_pid:
           try:
               os.kill(scan_pid, SIGTERM)
               time.sleep(1)
           except OSError as e:
               print(str(e))

           if http_pid:
              try:
                  os.kill(http_pid, SIGTERM)
@@ -216,13 +245,6 @@ class Daemon(object):
              except OSError as e:
                  print(str(e))

        try:
            if os.path.exists(self.scan_pidfile):
                os.remove(self.scan_pidfile)
        except IOError as e:
            message = str(e) + "\nCan not remove pid file {}".format(self.scan_pidfile)
            sys.stderr.write(message)

           try:
               if os.path.exists(self.http_pidfile):
                   os.remove(self.http_pidfile)
@@ -248,11 +270,14 @@ class opdsDaemon(Daemon):
    def __init__(self):
        self.start_scan=False
        self.cfg=sopdscfg.cfgreader()
        if not (self.cfg.SCAN_DAEMON or self.cfg.HTTP_DAEMON):
           print('Check configuration file. No daemons enabled.')
           sys.exit(0)

        self.logger = logging.getLogger('')
        self.logger.setLevel(self.cfg.LOGLEVEL)
        formatter=logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
        self.fh = logging.FileHandler(self.cfg.LOGFILE)
        self.fh = logging.FileHandler(self.cfg.SCAND_LOGFILE)
        self.fh.setLevel(self.cfg.LOGLEVEL)
        self.fh.setFormatter(formatter)
        self.logger.addHandler(self.fh)
@@ -260,7 +285,7 @@ class opdsDaemon(Daemon):

        self.scanner=opdsScanner(self.cfg, self.logger)

        Daemon.__init__(self, self.cfg.PID_FILE, self.cfg.HTTPD_PID_FILE, '/dev/null', self.cfg.LOGFILE,self.cfg.HTTPD_LOGFILE,self.cfg.LOGFILE,self.cfg.HTTPD_LOGFILE)
        Daemon.__init__(self, self.cfg.PID_FILE, self.cfg.HTTPD_PID_FILE, '/dev/null', self.cfg.SCAND_LOGFILE,self.cfg.HTTPD_LOGFILE,self.cfg.SCAND_LOGFILE,self.cfg.HTTPD_LOGFILE, self.cfg.SCAN_DAEMON, self.cfg.HTTP_DAEMON)

    def start(self):
        self.logger.info('sopdsDaemon start()...')