emulabserver.py.in 209 KB
Newer Older
1
2
#! /usr/bin/env python
#
3
# Copyright (c) 2004-2017 University of Utah and the Flux Group.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23
24
25
26
#
import sys
import socket
import os
Timothy Stack's avatar
   
Timothy Stack committed
27
28
import os.path
import stat
29
30
import tempfile
import time
31
32
import re
import string
Timothy Stack's avatar
   
Timothy Stack committed
33
34
35
36
import pwd
import grp
import errno
import exceptions
37
import xmlrpclib
38
import signal
39
import types
40
import datetime
41
import syslog
42
43
44

# Configure variables
TBDIR = "@prefix@"
45
BOSSNODE = "@BOSSNODE@"
46
BOSSEVENTPORT = "@BOSSEVENTPORT@"
Timothy Stack's avatar
   
Timothy Stack committed
47
48
OURDOMAIN = "@OURDOMAIN@"
USERNODE = "@USERNODE@"
Ryan Jackson's avatar
Ryan Jackson committed
49
50
51
BASEADDR = "@FRISEBEEMCASTADDR@"
BASEPORT = "@FRISEBEEMCASTPORT@"
SUBBOSS_UID = "elabman"
Timothy Stack's avatar
   
Timothy Stack committed
52
53
54
55
56
57
58
59
60

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 *
61

62
63
64
# Version
VERSION = 0.1

Timothy Stack's avatar
   
Timothy Stack committed
65
# Well known directories
66
67
68
69
70
PROJROOT = "@PROJROOT_DIR@"
GROUPROOT = "@GROUPSROOT_DIR@"
SCRATCHROOT = "@SCRATCHROOT_DIR@"
SHAREROOT = "@SHAREROOT_DIR@"
USERSROOT = "@USERSROOT_DIR@"
Timothy Stack's avatar
   
Timothy Stack committed
71
72
73
74
75
76
77

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

81
82
83
84
85
86
87
88
89
90
91
92
93
94
#
# 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" ]},
95
96
97
    "virt_lan_lans"             : { "rows"  : None, 
                                    "tag"   : "lan_lans",
                                    "attrs" : [ "vname" ]},
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    "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
113
114
115
    "virt_node_startloc"        : { "rows"  : None,
                                    "tag"   : "node_startlocs",
                                    "attrs" : [ "vname", "building" ]},
116
117
118
119
120
121
122
123
124
    "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
125
126
127
    "virt_user_environment"	: { "rows"  : None, 
                                    "tag"   : "user_environment",
                                    "attrs" : [ "name", "value" ]},
128
129
130
131
132
    "nseconfigs"		: { "rows"  : None, 
                                    "tag"   : "nseconfigs",
                                    "attrs" : [ "vname" ]},
    "eventlist"                 : { "rows"  : None, 
                                    "tag"   : "events",
Timothy Stack's avatar
   
Timothy Stack committed
133
                                    "attrs" : [ "vname" ]},
Timothy Stack's avatar
   
Timothy Stack committed
134
135
136
137
138
139
140
141
142
    "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
143
144
145
    "virt_tiptunnels"           : { "rows"  : None,
                                    "tag"   : "tiptunnels",
                                    "attrs" : [ "host", "vnode" ]},
146
147
    }
    
Timothy Stack's avatar
   
Timothy Stack committed
148
149
150
151
152
153
154
155
156
157
158
159
# 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

160
161
162
163
164
165
166
# Exception thrown when a timer expires.
class TimedOutError(EmulabError):
    pass

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

167
168
169
170
171
172
173
174
175
def logit(debug, msg):
    if debug:
        print msg
        pass
    else:
        syslog.syslog(syslog.LOG_INFO, msg);
        pass
    return

176
#
177
178
# 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
179
180
# pretty much any language should be able to talk to this class.
#
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#
# 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
204
205
206
#
# Check user permission to access a project.
#
207
def CheckProjPermission(uid_idx, pid):
Timothy Stack's avatar
   
Timothy Stack committed
208
209
210
211
212
    if not re.match("^[-\w]*$", pid):
        return EmulabResponse(RESPONSE_BADARGS,
                              output="Illegal characters in project ID!")

    res = DBQueryFatal("SELECT trust FROM group_membership "
213
214
                       "WHERE uid_idx=%s and pid=%s and gid=%s and trust!='none'",
                       (uid_idx, pid, pid))
Timothy Stack's avatar
   
Timothy Stack committed
215
216
217
218
219
220
221
222

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

223
def GetProjects(uid_idx):
Timothy Stack's avatar
   
Timothy Stack committed
224
    res = DBQueryFatal("SELECT distinct pid FROM group_membership "
225
226
                       "WHERE uid_idx=%s",
                       (uid_idx,))
Timothy Stack's avatar
   
Timothy Stack committed
227
228
229
230

    return [x[0] for x in res]


231
232
233
#
# Check user permission to access an experiment.
# 
234
def CheckExptPermission(uid_idx, pid, eid):
235
236
237
238
239
    if not (re.match("^[-\w]*$", pid) and
            re.match("^[-\w]*$", eid)):
        return EmulabResponse(RESPONSE_BADARGS,
                  output="Illegal characters in project and/or experiment IDs!")
    
240
241
242
243
244
245
246
247
248
249
    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
250
    
251
    res = DBQueryFatal("SELECT trust FROM group_membership "
252
253
                       "WHERE uid_idx=%s and pid=%s and gid=%s",
                       (uid_idx, pid, gid))
254
255
256
257
258
259
260

    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
261
262
263
#
# Check user permission to access a node.
# 
264
def CheckNodePermission(uid_idx, node):
Timothy Stack's avatar
   
Timothy Stack committed
265
266
267
268
269
270
271
272
273
274
    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)

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

277
278
279
#
# Check if user is an admin person
# 
280
def CheckIsAdmin(uid_idx):
281
    res = DBQueryFatal("SELECT admin FROM users "
282
283
                       "WHERE uid_idx=%s and status='active'",
                       (uid_idx,))
284
285
286
    
    if len(res) == 0:
        return EmulabResponse(RESPONSE_ERROR,
287
                              output="No such user: " + uid_idx)
288
289
290

    return res[0][0];

291
292
293
294
295
296
297
298
299
300
301
302
303
304
#
# 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])

305
306
307
308
309
310
311
312
313
314
315
316
317
#
# 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];

318
319
320
321
322
#
# This is a wrapper class so that you can invoke methods in dotted form.
# For example experiment.swapexp(...).
#
class EmulabServer:
323
    def __init__(self, uid, uid_idx, readonly=0, clientip=None, debug=0):
324
        self.readonly  = readonly;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
325
        self.clientip  = clientip;
326
        self.debug     = debug;
327
        self.instances = {};
328
329
        self.uid_idx   = uid_idx;
        self.uid       = uid;
330
331
332

        self.instances["experiment"] = experiment(self);
        self.instances["template"]   = template(self);
333
334
335
        if readonly:
            return
        
336
337
338
339
340
341
342
        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);
343
        self.instances["subboss"]    = subboss(self);
344
        self.instances["blob"]       = blob(self);
345
        self.instances["dataset"]    = dataset(self);
346
347
348
349
350
351
352
        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]):
353
354
            raise AttributeError("unknown method '%s' (readonly=%d)" %
                                 (name, self.readonly))
355
356
357
358
        
        return getattr(self.instances[dotted[0]], dotted[1]);
    pass

Timothy Stack's avatar
   
Timothy Stack committed
359
360
361
362
363
#
# This class implements the server side of the XMLRPC interface to emulab as a
# whole.
#
class emulab:
364
365
366
367
368
369
    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
370
        self.VERSION  = VERSION
Timothy Stack's avatar
   
Timothy Stack committed
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
408
409
410
411
412
413
414
415
416
417
418
419
        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"
420
            pass
Timothy Stack's avatar
   
Timothy Stack committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
            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(
446
                time.strptime(str(res[2]), "%Y-%m-%d %H:%M:%S"))
Timothy Stack's avatar
   
Timothy Stack committed
447
            tmp["msgid"] = res[3]
Timothy Stack's avatar
   
Timothy Stack committed
448
            
Timothy Stack's avatar
   
Timothy Stack committed
449
450
451
452
453
454
            result.append(tmp)
            pass

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

Timothy Stack's avatar
   
Timothy Stack committed
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
    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
479
480
481
482
483
484
485
486
487
    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
488
489
490
        result = DBQuery("select * from cameras where building=%s",
                        (argdict["area"],),
                        asDict=True)
Timothy Stack's avatar
   
Timothy Stack committed
491
        
Timothy Stack's avatar
   
Timothy Stack committed
492
        if len(result) == 0:
Timothy Stack's avatar
   
Timothy Stack committed
493
494
495
            return EmulabResponse(RESPONSE_ERROR,
                                  output="Unknown area " + argdict["area"])

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

Timothy Stack's avatar
   
Timothy Stack committed
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
527
528
529
530
531
532
533
534
535
536
537
538
        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
539
            scrubdict(ob)
Timothy Stack's avatar
   
Timothy Stack committed
540
541
542
543
544
            pass
        
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=res,
                              output=str(res))
Timothy Stack's avatar
   
Timothy Stack committed
545
546
547
548
549
550
551
552
553
    
    pass


#
# This class implements the server side of the XMLRPC interface to user
# specific information.
#
class user:
554
555
556
557
558
559
    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
560
        self.VERSION  = VERSION
Timothy Stack's avatar
   
Timothy Stack committed
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
        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'",
585
            (self.uid,))
Timothy Stack's avatar
   
Timothy Stack committed
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
621
622
623
624
625
626
627
628
629
630
631
632

        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 "
633
                           "WHERE uid_idx=%s and "
Timothy Stack's avatar
   
Timothy Stack committed
634
635
                           + trust_clause
                           + " ORDER BY pid",
636
                           (self.uid_idx,))
Timothy Stack's avatar
   
Timothy Stack committed
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655

        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))

656
657
658
659
660
661
662
663
664
665
666
667
668
669
    #
    # 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))

670
671
        res = DBQueryFatal("select mailman_password from users where uid_idx=%s",
                           (self.uid_idx,))
672
673
674
675
676
677

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

        passwd = res[0][0]
678
        return EmulabResponse(RESPONSE_SUCCESS, value=passwd, output=passwd)
679

Timothy Stack's avatar
   
Timothy Stack committed
680
681
682
683
684
685
686
687
    pass


#
# This class implements the server side of the XMLRPC interface to the emulab
# NFS exports.
#
class fs:
688
689
690
691
692
693
    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
694
        self.VERSION  = VERSION
Timothy Stack's avatar
   
Timothy Stack committed
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
829
830
831
832
833
834
835
836
837
838
839
840
        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 = [
841
            USERSROOT + "/" + self.uid, # XXX Use getpwuid() and handle admin
Timothy Stack's avatar
   
Timothy Stack committed
842
843
844
845
846
            SHAREROOT,
            ]

        # ... add the project/group listings.
        projs = DBQueryFatal("SELECT distinct pid,gid FROM group_membership "
847
848
                             "WHERE uid_idx=%s and trust!='none' ORDER BY pid",
                             (self.uid_idx,))
Timothy Stack's avatar
   
Timothy Stack committed
849
850
851
852

        for proj in projs:
            if proj[0] == proj[1]:
                res.append(PROJROOT + "/" + proj[0])
853
854
855
                if not SCRATCHROOT == "":
                    res.append(SCRATCHROOT + "/" + proj[0])
                    pass
Timothy Stack's avatar
   
Timothy Stack committed
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
                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:
873
874
875
876
877
878
    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
879
        self.VERSION  = VERSION
Timothy Stack's avatar
   
Timothy Stack committed
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
        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(
895
            "SELECT distinct i.imagename,v.description FROM images as i "
896
897
            "left join image_versions as v on "
            "     v.imageid=o.imageid and v.version=i.version "
Timothy Stack's avatar
   
Timothy Stack committed
898
            "left join group_membership as g on g.pid=i.pid "
899
            "WHERE g.uid_idx=%s or v.global",
900
            (self.uid_idx,))
Timothy Stack's avatar
   
Timothy Stack committed
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926

        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:
927
928
929
930
931
932
    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
933
        self.VERSION  = VERSION
Timothy Stack's avatar
   
Timothy Stack committed
934
935
936
937
938
939
940
941
942
943
944
945
946
947
        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
948
949
        res = DBQueryFatal("SELECT distinct v.* FROM os_info as o "
                           "left join os_info_versions as v on "
Leigh B Stoller's avatar
Leigh B Stoller committed
950
                           "     v.osid=o.osid and v.vers=o.version "
Timothy Stack's avatar
   
Timothy Stack committed
951
                           "left join group_membership as g on g.pid=o.pid "
952
953
                           "where (g.uid_idx=%s or v.shared=1) "
                           "group by o.pid,o.osname",
954
                           (self.uid_idx,),
Timothy Stack's avatar
   
Timothy Stack committed
955
                           True)
Timothy Stack's avatar
   
Timothy Stack committed
956
957
958
959
960
961
962
963

        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
964
965
966
            # XXX Legacy stuff...
            osid["fullosid"] = osid["osid"]
            osid["osid"] = osid["osname"]
Timothy Stack's avatar
   
Timothy Stack committed
967

968
            if not osid.has_key("OS") or len(osid["OS"]) == 0:
Timothy Stack's avatar
   
Timothy Stack committed
969
970
971
972
973
974
                osid["OS"] = "(None)"
                pass

            result[osid["osid"]] = scrubdict(osid)
            pass
        
Timothy Stack's avatar
   
Timothy Stack committed
975
976
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=result,
Timothy Stack's avatar
   
Timothy Stack committed
977
                              output="")
Timothy Stack's avatar
   
Timothy Stack committed
978
979
980
981
982
983
984
    
    def info(self, version, argdict):
        # Check for valid arguments.
        argerror = CheckRequiredArgs(argdict, ("osid",))
        if (argerror):
            return argerror

985
        if not re.match("^[-\w\.]*$", argdict["osid"]):
Timothy Stack's avatar
   
Timothy Stack committed
986
987
988
989
            return EmulabResponse(RESPONSE_BADARGS,
                                  output="Improperly formed osid!")

        # Get the listing that is accessible to this user and
990
        res = DBQueryFatal("SELECT distinct v.* FROM os_info as o "
991
                           "left join os_info_versions as v on "
Leigh B Stoller's avatar
Leigh B Stoller committed
992
                           "     v.osid=o.osid and v.vers=o.version "
Timothy Stack's avatar
   
Timothy Stack committed
993
                           "left join group_membership as g on g.pid=o.pid "
994
995
996
                           "where (g.uid_idx=%s or v.shared=1) and "
                           "      (o.osname=%s or o.osid=%s) "
                           "group by o.pid,o.osname",
997
                           (self.uid_idx, argdict["osid"], argdict["osid"]),
Timothy Stack's avatar
   
Timothy Stack committed
998
999
1000
1001
1002
1003
1004
1005
1006
1007
                           True)

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

        osid = res[0]
        osid["fullosid"] = osid["osid"]
        osid["osid"] = osid["osname"]
        
1008
        if not osid.has_key("OS") or len(osid["OS"]) == 0:
Timothy Stack's avatar
   
Timothy Stack committed
1009
1010
            osid["OS"] = "(None)"
            pass
1011

Timothy Stack's avatar
   
Timothy Stack committed
1012
1013
1014
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=scrubdict(osid),
                              output=str(osid))
Timothy Stack's avatar
   
Timothy Stack committed
1015
1016
1017

    pass

1018

1019
1020
1021
1022
#
# This class implements the server side of the XMLRPC interface to experiments.
#
class experiment:
1023
1024
1025
    ##
    # Initialize the object.  Currently only sets the objects 'VERSION' value.
    #
1026
1027
1028
1029
1030
1031
    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
1032
        self.VERSION  = VERSION
1033
1034
1035
1036
1037
1038
1039
1040
1041
        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):
1042
        if not argdict.has_key("str"):
1043
            return EmulabResponse(RESPONSE_BADARGS,
Timothy Stack's avatar
   
Timothy Stack committed
1044
                                  output="Must supply a string to echo!")
1045
        
1046
        return EmulabResponse(RESPONSE_SUCCESS, 0,
1047
1048
                             socket.gethostname() + ": " + str(version)
                             + " " + argdict["str"])
1049

Timothy Stack's avatar
   
Timothy Stack committed
1050
1051
1052
1053
1054
1055
1056
1057
    #
    # 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!")

1058
1059
1060
1061
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar
   
Timothy Stack committed
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
        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!")
        
1085
1086
1087
1088
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar
   
Timothy Stack committed
1089
1090
1091
1092
1093
1094
        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

1095
1096
1097
1098
1099
1100
1101
1102
        # 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
1103
        # XXX Let the user specify the pid/gid
1104
        dbres = DBQueryFatal("SELECT e.pid,e.gid,e.eid,e.expt_name,e.state,"
Timothy Stack's avatar
   
Timothy Stack committed
1105
1106
                             "e.expt_head_uid,e.minimum_nodes,e.maximum_nodes,"
                             "count(r.node_id) as actual_nodes "
1107
                             "  FROM experiments AS e "
Timothy Stack's avatar
   
Timothy Stack committed
1108
1109
1110
1111
                             "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",
1112
                             (self.uid,))
Timothy Stack's avatar
   
Timothy Stack committed
1113
1114
1115
1116
1117

        # 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:
1118
1119
1120
1121
1122
1123
1124
            # 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
1125
1126
1127
            minimum_nodes = res[6]
            maximum_nodes = res[7]
            actual_nodes = res[8]
1128
1129
1130
1131
            # ... make sure 'result' has the proper slots,
            if not result.has_key(pid):
                result[pid] = {
                    gid : list()
Timothy Stack's avatar
   
Timothy Stack committed
1132
1133
                    }
                pass
1134
1135
            elif not result[pid].has_key(gid):
                result[pid][gid] = list()
Timothy Stack's avatar
   
Timothy Stack committed
1136
                pass
1137
1138
1139
1140
1141
1142
1143

            # ... drop the data into place, and
            expdata = None
            if format == "brief":
                expdata = eid;
                pass
            elif format == "full":
1144
                expdata = scrubdict({
1145
1146
1147
1148
1149
1150
                    "pid" : pid,
                    "gid" : gid,
                    "name" : eid,
                    "description" : desc,
                    "state" : state,
                    "expt_head" : expt_head,
Timothy Stack's avatar
   
Timothy Stack committed
1151
1152
1153
                    "minimum_nodes" : minimum_nodes,
                    "maximum_nodes" : maximum_nodes,
                    "actual_nodes" : actual_nodes,
1154
                    })
Timothy Stack's avatar
   
Timothy Stack committed
1155
                pass
1156
1157

            # ... append it to the group list.
1158
            result[pid][gid].append(expdata)
Timothy Stack's avatar
   
Timothy Stack committed
1159
1160
1161
1162
1163
1164
            pass
        
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=result,
                              output=str(result))

1165
1166
1167
1168
1169
1170
    #
    # 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:
1171
            return EmulabResponse(RESPONSE_BADVERSION,
Timothy Stack's avatar
   
Timothy Stack committed
1172
1173
                                  output="Client version mismatch!")

1174
1175
1176
1177
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar
   
Timothy Stack committed
1178
1179
        try:
            checknologins()
1180
            pass
Timothy Stack's avatar
   
Timothy Stack committed
1181
1182
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))
1183

1184
1185
1186
        argerror = CheckRequiredArgs(argdict, ("proj", "exp"))
        if (argerror):
            return argerror
1187

1188
        nsfilename = None
1189
        argstr     = "-q -R"
1190
	extrainfo  = False
1191
1192
        
        for opt, val in argdict.items():
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1193
            if opt == "batch":
Timothy Stack's avatar
   
Timothy Stack committed
1194
                if not xbool(val):
1195
1196
1197
                    argstr += " -i"
                    pass
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1198
            elif opt == "description":
1199
                argstr += " -E "
1200
                argstr += escapeshellarg(val)
1201
                pass
1202
            elif opt == "group":
1203
                argstr += " -g "
1204
                argstr += escapeshellarg(val)
1205
                pass
1206
            elif opt == "exp":
1207
                argstr += " -e "
1208
                argstr += escapeshellarg(val)
1209
                pass
1210
            elif opt == "proj":
1211
                argstr += " -p "
1212
                argstr += escapeshellarg(val)
1213
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1214
            elif opt == "swappable":
Timothy Stack's avatar
   
Timothy Stack committed
1215
                if not xbool(val):
1216
1217
1218
                    if not argdict.has_key("noswap_reason"):
                        return EmulabResponse(RESPONSE_BADARGS,
                                       output="Must supply noswap reason!");
1219
                    argstr += " -S "
1220
                    argstr += escapeshellarg(argdict["noswap_reason"])
1221
1222
                    pass
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1223
            elif opt == "noswap_reason":
1224
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1225
            elif opt == "idleswap":
1226
                if val == 0:
1227
1228
1229
                    if not argdict.has_key("noidleswap_reason"):
                        return EmulabResponse(RESPONSE_BADARGS,
                                      output="Must supply noidleswap reason!");
1230
                    argstr += " -L "
1231
                    argstr += escapeshellarg(argdict["noidleswap_reason"])
1232
1233
1234
                    pass
                else:
                    argstr += " -l "
Timothy Stack's avatar
   
Timothy Stack committed
1235
                    argstr += escapeshellarg(str(val))
1236
1237
                    pass
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1238
            elif opt == "noidleswap_reason":
1239
                pass
1240
            elif opt == "autoswap" or opt == "max_duration":
1241
                argstr += " -a "
Timothy Stack's avatar
   
Timothy Stack committed
1242
                argstr += escapeshellarg(str(val))
1243
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1244
            elif opt == "noswapin":
Timothy Stack's avatar
   
Timothy Stack committed
1245
                if xbool(val):
1246
1247
                    argstr += " -f "
                    pass
1248
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1249
            elif opt == "wait":
Timothy Stack's avatar
   
Timothy Stack committed
1250
                if xbool(val):
1251
1252
                    argstr += " -w "
                    pass
1253
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1254
            elif opt == "nsfilepath":
1255
                # Backend script will verify this local path. 
1256
                nsfilename = escapeshellarg(val)
1257
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1258
            elif opt == "nsfilestr":
1259
1260
1261
                nsfilestr = val
            
                if len(nsfilestr) > (1024 * 512):
1262
                    return EmulabResponse(RESPONSE_TOOBIG,
1263
                                         output="NS File way too big!");
1264
1265
1266
        
                (nsfp, nsfilename) = writensfile(nsfilestr)
                if not nsfilename:
1267
                    return EmulabResponse(RESPONSE_SERVERERROR,
1268
                                         output="Server Error")
1269
                pass
1270
1271
1272
1273
1274
            elif opt == "noemail":
                if xbool(val):
                    argstr += " -N "
                    pass
                pass
1275
1276
1277
1278
1279
1280
	    elif opt == "extrainfo":
		if xbool(val):
		    argstr += " -X "
		    extrainfo = True
		    pass
                pass
1281
            pass
1282
1283


1284
        if nsfilename:
1285
            argstr += " " + nsfilename
1286
1287
            pass

1288
1289
        (exitval, output, errout) = runcommand(TBDIR + "/bin/batchexp " + argstr, 
                                               separate_stderr=extrainfo);
1290
        if exitval:
1291
1292
1293
1294
	    if extrainfo:
		try:
		    value = xmlrpclib.loads(output)[0][0]
		except:
1295
		    output = errout + output
1296
1297
1298
1299
		    return EmulabResponse(RESPONSE_ERROR, exitval >> 8, output=output)
		value["exitval"] = exitval >> 8
		output = value["output"]
		del value["output"]
1300
		value["errout"] = errout
1301
1302
1303
		return EmulabResponse(RESPONSE_ERROR, value, output=output)
	    else:
            	return EmulabResponse(RESPONSE_ERROR, exitval >> 8, output=output)
1304
        
1305
        return EmulabResponse(RESPONSE_SUCCESS, output=output)
1306
1307
1308
1309
1310
1311

    #
    # startexp is an alias for batchexp.
    # 
    def startexp(self, version, argdict):
        return self.batchexp(version, argdict)
1312

1313
1314
1315
1316
1317
1318
    #
    # swap an experiment using swapexp. 
    #
    def swapexp(self, version, argdict):
        if version != self.VERSION:
            return EmulabResponse(RESPONSE_BADVERSION,
Timothy Stack's avatar
   
Timothy Stack committed
1319
1320
                                  output="Client version mismatch!")

1321
1322
1323
1324
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar
   
Timothy Stack committed
1325
1326
        try:
            checknologins()
1327
            pass
Timothy Stack's avatar
   
Timothy Stack committed
1328
1329
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))
1330

1331
1332
1333
1334
        argerror = CheckRequiredArgs(argdict, ("proj", "exp", "direction"))
        if (argerror):
            return argerror

1335
1336
1337
        #
        # Check permission. This will check proj/exp for illegal chars.
        #
1338
        permerror = CheckExptPermission(self.uid_idx,
1339
                                        argdict["proj"], argdict["exp"])
1340
1341
1342
1343
1344
1345
1346
1347
        if (permerror):
            return permerror

        if not (argdict["direction"] == "in" or
                argdict["direction"] == "out"):
            return EmulabResponse(RESPONSE_BADARGS,
                                  output="direction must be 'in' or 'out'");

1348
        argstr = "-q"
1349
1350
	extrainfo = False

1351
        for opt, val in argdict.items():
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1352
            if opt == "wait":
Timothy Stack's avatar
   
Timothy Stack committed
1353
                if xbool(val):
1354
1355
1356
                    argstr += " -w "
                    pass
                pass
1357
1358
1359
1360
1361
            elif opt == "noemail":
                if xbool(val):
                    argstr += " -N "
                    pass
                pass
1362
1363
1364
1365
1366
1367
	    elif opt == "extrainfo":
		if xbool(val):
		    argstr += " -X "
		    extrainfo = True
		    pass
                pass
1368
1369
1370
            pass

        argstr += " -s " + escapeshellarg(argdict["direction"])
1371
1372
        argstr += " " + escapeshellarg(argdict["proj"])
        argstr += " " + escapeshellarg(argdict["exp"])
1373

1374
1375
        (exitval, output, errout) = runcommand(TBDIR + "/bin/swapexp " + argstr,
                                               separate_stderr=extrainfo);
1376
        if exitval:
1377
1378
1379
1380
	    if extrainfo:
		try:
		    value = xmlrpclib.loads(output)[0][0]
		except:
1381
		    output = errout + output
1382
1383
1384
1385
		    return EmulabResponse(RESPONSE_ERROR, exitval >> 8, output=output)
		value["exitval"] = exitval >> 8
		output = value["output"]
		del value["output"]
1386
		value["errout"] = errout
1387
1388
1389
		return EmulabResponse(RESPONSE_ERROR, value, output=output)
	    else:
            	return EmulabResponse(RESPONSE_ERROR, exitval >> 8, output=output)
1390
1391
1392
        
        return EmulabResponse(RESPONSE_SUCCESS, output=output)

1393
    #
Timothy Stack's avatar
   
Timothy Stack committed
1394
    # modify an experiment using swapexp. We get the NS file inline, which
1395
1396
    # we have to write to a temp file first. 
    #
1397
    def modify(self, version, argdict):
1398
        if version != self.VERSION:
1399
            return EmulabResponse(RESPONSE_BADVERSION,
Timothy Stack's avatar
   
Timothy Stack committed
1400
1401
                                  output="Client version mismatch!")

1402
1403
1404
1405
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar