示例#1
0
def main():
    manager = HenManager()
    manager.initLogging()

    #    doc = minidom.Document()
    #    nodesTag = doc.createElement("nodes")
    #    doc.appendChild(nodesTag)
    #
    #    nodes = manager.getNodes("all")
    #    for nodeTypeDictionary in nodes.values():
    #        for node in nodeTypeDictionary.values():
    #
    #            nodeTag = doc.createElement("node")
    #            nodesTag.appendChild(nodeTag)
    #            targetNode = node.getNodeID()
    #            nodeTag.setAttribute("id", targetNode)
    #
    #    print doc.toprettyxml(indent = '    ')

    print "Cache-Control: no-store, no-cache, must-revalidate"
    print "Content-type: text/xml\n\n"

    print "<nodes>"
    nodes = manager.getNodes("all")
    for nodeTypeDictionary in nodes.values():
        for node in nodeTypeDictionary.values():
            print "\t<node id=\"" + node.getNodeID() + "\"/>"

    print "</nodes>"
示例#2
0
def interfaceid_to_mac(node_str,interface_str):
    manager = HenManager()
    manager.initLogging()
    nodes = manager.getNodes("all","all")
    for nt in nodes:
        for nn in nodes[nt]:
            if nodes[nt][nn].getNodeID().upper() == str(node_str).upper():
                mac = getmac_from_interface(nodes[nt][nn],interface_str)
                return mac
    return None
示例#3
0
文件: check_port.py 项目: sohonet/HEN
def check_port(computer_str,interface_str):
	print computer_str,interface_str,
	switch_str = ""
        port_str = ""

        computer = None
        interface = None
        switch = None
        port = None

        switch_obj = None
        
        manager = HenManager()
        manager.initLogging()
        nodes = manager.getNodes("all")
        
        for node_type in nodes:
            for node in nodes[node_type]:
                if nodes[node_type][node].getNodeID() == computer_str:
                    computer = nodes[node_type][node]
                    break
                
        if computer != None:
            interfaces = computer.getInterfaces()
            for interface_type in interfaces:
                for iface in interfaces[interface_type]:
                    if iface.getInterfaceID() == interface_str:
                        switch_str = iface.getSwitch()
                        port_str = iface.getPort()

        for node_type in nodes:
            for node in nodes[node_type]:
                #print node,switch_str
                if nodes[node_type][node].getNodeID() == switch_str:
                    switch = nodes[node_type][node]
                    break

        if switch != None:
            switch_obj = switch.getInstance()
        
        if switch_obj != None:
	   port_internal_id = switch_obj.getPortInternalID(port_str)
           if (switch_obj.getPortStatus(port_str) == 1):
	      print "up",
	   else:
	      print "down"
	   #print switch_obj.getPortsSpeedByInternalID([port_internal_id])[0][1]
	   print switch_obj.getPortTdr(port_str)
示例#4
0
def main():
    form = cgi.FieldStorage()
    manager = HenManager()
    manager.initLogging()

    print "Cache-Control: no-store, no-cache, must-revalidate"
    print "Content-type: text/xml\n"
    print "<experiments>"

    experiments = manager.getExperimentEntries()
    for experimentID in experiments.keys():
        #segments = experiment.split("/")
        #Bfilename = segments[len(segments) - 1]
        # slice off the '.xml' extension
        #fileid = filename[:-4]
        print "\t<experiment id=\"" + experimentID + "\"/>"

    print "</experiments>"
示例#5
0
def main():
    form = cgi.FieldStorage()
    manager = HenManager()
    manager.initLogging()


    if form.has_key("id"):
        experimentid = form["id"].value
        print experimentid
        #manager.experimentDelete(targetNode)

        #cmd = "export PYTHONPATH=$HOME/hen_scripts/hen_scripts/trunk/lib"
        #os.system(cmd)
        #cmd = "sudo hm experiment delete " + targetNode
        #os.system(cmd)


        server = xmlrpclib.ServerProxy(uri="http://localhost:50001/")
        server.delete(experimentid)
示例#6
0
def main():
    form = cgi.FieldStorage()
    manager = HenManager()
    manager.initLogging()


    print "Cache-Control: no-store, no-cache, must-revalidate"
    print "Content-type: text/xml\n"
    print "<experiments>"

    experiments = manager.getExperimentEntries()
    for experimentID in experiments.keys():
        #segments = experiment.split("/")
        #Bfilename = segments[len(segments) - 1]
        # slice off the '.xml' extension
        #fileid = filename[:-4]
        print "\t<experiment id=\"" + experimentID + "\"/>"

    print "</experiments>"
示例#7
0
    def run(self,argv):
        if len(argv) != 2:
            print "Usage :"+argv[0]+" <powerswitch name>"
            sys.exit(1)

        self.target_name = argv[1]
        
        manager = HenManager()
        manager.initLogging()
        nodes = manager.getNodes("powerswitch","all")

        self.target = None
        for node in nodes.values():
            if (node.getNodeID() == self.target_name):
                self.target = node.getInstance()
                
        if self.target == None:
            print "Unknown powerswitch "+argv[1]
            sys.exit(1)

        self.run_tests()
示例#8
0
 def old(self):
     BASE_URL="cgi-bin/gui/components/network/"
     
     manager = HenManager()
     manager.initLogging()
     
     links = manager.getLinks("all","all")
     graph = pydot.Dot()
 
     switches = manager.getNodes("switch")
     for switch in switches.values():
         if self.__switchStatuses.has_key(switch.getNodeID()):
             if self.__switchStatuses[switch.getNodeID()] == 1:
                 graph.add_node(pydot.Node(switch.getNodeID(),URL=BASE_URL+\
                   "switchinfocgi.py?id="+switch.getNodeID(),\
                   style="filled",color="chartreuse1"))
             else:
                 graph.add_node(pydot.Node(switch.getNodeID(),URL=BASE_URL+\
                   "switchinfocgi.py?id="+switch.getNodeID(),\
                   style="filled",color="firebrick"))
         else:
             graph.add_node(pydot.Node(switch.getNodeID(),URL=BASE_URL+\
                               "switchinfocgi.py?id="+switch.getNodeID()))
     for linktype in links.values():
         for link in linktype.values():
             members = link.getLinkMembers()
             
             graph.add_edge(pydot.Edge(str(members[0].getDeviceId()),\
               str(members[1].getDeviceId()),label=link.getLinkId(),\
               arrowhead="none",headlabel=str(members[1].getDevicePort().\
               replace('GigabitEthernet ','').replace('Management','M')),\
               taillabel=str(members[0].getDevicePort().\
               replace('GigabitEthernet','')),fontsize=8,\
               tooltip=link.getLinkId(),\
               URL=BASE_URL+"linkinfocgi.py?id="+link.getLinkId()))
 
     # prog='circo' isn't bad
     print graph.create_svg(prog='dot')
示例#9
0
class ComputerControl(Daemon):
    """\brief Implements basic computer daemon functionality.
    """
    __version = "Computer Daemon v0.1 (simple)"
    __henManager = None
    
    def __init__(self):
        Daemon.__init__(self)
        self.__henManager = HenManager()
        # Allow specialized instance dictionary to be created in hm
        # self.__henManager.createNodeInstances()
        self.__registerMethods()
        self.__computerID = self.__getComputerID()
        self.__computerInfo = self.__henManager.getNodes("computer")[self.__computerID]
        self.__ifaceIDtoNameMappings = self.__getIfaceMappings()

    def getComputerManagementIP(self):
        # Get the management ip address so that we can bind to it.
        interfaces = self.__computerInfo.getInterfaces("management")
        try:
            return interfaces[0].getIP()
        except:
            return "0.0.0.0"
        
    def __getComputerID(self):
        # Prints the name of the node that the script is run from. To do so it matches the mac addresses of
        # all running interfaces against the mac addresses in the testbed's database. Prints None if no match is found

        # First create a list containing the mac addresses of all the running interfaces
        macAddresses = []
        macAddressMatcher = re.compile('(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}')
        lines = commands.getstatusoutput("ifconfig")[1].splitlines()
        for line in lines:
            matchObject = macAddressMatcher.search(line)
            if (matchObject):
                macAddresses.append(line[matchObject.start():matchObject.end()].upper())

        # Now match the created list against all of the management mac addresses in the testbed's database
        # for computer nodes
        self.__henManager.initLogging()
        nodes = self.__henManager.getNodes("computer","all")
        nodeName = None
        for node in nodes.values():
            for interface in node.getInterfaces("management"):
                for macAddress in macAddresses:
                    if (macAddress == interface.getMAC().upper()):
                        nodeName = node.getNodeID()
        if nodeName == None:
            nodes = self.__henManager.getNodes("virtualcomputer","all")
            for node in nodes.values():
                for interface in node.getInterfaces("management"):
                    for macAddress in macAddresses:
                        if (macAddress == interface.getMAC().upper()):
                            nodeName = node.getNodeID()
        return nodeName

    def __getIfaceMappings(self):
        mappings = {}

        # Supports only Linux for now
        interfaces = self.__computerInfo.getInterfaces("experimental")
        ifacesInfo = commands.getstatusoutput("ifconfig -a | grep HWaddr")[1].splitlines()
        for interface in interfaces:
            for infoLine in ifacesInfo:
                if (infoLine.find(interface.getMAC()) != -1):
                    mappings[interface.getInterfaceID()] = infoLine[:infoLine.find(" ")]
        return mappings
    
    def __registerMethods(self):
        self.registerMethodHandler("get_computer_id", self.getComputerID)        
        self.registerMethodHandler("autodetect", self.autodetect)        
        self.registerMethodHandler("execute_command", self.executeCommand)
        self.registerMethodHandler("gcc_compile", self.gccCompile)
        self.registerMethodHandler("cat", self.cat)        
        self.registerMethodHandler("make", self.make)
        self.registerMethodHandler("mkdir", self.mkdir)        
        self.registerMethodHandler("untar", self.untar)
        self.registerMethodHandler("add_route", self.addRoute)
        self.registerMethodHandler("delete_route", self.delRoute)
        self.registerMethodHandler("config_iface", self.configIface)
        self.registerMethodHandler("click-align", self.clickAlign)
        self.registerMethodHandler("click-install", self.clickInstall)
        self.registerMethodHandler("click-uninstall", self.clickUninstall)
        self.registerMethodHandler("load_module", self.loadModule)
        self.registerMethodHandler("unload_module", self.unloadModule)
        self.registerMethodHandler("linux_forwarding_on", self.linuxForwardingOn)
        self.registerMethodHandler("linux_forwarding_off", self.linuxForwardingOff)                                        

    def __sendReply(self,prot,code,seq,payload):
        if (code == 0):
            code = 200
        else:
            code = 422 # returnCodes[422] = "error executing command"
        prot.sendReply(code, seq, payload)

    def autodetect(self,prot,seq,ln,payload):
        pass

    def getComputerID(self,prot,seq,ln,payload):
        self.__sendReply(prot,"0",seq,self.__computerID)
        
    def executeCommand(self,prot,seq,ln,payload):
        (code, payload) = commands.getstatusoutput(payload)
        self.__sendReply(prot,code,seq,payload)        
    
    def gccCompile(self,prot,seq,ln,payload):
        (workDir, filename) = pickle.loads(payload)
        name = filename[:filename.find(".")]
        (code, payload) = commands.getstatusoutput("cd " + worDir + " ; g++ -o " + name + " " + filename)
        self.__sendReply(prot,code,seq,payload)        

    def cat(self,prot,seq,ln,payload):
        #print "got cat command"
        payload = pickle.loads(payload)[0]
        (code, payload) = commands.getstatusoutput("cat " + str(payload))
        self.__sendReply(prot,code,seq,payload)

    def make(self,prot,seq,ln,payload):
        (workDir, makeTarget) = pickle.loads(payload)
        (code, payload) = commands.getstatusoutput("cd " + workDir + " ; make -f " + makeTarget)
        self.__sendReply(prot,code,seq,payload)        

    def mkdir(self,prot,seq,ln,payload):
        code = os.mkdir(payload)
        self.__sendReply(prot,code,seq,"")
        
    def untar(self,prot,seq,ln,payload):
        (tarPath, targetDir) = pickle.loads(payload)
        (code, payload) = commands.getstatusoutput("tar -xf " + path + " -C " + targetDir)
        self.__sendReply(prot,code,seq,payload)                

    def addRoute(self,prot,seq,ln,payload):
        (network, netmask, gateway, interface) = pickle.loads(payload)
        (code, payload) = commands.getstatusoutput("route add -net " + network + \
                                                   " netmask " + netmask + \
                                                   " gw " + gateway \
                                                   + " dev " + interface)
        self.__sendReply(prot,code,seq,payload)

    def delRoute(self,prot,seq,ln,payload):
        (network, netmask) = pickle.loads(payload)
        (code, payload) = commands.getstatusoutput("route del -net " + network + " netmask " + netmask)
        self.__sendReply(prot,code,seq,payload)

    def configIface(self,prot,seq,ln,payload):
        (interfaceID, address, mask, status) = pickle.loads(payload)
        try:
            cmd = "ifconfig " + self.__ifaceIDtoNameMappings[interfaceID] + " "
        except KeyError:
            log.error("Key error "+str( self.__ifaceIDtoNameMappings))
            (code, payload) = (400, "Key error for interface")
            self.__sendReply(prot,code,seq,payload)
            return
        if (status == "on"):
            cmd += address + " netmask " + mask + " up"
        else:
            cmd += "down"
        (code, payload) = commands.getstatusoutput(cmd)
        self.__sendReply(prot,code,seq,payload)        

    def clickAlign(self,prot,seq,ln,payload):
        (clickAlignPath, configFile) = pickle.loads(payload)
        basePath = configFile[:configFile.rfind("/")]
        filename = configFile[configFile.rfind("/") + 1: configFile.find(".")]
        newPathToFile = basePath + "/" + filename + "-aligned.click'"
        (code, payload) = commands.getstatusoutput(clickAlignPath + " " + configFile + " > " + newPathToFile)
        self.__sendReply(prot,code,seq,payload)                

    def clickInstall(self,prot,seq,ln,payload):
        (clickInstallPath, configFile, numberThreads) = pickle.loads(payload)
        cmd = click-installPath + " "
        if (int(numberThreads) != 0):
            cmd += "--threads=" + numberThreads + " "
        cmd += configFile
        (code, payload) = commands.getstatusoutput(cmd)
        self.__sendReply(prot,code,seq,payload)        

    def clickUninstall(self,prot,seq,ln,payload):
        (code, payload) = commands.getstatusoutput(payload)
        self.__sendReply(prot,code,seq,payload)        

    def loadModule(self,prot,seq,ln,payload):
        (code, payload) = commands.getstatusoutput("insmod " + payload)
        self.__sendReply(prot,code,seq,payload)                

    def unloadModule(self,prot,seq,ln,payload):
        (code, payload) = commands.getstatusoutput("rmmod " + payload)
        self.__sendReply(prot,code,seq,payload)                        

    def linuxForwardingOn(self,prot,seq,ln,payload):
        (code, payload) = commands.getstatusoutput("echo '1' \> /proc/sys/net/ipv4/ip_forward")
        self.__sendReply(prot,code,seq,payload)                                

    def linuxForwardingOff(self,prot,seq,ln,payload):
        (code, payload) = commands.getstatusoutput("echo '0' \> /proc/sys/net/ipv4/ip_forward")
        self.__sendReply(prot,code,seq,payload)                                        
        
    def stopDaemon(self,prot,seq,ln,payload):
        """\brief Stops the daemon and all threads
        This method will first stop any more incoming queries, then wait for
        any update tasks to complete, before stopping itself.
        """
        log.info("stopDaemon called.")
        prot.sendReply(200, seq, "Accepted stop request.")
        log.debug("Sending stopDaemon() response")
        self.acceptConnections(False)
        log.info("Stopping ComputerDaemon (self)")
        self.stop()
示例#10
0
文件: nodeid.py 项目: benroeder/HEN
import commands, re
from henmanager import HenManager

# First create a list containing the mac addresses of all the running interfaces
macAddresses = []
macAddressMatcher = re.compile("(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}")
lines = commands.getstatusoutput("ifconfig")[1].splitlines()
for line in lines:
    matchObject = macAddressMatcher.search(line)
    if matchObject:
        macAddresses.append(line[matchObject.start() : matchObject.end()].upper())

# Now match the created list against all of the management mac addresses in the testbed's database
# for computer nodes
manager = HenManager()
manager.initLogging()
nodes = manager.getNodes("computer", "all")
nodeName = None
for node in nodes.values():
    for interface in node.getInterfaces("management"):
        for macAddress in macAddresses:
            if macAddress == interface.getMAC().upper():
                nodeName = node.getNodeID()
if nodeName == None:
    nodes = manager.getNodes("virtualcomputer", "all")
    for node in nodes.values():
        for interface in node.getInterfaces("management"):
            for macAddress in macAddresses:
                if macAddress == interface.getMAC().upper():
                    nodeName = node.getNodeID()
print nodeName
示例#11
0
#! /usr/bin/env python
from henmanager import HenManager
from auxiliary.hen import Node, SwitchNode, VLAN, Port

manager = HenManager()
manager.initLogging()
nodes = manager.getNodes("switch")

theSwitch = None
for node in nodes.values():
    #    print node
    if (node.getNodeID() == "switch1"):
        print node.getNodeID()
        theSwitch = node.getInstance()

vlans = theSwitch.getFullVLANInfo()
for vlan in vlans:
    print vlan

#res = theSwitch.getVLANToInterfacesTable()

#for p in res:
#    print str(p) + " res " + str(res[p])
示例#12
0
def main():

    manager = HenManager()
    manager.initLogging()
    #switchdb automatically loads most information into memory.
    switchdb = SwitchDB(manager)
示例#13
0
class ComputerControl(Daemon):
    """\brief Implements basic computer daemon functionality.
    """

    __version = "Computer Daemon v0.1 (simple)"
    __henManager = None

    def __init__(self):
        Daemon.__init__(self)
        self.__henManager = HenManager()
        # Allow specialized instance dictionary to be created in hm
        # self.__henManager.createNodeInstances()
        self.__registerMethods()
        self.__computerID = self.__getComputerID()
        self.__computerInfo = self.__henManager.getNodes("computer")[self.__computerID]
        self.__ifaceIDtoNameMappings = self.__getIfaceMappings()

    def getComputerManagementIP(self):
        # Get the management ip address so that we can bind to it.
        interfaces = self.__computerInfo.getInterfaces("management")
        try:
            return interfaces[0].getIP()
        except:
            return "0.0.0.0"

    def __getComputerID(self):
        # Prints the name of the node that the script is run from. To do so it matches the mac addresses of
        # all running interfaces against the mac addresses in the testbed's database. Prints None if no match is found

        # First create a list containing the mac addresses of all the running interfaces
        macAddresses = []
        macAddressMatcher = re.compile("(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}")
        lines = commands.getstatusoutput("ifconfig")[1].splitlines()
        for line in lines:
            matchObject = macAddressMatcher.search(line)
            if matchObject:
                macAddresses.append(line[matchObject.start() : matchObject.end()].upper())

        # Now match the created list against all of the management mac addresses in the testbed's database
        # for computer nodes
        self.__henManager.initLogging()
        nodes = self.__henManager.getNodes("computer", "all")
        nodeName = None
        for node in nodes.values():
            for interface in node.getInterfaces("management"):
                for macAddress in macAddresses:
                    if macAddress == interface.getMAC().upper():
                        nodeName = node.getNodeID()
        if nodeName == None:
            nodes = self.__henManager.getNodes("virtualcomputer", "all")
            for node in nodes.values():
                for interface in node.getInterfaces("management"):
                    for macAddress in macAddresses:
                        if macAddress == interface.getMAC().upper():
                            nodeName = node.getNodeID()
        return nodeName

    def __getIfaceMappings(self):
        mappings = {}

        # Supports only Linux for now
        interfaces = self.__computerInfo.getInterfaces("experimental")
        ifacesInfo = commands.getstatusoutput("ifconfig -a | grep HWaddr")[1].splitlines()
        for interface in interfaces:
            for infoLine in ifacesInfo:
                if infoLine.find(interface.getMAC()) != -1:
                    mappings[interface.getInterfaceID()] = infoLine[: infoLine.find(" ")]
        return mappings

    def __registerMethods(self):
        self.registerMethodHandler("get_computer_id", self.getComputerID)
        self.registerMethodHandler("autodetect", self.autodetect)
        self.registerMethodHandler("execute_command", self.executeCommand)
        self.registerMethodHandler("gcc_compile", self.gccCompile)
        self.registerMethodHandler("cat", self.cat)
        self.registerMethodHandler("make", self.make)
        self.registerMethodHandler("mkdir", self.mkdir)
        self.registerMethodHandler("untar", self.untar)
        self.registerMethodHandler("add_route", self.addRoute)
        self.registerMethodHandler("delete_route", self.delRoute)
        self.registerMethodHandler("config_iface", self.configIface)
        self.registerMethodHandler("click-align", self.clickAlign)
        self.registerMethodHandler("click-install", self.clickInstall)
        self.registerMethodHandler("click-uninstall", self.clickUninstall)
        self.registerMethodHandler("load_module", self.loadModule)
        self.registerMethodHandler("unload_module", self.unloadModule)
        self.registerMethodHandler("linux_forwarding_on", self.linuxForwardingOn)
        self.registerMethodHandler("linux_forwarding_off", self.linuxForwardingOff)

    def __sendReply(self, prot, code, seq, payload):
        if code == 0:
            code = 200
        else:
            code = 422  # returnCodes[422] = "error executing command"
        prot.sendReply(code, seq, payload)

    def autodetect(self, prot, seq, ln, payload):
        pass

    def getComputerID(self, prot, seq, ln, payload):
        self.__sendReply(prot, "0", seq, self.__computerID)

    def executeCommand(self, prot, seq, ln, payload):
        (code, payload) = commands.getstatusoutput(payload)
        self.__sendReply(prot, code, seq, payload)

    def gccCompile(self, prot, seq, ln, payload):
        (workDir, filename) = pickle.loads(payload)
        name = filename[: filename.find(".")]
        (code, payload) = commands.getstatusoutput("cd " + worDir + " ; g++ -o " + name + " " + filename)
        self.__sendReply(prot, code, seq, payload)

    def cat(self, prot, seq, ln, payload):
        # print "got cat command"
        payload = pickle.loads(payload)[0]
        (code, payload) = commands.getstatusoutput("cat " + str(payload))
        self.__sendReply(prot, code, seq, payload)

    def make(self, prot, seq, ln, payload):
        (workDir, makeTarget) = pickle.loads(payload)
        (code, payload) = commands.getstatusoutput("cd " + workDir + " ; make -f " + makeTarget)
        self.__sendReply(prot, code, seq, payload)

    def mkdir(self, prot, seq, ln, payload):
        code = os.mkdir(payload)
        self.__sendReply(prot, code, seq, "")

    def untar(self, prot, seq, ln, payload):
        (tarPath, targetDir) = pickle.loads(payload)
        (code, payload) = commands.getstatusoutput("tar -xf " + path + " -C " + targetDir)
        self.__sendReply(prot, code, seq, payload)

    def addRoute(self, prot, seq, ln, payload):
        (network, netmask, gateway, interface) = pickle.loads(payload)
        (code, payload) = commands.getstatusoutput(
            "route add -net " + network + " netmask " + netmask + " gw " + gateway + " dev " + interface
        )
        self.__sendReply(prot, code, seq, payload)

    def delRoute(self, prot, seq, ln, payload):
        (network, netmask) = pickle.loads(payload)
        (code, payload) = commands.getstatusoutput("route del -net " + network + " netmask " + netmask)
        self.__sendReply(prot, code, seq, payload)

    def configIface(self, prot, seq, ln, payload):
        (interfaceID, address, mask, status) = pickle.loads(payload)
        try:
            cmd = "ifconfig " + self.__ifaceIDtoNameMappings[interfaceID] + " "
        except KeyError:
            log.error("Key error " + str(self.__ifaceIDtoNameMappings))
            (code, payload) = (400, "Key error for interface")
            self.__sendReply(prot, code, seq, payload)
            return
        if status == "on":
            cmd += address + " netmask " + mask + " up"
        else:
            cmd += "down"
        (code, payload) = commands.getstatusoutput(cmd)
        self.__sendReply(prot, code, seq, payload)

    def clickAlign(self, prot, seq, ln, payload):
        (clickAlignPath, configFile) = pickle.loads(payload)
        basePath = configFile[: configFile.rfind("/")]
        filename = configFile[configFile.rfind("/") + 1 : configFile.find(".")]
        newPathToFile = basePath + "/" + filename + "-aligned.click'"
        (code, payload) = commands.getstatusoutput(clickAlignPath + " " + configFile + " > " + newPathToFile)
        self.__sendReply(prot, code, seq, payload)

    def clickInstall(self, prot, seq, ln, payload):
        (clickInstallPath, configFile, numberThreads) = pickle.loads(payload)
        cmd = click - installPath + " "
        if int(numberThreads) != 0:
            cmd += "--threads=" + numberThreads + " "
        cmd += configFile
        (code, payload) = commands.getstatusoutput(cmd)
        self.__sendReply(prot, code, seq, payload)

    def clickUninstall(self, prot, seq, ln, payload):
        (code, payload) = commands.getstatusoutput(payload)
        self.__sendReply(prot, code, seq, payload)

    def loadModule(self, prot, seq, ln, payload):
        (code, payload) = commands.getstatusoutput("insmod " + payload)
        self.__sendReply(prot, code, seq, payload)

    def unloadModule(self, prot, seq, ln, payload):
        (code, payload) = commands.getstatusoutput("rmmod " + payload)
        self.__sendReply(prot, code, seq, payload)

    def linuxForwardingOn(self, prot, seq, ln, payload):
        (code, payload) = commands.getstatusoutput("echo '1' \> /proc/sys/net/ipv4/ip_forward")
        self.__sendReply(prot, code, seq, payload)

    def linuxForwardingOff(self, prot, seq, ln, payload):
        (code, payload) = commands.getstatusoutput("echo '0' \> /proc/sys/net/ipv4/ip_forward")
        self.__sendReply(prot, code, seq, payload)

    def stopDaemon(self, prot, seq, ln, payload):
        """\brief Stops the daemon and all threads
        This method will first stop any more incoming queries, then wait for
        any update tasks to complete, before stopping itself.
        """
        log.info("stopDaemon called.")
        prot.sendReply(200, seq, "Accepted stop request.")
        log.debug("Sending stopDaemon() response")
        self.acceptConnections(False)
        log.info("Stopping ComputerDaemon (self)")
        self.stop()
示例#14
0
def main():
    
    manager = HenManager()
    manager.initLogging()
    #switchdb automatically loads most information into memory.
    switchdb = SwitchDB(manager)
示例#15
0
class AutodetectManager(Daemon):

    __hen_manager = None
    __hardware_processor = None

    def __init__(self):
        Daemon.__init__(self)
        self.__hen_manager = HenManager()
        self.__hen_manager.initLogging()
        self.__hardware_processor = LSHardwareProcessor(self.__hen_manager, \
                                                    self.__parseMacTableURL())
        self.__registerMethods()

    def __parseMacTableURL(self):
        """\brief Parses the Hen config file, and returns the MACTABLE_URL
            \return macTableURL - the value of MACTABLE_URL in the Hen config
        """
        configFile = ConfigParser.ConfigParser()
        configFile.read(HEN_CONFIG)
        return configFile.get('AUTODETECT', 'MACTABLE_URL')

    def __registerMethods(self):
        self.registerMethodHandler("receive_detectiondata", \
                                   self.receiveDetectionData)
        self.registerMethodHandler("enable_debug_mode", \
                                   self.enableDebugMode)
        self.registerMethodHandler("disable_debug_mode", \
                                   self.disableDebugMode)

    def enableDebugMode(self,prot,seq,ln,payload):
        self.__hardware_processor.enableDebugMode()
        prot.sendReply(200, seq, "")

    def disableDebugMode(self,prot,seq,ln,payload):
        self.__hardware_processor.disableDebugMode()
        prot.sendReply(200, seq, "")
        
    def receiveDetectionData(self,prot,seq,ln,payload):
        """\brief Method called when detection data is received from
            autodetectclient scripts being run on remote hosts.
        """
        log.debug("receiveDetectionData() called.")
        (nodeid, addr) = self.__ipAddressToNodeID(prot.getSocket())
        if not nodeid or not addr:
            log.warning("Bad results from __ipAddressToNodeID().")
            prot.sendReply(500, seq, \
                   "Failure: Daemon could not resolve IP to nodeid.")
            return
        log.info("received data from %s (%s)" % (str(addr), str(nodeid)))
        prot.sendReply(200, seq, "")
        self.__hardware_processor.parseFileAndPrint(nodeid, payload)


    def __ipAddressToNodeID(self, sock):
        """\brief Retrieves the IP address of the connected client, then tries
            to look up a nodeid for it from HenManager
            \param sock - socket on which the client is connected
            \return nodeid - id of node to which IP address belongs, -1 if not
                                found
        """
        try:
            (addr, port) = sock.getpeername()       
            log.debug("addr %" + str(addr))            
            computerNodes = self.__hen_manager.getNodes("computer", "all")
            for computerNode in computerNodes.values():
                interfaces = computerNode.getInterfaces("management")
                for interface in interfaces:
                    if (interface.getIP() == addr):
                        return (computerNode.getNodeID(), addr)
        except:
            pass
        return (None, None)
示例#16
0
class AutodetectManager(Daemon):

    __hen_manager = None
    __hardware_processor = None

    def __init__(self):
        Daemon.__init__(self)
        self.__hen_manager = HenManager()
        self.__hen_manager.initLogging()
        self.__hardware_processor = LSHardwareProcessor(self.__hen_manager, \
                                                    self.__parseMacTableURL())
        self.__registerMethods()

    def __parseMacTableURL(self):
        """\brief Parses the Hen config file, and returns the MACTABLE_URL
            \return macTableURL - the value of MACTABLE_URL in the Hen config
        """
        configFile = ConfigParser.ConfigParser()
        configFile.read(HEN_CONFIG)
        return configFile.get('AUTODETECT', 'MACTABLE_URL')

    def __registerMethods(self):
        self.registerMethodHandler("receive_detectiondata", \
                                   self.receiveDetectionData)
        self.registerMethodHandler("enable_debug_mode", \
                                   self.enableDebugMode)
        self.registerMethodHandler("disable_debug_mode", \
                                   self.disableDebugMode)

    def enableDebugMode(self, prot, seq, ln, payload):
        self.__hardware_processor.enableDebugMode()
        prot.sendReply(200, seq, "")

    def disableDebugMode(self, prot, seq, ln, payload):
        self.__hardware_processor.disableDebugMode()
        prot.sendReply(200, seq, "")

    def receiveDetectionData(self, prot, seq, ln, payload):
        """\brief Method called when detection data is received from
            autodetectclient scripts being run on remote hosts.
        """
        log.debug("receiveDetectionData() called.")
        (nodeid, addr) = self.__ipAddressToNodeID(prot.getSocket())
        if not nodeid or not addr:
            log.warning("Bad results from __ipAddressToNodeID().")
            prot.sendReply(500, seq, \
                   "Failure: Daemon could not resolve IP to nodeid.")
            return
        log.info("received data from %s (%s)" % (str(addr), str(nodeid)))
        prot.sendReply(200, seq, "")
        self.__hardware_processor.parseFileAndPrint(nodeid, payload)

    def __ipAddressToNodeID(self, sock):
        """\brief Retrieves the IP address of the connected client, then tries
            to look up a nodeid for it from HenManager
            \param sock - socket on which the client is connected
            \return nodeid - id of node to which IP address belongs, -1 if not
                                found
        """
        try:
            (addr, port) = sock.getpeername()
            log.debug("addr %" + str(addr))
            computerNodes = self.__hen_manager.getNodes("computer", "all")
            for computerNode in computerNodes.values():
                interfaces = computerNode.getInterfaces("management")
                for interface in interfaces:
                    if (interface.getIP() == addr):
                        return (computerNode.getNodeID(), addr)
        except:
            pass
        return (None, None)