source: fedd/fedd_client.py @ eaa530c

axis_examplecompt_changesinfo-opsversion-3.01version-3.02
Last change on this file since eaa530c was eaa530c, checked in by Ted Faber <faber@…>, 14 years ago

whoops, some more cl;eanup

  • Property mode set to 100755
File size: 60.6 KB
Line 
1#!/usr/local/bin/python
2
3import sys
4import os
5import pwd
6import tempfile
7import subprocess
8import re
9import xml.parsers.expat
10import time
11
12from federation import fedid, service_error
13from federation.util import fedd_ssl_context, pack_id, unpack_id
14from federation.remote_service import service_caller
15from federation import topdl
16
17from optparse import OptionParser, OptionValueError
18
19
20class IDFormatException(RuntimeError): pass
21
22class access_method:
23    """Encapsulates an access method generically."""
24    (type_ssh, type_x509, type_pgp) = ('sshPubkey', 'X509', 'pgpPubkey')
25    default_type = type_ssh
26    def __init__(self, buf=None, type=None, file=None):
27        self.buf = buf
28
29        if type != None: self.type = type
30        else: self.type = access_method.default_type
31
32        if file != None:
33            self.readfile(file)
34   
35    def readfile(self, file, type=None):
36        f = open(file, "r")
37        self.buf = f.read();
38        f.close()
39        if type == None:
40            if self.type == None:
41                self.type = access_method.default_type
42        else:
43            self.type = type;
44   
45class node_desc:
46    def __init__(self, image, hardware, count=1):
47        if getattr(image, "__iter__", None) == None:
48            if image == None: self.image = [ ]
49            else: self.image = [ image ]
50        else:
51            self.image = image
52
53        if getattr(hardware, "__iter__", None) == None: 
54            if hardware == None: self.hardware = [ ]
55            else: self.hardware = [ hardware ]
56        else:
57            self.hardware = hardware
58        if count != None: self.count = int(count)
59        else: self.count = 1
60
61class fedd_client_opts(OptionParser):
62    """Encapsulate option processing in this class, rather than in main"""
63    def __init__(self):
64        OptionParser.__init__(self, usage="%prog [opts] (--help for details)",
65                version="0.1")
66
67        self.add_option("--cert", action="store", dest="cert",
68                type="string", help="my certificate file")
69        self.add_option( "--debug", action="count", dest="debug", 
70                default=0, help="Set debug.  Repeat for more information")
71        self.add_option("--serializeOnly", action="store_true", 
72                dest="serialize_only", default=False,
73                help="Print the SOAP request that would be sent and exit")
74        self.add_option("--trusted", action="store", dest="trusted",
75                type="string", help="Trusted certificates (required)")
76        self.add_option("--url", action="store", dest="url",
77                type="string",default="https://localhost:23235", 
78                help="URL to connect to (default %default)")
79        self.add_option("--transport", action="store", type="choice",
80                choices=("xmlrpc", "soap"), default="soap",
81                help="Transport for request (xmlrpc|soap) (Default: %default)")
82        self.add_option("--trace", action="store_const", dest="tracefile", 
83                const=sys.stderr, help="Print SOAP exchange to stderr")
84class fedd_new_opts(fedd_client_opts):
85    def __init__(self):
86        fedd_client_opts.__init__(self)
87        self.add_option("--experiment_cert", dest="out_certfile",
88                type="string", help="output certificate file")
89        self.add_option("--experiment_name", dest="exp_name",
90                type="string", help="Suggested experiment name")
91
92class fedd_create_opts(fedd_new_opts):
93    def __init__(self):
94        fedd_new_opts.__init__(self)
95        self.add_option("--file", dest="file", 
96                help="experiment description file")
97        self.add_option("--project", action="store", dest="project", 
98                type="string",
99                help="Project to export from master")
100        self.add_option("--master", dest="master",
101                help="Master testbed in the federation")
102
103class fedd_split_opts(fedd_create_opts):
104    def __init__(self ):
105        fedd_create_opts.__init__(self)
106        self.add_option('--fedkit', action='store_true', dest='fedkit',
107                default=False,
108                help="get output suitable for federation kit install")
109        self.add_option('--gatewaykit', action='store_true',
110                dest='gatewaykit', default=False,
111                help="get output suitable for federation gateway kit install")
112
113
114class fedd_access_opts(fedd_create_opts):
115    def __init__(self):
116        fedd_create_opts.__init__(self)
117        self.add_option("--label", action="store", dest="label",
118                type="string", help="Label for output")
119        if add_node_callback:
120            self.add_option("--node", action="callback", type="string", 
121                    callback=add_node_callback, callback_args=(node_descs,),
122                    help="Node description: image:hardware[:count]")
123        self.add_option("--testbed", action="store", dest="testbed",
124                type="string",
125                help="Testbed identifier (URI) to contact (required)")
126
127class fedd_exp_data_opts(fedd_client_opts):
128    def __init__(self):
129        fedd_client_opts.__init__(self)
130        self.add_option("--experiment_cert", dest="exp_certfile",
131                type="string", help="experiment certificate file")
132        self.add_option("--experiment_name", dest="exp_name",
133                type="string", help="human readable experiment name")
134        self.add_option("--data", dest="data", default=[],
135                action="append", type="choice",
136                choices=("id", "federant", "vtopo", "vis", "log", "status"),
137                help="data to extract")
138
139class fedd_terminate_opts(fedd_exp_data_opts):
140    def __init__(self):
141        fedd_exp_data_opts.__init__(self)
142        self.add_option("--force", dest="force",
143                action="store_true", default=False,
144                help="Force termination if experiment is in strange state")
145        self.add_option("--logfile", dest="logfile", default=None,
146                help="File to write log to")
147        self.add_option("--print_log", dest="print_log", default=False,
148                action="store_true",
149                help="Print deallocation log to standard output")
150
151class fedd_multi_exp_data_opts(fedd_client_opts):
152    def __init__(self):
153        fedd_client_opts.__init__(self)
154        self.add_option("--data", dest="data", default=[],
155                action="append", type="choice",
156                choices=("id", "federant", "vtopo", "vis", "log", "status"),
157                help="data to extract")
158
159class fedd_spew_opts(fedd_client_opts):
160    def __init__(self):
161        fedd_client_opts.__init__(self)
162        self.add_option("--experiment_cert", dest="exp_certfile",
163                type="string", help="experiment name certificate file")
164        self.add_option("--experiment_name", dest="exp_name",
165                type="string", help="human readable experiment name")
166        self.add_option("--logfile", dest="logfile", default=None,
167                help="File to write log to")
168        self.add_option('--update_time', dest='update', type='int', default=10,
169                help='how often to update the printed log')
170
171class fedd_image_opts(fedd_exp_data_opts):
172    def __init__(self):
173        fedd_exp_data_opts.__init__(self)
174        self.add_option("--output", dest="outfile", type="string",
175                help="output image file")
176        self.add_option("--format", dest="format", type="choice", 
177                choices=("jpg", "png", "dot", "svg"),
178                help="Output file format override")
179        self.add_option("--program", dest="neato", default=None,
180                type="string",
181                help="Program compatible with dot (from graphviz) used to " + \
182                        "render image")
183        self.add_option("--labels", dest='labels', action='store_true',
184                default=True, help='Label nodes and edges')
185        self.add_option("--no_labels", dest='labels',
186                default=True, action='store_false',
187                help='Label nodes and edges')
188        self.add_option('--pixels', dest="pixels", default=None,
189                type="int",
190                help="Size of output in pixels (diagrams are square")
191
192class fedd_ns_image_opts(fedd_split_opts):
193    def __init__(self):
194        fedd_split_opts.__init__(self)
195        self.add_option("--output", dest="outfile", type="string",
196                help="output image file")
197        self.add_option("--format", dest="format", type="choice", 
198                choices=("jpg", "png", "dot", "svg"),
199                help="Output file format override")
200        self.add_option("--program", dest="neato", default=None,
201                type="string",
202                help="Program compatible with dot (from graphviz) used to " + \
203                        "render image")
204        self.add_option("--labels", dest='labels', action='store_true',
205                default=True, help='Label nodes and edges')
206        self.add_option("--no_labels", dest='labels',
207                default=True, action='store_false',
208                help='Label nodes and edges')
209        self.add_option('--pixels', dest="pixels", default=None,
210                type="int",
211                help="Size of output in pixels (diagrams are square")
212
213class fedd_start_opts(fedd_client_opts):
214    def __init__(self):
215        fedd_client_opts.__init__(self)
216        self.add_option("--file", dest="file", 
217                help="experiment description file")
218
219def exit_with_fault(dict, out=sys.stderr):
220    """ Print an error message and exit.
221
222    The dictionary contains the FeddFaultBody elements."""
223    codestr = ""
224
225    if dict.has_key('errstr'):
226        codestr = "Error: %s" % dict['errstr']
227
228    if dict.has_key('code'):
229        if len(codestr) > 0 : 
230            codestr += " (%d)" % dict['code']
231        else:
232            codestr = "Error Code: %d" % dict['code']
233
234    print>>out, codestr
235    print>>out, "Description: %s" % dict['desc']
236    sys.exit(dict.get('code', 20))
237# Base class for the various client operations.  It includes some commonly used
238# functions and classes the most important of which are the exception classes
239# and the service calling classes.
240class fedd_rpc:
241
242    class RPCException:
243        """
244        An error during the RPC exchange.  It unifies errors from both SOAP and
245        XMLPRC calls.
246        """
247        def __init__(self, fb):
248            self.desc = fb.get('desc', None)
249            self.code = fb.get('code', -1)
250            self.errstr = fb.get('errstr', None)
251
252    class caller(service_caller):
253        """
254        The caller is used by fedd_rpc.do_rpc to make the rpc call.  The extra
255        stashed information is used to parse responses a little.
256        """
257        def __init__(self, pre):
258            self.ResponseBody="%sResponseBody" % pre
259            self.method = pre
260            service_caller.__init__(self, self.method)
261
262    def __init__(self): 
263        """
264        Specialize the class for the pre method
265        """
266        self.caller = fedd_rpc.caller
267        self.RPCException = fedd_rpc.RPCException
268
269
270    def add_node_desc(self, option, opt_str, value, parser, node_descs):
271        def none_if_zero(x):
272            if len(x) > 0: return x
273            else: return None
274
275        params = map(none_if_zero, value.split(":"));
276       
277        if len(params) < 4 and len(params) > 1:
278            node_descs.append(node_desc(*params))
279        else:
280            raise OptionValueError("Bad node description: %s" % value)
281
282    def get_user_info(self):
283        pw = pwd.getpwuid(os.getuid());
284        try_cert=None
285        user = None
286
287        if pw != None:
288            user = pw[0]
289            try_cert = "%s/.ssl/emulab.pem" % pw[5];
290            if not os.access(try_cert, os.R_OK):
291                try_cert = None
292        return (user, try_cert)
293
294    def do_rpc(self, req_dict, url, transport, cert, trusted, tracefile=None,
295            serialize_only=False, caller=None):
296        """
297        The work of sending and parsing the RPC as either XMLRPC or SOAP
298        """
299
300        if caller is None: 
301            raise RuntimeError("Must provide caller to do_rpc")
302
303        context = None
304        while context == None:
305            try:
306                context = fedd_ssl_context(cert, trusted)
307            except Exception, e:
308                # Yes, doing this on message type is not ideal.  The string
309                # comes from OpenSSL, so check there is this stops working.
310                if str(e) == "bad decrypt": 
311                    print >>sys.stderr, "Bad Passphrase given."
312                else: raise
313
314        if transport == "soap":
315            if serialize_only:
316                print self.caller.serialize_soap(req_dict) 
317                sys.exit(0)
318            else:
319                try:
320                    resp = caller.call_soap_service(url, req_dict, 
321                            context=context, tracefile=tracefile)
322                except service_error, e:
323                    raise self.RPCException( {\
324                            'code': e.code, 
325                            'desc': e.desc, 
326                            'errstr': e.code_string()\
327                        })
328        elif transport == "xmlrpc":
329            if serialize_only:
330                ser = dumps((req_dict,))
331                print ser
332                sys.exit(0)
333            else:
334                try:
335                    resp = caller.call_xmlrpc_service(url, req_dict, 
336                            context=context, tracefile=tracefile)
337                except service_error, e:
338                    raise self.RPCException( {\
339                            'code': e.code, 
340                            'desc': e.desc, 
341                            'errstr': e.code_string()\
342                        })
343
344        else:
345            raise RuntimeError("Unknown RPC transport: %s" % transport)
346
347        if resp.has_key(caller.ResponseBody):
348            return resp[caller.ResponseBody]
349        else:
350            raise RuntimeError("No body in response??")
351
352class exp_data_base(fedd_rpc):
353    def __init__(self):
354        """
355        Init the various conversions
356        """
357
358        fedd_rpc.__init__(self)
359        # List of things one could ask for and what formatting routine is
360        # called.
361        self.params = {
362                'vis': ('vis', self.print_xml('vis')),
363                'vtopo': ('vtopo', self.print_xml('vtopo')),
364                'federant': ('federant', self.print_xml),
365                'id': ('experimentID', self.print_id),
366                'status': ('experimentStatus', self.print_string),
367                'log': ('allocationLog', self.print_string),
368                'access': ('experimentAccess', self.print_string),
369            }
370
371    # Utility functions
372    def print_string(self, d, out=sys.stdout):
373        print >>out, d
374
375    def print_id(self, d, out=sys.stdout):
376        if d:
377            for id in d:
378                for k in id.keys():
379                    print >>out, "%s: %s" % (k, id[k])
380
381    class print_xml:
382        """
383        Print the retrieved data is a simple xml representation of the dict.
384        """
385        def __init__(self, top):
386            self.xml = top
387
388        def __call__(self, d, out=sys.stdout):
389            str = "<%s>\n" % self.xml
390            for t in ('node', 'lan'):
391                if d.has_key(t): 
392                    for x in d[t]:
393                        str += "<%s>" % t
394                        for k in x.keys():
395                            str += "<%s>%s</%s>" % (k, x[k],k)
396                        str += "</%s>\n" % t
397            str+= "</%s>" % self.xml
398            print >>out, str
399
400       
401
402# Querying experiment data follows the same control flow regardless of the
403# specific data retrieved.  This class encapsulates that control flow.
404class exp_data(exp_data_base):
405    def __init__(self): 
406        exp_data_base.__init__(self)
407
408    def __call__(self):
409        """
410        The control flow.  Compose the request and print the response.
411        """
412        # Process the options using the customized option parser defined above
413        parser = fedd_exp_data_opts()
414
415        (opts, args) = parser.parse_args()
416
417        if opts.trusted:
418            if ( not os.access(opts.trusted, os.R_OK) ) :
419                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
420
421        if opts.debug > 0: opts.tracefile=sys.stderr
422
423        (user, cert) = self.get_user_info()
424
425        if opts.cert != None: cert = opts.cert
426
427        if cert == None:
428            sys.exit("No certificate given (--cert) or found")
429
430        if os.access(cert, os.R_OK):
431            fid = fedid(file=cert)
432        else:
433            sys.exit("Cannot read certificate (%s)" % cert)
434
435        if opts.exp_name and opts.exp_certfile:
436            sys.exit("Only one of --experiment_cert and " +\
437                    "--experiment_name permitted");
438
439        exp_id = None
440        if opts.exp_certfile:
441            exp_id = { 'fedid': fedid(file=opts.exp_certfile) }
442
443        if opts.exp_name:
444            exp_id = { 'localname' : opts.exp_name }
445
446        if not exp_id:
447            sys.exit("specify one of --experiment_cert and --experiment_name")
448
449
450        req = { 'experiment': exp_id }
451
452        try:
453            resp_dict = self.do_rpc(req,
454                    opts.url, opts.transport, cert, opts.trusted, 
455                    serialize_only=opts.serialize_only,
456                    tracefile=opts.tracefile,
457                    caller=self.caller('Info'))
458        except self.RPCException, e:
459            exit_with_fault(\
460                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
461        except RuntimeError, e:
462            sys.exit("Error processing RPC: %s" % e)
463
464        for d in opts.data:
465            key, output = self.params[d]
466            try:
467                if resp_dict.has_key(key):
468                    output(resp_dict[key])
469            except RuntimeError, e:
470                sys.exit("Bad response. %s" % e.message)
471
472class vtopo(exp_data):
473    """
474    vtopo is just an info --data=vtopo request, so this adds that parameter to
475    the arguments and executes exp_info when called.
476    """
477    def __init__(self):
478        exp_data.__init__(self)
479    def __call__(self):
480        sys.argv.append('--data=vtopo')
481        exp_data.__call__(self)
482
483
484class vis(exp_data):
485    """
486    vis is just an info --data=vis request, so this adds that parameter to
487    the arguments and executes exp_info when called.
488    """
489    def __init__(self):
490        exp_data.__init__(self)
491    def __call__(self):
492        sys.argv.append('--data=vis')
493        exp_data.__call__(self)
494
495class status(exp_data):
496    """
497    status is just an info --data=status request, so this adds that parameter
498    to the arguments and executes exp_info when called.
499    """
500    def __init__(self):
501        exp_data.__init__(self)
502    def __call__(self):
503        sys.argv.append('--data=status')
504        exp_data.__call__(self)
505
506class multi_exp_data(exp_data_base):
507    def __init__(self): 
508        exp_data_base.__init__(self)
509
510
511    def __call__(self):
512        """
513        The control flow.  Compose the request and print the response.
514        """
515        # Process the options using the customized option parser defined above
516        parser = fedd_multi_exp_data_opts()
517
518        (opts, args) = parser.parse_args()
519
520        if opts.trusted:
521            if ( not os.access(opts.trusted, os.R_OK) ) :
522                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
523
524        if opts.debug > 0: opts.tracefile=sys.stderr
525
526        (user, cert) = self.get_user_info()
527
528        if opts.cert != None: cert = opts.cert
529
530        if cert == None:
531            sys.exit("No certificate given (--cert) or found")
532
533        if os.access(cert, os.R_OK):
534            fid = fedid(file=cert)
535        else:
536            sys.exit("Cannot read certificate (%s)" % cert)
537
538        req = { }
539
540        try:
541            resp_dict = self.do_rpc(req,
542                    opts.url, opts.transport, cert, opts.trusted, 
543                    serialize_only=opts.serialize_only,
544                    tracefile=opts.tracefile,
545                    caller=self.caller('MultiInfo'))
546        except self.RPCException, e:
547            exit_with_fault(\
548                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
549        except RuntimeError, e:
550            sys.exit("Error processing RPC: %s" % e)
551
552        exps = resp_dict.get('info', [])
553        if exps:
554            print '---'
555            for exp in exps:
556                for d in opts.data:
557                    key, output = self.params[d]
558                    try:
559                        if exp.has_key(key):
560                            output(exp[key])
561                    except RuntimeError, e:
562                        sys.exit("Bad response. %s" % e.message)
563                print '---'
564
565
566class multi_status(exp_data_base):
567    def __init__(self): 
568        exp_data_base.__init__(self)
569
570
571    def __call__(self):
572        """
573        The control flow.  Compose the request and print the response.
574        """
575        # Process the options using the customized option parser defined above
576        parser = fedd_client_opts()
577
578        (opts, args) = parser.parse_args()
579
580        if opts.trusted:
581            if ( not os.access(opts.trusted, os.R_OK) ) :
582                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
583
584        if opts.debug > 0: opts.tracefile=sys.stderr
585
586        (user, cert) = self.get_user_info()
587
588        if opts.cert != None: cert = opts.cert
589
590        if cert == None:
591            sys.exit("No certificate given (--cert) or found")
592
593        if os.access(cert, os.R_OK):
594            fid = fedid(file=cert)
595        else:
596            sys.exit("Cannot read certificate (%s)" % cert)
597
598        req = { }
599
600        try:
601            resp_dict = self.do_rpc(req,
602                    opts.url, opts.transport, cert, opts.trusted, 
603                    serialize_only=opts.serialize_only,
604                    tracefile=opts.tracefile,
605                    caller=self.caller('MultiInfo'))
606        except self.RPCException, e:
607            exit_with_fault(\
608                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
609        except RuntimeError, e:
610            sys.exit("Error processing RPC: %s" % e)
611
612        for exp in resp_dict.get('info', []):
613            out = []
614            for eid in exp.get('experimentID', []):
615                if eid.has_key('localname'):
616                    out.append(eid['localname'])
617                    break
618            else:
619                out.append("")
620            for eid in exp.get('experimentID', []):
621                if eid.has_key('fedid'):
622                    out.append("%s" % eid['fedid'])
623                    break
624            else:
625                out.append("")
626
627            out.append(exp.get('experimentStatus', ""))
628
629            for f in exp.get('federant', []):
630                if f.get('master', False):
631                    em = f.get('emulab', None)
632                    if em:
633                        project = em.get('project', None)
634                        if project:
635                            tb = project.get('testbed', None)
636                            if tb and tb.has_key('localname'):
637                                out.append(tb['localname'])
638                            else:
639                                out.append("")
640                            pn = project.get('name', None)
641                            if pn and pn.has_key('localname'):
642                                out.append(pn['localname'])
643                            else:
644                                out.append("")
645                        else:
646                            out.extend(("", ""))
647                    else:
648                        out.extend(("", ""))
649                    break
650            else:
651                out.extend(("",""))
652
653            print ":".join(out)
654
655class image(fedd_rpc):
656    def __init__(self): 
657        """
658        Null constructor
659        """
660
661        fedd_rpc.__init__(self)
662
663    @staticmethod
664    def gen_dot_topo(d, labels, dotfile):
665        lans = { }
666        links = { }
667
668        for n in d.get('node', []):
669            print >>dotfile, '\t"%s" [shape=box,style=filled,\\' % n['vname']
670            print >>dotfile, '\t\tcolor=black,fillcolor="#60f8c0",regular=1]'
671
672        # Collect lan members (we have to draw extra stuff for these)
673        for n in d.get('lan', []):
674            v = n['vname']
675            m = n['member']
676            i = n['ip']
677            if m.find(':') != -1:
678                m = m[0:m.find(':')]
679            if lans.has_key(v):
680                lans[v].append((m, i))
681            elif links.has_key(v):
682                links[v].append((m, i))
683                if len(links[v]) > 2:
684                    lans[v] = links[v]
685                    del links[v]
686            else:
687                links[v] = [(m, i)]
688
689        # Encode the lans and the links
690        for l in lans.keys():
691            print >>dotfile, '\t"%s" [shape=ellipse, style=filled,\\' % l
692            print >>dotfile,'\t\tcolor=black,fillcolor="#80c0f8",regular=1]'
693            for n in lans[l]:
694                if labels:
695                    print >>dotfile, '\t"%s" -- "%s" [headlabel="%s"]' % \
696                            (l, n[0], n[1])
697                else:
698                    print >>dotfile, '\t"%s" -- "%s"' % (l, n[0])
699
700        for k, l in links.items():
701            if len(l) == 2:
702                if labels:
703                    print >>dotfile, \
704                            ('\t"%s" -- "%s" [label="%s",taillabel="%s",' + \
705                            'headlabel="%s"]') % \
706                            (l[0][0], l[1][0], k, l[0][1], l[1][1])
707                else:
708                    print >>dotfile, '\t"%s" -- "%s" ' % (l[0][0], l[1][0])
709
710
711    def gen_image(self, d, nodes, file, fmt, neato, labels, pix=None):
712
713        # Open up a temporary file for dot to turn into a visualization
714        try:
715            df, dotname = tempfile.mkstemp(prefix='fedd_client', suffix=".dot")
716            dotfile = os.fdopen(df, 'w')
717        except IOError:
718            raise service_error(service_error.internal,
719                    "Failed to open file in genviz")
720
721        if not neato:
722            for f in ['/usr/bin/neato', '/usr/local/bin/neato', 
723                    '/usr/bin/dot', '/usr/local/bin/dot']:
724                if os.access(f, os.X_OK):
725                    neato = f
726                    break
727            else:
728                sys.exit("Cannot find graph rendering program")
729
730        cmd = [neato, '-Gsplines=true']
731        if fmt != 'dot': cmd.append('-T%s' % fmt)
732        if file:
733            cmd.append('-o')
734            cmd.append(file)
735        cmd.append(dotname)
736
737        #nodes = d.get('node',[])
738
739        if nodes < 10: size = 5
740        elif nodes < 50: size = 10
741        else: size = 18
742
743        if pix:
744            dpi = pix / size
745        else:
746            dpi = None
747
748
749        print >>dotfile, "graph G {"
750        if dpi:
751            print >>dotfile, '\tgraph [size="%i,%i", dpi="%i", ratio=fill];' \
752                    % (size, size, dpi)
753        else:
754            print >>dotfile, '\tgraph [size="%i,%i", ratio=fill];' \
755                    % (size, size)
756
757        if labels:
758            print >>dotfile, '\tnode [fontname=arial,fontsize=9,label="\N"];'
759            print >>dotfile, '\tedge [fontname=arial,fontsize=9];\n'
760        else:
761            print >>dotfile, '\tnode [label=""];'
762
763
764        self.gen_dot_topo(d, labels, dotfile)
765        print >>dotfile, "}"
766        dotfile.close()
767
768        # Redirect the drawing program stderr
769        dev_null = open("/dev/null", "w")
770        rv = subprocess.call(cmd, stderr=dev_null)
771        os.remove(dotname)
772        dev_null.close()
773        if rv != 0:
774            sys.exit("Error creating graph")
775
776
777
778    def __call__(self):
779        """
780        The control flow.  Compose the request and print the response.
781        """
782        # Process the options using the customized option parser defined above
783        parser = fedd_image_opts()
784
785        (opts, args) = parser.parse_args()
786
787        if opts.trusted:
788            if ( not os.access(opts.trusted, os.R_OK) ) :
789                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
790
791        if opts.debug > 0: opts.tracefile=sys.stderr
792
793        (user, cert) = self.get_user_info()
794
795        if opts.cert != None: cert = opts.cert
796
797        if cert == None:
798            sys.exit("No certificate given (--cert) or found")
799
800        if os.access(cert, os.R_OK):
801            fid = fedid(file=cert)
802        else:
803            sys.exit("Cannot read certificate (%s)" % cert)
804
805        if opts.exp_name and opts.exp_certfile:
806            sys.exit("Only one of --experiment_cert and " +\
807                    "--experiment_name permitted");
808
809        if opts.exp_certfile:
810            exp_id = { 'fedid': fedid(file=opts.exp_certfile) }
811
812        if opts.exp_name:
813            exp_id = { 'localname' : opts.exp_name }
814
815        if opts.format and opts.outfile:
816            fmt = opts.format
817            file = opts.outfile
818        elif not opts.format and opts.outfile:
819            fmt = opts.outfile[-3:]
820            if fmt not in ("png", "jpg", "dot", "svg"):
821                sys.exit("Unexpected file type and no format specified")
822            file = opts.outfile
823        elif opts.format and not opts.outfile:
824            fmt = opts.format
825            file = None
826        else:
827            fmt="dot"
828            file = None
829
830
831        req = { 'experiment': exp_id }
832
833        try:
834            resp_dict = self.do_rpc(req,
835                    opts.url, opts.transport, cert, opts.trusted, 
836                    serialize_only=opts.serialize_only,
837                    tracefile=opts.tracefile,
838                    caller=self.caller('Vtopo'))
839        except self.RPCException, e:
840            exit_with_fault(\
841                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
842        except RuntimeError, e:
843            sys.exit("Error processing RPC: %s" % e)
844
845
846        if resp_dict.has_key('vtopo'):
847            self.gen_image(resp_dict['vtopo'], 
848                    len(resp_dict['vtopo'].get('node', [])),
849                    file, fmt, opts.neato, opts.labels, opts.pixels)
850        else:
851            sys.exit("Bad response. %s" % e.message)
852
853class ns_image(image):
854    def __init__(self): 
855        """
856        Null constructor
857        """
858
859        image.__init__(self)
860
861    def generate_topo_dict(self, splitout):
862        class topo_parse:
863            """
864            Parse the topology XML and create the dats structure.  This class
865            is copied from federation.experiment_control.
866            """
867            def __init__(self):
868                # Typing of the subelements for data conversion
869                self.str_subelements = ('vname', 'vnode', 'ips', 'ip', 'member')
870                self.int_subelements = ( 'bandwidth',)
871                self.float_subelements = ( 'delay',)
872                # The final data structure
873                self.nodes = [ ]
874                self.lans =  [ ]
875                self.topo = { \
876                        'node': self.nodes,\
877                        'lan' : self.lans,\
878                    }
879                self.element = { }  # Current element being created
880                self.chars = ""     # Last text seen
881
882            def end_element(self, name):
883                # After each sub element the contents is added to the current
884                # element or to the appropriate list.
885                if name == 'node':
886                    self.nodes.append(self.element)
887                    self.element = { }
888                elif name == 'lan':
889                    self.lans.append(self.element)
890                    self.element = { }
891                elif name in self.str_subelements:
892                    self.element[name] = self.chars
893                    self.chars = ""
894                elif name in self.int_subelements:
895                    self.element[name] = int(self.chars)
896                    self.chars = ""
897                elif name in self.float_subelements:
898                    self.element[name] = float(self.chars)
899                    self.chars = ""
900
901            def found_chars(self, data):
902                self.chars += data.rstrip()
903
904
905        tp = topo_parse();
906        parser = xml.parsers.expat.ParserCreate()
907        parser.EndElementHandler = tp.end_element
908        parser.CharacterDataHandler = tp.found_chars
909
910        m = re.search('^#\s+Begin\s+Vtopo\s*$(.*)^#\s+End\s+Vtopo', splitout, 
911                re.MULTILINE | re.DOTALL)
912        if m:
913            str = m.group(1)
914        else:
915            sys.exit("Badly formatted split")
916
917        parser.Parse(str)
918
919        return tp.topo
920
921    def __call__(self):
922        """
923        The control flow.  Compose the request and print the response.
924        """
925        # Process the options using the customized option parser defined above
926        parser = fedd_ns_image_opts()
927
928        (opts, args) = parser.parse_args()
929
930        if opts.trusted:
931            if ( not os.access(opts.trusted, os.R_OK) ) :
932                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
933
934        if opts.debug > 0: opts.tracefile=sys.stderr
935
936        (user, cert) = self.get_user_info()
937
938        if opts.cert != None: cert = opts.cert
939
940        if cert == None:
941            sys.exit("No certificate given (--cert) or found")
942
943        if os.access(cert, os.R_OK):
944            fid = fedid(file=cert)
945        else:
946            sys.exit("Cannot read certificate (%s)" % cert)
947
948        if opts.file:
949            exp_desc = ""
950            try:
951                f = open(opts.file, 'r')
952                for line in f:
953                    exp_desc += line
954                f.close()
955            except IOError:
956                sys.exit("Cannot read description file (%s)" %opts.file)
957        else:
958            sys.exit("Must specify an experiment description (--file)")
959
960        if not opts.master:
961            opts.master="dummy"
962
963
964        req = {
965                'description': { 'ns2description': exp_desc },
966                'master': opts.master,
967                'include_fedkit': opts.fedkit,
968                'include_gatewaykit': opts.gatewaykit,
969                }
970
971
972        if opts.format and opts.outfile:
973            fmt = opts.format
974            file = opts.outfile
975        elif not opts.format and opts.outfile:
976            fmt = opts.outfile[-3:]
977            if fmt not in ("png", "jpg", "dot", "svg"):
978                sys.exit("Unexpected file type and no format specified")
979            file = opts.outfile
980        elif opts.format and not opts.outfile:
981            fmt = opts.format
982            file = None
983        else:
984            fmt="dot"
985            file = None
986
987        try:
988            resp_dict = self.do_rpc(req,
989                    opts.url, opts.transport, cert, opts.trusted, 
990                    serialize_only=opts.serialize_only,
991                    tracefile=opts.tracefile,
992                    caller=self.caller('Ns2Split'))
993        except self.RPCException, e:
994            exit_with_fault(\
995                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
996        except RuntimeError, e:
997            sys.exit("Error processing RPC: %s" % e)
998
999
1000        if resp_dict.has_key('output'):
1001            if len(resp_dict['output']) < 1:
1002                sys.exit("Bad response: could not split")
1003            topo = self.generate_topo_dict(resp_dict['output'])
1004            self.gen_image(topo, len(topo.get('node', [])), file, fmt,
1005                    opts.neato, opts.labels, opts.pixels)
1006        else:
1007            sys.exit("Bad response. %s" % e.message)
1008
1009class topdl_image(image):
1010    def __init__(self): 
1011        """
1012        Null constructor
1013        """
1014
1015        image.__init__(self)
1016
1017    @staticmethod
1018    def gen_dot_topo(t, labels, dotfile):
1019        lans = [ s for s in t.substrates if len(s.interfaces) != 2]
1020        links = [ s for s in t.substrates if len(s.interfaces) == 2]
1021
1022        i = 0
1023        for n in t.elements:
1024            if n.name:
1025                print >>dotfile, '\t"%s" [shape=box,style=filled,\\' % n.name[0]
1026            else:
1027                print >>dotfile, \
1028                        '\t"unnamed_node%d" [shape=box,style=filled,\\' % i
1029                i += 1
1030            print >>dotfile, '\t\tcolor=black,fillcolor="#60f8c0",regular=1]'
1031
1032        # Encode the lans and the links
1033        for l in lans:
1034            print >>dotfile, '\t"%s" [shape=ellipse, style=filled,\\' % l.name
1035            print >>dotfile,'\t\tcolor=black,fillcolor="#80c0f8",regular=1]'
1036            for i in l.interfaces:
1037                ip = i.get_attribute('ip4_address')
1038                if labels and ip:
1039                    print >>dotfile, '\t"%s" -- "%s" [headlabel="%s"]' % \
1040                            (l.name, i.element.name[0], ip)
1041                else:
1042                    print >>dotfile, '\t"%s" -- "%s"' % \
1043                            (l.name, i.element.name[0])
1044
1045        for l in links:
1046            s, d = l.interfaces[0:2] 
1047            sip = s.get_attribute('ip4_address')
1048            dip = d.get_attribute('ip4_address')
1049            if labels and sip and dip:
1050                print >>dotfile, \
1051                        ('\t"%s" -- "%s" [label="%s",taillabel="%s",' + \
1052                        'headlabel="%s"]') % \
1053                        (s.element.name[0], d.element.name[0], l.name,
1054                            sip, dip)
1055            else:
1056                print >>dotfile, '\t"%s" -- "%s" ' % \
1057                        (s.element.name[0], d.element.name[0])
1058    def __call__(self):
1059        """
1060        The control flow.  Compose the request and print the response.
1061        """
1062        # Process the options using the customized option parser defined above
1063        parser = fedd_ns_image_opts()
1064
1065        (opts, args) = parser.parse_args()
1066
1067        if opts.trusted:
1068            if ( not os.access(opts.trusted, os.R_OK) ) :
1069                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
1070
1071        if opts.debug > 0: opts.tracefile=sys.stderr
1072
1073        (user, cert) = self.get_user_info()
1074
1075        if opts.cert != None: cert = opts.cert
1076
1077        if cert == None:
1078            sys.exit("No certificate given (--cert) or found")
1079
1080        if os.access(cert, os.R_OK):
1081            fid = fedid(file=cert)
1082        else:
1083            sys.exit("Cannot read certificate (%s)" % cert)
1084
1085        if opts.file:
1086            exp_desc = ""
1087            try:
1088                top = topdl.topology_from_xml(filename=opts.file, 
1089                        top="experiment")
1090            except IOError:
1091                sys.exit("Cannot read description file (%s)" % opts.file)
1092        else:
1093            sys.exit("Must specify an experiment description (--file)")
1094
1095        if not opts.master:
1096            opts.master="dummy"
1097
1098
1099        if opts.format and opts.outfile:
1100            fmt = opts.format
1101            file = opts.outfile
1102        elif not opts.format and opts.outfile:
1103            fmt = opts.outfile[-3:]
1104            if fmt not in ("png", "jpg", "dot", "svg"):
1105                sys.exit("Unexpected file type and no format specified")
1106            file = opts.outfile
1107        elif opts.format and not opts.outfile:
1108            fmt = opts.format
1109            file = None
1110        else:
1111            fmt="dot"
1112            file = None
1113
1114        self.gen_image(top, len(top.elements), file, fmt, opts.neato, 
1115                opts.labels, opts.pixels)
1116
1117class terminate(fedd_rpc):
1118    def __init__(self): 
1119        """
1120        Termination request
1121        """
1122
1123        fedd_rpc.__init__(self)
1124
1125    def __call__(self):
1126        """
1127        The control flow.  Compose the request and print the response.
1128        """
1129        # Process the options using the customized option parser defined above
1130        parser = fedd_terminate_opts()
1131
1132        (opts, args) = parser.parse_args()
1133
1134        (user, cert) = self.get_user_info()
1135        if opts.trusted:
1136            if ( not os.access(opts.trusted, os.R_OK) ) :
1137                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
1138
1139        if opts.debug > 0: opts.tracefile=sys.stderr
1140
1141        if opts.cert != None: cert = opts.cert
1142
1143        if cert == None:
1144            sys.exit("No certificate given (--cert) or found")
1145
1146        if os.access(cert, os.R_OK):
1147            fid = fedid(file=cert)
1148        else:
1149            sys.exit("Cannot read certificate (%s)" % cert)
1150
1151        if opts.exp_name and opts.exp_certfile:
1152            sys.exit("Only one of --experiment_cert and " +\
1153                    "--experiment_name permitted")
1154
1155        if opts.print_log and opts.logfile:
1156            sys.exit("Only one of --logfile and --print_log is permitted")
1157        elif opts.print_log:
1158            out = sys.stdout
1159        elif opts.logfile:
1160            try:
1161                out = open(opts.logfile, "w")
1162            except IOError,e:
1163                sys.exit("Cannot open logfile: %s" %e)
1164        else:
1165            out = None
1166
1167        exp_id = None
1168
1169        if opts.exp_certfile:
1170            exp_id = { 'fedid': fedid(file=opts.exp_certfile) }
1171
1172        if opts.exp_name:
1173            exp_id = { 'localname' : opts.exp_name }
1174
1175        if not exp_id:
1176            sys.exit("Must give one of --experiment_cert and " +\
1177                    "--experiment_name");
1178
1179        req = { 'experiment': exp_id, 'force': opts.force }
1180
1181        try:
1182            resp_dict = self.do_rpc(req,
1183                    opts.url, opts.transport, cert, opts.trusted, 
1184                    serialize_only=opts.serialize_only,
1185                    tracefile=opts.tracefile,
1186                    caller=self.caller('Terminate'))
1187        except self.RPCException, e:
1188            exit_with_fault(\
1189                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
1190        except RuntimeError, e:
1191            print e
1192            sys.exit("Error processing RPC: %s" % e)
1193
1194        if out:
1195            log = resp_dict.get('deallocationLog', None)
1196            if log:
1197                print >>out, log
1198                out.close()
1199            else:
1200                out.close()
1201                sys.exit("No log returned")
1202
1203class terminate_segment(fedd_rpc):
1204    def __init__(self): 
1205        """
1206        Termination request
1207        """
1208
1209        fedd_rpc.__init__(self)
1210
1211    def __call__(self):
1212        """
1213        The control flow.  Compose the request and print the response.
1214        """
1215        # Process the options using the customized option parser defined above
1216        parser = fedd_terminate_opts()
1217
1218        (opts, args) = parser.parse_args()
1219
1220        (user, cert) = self.get_user_info()
1221        if opts.trusted:
1222            if ( not os.access(opts.trusted, os.R_OK) ) :
1223                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
1224
1225        if opts.debug > 0: opts.tracefile=sys.stderr
1226
1227        if opts.cert != None: cert = opts.cert
1228
1229        if cert == None:
1230            sys.exit("No certificate given (--cert) or found")
1231
1232        if os.access(cert, os.R_OK):
1233            fid = fedid(file=cert)
1234        else:
1235            sys.exit("Cannot read certificate (%s)" % cert)
1236
1237        if opts.exp_name and opts.exp_certfile:
1238            sys.exit("Only one of --experiment_cert and " +\
1239                    "--experiment_name permitted")
1240
1241        if opts.print_log and opts.logfile:
1242            sys.exit("Only one of --logfile and --print_log is permitted")
1243        elif opts.print_log:
1244            out = sys.stdout
1245        elif opts.logfile:
1246            try:
1247                out = open(opts.logfile, "w")
1248            except IOError,e:
1249                sys.exit("Cannot open logfile: %s" %e)
1250        else:
1251            out = None
1252
1253        exp_id = None
1254
1255        if opts.exp_certfile:
1256            exp_id = { 'fedid': fedid(file=opts.exp_certfile) }
1257
1258        if opts.exp_name:
1259            exp_id = { 'localname' : opts.exp_name }
1260
1261        if not exp_id:
1262            sys.exit("Must give one of --experiment_cert and " +\
1263                    "--experiment_name");
1264
1265        req = { 'allocID': exp_id, 'force': opts.force }
1266
1267        try:
1268            resp_dict = self.do_rpc(req,
1269                    opts.url, opts.transport, cert, opts.trusted, 
1270                    serialize_only=opts.serialize_only,
1271                    tracefile=opts.tracefile,
1272                    caller=self.caller('TerminateSegment'))
1273        except self.RPCException, e:
1274            exit_with_fault(\
1275                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
1276        except RuntimeError, e:
1277            print e
1278            sys.exit("Error processing RPC: %s" % e)
1279
1280        if out:
1281            log = resp_dict.get('deallocationLog', None)
1282            if log:
1283                print >>out, log
1284                out.close()
1285            else:
1286                out.close()
1287                sys.exit("No log returned")
1288
1289class new(fedd_rpc):
1290    def __init__(self): 
1291        fedd_rpc.__init__(self)
1292    def __call__(self):
1293        # Process the options using the customized option parser defined above
1294        parser = fedd_new_opts()
1295
1296        (opts, args) = parser.parse_args()
1297
1298        if opts.trusted:
1299            if ( not os.access(opts.trusted, os.R_OK) ) :
1300                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
1301
1302        if opts.debug > 0: opts.tracefile=sys.stderr
1303
1304        (user, cert) = self.get_user_info()
1305
1306        if opts.cert != None: cert = opts.cert
1307
1308        if cert == None:
1309            sys.exit("No certificate given (--cert) or found")
1310
1311        if os.access(cert, os.R_OK):
1312            fid = fedid(file=cert)
1313        else:
1314            sys.exit("Cannot read certificate (%s)" % cert)
1315
1316        out_certfile = opts.out_certfile
1317
1318        msg = { }
1319
1320        if opts.exp_name:
1321            msg['experimentID'] = { 'localname': opts.exp_name }
1322
1323        if opts.debug > 1: print >>sys.stderr, msg
1324
1325        try:
1326            resp_dict = self.do_rpc(msg, 
1327                    opts.url, opts.transport, cert, opts.trusted, 
1328                    serialize_only=opts.serialize_only,
1329                    tracefile=opts.tracefile, 
1330                    caller=self.caller("New"))
1331        except self.RPCException, e:
1332            exit_with_fault(\
1333                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
1334        except RuntimeError, e:
1335            sys.exit("Error processing RPC: %s" % e)
1336
1337        if opts.debug > 1: print >>sys.stderr, resp_dict
1338
1339        ea = resp_dict.get('experimentAccess', None)
1340        if out_certfile and ea and ea.has_key('X509'):
1341            try:
1342                f = open(out_certfile, "w")
1343                print >>f, ea['X509']
1344                f.close()
1345            except IOError:
1346                sys.exit('Could not write to %s' %  out_certfile)
1347        eid = resp_dict.get('experimentID', None)
1348        if eid:
1349            for id in eid:
1350                for k in id.keys():
1351                    print "%s: %s" % (k, id[k])
1352        st = resp_dict.get('experimentStatus', None)
1353        if st:
1354            print "status: %s" % st
1355
1356
1357class create(fedd_rpc):
1358    def __init__(self): 
1359        fedd_rpc.__init__(self)
1360    def __call__(self):
1361        parser = fedd_create_opts()
1362
1363        (opts, args) = parser.parse_args()
1364
1365        if opts.trusted:
1366            if ( not os.access(opts.trusted, os.R_OK) ) :
1367                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
1368
1369        if not opts.project :
1370            parser.error('--project is required')
1371
1372        if opts.debug > 0: opts.tracefile=sys.stderr
1373
1374        (user, cert) = self.get_user_info()
1375
1376        if opts.cert != None: cert = opts.cert
1377
1378        if cert == None:
1379            sys.exit("No certificate given (--cert) or found")
1380
1381        if os.access(cert, os.R_OK):
1382            fid = fedid(file=cert)
1383        else:
1384            sys.exit("Cannot read certificate (%s)" % cert)
1385
1386        if opts.file:
1387            exp_desc = ""
1388            try:
1389                f = open(opts.file, 'r')
1390                for line in f:
1391                    exp_desc += line
1392                f.close()
1393            except IOError:
1394                sys.exit("Cannot read description file (%s)" %opts.file)
1395        else:
1396            sys.exit("Must specify an experiment description (--file)")
1397
1398        if not opts.master:
1399            sys.exit("Must specify a master testbed (--master)")
1400
1401        out_certfile = opts.out_certfile
1402
1403        msg = { }
1404
1405        if opts.exp_name:
1406            msg['experimentID'] = { 'localname': opts.exp_name }
1407
1408        if opts.debug > 1: print >>sys.stderr, msg
1409
1410        try:
1411            resp_dict = self.do_rpc(msg, 
1412                    opts.url, opts.transport, cert, opts.trusted, 
1413                    serialize_only=opts.serialize_only,
1414                    tracefile=opts.tracefile,
1415                    caller=self.caller('New'))
1416        except self.RPCException, e:
1417            exit_with_fault(\
1418                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
1419        except RuntimeError, e:
1420            sys.exit("Error processing RPC: %s" % e)
1421
1422        if opts.debug > 1: print >>sys.stderr, resp_dict
1423
1424        ea = resp_dict.get('experimentAccess', None)
1425        if out_certfile and ea and ea.has_key('X509'):
1426            try:
1427                f = open(out_certfile, "w")
1428                print >>f, ea['X509']
1429                f.close()
1430            except IOError:
1431                sys.exit('Could not write to %s' %  out_certfile)
1432        eid = resp_dict.get('experimentID', None)
1433        e_fedid = None
1434        e_local = None
1435        if eid:
1436            for id in eid:
1437                for k in id.keys():
1438                    if k =='fedid':
1439                        e_fedid = id[k]
1440                    elif k =='localname':
1441                        e_local = id[k]
1442
1443        msg = {
1444                'experimentdescription': { 'ns2description': exp_desc },
1445                'master': opts.master,
1446                'exportProject': { 'localname': opts.project },
1447            }
1448
1449        if e_fedid:
1450            msg['experimentID'] = { 'fedid': e_fedid }
1451        elif e_local:
1452            msg['experimentID'] = { 'localname': e_local }
1453        else:
1454            sys.exit("New did not return an experiment ID??")
1455
1456        if opts.debug > 1: print >>sys.stderr, msg
1457
1458        try:
1459            resp_dict = self.do_rpc(msg, 
1460                    opts.url, opts.transport, cert, opts.trusted, 
1461                    serialize_only=opts.serialize_only,
1462                    tracefile=opts.tracefile,
1463                    caller=self.caller('Create'))
1464        except self.RPCException, e:
1465            exit_with_fault(\
1466                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
1467        except RuntimeError, e:
1468            sys.exit("Error processing RPC: %s" % e)
1469
1470        if opts.debug > 1: print >>sys.stderr, resp_dict
1471
1472        ea = resp_dict.get('experimentAccess', None)
1473        if out_certfile and ea and ea.has_key('X509'):
1474            try:
1475                f = open(out_certfile, "w")
1476                print >>f, ea['X509']
1477                f.close()
1478            except IOError:
1479                sys.exit('Could not write to %s' %  out_certfile)
1480        eid = resp_dict.get('experimentID', None)
1481        if eid:
1482            for id in eid:
1483                for k in id.keys():
1484                    print "%s: %s" % (k, id[k])
1485        st = resp_dict.get('experimentStatus', None)
1486        if st:
1487            print "status: %s" % st
1488
1489class split(fedd_rpc):
1490    def __init__(self): 
1491        fedd_rpc.__init__(self)
1492    def __call__(self):
1493        # Process the options using the customized option parser defined above
1494        parser = fedd_split_opts()
1495
1496        (opts, args) = parser.parse_args()
1497
1498        if opts.trusted:
1499            if ( not os.access(opts.trusted, os.R_OK) ) :
1500                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
1501
1502        if opts.debug > 0: opts.tracefile=sys.stderr
1503
1504        (user, cert) = self.get_user_info()
1505
1506        if opts.cert != None: cert = opts.cert
1507
1508        if cert == None:
1509            sys.exit("No certificate given (--cert) or found")
1510
1511        if os.access(cert, os.R_OK):
1512            fid = fedid(file=cert)
1513            if opts.use_fedid == True:
1514                user = fid
1515        else:
1516            sys.exit("Cannot read certificate (%s)" % cert)
1517
1518        if opts.file:
1519            exp_desc = ""
1520            try:
1521                f = open(opts.file, 'r')
1522                for line in f:
1523                    exp_desc += line
1524                f.close()
1525            except IOError:
1526                sys.exit("Cannot read description file (%s)" %opts.file)
1527        else:
1528            sys.exit("Must specify an experiment description (--file)")
1529
1530        if not opts.master:
1531            sys.exit("Must specify a master testbed (--master)")
1532
1533        out_certfile = opts.out_certfile
1534
1535        msg = {
1536                'description': { 'ns2description': exp_desc },
1537                'master': opts.master,
1538                'include_fedkit': opts.fedkit,
1539                'include_gatewaykit': opts.gatewaykit,
1540                }
1541
1542        if opts.debug > 1: print >>sys.stderr, msg
1543
1544        try:
1545            resp_dict = self.do_rpc(msg, 
1546                    opts.url, opts.transport, cert, opts.trusted, 
1547                    serialize_only=opts.serialize_only,
1548                    tracefile=opts.tracefile,
1549                    caller=self.caller('Ns2Split'))
1550        except self.RPCException, e:
1551            exit_with_fault(\
1552                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
1553        except RuntimeError, e:
1554            sys.exit("Error processing RPC: %s" % e)
1555
1556        if opts.debug > 1: print >>sys.stderr, resp_dict
1557
1558        out = resp_dict.get('output', None)
1559
1560        for line in out.splitlines():
1561            print "%s" % line
1562
1563class access(fedd_rpc):
1564    def __init__(self):
1565        fedd_rpc.__init__(self)
1566
1567    def print_response_as_testbed(self, resp, label, out=sys.stdout):
1568        """Print the response as input to the splitter script"""
1569
1570        e = resp.get('emulab', None)
1571        if e:
1572            p = e['project']
1573            fields = { 
1574                    "Boss": e['boss'],
1575                    "OpsNode": e['ops'],
1576                    "Domain": e['domain'],
1577                    "FileServer": e['fileServer'],
1578                    "EventServer": e['eventServer'],
1579                    "Project": unpack_id(p['name'])
1580                    }
1581            if (label != None): print >> out, "[%s]" % label
1582
1583            for l, v in fields.iteritems():
1584                print >>out, "%s: %s" % (l, v)
1585
1586            for u in p['user']:
1587                print >>out, "User: %s" % unpack_id(u['userID'])
1588
1589            for a in e['fedAttr']:
1590                print >>out, "%s: %s" % (a['attribute'], a['value'])
1591
1592    def __call__(self):
1593        node_descs = []
1594        proj = None
1595
1596        # Process the options using the customized option parser defined above
1597        parser = fedd_access_opts()
1598
1599        (opts, args) = parser.parse_args()
1600
1601        if opts.testbed == None:
1602            parser.error("--testbed is required")
1603
1604        if opts.trusted:
1605            if ( not os.access(opts.trusted, os.R_OK) ) :
1606                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
1607
1608        if opts.debug > 0: opts.tracefile=sys.stderr
1609
1610        (user, cert) = self.get_user_info()
1611
1612        if opts.cert != None: cert = opts.cert
1613
1614        if cert == None:
1615            sys.exit("No certificate given (--cert) or found")
1616
1617        if os.access(cert, os.R_OK):
1618            fid = fedid(file=cert)
1619            if opts.use_fedid == True:
1620                user = fid
1621        else:
1622            sys.exit("Cannot read certificate (%s)" % cert)
1623
1624        msg = {
1625                'allocID': pack_id('test alloc'),
1626                'destinationTestbed': pack_id(opts.testbed),
1627                }
1628
1629        if len(node_descs) > 0:
1630            msg['resources'] = { 
1631                    'node': [ 
1632                        { 
1633                            'image':  n.image ,
1634                            'hardware':  n.hardware,
1635                            'count': n.count,
1636                        } for n in node_descs],
1637                    }
1638
1639        if opts.debug > 1: print >>sys.stderr, msg
1640
1641        try:
1642            resp_dict = self.do_rpc(msg, 
1643                    opts.url, opts.transport, cert, opts.trusted, 
1644                    serialize_only=opts.serialize_only,
1645                    tracefile=opts.tracefile,
1646                    caller=self.caller('RequestAccess'))
1647        except self.RPCException, e:
1648            exit_with_fault(\
1649                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
1650        except RuntimeError, e:
1651            sys.exit("Error processing RPC: %s" % e.message)
1652
1653        if opts.debug > 1: print >>sys.stderr, resp_dict
1654        self.print_response_as_testbed(resp_dict, opts.label)
1655
1656# Keep requesting experiment status and printing updates to the log until the
1657# experiment is done being created.
1658class spew_log(fedd_rpc):
1659    def __init__(self): 
1660        """
1661        Init the superclass
1662        """
1663
1664        fedd_rpc.__init__(self)
1665
1666    def __call__(self):
1667        """
1668        The control flow.  Compose the request and print the response.
1669        """
1670        # Process the options using the customized option parser defined above
1671        parser = fedd_spew_opts()
1672
1673        (opts, args) = parser.parse_args()
1674
1675        if opts.trusted:
1676            if ( not os.access(opts.trusted, os.R_OK) ) :
1677                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
1678
1679        if opts.debug > 0: opts.tracefile=sys.stderr
1680
1681        (user, cert) = self.get_user_info()
1682
1683        if opts.cert != None: cert = opts.cert
1684
1685        if cert == None:
1686            sys.exit("No certificate given (--cert) or found")
1687
1688        if os.access(cert, os.R_OK):
1689            fid = fedid(file=cert)
1690        else:
1691            sys.exit("Cannot read certificate (%s)" % cert)
1692
1693        if opts.exp_name and opts.exp_certfile:
1694            sys.exit("Only one of --experiment_cert and " +\
1695                    "--experiment_name permitted");
1696
1697        if opts.exp_certfile:
1698            exp_id = { 'fedid': fedid(file=opts.exp_certfile) }
1699
1700        if opts.exp_name:
1701            exp_id = { 'localname' : opts.exp_name }
1702
1703        if opts.logfile:
1704            try:
1705                out = open(opts.logfile, "w")
1706            except IOError,e:
1707                sys.exit("Cannot open logfile: %s" %e)
1708        else:
1709            out = sys.stdout
1710
1711        req = { 'experiment': exp_id }
1712
1713        status = "starting"
1714        log = ""
1715        log_offset = 0
1716        update = opts.update
1717        while status == 'starting':
1718            try:
1719                resp_dict = self.do_rpc(req,
1720                        opts.url, opts.transport, cert, opts.trusted, 
1721                        serialize_only=opts.serialize_only,
1722                        tracefile=opts.tracefile,
1723                        caller=self.caller('Info'))
1724            except self.RPCException, e:
1725                exit_with_fault(\
1726                        {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
1727            except RuntimeError, e:
1728                sys.exit("Error processing RPC: %s" % e)
1729
1730            status = resp_dict.get('experimentStatus', None)
1731            log = resp_dict.get('allocationLog', None)
1732            if not status:
1733                sys.exit("No status in Info response??")
1734            if log:
1735                if len(log) > log_offset:
1736                    print >>out, log[log_offset:],
1737                    out.flush()
1738                    log_offset = len(log)
1739            if status == 'starting': 
1740                time.sleep(update)
1741
1742        print >>out
1743        print >>out, status
1744        out.close()
1745
1746class start_segment(fedd_rpc):
1747    def __init__(self): 
1748        fedd_rpc.__init__(self)
1749    def __call__(self):
1750        # Process the options using the customized option parser defined above
1751        parser = fedd_start_opts()
1752
1753        (opts, args) = parser.parse_args()
1754
1755        if opts.trusted:
1756            if ( not os.access(opts.trusted, os.R_OK) ) :
1757                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
1758
1759        if opts.debug > 0: opts.tracefile=sys.stderr
1760
1761        (user, cert) = self.get_user_info()
1762
1763        if opts.cert != None: cert = opts.cert
1764
1765        if cert == None:
1766            sys.exit("No certificate given (--cert) or found")
1767
1768        if os.access(cert, os.R_OK):
1769            fid = fedid(file=cert)
1770        else:
1771            sys.exit("Cannot read certificate (%s)" % cert)
1772
1773        if opts.file:
1774            try:
1775                top = topdl.topology_from_xml(filename=opts.file, 
1776                        top='experiment')
1777            except IOError:
1778                sys.exit("Cannot read description file (%s)" %opts.file)
1779        else:
1780            sys.exit("Must specify an experiment description (--file)")
1781
1782        msg = {
1783                'segmentdescription': { 'topdldescription': top.to_dict() },
1784                'allocID': pack_id(fid),
1785                'master': False,
1786                }
1787
1788        if opts.debug > 1: print >>sys.stderr, msg
1789
1790        try:
1791            resp_dict = self.do_rpc(msg, 
1792                    opts.url, opts.transport, cert, opts.trusted, 
1793                    serialize_only=opts.serialize_only,
1794                    tracefile=opts.tracefile,
1795                    caller=self.caller('StartSegment'))
1796        except self.RPCException, e:
1797            exit_with_fault(\
1798                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
1799        except RuntimeError, e:
1800            sys.exit("Error processing RPC: %s" % e)
1801
1802        if opts.debug > 1: print >>sys.stderr, resp_dict
1803        print resp_dict
1804
1805
1806
1807cmds = {\
1808        'new': new(),\
1809        'create': create(),\
1810        'split': split(),\
1811        'access': access(),\
1812        'vtopo': vtopo(),\
1813        'vis': vis(),\
1814        'info': exp_data(),\
1815        'multiinfo': multi_exp_data(),\
1816        'multistatus': multi_status(),\
1817        'image': image(),\
1818        'ns_image': ns_image(),\
1819        'status': status(),\
1820        'terminate': terminate(),\
1821        'spewlog': spew_log(),\
1822        'topdl_image': topdl_image(),\
1823        'start_segment': start_segment(),\
1824        'terminate_segment': terminate_segment(),\
1825    }
1826
1827operation = cmds.get(sys.argv[1], None)
1828if operation:
1829    del sys.argv[1]
1830    operation()
1831else:
1832    if sys.argv[1] == '--help':
1833        sys.exit(\
1834'''Only context sensitive help is available.  For one of the commands:
1835
1836%s
1837
1838type
1839  %s command --help
1840
1841to get help, e.g., %s create --help
1842''' % (", ".join(cmds.keys()), sys.argv[0], sys.argv[0]))
1843    else:
1844        sys.exit("Bad command: %s.  Valid ones are: %s" % \
1845                (sys.argv[1], ", ".join(cmds.keys())))
1846
Note: See TracBrowser for help on using the repository browser.