Example #1
0
 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()
Example #2
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>"
Example #3
0
def main():
    if len(sys.argv) != 2:
        print "FAIL: nodeid not provided!"
        return -1
    
    nodeid = sys.argv[1]
    hm = HenManager()
    if (hm.power(sys.argv[1], "poweroff") < 0):
        print "FAIL: hm.power(%s, \"poweroff\") failed (cause unknown)!"\
                % nodeid
        return -1
    time.sleep(2)
    (sts, output) = hm.powerSilent(sys.argv[1], "status")
    if (sts < 0):
        print "FAIL: hm.power(%s, \"status\") returned: %s" % (nodeid, output)
        return -1
    if (output == "on"):
        print "FAIL: hm.power(%s, \"status\") says the node is still on!" \
                    % nodeid
        return -1
    if (output == "off"):
        print "SUCCESS: hm.power(%s, \"poweroff\") succeeded." % nodeid
        return 0
    print "FAIL: hm.power(%s, \"status\") returned: %s" % (nodeid, output)
    return -1
Example #4
0
def main():
    if len(sys.argv) != 2:
        print "FAIL: nodeid not provided!"
        return -1

    nodeid = sys.argv[1]
    hm = HenManager()
    if (hm.power(sys.argv[1], "poweroff") < 0):
        print "FAIL: hm.power(%s, \"poweroff\") failed (cause unknown)!"\
                % nodeid
        return -1
    time.sleep(2)
    (sts, output) = hm.powerSilent(sys.argv[1], "status")
    if (sts < 0):
        print "FAIL: hm.power(%s, \"status\") returned: %s" % (nodeid, output)
        return -1
    if (output == "on"):
        print "FAIL: hm.power(%s, \"status\") says the node is still on!" \
                    % nodeid
        return -1
    if (output == "off"):
        print "SUCCESS: hm.power(%s, \"poweroff\") succeeded." % nodeid
        return 0
    print "FAIL: hm.power(%s, \"status\") returned: %s" % (nodeid, output)
    return -1
Example #5
0
    def writeDHCPConfig(self):
        """\brief Writes the dhcp config file
        """
        dnsServer = self.getDHCPConfigInfo().getDomainNameServers()
        self.__outputFile = open(self.__outputFilename, "w")
        manager = HenManager()
        nodes = manager.getNodes("all", "all")
        #        if (not self.__parser):
        #            print "error: parser is null"
        #            return
        #        self.__parser.parseAll()
        #        nodes = self.__parser.getNodes("all", "all")

        # write initial block
        self.__writeStartingBlock()

        # process each subnet
        subnetInfoList = self.getDHCPConfigInfo().getSubnetInfoList()

        for subnetInfo in subnetInfoList:

            self.__writeSubnetBlock(subnetInfo)
            if (subnetInfo.getSubnetType() == "experimental"):
                for nodeType in nodes.keys():
                    for node in nodes[nodeType].values():
                        interfacesList = node.getInterfaces("management")
                        if (interfacesList != None):
                            for interface in interfacesList:
                                self.__writeNode(node.getNodeID(), interface,
                                                 node.getNetbootable(),
                                                 dnsServer, node.getNodeType(),
                                                 subnetInfo.getDomainName())
            elif (subnetInfo.getSubnetType() == "infrastructure"):
                for nodeType in nodes.keys():
                    for node in nodes[nodeType].values():
                        interfacesList = node.getInterfaces("infrastructure")
                        if (interfacesList != None):
                            for interface in interfacesList:
                                self.__writeNode(node.getNodeID(), interface,
                                                 node.getNetbootable(),
                                                 dnsServer, node.getNodeType(),
                                                 subnetInfo.getDomainName())
            elif (subnetInfo.getSubnetType() == "virtual"):
                for nodeType in nodes.keys():
                    for node in nodes[nodeType].values():
                        interfacesList = node.getInterfaces("virtual")

                        if (interfacesList != None):
                            for interface in interfacesList:
                                self.__writeNode(node.getNodeID(), interface,
                                                 node.getNetbootable(),
                                                 dnsServer, node.getNodeType(),
                                                 subnetInfo.getDomainName())

            self.__writeEndingBlock()

        self.__closeFile()
        return 0
Example #6
0
 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()
Example #7
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
Example #8
0
    def writeDHCPConfig(self):
        """\brief Writes the dhcp config file
        """
        dnsServer = self.getDHCPConfigInfo().getDomainNameServers()
        self.__outputFile = open(self.__outputFilename, "w")
        manager = HenManager()
        nodes = manager.getNodes("all","all")
#        if (not self.__parser):
#            print "error: parser is null"
#            return
#        self.__parser.parseAll()
#        nodes = self.__parser.getNodes("all", "all")

        # write initial block
	self.__writeStartingBlock()

        # process each subnet
        subnetInfoList = self.getDHCPConfigInfo().getSubnetInfoList()
        
        for subnetInfo in subnetInfoList:
            
            self.__writeSubnetBlock(subnetInfo)
            if (subnetInfo.getSubnetType() == "experimental"):
                for nodeType in nodes.keys():
                    for node in nodes[nodeType].values():
                        interfacesList = node.getInterfaces("management")
                        if (interfacesList != None):
                            for interface in interfacesList:
                                self.__writeNode(node.getNodeID(), interface, node.getNetbootable(), dnsServer, node.getNodeType(), subnetInfo.getDomainName())
            elif (subnetInfo.getSubnetType() == "infrastructure"):
                for nodeType in nodes.keys():
                    for node in nodes[nodeType].values():
                        interfacesList = node.getInterfaces("infrastructure")
                        if (interfacesList != None):
                            for interface in interfacesList:
                                self.__writeNode(node.getNodeID(), interface, node.getNetbootable(), dnsServer, node.getNodeType(), subnetInfo.getDomainName())
            elif (subnetInfo.getSubnetType() == "virtual"):
                for nodeType in nodes.keys():
                    for node in nodes[nodeType].values():
                        interfacesList = node.getInterfaces("virtual")
                        
                        if (interfacesList != None):
                            for interface in interfacesList:
                                self.__writeNode(node.getNodeID(), interface, node.getNetbootable(), dnsServer, node.getNodeType(), subnetInfo.getDomainName())

            self.__writeEndingBlock()

        self. __closeFile()
        return 0
Example #9
0
class FileNodeManager:

    def __init__(self):
        self.__manager = HenManager()

    def fileNodeCreate(self, fileNodeType, owner, path, architecture, osType, version, mustClone, description, attributes, username, password):

        return self.__manager.fileNodeCreate(fileNodeType, owner, path, architecture, osType, version, mustClone, description, attributes, username, password)
    
    def elementEdit(self, elementID, parameters, attributes):
        return self.__manager. elementEdit(elementID, parameters, attributes)

    def elementDelete(self, elementID):
        # Send a non-manager delete command
        return self.__manager.elementDelete(elementID, False)
Example #10
0
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)
Example #11
0
    def __init__(self):
        Daemon.__init__(self)
        # Initalise variables
        self.__henManager = HenManager()
        self.__nodes = None
        self.__vlans = {}  #
        self.__vlan_info = {}  # switch_name -> [vlan_name,vlan_name,...]
        self.__switch_instances = {}
        self.__test_mode = False
        self.__minimum_id = 200
        self.__maximum_id = 2000
        self.__vlanOwnerFilename = "/usr/local/hen/etc/switchd/vlan_owner.dat"

        self.__int_to_vlan = {}  # (computer_str,interface_str) -> vlan_name

        self.__switchdb = SwitchDB()
        log.debug("Switchdb " + str(self.__switchdb))
        # Register hen rpc methods and handlers
        log.debug("Registering methods")
        self.__registerMethods()
        # Load vlan info
        log.debug("Loading vlan info")
        self.__initaliseVlanInfo()
        # Setup mac polling
        log.debug("Loading henmanager")
        self.__switchdb.setHenManager(self.__henManager)
        log.debug("Loading links Db")
        self.__switchdb.loadLinksDb()
        log.debug("Initiating Nodes")
        self.initiateNodes()

        # vlan owners
        self.__vlan_owner_name = {}
        self.__vlan_name_owner = {}
        self.loadVlanOwnerFile()
Example #12
0
class ConfigManager:

    def __init__(self):
        self.__manager = HenManager()

    def writeConfigFileLines(self, lines):
        return self.__manager.writeConfigFileLines(lines)
Example #13
0
 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()
Example #14
0
 def __init__(self, filename, rightsFilename, notificationsFilename, dbsRoot, maxNumWeeks=2,debug=False):
     self.__daemonEMail = "*****@*****.**"        
     self.__filename = filename
     self.__rightsFilename = rightsFilename
     self.__notificationsFilename = notificationsFilename
     self.__notifications = {}        
     self.__dbsRoot = dbsRoot
     self.__maxNumWeeks = maxNumWeeks
     self.__reservations = {}
     self.__rights = {}
     self.__nextID = 0
     self.__xmldoc = None
     self.__rightsXmldoc = None
     self.__henManager = HenManager()
     self.__symlinksRoot = "/export/machines/"
     self.__smtpServerName = "smtp.cs.ucl.ac.uk"
     self.__parser = ReservationDBParser(filename, rightsFilename, notificationsFilename, self.__dbsRoot)
     self.__notifier = None        
     self.__debug = debug
     self.mytime = datetime.date.today()
     
     # Start the early notification thread
     self.__notifier = ReservationExpiryNotifier(self.__daemonEMail, \
                                                 self.__smtpServerName, \
                                                 self.__filename, \
                                                 self.__rightsFilename, \
                                                 self.__notificationsFilename, \
                                                 self.__dbsRoot,
                                                 self.__debug)
     if not self.__debug:
         self.__notifier.start()
Example #15
0
class ElementManager:

    def __init__(self):
        self.__manager = HenManager()

    ##########################################################################################        
    # Create functions
    ##########################################################################################
    def computerNodeCreate(self, netbootable, infrastructure, rackName, macAddress, powerID, powerPort, serialID, serialPort, serviceProcessorID, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, status, vendor, model):
        return self.__manager.computerNodeCreate(netbootable, infrastructure, rackName, macAddress, powerID, powerPort, serialID, serialPort, serviceProcessorID, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, status, vendor, model)

    def serverNodeCreate(self, rackName, serialID, serialPort, managementMAC, infrastructureMAC, externalMAC, externalIP, externalSubnet, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, powerID, powerPort, serviceProcessorID, status, vendor, model):
        return self.__manager.serverNodeCreate(rackName, serialID, serialPort, managementMAC, infrastructureMAC, externalMAC, externalIP, externalSubnet, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, powerID, powerPort, serviceProcessorID, status, vendor, model)

    def serialNodeCreate(self, vendor, model, macAddress, powerID, powerPort, username, password, rackName, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, status):
        return self.__manager.serialNodeCreate(vendor, model, macAddress, powerID, powerPort, username, password, rackName, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, status)

    def switchNodeCreate(self, infrastructure, vendor, model, macAddress, powerID, powerPort, serialID, serialPort, rackName, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, status):
        return self.__manager.switchNodeCreate(infrastructure, vendor, model, macAddress, powerID, powerPort, serialID, serialPort, rackName, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, status)
        
    def powerswitchNodeCreate(self, vendor, model, macAddress, serialID, serialPort, rackName, username, password, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, status):
        return self.__manager.powerswitchNodeCreate(vendor, model, macAddress, serialID, serialPort, rackName, username, password, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, status)

    def routerNodeCreate(self, vendor, model, macAddress, powerID, powerPort, serialID, serialPort, rackName, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, status):
        return self.__manager.routerNodeCreate(vendor, model, macAddress, powerID, powerPort, serialID, serialPort, rackName, attributes, building, floor, room, rackRow, rackStartUnit, rackEndUnit, rackPosition, status)
            
    def serviceprocessorNodeCreate(self, macAddress, powerID, powerPort, username, password, attributes, status, vendor, model):
        return self.__manager.serviceprocessorNodeCreate(macAddress, powerID, powerPort, username, password, attributes, status, vendor, model)

    def infrastructureRackCreate(self, vendor, model, description, building, floor, room, rackRow, rowPosition, height, width, depth, rearRightSlots, rearLeftSlots, numberUnits, status, attributes):
        return self.__manager.infrastructureRackCreate(vendor, model, description, building, floor, room, rackRow, rowPosition, height, width, depth, rearRightSlots, rearLeftSlots, numberUnits, status, attributes)

    def fileNodeCreate(self, fileNodeType, owner, path, architecture, osType, version, mustClone, description, attributes, username, password, status):
        return self.__manager.fileNodeCreate(fileNodeType, owner, path, architecture, osType, version, mustClone, description, attributes, username, password, status)

    ##########################################################################################
    # Edit functions
    ##########################################################################################
    def elementEdit(self, elementID, parameters, attributes):
        return self.__manager. elementEdit(elementID, parameters, attributes)

    ##########################################################################################    
    # Delete functions
    ##########################################################################################
    def elementDelete(self, elementID):
        return self.__manager.elementDelete(elementID)
Example #16
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>"
Example #17
0
 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()
Example #18
0
File: filed.py Project: sohonet/HEN
class FileNodeManager:
    def __init__(self):
        self.__manager = HenManager()

    def fileNodeCreate(self, fileNodeType, owner, path, architecture, osType,
                       version, mustClone, description, attributes, username,
                       password):

        return self.__manager.fileNodeCreate(fileNodeType, owner, path,
                                             architecture, osType, version,
                                             mustClone, description,
                                             attributes, username, password)

    def elementEdit(self, elementID, parameters, attributes):
        return self.__manager.elementEdit(elementID, parameters, attributes)

    def elementDelete(self, elementID):
        # Send a non-manager delete command
        return self.__manager.elementDelete(elementID, False)
Example #19
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)
Example #20
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>"
Example #21
0
def main():
    # due to possible name resolution issues, use '127.0.0.1'
    # instead of localhost
    #myHost = gethostname()
    #myHost = "192.168.0.1"
    myPort = 55000
    myHost = "127.0.0.1"
    #myPort = 4789

    s = socket(AF_INET, SOCK_STREAM)  # create a TCP socket
    s.bind((myHost, myPort))  # bind it to the server port
    s.listen(5)  # allow 5 simultaneous
    # pending connections

    manager = HenManager()
    dir = '/tmp/'
    filename = 'dumpfile'
    filepath = dir + filename

    while 1:
        # wait for next client to connect
        (connection, address) = s.accept()  # connection is a new socket
        total_data = []
        while 1:
            data = connection.recv(32768)
            print data
            if not data: break
            total_data.append(data)

        f = open(filepath, 'w')
        f.write(''.join(total_data))
        f.close()
        connection.close()  # close socket

        # open file again as readonly
        f = open(filepath, "r")
        lines = f.read()

        # find the experimentid attribute
        fname = re.findall('experimentid=\"[a-zA-Z0-9]+\"', lines)
        fn = fname[0]
        # get start index of attribute value
        start = string.find(fn, "\"")
        fid = fn[start + 1:-1]

        # rename file to its id
        newfilepath = dir + fid
        os.rename(filepath, newfilepath)
        f.close()

        #manager.experimentCreate(filepath)
        cmd = "export PYTHONPATH=$HOME/hen_scripts/hen_scripts/trunk/lib"
        os.system(cmd)
        cmd = "cd /tmp; sudo hm experiment create " + fid + " " + fid
        os.system(cmd)
Example #22
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()
Example #23
0
    def __init__(self,
                 filename,
                 rightsFilename,
                 notificationsFilename,
                 dbsRoot,
                 maxNumWeeks=2,
                 debug=False):
        self.__daemonEMail = "*****@*****.**"
        self.__filename = filename
        self.__rightsFilename = rightsFilename
        self.__notificationsFilename = notificationsFilename
        self.__notifications = {}
        self.__dbsRoot = dbsRoot
        self.__maxNumWeeks = maxNumWeeks
        self.__reservations = {}
        self.__rights = {}
        self.__nextID = 0
        self.__xmldoc = None
        self.__rightsXmldoc = None
        self.__henManager = HenManager()
        self.__symlinksRoot = "/export/machines/"
        self.__smtpServerName = "smtp.cs.ucl.ac.uk"
        self.__parser = ReservationDBParser(filename, rightsFilename,
                                            notificationsFilename,
                                            self.__dbsRoot)
        self.__notifier = None
        self.__debug = debug
        self.mytime = datetime.date.today()

        # Start the early notification thread
        self.__notifier = ReservationExpiryNotifier(self.__daemonEMail, \
                                                    self.__smtpServerName, \
                                                    self.__filename, \
                                                    self.__rightsFilename, \
                                                    self.__notificationsFilename, \
                                                    self.__dbsRoot,
                                                    self.__debug)
        if not self.__debug:
            self.__notifier.start()
Example #24
0
    def load_data(self):
        log.info("Loading Data")
        self.__manager = HenManager()
        for i in range(1, 254):
            self.__man_ips["192.168.0." + str(i)] = "free"
            self.__inf_ips["192.168.1." + str(i)] = "free"

        n = self.__manager.getNodes("all", "all")
        for nt in n:
            for node in n[nt].values():
                try:
                    man_ip = node.getInterfaces("management")
                    inf_ip = node.getInterfaces("infrastructure")
                    if man_ip != []:
                        self.__nodes[man_ip[0].getIP()] = node
                        self.__man_ips[str(
                            man_ip[0].getIP())] = node.getNodeID()
                    if inf_ip != []:
                        self.__nodes[inf_ip[0].getIP()] = node
                        self.__inf_ips[str(
                            inf_ip[0].getIP())] = node.getNodeID()
                except:
                    pass
        self.show_stats()
Example #25
0
class ConfigReader(Daemon):
    """\brief Implements basic config daemon functionality.
    """
    __version = "Config Daemon v0.1 (simple)"
    __henManager = None
    
    def __init__(self):
        Daemon.__init__(self)
        self.__henManager = HenManager()
        self.__registerMethods()
        
    def __registerMethods(self):
        self.registerMethodHandler("get_object_for_id", self.getObjectForId)
        self.registerMethodHandler("stop_daemon", self.stopDaemon)
        
    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 getObjectForId(self,prot,seq,ln,payload):
        nodes = self.__henManager.getNodes("all")
        for ntk in nodes:
            #print "ntk ",str(ntk)
            for nk in nodes[ntk]:
                #print "nk ",str(nk)
                if nodes[ntk][nk].getNodeID() == payload:
                    payload=pickle.dumps(nodes[ntk][nk])
                    code = 0
                    self.__sendReply(prot,code,seq,payload)
                    return
        payload = "not found"
        code = -1
        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 ConfigDaemon (self)")
        self.stop()
Example #26
0
class ConfigReader(Daemon):
    """\brief Implements basic config daemon functionality.
    """
    __version = "Config Daemon v0.1 (simple)"
    __henManager = None

    def __init__(self):
        Daemon.__init__(self)
        self.__henManager = HenManager()
        self.__registerMethods()

    def __registerMethods(self):
        self.registerMethodHandler("get_object_for_id", self.getObjectForId)
        self.registerMethodHandler("stop_daemon", self.stopDaemon)

    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 getObjectForId(self, prot, seq, ln, payload):
        nodes = self.__henManager.getNodes("all")
        for ntk in nodes:
            #print "ntk ",str(ntk)
            for nk in nodes[ntk]:
                #print "nk ",str(nk)
                if nodes[ntk][nk].getNodeID() == payload:
                    payload = pickle.dumps(nodes[ntk][nk])
                    code = 0
                    self.__sendReply(prot, code, seq, payload)
                    return
        payload = "not found"
        code = -1
        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 ConfigDaemon (self)")
        self.stop()
Example #27
0
    def load_data(self):
        log.info("Loading Data")
        self.__manager = HenManager()
        for i in range(1, 254):
            self.__man_ips["192.168.0." + str(i)] = "free"
            self.__inf_ips["192.168.1." + str(i)] = "free"

        n = self.__manager.getNodes("all", "all")
        for nt in n:
            for node in n[nt].values():
                try:
                    man_ip = node.getInterfaces("management")
                    inf_ip = node.getInterfaces("infrastructure")
                    if man_ip != []:
                        self.__nodes[man_ip[0].getIP()] = node
                        self.__man_ips[str(man_ip[0].getIP())] = node.getNodeID()
                    if inf_ip != []:
                        self.__nodes[inf_ip[0].getIP()] = node
                        self.__inf_ips[str(inf_ip[0].getIP())] = node.getNodeID()
                except:
                    pass
        self.show_stats()
Example #28
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')
Example #29
0
 def __init__(self):
     self.__manager = HenManager()
Example #30
0
##################################################################################################################
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()
Example #31
0
        else:
            newParameters[oldName] = parameters[oldName]

    return newParameters


# Make sure that the necessary cgi parameters are given and retrieve them
form = cgi.FieldStorage()
if ((not form) or (not form.has_key("action"))):
    sys.exit()

print "Content-Type: text/xml"
print ""
print ""

manager = HenManager()
fileNodes = manager.getFileNodes("all")

action = form["action"].value

# Get all the files for the given user, including those that he/she owns through
# the <experimentgroup> tag
if (action == "getfilesbyuser"):
    print '<experiments>'

    if (not form.has_key("username")):
        print '</experiments>'
        sys.exit()

    # Retrieve the user's experiment groups from the LDAP server (hard-coded for now)
    userExperimentGroups = ["dostunneling"]
Example #32
0
# inventory.py:
#
##################################################################################################################
import sys, os, time
sys.path.append("/home/arkell/u0/fhuici/development/svn/hen_scripts/lib")
os.environ["PATH"] += ":/usr/local/bin:/usr/bin"
from henmanager import HenManager

###########################################################################################
#   Main execution
###########################################################################################
outputFilename = "/home/arkell/u0/www/data/inventory.html"
while 1:
    try:
        print "Updating inventory information..."
        manager = HenManager()
        nodes = manager.getNodes("all")

        result = ""
        for nodeTypeDictionary in nodes.values():
            for node in nodeTypeDictionary.values():
                result += str(node) + "\n"

        print "writing to file..."
        if (os.path.exists(outputFilename)):
            os.remove(outputFilename)
        outputFile = open(outputFilename, "w")
        outputFile.write(
            "Content-type: text/html\n\n<html><head><title></title></head><body>\n"
        )
        outputFile.write(result)
Example #33
0
File: filed.py Project: sohonet/HEN
 def __init__(self):
     self.__manager = HenManager()
Example #34
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()
Example #35
0
		print "Error"

def createVLAN(switch,name,id,ports=None):
	vlan = VLAN(name,id,ports,None)
	if switch.createVLAN(vlan) != 0:
		print "Error creating vlan"

def deleteVLAN(switch,name,id):
	vlan = VLAN(name,id,[],None)
	if switch.deleteVLAN(vlan) != 0:
		print "Error removing vlan"

print "Content-type: text/html\n\n"
print "<html><title></title><head>"

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

for n in nodes.values():
	portsBlackList = []
	s = n.getInstance()
	#s.setSwitchName(n.getNodeID())
	if s != None:
		#printVlans(s)
		deleteVLAN(s,"B",4)
		#createVLAN(s,"A",3,["GigabitEthernet2/1/1","GigabitEthernet2/1/2","GigabitEthernet2/1/3","GigabitEthernet2/1/4"])
		#createVLAN(s,"B",4,["GigabitEthernet2/1/5","GigabitEthernet2/1/6","GigabitEthernet2/1/7","GigabitEthernet2/1/8"])
		#addPorts(s,"vlana",["GigabitEthernet2/1/1","GigabitEthernet2/1/2","GigabitEthernet2/1/3"])
		#deletePorts(s,"vlana",["GigabitEthernet2/1/1","GigabitEthernet2/1/2","GigabitEthernet2/1/3"])
		#
Example #36
0
sys.path.append("/usr/local/hen/lib")
#sys.path.append("/usr/local/hen/lib/")
for i in temp:
    sys.path.append(i)
#os.environ["PATH"] += ":/usr/local/bin:/usr/bin"
from henmanager import HenManager

###########################################################################################
#   Main execution
###########################################################################################
print "Content-Type: text/xml"
print ""
print ""

print "<row>"
manager = HenManager("/usr/local/hen/etc/configs/config")
racks = manager.getInfrastructures("rack", "all")
nodes = manager.getNodes("all", "all")

for key in racks.keys():
    r = manager.getInfrastructures("rack")[key]
    s = '<rack id="' + str(r.getID()) + \
        '" rowposition="' + str(r.getRowPosition()) + \
        '" height="' + str(r.getPhysicalSize().getNumberUnits())

    if (r.getPhysicalSize().getWidth() == "75"):
        s += '" width="wide" >'
    elif (r.getPhysicalSize().getWidth() == "60"):
        s += '" width="narrow" >'
    else:
        s += '" width="wide" >'
Example #37
0
        #    string += '\t<usermanagement username="******" password="******" />\n'
        #string += '\n'
        
        # Write attributes, if any
        attributes = node.getAttributes()
        if (attributes != None and len(attributes) != 0):
            for attribute in attributes.keys():
                string += '\t<attribute name="' + str(attribute) + '" value="' + str(attributes[attribute]) + '" />\n'

        # Write closing tag
        string += '\n</node>'

        print string


###########################################################################################
#   Main execution
###########################################################################################
if (len(sys.argv) != 3):
	print "usage: python processlshw [xml file] [node id]"
	os._exit(1)
else:
        configFile = ConfigParser.ConfigParser()	
        configFile.read('/usr/local/hen/etc/configs/config')
        macTableURL = configFile.get('AUTODETECT', 'MACTABLE_URL')
        manager = HenManager()
        manager.initLogging()

        processor = LSHardwareProcessor(manager, macTableURL)
        processor.parseFileAndPrint(sys.argv[1], sys.argv[2])
Example #38
0
###########################################################################################
#   Main execution
###########################################################################################            

# Make sure that the necessary cgi parameters are given and retrieve them
form = cgi.FieldStorage()

if ((not form) or (not form.has_key("action"))):
    sys.exit()

print "Content-Type: text/xml"
print ""
print ""
print '<config>'

manager = HenManager()
action = form["action"].value

if (action == "getconfig"):
    print '\t<configfile>'
    for line in manager.getConfigFileLines():
        print '\t\t<line>' + str(line) + "</line>"
    print '\t</configfile>'
    
elif (action == "editconfig"):

    if (not form.has_key("configfile")):
        sys.exit()
        
    configFile = form["configfile"].value
Example #39
0
                                                macs[m].setDevice(
                                                    node.getNodeID())

                            except AttributeError, a:
                                pass
                            except KeyError, a:
                                pass
                            except TypeError, a:
                                pass

                for x in range(0, len(uniqueMacs)):
                    print str(uniqueMacs[x].getMAC()) + " " +  str(uniqueMacs[x].getSwitch()) + " " + \
                          str(uniqueMacs[x].getPort()) + " " + str(uniqueMacs[x].getLearned()) + " " + str(uniqueMacs[x].getDevice())+ "<br>"
            self.__numOfSwitches = self.__numOfSwitches - 1
            self.__release_final_lock()
            self.__lock.release()
        except Exception, e:
            print e
            print "Trouble getting lock"
            self.__numOfSwitches = self.__numOfSwitches - 1
            self.__release_final_lock()


###########################################################################################
#   Main execution
###########################################################################################
manager = HenManager()
manager.initLogging()
macRetriever = MACTableRetriever(manager)
macRetriever.printVLANTables()
Example #40
0
class DetectorDaemon(threading.Thread):
    def __init__(self, d, debug):
        self.__debug = debug
        self.__device_list = d
        self.__run = True
        self.__nodes = {}
        self.__running = []
        self.__man_ips = {}
        self.__inf_ips = {}
        self.__symlinksRoot = "/export/machines/"
        if self.__debug:
            self.__etcRoot = "/usr/local/hen/etc/daemons/autodetectiond/debug/"
        else:
            self.__etcRoot = "/usr/local/hen/etc/daemons/autodetectiond/"

        self.load_data()
        self.show_stats()

        threading.Thread.__init__(self)

    def show_stats(self):
        count = 0
        string = "Number of free management ips :"
        for i in self.__man_ips:
            if self.__man_ips[i] == "free":
                count = count + 1
        string = string + str(count)
        log.info(string)
        count = 0
        string = "Number of free infrastructure ips :"
        for i in self.__inf_ips:
            if self.__inf_ips[i] == "free":
                count = count + 1
        string = string + str(count)
        log.info(string)

    def load_data(self):
        log.info("Loading Data")
        self.__manager = HenManager()
        for i in range(1, 254):
            self.__man_ips["192.168.0." + str(i)] = "free"
            self.__inf_ips["192.168.1." + str(i)] = "free"

        n = self.__manager.getNodes("all", "all")
        for nt in n:
            for node in n[nt].values():
                try:
                    man_ip = node.getInterfaces("management")
                    inf_ip = node.getInterfaces("infrastructure")
                    if man_ip != []:
                        self.__nodes[man_ip[0].getIP()] = node
                        self.__man_ips[str(man_ip[0].getIP())] = node.getNodeID()
                    if inf_ip != []:
                        self.__nodes[inf_ip[0].getIP()] = node
                        self.__inf_ips[str(inf_ip[0].getIP())] = node.getNodeID()
                except:
                    pass
        self.show_stats()

    def getFreeIp(self, type_str):
        if type_str == "infrastructure":
            for i in self.__inf_ips:
                if self.__inf_ips[i] == "free":
                    return i
            return "no free infrastructure ip"
        elif type_str == "management":
            for i in self.__man_ips:
                if self.__man_ips[i] == "free":
                    return i
            return "no free infrastructure ip"
        else:
            return "unknown ip type " + type_str

    def writeXML(self, node, old=False):
        xmlstring = self.__manager.parser.writeNodePhysicalFileString(node, self.__debug)
        print xmlstring
        filename = self.__etcRoot + node.getNodeID() + ".xml"
        if old:
            filename = filename + ".old"
        try:
            if not self.__debug:
                theFile = open(filename, "w")
                theFile.write(xmlstring)
                theFile.close()
            else:
                print "Would write to file ", filename
                print xmlstring
        except Exception, e:
            log.info("error while writing xml file for " + str(node.getNodeID()))
            log.info(str(e))
            return -1
Example #41
0
###########################################################################################
#   Main execution
###########################################################################################

# Make sure that the necessary cgi parameters are given and retrieve them
form = cgi.FieldStorage()

if ((not form) or (not form.has_key("action"))):
    sys.exit()

print "Content-Type: text/xml"
print ""
print ""
print '<power>'

manager = HenManager()
action = form["action"].value

# Perform power operation
if (action == "status" or action == "poweron" or action == "poweroff"
        or action == "restart"):
    if (not form.has_key("numbernodes")):
        print '</power>'
        sys.exit()

    numberNodes = form["numbernodes"].value

    if (action != "status"):
        for i in range(0, int(numberNodes)):
            nodeID = form["node" + str(i)].value
            manager.powerSilent(nodeID, action)
Example #42
0
class HardwareDetectionRunner:

    __prot = None
    __host = None
    __port = None
    __hm = None
    __interfaceNames = None
    __data = None

    def __init__(self, host, port):
        self.__prot = auxiliary.protocol.Protocol(None)
        self.__host = host
        self.__port = port
        self.__data = ""
        self.__hm = HenManager()

    def run(self):
        """\brief Runs all the necessary detection methods."""
        print "Running hardware detection:"
        print "\tRetrieving experimental interface names..."
        self.getExperimentalInterfacesNames()
        print "\tPolling interfaces..."
        self.pollInterfaces()
        # Sometimes mii-tool will report no link if this sleep time is not here
        print "Waiting " + str(AUTONEGOTIATION_WAIT_TIME) + \
                " seconds for autonegotiation to finish",
        self.waitForAutonegotiation()
        print "Retrieving number of processors..."
        self.getNumberProcessors()
        print "Retrieving number of cores..."
        self.getNumberCores()
        print "Retrieving no-carrier-sense MACs..."
        self.getNoCarrierMACs()
        print "Retrieving output from lshw..."
        self.getLSHWOutput()
        print "Polling interfaces once to seed fdb"
        self.pollInterfaces()
        print "Sending results to AutodetectDaemon... "
        self.sendData()
        print "Polling interfaces continually..."
        while 1:
            self.pollInterfaces()    
            time.sleep(POLL_INTERFACE_INTERVAL)

    def waitForAutonegotiation(self):
        """\brief Prints a dot per second whilst waiting for the number of
            seconds defined by AUTONEGOTIATION_WAIT_TIME
        """
        ticks = AUTONEGOTIATION_WAIT_TIME
        while ticks > 0:
            print '.',
            ticks -= 1
            time.sleep(1)

    def pollInterfaces(self):
        for interfaceName in self.__interfaceNames:
            cmd = "/sbin/ifconfig " + interfaceName + " up"
            os.system(cmd)
            cmd = "etherwake -i " + interfaceName + " 00:11:22:33:44:55"
            os.system(cmd)

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

        # Find which of these is the management interface so we can filter it out
        nodes = self.__hm.getNodes("computer", "all")
        for node in nodes.values():
            managementMACAddress = \
                node.getInterfaces("management")[0].getMAC().upper()
            if (managementMACAddress in macAddresses):
                break

        self.__interfaceNames = []
        for macAddress in macAddresses:
            if (macAddress != managementMACAddress):
                # We need to convert the mac addresses to interface names
               self.__interfaceNames.append(commands.getstatusoutput(\
                                       "ifconfig -a | grep " + macAddress + \
                                       " | awk '{print $1}'")[1])

    def getNumberProcessors(self):
        data = commands.getstatusoutput(\
                "cat /proc/cpuinfo | grep 'physical id'")[1]
        data = data.split("\n")
        uniqueIDs = []
        for line in data:
            processorID = line[line.find(":") + 1:]
            if (processorID not in uniqueIDs):
                uniqueIDs.append(processorID)
        self.__data += "<numbercpus>%s</numbercpus>" % str(len(uniqueIDs))

    def getNumberCores(self):
        data = commands.getstatusoutput(\
                "cat /proc/cpuinfo | grep 'cpu cores'")[1]
        cores = 1
        try:
            data = data.split("\n")[0]
            cores =  int(data[data.find(":") + 1:])
        except:
            pass
        self.__data += "<numbercorespercpu>%s</numbercorespercpu>" % str(cores)

    def getNoCarrierMACs(self):
        self.__data += "<nocarriermacs>"
        data = commands.getstatusoutput("mii-tool")[1]
        data = data.split("\n")
        counter = 0
        for line in data:
            if (line.find("no link") != -1):
                ifaceName = line[:line.find(":")]
                data = commands.getstatusoutput(\
                            "ifconfig " + ifaceName)[1].split("\n")[0]
                macAddress = data[data.find("HWaddr") + 7:].strip()
                self.__data += str(macAddress).upper()
                counter += 1
                if (counter != len(noCarrierMACs)):
                    self.__data += ","
        self.__data += "</nocarriermacs>"

    def getLSHWOutput(self):
        self.__data += commands.getstatusoutput("/usr/sbin/lshw -xml")[1]

    def sendData(self):
        """\brief Connects to the autodetectdaemon and sends the data created
            by the detection code.
        """
        self.__prot.open(self.__host, self.__port)
        self.__prot.sendRequest("receive_detectiondata", \
                                self.__data, \
                                self.responseHandler)
        self.__prot.readAndProcess()

    def responseHandler(self,code,seq,size,payload):
        """\brief Handles the response from the autodetectdaemon. We can add
            code here for re-sending the data, if need be.
        """
        if code == 200:
            print "Data successfully received by AutodetectDaemon"
            self.__prot.close()
        else:
            print "ERROR: Received code[%s] from daemon. Payload = %s" % \
                (str(code), str(payload))
Example #43
0
def main():

    manager = HenManager()
    manager.initLogging()
    #switchdb automatically loads most information into memory.
    switchdb = SwitchDB(manager)
Example #44
0
 def __init__(self):
     Daemon.__init__(self)
     self.__henManager = HenManager()
     self.__registerMethods()
Example #45
0
def main():
    
    manager = HenManager()
    manager.initLogging()
    #switchdb automatically loads most information into memory.
    switchdb = SwitchDB(manager)
Example #46
0
sys.path = []
sys.path.append("/usr/local/hen/lib/")
for i in temp:
    sys.path.append(i)

from henmanager import HenManager

###########################################################################################
#   Main execution
###########################################################################################            
print "Content-Type: text/xml"
print ""
print ""

print "<row>"
manager = HenManager("/usr/local/hen/etc/configs/config" )
racks = manager.getInfrastructures("rack")
nodes = manager.getNodes("all", "all")

rackNodes = {}

for key in racks.keys():
    rackNodes[key] = []

for nodeTypeDictionary in nodes.values():
    for node in nodeTypeDictionary.values():
        location = node.getPhysicalLocation()
        if (location != None):
            if rackNodes.has_key(location.getRackName()):
                s = '<node id="' + str(node.getNodeID())
                s += '" type="physicallocation-' + str(node.getNodeType())
Example #47
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])
Example #48
0
from auxiliary.daemonlocations import DaemonLocations
from auxiliary.protocol import Protocol
import datetime

powerdaemon = Protocol(None)
powerdaemon.open(DaemonLocations.powerDaemon[0], DaemonLocations.powerDaemon[1])
version = powerdaemon.doSynchronousCall("get_config_version","")
print "Version is "+str(version[0][2])
tics = os.stat('/usr/local/hen/etc/physical/topology.xml')[ST_MTIME]
t = datetime.datetime.fromtimestamp(tics)
lastAccess=str(t.strftime('%Y-%m-%d'))
print "Last access time is "+lastAccess
if (str(lastAccess)!=str(version[0][2])):
	print "Setting new config"
	from henmanager import HenManager
	hm = HenManager()
	payload = lastAccess + ","+ pickle.dumps(hm.getNodes("all"))
	print "Result is:"+str(powerdaemon.doSynchronousCall("set_config",payload))
	

def addLink(tag,action,old,new):
    print "AddLink got "+tag,action,old,new

def removeLink(tag,action,old,new):
    print "RemoveLink got "+tag,action,old,new
    
def changePowerState(tag,action,node,attr):
	print "changePowerState got "+tag,action,node,attr
	id = node.xpath("ancestor::node")[0].attributes[(None,'id')].value

	param = str(id)+","+str(attr.value)
Example #49
0
#
##################################################################################################################
import sys, os, time, cgi
temp = sys.path

sys.path.append("/usr/local/hen/lib/")
from henmanager import HenManager

###########################################################################################
#   Main execution
###########################################################################################            
print "Content-Type: text/html"
print ""
print ""

manager = HenManager()
nodes = manager.getNodes("all")

form = cgi.FieldStorage()
if form.has_key("id"):
    pass
else:
    sys.exit()

nodeid = form["id"].value

for nodeTypeDictionary in nodes.values():
    for node in nodeTypeDictionary.values():
        if (nodeid == node.getNodeID()):
            print "<p>"
            print "power status of "
Example #50
0
#!/usr/local/bin/python

from henmanager import HenManager
import time
import resource
import gc

manager = HenManager()
manager.initLogging()

switches = manager.getNodes("switch", "all")

switch = None
#switch_node = None
for sw in switches.values():
    if sw.getNodeID() == "switch5":
        #switch_node = sw
        switch = sw.getInstance()
while True:

    sn = switch.getSensorReadings()
    print sn,
    print resource.getrusage(resource.RUSAGE_SELF)[2]
    try:
        pnodeid = switch.getPowerNodeID()
        if (pnodeid == "None" or pnodeid == "none"):
            pass
        (st,msg) = manager.powerSilent(switch.getNodeID(), "status", \
                                                    pnodeid)
        print "power status[%S], message[%s]" % (st, msg)
    except:
Example #51
0
 def __init__(self, host, port):
     self.__prot = auxiliary.protocol.Protocol(None)
     self.__host = host
     self.__port = port
     self.__data = ""
     self.__hm = HenManager()
Example #52
0
    
    return reversedEntries


# Make sure that the necessary cgi parameters are given and retrieve them
form = cgi.FieldStorage()

if ((not form) or (not form.has_key("action"))):
    sys.exit()

print "Content-Type: text/xml"
print ""
print ""
print '<experiments>'

manager = HenManager()
action = form["action"].value

if (action == "getlogsbyelement"):
    if (not form.has_key("elementid")):
        print '</experiments>'
        sys.exit()
        
    elementID = form["elementid"].value

    logEntries = manager.getLogEntriesByElement(elementID)
    logEntries = reverseLogEntries(logEntries)
    for logEntry in logEntries:
        author = logEntry.getAuthorLoginID()
        affectedElements = logEntry.getAffectedElementsIDs()
        date = logEntry.getDate()
Example #53
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()