emulabserver.py.in 98 KB
Newer Older
1
2
3
4
5
6
7
8
9
#! /usr/bin/env python
#
# EMULAB-COPYRIGHT
# Copyright (c) 2004 University of Utah and the Flux Group.
# 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
14
import popen2
import tempfile
import time
15
16
import re
import string
Timothy Stack's avatar
   
Timothy Stack committed
17
18
19
20
import pwd
import grp
import errno
import exceptions
21
import xmlrpclib
22
import signal
23
import types
24
import datetime
25
sys.path.append("@prefix@/lib")
26
from libdb        import *
27
from libtestbed   import SENDMAIL, TBOPS
28
from emulabclient import *
29
30
31

# Configure variables
TBDIR = "@prefix@"
32
BOSSNODE = "@BOSSNODE@"
33
BOSSEVENTPORT = "@BOSSEVENTPORT@"
34

35
36
37
# Version
VERSION = 0.1

Timothy Stack's avatar
   
Timothy Stack committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Well known directories
PROJROOT = "/proj"
GROUPROOT = "/groups"
SHAREROOT = "/share"
USERSROOT = "/users"

# List of directories exported to nodes via NFS.
NFS_EXPORTS = [
    PROJROOT,
    GROUPROOT,
    SHAREROOT,
    USERSROOT,
    ]

52
53
54
55
56
57
58
59
60
61
62
63
64
65
#
# 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" ]},
66
67
68
    "virt_lan_lans"             : { "rows"  : None, 
                                    "tag"   : "lan_lans",
                                    "attrs" : [ "vname" ]},
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
    "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" ]},
    "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" ]},
    "nseconfigs"		: { "rows"  : None, 
                                    "tag"   : "nseconfigs",
                                    "attrs" : [ "vname" ]},
    "eventlist"                 : { "rows"  : None, 
                                    "tag"   : "events",
                                    "attrs" : [ "vname" ]}
    }
    
Timothy Stack's avatar
   
Timothy Stack committed
101
102
103
104
105
106
107
108
109
110
111
112
# 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

113
114
115
116
117
118
119
# Exception thrown when a timer expires.
class TimedOutError(EmulabError):
    pass

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

120
#
121
122
# 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
123
124
# pretty much any language should be able to talk to this class.
#
125

126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#
# 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

149
150
151
#
# Check user permission to access an experiment.
# 
152
def CheckExptPermission(uid, pid, eid):
153
154
155
156
157
    if not (re.match("^[-\w]*$", pid) and
            re.match("^[-\w]*$", eid)):
        return EmulabResponse(RESPONSE_BADARGS,
                  output="Illegal characters in project and/or experiment IDs!")
    
158
159
160
161
162
163
164
165
166
167
168
169
170
    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]
        
    res = DBQueryFatal("SELECT trust FROM group_membership "
                       "WHERE uid=%s and pid=%s and gid=%s",
171
                       (uid, pid, gid))
172
173
174
175
176
177
178

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

179
180
181
182
183
#
# This is a wrapper class so that you can invoke methods in dotted form.
# For example experiment.swapexp(...).
#
class EmulabServer:
184
185
    def __init__(self, readonly=0):
        self.readonly  = readonly;
186
        self.instances = {};
187
        self.uid       = pwd.getpwuid(os.getuid())[0]
188
189
190
191
192
193
194
195
196
197
198

        self.instances["experiment"] = experiment(readonly=self.readonly);
        if readonly:
            return
        
        self.instances["emulab"]     = emulab(readonly=self.readonly);
        self.instances["user"]       = user(readonly=self.readonly);
        self.instances["fs"]         = fs(readonly=self.readonly);
        self.instances["imageid"]    = imageid(readonly=self.readonly);
        self.instances["osid"]       = osid(readonly=self.readonly);
        self.instances["node"]       = node(readonly=self.readonly);
199
200
201
202
203
204
205
        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]):
206
            raise AttributeError("unknown method '%s'" % name)
207
208
209
210
        
        return getattr(self.instances[dotted[0]], dotted[1]);
    pass

Timothy Stack's avatar
   
Timothy Stack committed
211
212
213
214
215
#
# This class implements the server side of the XMLRPC interface to emulab as a
# whole.
#
class emulab:
216
217
218
    def __init__(self, readonly=0):
        self.readonly = readonly;
        self.VERSION  = VERSION
219
        self.uid      = pwd.getpwuid(os.getuid())[0]
Timothy Stack's avatar
   
Timothy Stack committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
        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)
            pass
        elif starting:
            comparison = "> %s"
            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(
295
                time.strptime(str(res[2]), "%Y-%m-%d %H:%M:%S"))
Timothy Stack's avatar
   
Timothy Stack committed
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
            tmp["msgid"] = res[3]
            result.append(tmp)
            pass

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


#
# This class implements the server side of the XMLRPC interface to user
# specific information.
#
class user:
312
313
314
    def __init__(self, readonly=0):
        self.readonly = readonly;
        self.VERSION  = VERSION
315
        self.uid      = pwd.getpwuid(os.getuid())[0]
Timothy Stack's avatar
   
Timothy Stack committed
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
        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'",
340
            (self.uid,))
Timothy Stack's avatar
   
Timothy Stack committed
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
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

        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 "
                           "WHERE uid=%s and "
                           + trust_clause
                           + " ORDER BY pid",
391
                           (self.uid,))
Timothy Stack's avatar
   
Timothy Stack committed
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

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

    pass


#
# This class implements the server side of the XMLRPC interface to the emulab
# NFS exports.
#
class fs:
419
420
421
    def __init__(self, readonly=0):
        self.readonly = readonly;
        self.VERSION  = VERSION
422
        self.uid      = pwd.getpwuid(os.getuid())[0]
Timothy Stack's avatar
   
Timothy Stack committed
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
        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 = [
569
            USERSROOT + "/" + self.uid, # XXX Use getpwuid() and handle admin
Timothy Stack's avatar
   
Timothy Stack committed
570
571
572
573
574
575
            SHAREROOT,
            ]

        # ... add the project/group listings.
        projs = DBQueryFatal("SELECT distinct pid,gid FROM group_membership "
                             "WHERE uid=%s and trust!='none' ORDER BY pid",
576
                             (self.uid,))
Timothy Stack's avatar
   
Timothy Stack committed
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597

        for proj in projs:
            if proj[0] == proj[1]:
                res.append(PROJROOT + "/" + proj[0])
                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:
598
599
600
    def __init__(self, readonly=0):
        self.readonly = readonly;
        self.VERSION  = VERSION
601
        self.uid      = pwd.getpwuid(os.getuid())[0]
Timothy Stack's avatar
   
Timothy Stack committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
        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 "
            "WHERE g.uid=%s or i.global",
620
            (self.uid,))
Timothy Stack's avatar
   
Timothy Stack committed
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646

        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:
647
648
649
    def __init__(self, readonly=0):
        self.readonly = readonly;
        self.VERSION  = VERSION
650
        self.uid      = pwd.getpwuid(os.getuid())[0]
Timothy Stack's avatar
   
Timothy Stack committed
651
652
653
654
655
656
657
658
659
660
661
662
663
664
        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
665
666
        res = DBQueryFatal("SELECT distinct "
                           "o.osname,o.pid,o.description,o.OS FROM "
Timothy Stack's avatar
   
Timothy Stack committed
667
668
669
                           "os_info as o "
                           "left join group_membership as g on g.pid=o.pid "
                           "where g.uid=%s or o.shared=1",
670
                           (self.uid,))
Timothy Stack's avatar
   
Timothy Stack committed
671
672
673
674
675
676
677
678
679
680

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

        # ... package it up.
        result = {}
        for osid in res:
            tmp = {
                "osid" : osid[0],
681
682
683
                "pid" : osid[1],
                "description" : osid[2],
                "OS" : osid[3],
Timothy Stack's avatar
   
Timothy Stack committed
684
685
686
687
688
689
690
691
692
693
                }
            result[osid[0]] = tmp
            pass

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

    pass

694

695
696
697
698
#
# This class implements the server side of the XMLRPC interface to experiments.
#
class experiment:
699
700
701
    ##
    # Initialize the object.  Currently only sets the objects 'VERSION' value.
    #
702
703
704
    def __init__(self, readonly=0):
        self.readonly = readonly;
        self.VERSION  = VERSION
705
        self.uid      = pwd.getpwuid(os.getuid())[0]
706
707
708
709
710
711
712
713
714
        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):
715
        if not argdict.has_key("str"):
716
            return EmulabResponse(RESPONSE_BADARGS,
Timothy Stack's avatar
   
Timothy Stack committed
717
                                  output="Must supply a string to echo!")
718
        
719
        return EmulabResponse(RESPONSE_SUCCESS, 0,
720
721
                             socket.gethostname() + ": " + str(version)
                             + " " + argdict["str"])
722

Timothy Stack's avatar
   
Timothy Stack committed
723
724
725
726
727
728
729
730
    #
    # 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!")

731
732
733
734
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar
   
Timothy Stack committed
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
        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!")
        
758
759
760
761
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar
   
Timothy Stack committed
762
763
764
765
766
767
        try:
            checknologins()
            pass
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))

768
769
770
771
772
773
774
775
        # 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
776
        # XXX Let the user specify the pid/gid
777
778
779
780
        dbres = DBQueryFatal("SELECT e.pid,e.gid,e.eid,e.expt_name,e.state,"
                             "e.expt_head_uid "
                             "  FROM experiments AS e "
                             "WHERE e.expt_head_uid=%s",
781
                             (self.uid,))
Timothy Stack's avatar
   
Timothy Stack committed
782
783
784
785
786

        # 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:
787
788
789
790
791
792
793
794
795
796
797
            # 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]
            # ... make sure 'result' has the proper slots,
            if not result.has_key(pid):
                result[pid] = {
                    gid : list()
Timothy Stack's avatar
   
Timothy Stack committed
798
799
                    }
                pass
800
801
            elif not result[pid].has_key(gid):
                result[pid][gid] = list()
Timothy Stack's avatar
   
Timothy Stack committed
802
                pass
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817

            # ... drop the data into place, and
            expdata = None
            if format == "brief":
                expdata = eid;
                pass
            elif format == "full":
                expdata = {
                    "pid" : pid,
                    "gid" : gid,
                    "name" : eid,
                    "description" : desc,
                    "state" : state,
                    "expt_head" : expt_head,
                    }
Timothy Stack's avatar
   
Timothy Stack committed
818
                pass
819
820
821

            # ... append it to the group list.
            result[pid][gid].append(expdata)
Timothy Stack's avatar
   
Timothy Stack committed
822
823
824
825
826
827
            pass
        
        return EmulabResponse(RESPONSE_SUCCESS,
                              value=result,
                              output=str(result))

828
829
830
831
832
833
    #
    # 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:
834
            return EmulabResponse(RESPONSE_BADVERSION,
Timothy Stack's avatar
   
Timothy Stack committed
835
836
                                  output="Client version mismatch!")

837
838
839
840
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar
   
Timothy Stack committed
841
842
        try:
            checknologins()
843
            pass
Timothy Stack's avatar
   
Timothy Stack committed
844
845
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))
846

847
848
849
        argerror = CheckRequiredArgs(argdict, ("proj", "exp"))
        if (argerror):
            return argerror
850

851
        nsfilename = None
852
        argstr     = "-q"
853
854
        
        for opt, val in argdict.items():
Leigh B. Stoller's avatar
Leigh B. Stoller committed
855
            if opt == "batch":
Timothy Stack's avatar
   
Timothy Stack committed
856
                if not xbool(val):
857
858
859
                    argstr += " -i"
                    pass
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
860
            elif opt == "description":
861
                argstr += " -E "
862
                argstr += escapeshellarg(val)
863
                pass
864
            elif opt == "group":
865
                argstr += " -g "
866
                argstr += escapeshellarg(val)
867
                pass
868
            elif opt == "exp":
869
                argstr += " -e "
870
                argstr += escapeshellarg(val)
871
                pass
872
            elif opt == "proj":
873
                argstr += " -p "
874
                argstr += escapeshellarg(val)
875
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
876
            elif opt == "swappable":
Timothy Stack's avatar
   
Timothy Stack committed
877
                if not xbool(val):
878
879
880
                    if not argdict.has_key("noswap_reason"):
                        return EmulabResponse(RESPONSE_BADARGS,
                                       output="Must supply noswap reason!");
881
                    argstr += " -S "
882
                    argstr += escapeshellarg(argdict["noswap_reason"])
883
884
                    pass
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
885
            elif opt == "noswap_reason":
886
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
887
            elif opt == "idleswap":
888
                if val == 0:
889
890
891
                    if not argdict.has_key("noidleswap_reason"):
                        return EmulabResponse(RESPONSE_BADARGS,
                                      output="Must supply noidleswap reason!");
892
                    argstr += " -L "
893
                    argstr += escapeshellarg(argdict["noidleswap_reason"])
894
895
896
                    pass
                else:
                    argstr += " -l "
Timothy Stack's avatar
   
Timothy Stack committed
897
                    argstr += escapeshellarg(str(val))
898
899
                    pass
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
900
            elif opt == "noidleswap_reason":
901
                pass
902
            elif opt == "autoswap" or opt == "max_duration":
903
                argstr += " -a "
Timothy Stack's avatar
   
Timothy Stack committed
904
                argstr += escapeshellarg(str(val))
905
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
906
            elif opt == "noswapin":
Timothy Stack's avatar
   
Timothy Stack committed
907
                if xbool(val):
908
909
                    argstr += " -f "
                    pass
910
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
911
            elif opt == "wait":
Timothy Stack's avatar
   
Timothy Stack committed
912
                if xbool(val):
913
914
                    argstr += " -w "
                    pass
915
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
916
            elif opt == "nsfilepath":
917
                # Backend script will verify this local path. 
918
                nsfilename = escapeshellarg(val)
919
                pass
Leigh B. Stoller's avatar
Leigh B. Stoller committed
920
            elif opt == "nsfilestr":
921
922
923
                nsfilestr = val
            
                if len(nsfilestr) > (1024 * 512):
924
                    return EmulabResponse(RESPONSE_TOOBIG,
925
                                         output="NS File way too big!");
926
927
928
        
                (nsfp, nsfilename) = writensfile(nsfilestr)
                if not nsfilename:
929
                    return EmulabResponse(RESPONSE_SERVERERROR,
930
                                         output="Server Error")
931
932
933
934
                pass
            pass

        if nsfilename:
935
            argstr += " " + nsfilename
936
937
938
            pass

        (exitval, output) = runcommand(TBDIR + "/bin/batchexp " + argstr)
939
        if exitval:
940
            return EmulabResponse(RESPONSE_ERROR, exitval >> 8, output=output)
941
        
942
        return EmulabResponse(RESPONSE_SUCCESS, output=output)
943
944
945
946
947
948

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

950
951
952
953
954
955
    #
    # 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
956
957
                                  output="Client version mismatch!")

958
959
960
961
        if self.readonly:
            return EmulabResponse(RESPONSE_FORBIDDEN,
                              output="Insufficient privledge to invoke method")
        
Timothy Stack's avatar
   
Timothy Stack committed
962
963
        try:
            checknologins()
964
            pass
Timothy Stack's avatar
   
Timothy Stack committed
965
966
        except NoLoginsError, e:
            return EmulabResponse(RESPONSE_REFUSED, output=str(e))
967

968
969
970
971
        argerror = CheckRequiredArgs(argdict, ("proj", "exp", "direction"))
        if (argerror):
            return argerror

972
973
974
        #
        # Check permission. This will check proj/exp for illegal chars.
        #
975
976
        permerror = CheckExptPermission(self.uid,
                                        argdict["proj"], argdict["exp"])
977
978
979
980
981
982
983
984
        if (permerror):
            return permerror

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

985
        argstr = "-q"
986
        for opt, val in argdict.items():
Leigh B. Stoller's avatar
Leigh B. Stoller committed
987
            if opt == "wait":
Timothy Stack's avatar
   
Timothy Stack committed
988
                if xbool(val):
989
990
991
992
993
994
                    argstr += " -w "
                    pass
                pass
            pass

        argstr += " -s " + escapeshellarg(argdict["direction"])
995
996
        argstr += " " + escapeshellarg(argdict["proj"])
        argstr += " " + escapeshellarg(argdict["exp"])
997
998
999
1000

        (exitval, output) = runcommand(TBDIR + "/bin/swapexp " + argstr)
        if exitval:
            return EmulabResponse(RESPONSE_ERROR, exitval >> 8, output=output)
For faster browsing, not all history is shown. View entire blame