Ejemplo n.º 1
0
 def do_bar(self, *sp):
     """? Draw a bar graph.  A bar graph compares single values of multiple entities.  If locations do not resolve to single-number entities, the bar graph will not be shown.
 Arguments: locations (must contain a number)
 Example:  Compare number of threads in all components on all network elements
    cd /*/safplusAmf/Component/*/procStats
    bar numThreads/current
       """
     depth = 1
     rest = ""
     if len(sp):
         if sp[0][0] == "-":  # Its a flag
             depth = int(sp[0][1:])  # depth modifier flag
             if len(sp) > 1:
                 rest = sp[1:]
         else:
             rest = sp
     xml = []
     for arg in rest:
         t = os.path.normpath(os.path.join(self.curdir, arg))
         xml.append(access.mgtGet("{d=%s}%s" % (depth, str(t))))
     self.bar(xml, self.xmlterm)
     return ""
Ejemplo n.º 2
0
    def do_plot(self, *sp):
        """? Draw a line graph
    Arguments: locations that contain plottable data (comma separated list of numbers)
    Example:  Plot memory utilization on all components in 10 second and 5 minute time frames. 
       cd /local/node/*/bytesReceived
       plot sec10 min5         
"""
        depth = 1
        rest = ""
        if len(sp):
            if sp[0][0] == "-":  # Its a flag
                depth = int(sp[0][1:])  # depth modifier flag
                if len(sp) > 1:
                    rest = sp[1:]
            else:
                rest = sp
        xml = []
        for arg in rest:
            t = os.path.normpath(os.path.join(self.curdir, arg))
            xml.append(access.mgtGet("{d=%s}%s" % (depth, str(t))))
        self.plot(xml, self.xmlterm)
        return ""
Ejemplo n.º 3
0
    def do_ls(self, *sp):
        """Displays the object tree at the current or specified location.
Arguments: [-N] location
By default the specified location and children are shown.  Use -N to specify how many children to show.  For example -2 will show this location, children and grandchildren.
    """
        depth = 1
        rest = [""]
        if len(sp):
            if sp[0][0] == "-":  # Its a flag
                depth = int(sp[0][1:])  # depth modifier flag
                if len(sp) > 1:
                    rest = sp[1:]
            else:
                rest = sp[0:]
        xml = []
        for r in rest:
            t = os.path.normpath(os.path.join(self.curdir, r))
            gs = "{d=%s}%s" % (depth, str(t))
            xml.append(access.mgtGet(gs))
        #print xml
        return "<top>" + "\n".join(
            xml
        ) + "</top>"  # I have to wrap in an xml tag in case I get 2 top levels from mgtGet
Ejemplo n.º 4
0
    def xxexecute(self, textLine, xt):
        """Execute the passed string"""
        cmdList = textLine.split(";")
        depth = 1
        while cmdList:
            text = cmdList.pop(0)
            sp = text.split()
            if sp:
                alias = xt.aliases.get(sp[0], None)
                if alias:  # Rewrite text with the alias and resplit
                    sp[0] = alias
                    text = " ".join(sp)
                    sp = text.split()
                # Now process the command
                if sp[0] == "ls" or sp[0] == "dir":
                    rest = ""
                    if len(sp) > 1:
                        if sp[1][0] == "-":  # Its a flag
                            depth = int(sp[1][1:])  # depth modifier flag
                            if len(sp) > 2:
                                rest = sp[2]
                        else:
                            rest = sp[1]
                    t = os.path.normpath(os.path.join(self.curdir, rest))
                    gs = "{d=%s}%s" % (depth, str(t))
                    #print "getting ", gs
                    xml = access.mgtGet(gs)
                    #print xml
                    xt.doc.append(
                        "<top>" + xml + "</top>"
                    )  # I have to wrap in an xml tag in case I get 2 top levels from mgtGet
                elif sp[0] == "plot":
                    rest = ""
                    if len(sp) > 1:
                        if sp[1][0] == "-":  # Its a flag
                            depth = int(sp[1][1:])  # depth modifier flag
                            if len(sp) > 2:
                                rest = sp[2:]
                        else:
                            rest = sp[1:]
                    xml = []
                    for arg in rest:
                        t = os.path.normpath(os.path.join(self.curdir, arg))
                        xml.append(access.mgtGet("{d=%s}%s" % (depth, str(t))))
                    self.plot(xml, xt)
                elif sp[0] == "bar":
                    rest = ""
                    if len(sp) > 1:
                        if sp[1][0] == "-":  # Its a flag
                            depth = int(sp[1][1:])  # depth modifier flag
                            if len(sp) > 2:
                                rest = sp[2:]
                        else:
                            rest = sp[1:]
                    xml = []
                    for arg in rest:
                        t = os.path.normpath(os.path.join(self.curdir, arg))
                        xml.append(access.mgtGet("{d=%s}%s" % (depth, str(t))))
                    self.bar(xml, xt)

                elif sp[0] == "cd":
                    self.curdir = os.path.normpath(
                        os.path.join(self.curdir, sp[1]))
                    xt.cmdLine.setPrompt()
                elif sp[0] == 'pwd':
                    xt.doc.append(self.curdir)
                elif sp[0] == 'raw':
                    prefix = "{d=%s}"
                    rest = ""
                    flags = sp[1:]
                    for flag in flags:
                        if flag[0] == "-":  # Its a flag
                            if flag[1] == 'b':
                                prefix = "{b,d=%s}"
                            elif flag[1] == 'p':
                                prefix = "{p,d=%s}"
                            else:
                                try:
                                    depth = int(
                                        flag[1:])  # depth modifier flag
                                except ValueError, e:
                                    xt.doc.append("bad flag: " + flag)
                                    pass
                        else:
                            rest = flag
                    t = os.path.normpath(os.path.join(self.curdir, rest))
                    # print (prefix % depth) + str(t)
                    xml = access.mgtGet((prefix % depth) + str(t))
                    txt = "<text>" + xmlterm.escape(
                        xmlterm.indent("<top>" + xml + "</top>")) + "</text>"
                    xt.doc.append(
                        txt
                    )  # I have to wrap in an xml tag in case I get 2 top levels from mgtGet

                elif sp[0] == "!time":  # Show the time (for fun)
                    xt.doc.append("<time/>")
                elif sp[0] == '!echo':  # Display something on the terminal
                    xt.doc.append(" ".join(sp[1:]))
                    if 0:
                        try:  # If its good XML append it, otherwise excape it and dump as text
                            rest = " ".join(sp[1:])
                            testtree = ET.fromstring(rest)
                            xt.doc.append(rest)
                        except ET.ParseError:
                            xt.doc.append(xmlterm.escape(rest))
                elif sp[0] == '!name':  # Change the terminal's title
                    xt.frame.SetTitle(sp[1])
                elif sp[0] == 'alias' or sp[
                        0] == '!alias':  # Make one command become another
                    xt.aliases[sp[1]] = " ".join(sp[2:])
                elif sp[0] == '!exit' or sp[0] == 'exit':  # goodbye
                    self.parentWin.GetParent().frame.Close()
                else:
                    pdb.set_trace()
                    # TODO look for registered RPC call
                    t = xmlterm.escape(" ".join(sp))
                    xt.doc.append('<process>%s</process>' % t)
Ejemplo n.º 5
0
class TermController(xmlterm.XmlResolver):
    """This class customizes the XML terminal"""
    def __init__(self):
        xmlterm.XmlResolver.__init__(self)
        self.tags.update(xmlterm.GetDefaultResolverMapping())
        self.curdir = "/"
        self.cmds.append(self)  # I provide some default commands
        self.xmlterm = None

    def newContext(self):
        path = self.curdir.split("/")
        return xmlterm.ParsingContext(path)

    def start(self, xt):
        """Called when the XML terminal is just getting started"""
        self.xmlterm = xt
        xt.frame.SetTitle(CliName)

    def prompt(self):
        """Returns the terminal prompt"""
        return self.curdir + "> "

    def new(self):
        """Clone this controller for sub-documents"""
        return TermController()

    def completion(self, s):
        """Return the best command line completion candidate, given that the user already typed the string s"""
        if not s:
            return ""
        cmds = ["!time ", "!echo ", "alias ", "!alias ", "!name", "cd", "get"]
        for c in cmds:
            if c.startswith(s):
                print "complete", c
                return c[len(s):]
        return ""

    def bar(self, xml, xt):
        """Implement the bar graph command, which draws a bar graph"""
        et = ET.fromstring("<top>" + "".join(xml) + "</top>")
        metrics = findMetrics(et)
        if not metrics:
            xt.doc.append("Nothing to graph")
            return
        metricNames = [x[0] for x in metrics]
        (pfxLen, sfxLen) = uniquePortion(metricNames)
        st = ['<barGraph>']
        for s in metrics:
            if s[1]:  # If the series has some data then add it to the plot
                lbl = s[0][pfxLen:sfxLen]
                st.append('<metric label="%s">' % lbl)
                if type(s[1]) is types.ListType:
                    st.append(
                        str(sum(s[1]) / len(s[1]))
                    )  # TODO specify the operation.  sum, max, min, ave
                else:
                    st.append(str(s[1]))
                st.append('</metric>')
        st.append("</barGraph>")
        xt.doc.append(
            "".join(st)
        )  # I have to wrap in an xml tag in case I get 2 top levels from mgtGet

    def plot(self, xml, xt):
        """Implement the plot command -- draws a plot (line graph)"""

        et = ET.fromstring("<top>" + "".join(xml) + "</top>")
        series = findSeries(et)
        if len(series) == 0:
            xt.doc.append("Nothing to plot")
            return

        seriesNames = [x[0] for x in series]

        sz = xt.GetSize()
        sizeString = "(%s,%s)" % (sz[0] - 30, sz[1] / 2)
        (pfxLen, sfxLen) = uniquePortion(seriesNames)

        st = ['<plot size="%s">' % sizeString]

        for s in series:
            if s[1]:  # If the series has some data then add it to the plot
                if s[1][0] == "{":  # If its complex data just try to grab the "val" out of it
                    dlst = json.loads("[" + s[1] + "]")
                    series = [x["val"] for x in dlst]
                else:
                    series = s[1]
                lbl = s[0][pfxLen:sfxLen]
                st.append('<series label="%s">' % lbl)
                st.append(str(series))
                st.append('</series>')
        st.append("</plot>")
        # print "".join(st)
        xt.doc.append(
            "".join(st)
        )  # I have to wrap in an xml tag in case I get 2 top levels from mgtGet

    def do_help(self, *command):
        """? display this help, or detailed help about a particular command"""
        if command:
            command = [" ".join(command)]
        else:
            command = None
        return "<top>" + self.getHelp(command) + "</top>"

    def do_ls(self, *sp):
        """Displays the object tree at the current or specified location.
Arguments: [-N] location
By default the specified location and children are shown.  Use -N to specify how many children to show.  For example -2 will show this location, children and grandchildren.
    """
        depth = 1
        rest = [""]
        if len(sp):
            if sp[0][0] == "-":  # Its a flag
                depth = int(sp[0][1:])  # depth modifier flag
                if len(sp) > 1:
                    rest = sp[1:]
            else:
                rest = sp[0:]
        xml = []
        for r in rest:
            t = os.path.normpath(os.path.join(self.curdir, r))
            gs = "{d=%s}%s" % (depth, str(t))
            xml.append(access.mgtGet(gs))
        #print xml
        return "<top>" + "\n".join(
            xml
        ) + "</top>"  # I have to wrap in an xml tag in case I get 2 top levels from mgtGet

    def do_cd(self, location):
        """Change the current directory (object tree context)"""
        tmp = os.path.normpath(os.path.join(self.curdir, location))
        if access.isValidDirectory(tmp):
            self.curdir = tmp
            self.xmlterm.cmdLine.setPrompt()
        else:
            return "<error>Invalid path [%s]</error>" % tmp
        return ""

    def do_pwd(self, *sp):
        """Print working directory - shows the current directory"""
        return self.curdir

    def do_raw(self, *sp):
        """Equivalent to 'ls' but displays raw XML"""
        depth = 1
        prefix = "{d=%s}"
        rest = ""
        flags = sp
        for flag in flags:
            if flag[0] == "-":  # Its a flag
                if flag[1] == 'b':
                    prefix = "{b,d=%s}"
                elif flag[1] == 'p':
                    prefix = "{p,d=%s}"
                else:
                    try:
                        depth = int(flag[1:])  # depth modifier flag
                    except ValueError, e:
                        xt.doc.append("bad flag: " + flag)
                        pass
            else:
                rest = flag
        t = os.path.normpath(os.path.join(self.curdir, rest))
        # print (prefix % depth) + str(t)
        xml = access.mgtGet((prefix % depth) + str(t))
        txt = "<text>" + xmlterm.escape(
            xmlterm.indent("<top>" + xml + "</top>")) + "</text>"
        return txt  # I have to wrap in an xml tag in case I get 2 top levels from mgtGet