コード例 #1
0
ファイル: winservice.py プロジェクト: francasense/web2py
    def start(self):
        import newcron
        import logging
        import logging.config
        from settings import global_settings
        from fileutils import abspath
        from os.path import exists, join
        
        self.log('web2py Cron service starting')
        if not self.chdir():
            return
        if len(sys.argv) == 2:
            opt_mod = sys.argv[1]
        else:
            opt_mod = self._exe_args_
        options = __import__(opt_mod, [], [], '')
        logpath = abspath(join(options.folder, "logging.conf"))
        
        if exists(logpath):
            logging.config.fileConfig(logpath)
        else:
            logging.basicConfig()
        logger = logging.getLogger("web2py.cron")
        global_settings.web2py_crontype = 'external'
        if options.scheduler:   # -K
            apps = [app.strip() for app in options.scheduler.split(
                    ',') if check_existent_app(options, app.strip())]
        else:
            apps = None

        misfire_gracetime = float(options.misfire_gracetime) if 'misfire_gracetime' in dir(options) else 0.0
        logger.info('Starting Window cron service with %0.2f secs gracetime.' % misfire_gracetime)
        self._started = True
        wait_full_min = lambda: 60 - time.time() % 60
        while True:
            try:
                if wait_full_min() >= misfire_gracetime: # an offset of max. 5 secs before full minute (e.g. time.sleep(60) == 58.99 secs)
                    self.extcron = newcron.extcron(options.folder, apps=apps)
                    self.extcron.start()
                    time.sleep(wait_full_min())
                else:
                    logger.debug('time.sleep() offset detected: %0.3f s' % wait_full_min())
                    while wait_full_min() <= misfire_gracetime:
                        pass
                if apps != None:
                    break
                if not self._started:
                    break
            except Exception, ex:
                self.extcron = None
                self.log_error('%s, restarting service.' % ex)
                logger.exception('Exception! Restarting Windows cron service.' % ex)
                self.start()
コード例 #2
0
ファイル: winservice.py プロジェクト: slvwolf/web2py
 def start(self):
     import newcron
     import global_settings
     self.log('web2py server starting')
     if not self.chdir():
         return
     if len(sys.argv) == 2:
         opt_mod = sys.argv[1]
     else:
         opt_mod = self._exe_args_
     options = __import__(opt_mod, [], [], '')
     global_settings.global_settings.web2py_crontype = 'external'
     if options.scheduler:   # -K                         
         apps = [app.strip() for app in options.scheduler.split(
                 ',') if check_existent_app(options, app.strip())]
     else:
         apps = None
     self.extcron = newcron.extcron(options.folder, apps=apps)
     try:
         self.extcron.start()
     except:
         # self.server.stop()
         self.extcron = None
         raise
コード例 #3
0
ファイル: widget.py プロジェクト: BlackgateResearch/gmr
def start(cron = True):
    """ Start server  """

    # ## get command line arguments

    (options, args) = console()

    print ProgramName
    print ProgramAuthor
    print ProgramVersion

    from sql import drivers
    print 'Database drivers available: %s' % ', '.join(drivers)


    # ## if -L load options from options.config file
    if options.config:
        try:
            options2 = __import__(options.config, [], [], '')
        except Exception:
            try:
                # Jython doesn't like the extra stuff
                options = __import__(options.config)
            except Exception:
                print 'Cannot import config file [%s]' % options.config
                sys.exit(1)
        for key in dir(options2):
            if hasattr(options,key):
                setattr(options,key,getattr(options2,key))

    # ## if -T run doctests (no cron)
    if hasattr(options,'test') and options.test:
        test(options.test, verbose=options.verbose)
        return

    # ## if -S start interactive shell (also no cron)
    if options.shell:
        sys.args = options.args
        run(options.shell, plain=options.plain,
            import_models=options.import_models, startfile=options.run)
        return

    # ## if -C start cron run (extcron) and exit
    # ## if -N or not cron disable cron in this *process*
    # ## if --softcron use softcron
    # ## use hardcron in all ther cases
    if options.extcron:
        print 'Starting extcron...'
        settings.web2py_crontype = 'external'
        extcron = newcron.extcron(os.getcwd())
        extcron.start()
        extcron.join()
        return
    elif cron and not options.nocron and options.softcron:
        print 'Using softcron (but this is not very efficient)'
        settings.web2py_crontype = 'soft'
    elif cron and not options.nocron:
        print 'Starting hardcron...'
        settings.web2py_crontype = 'hard'
        newcron.hardcron(os.getcwd()).start()

    # ## if -W install/start/stop web2py as service
    if options.winservice:
        if os.name == 'nt':
            web2py_windows_service_handler(['', options.winservice],
                    options.config)
        else:
            print 'Error: Windows services not supported on this platform'
            sys.exit(1)
        return

    # ## if no password provided and havetk start Tk interface
    # ## or start interface if we want to put in taskbar (system tray)

    try:
        options.taskbar
    except:
        options.taskbar = False

    if options.taskbar and os.name != 'nt':
        print 'Error: taskbar not supported on this platform'
        sys.exit(1)

    root = None

    if not options.nogui:
        try:
            import tkMessageBox
            import Tkinter
            havetk = True
        except ImportError:
            logger.warn('GUI not available because Tk library is not installed')
            havetk = False

        if options.password == '<ask>' and havetk or options.taskbar and havetk:
            try:
                root = Tkinter.Tk()
            except:
                pass

    if root:
        root.focus_force()
        if not options.quiet:
            presentation(root)
        master = web2pyDialog(root, options)
        signal.signal(signal.SIGTERM, lambda a, b: master.quit())

        try:
            root.mainloop()
        except:
            master.quit()

        sys.exit()

    # ## if no tk and no password, ask for a password

    if not root and options.password == '<ask>':
        options.password = raw_input('choose a password:'******'no password, no admin interface'

    # ## start server

    (ip, port) = (options.ip, int(options.port))

    print 'please visit:'
    print '\thttp://%s:%s' % (ip, port)
    print 'use "kill -SIGTERM %i" to shutdown the web2py server' % os.getpid()

    server = main.HttpServer(ip=ip,
                             port=port,
                             password=options.password,
                             pid_filename=options.pid_filename,
                             log_filename=options.log_filename,
                             profiler_filename=options.profiler_filename,
                             ssl_certificate=options.ssl_certificate,
                             ssl_private_key=options.ssl_private_key,
                             numthreads=options.numthreads,
                             server_name=options.server_name,
                             request_queue_size=options.request_queue_size,
                             timeout=options.timeout,
                             shutdown_timeout=options.shutdown_timeout,
                             path=options.folder,
                             interfaces=options.interfaces)

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
コード例 #4
0
ファイル: widget.py プロジェクト: faridsanusi/web2py
def start(cron=True):
    """ Start server  """

    # ## get command line arguments

    (options, args) = console()

    if not options.nobanner:
        print ProgramName
        print ProgramAuthor
        print ProgramVersion

    from dal import drivers
    if not options.nobanner:
        print 'Database drivers available: %s' % ', '.join(drivers)


    # ## if -L load options from options.config file
    if options.config:
        try:
            options2 = __import__(options.config, {}, {}, '')
        except Exception:
            try:
                # Jython doesn't like the extra stuff
                options2 = __import__(options.config)
            except Exception:
                print 'Cannot import config file [%s]' % options.config
                sys.exit(1)
        for key in dir(options2):
            if hasattr(options,key):
                setattr(options,key,getattr(options2,key))

    if False and not os.path.exists('logging.conf') and \
            os.path.exists('logging.example.conf'):
        import shutil
        sys.stdout.write("Copying logging.conf.example to logging.conf ... ")
        shutil.copyfile('logging.example.conf', 'logging.conf')
        sys.stdout.write("OK\n")

    # ## if -T run doctests (no cron)
    if hasattr(options,'test') and options.test:
        test(options.test, verbose=options.verbose)
        return

    # ## if -S start interactive shell (also no cron)
    if options.shell:
        if not options.args is None:
            sys.argv[:] = options.args
        run(options.shell, plain=options.plain, bpython=options.bpython,
            import_models=options.import_models, startfile=options.run)
        return

    # ## if -C start cron run (extcron) and exit
    # ##    -K specifies optional apps list (overloading scheduler)
    if options.extcron:
        logger.debug('Starting extcron...')
        global_settings.web2py_crontype = 'external'
        if options.scheduler:   # -K
            apps = [app.strip() for app in options.scheduler.split(',') if check_existent_app(options, app.strip())]
        else:
            apps = None
        extcron = newcron.extcron(options.folder, apps=apps)
        extcron.start()
        extcron.join()
        return

    # ## if -K
    if options.scheduler and not options.with_scheduler:
        try:
            start_schedulers(options)
        except KeyboardInterrupt:
            pass
        return


    # ## if -N or not cron disable cron in this *process*
    # ## if --softcron use softcron
    # ## use hardcron in all other cases
    if cron and not options.nocron and options.softcron:
        print 'Using softcron (but this is not very efficient)'
        global_settings.web2py_crontype = 'soft'
    elif cron and not options.nocron:
        logger.debug('Starting hardcron...')
        global_settings.web2py_crontype = 'hard'
        newcron.hardcron(options.folder).start()

    # ## if -W install/start/stop web2py as service
    if options.winservice:
        if os.name == 'nt':
            web2py_windows_service_handler(['', options.winservice],
                    options.config)
        else:
            print 'Error: Windows services not supported on this platform'
            sys.exit(1)
        return

    # ## if no password provided and havetk start Tk interface
    # ## or start interface if we want to put in taskbar (system tray)

    try:
        options.taskbar
    except:
        options.taskbar = False

    if options.taskbar and os.name != 'nt':
        print 'Error: taskbar not supported on this platform'
        sys.exit(1)

    root = None

    if not options.nogui:
        try:
            import Tkinter
            havetk = True
        except ImportError:
            logger.warn('GUI not available because Tk library is not installed')
            havetk = False

        if options.password == '<ask>' and havetk or options.taskbar and havetk:
            try:
                root = Tkinter.Tk()
            except:
                pass

    if root:
        root.focus_force()

        # Mac OS X - make the GUI window rise to the top
        if os.path.exists("/usr/bin/osascript"):
            applescript = """
tell application "System Events"
    set proc to first process whose unix id is %d
    set frontmost of proc to true
end tell
""" % (os.getpid())
            os.system("/usr/bin/osascript -e '%s'" % applescript)

        if not options.quiet:
            presentation(root)
        master = web2pyDialog(root, options)
        signal.signal(signal.SIGTERM, lambda a, b: master.quit())

        try:
            root.mainloop()
        except:
            master.quit()

        sys.exit()

    # ## if no tk and no password, ask for a password

    if not root and options.password == '<ask>':
        options.password = getpass.getpass('choose a password:'******'no password, no admin interface'

    # ##-X (if no tk, the widget takes care of it himself)
    if not root and options.scheduler and options.with_scheduler:
        t = threading.Thread(target=start_schedulers, args=(options,))
        t.start()

    # ## start server

    (ip, port) = (options.ip, int(options.port))

    # Check for non default value for ssl inputs
    if (len(options.ssl_certificate) > 0) or (len(options.ssl_private_key) > 0):
        proto = 'https'
    else:
        proto = 'http'
    url = '%s://%s:%s' % (proto, ip, port)

    if not options.nobanner:
        print 'please visit:'
        print '\t', url
        print 'use "kill -SIGTERM %i" to shutdown the web2py server' % os.getpid()

    server = main.HttpServer(ip=ip,
                             port=port,
                             password=options.password,
                             pid_filename=options.pid_filename,
                             log_filename=options.log_filename,
                             profiler_filename=options.profiler_filename,
                             ssl_certificate=options.ssl_certificate,
                             ssl_private_key=options.ssl_private_key,
                             ssl_ca_certificate=options.ssl_ca_certificate,
                             min_threads=options.minthreads,
                             max_threads=options.maxthreads,
                             server_name=options.server_name,
                             request_queue_size=options.request_queue_size,
                             timeout=options.timeout,
                             socket_timeout=options.socket_timeout,
                             shutdown_timeout=options.shutdown_timeout,
                             path=options.folder,
                             interfaces=options.interfaces)

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
        try:
            t.join()
        except:
            pass
    logging.shutdown()
コード例 #5
0
ファイル: widget.py プロジェクト: CzechErface/web2py
def start(cron=True):
    """ Starts server  """

    # ## get command line arguments

    (options, args) = console()

    if not options.nobanner:
        print ProgramName
        print ProgramAuthor
        print ProgramVersion

    from pydal.drivers import DRIVERS
    if not options.nobanner:
        print 'Database drivers available: %s' % ', '.join(DRIVERS)

    # ## if -L load options from options.config file
    if options.config:
        try:
            options2 = __import__(options.config, {}, {}, '')
        except Exception:
            try:
                # Jython doesn't like the extra stuff
                options2 = __import__(options.config)
            except Exception:
                print 'Cannot import config file [%s]' % options.config
                sys.exit(1)
        for key in dir(options2):
            if hasattr(options, key):
                setattr(options, key, getattr(options2, key))

    logfile0 = os.path.join('examples', 'logging.example.conf')
    logfile1 = os.path.join(options.folder, 'logging.conf')
    if not os.path.exists(logfile1) and os.path.exists(logfile0):
        import shutil
        sys.stdout.write("Copying logging.conf.example to logging.conf ... ")
        shutil.copyfile(logfile0, logfile1)
        sys.stdout.write("OK\n")

    # ## if -T run doctests (no cron)
    if hasattr(options, 'test') and options.test:
        test(options.test, verbose=options.verbose)
        return

    # ## if -S start interactive shell (also no cron)
    if options.shell:
        if options.folder:
            os.chdir(options.folder)
        if not options.args is None:
            sys.argv[:] = options.args
        run(options.shell, plain=options.plain, bpython=options.bpython,
            import_models=options.import_models, startfile=options.run,
            cronjob=options.cronjob)
        return

    # ## if -C start cron run (extcron) and exit
    # ##    -K specifies optional apps list (overloading scheduler)
    if options.extcron:
        logger.debug('Starting extcron...')
        global_settings.web2py_crontype = 'external'
        if options.scheduler:   # -K
            apps = [app.strip() for app in options.scheduler.split(
                ',') if check_existent_app(options, app.strip())]
        else:
            apps = None
        extcron = newcron.extcron(options.folder, apps=apps)
        extcron.start()
        extcron.join()
        return

    # ## if -K
    if options.scheduler and not options.with_scheduler:
        try:
            start_schedulers(options)
        except KeyboardInterrupt:
            pass
        return

    # ## if -H cron is enabled in this *process*
    # ## if --softcron use softcron
    # ## use hardcron in all other cases
    if cron and options.runcron and options.softcron:
        print 'Using softcron (but this is not very efficient)'
        global_settings.web2py_crontype = 'soft'
    elif cron and options.runcron:
        logger.debug('Starting hardcron...')
        global_settings.web2py_crontype = 'hard'
        newcron.hardcron(options.folder).start()

    # ## if no password provided and havetk start Tk interface
    # ## or start interface if we want to put in taskbar (system tray)

    try:
        options.taskbar
    except:
        options.taskbar = False

    if options.taskbar and os.name != 'nt':
        print 'Error: taskbar not supported on this platform'
        sys.exit(1)

    root = None

    if not options.nogui and options.password == '<ask>':
        try:
            import Tkinter
            havetk = True
            try:
                root = Tkinter.Tk()
            except:
                pass
        except (ImportError, OSError):
            logger.warn(
                'GUI not available because Tk library is not installed')
            havetk = False
            options.nogui = True

    if root:
        root.focus_force()

        # Mac OS X - make the GUI window rise to the top
        if os.path.exists("/usr/bin/osascript"):
            applescript = """
tell application "System Events"
    set proc to first process whose unix id is %d
    set frontmost of proc to true
end tell
""" % (os.getpid())
            os.system("/usr/bin/osascript -e '%s'" % applescript)

        master = web2pyDialog(root, options)
        signal.signal(signal.SIGTERM, lambda a, b: master.quit())

        try:
            root.mainloop()
        except:
            master.quit()

        sys.exit()

    # ## if no tk and no password, ask for a password

    if not root and options.password == '<ask>':
        options.password = getpass.getpass('choose a password:'******'no password, no admin interface'

    # ##-X (if no tk, the widget takes care of it himself)
    if not root and options.scheduler and options.with_scheduler:
        t = threading.Thread(target=start_schedulers, args=(options,))
        t.start()

    # ## start server

    # Use first interface IP and port if interfaces specified, since the
    # interfaces option overrides the IP (and related) options.
    if not options.interfaces:
        (ip, port) = (options.ip, int(options.port))
    else:
        first_if = options.interfaces[0]
        (ip, port) = first_if[0], first_if[1]

    # Check for non default value for ssl inputs
    if (len(options.ssl_certificate) > 0) or (len(options.ssl_private_key) > 0):
        proto = 'https'
    else:
        proto = 'http'

    url = get_url(ip, proto=proto, port=port)

    if not options.nobanner:
        message = '\nplease visit:\n\t%s\n' % url
        if sys.platform.startswith('win'):
            message += 'use "taskkill /f /pid %i" to shutdown the web2py server\n\n' % os.getpid()
        else:
            message += 'use "kill -SIGTERM %i" to shutdown the web2py server\n\n' % os.getpid()
        print message

    # enhance linecache.getline (used by debugger) to look at the source file
    # if the line was not found (under py2exe & when file was modified)
    import linecache
    py2exe_getline = linecache.getline

    def getline(filename, lineno, *args, **kwargs):
        line = py2exe_getline(filename, lineno, *args, **kwargs)
        if not line:
            try:
                f = open(filename, "r")
                try:
                    for i, line in enumerate(f):
                        if lineno == i + 1:
                            break
                    else:
                        line = None
                finally:
                    f.close()
            except (IOError, OSError):
                line = None
        return line
    linecache.getline = getline

    server = main.HttpServer(ip=ip,
                             port=port,
                             password=options.password,
                             pid_filename=options.pid_filename,
                             log_filename=options.log_filename,
                             profiler_dir=options.profiler_dir,
                             ssl_certificate=options.ssl_certificate,
                             ssl_private_key=options.ssl_private_key,
                             ssl_ca_certificate=options.ssl_ca_certificate,
                             min_threads=options.minthreads,
                             max_threads=options.maxthreads,
                             server_name=options.server_name,
                             request_queue_size=options.request_queue_size,
                             timeout=options.timeout,
                             socket_timeout=options.socket_timeout,
                             shutdown_timeout=options.shutdown_timeout,
                             path=options.folder,
                             interfaces=options.interfaces)

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
        try:
            t.join()
        except:
            pass
    logging.shutdown()
コード例 #6
0
def start(cron=True):
    """ Start server  """

    # ## get command line arguments

    (options, args) = console()

    if not options.nobanner:
        print ProgramName
        print ProgramAuthor
        print ProgramVersion

    from dal import drivers

    if not options.nobanner:
        print "Database drivers available: %s" % ", ".join(drivers)

    # ## if -L load options from options.config file
    if options.config:
        try:
            options2 = __import__(options.config, {}, {}, "")
        except Exception:
            try:
                # Jython doesn't like the extra stuff
                options2 = __import__(options.config)
            except Exception:
                print "Cannot import config file [%s]" % options.config
                sys.exit(1)
        for key in dir(options2):
            if hasattr(options, key):
                setattr(options, key, getattr(options2, key))

    # ## if -T run doctests (no cron)
    if hasattr(options, "test") and options.test:
        test(options.test, verbose=options.verbose)
        return

    # ## if -K
    if options.scheduler:
        try:
            start_schedulers(options)
        except KeyboardInterrupt:
            pass
        return

    # ## if -S start interactive shell (also no cron)
    if options.shell:
        if not options.args is None:
            sys.argv[:] = options.args
        run(
            options.shell,
            plain=options.plain,
            bpython=options.bpython,
            import_models=options.import_models,
            startfile=options.run,
        )
        return

    # ## if -C start cron run (extcron) and exit
    # ## if -N or not cron disable cron in this *process*
    # ## if --softcron use softcron
    # ## use hardcron in all other cases
    if options.extcron:
        print "Starting extcron..."
        global_settings.web2py_crontype = "external"
        extcron = newcron.extcron(options.folder)
        extcron.start()
        extcron.join()
        return
    elif cron and not options.nocron and options.softcron:
        print "Using softcron (but this is not very efficient)"
        global_settings.web2py_crontype = "soft"
    elif cron and not options.nocron:
        print "Starting hardcron..."
        global_settings.web2py_crontype = "hard"
        newcron.hardcron(options.folder).start()

    # ## if -W install/start/stop web2py as service
    if options.winservice:
        if os.name == "nt":
            web2py_windows_service_handler(["", options.winservice], options.config)
        else:
            print "Error: Windows services not supported on this platform"
            sys.exit(1)
        return

    # ## if no password provided and havetk start Tk interface
    # ## or start interface if we want to put in taskbar (system tray)

    try:
        options.taskbar
    except:
        options.taskbar = False

    if options.taskbar and os.name != "nt":
        print "Error: taskbar not supported on this platform"
        sys.exit(1)

    root = None

    if not options.nogui:
        try:
            import Tkinter

            havetk = True
        except ImportError:
            logger.warn("GUI not available because Tk library is not installed")
            havetk = False

        if options.password == "<ask>" and havetk or options.taskbar and havetk:
            try:
                root = Tkinter.Tk()
            except:
                pass

    if root:
        root.focus_force()
        if not options.quiet:
            presentation(root)
        master = web2pyDialog(root, options)
        signal.signal(signal.SIGTERM, lambda a, b: master.quit())

        try:
            root.mainloop()
        except:
            master.quit()

        sys.exit()

    # ## if no tk and no password, ask for a password

    if not root and options.password == "<ask>":
        options.password = raw_input("choose a password:"******"no password, no admin interface"

    # ## start server

    (ip, port) = (options.ip, int(options.port))

    if not options.nobanner:
        print "please visit:"
        print "\thttp://%s:%s" % (ip, port)
        print 'use "kill -SIGTERM %i" to shutdown the web2py server' % os.getpid()

    server = main.HttpServer(
        ip=ip,
        port=port,
        password=options.password,
        pid_filename=options.pid_filename,
        log_filename=options.log_filename,
        profiler_filename=options.profiler_filename,
        ssl_certificate=options.ssl_certificate,
        ssl_private_key=options.ssl_private_key,
        ssl_ca_certificate=options.ssl_ca_certificate,
        min_threads=options.minthreads,
        max_threads=options.maxthreads,
        server_name=options.server_name,
        request_queue_size=options.request_queue_size,
        timeout=options.timeout,
        socket_timeout=options.socket_timeout,
        shutdown_timeout=options.shutdown_timeout,
        path=options.folder,
        interfaces=options.interfaces,
    )

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
    logging.shutdown()
コード例 #7
0
ファイル: widget.py プロジェクト: BinweiRu/web2py
def start(cron=True):
    """ Start server  """

    # ## get command line arguments

    (options, args) = console()

    if not options.nobanner:
        print ProgramName
        print ProgramAuthor
        print ProgramVersion

    from dal import DRIVERS

    if not options.nobanner:
        print "Database drivers available: %s" % ", ".join(DRIVERS)

    # ## if -L load options from options.config file
    if options.config:
        try:
            options2 = __import__(options.config, {}, {}, "")
        except Exception:
            try:
                # Jython doesn't like the extra stuff
                options2 = __import__(options.config)
            except Exception:
                print "Cannot import config file [%s]" % options.config
                sys.exit(1)
        for key in dir(options2):
            if hasattr(options, key):
                setattr(options, key, getattr(options2, key))

    if False and not os.path.exists("logging.conf") and os.path.exists("logging.example.conf"):
        import shutil

        sys.stdout.write("Copying logging.conf.example to logging.conf ... ")
        shutil.copyfile("logging.example.conf", "logging.conf")
        sys.stdout.write("OK\n")

    # ## if -T run doctests (no cron)
    if hasattr(options, "test") and options.test:
        test(options.test, verbose=options.verbose)
        return

    # ## if -S start interactive shell (also no cron)
    if options.shell:
        if not options.args is None:
            sys.argv[:] = options.args
        run(
            options.shell,
            plain=options.plain,
            bpython=options.bpython,
            import_models=options.import_models,
            startfile=options.run,
            cronjob=options.cronjob,
        )
        return

    # ## if -C start cron run (extcron) and exit
    # ##    -K specifies optional apps list (overloading scheduler)
    if options.extcron:
        logger.debug("Starting extcron...")
        global_settings.web2py_crontype = "external"
        if options.scheduler:  # -K
            apps = [app.strip() for app in options.scheduler.split(",") if check_existent_app(options, app.strip())]
        else:
            apps = None
        extcron = newcron.extcron(options.folder, apps=apps)
        extcron.start()
        extcron.join()
        return

    # ## if -K
    if options.scheduler and not options.with_scheduler:
        try:
            start_schedulers(options)
        except KeyboardInterrupt:
            pass
        return

    # ## if -W install/start/stop web2py as service
    if options.winservice:
        if os.name == "nt":
            try:
                from winservice import register_service_handler, Web2pyService

                register_service_handler(argv=["", options.winservice], opt_file=options.config, cls=Web2pyService)
            except ImportError:
                print "Error: Missing python module winservice"
                sys.exit(1)
        else:
            print "Error: Windows services not supported on this platform"
            sys.exit(1)
        return

    # ## if -H cron is enabled in this *process*
    # ## if --softcron use softcron
    # ## use hardcron in all other cases
    if cron and options.runcron and options.softcron:
        print "Using softcron (but this is not very efficient)"
        global_settings.web2py_crontype = "soft"
    elif cron and options.runcron:
        logger.debug("Starting hardcron...")
        global_settings.web2py_crontype = "hard"
        newcron.hardcron(options.folder).start()

    # ## if no password provided and havetk start Tk interface
    # ## or start interface if we want to put in taskbar (system tray)

    try:
        options.taskbar
    except:
        options.taskbar = False

    if options.taskbar and os.name != "nt":
        print "Error: taskbar not supported on this platform"
        sys.exit(1)

    root = None

    if not options.nogui:
        try:
            import Tkinter

            havetk = True
        except ImportError:
            logger.warn("GUI not available because Tk library is not installed")
            havetk = False
            options.nogui = True

        if options.password == "<ask>" and havetk or options.taskbar and havetk:
            try:
                root = Tkinter.Tk()
            except:
                pass

    if root:
        root.focus_force()

        # Mac OS X - make the GUI window rise to the top
        if os.path.exists("/usr/bin/osascript"):
            applescript = """
tell application "System Events"
    set proc to first process whose unix id is %d
    set frontmost of proc to true
end tell
""" % (
                os.getpid()
            )
            os.system("/usr/bin/osascript -e '%s'" % applescript)

        if not options.quiet:
            presentation(root)
        master = web2pyDialog(root, options)
        signal.signal(signal.SIGTERM, lambda a, b: master.quit())

        try:
            root.mainloop()
        except:
            master.quit()

        sys.exit()

    # ## if no tk and no password, ask for a password

    if not root and options.password == "<ask>":
        options.password = getpass.getpass("choose a password:"******"no password, no admin interface"

    # ##-X (if no tk, the widget takes care of it himself)
    if not root and options.scheduler and options.with_scheduler:
        t = threading.Thread(target=start_schedulers, args=(options,))
        t.start()

    # ## start server

    # Use first interface IP and port if interfaces specified, since the
    # interfaces option overrides the IP (and related) options.
    if not options.interfaces:
        (ip, port) = (options.ip, int(options.port))
    else:
        first_if = options.interfaces[0]
        (ip, port) = first_if[0], first_if[1]

    # Check for non default value for ssl inputs
    if (len(options.ssl_certificate) > 0) or (len(options.ssl_private_key) > 0):
        proto = "https"
    else:
        proto = "http"

    url = get_url(ip, proto=proto, port=port)

    if not options.nobanner:
        print "please visit:"
        print "\t", url
        print 'use "kill -SIGTERM %i" to shutdown the web2py server' % os.getpid()

    server = main.HttpServer(
        ip=ip,
        port=port,
        password=options.password,
        pid_filename=options.pid_filename,
        log_filename=options.log_filename,
        profiler_dir=options.profiler_dir,
        ssl_certificate=options.ssl_certificate,
        ssl_private_key=options.ssl_private_key,
        ssl_ca_certificate=options.ssl_ca_certificate,
        min_threads=options.minthreads,
        max_threads=options.maxthreads,
        server_name=options.server_name,
        request_queue_size=options.request_queue_size,
        timeout=options.timeout,
        socket_timeout=options.socket_timeout,
        shutdown_timeout=options.shutdown_timeout,
        path=options.folder,
        interfaces=options.interfaces,
    )

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
        try:
            t.join()
        except:
            pass
    logging.shutdown()
コード例 #8
0
def start(cron=True):
    """ Starts server  """

    # ## get command line arguments

    (options, args) = console()

    if not options.nobanner:
        print ProgramName
        print ProgramAuthor
        print ProgramVersion

    from pydal.drivers import DRIVERS
    if not options.nobanner:
        print 'Database drivers available: %s' % ', '.join(DRIVERS)

    # ## if -L load options from options.config file
    if options.config:
        try:
            options2 = __import__(options.config, {}, {}, '')
        except Exception:
            try:
                # Jython doesn't like the extra stuff
                options2 = __import__(options.config)
            except Exception:
                print 'Cannot import config file [%s]' % options.config
                sys.exit(1)
        for key in dir(options2):
            if hasattr(options, key):
                setattr(options, key, getattr(options2, key))

    logfile0 = os.path.join('extras', 'examples', 'logging.example.conf')
    if not os.path.exists('logging.conf') and os.path.exists(logfile0):
        import shutil
        sys.stdout.write("Copying logging.conf.example to logging.conf ... ")
        shutil.copyfile('logging.example.conf', logfile0)
        sys.stdout.write("OK\n")

    # ## if -T run doctests (no cron)
    if hasattr(options, 'test') and options.test:
        test(options.test, verbose=options.verbose)
        return

    # ## if -S start interactive shell (also no cron)
    if options.shell:
        if options.folder:
            os.chdir(options.folder)
        if not options.args is None:
            sys.argv[:] = options.args
        run(options.shell,
            plain=options.plain,
            bpython=options.bpython,
            import_models=options.import_models,
            startfile=options.run,
            cronjob=options.cronjob)
        return

    # ## if -C start cron run (extcron) and exit
    # ##    -K specifies optional apps list (overloading scheduler)
    if options.extcron:
        logger.debug('Starting extcron...')
        global_settings.web2py_crontype = 'external'
        if options.scheduler:  # -K
            apps = [
                app.strip() for app in options.scheduler.split(',')
                if check_existent_app(options, app.strip())
            ]
        else:
            apps = None
        extcron = newcron.extcron(options.folder, apps=apps)
        extcron.start()
        extcron.join()
        return

    # ## if -K
    if options.scheduler and not options.with_scheduler:
        try:
            start_schedulers(options)
        except KeyboardInterrupt:
            pass
        return

    # ## if -H cron is enabled in this *process*
    # ## if --softcron use softcron
    # ## use hardcron in all other cases
    if cron and options.runcron and options.softcron:
        print 'Using softcron (but this is not very efficient)'
        global_settings.web2py_crontype = 'soft'
    elif cron and options.runcron:
        logger.debug('Starting hardcron...')
        global_settings.web2py_crontype = 'hard'
        newcron.hardcron(options.folder).start()

    # ## if no password provided and havetk start Tk interface
    # ## or start interface if we want to put in taskbar (system tray)

    try:
        options.taskbar
    except:
        options.taskbar = False

    if options.taskbar and os.name != 'nt':
        print 'Error: taskbar not supported on this platform'
        sys.exit(1)

    root = None

    if not options.nogui and options.password == '<ask>':
        try:
            import Tkinter
            havetk = True
            try:
                root = Tkinter.Tk()
            except:
                pass
        except (ImportError, OSError):
            logger.warn(
                'GUI not available because Tk library is not installed')
            havetk = False
            options.nogui = True

    if root:
        root.focus_force()

        # Mac OS X - make the GUI window rise to the top
        if os.path.exists("/usr/bin/osascript"):
            applescript = """
tell application "System Events"
    set proc to first process whose unix id is %d
    set frontmost of proc to true
end tell
""" % (os.getpid())
            os.system("/usr/bin/osascript -e '%s'" % applescript)

        master = web2pyDialog(root, options)
        signal.signal(signal.SIGTERM, lambda a, b: master.quit())

        try:
            root.mainloop()
        except:
            master.quit()

        sys.exit()

    # ## if no tk and no password, ask for a password

    if not root and options.password == '<ask>':
        options.password = getpass.getpass('choose a password:'******'no password, no admin interface'

    # ##-X (if no tk, the widget takes care of it himself)
    if not root and options.scheduler and options.with_scheduler:
        t = threading.Thread(target=start_schedulers, args=(options, ))
        t.start()

    # ## start server

    # Use first interface IP and port if interfaces specified, since the
    # interfaces option overrides the IP (and related) options.
    if not options.interfaces:
        (ip, port) = (options.ip, int(options.port))
    else:
        first_if = options.interfaces[0]
        (ip, port) = first_if[0], first_if[1]

    # Check for non default value for ssl inputs
    if (len(options.ssl_certificate) > 0) or (len(options.ssl_private_key) >
                                              0):
        proto = 'https'
    else:
        proto = 'http'

    url = get_url(ip, proto=proto, port=port)

    if not options.nobanner:
        message = '\nplease visit:\n\t%s\n' % url
        if sys.platform.startswith('win'):
            message += 'use "taskkill /f /pid %i" to shutdown the web2py server\n\n' % os.getpid(
            )
        else:
            message += 'use "kill -SIGTERM %i" to shutdown the web2py server\n\n' % os.getpid(
            )
        print message

    # enhance linecache.getline (used by debugger) to look at the source file
    # if the line was not found (under py2exe & when file was modified)
    import linecache
    py2exe_getline = linecache.getline

    def getline(filename, lineno, *args, **kwargs):
        line = py2exe_getline(filename, lineno, *args, **kwargs)
        if not line:
            try:
                f = open(filename, "r")
                try:
                    for i, line in enumerate(f):
                        if lineno == i + 1:
                            break
                    else:
                        line = None
                finally:
                    f.close()
            except (IOError, OSError):
                line = None
        return line

    linecache.getline = getline

    server = main.HttpServer(ip=ip,
                             port=port,
                             password=options.password,
                             pid_filename=options.pid_filename,
                             log_filename=options.log_filename,
                             profiler_dir=options.profiler_dir,
                             ssl_certificate=options.ssl_certificate,
                             ssl_private_key=options.ssl_private_key,
                             ssl_ca_certificate=options.ssl_ca_certificate,
                             min_threads=options.minthreads,
                             max_threads=options.maxthreads,
                             server_name=options.server_name,
                             request_queue_size=options.request_queue_size,
                             timeout=options.timeout,
                             socket_timeout=options.socket_timeout,
                             shutdown_timeout=options.shutdown_timeout,
                             path=options.folder,
                             interfaces=options.interfaces)

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
        try:
            t.join()
        except:
            pass
    logging.shutdown()
コード例 #9
0
def start(cron=True):
    """ Start server  """

    # ## get command line arguments

    (options, args) = console()

    if not options.nobanner:
        print ProgramName
        print ProgramAuthor
        print ProgramVersion

    from dal import drivers
    if not options.nobanner:
        print 'Database drivers available: %s' % ', '.join(drivers)

    # ## if -L load options from options.config file
    if options.config:
        try:
            options2 = __import__(options.config, {}, {}, '')
        except Exception:
            try:
                # Jython doesn't like the extra stuff
                options2 = __import__(options.config)
            except Exception:
                print 'Cannot import config file [%s]' % options.config
                sys.exit(1)
        for key in dir(options2):
            if hasattr(options, key):
                setattr(options, key, getattr(options2, key))

    # ## if -T run doctests (no cron)
    if hasattr(options, 'test') and options.test:
        test(options.test, verbose=options.verbose)
        return

    # ## if -S start interactive shell (also no cron)
    if options.shell:
        if options.args != None:
            sys.argv[:] = options.args
        run(options.shell,
            plain=options.plain,
            bpython=options.bpython,
            import_models=options.import_models,
            startfile=options.run)
        return

    # ## if -C start cron run (extcron) and exit
    # ## if -N or not cron disable cron in this *process*
    # ## if --softcron use softcron
    # ## use hardcron in all other cases
    if options.extcron:
        print 'Starting extcron...'
        global_settings.web2py_crontype = 'external'
        extcron = newcron.extcron(options.folder)
        extcron.start()
        extcron.join()
        return
    elif cron and not options.nocron and options.softcron:
        print 'Using softcron (but this is not very efficient)'
        global_settings.web2py_crontype = 'soft'
    elif cron and not options.nocron:
        print 'Starting hardcron...'
        global_settings.web2py_crontype = 'hard'
        newcron.hardcron(options.folder).start()

    # ## if -W install/start/stop web2py as service
    if options.winservice:
        if os.name == 'nt':
            web2py_windows_service_handler(['', options.winservice],
                                           options.config)
        else:
            print 'Error: Windows services not supported on this platform'
            sys.exit(1)
        return

    # ## if no password provided and havetk start Tk interface
    # ## or start interface if we want to put in taskbar (system tray)

    try:
        options.taskbar
    except:
        options.taskbar = False

    if options.taskbar and os.name != 'nt':
        print 'Error: taskbar not supported on this platform'
        sys.exit(1)

    root = None

    if not options.nogui:
        try:
            import Tkinter
            havetk = True
        except ImportError:
            logger.warn(
                'GUI not available because Tk library is not installed')
            havetk = False

        if options.password == '<ask>' and havetk or options.taskbar and havetk:
            try:
                root = Tkinter.Tk()
            except:
                pass

    if root:
        root.focus_force()
        if not options.quiet:
            presentation(root)
        master = web2pyDialog(root, options)
        signal.signal(signal.SIGTERM, lambda a, b: master.quit())

        try:
            root.mainloop()
        except:
            master.quit()

        sys.exit()

    # ## if no tk and no password, ask for a password

    if not root and options.password == '<ask>':
        options.password = raw_input('choose a password:'******'no password, no admin interface'

    # ## start server

    (ip, port) = (options.ip, int(options.port))

    if not options.nobanner:
        print 'please visit:'
        print '\thttp://%s:%s' % (ip, port)
        print 'use "kill -SIGTERM %i" to shutdown the web2py server' % os.getpid(
        )

    server = main.HttpServer(ip=ip,
                             port=port,
                             password=options.password,
                             pid_filename=options.pid_filename,
                             log_filename=options.log_filename,
                             profiler_filename=options.profiler_filename,
                             ssl_certificate=options.ssl_certificate,
                             ssl_private_key=options.ssl_private_key,
                             min_threads=options.minthreads,
                             max_threads=options.maxthreads,
                             server_name=options.server_name,
                             request_queue_size=options.request_queue_size,
                             timeout=options.timeout,
                             shutdown_timeout=options.shutdown_timeout,
                             path=options.folder,
                             interfaces=options.interfaces)

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
    logging.shutdown()
コード例 #10
0
def start(cron=True):
    """ Start server  """

    # ## get command line arguments

    (options, args) = console()

    if not options.nobanner:
        print ProgramName
        print ProgramAuthor
        print ProgramVersion

    from dal import DRIVERS
    if not options.nobanner:
        print 'Database drivers available: %s' % ', '.join(DRIVERS)

    # ## if -L load options from options.config file
    if options.config:
        try:
            options2 = __import__(options.config, {}, {}, '')
        except Exception:
            try:
                # Jython doesn't like the extra stuff
                options2 = __import__(options.config)
            except Exception:
                print 'Cannot import config file [%s]' % options.config
                sys.exit(1)
        for key in dir(options2):
            if hasattr(options, key):
                setattr(options, key, getattr(options2, key))

    if False and not os.path.exists('logging.conf') and \
            os.path.exists('logging.example.conf'):
        import shutil
        sys.stdout.write("Copying logging.conf.example to logging.conf ... ")
        shutil.copyfile('logging.example.conf', 'logging.conf')
        sys.stdout.write("OK\n")

    # ## if -T run doctests (no cron)
    if hasattr(options, 'test') and options.test:
        test(options.test, verbose=options.verbose)
        return

    # ## if -S start interactive shell (also no cron)
    if options.shell:
        if not options.args is None:
            sys.argv[:] = options.args
        run(options.shell,
            plain=options.plain,
            bpython=options.bpython,
            import_models=options.import_models,
            startfile=options.run)
        return

    # ## if -C start cron run (extcron) and exit
    # ##    -K specifies optional apps list (overloading scheduler)
    if options.extcron:
        logger.debug('Starting extcron...')
        global_settings.web2py_crontype = 'external'
        if options.scheduler:  # -K
            apps = [
                app.strip() for app in options.scheduler.split(',')
                if check_existent_app(options, app.strip())
            ]
        else:
            apps = None
        extcron = newcron.extcron(options.folder, apps=apps)
        extcron.start()
        extcron.join()
        return

    # ## if -K
    if options.scheduler and not options.with_scheduler:
        try:
            start_schedulers(options)
        except KeyboardInterrupt:
            pass
        return

    # ## if -H cron is enabled in this *process*
    # ## if --softcron use softcron
    # ## use hardcron in all other cases
    if cron and options.runcron and options.softcron:
        print 'Using softcron (but this is not very efficient)'
        global_settings.web2py_crontype = 'soft'
    elif cron and options.runcron:
        logger.debug('Starting hardcron...')
        global_settings.web2py_crontype = 'hard'
        newcron.hardcron(options.folder).start()

    # ## if -W install/start/stop web2py as service
    if options.winservice:
        if os.name == 'nt':
            if have_winservice:
                web2py_windows_service_handler(['', options.winservice],
                                               options.config)
            else:
                print 'Error: Missing python module winservice'
                sys.exit(1)
        else:
            print 'Error: Windows services not supported on this platform'
            sys.exit(1)
        return

    # ## if no password provided and havetk start Tk interface
    # ## or start interface if we want to put in taskbar (system tray)

    try:
        options.taskbar
    except:
        options.taskbar = False

    if options.taskbar and os.name != 'nt':
        print 'Error: taskbar not supported on this platform'
        sys.exit(1)

    root = None

    if not options.nogui:
        try:
            import Tkinter
            havetk = True
        except ImportError:
            logger.warn(
                'GUI not available because Tk library is not installed')
            havetk = False

        if options.password == '<ask>' and havetk or options.taskbar and havetk:
            try:
                root = Tkinter.Tk()
            except:
                pass

    if root:
        root.focus_force()

        # Mac OS X - make the GUI window rise to the top
        if os.path.exists("/usr/bin/osascript"):
            applescript = """
tell application "System Events"
    set proc to first process whose unix id is %d
    set frontmost of proc to true
end tell
""" % (os.getpid())
            os.system("/usr/bin/osascript -e '%s'" % applescript)

        if not options.quiet:
            presentation(root)
        master = web2pyDialog(root, options)
        signal.signal(signal.SIGTERM, lambda a, b: master.quit())

        try:
            root.mainloop()
        except:
            master.quit()

        sys.exit()

    # ## if no tk and no password, ask for a password

    if not root and options.password == '<ask>':
        options.password = getpass.getpass('choose a password:'******'no password, no admin interface'

    # ##-X (if no tk, the widget takes care of it himself)
    if not root and options.scheduler and options.with_scheduler:
        t = threading.Thread(target=start_schedulers, args=(options, ))
        t.start()

    # ## start server

    (ip, port) = (options.ip, int(options.port))

    # Check for non default value for ssl inputs
    if (len(options.ssl_certificate) > 0) or (len(options.ssl_private_key) >
                                              0):
        proto = 'https'
    else:
        proto = 'http'
    url = '%s://%s:%s' % (proto, ip, port)

    if not options.nobanner:
        print 'please visit:'
        print '\t', url
        print 'use "kill -SIGTERM %i" to shutdown the web2py server' % os.getpid(
        )

    server = main.HttpServer(ip=ip,
                             port=port,
                             password=options.password,
                             pid_filename=options.pid_filename,
                             log_filename=options.log_filename,
                             profiler_filename=options.profiler_filename,
                             ssl_certificate=options.ssl_certificate,
                             ssl_private_key=options.ssl_private_key,
                             ssl_ca_certificate=options.ssl_ca_certificate,
                             min_threads=options.minthreads,
                             max_threads=options.maxthreads,
                             server_name=options.server_name,
                             request_queue_size=options.request_queue_size,
                             timeout=options.timeout,
                             socket_timeout=options.socket_timeout,
                             shutdown_timeout=options.shutdown_timeout,
                             path=options.folder,
                             interfaces=options.interfaces)

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
        try:
            t.join()
        except:
            pass
    logging.shutdown()