~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/webapp/console/service.py

  • Committer: William Grant
  • Date: 2010-02-18 03:31:47 UTC
  • Revision ID: grantw@unimelb.edu.au-20100218033147-z1es9tzrx7eg85gu
Ensure that we always close the DB connection at request termination, even in the case of an exception.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# IVLE
2
 
# Copyright (C) 2007-2008 The University of Melbourne
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2009 The University of Melbourne
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
5
5
# it under the terms of the GNU General Public License as published by
15
15
# along with this program; if not, write to the Free Software
16
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
17
 
18
 
# App: consoleservice
19
 
# Author: Matt Giuca, Tom Conway
20
 
# Date: 14/1/2008
21
 
 
22
 
import cStringIO
23
 
import httplib
24
 
import md5
 
18
# Author: Matt Giuca, Tom Conway, Will Grant
 
19
 
 
20
'''Python console RPC service.
 
21
 
 
22
Provides an HTTP RPC interface to a Python console process.
 
23
 
 
24
'''
 
25
 
25
26
import os
26
 
import pwd
27
 
import random
28
27
import socket
29
 
import sys
30
 
import urllib
31
 
import uuid
32
28
 
33
29
import cjson
34
 
 
35
 
from common import (util, studpath, chat)
36
 
import conf
37
 
 
38
 
trampoline_path = os.path.join(conf.ivle_install_dir, "bin/trampoline")
39
 
python_path = "/usr/bin/python"                     # Within jail
40
 
console_dir = "/opt/ivle/scripts"                   # Within jail
41
 
console_path = "/opt/ivle/scripts/python-console"   # Within jail
42
 
 
43
 
def handle(req):
44
 
    """Handler for the Console Service AJAX backend application."""
45
 
    if len(req.path) > 0 and req.path[-1] == os.sep:
46
 
        path = req.path[:-1]
47
 
    else:
48
 
        path = req.path
49
 
    # The path determines which "command" we are receiving
50
 
    if req.path == "start":
51
 
        handle_start(req)
52
 
    elif req.path == "chat":
53
 
        handle_chat(req)
54
 
    elif req.path == "block":
55
 
        handle_chat(req, kind="block")
56
 
    else:
57
 
        req.throw_error(req.HTTP_BAD_REQUEST)
58
 
 
59
 
def handle_start(req):
60
 
    jail_path = os.path.join(conf.jail_base, req.username)
61
 
    working_dir = os.path.join("/home", req.username)   # Within jail
62
 
 
63
 
    # Get the UID of the logged-in user
64
 
    try:
65
 
        (_,_,uid,_,_,_,_) = pwd.getpwnam(req.username)
66
 
    except KeyError:
67
 
        # The user does not exist. This should have already failed the
68
 
        # previous test.
69
 
        req.throw_error(req.HTTP_INTERNAL_SERVER_ERROR)
70
 
 
71
 
    # Set request attributes
72
 
    req.content_type = "text/plain"
73
 
    req.write_html_head_foot = False
74
 
 
75
 
    # TODO: Figure out the host name the console server is running on.
76
 
    host = socket.gethostname()
77
 
 
78
 
    # Create magic
79
 
    # TODO
80
 
    magic = md5.new(uuid.uuid4().bytes).digest().encode('hex')
81
 
 
82
 
    # Try to find a free port on the server.
83
 
    # Just try some random ports in the range [3000,8000)
84
 
    # until we either succeed, or give up. If you think this
85
 
    # sounds risky, it isn't:
86
 
    # For N ports (e.g. 5000) with k (e.g. 100) in use, the
87
 
    # probability of failing to find a free port in t (e.g. 5) tries
88
 
    # is (k / N) ** t (e.g. 3.2*10e-9).
89
 
 
90
 
    tries = 0
91
 
    while tries < 5:
92
 
        port = int(random.uniform(3000, 8000))
93
 
 
94
 
        # Start the console server (port, magic)
95
 
        # trampoline usage: tramp uid jail_dir working_dir script_path args
96
 
        # console usage:    python-console port magic
97
 
        # TODO: Pass working_dir as argument, let console cd to it
98
 
        cmd = ' '.join([trampoline_path, str(uid), jail_path,
99
 
                            console_dir, python_path, console_path,
100
 
                            str(port), str(magic)])
101
 
 
102
 
        # print >> sys.stderr, cmd
103
 
        res = os.system(cmd)
104
 
        # print >> sys.stderr, res
105
 
 
106
 
        if res == 0:
107
 
            # success
108
 
            break;
109
 
 
110
 
        tries += 1
111
 
 
112
 
    if tries == 5:
113
 
        raise Exception, "unable to find a free port!"
114
 
 
115
 
    # Assemble the key and return it.
116
 
    key = cjson.encode({"host": host, "port": port, "magic": magic})
117
 
    req.write(cjson.encode(key.encode("hex")))
118
 
 
119
 
def handle_chat(req, kind = "chat"):
120
 
    # The request *should* have the following four fields:
121
 
    # host, port, magic: Host and port where the console server lives,
122
 
    # and the secret to use to digitally sign the communication with the
123
 
    # console server.
124
 
    # text: Fields to pass along to the console server
125
 
    # It simply acts as a proxy to the console server
126
 
    if req.method != "POST":
127
 
        req.throw_error(req.HTTP_BAD_REQUEST)
128
 
    fields = req.get_fieldstorage()
129
 
    try:
130
 
        key = cjson.decode(fields.getfirst("key").value.decode("hex"))
131
 
        host = key['host']
132
 
        port = key['port']
133
 
        magic = key['magic']
134
 
    except AttributeError:
135
 
        # Any of the getfirsts returned None
136
 
        req.throw_error(req.HTTP_BAD_REQUEST)
137
 
    # If text is None, it was probably just an empty line
138
 
    try:
139
 
        text = fields.getfirst("text").value
140
 
    except AttributeError:
141
 
        text = ""
142
 
 
143
 
    msg = {'cmd':kind, 'text':text}
144
 
    response = chat.chat(host, port, msg, magic, decode = False)
145
 
    print >> open("/tmp/wibble","w"), repr(msg), repr(response)
146
 
    req.content_type = "text/plain"
147
 
    req.write(response)
148
 
 
 
30
import errno
 
31
 
 
32
import ivle.console
 
33
import ivle.chat
 
34
from ivle.webapp.base.rest import JSONRESTView, named_operation
 
35
from ivle.webapp.errors import BadRequest
 
36
 
 
37
# XXX: Should be RPC view, with actions in URL?
 
38
class ConsoleServiceRESTView(JSONRESTView):
 
39
    '''An RPC interface to a Python console.'''
 
40
    def get_permissions(self, user, config):
 
41
        if user is not None:
 
42
            return set(['use'])
 
43
        else:
 
44
            return set()
 
45
 
 
46
    @named_operation('use')
 
47
    def start(self, req, cwd=''):
 
48
        working_dir = os.path.join("/home", req.user.login, cwd)
 
49
 
 
50
        uid = req.user.unixid
 
51
 
 
52
        # Start the server
 
53
        jail_path = os.path.join(req.config['paths']['jails']['mounts'],
 
54
                                 req.user.login)
 
55
        cons = ivle.console.Console(req.config, uid, jail_path, working_dir)
 
56
 
 
57
        # Assemble the key and return it. Yes, it is double-encoded.
 
58
        return {'key': cjson.encode({"host": cons.host,
 
59
                                     "port": cons.port,
 
60
                                     "magic": cons.magic}).encode('hex')}
 
61
 
 
62
    @named_operation('use')
 
63
    def chat(self, req, key, text='', cwd='', kind="chat"):
 
64
        # The request *should* have the following four fields:
 
65
        # key: Hex JSON dict of host and port where the console server lives,
 
66
        # and the secret to use to digitally sign the communication with the
 
67
        # console server.
 
68
        # text: Fields to pass along to the console server
 
69
        # It simply acts as a proxy to the console server
 
70
 
 
71
        try:
 
72
            keydict = cjson.decode(key.decode('hex'))
 
73
            host = keydict['host']
 
74
            port = keydict['port']
 
75
            magic = keydict['magic']
 
76
        except KeyError:
 
77
            raise BadRequest("Invalid console key.")
 
78
 
 
79
        jail_path = os.path.join(req.config['paths']['jails']['mounts'],
 
80
                                 req.user.login)
 
81
        # Within Jail
 
82
        working_dir = os.path.join("/home", req.user.login, cwd)
 
83
        uid = req.user.unixid
 
84
 
 
85
        # XXX: JSONRESTView should do this for us.
 
86
        text = text.decode('utf-8')
 
87
 
 
88
        msg = {'cmd':kind, 'text':text}
 
89
        try:
 
90
            json_response = ivle.chat.chat(host, port, msg, magic,decode=False)
 
91
 
 
92
            # Snoop the response from python-console to check that it's valid
 
93
            try:
 
94
                response = cjson.decode(json_response)
 
95
            except cjson.DecodeError:
 
96
                # Could not decode the reply from the python-console server
 
97
                response = {"terminate":
 
98
                    "Communication to console process lost"}
 
99
            if "terminate" in response:
 
100
                response = restart_console(req.config, uid, jail_path,
 
101
                    working_dir, response["terminate"])
 
102
        except socket.error, (enumber, estring):
 
103
            if enumber == errno.ECONNREFUSED:
 
104
                # Timeout: Restart the session
 
105
                response = restart_console(req.config, uid, jail_path,
 
106
                    working_dir,
 
107
                    "The IVLE console has timed out due to inactivity")
 
108
            elif enumber == errno.ECONNRESET:
 
109
                # Communication issue: Restart the session
 
110
                response = restart_console(req.config, uid, jail_path,
 
111
                    working_dir,
 
112
                    "Connection with the console has been reset")
 
113
            else:
 
114
                # Some other error - probably serious
 
115
                raise socket.error, (enumber, estring)
 
116
        return response
 
117
 
 
118
 
 
119
def restart_console(config, uid, jail_path, working_dir, reason):
 
120
    """Tells the client that it must be issued a new console since the old 
 
121
    console is no longer availible. The client must accept the new key.
 
122
    Returns the JSON response to be given to the client.
 
123
    """
 
124
    # Start a new console server console
 
125
    cons = ivle.console.Console(config, uid, jail_path, working_dir)
 
126
 
 
127
    # Make a JSON object to tell the browser to restart its console client
 
128
    new_key = cjson.encode(
 
129
        {"host": cons.host, "port": cons.port, "magic": cons.magic})
 
130
 
 
131
    return {"restart": reason, "key": new_key.encode("hex")}