Ignore:
Timestamp:
Aug 2, 2009 6:25:17 PM (15 years ago)
Author:
Ted Faber <faber@…>
Branches:
axis_example, compt_changes, info-ops, master, version-2.00, version-3.01, version-3.02
Children:
81a7f3f
Parents:
cdb62d9
Message:

create images from topdl descriptions, a good sign they're coming out right.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • fedd/fedd_client.py

    rcdb62d9 rdf783c1  
    1313from federation.util import fedd_ssl_context, pack_id, unpack_id
    1414from federation.remote_service import service_caller
     15from federation import topdl
    1516
    1617from optparse import OptionParser, OptionValueError
     
    477478                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
    478479        except RuntimeError, e:
    479             print e
    480480            sys.exit("Error processing RPC: %s" % e)
    481481
     
    565565                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
    566566        except RuntimeError, e:
    567             print e
    568567            sys.exit("Error processing RPC: %s" % e)
    569568
     
    625624                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
    626625        except RuntimeError, e:
    627             print e
    628626            sys.exit("Error processing RPC: %s" % e)
    629627
     
    677675        """
    678676
    679         fedd_rpc.__init__(self, 'Vtopo')
    680 
    681     def gen_image(self, d, file, fmt, neato, labels, pix=None):
    682 
    683         # Open up a temporary file for dot to turn into a visualization
    684         try:
    685             df, dotname = tempfile.mkstemp(prefix='fedd_client', suffix=".dot")
    686             dotfile = os.fdopen(df, 'w')
    687         except IOError:
    688             raise service_error(service_error.internal,
    689                     "Failed to open file in genviz")
    690 
    691         if not neato:
    692             for f in ['/usr/bin/neato', '/usr/local/bin/neato',
    693                     '/usr/bin/dot', '/usr/local/bin/dot']:
    694                 if os.access(f, os.X_OK):
    695                     neato = f
    696                     break
    697             else:
    698                 sys.exit("Cannot find graph rendering program")
    699 
    700         cmd = [neato, '-Gsplines=true']
    701         if fmt != 'dot': cmd.append('-T%s' % fmt)
    702         if file:
    703             cmd.append('-o')
    704             cmd.append(file)
    705         cmd.append(dotname)
    706 
    707         nodes = d.get('node',[])
    708 
    709         if len(nodes) < 10: size = 5
    710         elif len(nodes) < 50: size = 10
    711         else: size = 18
    712 
    713         if pix:
    714             dpi = pix / size
    715         else:
    716             dpi = None
    717 
    718 
    719         print >>dotfile, "graph G {"
    720         if dpi:
    721             print >>dotfile, '\tgraph [size="%i,%i", dpi="%i", ratio=fill];' \
    722                     % (size, size, dpi)
    723         else:
    724             print >>dotfile, '\tgraph [size="%i,%i", ratio=fill];' \
    725                     % (size, size)
    726 
    727         if labels:
    728             print >>dotfile, '\tnode [fontname=arial,fontsize=9,label="\N"];'
    729             print >>dotfile, '\tedge [fontname=arial,fontsize=9];\n'
    730         else:
    731             print >>dotfile, '\tnode [label=""];'
     677        fedd_rpc.__init__(self, op)
     678
     679    @staticmethod
     680    def gen_dot_topo(d, labels, dotfile):
     681        lans = { }
     682        links = { }
    732683
    733684        for n in d.get('node', []):
    734685            print >>dotfile, '\t"%s" [shape=box,style=filled,\\' % n['vname']
    735686            print >>dotfile, '\t\tcolor=black,fillcolor="#60f8c0",regular=1]'
    736 
    737 
    738         lans = { }
    739         links = { }
    740687
    741688        # Collect lan members (we have to draw extra stuff for these)
     
    777724                    print >>dotfile, '\t"%s" -- "%s" ' % (l[0][0], l[1][0])
    778725
     726
     727    def gen_image(self, d, nodes, file, fmt, neato, labels, pix=None):
     728
     729        # Open up a temporary file for dot to turn into a visualization
     730        try:
     731            df, dotname = tempfile.mkstemp(prefix='fedd_client', suffix=".dot")
     732            dotfile = os.fdopen(df, 'w')
     733        except IOError:
     734            raise service_error(service_error.internal,
     735                    "Failed to open file in genviz")
     736
     737        if not neato:
     738            for f in ['/usr/bin/neato', '/usr/local/bin/neato',
     739                    '/usr/bin/dot', '/usr/local/bin/dot']:
     740                if os.access(f, os.X_OK):
     741                    neato = f
     742                    break
     743            else:
     744                sys.exit("Cannot find graph rendering program")
     745
     746        cmd = [neato, '-Gsplines=true']
     747        if fmt != 'dot': cmd.append('-T%s' % fmt)
     748        if file:
     749            cmd.append('-o')
     750            cmd.append(file)
     751        cmd.append(dotname)
     752
     753        #nodes = d.get('node',[])
     754
     755        if nodes < 10: size = 5
     756        elif nodes < 50: size = 10
     757        else: size = 18
     758
     759        if pix:
     760            dpi = pix / size
     761        else:
     762            dpi = None
     763
     764
     765        print >>dotfile, "graph G {"
     766        if dpi:
     767            print >>dotfile, '\tgraph [size="%i,%i", dpi="%i", ratio=fill];' \
     768                    % (size, size, dpi)
     769        else:
     770            print >>dotfile, '\tgraph [size="%i,%i", ratio=fill];' \
     771                    % (size, size)
     772
     773        if labels:
     774            print >>dotfile, '\tnode [fontname=arial,fontsize=9,label="\N"];'
     775            print >>dotfile, '\tedge [fontname=arial,fontsize=9];\n'
     776        else:
     777            print >>dotfile, '\tnode [label=""];'
     778
     779
     780        self.gen_dot_topo(d, labels, dotfile)
    779781        print >>dotfile, "}"
    780782        dotfile.close()
     
    854856                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
    855857        except RuntimeError, e:
    856             print e
    857858            sys.exit("Error processing RPC: %s" % e)
    858859
    859860
    860861        if resp_dict.has_key('vtopo'):
    861             self.gen_image(resp_dict['vtopo'], file, fmt, opts.neato,
    862                     opts.labels, opts.pixels)
     862            self.gen_image(resp_dict['vtopo'],
     863                    len(resp_dict['vtopo'].get('node', [])),
     864                    file, fmt, opts.neato, opts.labels, opts.pixels)
    863865        else:
    864866            sys.exit("Bad response. %s" % e.message)
     
    10001002            file = None
    10011003
    1002 
    10031004        try:
    10041005            resp_dict = self.do_rpc(req,
     
    10101011                    {'desc': e.desc, 'errstr': e.errstr, 'code': e.code})
    10111012        except RuntimeError, e:
    1012             print e
    10131013            sys.exit("Error processing RPC: %s" % e)
    10141014
     
    10181018                sys.exit("Bad response: could not split")
    10191019            topo = self.generate_topo_dict(resp_dict['output'])
    1020             self.gen_image(topo, file, fmt, opts.neato, opts.labels,
    1021                     opts.pixels)
     1020            self.gen_image(topo, len(topo.get('node', [])), file, fmt,
     1021                    opts.neato, opts.labels, opts.pixels)
    10221022        else:
    10231023            sys.exit("Bad response. %s" % e.message)
     1024
     1025class topdl_image(image):
     1026    def __init__(self, op='Ns2Split'):
     1027        """
     1028        Null constructor
     1029        """
     1030
     1031        image.__init__(self, 'Ns2Split')
     1032
     1033    @staticmethod
     1034    def gen_dot_topo(t, labels, dotfile):
     1035        lans = [ s for s in t.substrates if len(s.interfaces) != 2]
     1036        links = [ s for s in t.substrates if len(s.interfaces) == 2]
     1037
     1038        i = 0
     1039        for n in t.elements:
     1040            if n.name:
     1041                print >>dotfile, '\t"%s" [shape=box,style=filled,\\' % n.name[0]
     1042            else:
     1043                print >>dotfile, \
     1044                        '\t"unnamed_node%d" [shape=box,style=filled,\\' % i
     1045                i += 1
     1046            print >>dotfile, '\t\tcolor=black,fillcolor="#60f8c0",regular=1]'
     1047
     1048        # Encode the lans and the links
     1049        for l in lans:
     1050            print >>dotfile, '\t"%s" [shape=ellipse, style=filled,\\' % l.name
     1051            print >>dotfile,'\t\tcolor=black,fillcolor="#80c0f8",regular=1]'
     1052            for i in l.interfaces:
     1053                ip = i.get_attribute('ip4_address')
     1054                if labels and ip:
     1055                    print >>dotfile, '\t"%s" -- "%s" [headlabel="%s"]' % \
     1056                            (l.name, i.element.name[0], ip)
     1057                else:
     1058                    print >>dotfile, '\t"%s" -- "%s"' % \
     1059                            (l.name, i.element.name[0])
     1060
     1061        for l in links:
     1062            s, d = l.interfaces[0:2]
     1063            sip = s.get_attribute('ip4_address')
     1064            dip = s.get_attribute('ip4_address')
     1065            if labels and sip and dip:
     1066                print >>dotfile, \
     1067                        ('\t"%s" -- "%s" [label="%s",taillabel="%s",' + \
     1068                        'headlabel="%s"]') % \
     1069                        (s.element.name[0], d.element.name[0], l.name,
     1070                            sip, dip)
     1071            else:
     1072                print >>dotfile, '\t"%s" -- "%s" ' % \
     1073                        (s.element.name[0], d.element.name[0])
     1074    def __call__(self):
     1075        """
     1076        The control flow.  Compose the request and print the response.
     1077        """
     1078        access_keys = []
     1079        # Process the options using the customized option parser defined above
     1080        parser = fedd_ns_image_opts(access_keys, self.add_ssh_key,
     1081                self.add_x509_cert)
     1082
     1083        (opts, args) = parser.parse_args()
     1084
     1085        if opts.trusted:
     1086            if ( not os.access(opts.trusted, os.R_OK) ) :
     1087                sys.exit("Cannot read trusted certificates (%s)" % opts.trusted)
     1088
     1089        if opts.debug > 0: opts.tracefile=sys.stderr
     1090
     1091        (user, cert) = self.get_user_info([])
     1092
     1093        if opts.cert != None: cert = opts.cert
     1094
     1095        if cert == None:
     1096            sys.exit("No certificate given (--cert) or found")
     1097
     1098        if os.access(cert, os.R_OK):
     1099            fid = fedid(file=cert)
     1100        else:
     1101            sys.exit("Cannot read certificate (%s)" % cert)
     1102
     1103        if opts.file:
     1104            exp_desc = ""
     1105            try:
     1106                top = topdl.topology_from_xml(file=opts.file, top="experiment")
     1107            except IOError:
     1108                sys.exit("Cannot read description file (%s)" % opts.file)
     1109        else:
     1110            sys.exit("Must specify an experiment description (--file)")
     1111
     1112        if not opts.master:
     1113            opts.master="dummy"
     1114
     1115
     1116        if opts.format and opts.outfile:
     1117            fmt = opts.format
     1118            file = opts.outfile
     1119        elif not opts.format and opts.outfile:
     1120            fmt = opts.outfile[-3:]
     1121            if fmt not in ("png", "jpg", "dot", "svg"):
     1122                sys.exit("Unexpected file type and no format specified")
     1123            file = opts.outfile
     1124        elif opts.format and not opts.outfile:
     1125            fmt = opts.format
     1126            file = None
     1127        else:
     1128            fmt="dot"
     1129            file = None
     1130
     1131        self.gen_image(top, len(top.elements), file, fmt, opts.neato,
     1132                opts.labels, opts.pixels)
    10241133
    10251134class terminate(fedd_rpc):
     
    14951604        'status': status(),\
    14961605        'terminate': terminate(),\
    1497         'spewlog': spew_log(),
     1606        'spewlog': spew_log(),\
     1607        'topdl_image': topdl_image(),\
    14981608    }
    14991609
Note: See TracChangeset for help on using the changeset viewer.