emulabserver.py.in 203 KB
Newer Older
1 2 3
#! /usr/bin/env python
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2004-2011 University of Utah and the Flux Group.
5 6 7 8 9
# All rights reserved.
#
import sys
import socket
import os
Timothy Stack's avatar
 
Timothy Stack committed
10 11
import os.path
import stat
12 13
import tempfile
import time
14 15
import re
import string
Timothy Stack's avatar
 
Timothy Stack committed
16 17 18 19
import pwd
import grp
import errno
import exceptions
20
import xmlrpclib
21
import signal
22
import types
23
import datetime
24
import syslog
25 26 27

# Configure variables
TBDIR = "@prefix@"
28
BOSSNODE = "@BOSSNODE@"
29
BOSSEVENTPORT = "@BOSSEVENTPORT@"
Timothy Stack's avatar
 
Timothy Stack committed
30 31
OURDOMAIN = "@OURDOMAIN@"
USERNODE = "@USERNODE@"
Ryan Jackson's avatar
Ryan Jackson committed
32 33 34
BASEADDR = "@FRISEBEEMCASTADDR@"
BASEPORT = "@FRISEBEEMCASTPORT@"
SUBBOSS_UID = "elabman"
Timothy Stack's avatar
 
Timothy Stack committed
35 36 37 38 39 40 41 42 43

TBPATH = os.path.join(TBDIR, "lib")
if TBPATH not in sys.path:
    sys.path.append(TBPATH)
    pass

from libdb        import *
from libtestbed   import SENDMAIL, TBOPS
from emulabclient import *
44

45 46 47
# Version
VERSION = 0.1

Timothy Stack's avatar
 
Timothy Stack committed
48
# Well known directories
49 50 51 52 53
PROJROOT = "@PROJROOT_DIR@"
GROUPROOT = "@GROUPSROOT_DIR@"
SCRATCHROOT = "@SCRATCHROOT_DIR@"
SHAREROOT = "@SHAREROOT_DIR@"
USERSROOT = "@USERSROOT_DIR@"
Timothy Stack's avatar
 
Timothy Stack committed
54 55 56 57 58 59 60

# List of directories exported to nodes via NFS.
NFS_EXPORTS = [
    PROJROOT,
    GROUPROOT,
    SHAREROOT,
    USERSROOT,
61
    SCRATCHROOT,
Timothy Stack's avatar
 
Timothy Stack committed
62 63
    ]

64 65 66 67 68 69 70 71 72 73 74 75 76 77
#
# XXX
# This mirrors db/xmlconvert. Be sure to keep this table in sync with that table.
#
virtual_tables = {
    "experiments"		: { "rows"  : None, 
                                    "tag"   : "experiment",
                                    "attrs" : [ ] },
    "virt_nodes"		: { "rows"  : None, 
                                    "tag"   : "nodes",
                                    "attrs" : [ "vname" ]},
    "virt_lans"                 : { "rows"  : None, 
                                    "tag"   : "lans",
                                    "attrs" : [ "vname" ]},
78 79 80
    "virt_lan_lans"             : { "rows"  : None, 
                                    "tag"   : "lan_lans",
                                    "attrs" : [ "vname" ]},
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    "virt_lan_settings"         : { "rows"  : None, 
                                    "tag"   : "lan_settings",
                                    "attrs" : [ "vname", "capkey" ]},
    "virt_lan_member_settings"  : { "rows"  : None, 
                                    "tag"   : "lan_member_settings",
                                    "attrs" : [ "vname", "member", "capkey" ]},
    "virt_trafgens"		: { "rows"  : None, 
                                    "tag"   : "trafgens",
                                    "attrs" : [ "vname", "vnode" ]},
    "virt_agents"		: { "rows"  : None, 
                                    "tag"   : "agents",
                                    "attrs" : [ "vname", "vnode" ]},
    "virt_node_desires"         : { "rows"  : None, 
                                    "tag"   : "node_desires",
                                    "attrs" : [ "vname", "desire" ]},
Timothy Stack's avatar
 
Timothy Stack committed
96 97 98
    "virt_node_startloc"        : { "rows"  : None,
                                    "tag"   : "node_startlocs",
                                    "attrs" : [ "vname", "building" ]},
99 100 101 102 103 104 105 106 107
    "virt_routes"		: { "rows"  : None, 
                                    "tag"   : "routes",
                                    "attrs" : [ "vname", "src", "dst" ]},
    "virt_vtypes"		: { "rows"  : None, 
                                    "tag"   : "vtypes",
                                    "attrs" : [ "name" ]},
    "virt_programs"		: { "rows"  : None, 
                                    "tag"   : "programs",
                                    "attrs" : [ "vname", "vnode" ]},
Timothy Stack's avatar
 
Timothy Stack committed
108 109 110
    "virt_user_environment"	: { "rows"  : None, 
                                    "tag"   : "user_environment",
                                    "attrs" : [ "name", "value" ]},
111 112 113 114 115
    "nseconfigs"		: { "rows"  : None, 
                                    "tag"   : "nseconfigs",
                                    "attrs" : [ "vname" ]},
    "eventlist"                 : { "rows"  : None, 
                                    "tag"   : "events",
Timothy Stack's avatar
 
Timothy Stack committed
116
                                    "attrs" : [ "vname" ]},
Timothy Stack's avatar
 
Timothy Stack committed
117 118 119 120 121 122 123 124 125
    "event_groups"              : { "rows"  : None,
                                    "tag"   : "event_groups",
                                    "attrs" : [ "group_name", "agent-name" ]},
    "virt_firewalls"            : { "rows"  : None,
                                    "tag"   : "virt_firewalls",
                                    "attrs" : [ "fwname", "type", "style" ]},
    "firewall_rules"            : { "rows"  : None,
                                    "tag"   : "firewall_rules",
                                    "attrs" : [ "fwname", "ruleno", "rule" ]},
Timothy Stack's avatar
 
Timothy Stack committed
126 127 128
    "virt_tiptunnels"           : { "rows"  : None,
                                    "tag"   : "tiptunnels",
                                    "attrs" : [ "host", "vnode" ]},
129 130
    }
    
Timothy Stack's avatar
 
Timothy Stack committed
131 132 133 134 135 136 137 138 139 140 141 142
# Base class for emulab specific exceptions.
class EmulabError(exceptions.Exception):
    pass

# Exception thrown when logins are not allowed.
class NoLoginsError(EmulabError):
    pass

# Exception thrown an unknown user tries to import this module.
class UnknownUserError(EmulabError):
    pass

143 144 145 146 147 148 149
# Exception thrown when a timer expires.
class TimedOutError(EmulabError):
    pass

def TimeoutHandler(signum, frame):
    raise TimedOutError, 'Timer Expired'

150 151 152 153 154 155 156 157 158
def logit(debug, msg):
    if debug:
        print msg
        pass
    else:
        syslog.syslog(syslog.LOG_INFO, msg);
        pass
    return

159
#
160 161
# Arguments to methods are passed as a Dictionary. This converts to a XML
# "struct" which in Perl/PHP/Ruby would be a hash. So, a client written in
162 163
# pretty much any language should be able to talk to this class.
#
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
#
# A helper function for checking required arguments.
#
def CheckRequiredArgs(argdict, arglist):
    # proj,group,exp are aliases for pid,gid,eid
    if (argdict.has_key("pid") and not argdict.has_key("proj")):
        argdict["proj"] = argdict["pid"]
        pass
    if (argdict.has_key("gid") and not argdict.has_key("group")):
        argdict["group"] = argdict["gid"]
        pass
    if (argdict.has_key("eid") and not argdict.has_key("exp")):
        argdict["exp"] = argdict["eid"]
        pass

    # Okay, now check.
    for arg in arglist:
        if not argdict.has_key(arg):
            return EmulabResponse(RESPONSE_BADARGS,
                                  output="Must supply '" + arg + "'")
        pass
    return None

Timothy Stack's avatar
 
Timothy Stack committed
187 188 189
#
# Check user permission to access a project.
#
190
def CheckProjPermission(uid_idx, pid):
Timothy Stack's avatar
 
Timothy Stack committed
191 192 193 194 195
    if not re.match("^[-\w]*$", pid):
        return EmulabResponse(RESPONSE_BADARGS,
                              output="Illegal characters in project ID!")

    res = DBQueryFatal("SELECT trust FROM group_membership "
196 197
                       "WHERE uid_idx=%s and pid=%s and gid=%s and trust!='none'",
                       (uid_idx, pid, pid))
Timothy Stack's avatar
 
Timothy Stack committed
198 199 200 201 202 203 204 205

    if len(res) == 0:
        return EmulabResponse(RESPONSE_FORBIDDEN,
                              output=("You do not have permission to " +
                                      "access project: " + pid))
    
    return None

206
def GetProjects(uid_idx):
Timothy Stack's avatar
 
Timothy Stack committed
207
    res = DBQueryFatal("SELECT distinct pid FROM group_membership "
208 209
                       "WHERE uid_idx=%s",
                       (uid_idx,))
Timothy Stack's avatar
 
Timothy Stack committed
210 211 212 213

    return [x[0] for x in res]


214 215 216
#
# Check user permission to access an experiment.
# 
217
def CheckExptPermission(uid_idx, pid, eid):
218 219 220 221 222
    if not (re.match("^[-\w]*$", pid) and
            re.match("^[-\w]*$", eid)):
        return EmulabResponse(RESPONSE_BADARGS,
                  output="Illegal characters in project and/or experiment IDs!")
    
223 224 225 226 227 228 229 230 231 232
    res = DBQueryFatal("SELECT gid FROM experiments "
                       "WHERE pid=%s and eid=%s",
                       (pid, eid))

    if len(res) == 0:
        return EmulabResponse(RESPONSE_ERROR,
                              output="No such experiment: " +
                              pid + "/" + eid)

    gid = res[0][0]
Timothy Stack's avatar
 
Timothy Stack committed
233
    
234
    res = DBQueryFatal("SELECT trust FROM group_membership "
235 236
                       "WHERE uid_idx=%s and pid=%s and gid=%s",
                       (uid_idx, pid, gid))
237 238 239 240 241 242 243

    if len(res) == 0:
        return EmulabResponse(RESPONSE_FORBIDDEN,
                              output=("You do not have permission to " +
                                      "access experiment: " + pid + "/" + eid))
    return None

Timothy Stack's avatar
 
Timothy Stack committed
244 245 246
#
# Check user permission to access a node.
# 
247
def CheckNodePermission(uid_idx, node):
Timothy Stack's avatar
 
Timothy Stack committed
248 249 250 251 252 253 254 255 256 257
    res = DBQueryFatal("SELECT e.pid,e.eid FROM reserved AS r "
                       "left join experiments as e on "
                       "     e.pid=r.pid and e.eid=r.eid "
                       "WHERE r.node_id=%s",
                       (node,))
    
    if len(res) == 0:
        return EmulabResponse(RESPONSE_ERROR,
                              output="No such node: " + node)

258
    return CheckExptPermission(uid_idx, res[0][0], res[0][1])
Timothy Stack's avatar
 
Timothy Stack committed
259

260 261 262
#
# Check if user is an admin person
# 
263
def CheckIsAdmin(uid_idx):
264
    res = DBQueryFatal("SELECT admin FROM users "
265 266
                       "WHERE uid_idx=%s and status='active'",
                       (uid_idx,))
267 268 269
    
    if len(res) == 0:
        return EmulabResponse(RESPONSE_ERROR,
270
                              output="No such user: " + uid_idx)
271 272 273

    return res[0][0];

274 275 276 277 278 279 280 281 282 283 284 285 286 287
#
# Template lookup, by exptidx of an experiment.
#
def TemplateLookup(exptidx):
    res = DBQueryFatal("select parent_guid,parent_vers from "
                       "   experiment_template_instances "
                       "where exptidx=%s",
                       (exptidx,))
    
    if len(res) == 0:
        return None

    return (res[0][0], res[0][1])

288 289 290 291 292 293 294 295 296 297 298 299 300
#
# Get an experiment index.
#
def ExperimentIndex(pid, eid):
    res = DBQueryFatal("select idx from experiments "
                       "where pid=%s and eid=%s",
                       (pid, eid))
    
    if len(res) == 0:
        return None
    
    return res[0][0];

301 302 303 304 305
#
# This is a wrapper class so that you can invoke methods in dotted form.
# For example experiment.swapexp(...).
#
class EmulabServer:
306
    def __init__(self, readonly=0, clientip=None, debug=0):
307
        self.readonly  = readonly;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
308
        self.clientip  = clientip;
309
        self.debug     = debug;
310
        self.instances = {};
311
        self.uid       = pwd.getpwuid(os.getuid())[0]
312

313 314 315 316 317 318 319 320 321
        res = DBQueryFatal("select uid_idx from users "
                           "where uid=%s and status='active'",
                           (self.uid,))
        if len(res) == 0:
            return
        self.uid_idx = res[0][0]

        self.instances["experiment"] = experiment(self);
        self.instances["template"]   = template(self);
322 323 324
        if readonly:
            return
        
325 326 327 328 329 330 331
        self.instances["emulab"]     = emulab(self);
        self.instances["user"]       = user(self);
        self.instances["fs"]         = fs(self);
        self.instances["imageid"]    = imageid(self);
        self.instances["osid"]       = osid(self);
        self.instances["node"]       = node(self);
        self.instances["elabinelab"] = elabinelab(self);
Ryan Jackson's avatar
Ryan Jackson committed
332
        self.instances["subboss"] = subboss(self);
333
        self.instances["blob"]       = blob(self);
334 335 336 337 338 339 340
        return

    def __getattr__(self, name):
        dotted = name.split(".");
        if len(dotted) != 2:
            raise AttributeError("Bad name '%s'" % name)
        if not self.instances.has_key(dotted[0]):
341 342
            raise AttributeError("unknown method '%s' (readonly=%d)" %
                                 (name, self.readonly))
343 344 345 346
        
        return getattr(self.instances[dotted[0]], dotted[1]);
    pass

Timothy Stack's avatar
 
Timothy Stack committed
347 348 349 350 351
#
# This class implements the server side of the XMLRPC interface to emulab as a
# whole.
#
class emulab:
352 353 354 355 356 357
    def __init__(self, server):
        self.server   = server
        self.readonly = server.readonly
        self.uid      = server.uid
        self.uid_idx  = server.uid_idx
        self.debug    = server.debug
358
        self.VERSION  = VERSION
Timothy Stack's avatar
 
Timothy Stack committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
        return

    #
    # Get the global 'notice' message that is usually printed under the menu
    # on the web site.
    #
    def message(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

        msg = TBGetSiteVar("web/message")

        return EmulabResponse(RESPONSE_SUCCESS,
                              value=msg,
                              output=msg)

    #
    # Get the news items as a list of {subject,author,date,msgid} items for
    # dates between an option start and ending.
    #
    def news(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

        # Process optional arguments.
        starting = None;
        if argdict.has_key("starting"):
            if not re.match("^[-:\w]*$", str(argdict["starting"])):
                return EmulabResponse(RESPONSE_BADARGS,
                                      output="Improperly formed 'starting'!")
            starting = sqldate(argdict["starting"])
            pass

        ending = None
        if argdict.has_key("ending"):
            if not re.match("^[-:\w]*$", str(argdict["ending"])):
                return EmulabResponse(RESPONSE_BADARGS,
                                      output="Improperly formed 'ending'!")
            ending = sqldate(argdict["ending"])
            pass

        # Construct the SQL date comparison
        if starting and ending:
            comparison = "BETWEEN %s and %s"
            sub = (starting, ending)
        elif starting:
            comparison = "> %s"
408
            pass
Timothy Stack's avatar
 
Timothy Stack committed
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
            sub = (starting,)
            pass
        elif ending:
            comparison = "< %s"
            sub = (ending,)
            pass
        else:
            comparison = ""
            sub = ()
            pass

        # Get the headlines and
        dbres = DBQueryFatal("SELECT subject,author,date,msgid FROM webnews "
                             "WHERE date "
                             + comparison
                             + " ORDER BY date DESC",
                             sub)

        # ... package them up
        result = []
        for res in dbres:
            tmp = {}
            tmp["subject"] = res[0]
            tmp["author"] = res[1]
            tmp["date"] = xmlrpclib.DateTime(
434
                time.strptime(str(res[2]), "%Y-%m-%d %H:%M:%S"))
Timothy Stack's avatar
 
Timothy Stack committed
435
            tmp["msgid"] = res[3]
Timothy Stack's avatar
 
Timothy Stack committed
436
            
Timothy Stack's avatar
 
Timothy Stack committed
437 438 439 440 441 442
            result.append(tmp)
            pass

        return EmulabResponse(RESPONSE_SUCCESS,
                              value=result,
                              output=str(result))
Timothy Stack's avatar
 
Timothy Stack committed
443

Timothy Stack's avatar
 
Timothy Stack committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    def getareas(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")
        
        # Get the listing that is accessible to this user and
        res = DBQueryFatal("SELECT distinct building FROM obstacles")

        if len(res) == 0:
            return EmulabResponse(RESPONSE_ERROR,
                                  output="No areas?")

        result = {}
        for area in res:
            result[area[0]] = {
                "name" : area[0]
                }
            pass

        return EmulabResponse(RESPONSE_SUCCESS,
                              value=result,
                              output=str(result))

Timothy Stack's avatar
 
Timothy Stack committed
467 468 469 470 471 472 473 474 475
    def vision_config(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

        if not re.match("^[-:\w]*$", str(argdict["area"])):
            return EmulabResponse(RESPONSE_BADARGS,
                                  output="Improperly formed 'area'!")

Timothy Stack's avatar
 
Timothy Stack committed
476 477 478
        result = DBQuery("select * from cameras where building=%s",
                        (argdict["area"],),
                        asDict=True)
Timothy Stack's avatar
 
Timothy Stack committed
479
        
Timothy Stack's avatar
 
Timothy Stack committed
480
        if len(result) == 0:
Timothy Stack's avatar
 
Timothy Stack committed
481 482 483
            return EmulabResponse(RESPONSE_ERROR,
                                  output="Unknown area " + argdict["area"])

Timothy Stack's avatar
 
Timothy Stack committed
484 485 486
        result = [scrubdict(x, defaultvals={ "loc_x" : 0.0, "loc_y" : 0.0 })
                  for x in result]

Timothy Stack's avatar
 
Timothy Stack committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=result,
                              output=str(result))

    def obstacle_config(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

        if not re.match("^[-:\w]*$", str(argdict["area"])):
            return EmulabResponse(RESPONSE_BADARGS,
                                  output="Improperly formed 'area'!")

        if not argdict.has_key("units"):
            argdict["units"] = "pixels"
            pass
        
        res = DBQuery("select * from obstacles where building=%s",
                      (argdict["area"],),
                      asDict=True)

        ppm = DBQueryFatal("select pixels_per_meter from floorimages "
                           "where building=%s",
                           (argdict["area"],))
        
        if len(res) == 0 or len(ppm) == 0:
            return EmulabResponse(RESPONSE_ERROR,
                                  output="No such area " + argdict["area"])

        ppm = ppm[0][0]

        for ob in res:
            if argdict["units"] == "meters":
                ob["x1"] = ob["x1"] / ppm
                ob["y1"] = ob["y1"] / ppm
                ob["z1"] = ob["z1"] / ppm
                ob["x2"] = ob["x2"] / ppm
                ob["y2"] = ob["y2"] / ppm
                ob["z2"] = ob["z2"] / ppm
                pass
Timothy Stack's avatar
 
Timothy Stack committed
527
            scrubdict(ob)
Timothy Stack's avatar
 
Timothy Stack committed
528 529 530 531 532
            pass
        
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=res,
                              output=str(res))
Timothy Stack's avatar
 
Timothy Stack committed
533 534 535 536 537 538 539 540 541
    
    pass


#
# This class implements the server side of the XMLRPC interface to user
# specific information.
#
class user:
542 543 544 545 546 547
    def __init__(self, server):
        self.server   = server
        self.readonly = server.readonly
        self.uid      = server.uid
        self.uid_idx  = server.uid_idx
        self.debug    = server.debug
548
        self.VERSION  = VERSION
Timothy Stack's avatar
 
Timothy Stack committed
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
        return

    #
    # Get the number of nodes this user is has allocated.
    #
    def nodecount(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

        res = DBQueryFatal(
            "SELECT a.node_id FROM nodes AS a "
            "left join reserved as b on a.node_id=b.node_id "
            "left join node_types as nt on a.type=nt.type "
            "left join experiments as e on b.pid=e.pid and "
            " b.eid=e.eid "
            "WHERE e.expt_head_uid=%s and e.pid!='emulab-ops' "
            "  and a.role='testnode' and nt.class = 'pc'",
573
            (self.uid,))
Timothy Stack's avatar
 
Timothy Stack committed
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620

        return EmulabResponse(RESPONSE_SUCCESS,
                              value=len(res),
                              output=str(len(res)))

    #
    # Get the listing of projects/groups that this user is a member of and,
    # optionally, has the permission to perform some task.
    #
    def membership(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

        permission = "readinfo"
        if argdict.has_key("permission"):
            permission = argdict["permission"]
            pass

        # Convert the permission to a SQL condition.
        if permission == "readinfo":
            trust_clause = "trust!='none'"
            pass
        elif permission == "makegroup":
            trust_clause = "trust='project_root'"
            pass
        elif permission == "createexpt":
            trust_clause = ("(trust='project_root' or trust='group_root' or "
                            " trust='local_root')")
            pass
        elif permission == "makeosid" or permission == "makeimageid":
            # XXX Handle admin
            trust_clause = ("(trust='project_root' or trust='group_root' or "
                            " trust='local_root')")
            pass
        else:
            return EmulabResponse(RESPONSE_BADARGS,
                                  output=("Bad permission value: "
                                          + permission))

        res = DBQueryFatal("SELECT distinct pid,gid FROM group_membership "
621
                           "WHERE uid_idx=%s and "
Timothy Stack's avatar
 
Timothy Stack committed
622 623
                           + trust_clause
                           + " ORDER BY pid",
624
                           (self.uid_idx,))
Timothy Stack's avatar
 
Timothy Stack committed
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643

        result = {}
        for proj in res:
            if result.has_key(proj[0]):
                # Add group to existing project list
                tmp = result[proj[0]]
                tmp.append(proj[1])
                pass
            else:
                # Add new project to root list
                tmp = [proj[1],]
                result[proj[0]] = tmp
                pass
            pass

        return EmulabResponse(RESPONSE_SUCCESS,
                              value=result,
                              output=str(result))

644 645 646 647 648 649 650 651 652 653 654 655 656 657
    #
    # Return collab password,
    #
    def collabpassword(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

658 659
        res = DBQueryFatal("select mailman_password from users where uid_idx=%s",
                           (self.uid_idx,))
660 661 662 663 664 665

        if len(res) == 0:
            return EmulabResponse(RESPONSE_ERROR,
                                  output="No such user!")

        passwd = res[0][0]
666
        return EmulabResponse(RESPONSE_SUCCESS, value=passwd, output=passwd)
667

Timothy Stack's avatar
 
Timothy Stack committed
668 669 670 671 672 673 674 675
    pass


#
# This class implements the server side of the XMLRPC interface to the emulab
# NFS exports.
#
class fs:
676 677 678 679 680 681
    def __init__(self, server):
        self.server   = server
        self.readonly = server.readonly
        self.uid      = server.uid
        self.uid_idx  = server.uid_idx
        self.debug    = server.debug
682
        self.VERSION  = VERSION
Timothy Stack's avatar
 
Timothy Stack committed
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
        return

    #
    # Check the accessibility of a path.
    #
    def access(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!");

        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

        argerror = CheckRequiredArgs(argdict, ("permission", "path"))
        if (argerror):
            return argerror

        try:
            path = nfspath(argdict["path"]) # Scrub the path
            
            permission = argdict["permission"]

            # Convert the permission to a python compatible value.
            if permission == "read" or permission == "r":
                accessmode = os.R_OK
                pass
            elif permission == "write" or permission == "w":
                accessmode = os.W_OK
                pass
            elif permission == "execute" or permission == "x":
                accessmode = os.X_OK
                pass
            elif permission == "exists" or permission == "e":
                accessmode = os.F_OK
                pass
            else:
                return EmulabResponse(RESPONSE_BADARGS,
                                      output=("Bad permission value: "
                                              + permission))
            
            res = os.access(path, accessmode)

            return EmulabResponse(RESPONSE_SUCCESS,
                                  value=res,
                                  output=str(res))
        except OSError, e:
            return EmulabResponse(RESPONSE_ERROR,
                                  value=e,
                                  output=(e.strerror + ": " + e.filename))

        # Never reached...
        assert False
        pass

    #
    # Get a directory listing for a given path.
    #
    def listdir(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

        argerror = CheckRequiredArgs(argdict, ("path",))
        if (argerror):
            return argerror

        try:
            path = nfspath(argdict["path"]) # Scrub the path

            # Make sure the path is accessible,
            if not os.access(path, os.X_OK):
                raise OSError(errno.EPERM, "Path is not accessible", path)

            # ... get the directory listing, and
            res = os.listdir(path)

            # ... package it up into a platform independent from.
            result = []
            for entry in res:
                try:
                    st = os.stat(os.path.join(path, entry))
                    # The UID/GID will be meaningless to the other side,
                    # resolve them before sending it back.
                    try:
                        uname = pwd.getpwuid(st[stat.ST_UID])[0]
                        pass
                    except:
                        # Unknown UID, just send the number as a string
                        uname = str(st[stat.ST_UID])
                        pass
                    try:
                        gname = grp.getgrgid(st[stat.ST_GID])[0]
                        pass
                    except:
                        # Unknown GID, just send the number as a string
                        gname = str(st[stat.ST_GID])
                        pass
                    result.append((entry,
                                   filetype(st[stat.ST_MODE]),
                                   stat.S_IMODE(st[stat.ST_MODE]),
                                   uname,
                                   gname,
                                   st[stat.ST_SIZE],
                                   st[stat.ST_ATIME],
                                   st[stat.ST_MTIME],
                                   st[stat.ST_CTIME]))
                except OSError:
                    pass
                pass
            retval = EmulabResponse(RESPONSE_SUCCESS,
                                    value=result,
                                    output=str(result))
            pass
        except OSError, e:
            retval = EmulabResponse(RESPONSE_ERROR,
                                    value=e,
                                    output=(e.strerror + ": " + e.filename))
            pass

        return retval

    #
    # Get the list of potential NFS exports for an experiment.
    #
    def exports(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

        # Start with the default set of exports, then
        res = [
829
            USERSROOT + "/" + self.uid, # XXX Use getpwuid() and handle admin
Timothy Stack's avatar
 
Timothy Stack committed
830 831 832 833 834
            SHAREROOT,
            ]

        # ... add the project/group listings.
        projs = DBQueryFatal("SELECT distinct pid,gid FROM group_membership "
835 836
                             "WHERE uid_idx=%s and trust!='none' ORDER BY pid",
                             (self.uid_idx,))
Timothy Stack's avatar
 
Timothy Stack committed
837 838 839 840

        for proj in projs:
            if proj[0] == proj[1]:
                res.append(PROJROOT + "/" + proj[0])
841 842 843
                if not SCRATCHROOT == "":
                    res.append(SCRATCHROOT + "/" + proj[0])
                    pass
Timothy Stack's avatar
 
Timothy Stack committed
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
                pass
            else:
                res.append(GROUPROOT + "/" + proj[0] + "/" + proj[1])
                pass
            pass
        
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=res,
                              output=str(res))

    pass


#
# This class implements the server side of the XMLRPC interface to image IDs.
#
class imageid:
861 862 863 864 865 866
    def __init__(self, server):
        self.server   = server
        self.readonly = server.readonly
        self.uid      = server.uid
        self.uid_idx  = server.uid_idx
        self.debug    = server.debug
867
        self.VERSION  = VERSION
Timothy Stack's avatar
 
Timothy Stack committed
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
        return

    def getlist(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

        # Get the listing that is accessible to this user and
        res = DBQueryFatal(
            "SELECT distinct i.imagename,i.description FROM images as i "
            "left join group_membership as g on g.pid=i.pid "
885 886
            "WHERE g.uid_idx=%s or i.global",
            (self.uid_idx,))
Timothy Stack's avatar
 
Timothy Stack committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912

        if len(res) == 0:
            return EmulabResponse(RESPONSE_ERROR,
                                  output="No image ids?")

        # ... package it up.
        result = {}
        for image in res:
            tmp = {
                "imageid" : image[0],
                "description" : image[1],
                }
            result[image[0]] = tmp
            pass

        return EmulabResponse(RESPONSE_SUCCESS,
                              value=result,
                              output=str(result))

    pass


#
# This class implements the server side of the XMLRPC interface to OS IDs.
#
class osid:
913 914 915 916 917 918
    def __init__(self, server):
        self.server   = server
        self.readonly = server.readonly
        self.uid      = server.uid
        self.uid_idx  = server.uid_idx
        self.debug    = server.debug
919
        self.VERSION  = VERSION
Timothy Stack's avatar
 
Timothy Stack committed
920 921 922 923 924 925 926 927 928 929 930 931 932 933
        return

    def getlist(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

        # Get the listing that is accessible to this user and
934
        res = DBQueryFatal("SELECT distinct "
Timothy Stack's avatar
 
Timothy Stack committed
935
                           "o.* FROM "
Timothy Stack's avatar
 
Timothy Stack committed
936 937
                           "os_info as o "
                           "left join group_membership as g on g.pid=o.pid "
938 939
                           "where g.uid_idx=%s or o.shared=1",
                           (self.uid_idx,),
Timothy Stack's avatar
 
Timothy Stack committed
940
                           True)
Timothy Stack's avatar
 
Timothy Stack committed
941 942 943 944 945 946 947 948

        if len(res) == 0:
            return EmulabResponse(RESPONSE_ERROR,
                                  output="No OS IDs?")

        # ... package it up.
        result = {}
        for osid in res:
Timothy Stack's avatar
 
Timothy Stack committed
949 950 951
            # XXX Legacy stuff...
            osid["fullosid"] = osid["osid"]
            osid["osid"] = osid["osname"]
Timothy Stack's avatar
 
Timothy Stack committed
952

Timothy Stack's avatar
 
Timothy Stack committed
953 954 955 956 957 958 959
            if not osid["OS"] or len(osid["OS"]) == 0:
                osid["OS"] = "(None)"
                pass

            result[osid["osid"]] = scrubdict(osid)
            pass
        
Timothy Stack's avatar
 
Timothy Stack committed
960 961
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=result,
Timothy Stack's avatar
 
Timothy Stack committed
962
                              output="")
Timothy Stack's avatar
 
Timothy Stack committed
963 964 965 966 967 968 969
    
    def info(self, version, argdict):
        # Check for valid arguments.
        argerror = CheckRequiredArgs(argdict, ("osid",))
        if (argerror):
            return argerror

970
        if not re.match("^[-\w\.]*$", argdict["osid"]):
Timothy Stack's avatar
 
Timothy Stack committed
971 972 973 974 975 976 977 978
            return EmulabResponse(RESPONSE_BADARGS,
                                  output="Improperly formed osid!")

        # Get the listing that is accessible to this user and
        res = DBQueryFatal("SELECT distinct "
                           "o.* FROM "
                           "os_info as o "
                           "left join group_membership as g on g.pid=o.pid "
979
                           "where (g.uid_idx=%s or o.shared=1) and "
Timothy Stack's avatar
 
Timothy Stack committed
980
                           "(o.osname=%s or o.osid=%s)",
981
                           (self.uid_idx, argdict["osid"], argdict["osid"]),
Timothy Stack's avatar
 
Timothy Stack committed
982 983 984 985 986 987 988 989 990 991 992 993 994
                           True)

        if len(res) == 0:
            return EmulabResponse(RESPONSE_ERROR,
                                  output="Unknown OS ID?")

        osid = res[0]
        osid["fullosid"] = osid["osid"]
        osid["osid"] = osid["osname"]
        
        if not osid["OS"] or len(osid["OS"]) == 0:
            osid["OS"] = "(None)"
            pass
995

Timothy Stack's avatar
 
Timothy Stack committed
996 997 998
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=scrubdict(osid),
                              output=str(osid))
Timothy Stack's avatar
 
Timothy Stack committed
999 1000 1001

    pass

1002

1003 1004 1005 1006
#
# This class implements the server side of the XMLRPC interface to experiments.
#
class experiment:
1007 1008 1009
    ##
    # Initialize the object.  Currently only sets the objects 'VERSION' value.
    #
1010 1011 1012 1013 1014 1015
    def __init__(self, server):
        self.server   = server
        self.readonly = server.readonly
        self.uid      = server.uid
        self.uid_idx  = server.uid_idx
        self.debug    = server.debug
1016
        self.VERSION  = VERSION
1017 1018 1019 1020 1021 1022 1023 1024 1025
        return

    ##
    # Echo a message, basically, prepend the host name to the parameter list.
    #
    # @param args The argument list to echo back.
    # @return The 'msg' value with this machine's name prepended.
    #
    def echo(self, version, argdict):
1026
        if not argdict.has_key("str"):
1027
            return EmulabResponse(RESPONSE_BADARGS,
Timothy Stack's avatar
 
Timothy Stack committed
1028
                                  output="Must supply a string to echo!")
1029
        
1030
        return EmulabResponse(RESPONSE_SUCCESS, 0,
1031 1032
                             socket.gethostname() + ": " + str(version)
                             + " " + argdict["str"])
1033

Timothy Stack's avatar
 
Timothy Stack committed
1034 1035 1036 1037 1038 1039 1040 1041
    #
    # Get the physical/policy constraints for experiment parameters.
    #
    def constraints(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")

1042 1043 1044 1045
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar
 
Timothy Stack committed
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

        result = {
            "idle/threshold" : TBGetSiteVar("idle/threshold"),
            # XXX Add more...
            }
        
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=result,
                              output=str(result))

    #
    # Get the list of experiments where the user is the head.
    #
    def getlist(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
                                  output="Client version mismatch!")
        
1069 1070 1071 1072
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar
 
Timothy Stack committed
1073 1074 1075 1076 1077 1078
        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

1079 1080 1081 1082 1083 1084 1085 1086
        # Figure out the format for the returned data.
        if argdict.has_key("format"):
            format = argdict["format"]
            pass
        else:
            format = "brief"
            pass

Timothy Stack's avatar
 
Timothy Stack committed
1087
        # XXX Let the user specify the pid/gid
1088
        dbres = DBQueryFatal("SELECT e.pid,e.gid,e.eid,e.expt_name,e.state,"
Timothy Stack's avatar
 
Timothy Stack committed
1089 1090
                             "e.expt_head_uid,e.minimum_nodes,e.maximum_nodes,"
                             "count(r.node_id) as actual_nodes "
1091
                             "  FROM experiments AS e "
Timothy Stack's avatar
 
Timothy Stack committed
1092 1093 1094 1095
                             "left join reserved as r on e.pid=r.pid and "
                             "  e.eid=r.eid "
                             "WHERE e.expt_head_uid=%s "
                             "GROUP BY e.pid,e.eid",
1096
                             (self.uid,))
Timothy Stack's avatar
 
Timothy Stack committed
1097 1098 1099 1100 1101

        # Build a dictionary of projects that refer to a dictionary of groups
        # that refer to a list of experiments in that group.
        result = {}
        for res in dbres:
1102 1103 1104 1105 1106 1107 1108
            # Get everything from the DB result,
            pid = res[0]
            gid = res[1]
            eid = res[2]
            desc = res[3]
            state = res[4]
            expt_head = res[5]
Timothy Stack's avatar
 
Timothy Stack committed
1109 1110 1111
            minimum_nodes = res[6]
            maximum_nodes = res[7]
            actual_nodes = res[8]
1112 1113 1114 1115
            # ... make sure 'result' has the proper slots,
            if not result.has_key(pid):
                result[pid] = {
                    gid : list()
Timothy Stack's avatar
 
Timothy Stack committed
1116 1117
                    }
                pass
1118 1119
            elif not result[pid].has_key(gid):
                result[pid][gid] = list()
Timothy Stack's avatar
 
Timothy Stack committed
1120
                pass
1121 1122 1123 1124 1125 1126 1127

            # ... drop the data into place, and
            expdata = None
            if format == "brief":
                expdata = eid;
                pass
            elif format == "full":
1128
                expdata = scrubdict({
1129 1130 1131 1132 1133 1134
                    "pid" : pid,
                    "gid" : gid,
                    "name" : eid,
                    "description" : desc,
                    "state" : state,
                    "expt_head" : expt_head,
Timothy Stack's avatar
 
Timothy Stack committed
1135 1136 1137
                    "minimum_nodes" : minimum_nodes,
                    "maximum_nodes" : maximum_nodes,
                    "actual_nodes" : actual_nodes,
1138
                    })
Timothy Stack's avatar
 
Timothy Stack committed
1139
                pass
1140 1141

            # ... append it to the group list.
1142
            result[pid][gid].append(expdata)
Timothy Stack's avatar
 
Timothy Stack committed
1143 1144 1145 1146 1147 1148
            pass
        
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=result,
                              output=str(result))

1149 1150 1151 1152 1153 1154
    #
    # Start an experiment using batchexp. We get the NS file inline, which
    # we have to write to a temp file first. 
    #
    def batchexp(self, version, argdict):
        if version != self.VERSION:
1155
            return EmulabResponse(RESPONSE_BADVERSION,
Timothy Stack's avatar
 
Timothy Stack committed
1156 1157
                                  output="Client version mismatch!")

1158 1159 1160 1161
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar
 
Timothy Stack committed
1162 1163
        try:
            checknologins()
1164
            pass
Timothy Stack's avatar
 
Timothy Stack committed
1165 1166
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))
1167

1168 1169 1170
        argerror = CheckRequiredArgs(argdict, ("proj", "exp"))
        if (argerror):
            return argerror
1171

1172
        nsfilename = None
1173
        argstr     = "-q"
1174
	extrainfo  = False
1175 1176
        
        for opt, val in argdict.items():
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1177
            if opt == "batch":
Timothy Stack's avatar
 
Timothy Stack committed
1178
                if not xbool(val):
1179 1180 1181
                    argstr += " -i"
                    pass
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1182
            elif opt == "description":
1183
                argstr += " -E "
1184
                argstr += escapeshellarg(val)
1185
                pass
1186
            elif opt == "group":
1187
                argstr += " -g "
1188
                argstr += escapeshellarg(val)
1189
                pass
1190
            elif opt == "exp":
1191
                argstr += " -e "
1192
                argstr += escapeshellarg(val)
1193
                pass
1194
            elif opt == "proj":
1195
                argstr += " -p "
1196
                argstr += escapeshellarg(val)
1197
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1198
            elif opt == "swappable":
Timothy Stack's avatar
 
Timothy Stack committed
1199
                if not xbool(val):
1200 1201 1202
                    if not argdict.has_key("noswap_reason"):
                        return EmulabResponse(RESPONSE_BADARGS,
                                       output="Must supply noswap reason!");
1203
                    argstr += " -S "
1204
                    argstr += escapeshellarg(argdict["noswap_reason"])
1205 1206
                    pass
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1207
            elif opt == "noswap_reason":
1208
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1209
            elif opt == "idleswap":
1210
                if val == 0:
1211 1212 1213
                    if not argdict.has_key("noidleswap_reason"):
                        return EmulabResponse(RESPONSE_BADARGS,
                                      output="Must supply noidleswap reason!");
1214
                    argstr += " -L "
1215
                    argstr += escapeshellarg(argdict["noidleswap_reason"])
1216 1217 1218
                    pass
                else:
                    argstr += " -l "
Timothy Stack's avatar
 
Timothy Stack committed
1219
                    argstr += escapeshellarg(str(val))
1220 1221
                    pass
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1222
            elif opt == "noidleswap_reason":
1223
                pass
1224
            elif opt == "autoswap" or opt == "max_duration":
1225
                argstr += " -a "
Timothy Stack's avatar
 
Timothy Stack committed
1226
                argstr += escapeshellarg(str(val))
1227
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1228
            elif opt == "noswapin":
Timothy Stack's avatar
 
Timothy Stack committed
1229
                if xbool(val):
1230 1231
                    argstr += " -f "
                    pass
1232
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1233
            elif opt == "wait":
Timothy Stack's avatar
 
Timothy Stack committed
1234
                if xbool(val):
1235 1236
                    argstr += " -w "
                    pass
1237
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1238
            elif opt == "nsfilepath":
1239
                # Backend script will verify this local path. 
1240
                nsfilename = escapeshellarg(val)
1241
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1242
            elif opt == "nsfilestr":
1243 1244 1245
                nsfilestr = val
            
                if len(nsfilestr) > (1024 * 512):