Exemple #1
0
    def run_command(self, kw):
        """Run a twistd webserver."""
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.

        self.prepare_kwds(kw)
        conf = os.path.join(kw["directory"], "twistedconf.tac")
        if platformType != "win32":
            from twisted.scripts._twistd_unix import checkPID

            try:
                checkPID(kw["pidfile"])
            except SystemExit as e:
                pid = int(open(kw["pidfile"]).read())

                if str(e).startswith("Another twistd server is running,"):
                    print "Another Sage Notebook server is running, PID %d." % pid

                    old_interface, old_port, old_secure = self.get_old_settings(conf)
                    if (kw["automatic_login"] or kw["upload"]) and old_port:
                        old_interface = old_interface or "localhost"
                        if kw["upload"]:
                            import urllib

                            startpath = "/upload_worksheet?url=file://%s" % (urllib.quote(kw["upload"]))
                        else:
                            startpath = "/"

                        print "Opening web browser at http%s://%s:%s%s ..." % (
                            "s" if old_secure else "",
                            old_interface,
                            old_port,
                            startpath,
                        )

                        from sagenb.misc.misc import open_page as browse_to

                        browse_to(old_interface, old_port, old_secure, startpath)
                        return None
                    print "\nPlease either stop the old server or run the new server in a different directory."
                    return None

        ## Create the config file
        if kw["secure"]:
            kw["strport"] = (
                "ssl:%(port)s:interface=%(interface)s:privateKey=%(private_pem)s:certKey=%(public_pem)s" % kw
            )
        else:
            kw["strport"] = "tcp:%(port)s:interface=%(interface)s" % kw

        with open(conf, "w") as config:
            config.write((self.config_stub + self.TWISTD_NOTEBOOK_CONFIG) % kw)

        if kw["profile"]:
            profilecmd = "--profile=%s --profiler=cprofile --savestats" % self.profile_file(kw["profile"])
        else:
            profilecmd = ""
        cmd = 'twistd %s --pidfile="%s" -ny "%s"' % (profilecmd, kw["pidfile"], conf)
        return cmd
Exemple #2
0
    def run_command(self, kw):
        """Run a twistd webserver."""
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.

        self.prepare_kwds(kw)
        conf = os.path.join(kw['directory'], 'twistedconf.tac')
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(kw['pidfile'])
            except SystemExit as e:
                pid = int(open(kw['pidfile']).read())

                if str(e).startswith('Another twistd server is running,'):
                    print('Another Sage Notebook server is running, PID %d.' %
                          pid)

                    old_interface, old_port, old_secure = self.get_old_settings(
                        conf)
                    if (kw['automatic_login'] or kw['upload']) and old_port:
                        old_interface = old_interface or 'localhost'
                        if kw['upload']:
                            import urllib
                            startpath = '/upload_worksheet?url=file://%s' % (
                                urllib.quote(kw['upload']))
                        else:
                            startpath = '/'

                        print('Opening web browser at http%s://%s:%s%s ...' %
                              ('s' if old_secure else '', old_interface,
                               old_port, startpath))

                        from sagenb.misc.misc import open_page as browse_to
                        browse_to(old_interface, old_port, old_secure,
                                  startpath)
                        return None
                    print(
                        '\nPlease either stop the old server or run the new server in a different directory.'
                    )
                    return None

        ## Create the config file
        if kw['secure']:
            kw['strport'] = 'ssl:%(port)s:interface=%(interface)s:privateKey=%(private_pem)s:certKey=%(public_pem)s' % kw
        else:
            kw['strport'] = 'tcp:%(port)s:interface=%(interface)s' % kw

        with open(conf, 'w') as config:
            config.write((self.config_stub + self.TWISTD_NOTEBOOK_CONFIG) % kw)

        if kw['profile']:
            profilecmd = '--profile=%s --profiler=cprofile --savestats' % self.profile_file(
                kw['profile'])
        else:
            profilecmd = ''
        cmd = 'twistd %s --pidfile="%s" -ny "%s"' % (profilecmd, kw['pidfile'],
                                                     conf)
        return cmd
Exemple #3
0
    def run_command(self, kw):
        """Run a twistd webserver."""
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.

        self.prepare_kwds(kw)
        conf = os.path.join(kw['directory'], 'twistedconf.tac')
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(kw['pidfile'])
            except SystemExit as e:
                pid = int(open(kw['pidfile']).read())

                if str(e).startswith('Another twistd server is running,'):
                    print 'Another Sage Notebook server is running, PID %d.' % pid

                    old_interface, old_port, old_secure = self.get_old_settings(conf)
                    if (kw['automatic_login'] or kw['upload']) and old_port:
                        old_interface = old_interface or 'localhost'
                        if kw['upload']:
                            import urllib
                            startpath = '/upload_worksheet?url=file://%s' % (urllib.quote(kw['upload']))
                        else:
                            startpath = '/'

                        print 'Opening web browser at http%s://%s:%s%s ...' % (
                            's' if old_secure else '', old_interface, old_port, startpath)

                        from sagenb.misc.misc import open_page as browse_to
                        browse_to(old_interface, old_port, old_secure, startpath)
                        return None
                    print '\nPlease either stop the old server or run the new server in a different directory.'
                    return None

        ## Create the config file
        if kw['secure']:
            kw['strport'] = 'ssl:%(port)s:interface=%(interface)s:privateKey=%(private_pem)s:certKey=%(public_pem)s'%kw
        else:
            kw['strport'] = 'tcp:%(port)s:interface=%(interface)s'%kw


        with open(conf, 'w') as config:
            config.write((self.config_stub+self.TWISTD_NOTEBOOK_CONFIG)%kw)

        if kw['profile']:
            profilecmd = '--profile=%s --profiler=cprofile --savestats'%self.profile_file(kw['profile'])
        else:
            profilecmd=''
        cmd = 'twistd %s --pidfile="%s" -ny "%s"' % (profilecmd, kw['pidfile'], conf)
        return cmd
Exemple #4
0
    def run(port, subnets):
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.
        pidfile = os.path.join(directory, 'twistd.pid')
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(pidfile)
            except SystemExit as e:
                pid = int(open(pidfile).read())

                if str(e).startswith('Another twistd server is running,'):
                    print 'Another Sage Notebook server is running, PID %d.' % pid
                    old_interface, old_port, old_secure = get_old_settings(conf)
                    if open_viewer and old_port:
                        old_interface = old_interface or 'localhost'

                        print 'Opening web browser at http%s://%s:%s/ ...' % (
                            's' if old_secure else '', old_interface, old_port)

                        from sagenb.misc.misc import open_page as browse_to
                        browse_to(old_interface, old_port, old_secure, '/')
                        return
                    print '\nPlease either stop the old server or run the new server in a different directory.'
                    return

        ## Create the config file
        if secure:
            if (not os.path.exists(private_pem) or
                not os.path.exists(public_pem)):
                print "In order to use an SECURE encrypted notebook, you must first run notebook.setup()."
                print "Now running notebook.setup()"
                notebook_setup()
            if (not os.path.exists(private_pem) or
                not os.path.exists(public_pem)):
                print "Failed to setup notebook.  Please try notebook.setup() again manually."
            strport = '%s:%s:interface=%s:privateKey=%s:certKey=%s' % (
                protocol, port, interface, private_pem, public_pem)
        else:
            strport = 'tcp:%s:interface=%s' % (port, interface)

        notebook_opts = '"%s",interface="%s",port=%s,secure=%s' % (
            os.path.abspath(directory), interface, port, secure)

        if open_viewer:
            if require_login:
                start_path = "'/?startup_token=%s' % startup_token"
            else:
                start_path = "'/'"
            if interface:
                hostname = interface
            else:
                hostname = 'localhost'
            open_page = "from sagenb.misc.misc import open_page; open_page('%s', %s, %s, %s)" % (hostname, port, secure, start_path)
        else:
            open_page = ''

        config = open(conf, 'w')

        if subnets is None:
            factory = "factory = channel.HTTPFactory(site)"
        else:
            if not isinstance(subnets, (list, tuple)):
                subnets = [subnets]
            factory = """
# See http://stackoverflow.com/questions/1273297/python-twisted-restricting-access-by-ip-address
from sagenb.misc.ipaddr import IPNetwork
subnets = eval(r"%s")
if not any(s.startswith('127') for s in subnets):
    subnets.insert(0, '127.0.0.0/8')
subnets = [IPNetwork(x) for x in subnets]
class RestrictedIPFactory(channel.HTTPFactory):
    def buildProtocol(self, addr):
        a = str(addr.host)
        for X in subnets:
            if a in X:
                return channel.HTTPFactory.buildProtocol(self, addr)
        print 'Ignoring all requests from IP address '+str(addr.host)

factory = RestrictedIPFactory(site)
""" % tuple([subnets])

        config.write("""
####################################################################
# WARNING -- Do not edit this file!   It is autogenerated each time
# the notebook(...) command is executed.
####################################################################
from twisted.internet import reactor

# Now set things up and start the notebook
import sagenb.notebook.notebook
sagenb.notebook.notebook.JSMATH=True
import sagenb.notebook.notebook as notebook
import sagenb.notebook.twist as twist
twist.notebook = notebook.load_notebook(%s)
twist.SAGETEX_PATH = %r
twist.OPEN_MODE = %s
twist.SID_COOKIE = str(hash(%r))
twist.DIR = %r
twist.reactor = reactor
twist.init_updates()
import sagenb.notebook.worksheet as worksheet

import signal, sys, random
def save_notebook():
    from twisted.internet.error import ReactorNotRunning
    print "Quitting all running worksheets..."
    twist.notebook.quit()
    print "Saving notebook..."
    twist.notebook.save()
    print "Notebook cleanly saved."

def my_sigint(x, n):
    try:
        reactor.stop()
    except ReactorNotRunning:
        pass
    signal.signal(signal.SIGINT, signal.SIG_DFL)


signal.signal(signal.SIGINT, my_sigint)

## Disable client-side certificate request for gnutls
try:
    import gnutls.connection
    gnutls.connection.CERT_REQUEST = 0
except (OSError, ImportError):
    print "Note: GNUTLS not available."


## Authentication framework (ported from Knooboo)
from twisted.web2 import log, server, channel
from twisted.cred import portal, checkers, credentials
import sagenb.notebook.guard as guard
import sagenb.notebook.avatars as avatars

from twisted.cred import portal

realm = avatars.LoginSystem()
p = portal.Portal(realm)
startup_token = '%%x' %% random.randint(0, 2**128)
startup_checker = avatars.OneTimeTokenChecker()
startup_checker.token = startup_token
p.registerChecker(startup_checker)
password_checker = avatars.PasswordChecker()
p.registerChecker(password_checker)
p.registerChecker(checkers.AllowAnonymousAccess())
rsrc = guard.MySessionWrapper(p)
log.DefaultCommonAccessLoggingObserver().start()
site = server.Site(rsrc)
%s
from twisted.web2 import channel
from twisted.application import service, strports
application = service.Application("SAGE Notebook")
s = strports.service(%r, factory)
%s
s.setServiceParent(application)

reactor.addSystemEventTrigger('before', 'shutdown', save_notebook)

""" % (notebook_opts, sagetex_path, not require_login,
       os.path.abspath(directory), cwd, factory,
       strport, open_page))

        config.close()

        ## Start up twisted
        cmd = 'twistd --pidfile="%s" -ny "%s"' % (pidfile, conf)
        if not quiet:
            print_open_msg('localhost' if not interface else interface,
                           port, secure=secure)
        if secure and not quiet:
            print "There is an admin account.  If you do not remember the password,"
            print "quit the notebook and type notebook(reset=True)."

        if fork:
            import pexpect
            return pexpect.spawn(cmd)
        else:
            e = os.system(cmd)

        os.chdir(cwd)
        if e == 256:
            raise socket.error

        return True
Exemple #5
0
    def run(port):
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.
        pidfile = os.path.join(directory, 'twistd.pid')
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(pidfile)
            except SystemExit as e:
                pid = int(open(pidfile).read())

                if str(e).startswith('Another twistd server is running,'):
                    print 'Another Sage Notebook server is running, PID %d.' % pid
                    old_interface, old_port, old_secure = get_old_settings(conf)
                    if open_viewer and old_port:
                        old_interface = old_interface or 'localhost'

                        print 'Opening web browser at http%s://%s:%s/ ...' % (
                            's' if old_secure else '', old_interface, old_port)

                        from sagenb.misc.misc import open_page as browse_to
                        browse_to(old_interface, old_port, old_secure, '/')
                        return
                    print '\nPlease either stop the old server or run the new server in a different directory.'
                    return

        ## Create the config file
        if secure:
            if (not os.path.exists(private_pem) or
                not os.path.exists(public_pem)):
                print "In order to use an SECURE encrypted notebook, you must first run notebook.setup()."
                print "Now running notebook.setup()"
                notebook_setup()
            if (not os.path.exists(private_pem) or
                not os.path.exists(public_pem)):
                print "Failed to setup notebook.  Please try notebook.setup() again manually."
            strport = '%s:%s:interface=%s:privateKey=%s:certKey=%s'%(
                protocol, port, interface, private_pem, public_pem)
        else:
            strport = 'tcp:%s:interface=%s' % (port, interface)

        notebook_opts = '"%s",interface="%s",port=%s,secure=%s' % (
            os.path.abspath(directory), interface, port, secure)

        if open_viewer:
            start_path = "'/?startup_token=%s' % startup_token"
            if interface:
                hostname = interface
            else:
                hostname = 'localhost'
            open_page = "from sagenb.misc.misc import open_page; open_page('%s', %s, %s, %s)" % (hostname, port, secure, start_path)
        else:
            open_page = ''

        config = open(conf, 'w')

        config.write(FLASK_NOTEBOOK_CONFIG%{'notebook_opts': notebook_opts, 'sagetex_path': sagetex_path,
                                            'do_not_require_login': not require_login,
                                            'dir': os.path.abspath(directory), 'cwd':cwd, 
                                            'strport': strport,
                                            'open_page': open_page})


        config.close()                     

        ## Start up twisted
        cmd = 'twistd --pidfile="%s" -ny "%s"' % (pidfile, conf)
        if not quiet:
            print_open_msg('localhost' if not interface else interface,
            port, secure=secure)
        if secure and not quiet:
            print "There is an admin account.  If you do not remember the password,"
            print "quit the notebook and type notebook(reset=True)."

        if fork:
            import pexpect
            return pexpect.spawn(cmd)
        else:
            e = os.system(cmd)

        os.chdir(cwd)
        if e == 256:
            raise socket.error

        return True
Exemple #6
0
    def run(port):
        # Is a server already running? Check if a Twistd PID exists in
        # the given directory.
        pidfile = os.path.join(directory, 'twistd.pid')
        if platformType != 'win32':
            from twisted.scripts._twistd_unix import checkPID
            try:
                checkPID(pidfile)
            except SystemExit as e:
                pid = int(open(pidfile).read())

                if str(e).startswith('Another twistd server is running,'):
                    print 'Another Sage Notebook server is running, PID %d.' % pid
                    old_interface, old_port, old_secure = get_old_settings(
                        conf)
                    if open_viewer and old_port:
                        old_interface = old_interface or 'localhost'

                        print 'Opening web browser at http%s://%s:%s/ ...' % (
                            's' if old_secure else '', old_interface, old_port)

                        from sagenb.misc.misc import open_page as browse_to
                        browse_to(old_interface, old_port, old_secure, '/')
                        return
                    print '\nPlease either stop the old server or run the new server in a different directory.'
                    return

        ## Create the config file
        if secure:
            if (not os.path.exists(private_pem)
                    or not os.path.exists(public_pem)):
                print "In order to use an SECURE encrypted notebook, you must first run notebook.setup()."
                print "Now running notebook.setup()"
                notebook_setup()
            if (not os.path.exists(private_pem)
                    or not os.path.exists(public_pem)):
                print "Failed to setup notebook.  Please try notebook.setup() again manually."
            strport = '%s:%s:interface=%s:privateKey=%s:certKey=%s' % (
                protocol, port, interface, private_pem, public_pem)
        else:
            strport = 'tcp:%s:interface=%s' % (port, interface)

        notebook_opts = '"%s",interface="%s",port=%s,secure=%s' % (
            os.path.abspath(directory), interface, port, secure)

        if open_viewer:
            start_path = "'/?startup_token=%s' % startup_token"
            if interface:
                hostname = interface
            else:
                hostname = 'localhost'
            open_page = "from sagenb.misc.misc import open_page; open_page('%s', %s, %s, %s)" % (
                hostname, port, secure, start_path)
        else:
            open_page = ''

        config = open(conf, 'w')

        config.write(
            FLASK_NOTEBOOK_CONFIG % {
                'notebook_opts': notebook_opts,
                'sagetex_path': sagetex_path,
                'do_not_require_login': not require_login,
                'dir': os.path.abspath(directory),
                'cwd': cwd,
                'strport': strport,
                'open_page': open_page
            })

        config.close()

        ## Start up twisted
        cmd = 'twistd --pidfile="%s" -ny "%s"' % (pidfile, conf)
        if not quiet:
            print_open_msg('localhost' if not interface else interface,
                           port,
                           secure=secure)
        if secure and not quiet:
            print "There is an admin account.  If you do not remember the password,"
            print "quit the notebook and type notebook(reset=True)."

        if fork:
            import pexpect
            return pexpect.spawn(cmd)
        else:
            e = os.system(cmd)

        os.chdir(cwd)
        if e == 256:
            raise socket.error

        return True