Beispiel #1
0
def createLayer2Topology(interfaceEnd1, interfaceEnd2):
    OSHV = ObjectStateHolderVector()
    end1Node = modeling.createCompleteHostOSH('node', str(interfaceEnd1.xHash))
    end2Node = modeling.createCompleteHostOSH('node', str(interfaceEnd2.xHash))
    interface1 = modeling.createInterfaceOSH(
        interfaceEnd1.ifMac, end1Node, interfaceEnd1.ifDescr,
        interfaceEnd1.ifIndex, interfaceEnd1.ifType,
        interfaceEnd1.ifAdminStatus, interfaceEnd1.ifOperStatus,
        interfaceEnd1.ifSpeed, interfaceEnd1.ifName, interfaceEnd1.ifAlias)
    interface2 = modeling.createInterfaceOSH(
        interfaceEnd2.ifMac, end2Node, interfaceEnd2.ifDescr,
        interfaceEnd2.ifIndex, interfaceEnd2.ifType,
        interfaceEnd2.ifAdminStatus, interfaceEnd2.ifOperStatus,
        interfaceEnd2.ifSpeed, interfaceEnd2.ifName, interfaceEnd2.ifAlias)
    layer2Osh = ObjectStateHolder('layer2_connection')
    layer2Osh.setAttribute(
        'layer2_connection_id',
        str(hash(interfaceEnd1.ifMac + interfaceEnd2.ifMac)))
    member1 = modeling.createLinkOSH('member', layer2Osh, interface1)
    member2 = modeling.createLinkOSH('member', layer2Osh, interface2)
    OSHV.add(end1Node)
    OSHV.add(end2Node)
    OSHV.add(interface1)
    OSHV.add(interface2)
    OSHV.add(layer2Osh)
    OSHV.add(member1)
    OSHV.add(member2)
    return OSHV
Beispiel #2
0
def build_network_device(device):
    '''
    Build Layer 2 connection end.
    @type param: NetworkDevice -> OSH
    '''
    device_osh = None
    device_ip_address_osh = None
    device_interface_osh = None
    device_member_ip = None
    if device.ucmdb_id:
        device_osh = modeling.createOshByCmdbIdString('node', device.ucmdb_id)
    if device.mac_address:
        if not device_osh:
            device_osh = modeling.createCompleteHostOSH(
                'node', device.mac_address)
        device_interface_osh = modeling.createInterfaceOSH(
            device.mac_address, device_osh)
    if device.ip_address:
        if not device_osh:
            device_osh = modeling.createHostOSH(device.ip_address)
        device_ip_address_osh = modeling.createIpOSH(device.ip_address)
        device_member_ip = modeling.createLinkOSH('contained', device_osh,
                                                  device_ip_address_osh)
    if device.port:
        if device_interface_osh:
            device_interface_osh.setAttribute('interface_name', device.port)
        elif device_osh:
            device_interface_osh = ObjectStateHolder('interface')
            device_interface_osh.setContainer(device_osh)
            device_interface_osh.setAttribute('interface_name', device.port)
    return device_osh, device_ip_address_osh, device_interface_osh, device_member_ip
Beispiel #3
0
def build_network_device(device):
    '''
    Build Layer 2 connection end.
    @type param: NetworkDevice -> OSH
    '''
    device_osh = None
    device_ip_address_osh = None
    device_interface_osh = None
    device_member_ip = None
    if device.ucmdb_id:
        device_osh = modeling.createOshByCmdbIdString('node', device.ucmdb_id)
    if device.mac_address:
        if not device_osh:
            device_osh = modeling.createCompleteHostOSH('node', device.mac_address)
        device_interface_osh = modeling.createInterfaceOSH(device.mac_address, device_osh)
    if device.ip_address:
        if not device_osh:
            device_osh = modeling.createHostOSH(device.ip_address)
        device_ip_address_osh = modeling.createIpOSH(device.ip_address)
        device_member_ip = modeling.createLinkOSH('contained', device_osh, device_ip_address_osh)
    if device.port:
        if device_interface_osh:
            device_interface_osh.setAttribute('interface_name', device.port)
        elif device_osh:
            device_interface_osh = ObjectStateHolder('interface')
            device_interface_osh.setContainer(device_osh)
            device_interface_osh.setAttribute('interface_name', device.port)
    return device_osh, device_ip_address_osh, device_interface_osh, device_member_ip
Beispiel #4
0
    def build(self, containerOsh):
        self.osh = modeling.createInterfaceOSH(
            self.mac,
            containerOsh,
            description=self.description,
            index=self.index,
            type=self.type,
            adminStatus=self.adminStatus,
            operStatus=self.operationalStatus,
            speed=self.speed,
            name=self.name,
            alias=self.alias,
        )
        if not self.osh:
            logger.warn("Interface '%s' cannot be built" % self.name)
            return
        for role in self._rolesByClass.values():
            role._build(containerOsh)
        isVirtual = self._hasRole(_VirtualRole)
        self.osh.setBoolAttribute("isvirtual", isVirtual)
        if isVirtual:
            list_ = StringVector(("virtual_interface",))
            roleAttribute = AttributeStateHolder("interface_role", list_)
            self.osh.addAttributeToList(roleAttribute)
        else:
            list_ = StringVector(("physical_interface",))
            roleAttribute = AttributeStateHolder("interface_role", list_)
            self.osh.addAttributeToList(roleAttribute)

        if self.speed:
            self.osh.setLongAttribute("interface_speed", long(self.speed))
Beispiel #5
0
def reportRemotePeer(remote_peer, localInterfaceOsh, local_mac):
    vector = ObjectStateHolderVector()
    if remote_peer.peer_ips:
        hostOsh = modeling.createHostOSH(str(remote_peer.peer_ips[0]))
    if remote_peer.platform in VIRTUAL_HOST_PLATFORMS:
        hostOsh.setBoolAttribute('host_isvirtual', 1)
        vector.add(hostOsh)
        for ip in remote_peer.peer_ips:
            ipOsh = modeling.createIpOSH(ip)
            linkOsh = modeling.createLinkOSH('containment', hostOsh, ipOsh)
            vector.add(ipOsh)
            vector.add(linkOsh)
    else:
        hostOsh = ObjectStateHolder('node')
        hostOsh.setBoolAttribute('host_iscomplete', 1)
        hostOsh.setStringAttribute('name', remote_peer.system_name)
        if remote_peer.platform in VIRTUAL_HOST_PLATFORMS:
            hostOsh.setBoolAttribute('host_isvirtual', 1)
        vector.add(hostOsh)
    
    if remote_peer.interface_name or remote_peer.interface_mac:
        remoteInterfaceOsh = modeling.createInterfaceOSH(mac = remote_peer.interface_mac, hostOSH = hostOsh, name = remote_peer.interface_name)
        if not remoteInterfaceOsh:
            return ObjectStateHolderVector()
        if remote_peer.interface_name:
            remoteInterfaceOsh.setStringAttribute('name', remote_peer.interface_name)
        vector.add(remoteInterfaceOsh)
        l2id = str(hash(':'.join([remote_peer.interface_mac or remote_peer.interface_name, local_mac])))
        vector.addAll(reportLayer2Connection(localInterfaceOsh, remoteInterfaceOsh, l2id))
    return vector
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    connection = Framework.getProbeDatabaseConnection('common')
    
    for mac_preffix, vendor in THIN_CLIENT_MAC_TO_VENDOR_PAIRS.items():
        st = getPreparedStatement(connection, mac_preffix)
        rs = st.executeQuery()
        while (rs.next()):
            mac = rs.getString('mac_address')
            ip = rs.getString('ip_address')
            if ip_addr.isValidIpAddressNotZero(ip) and not DSM.isIpOutOfScope(ip) and DSM.isClientIp(ip): 
                ip_osh = build_client_ip_osh(ip, mac)
                node_osh = build_node_osh(mac, vendor)
                if ip_osh and node_osh:
                    link_osh = modeling.createLinkOSH('containment', node_osh, ip_osh)
                    interface_osh = modeling.createInterfaceOSH(mac, node_osh)
                    OSHVResult.add(ip_osh)
                    OSHVResult.add(node_osh)
                    OSHVResult.add(link_osh)
                    OSHVResult.add(interface_osh)
                else:
                    debug('Failed to create topology for ip %s , mac %s, vendor %s' % (ip, mac, vendor))
            else:
                debug('Skipping IP address %s since it is invalid or not assigned to any probe or not in client ip range. ' %  ip)
        rs.close()
        connection.close(st)
  
    connection.close()
    return OSHVResult
Beispiel #7
0
    def report(self, ivmHostOsh, hypervisor, vms, reportVmName):
        if not (ivmHostOsh and hypervisor and vms):
            raise ValueError(
                'Failed to build topology. Not all required entities are discovered.'
            )

        vector = ObjectStateHolderVector()
        hypervisorOsh = createHypervisorOsh(hypervisor, ivmHostOsh)
        vector.add(hypervisorOsh)
        logger.debug(vms)
        for vm in vms:
            logger.debug('Report name %s' % reportVmName)
            if reportVmName and reportVmName.lower().strip() == 'true':
                virtualServerOsh = createVirtualServerOsh(vm)
            elif vm.macs:
                virtualServerOsh = createVirtualServerOsh(vm, False)

            vector.add(virtualServerOsh)
            if vm.macs:
                for mac in vm.macs:
                    vector.add(
                        modeling.createInterfaceOSH(mac, virtualServerOsh))
            vector.add(
                modeling.createLinkOSH("execution_environment", hypervisorOsh,
                                       virtualServerOsh))
            virtualServerConfigOsh = createVirtualServerConfigOsh(
                vm.vserver_config, virtualServerOsh)
            vector.add(virtualServerConfigOsh)
        return vector
Beispiel #8
0
    def build(self, containerOsh):
        self.osh = modeling.createInterfaceOSH(
            self.mac,
            containerOsh,
            description=self.description,
            index=self.index,
            type=self.type,
            adminStatus=self.adminStatus,
            operStatus=self.operationalStatus,
            speed=self.speed,
            name=self.name,
            alias=self.alias)
        if not self.osh:
            logger.warn("Interface '%s' cannot be built" % self.name)
            return
        for role in self._rolesByClass.values():
            role._build(containerOsh)
        isVirtual = self._hasRole(_VirtualRole)
        self.osh.setBoolAttribute('isvirtual', isVirtual)
        if isVirtual:
            list_ = StringVector(('virtual_interface', ))
            roleAttribute = AttributeStateHolder('interface_role', list_)
            self.osh.addAttributeToList(roleAttribute)
        else:
            list_ = StringVector(('physical_interface', ))
            roleAttribute = AttributeStateHolder('interface_role', list_)
            self.osh.addAttributeToList(roleAttribute)

        if self.speed:
            self.osh.setLongAttribute('interface_speed', long(self.speed))
def createLayer2Topology(serverOsh, iface, interfaceEnd2):
    OSHV = ObjectStateHolderVector()
    end2Node = modeling.createCompleteHostOSH('node',str(interfaceEnd2.xHash))
    interface1 = modeling.createInterfaceOSH(iface['mac'], serverOsh, name = iface['name'])
    interface2 = modeling.createInterfaceOSH(interfaceEnd2.ifMac, end2Node, interfaceEnd2.ifDescr, interfaceEnd2.ifIndex, interfaceEnd2.ifType, interfaceEnd2.ifAdminStatus, interfaceEnd2.ifOperStatus, interfaceEnd2.ifSpeed, interfaceEnd2.ifName, interfaceEnd2.ifAlias)
    layer2Osh = ObjectStateHolder('layer2_connection')
    layer2Osh.setAttribute('layer2_connection_id',str(hash(iface['mac']+interfaceEnd2.ifMac)))
    member1 = modeling.createLinkOSH('member', layer2Osh, interface1)
    member2 = modeling.createLinkOSH('member', layer2Osh, interface2)
    OSHV.add(serverOsh)
    OSHV.add(end2Node)
    OSHV.add(interface1)
    OSHV.add(interface2)
    OSHV.add(layer2Osh)
    OSHV.add(member1)
    OSHV.add(member2)
    return OSHV
Beispiel #10
0
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()
    snmpMethod = getFrameworkParameter(Framework, 'snmpMethod', SnmpQueries.defaultSnmpMethod)
    backupSnmpMethod = getFrameworkParameter(Framework, 'backupSnmpMethod', SnmpQueries.defaultBackupSnmpMethod)
    moonWalkBulkSize = int(getFrameworkParameter(Framework, 'moonWalkBulkSize', SnmpQueries.defaultMoonWalkBulkSize))
    moonWalkSleep = long(getFrameworkParameter(Framework, 'moonWalkSleep', SnmpQueries.defaultMoonWalkSleep))
    snmpBulkSize = int(getFrameworkParameter(Framework, 'snmpBulkSize', SnmpQueries.defaultSnmpBulkSize))
    discoverUnknownIPs = Boolean.parseBoolean(Framework.getParameter('discoverUnknownIPs'))
    
    #getting DestinationData from Framework; the method is protected.
    destination = Framework.getCurrentDestination()
    
    discoveredHostIpList = SnmpQueries.getSnmpIpDataOneDestination(snmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, destination)
    logger.debug('Discover ARP by %s returned %s objects' % (snmpMethod, str(discoveredHostIpList.size())))
    if (discoveredHostIpList.size() == 0) and (snmpMethod != backupSnmpMethod):
        discoveredHostIpList = SnmpQueries.getSnmpIpDataOneDestination(backupSnmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, destination)
        logger.debug('Discover ARP by %s returned %s objects' % (backupSnmpMethod, str(discoveredHostIpList.size())))
        if (discoveredHostIpList.size()==0):
            Framework.reportWarning('Failed to discover SNMP IP data')
            return OSHVResult
    
    discoveredHostArpList = SnmpQueries.getSnmpArpDataOneDestination(snmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, destination)
    discoveredHostArpList.addAll(SnmpQueries.getSnmpArpDataOneDestination(snmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, Boolean.TRUE, destination))
    if (discoveredHostArpList.size()==0) and (snmpMethod != backupSnmpMethod):
        discoveredHostArpList = SnmpQueries.getSnmpArpDataOneDestination(backupSnmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, destination)
        discoveredHostArpList.addAll(SnmpQueries.getSnmpArpDataOneDestination(backupSnmpMethod, snmpBulkSize, moonWalkBulkSize, moonWalkSleep, Boolean.FALSE, Boolean.TRUE, destination))
        if (discoveredHostArpList.size()==0):
            Framework.reportWarning('Failed to discover SNMP ARP data')
            return OSHVResult

    networkOSH = None
    for i in range(discoveredHostArpList.size()):
        currArp = discoveredHostArpList.get(i)
        for currIp in discoveredHostIpList:
            if networkOSH is None:
                networkOSH = modeling.createNetworkOSH(currIp.netaddr, currIp.netmask)
                OSHVResult.add(networkOSH)
            if (currIp.domain == 'unknown') and not discoverUnknownIPs:
                continue
            if not netutils.isValidMac(currArp.designatedMacAddress):
                continue
            
            #report start
            designatedIpNetAddress = IPv4(currArp.designatedIpAddress, currIp.netmask).getFirstIp().toString();
            if designatedIpNetAddress == currIp.netaddr:
                hostOSH = modeling.createHostOSH(currArp.designatedIpAddress)
                OSHVResult.add(hostOSH)
                OSHVResult.add(modeling.createLinkOSH('member', networkOSH, hostOSH))
                
                ipOsh = modeling.createIpOSH(currArp.designatedIpAddress, currIp.netmask)
                OSHVResult.add(ipOsh)
                OSHVResult.add(modeling.createLinkOSH('member', networkOSH, ipOsh))
                
                ifOsh = modeling.createInterfaceOSH(netutils.parseMac(currArp.designatedMacAddress), hostOSH)
                OSHVResult.add(ifOsh)
                OSHVResult.add(modeling.createLinkOSH('containment', ifOsh, ipOsh))
    
    return OSHVResult
Beispiel #11
0
    def buildTopology(self):
        '''
        Construct as400 node topology
        @types AS400Client -> ObjectStateHolderVector
        '''
        myvec = ObjectStateHolderVector()
        ip_address = self.__client.getIpAddress()
        # create as400 agent OSH

        interfaceList = self.__interfacesInfo
        as400HostOsh = None
        if interfaceList and len(interfaceList) > 0:
            # Create as400 CIT       
            try: 
                # Get the host_key - lowest mac address of the valid interface list
                as400HostOsh = modeling.createCompleteHostOSHByInterfaceList('as400_node', interfaceList, 'OS400', self.__sysInfo.hostName)
                as400HostOsh.setAttribute('host_model', self.__sysInfo.hostModel)
                as400HostOsh.setAttribute('host_serialnumber', self.__sysInfo.hostSerialNum)
                as400HostOsh.setAttribute('host_osversion', self.__sysInfo.hostOSVersion)
                as400HostOsh.setAttribute('host_vendor', 'IBM')
                myvec.add(as400HostOsh)
                
                as400Osh = self.__createAS400AgentOSH(ip_address)
                as400Osh.setAttribute('credentials_id', self.__client.getCredentialId())
                as400Osh.setContainer(as400HostOsh)
                myvec.add(as400Osh)

            except:
                logger.warn('Could not find a valid MAC addresses for key on ip : ', self.__client.getIpAddress())
       
        # add all interfaces to the host
        if as400HostOsh is not None:
            for interface in interfaceList:
                interfaceOsh = modeling.createInterfaceOSH(interface.macAddress, as400HostOsh, interface.description, interface.interfaceIndex, interface.type, interface.adminStatus, interface.adminStatus, interface.speed, interface.name, interface.alias, interface.className)
                ips = interface.ips
                masks = interface.masks
                if interfaceOsh:
                    myvec.add(interfaceOsh)
                    if ips and masks:
                        for i in xrange(len(ips)):
                            ipAddress = ips[i]
                            ipMask = masks[i]

                            ipProp = modeling.getIpAddressPropertyValue(ipAddress, ipMask, interface.dhcpEnabled, interface.description)
                            ipOSH = modeling.createIpOSH(ipAddress, ipMask, ipProp)
                            myvec.add(ipOSH)
                            
                            myvec.add(modeling.createLinkOSH('containment', as400HostOsh, ipOSH))
                            netOSH = modeling.createNetworkOSH(ipAddress, ipMask)   
                            myvec.add(netOSH)
                            
                            myvec.add(modeling.createLinkOSH('member', netOSH, as400HostOsh))
                            myvec.add(modeling.createLinkOSH('member', netOSH, ipOSH))
                            myvec.add(modeling.createLinkOSH('containment', interfaceOsh, ipOSH))
        else:
            logger.warn('Parent host wasn\'t created. No interfaces will be reported.')
        return myvec
Beispiel #12
0
 def addToOSHV (self, aSwitch, ObjSHV):
     aPtOSH = ObjectStateHolder("port")
     aPtOSH.setContainer(aSwitch.hostOSH)
     modeling.setPhysicalPortNumber(aPtOSH, self.portNumber)
     aPtOSH.setAttribute('port_remotestpbgid',self.remoteStpBgId)
     self.__setRemotePortNumber(aPtOSH, self.remoteStpPortId)
     aPtOSH.setAttribute('port_intfcindex',int(self.interfaceIndex))
     aPtOSH.setAttribute('port_nextmac',self.remoteTermMac)
     aPtOSH.setAttribute('port_hostbgid',self.hostBgId)
     aPtOSH.setAttribute('port_discoverylastrun',self.discoveryInst)
     aPtOSH.setAttribute('data_name',self.data_name)
     ObjSHV.add(aPtOSH)
     if self.ucmdbversion and self.ucmdbversion >= 9:
         interface = aSwitch.getInterfaceByIfIndex(self.interfaceIndex)
         if interface:
             intfOsh = modeling.createInterfaceOSH(interface.ifMac, aSwitch.hostOSH, interface.ifDescr, interface.ifIndex, interface.ifType, interface.ifAdminStatus, interface.ifOperStatus, interface.ifSpeed, interface.ifName, interface.ifAlias)
             if intfOsh:
                 ObjSHV.add(modeling.createLinkOSH('realization', aPtOSH, intfOsh))
         #in case we get a MAC for remote iface and this is a real MAC report a Layer2Connection between these interfaces
         if self.remoteTermMac and not self.remoteTermMac.endswith(":" + self.portNumber) and netutils.isValidMac(self.remoteTermMac):
             logger.debug('Created L2C from Ports')
             #write the reported layer2 info to file in order to post process in case of remote MAC "Multiple Match" 
             md5_obj = md5.new()
             updateValue = ''
             vlan_id = self.framework.getDestinationAttribute('snmpCommunityPostfix')
             for value in [interface.ifMac.upper(), interface.ifDescr, interface.ifIndex, interface.ifType, interface.ifAdminStatus, interface.ifOperStatus, interface.ifSpeed, interface.ifName, interface.ifAlias, vlan_id]:
                 if not updateValue:
                     updateValue = str(value)
                 else:
                     updateValue = updateValue + ':::' + str(value)
             md5_obj.update(updateValue)
             
             filename = md5_obj.hexdigest()
             filepath = os.path.join(CollectorsParameters.HOME_DIR, 'runtime/l2reported/')
             if not os.path.exists(filepath):
                 try:
                     os.mkdir(filepath)
                 except:
                     logger.debug('folder creation failed')
             f = open(filepath+filename,'w')
             f.write(updateValue+'\n')
             macsSeparated = ''
             for mac in [self.remoteTermMacRaw.get(self.remoteTermMac)]:
                 if mac.count('.'):
                     mac = self.convertToHexString(mac)
                 if not macsSeparated:
                     macsSeparated = mac
                 else:
                     macsSeparated = macsSeparated + ':::' + mac
             f.write(macsSeparated)
             f.close()
             
             ObjSHV.addAll(modeling.createLayer2ConnectionWithLinks([self.remoteTermMacRaw.get(self.remoteTermMac)], aSwitch, interface))
Beispiel #13
0
def reportVirtualMachine(vm_map, server, server_osh, host_class, lpar,
                         server_serial_to_interfaces):
    vector = ObjectStateHolderVector()
    key = '%s%s' % (server.serial, lpar.lparId)
    hostDo = vm_map.get(key)

    if not hostDo:
        logger.warn('Failed to report lpar with id %s and name %s' %
                    (lpar.lparId, lpar.lparName))
        return vector, None

    vm_osh = buildGenericHostObject(host_class, hostDo, False)
    if lpar.type != 'os400':
        vm_osh.setStringAttribute("os_family", 'unix')

    if lpar.logicalSerialNumber:
        vm_osh.setStringAttribute('serial_number', lpar.logicalSerialNumber)
    elif hostDo.serial:
        vm_osh.setStringAttribute('serial_number',
                                  'derived:%s' % hostDo.serial)

    if hostDo.ipList:
        vm_osh.setStringAttribute('host_key', str(hostDo.ipList[0]))
    if not hostDo.ipList and hostDo.macs:
        vm_osh.setStringAttribute('host_key', str(hostDo.macs[0]))
    hypervisor_osh = createIbmHypervisorOsh(server_osh)
    link_osh = modeling.createLinkOSH('execution_environment', hypervisor_osh,
                                      vm_osh)
    vector.add(vm_osh)
    vector.add(hypervisor_osh)
    vector.add(link_osh)
    if lpar.rmcIp:
        hostDo.ipList.append(lpar.rmcIp)
    if hostDo.ipList:
        for ip in hostDo.ipList:
            #logger.debug('Reporting %s ip for lpar %s' % (ip, hostDo.displayName))
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', vm_osh, ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)

    interfaces_map = server_serial_to_interfaces.get(hostDo.serial, {})
    if hostDo.macs:
        for mac in hostDo.macs:
            interface_osh = modeling.createInterfaceOSH(mac, vm_osh)
            vector.add(interface_osh)
            server_iface_osh = interfaces_map.get(mac)
            if server_iface_osh:
                link_osh = modeling.createLinkOSH('realization', interface_osh,
                                                  server_iface_osh)
                vector.add(link_osh)

    return vector, vm_osh
Beispiel #14
0
def createLayer2Topology(interfaceEnd1, interfaceEnd2):
    OSHV = ObjectStateHolderVector()
    end1Node = modeling.createCompleteHostOSH("node", str(interfaceEnd1.xHash))
    end2Node = modeling.createCompleteHostOSH("node", str(interfaceEnd2.xHash))
    interface1 = modeling.createInterfaceOSH(
        interfaceEnd1.ifMac,
        end1Node,
        interfaceEnd1.ifDescr,
        interfaceEnd1.ifIndex,
        interfaceEnd1.ifType,
        interfaceEnd1.ifAdminStatus,
        interfaceEnd1.ifOperStatus,
        interfaceEnd1.ifSpeed,
        interfaceEnd1.ifName,
        interfaceEnd1.ifAlias,
    )
    interface2 = modeling.createInterfaceOSH(
        interfaceEnd2.ifMac,
        end2Node,
        interfaceEnd2.ifDescr,
        interfaceEnd2.ifIndex,
        interfaceEnd2.ifType,
        interfaceEnd2.ifAdminStatus,
        interfaceEnd2.ifOperStatus,
        interfaceEnd2.ifSpeed,
        interfaceEnd2.ifName,
        interfaceEnd2.ifAlias,
    )
    layer2Osh = ObjectStateHolder("layer2_connection")
    layer2Osh.setAttribute("layer2_connection_id", str(hash(interfaceEnd1.ifMac + interfaceEnd2.ifMac)))
    member1 = modeling.createLinkOSH("member", layer2Osh, interface1)
    member2 = modeling.createLinkOSH("member", layer2Osh, interface2)
    OSHV.add(end1Node)
    OSHV.add(end2Node)
    OSHV.add(interface1)
    OSHV.add(interface2)
    OSHV.add(layer2Osh)
    OSHV.add(member1)
    OSHV.add(member2)
    return OSHV
def createTransportInterfaceObject(nodeName, interfaceName, cluster, hostOshByName):
    hostOsh = hostOshByName.get(nodeName)
    if not hostOsh: return
    
    node = cluster.nodesByName.get(nodeName)
    if not node: return
    
    tAdapter = node.transportAdaptersByName.get(interfaceName)
    if not tAdapter: return
    
    interfaceOsh = modeling.createInterfaceOSH(tAdapter.mac, hostOsh, name = tAdapter.name)
    if interfaceOsh:
        return (interfaceOsh, tAdapter)
    def build(self, port):
        if port is None:
            raise ValueError("port is None")

        interfaceOsh = modeling.createInterfaceOSH(port.getMac(), name=port.getName())

        if interfaceOsh:
            _roleMethodFn = fptools.comp(self.roleMethods.get, lambda r: r.getId())
            roleMethods = itertools.ifilter(None, itertools.imap(_roleMethodFn, port.iterRoles()))
            for method in roleMethods:
                method(interfaceOsh)

        return interfaceOsh
Beispiel #17
0
def createinterfaces(shell, HostOSH, Framework):
    mac = None
    myVec = ObjectStateHolderVector()
    lines = ()

    # Get a listing of the device names for the network interfaces
    # prtconf = client.execCmd('lscfg | grep ent')

    prtconf = shell.execAlternateCmds(
        '/usr/sbin/lsdev -Cc adapter | egrep ^ent',
        'lsdev -Cc adapter | egrep ^ent', 'lsdev -Cc adapter | grep -e ^ent',
        '/usr/sbin/lsdev -Cc adapter | grep -e ^ent')
    #prtconf ='ent0      Available 03-08 2-Port 10/100/1000 Base-TX PCI-X Adapter (14108902)'

    if prtconf == None:
        prtconf = ''

    lines = prtconf.split('\n')
    interfaces = {}
    for line in lines:
        m = re.search('^(\S+)', line)
        if (m):
            interfaces[m.group(1)] = 'pending'

        if (len(interfaces) < 1):
            logger.debug('did not find any interfaces in prtconf (timeout?)')
            #fail step
            return

        # Get further info on each of the network interfaces
        for devname in interfaces.keys():
            entstat = shell.execCmd(
                'entstat ' +
                devname)  #@@CMD_PERMISION shell protocol execution
            #            entstat = simulatecmd('c:/entstat.txt')
            if entstat == None:
                entstat = ''
            m = re.search('Device Type: (.+)', entstat)
            intdescription = None
            if (m):
                intdescription = m.group(1).strip()
            m = re.search('Hardware Address: ([0-9a-f:]{17})', entstat)
            rawMac = None
            if (m):
                rawMac = m.group(1)
                mac = netutils.parseMac(rawMac)
                hostifOSH = modeling.createInterfaceOSH(
                    mac, description=intdescription)
                hostifOSH.setContainer(HostOSH)
                myVec.add(hostifOSH)
    return myVec
Beispiel #18
0
    def report(self, serverOshDict, networkOshDict):
        vector = ObjectStateHolderVector()
        interfaceOsh = modeling.createInterfaceOSH(self.mac)
        interfaceOsh.setAttribute("name", self.name)
        serverOsh = serverOshDict.get(self.vm_id, None)
        if serverOsh:
            interfaceOsh.setContainer(serverOsh)
            vector.add(interfaceOsh)

            networkOsh = networkOshDict.get(self.network_id, None)
            if networkOsh:
                vector.add(modeling.createLinkOSH("membership", networkOsh, interfaceOsh))

        return vector
Beispiel #19
0
def addserviceresourceOSH(shell, resourceDictionary, HostOSH, myVec,
                          SvcDictionary, resourcegroupOSH):
    for svcif_name in SvcDictionary.keys():
        (svcif_name, svcif_ip, svcif_device, svcif_interface, svcif_node,
         svcif_network, svcif_status,
         service_label) = SvcDictionary[svcif_name]
        if resourceDictionary.has_key(svcif_name):
            (name, type, network, nettype, attr, node, ipaddr, haddr,
             interfacename, globalname, netmask, hb_addr,
             site_name) = resourceDictionary[svcif_name]
            if (type == 'boot'):
                svcifOSH = ObjectStateHolder('hacmpresource')
                svcifOSH.setAttribute('data_name', svcif_name)
                svcifOSH.setAttribute('resource_type', 'interface')
                svcifOSH.setAttribute('resource_subtype', type)
                svcifOSH.setContainer(resourcegroupOSH)
                myVec.add(svcifOSH)
                mac_address = None
                mac_address = getMAC(shell, interfacename)
                if (mac_address != None):
                    hostifOSH = modeling.createInterfaceOSH(mac_address,
                                                            name=interfacename)
                    hostifOSH.setContainer(HostOSH)
                    myVec.add(hostifOSH)
                    dependOSH = modeling.createLinkOSH('depend', svcifOSH,
                                                       hostifOSH)
                    myVec.add(dependOSH)
            if (type == 'service') and (nettype == 'diskhb'):
                svcifOSH = ObjectStateHolder('hacmpresource')
                svcifOSH.setAttribute('data_name', svcif_name)
                svcifOSH.setAttribute('resource_type', 'network')
                svcifOSH.setAttribute('resource_subtype', type)
                svcifOSH.setContainer(resourcegroupOSH)
                myVec.add(svcifOSH)
                phydiskhb = ipaddr.split('/')
                lenphydisk = len(phydiskhb)
                phydiskOSH = ObjectStateHolder('physicalvolume')
                phydiskOSH.setAttribute('data_name', phydiskhb[lenphydisk - 1])
                phydiskOSH.setContainer(HostOSH)
                myVec.add(phydiskOSH)
                dependOSH = modeling.createLinkOSH('depend', svcifOSH,
                                                   phydiskOSH)
                myVec.add(dependOSH)
    svclblOSH = ObjectStateHolder('hacmpresource')
    svclblOSH.setAttribute('data_name', service_label)
    svclblOSH.setAttribute('resource_type', 'service label')
    svclblOSH.setContainer(resourcegroupOSH)
    myVec.add(svclblOSH)
    return myVec
Beispiel #20
0
def reportVirtualMachine(vm_map, server, server_osh, host_class, lpar, server_serial_to_interfaces):
    vector = ObjectStateHolderVector()
    key = '%s%s' % (server.serial, lpar.lparId)
    hostDo = vm_map.get(key)
    
    if not hostDo:
        logger.warn('Failed to report lpar with id %s and name %s' % (lpar.lparId, lpar.lparName))
        return vector, None
    
    vm_osh = buildGenericHostObject(host_class, hostDo, False)
    if lpar.type != 'os400':
        vm_osh.setStringAttribute("os_family", 'unix')


    if lpar.logicalSerialNumber:
        vm_osh.setStringAttribute('serial_number', lpar.logicalSerialNumber)
    elif hostDo.serial:
        vm_osh.setStringAttribute('serial_number', 'derived:%s' % hostDo.serial)
    
    if hostDo.ipList:
        vm_osh.setStringAttribute('host_key', str(hostDo.ipList[0]))
    if not hostDo.ipList and hostDo.macs:
        vm_osh.setStringAttribute('host_key', str(hostDo.macs[0]))
    hypervisor_osh = createIbmHypervisorOsh(server_osh)
    link_osh = modeling.createLinkOSH('execution_environment', hypervisor_osh, vm_osh)
    vector.add(vm_osh)
    vector.add(hypervisor_osh)
    vector.add(link_osh)
    if lpar.rmcIp:
        hostDo.ipList.append(lpar.rmcIp)
    if hostDo.ipList:
        for ip in hostDo.ipList:
            #logger.debug('Reporting %s ip for lpar %s' % (ip, hostDo.displayName))
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', vm_osh, ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)
    
    interfaces_map = server_serial_to_interfaces.get(hostDo.serial, {})
    if hostDo.macs:
        for mac in hostDo.macs:
            interface_osh = modeling.createInterfaceOSH(mac, vm_osh)
            vector.add(interface_osh)
            server_iface_osh = interfaces_map.get(mac)
            if server_iface_osh:
                link_osh = modeling.createLinkOSH('realization', interface_osh, server_iface_osh)
                vector.add(link_osh)

    return vector, vm_osh
def createinterfaces(shell,HostOSH,Framework):
    mac = None
    myVec = ObjectStateHolderVector()
    lines = ()
    
    # Get a listing of the device names for the network interfaces
    # prtconf = client.execCmd('lscfg | grep ent')
     
     
    prtconf = shell.execAlternateCmds('/usr/sbin/lsdev -Cc adapter | egrep ^ent',
                                    'lsdev -Cc adapter | egrep ^ent',
                                    'lsdev -Cc adapter | grep -e ^ent',
                                    '/usr/sbin/lsdev -Cc adapter | grep -e ^ent')
    #prtconf ='ent0      Available 03-08 2-Port 10/100/1000 Base-TX PCI-X Adapter (14108902)'

    if prtconf == None:
        prtconf = ''

    lines = prtconf.split('\n')
    interfaces = {}
    for line in lines:
        m = re.search('^(\S+)',line)
        if(m):
            interfaces[m.group(1)] = 'pending'

        if(len(interfaces) < 1):
            logger.debug('did not find any interfaces in prtconf (timeout?)' )
            #fail step
            return 

        # Get further info on each of the network interfaces
        for devname in interfaces.keys():
            entstat = shell.execCmd('entstat ' + devname)#@@CMD_PERMISION shell protocol execution
#            entstat = simulatecmd('c:/entstat.txt')
            if entstat == None:
                entstat = ''
            m = re.search('Device Type: (.+)', entstat)
            intdescription = None
            if(m):
                intdescription = m.group(1).strip()
            m = re.search('Hardware Address: ([0-9a-f:]{17})', entstat)
            rawMac = None
            if(m):
                rawMac = m.group(1)
                mac = netutils.parseMac(rawMac) 
                hostifOSH = modeling.createInterfaceOSH(mac, description=intdescription)
                hostifOSH.setContainer(HostOSH)
                myVec.add(hostifOSH) 
    return myVec
Beispiel #22
0
    def build(self, port):
        if port is None:
            raise ValueError("port is None")

        interfaceOsh = modeling.createInterfaceOSH(port.getMac(),
                                                   name=port.getName())

        if interfaceOsh:
            _roleMethodFn = fptools.comp(self.roleMethods.get,
                                         lambda r: r.getId())
            roleMethods = itertools.ifilter(
                None, itertools.imap(_roleMethodFn, port.iterRoles()))
            for method in roleMethods:
                method(interfaceOsh)

        return interfaceOsh
Beispiel #23
0
def createIF_OSH(physicalAddress, hostOSH, description, macHostMap, hostedOnId, concentrator=0):
	ifOSH = ObjectStateHolder()
	if macHostMap.has_key(physicalAddress) and macHostMap[physicalAddress][0] == hostedOnId and concentrator == 0:
		#logger.debug ('Found existing interface OSH on host [%s]- %s' % (macHostMap[physicalAddress][0], macHostMap[physicalAddress][1]))
		if notNull(macHostMap[physicalAddress][1]):
			return macHostMap[physicalAddress][1]
	else:
		name = description
		ifOSH = modeling.createInterfaceOSH(physicalAddress, hostOSH, description, None, None, None, None, None, name)
		if ifOSH:
			if physicalAddress[0:4] == _MAC_PREFIX:		# create pseudo interfaces. these have no MAC addresses, so use the the key - 'ZZZZ' + NNM_INTERFACE_UID
				ifOSH.setBoolAttribute('isPseudo', 1)
			else:
				ifOSH.setBoolAttribute('isPseudo', 0)
			macHostMap[physicalAddress] = [hostedOnId, ifOSH]
	return ifOSH
def createTransportInterfaceObject(nodeName, interfaceName, cluster,
                                   hostOshByName):
    hostOsh = hostOshByName.get(nodeName)
    if not hostOsh: return

    node = cluster.nodesByName.get(nodeName)
    if not node: return

    tAdapter = node.transportAdaptersByName.get(interfaceName)
    if not tAdapter: return

    interfaceOsh = modeling.createInterfaceOSH(tAdapter.mac,
                                               hostOsh,
                                               name=tAdapter.name)
    if interfaceOsh:
        return (interfaceOsh, tAdapter)
Beispiel #25
0
def report_vm_node(vm_config, hypervisor_osh):
    '''
    Create VM node identified by virtual interfaces

    @types: list[ovm_cli.ShowVmCmd.Config], osh -> osh[node]?, seq[osh]
    '''
    name = vm_config.vm.name
    host_osh = ovm_node.build_vm_node(name)
    oshs = (modeling.createInterfaceOSH(second(vnic), host_osh)
            for vnic in vm_config.vnics)
    oshs = filter(None, oshs)
    if not oshs:
        return None, ()
    report_run_link = ovm_linkage.Reporter().execution_environment
    oshs.append(report_run_link(hypervisor_osh, host_osh))
    oshs.append(host_osh)
    return host_osh, oshs
def report_vm_node(vm_config, hypervisor_osh):
    '''
    Create VM node identified by virtual interfaces

    @types: list[ovm_cli.ShowVmCmd.Config], osh -> osh[node]?, seq[osh]
    '''
    name = vm_config.vm.name
    host_osh = ovm_node.build_vm_node(name)
    oshs = (modeling.createInterfaceOSH(second(vnic), host_osh)
                      for vnic in vm_config.vnics)
    oshs = filter(None, oshs)
    if not oshs:
        return None, ()
    report_run_link = ovm_linkage.Reporter().execution_environment
    oshs.append(report_run_link(hypervisor_osh, host_osh))
    oshs.append(host_osh)
    return host_osh, oshs
Beispiel #27
0
def reportSwitch(hostDo, chassis_map, server_map, fsm_osh):
    vector = ObjectStateHolderVector()
    switch_osh = buildSwitch(hostDo)
    link_osh = modeling.createLinkOSH('manage', fsm_osh, switch_osh)
    vector.add(link_osh)
    if hostDo.ipList:
        for ip in hostDo.ipList:
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', switch_osh, ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)
            
    iface_mac_to_iface_osh = {}
    if hostDo.macs:
        for mac in hostDo.macs:
            interface_osh = modeling.createInterfaceOSH(mac, switch_osh)
            vector.add(interface_osh)
            iface_mac_to_iface_osh[mac] = interface_osh
    return vector, switch_osh
Beispiel #28
0
def reportServer(hostDo, chassis_map):
    vector = ObjectStateHolderVector()
    server_osh = buildServer(hostDo)
    chassis_osh = chassis_map.get(hostDo.referenced_chassis)
    if not chassis_osh:
        logger.warn(
            'Failed to get referenced chassis "%s" for server %s. Server will not be reported.'
            % (hostDo.referenced_chassis, hostDo))
        return vector, None, {}
    link_osh = modeling.createLinkOSH('containment', chassis_osh, server_osh)
    vector.add(server_osh)
    vector.add(chassis_osh)
    vector.add(link_osh)

    if hostDo.ipList:
        for ip in hostDo.ipList:
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', server_osh,
                                              ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)

    iface_mac_to_iface_osh = {}
    if hostDo.macs:
        for mac in hostDo.macs:
            interface_osh = modeling.createInterfaceOSH(mac, server_osh)
            vector.add(interface_osh)
            iface_mac_to_iface_osh[mac] = interface_osh

    if hostDo.managedSystem:
        if hostDo.managedSystem.cpuParameters and hostDo.managedSystem.cpuParameters.instCpuUnits:
            for i in xrange(
                    int(hostDo.managedSystem.cpuParameters.instCpuUnits)):
                cpuOsh = modeling.createCpuOsh('CPU' + str(i), server_osh)
                # We treat a core as a physical CPU, so set core_number to 1
                cpuOsh.setIntegerAttribute("core_number", 1)
                vector.add(cpuOsh)

        if hostDo.managedSystem.ioSlotList:
            for ioSlot in hostDo.managedSystem.ioSlotList:
                vector.add(ibm_hmc_lib.createIoSlotOsh(ioSlot, server_osh))

    return vector, server_osh, iface_mac_to_iface_osh
Beispiel #29
0
def reportSwitch(hostDo, chassis_map, server_map, fsm_osh):
    vector = ObjectStateHolderVector()
    switch_osh = buildSwitch(hostDo)
    link_osh = modeling.createLinkOSH('manage', fsm_osh, switch_osh)
    vector.add(link_osh)
    if hostDo.ipList:
        for ip in hostDo.ipList:
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', switch_osh,
                                              ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)

    iface_mac_to_iface_osh = {}
    if hostDo.macs:
        for mac in hostDo.macs:
            interface_osh = modeling.createInterfaceOSH(mac, switch_osh)
            vector.add(interface_osh)
            iface_mac_to_iface_osh[mac] = interface_osh
    return vector, switch_osh
def addserviceresourceOSH(shell, resourceDictionary, HostOSH, myVec, SvcDictionary, resourcegroupOSH):
    for svcif_name in SvcDictionary.keys():
        (svcif_name, svcif_ip, svcif_device, svcif_interface, svcif_node, svcif_network, svcif_status, service_label) = SvcDictionary[svcif_name]
        if resourceDictionary.has_key(svcif_name):
            (name, type, network, nettype, attr, node, ipaddr, haddr, interfacename, globalname, netmask, hb_addr, site_name) = resourceDictionary[svcif_name]
            if (type == 'boot'):
                svcifOSH = ObjectStateHolder('hacmpresource')
                svcifOSH.setAttribute('data_name', svcif_name)
                svcifOSH.setAttribute('resource_type', 'interface')
                svcifOSH.setAttribute('resource_subtype', type)
                svcifOSH.setContainer(resourcegroupOSH)
                myVec.add(svcifOSH)
                mac_address = None
                mac_address = getMAC(shell, interfacename)
                if (mac_address != None):
                    hostifOSH = modeling.createInterfaceOSH(mac_address, name=interfacename)
                    hostifOSH.setContainer(HostOSH)
                    myVec.add(hostifOSH)
                    dependOSH = modeling.createLinkOSH('depend', svcifOSH, hostifOSH)
                    myVec.add(dependOSH)
            if (type == 'service') and (nettype == 'diskhb'):
                svcifOSH = ObjectStateHolder('hacmpresource')
                svcifOSH.setAttribute('data_name', svcif_name)
                svcifOSH.setAttribute('resource_type', 'network')
                svcifOSH.setAttribute('resource_subtype', type)
                svcifOSH.setContainer(resourcegroupOSH)
                myVec.add(svcifOSH)
                phydiskhb = ipaddr.split('/')
                lenphydisk =len(phydiskhb)
                phydiskOSH =   ObjectStateHolder('physicalvolume')
                phydiskOSH.setAttribute('data_name', phydiskhb[lenphydisk-1] )
                phydiskOSH.setContainer(HostOSH)
                myVec.add(phydiskOSH)
                dependOSH = modeling.createLinkOSH('depend', svcifOSH, phydiskOSH)
                myVec.add(dependOSH)
    svclblOSH = ObjectStateHolder('hacmpresource')
    svclblOSH.setAttribute('data_name', service_label)
    svclblOSH.setAttribute('resource_type', 'service label')
    svclblOSH.setContainer(resourcegroupOSH)
    myVec.add(svclblOSH)
    return myVec
Beispiel #31
0
def reportRemotePeer(remote_peer, localInterfaceOsh, local_mac):
    vector = ObjectStateHolderVector()
    if remote_peer.peer_ips:
        hostOsh = modeling.createHostOSH(str(remote_peer.peer_ips[0]))
    if remote_peer.platform in VIRTUAL_HOST_PLATFORMS:
        hostOsh.setBoolAttribute('host_isvirtual', 1)
        vector.add(hostOsh)
        for ip in remote_peer.peer_ips:
            ipOsh = modeling.createIpOSH(ip)
            linkOsh = modeling.createLinkOSH('containment', hostOsh, ipOsh)
            vector.add(ipOsh)
            vector.add(linkOsh)
    else:
        hostOsh = ObjectStateHolder('node')
        hostOsh.setBoolAttribute('host_iscomplete', 1)
        hostOsh.setStringAttribute('name', remote_peer.system_name)
        if remote_peer.platform in VIRTUAL_HOST_PLATFORMS:
            hostOsh.setBoolAttribute('host_isvirtual', 1)
        vector.add(hostOsh)

    if remote_peer.interface_name or remote_peer.interface_mac:
        remoteInterfaceOsh = modeling.createInterfaceOSH(
            mac=remote_peer.interface_mac,
            hostOSH=hostOsh,
            name=remote_peer.interface_name)
        if not remoteInterfaceOsh:
            return ObjectStateHolderVector()
        if remote_peer.interface_name:
            remoteInterfaceOsh.setStringAttribute('name',
                                                  remote_peer.interface_name)
        vector.add(remoteInterfaceOsh)
        l2id = str(
            hash(':'.join([
                remote_peer.interface_mac or remote_peer.interface_name,
                local_mac
            ])))
        vector.addAll(
            reportLayer2Connection(localInterfaceOsh, remoteInterfaceOsh,
                                   l2id))
    return vector
Beispiel #32
0
def reportServer(hostDo, chassis_map):
    vector = ObjectStateHolderVector()
    server_osh = buildServer(hostDo)
    chassis_osh = chassis_map.get(hostDo.referenced_chassis)
    if not chassis_osh:
        logger.warn('Failed to get referenced chassis "%s" for server %s. Server will not be reported.' % (hostDo.referenced_chassis, hostDo))
        return vector, None, {}
    link_osh = modeling.createLinkOSH('containment', chassis_osh, server_osh)
    vector.add(server_osh)
    vector.add(chassis_osh)
    vector.add(link_osh)

    if hostDo.ipList:
        for ip in hostDo.ipList:
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', server_osh, ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)
            
    iface_mac_to_iface_osh = {}
    if hostDo.macs:
        for mac in hostDo.macs:
            interface_osh = modeling.createInterfaceOSH(mac, server_osh)
            vector.add(interface_osh)
            iface_mac_to_iface_osh[mac] = interface_osh
            
    if hostDo.managedSystem:
        if hostDo.managedSystem.cpuParameters and hostDo.managedSystem.cpuParameters.instCpuUnits:
            for i in xrange(int(hostDo.managedSystem.cpuParameters.instCpuUnits)):
                cpuOsh = modeling.createCpuOsh('CPU' + str(i), server_osh)
                # We treat a core as a physical CPU, so set core_number to 1
                cpuOsh.setIntegerAttribute("core_number", 1)
                vector.add(cpuOsh)
                
        if hostDo.managedSystem.ioSlotList:
            for ioSlot in hostDo.managedSystem.ioSlotList:
                vector.add(ibm_hmc_lib.createIoSlotOsh(ioSlot, server_osh))

    return vector, server_osh, iface_mac_to_iface_osh
def processInterfaces(_vector, ifOshMap, hostIfMap, hostId, ifMap, hostOSH):
	if hostIfMap.has_key(hostId):
		ifList = hostIfMap[hostId]
		for ifs in ifList:
			if ifMap.has_key(ifs):
				physicalAddress = ifMap[ifs].physicalAddress
				description = None
				name = None
				ifobj = ifMap[ifs]
				if notNull(ifobj.ifDescr) or notNull(ifobj.ifName) or notNull(physicalAddress):
					description = ifobj.ifDescr
					ifName = ifobj.ifName
					if notNull(description) and not notNull(ifName):
						ifName = description
					if not notNull(physicalAddress):
						physicalAddress = ''
					ifOSH = modeling.createInterfaceOSH(physicalAddress, hostOSH, description, ifobj.ifIndex, ifobj.ifType, None, None, ifobj.ifSpeed, ifName, ifobj.ifAlias)
					if notNull(ifOSH):
						ifOSH = setPseudoAttribute(ifOSH, physicalAddress)
						_vector.add(ifOSH)
						ifOshMap[ifs] = ifOSH ## Add interface OSH to map for later use to create L2 Connection objects
	return (_vector, ifOshMap)
Beispiel #34
0
    def report(self, ivmHostOsh, hypervisor, vms, reportVmName):
        if not (ivmHostOsh and hypervisor and vms):
            raise ValueError("Failed to build topology. Not all required entities are discovered.")

        vector = ObjectStateHolderVector()
        hypervisorOsh = createHypervisorOsh(hypervisor, ivmHostOsh)
        vector.add(hypervisorOsh)
        logger.debug(vms)
        for vm in vms:
            logger.debug("Report name %s" % reportVmName)
            if reportVmName and reportVmName.lower().strip() == "true":
                virtualServerOsh = createVirtualServerOsh(vm)
            elif vm.macs:
                virtualServerOsh = createVirtualServerOsh(vm, False)

            vector.add(virtualServerOsh)
            if vm.macs:
                for mac in vm.macs:
                    vector.add(modeling.createInterfaceOSH(mac, virtualServerOsh))
            vector.add(modeling.createLinkOSH("execution_environment", hypervisorOsh, virtualServerOsh))
            virtualServerConfigOsh = createVirtualServerConfigOsh(vm.vserver_config, virtualServerOsh)
            vector.add(virtualServerConfigOsh)
        return vector
def DiscoveryMain(Framework):
    OSHVResult = ObjectStateHolderVector()

    connection = Framework.getProbeDatabaseConnection('common')

    for mac_preffix, vendor in THIN_CLIENT_MAC_TO_VENDOR_PAIRS.items():
        st = getPreparedStatement(connection, mac_preffix)
        rs = st.executeQuery()
        while (rs.next()):
            mac = rs.getString('mac_address')
            ip = rs.getString('ip_address')
            if ip_addr.isValidIpAddressNotZero(
                    ip) and not DSM.isIpOutOfScope(ip) and DSM.isClientIp(ip):
                ip_osh = build_client_ip_osh(ip, mac)
                node_osh = build_node_osh(mac, vendor)
                if ip_osh and node_osh:
                    link_osh = modeling.createLinkOSH('containment', node_osh,
                                                      ip_osh)
                    interface_osh = modeling.createInterfaceOSH(mac, node_osh)
                    OSHVResult.add(ip_osh)
                    OSHVResult.add(node_osh)
                    OSHVResult.add(link_osh)
                    OSHVResult.add(interface_osh)
                else:
                    debug(
                        'Failed to create topology for ip %s , mac %s, vendor %s'
                        % (ip, mac, vendor))
            else:
                debug(
                    'Skipping IP address %s since it is invalid or not assigned to any probe or not in client ip range. '
                    % ip)
        rs.close()
        connection.close(st)

    connection.close()
    return OSHVResult
Beispiel #36
0
def processNmapResult(fileName, OSHVResult, discoverOsName,
                      doServiceFingerprints, createApp, Framework):
    try:
        document = SAXBuilder(0).build(fileName)
    except:
        raise ValueError, "Can't parse XML document with nmap results. Skipped."
    hosts = XmlWrapper(document.getRootElement().getChildren('host'))
    for host in hosts:
        hostOsh = None
        ip = None
        macs = []
        addresses = XmlWrapper(host.getChildren('address'))
        for address in addresses:
            type = address.getAttributeValue('addrtype')
            addr = address.getAttributeValue('addr')
            if type == 'ipv4':
                ip = addr
            elif type == 'mac':
                macs.append(addr)
        hostnames = host.getChild('hostnames')
        if (hostnames is not None) and netutils.isValidIp(ip):
            hostnames = map(lambda elem: elem.getAttributeValue('name'),
                            XmlWrapper(hostnames.getChildren('hostname')))
            hostname = hostnames and hostnames[
                0] or None  #using only first dnsname
            os = host.getChild('os')
            if os and discoverOsName:
                osClass = os.getChild('osclass')
                if not osClass:
                    osMatch = os.getChild('osmatch')
                    osClass = osMatch.getChild('osclass')
                if osClass:
                    osType = osClass.getAttributeValue("type")
                    osFamily = osClass.getAttributeValue("osfamily")
                    osVendor = osClass.getAttributeValue("vendor")

                    hostClass = getHostClass(osType, osFamily)
                    if not hostClass:
                        Framework.reportWarning(
                            "Unknown OS detected. Vendor '%s', family '%s'" %
                            (osVendor, osFamily))
                        hostClass = "host"

                    hostOsh = modeling.createHostOSH(ip, hostClass)
                    hostOsh.setAttribute("host_vendor", osVendor)
                    osMatch = os.getChild('osmatch')
                    if osMatch:
                        separateCaption(hostOsh,
                                        osMatch.getAttributeValue("name"))
                        hostOsh.setAttribute(
                            "host_osaccuracy",
                            osMatch.getAttributeValue("accuracy") + '%')
            if not hostOsh:
                hostOsh = modeling.createHostOSH(ip)

            ipOsh = modeling.createIpOSH(ip, dnsname=hostname)
            OSHVResult.add(ipOsh)
            OSHVResult.add(finalizeHostOsh(hostOsh))
            OSHVResult.add(modeling.createLinkOSH('contained', hostOsh, ipOsh))

            for mac in macs:
                if netutils.isValidMac(mac):
                    interfaceOsh = modeling.createInterfaceOSH(mac, hostOsh)
                    OSHVResult.add(interfaceOsh)
                    OSHVResult.add(
                        modeling.createLinkOSH('containment', interfaceOsh,
                                               ipOsh))

            applicationList = []
            if not host.getChild('ports'):
                return
            ports = XmlWrapper(host.getChild('ports').getChildren('port'))
            for port in ports:
                portNumber = port.getAttributeValue('portid')
                protocol = port.getAttributeValue('protocol')
                serviceName = None
                if doServiceFingerprints:
                    if port.getChild("state").getAttributeValue("state").find(
                            'open') == -1:
                        continue
                    serviceNode = port.getChild("service")
                    if serviceNode:
                        serviceName = serviceNode.getAttributeValue("name")
                        serviceProduct = serviceNode.getAttributeValue(
                            "product")
                        serviceVersion = serviceNode.getAttributeValue(
                            "version")
                        if createApp and serviceProduct and serviceProduct not in applicationList:
                            addApplicationCI(ip, hostOsh, serviceProduct,
                                             serviceVersion, OSHVResult)
                            applicationList.append(serviceProduct)
                addServiceAddressOsh(hostOsh, OSHVResult, ip, portNumber,
                                     protocol, serviceName)
Beispiel #37
0
 def build_vif(self, vif):
     return modeling.createInterfaceOSH(vif.getMAC())
Beispiel #38
0
 def build_pif(self, pif):
     return modeling.createInterfaceOSH(pif.getMAC(), name=pif.getName())
Beispiel #39
0
def processNodeInfo(ipAddress, macAddress, nodeName, subnetMask, ipAddressList, macAddressList, nodeOshDict, allowDnsLookup):
    try:
        nodeOSH = interfaceOSH = ipOSH = None
        ## Try and get a DNS name for this node
        nodeDnsName = None
        if allowDnsLookup and ipAddress and netutils.isValidIp(ipAddress):
            nodeDnsName = netutils.getHostName(ipAddress)
            ciscoworks_utils.debugPrint(3, '[' + SCRIPT_NAME + ':processNodeInfo] Got DNS name <%s> for Node <%s> using IP <%s>' % (nodeDnsName, nodeName, ipAddress))
            if nodeDnsName:
                nodeName = nodeDnsName

        ## Discard IP if this is a duplicate
        if ipAddress and netutils.isValidIp(ipAddress) and ipAddress in ipAddressList:
            logger.debug('Ignoring duplicate IP <%s> on Node <%s>...' % (ipAddress, nodeName))
            ipAddress = None
        else:
            ipAddressList.append(ipAddress)

        ## Set the real name of the netDevice
        nodeRealName = nodeName
        if nodeName and netutils.isValidIp(nodeName):
            nodeRealName = ''

        ## Build a host key and create OSHs
        ## Check for and clean up MAC
        macAddy = None
        if macAddress:
            macAddy = netutils.parseMac(macAddress)
            ## Check for duplicate MAC addresses
            if macAddy in macAddressList:
                logger.debug('Ignoring duplicate MAC Address <%s> on Node <%s>...' % (macAddy, nodeName))
                macAddy = None
            else:
                macAddressList.append(macAddy)
            if netutils.isValidMac(macAddy):
                ciscoworks_utils.debugPrint(3, '[' + SCRIPT_NAME + ':processNodeInfo] Got MAC Address <%s> for Node <%s>' % (macAddy, nodeName))
                nodeOSH = modeling.createCompleteHostOSH('node', macAddy, None, nodeName)
                interfaceOSH = modeling.createInterfaceOSH(macAddy, nodeOSH)
            else:
                ciscoworks_utils.debugPrint(3, '[' + SCRIPT_NAME + ':processNodeInfo] Got invalid MAC Address <%s> for Node <%s>' % (macAddress, nodeName))
                macAddy = None

        ## Check for a valid IP
        if ipAddress and netutils.isValidIp(ipAddress):
            subnetMask = None
            if subnetMask:
                subnetMask = netutils.parseNetMask(subnetMask)
            ipOSH = modeling.createIpOSH(ipAddress, subnetMask, ipAddress, None)
            ## Use IP as a host key if a MAC is not available
            if not macAddy:
                nodeOSH = modeling.createHostOSH(ipAddress, 'node', None, nodeRealName)
        else:
            logger.debug('IP address not available for Node <%s> with MAC address <%s>' % (nodeName, macAddress))

        if not nodeOSH:
            logger.debug('Ignoring Node <%s> because a valid IP/MAC address was not found for it...' % nodeName)

        return (nodeOSH, interfaceOSH, ipOSH)
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME + ':processNodeInfo] Exception: <%s>' % excInfo)
        pass
Beispiel #40
0
def doDicovery(shell, framework, rootServerOsh):
    resultVector = ObjectStateHolderVector()
    try:
        domainsList = discoverDomainsList(shell)
    except ValueError:
        raise ValueError, 'No libvirt Found. Failed to discover neither Xen nor KVM'
    domainsConfigDict = discoverDomainConfiguration(shell, domainsList)

    bridgeDict = discoverBridges(shell)
    ifaceNameToIfaceMacMap = discoverInterfacesByIfconfig(shell)
    #building topology
    ucmdbVersion = logger.Version().getVersion(framework)

    resultVector.add(rootServerOsh)
    bridgeToPortOshMap = {}
    for bridge in bridgeDict.values():
        bridgeOsh = createBridgeOsh(bridge.mac, bridge.name, rootServerOsh)
        if bridgeOsh:
            portNumber = 0
            for ifaceName in bridge.ifaceNameList:
                ifaceMac = ifaceNameToIfaceMacMap.get(ifaceName)
                interfaceOsh = modeling.createInterfaceOSH(
                    ifaceMac, rootServerOsh)
                resultVector.add(bridgeOsh)
                if interfaceOsh:
                    linkOsh = modeling.createLinkOSH('containment', bridgeOsh,
                                                     interfaceOsh)
                    resultVector.add(linkOsh)
                    resultVector.add(interfaceOsh)
                    portOsh = createBridgePhysicalPort(str(portNumber),
                                                       bridgeOsh)
                    portNumber += 1
                    linkOsh = modeling.createLinkOSH('realization', portOsh,
                                                     interfaceOsh)
                    bridgeToPortOshMap[bridge.name] = portOsh
                    resultVector.add(portOsh)
                    resultVector.add(linkOsh)

    (hypervisorVersion,
     hypervisorVersionDescription) = getHypervisorData(shell)
    if hypervisorVersion and not domainsConfigDict and checkKvmIrqProcess(
            shell):
        hypervisorOsh = KvmHypervisor(
            hypervisorVersion,
            hypervisorVersionDescription).build(rootServerOsh)
        resultVector.add(hypervisorOsh)

    for (domainName, config) in domainsConfigDict.items():
        hypervisorOsh = config.name == XEN_DOMAIN and XenHypervisor(
            hypervisorVersion, hypervisorVersionDescription).build(
                rootServerOsh) or KvmHypervisor(
                    hypervisorVersion,
                    hypervisorVersionDescription).build(rootServerOsh)
        resultVector.add(hypervisorOsh)

        if config.domainId == 0 and config.name == XEN_DOMAIN:
            domainConfigOsh = createXenDomainConfigOsh(config, rootServerOsh)
            resultVector.add(domainConfigOsh)
        else:
            vHostOsh = createVirtHostOsh(config)
            if vHostOsh:
                domainConfigOsh = config.name == XEN_DOMAIN and createXenDomainConfigOsh(
                    config, vHostOsh) or createKvmDomainConfigOsh(
                        config, vHostOsh)
                linkOsh = modeling.createLinkOSH('run', hypervisorOsh,
                                                 vHostOsh)
                resultVector.add(vHostOsh)
                resultVector.add(domainConfigOsh)
                resultVector.add(linkOsh)
                for networkInterface in config.interfaceList:
                    interfaceOsh = modeling.createInterfaceOSH(
                        networkInterface.macAddress, vHostOsh)
                    if interfaceOsh:
                        interfaceOsh.setBoolAttribute('isvirtual', 1)
                        resultVector.add(interfaceOsh)
                for i in range(len(config.bridgeNameList)):
                    bridgeName = config.bridgeNameList[i]
                    ifaceMac = config.interfaceList[i]
                    bridge = bridgeDict.get(bridgeName)
                    if bridge:
                        interfaceOsh = modeling.createInterfaceOSH(
                            networkInterface.macAddress, vHostOsh)
                        portOsh = bridgeToPortOshMap.get(bridgeName)
                        if ucmdbVersion < 9:
                            linkOsh = modeling.createLinkOSH(
                                'layertwo', interfaceOsh, portOsh)
                            resultVector.add(linkOsh)
                shareOsh = createNetworkShare(config.disk, rootServerOsh,
                                              ucmdbVersion)
                if shareOsh:
                    diskOsh = modeling.createDiskOSH(
                        vHostOsh, config.mountPoint,
                        modeling.UNKNOWN_STORAGE_TYPE)
                    if diskOsh:
                        linkOsh = modeling.createLinkOSH(
                            'realization', shareOsh, diskOsh)
                        resultVector.add(shareOsh)
                        resultVector.add(diskOsh)
                        resultVector.add(linkOsh)
    return resultVector
Beispiel #41
0
 def build(self, switch):
     if not switch:
         raise ValueError("switch is None")
     return modeling.createInterfaceOSH(None, name=switch.backingInterfaceName)
Beispiel #42
0
 def createPnic(self, pnic):
     mac = pnic.getMac()
     name = pnic.getDevice()
     driver = pnic.getDriver()
     pnicOsh = modeling.createInterfaceOSH(mac, name = name, alias = driver)
     return pnicOsh
Beispiel #43
0
 def build(self, switch):
     if not switch:
         raise ValueError("switch is None")
     if not switch.getMac():
         raise ValueError("switch has no MAC")
     return modeling.createInterfaceOSH(switch.getMac())
 def build_pif(self, pif):
     return modeling.createInterfaceOSH(pif.getMAC(), name=pif.getName())
Beispiel #45
0
def doDicovery(shell, framework, rootServerOsh):
    resultVector = ObjectStateHolderVector()
    try:
        domainsList = discoverDomainsList(shell)
    except ValueError:
        raise ValueError, 'No libvirt Found. Failed to discover neither Xen nor KVM'
    domainsConfigDict = discoverDomainConfiguration(shell, domainsList)
    
    bridgeDict = discoverBridges(shell)
    ifaceNameToIfaceMacMap = discoverInterfacesByIfconfig(shell)
    #building topology
    ucmdbVersion = logger.Version().getVersion(framework)
    
    resultVector.add(rootServerOsh)
    bridgeToPortOshMap = {}
    for bridge in bridgeDict.values():
        bridgeOsh = createBridgeOsh(bridge.mac, bridge.name, rootServerOsh)
        if bridgeOsh:
            portNumber = 0
            for ifaceName in bridge.ifaceNameList:
                ifaceMac = ifaceNameToIfaceMacMap.get(ifaceName)
                interfaceOsh = modeling.createInterfaceOSH(ifaceMac, rootServerOsh)
                resultVector.add(bridgeOsh)
                if interfaceOsh:
                    linkOsh = modeling.createLinkOSH('containment', bridgeOsh, interfaceOsh)
                    resultVector.add(linkOsh)
                    resultVector.add(interfaceOsh)
                    portOsh = createBridgePhysicalPort(str(portNumber), bridgeOsh)
                    portNumber += 1
                    linkOsh = modeling.createLinkOSH('realization', portOsh, interfaceOsh)
                    bridgeToPortOshMap[bridge.name] = portOsh
                    resultVector.add(portOsh)
                    resultVector.add(linkOsh)
    
    (hypervisorVersion, hypervisorVersionDescription) = getHypervisorData(shell)
    if hypervisorVersion and not domainsConfigDict and checkKvmIrqProcess(shell):
        hypervisorOsh = KvmHypervisor(hypervisorVersion, hypervisorVersionDescription).build(rootServerOsh)
        resultVector.add(hypervisorOsh)
        
    for (domainName, config) in domainsConfigDict.items():
        hypervisorOsh = config.name == XEN_DOMAIN and XenHypervisor(hypervisorVersion, hypervisorVersionDescription).build(rootServerOsh) or KvmHypervisor(hypervisorVersion, hypervisorVersionDescription).build(rootServerOsh)
        resultVector.add(hypervisorOsh)

        if config.domainId == 0 and config.name == XEN_DOMAIN:
            domainConfigOsh = createXenDomainConfigOsh(config, rootServerOsh)
            resultVector.add(domainConfigOsh)
        else:
            vHostOsh = createVirtHostOsh(config)
            if vHostOsh: 
                domainConfigOsh = config.name == XEN_DOMAIN and createXenDomainConfigOsh(config, vHostOsh) or createKvmDomainConfigOsh(config, vHostOsh) 
                linkOsh = modeling.createLinkOSH('run', hypervisorOsh, vHostOsh)
                resultVector.add(vHostOsh)
                resultVector.add(domainConfigOsh)
                resultVector.add(linkOsh)
                for networkInterface in config.interfaceList:  
                    interfaceOsh = modeling.createInterfaceOSH(networkInterface.macAddress, vHostOsh)
                    if interfaceOsh: 
                        interfaceOsh.setBoolAttribute('isvirtual', 1)
                        resultVector.add(interfaceOsh)
                for i in range(len(config.bridgeNameList)):
                    bridgeName = config.bridgeNameList[i]
                    ifaceMac = config.interfaceList[i]
                    bridge = bridgeDict.get(bridgeName)
                    if bridge:
                        interfaceOsh = modeling.createInterfaceOSH(networkInterface.macAddress, vHostOsh)
                        portOsh = bridgeToPortOshMap.get(bridgeName)
                        if ucmdbVersion < 9:
                            linkOsh = modeling.createLinkOSH('layertwo', interfaceOsh, portOsh)
                            resultVector.add(linkOsh)
                shareOsh = createNetworkShare(config.disk, rootServerOsh, ucmdbVersion)
                if shareOsh:
                    diskOsh = modeling.createDiskOSH(vHostOsh, config.mountPoint, modeling.UNKNOWN_STORAGE_TYPE)
                    if diskOsh:
                        linkOsh = modeling.createLinkOSH('realization', shareOsh, diskOsh)
                        resultVector.add(shareOsh)
                        resultVector.add(diskOsh)
                        resultVector.add(linkOsh)
    return resultVector
Beispiel #46
0
 def build(self, switch):
     if not switch: raise ValueError("switch is None")
     if not switch.getMac(): raise ValueError("switch has no MAC")
     return modeling.createInterfaceOSH(switch.getMac())
Beispiel #47
0
def createInterfaceObjects(ifList, host_id, ucmdbversion = None):
    result = ObjectStateHolderVector()
    
    discoveredHostOSH = modeling.createOshByCmdbId('host', host_id)
    
    for interface in ifList:
        if interface.ifType and int(interface.ifType) == 24:
            continue
        
        if not modeling.isValidInterface(interface.ifMac, interface.ifDescr, interface.ifName):
            continue
        
        interface.ifDescr = _stripVirtualMiniportInfo(interface.ifDescr)
        
        interfaceOSH = modeling.createInterfaceOSH(interface.ifMac, discoveredHostOSH, interface.ifDescr, interface.ifIndex, interface.ifType, interface.ifAdminStatus, interface.ifOperStatus, interface.ifSpeed, interface.ifName, interface.ifAlias)
        if not interfaceOSH:
            continue

        result.add(interfaceOSH)
        if ucmdbversion and ucmdbversion < 9:
            interfaceIndexOSH = ObjectStateHolder("interfaceindex")
            interfaceIndexOSH.setIntegerAttribute("interfaceindex_index", interface.ifIndex)
            if interface.ifAdminStatus:
                intValue = None
                try:
                    intValue = int(interface.ifAdminStatus)
                except:
                    logger.warn("Failed to convert the interface admin status '%s'" % interface.ifAdminStatus)
                else:
                    if intValue > 0:
                        interfaceIndexOSH.setEnumAttribute("interfaceindex_adminstatus", intValue)
            if interface.ifDescr != None and interface.ifDescr != '':
                interfaceIndexOSH.setStringAttribute("interfaceindex_description", interface.ifDescr)
            if interface.ifIndex != None and interface.ifIndex != '':
                interfaceIndexOSH.setIntegerAttribute("interfaceindex_index", interface.ifIndex)
            if interface.ifSpeed != None and interface.ifSpeed != '':
                interfaceIndexOSH.setDoubleAttribute("interfaceindex_speed", interface.ifSpeed)
            if interface.ifType:
                intValue = None
                try:
                    intValue = int(interface.ifType)
                except:
                    logger.warn("Failed to convert the interface type '%s'" % interface.ifType)
                else:
                    if intValue > 0:
                        interfaceIndexOSH.setEnumAttribute("interfaceindex_type", intValue)
            interfaceIndexOSH.setContainer(discoveredHostOSH)
            result.add(interfaceIndexOSH)
            
    
            parentLinkOSH = modeling.createLinkOSH('parent', interfaceIndexOSH, interfaceOSH)
            result.add(parentLinkOSH)

        for ip in interface.ipList:
            if str(ip.ipAddr).startswith('0.') or str(ip.ipAddr).startswith('127.'):
                continue
            ipOSH = modeling.createIpOSH(ip.ipAddr)
            parentLinkOSH = modeling.createLinkOSH('containment', interfaceOSH, ipOSH)
            result.add(parentLinkOSH)
        
    return result
Beispiel #48
0
def getNetDevicePortsAndVlans(localDbClient, portVlanIdMap, netDeviceID,
                              netDeviceElementID, netDeviceName, netDeviceOSH):
    try:
        returnOSHV = ObjectStateHolderVector()

        netDevicePortVlanQuery = '''SELECT phyPort.PhysicalPortID, phyPort.SNMPPhysicalIndex, phyPort.ParentRelPos,
                                        port.PORT_NAME, port.PORT_DESC, port.PORT_DUPLEX_MODE, port.PORT_TYPE,
                                        port.PORT_SPEED, port.VLAN_NAME, port.VLANID, port.Port_Admin_Status, port.Port_Oper_Status,
                                        interface.EndpointID, interface.Description, interface.Alias, interface.MediaAccessAddress
                                    FROM lmsdatagrp.PORT_INVENTORY port JOIN dba.PhysicalPort phyPort ON port.PORT_NAME=phyPort.PortName
                                        JOIN dba.IFEntryEndpoint interface ON port.PORT_NAME=interface.EndpointName
                                    WHERE phyPort.NetworkElementID=%s AND interface.NetworkElementID=%s AND port.DEVICE_ID=%s
                                        AND phyPort.PortName=port.PORT_NAME''' % (
            netDeviceElementID, netDeviceElementID, netDeviceID)
        netDevicePortVlanResultSet = ciscoworks_utils.doQuery(
            localDbClient, netDevicePortVlanQuery)

        ## Return if query returns no results
        if netDevicePortVlanResultSet == None:
            logger.info(
                '[' + SCRIPT_NAME +
                ':getNetDevicePortsAndVlans] No Ports or VLANs found for Net Device <%s>'
                % netDeviceName)
            return None

        ## We have query results!
        while netDevicePortVlanResultSet.next():
            portID = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 1)
            portIndex = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 2)
            portSlot = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 3)
            portName = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 4)
            portDesc = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 5)
            portDuplexMode = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 6)
            interfaceType = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 7)
            interfaceSpeed = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 8)
            vlanName = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 9)
            vlanID = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 10)
            adminStatus = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 11)
            operStatus = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 12)
            interfaceIndex = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 13)
            interfaceDesc = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 14)
            interfaceAlias = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 15)
            interfaceMAC = ciscoworks_utils.getStringFromResultSet(
                netDevicePortVlanResultSet, 16)

            if not portID or type(eval(portID)) != type(1):
                logger.debug(
                    '[' + SCRIPT_NAME +
                    ':getNetDevicePortsAndVlans] Invalid portID found for Port <%s> on Net Device <%s>! Skipping...'
                    % (portName, netDeviceName))
                continue
            ciscoworks_utils.debugPrint(
                2, '[' + SCRIPT_NAME +
                ':getNetDevicePortsAndVlans] Got port <%s> for Net Device <%s> with ID <%s>'
                % (portName, netDeviceName, netDeviceElementID))

            ## Build PHYSICAL PORT OSH
            portOSH = ObjectStateHolder('physical_port')
            ciscoworks_utils.populateOSH(
                portOSH, {
                    'port_index': int(portIndex),
                    'name': portName,
                    'port_displayName': portName,
                    'description': portDesc,
                    'port_vlan': vlanID,
                    'port_slot': portSlot
                })
            ## Map duplex settings value to UCMDB enum
            portDuplexModeMap = {
                'auto-duplex': 'auto-negotiated',
                'full-duplex': 'full',
                'half-duplex': 'half'
            }
            if portDuplexMode and portDuplexMode in portDuplexModeMap.keys():
                ciscoworks_utils.debugPrint(
                    3, '[' + SCRIPT_NAME +
                    ':getNetDevicePortsAndVlans] Setting duplex mode <%s> for port <%s>'
                    % (portDuplexModeMap[portDuplexMode], portName))
                portOSH.setStringAttribute('duplex_setting',
                                           portDuplexModeMap[portDuplexMode])
            portOSH.setContainer(netDeviceOSH)
            returnOSHV.add(portOSH)

            ## Build INTERFACE OSH
            if interfaceMAC:
                macAddress = netutils.parseMac(interfaceMAC)
                if netutils.isValidMac(macAddress):
                    ciscoworks_utils.debugPrint(
                        3, '[' + SCRIPT_NAME +
                        ':getNetDevicePortsAndVlans] Got interface <%s> for Net Device <%s> with ID <%s>'
                        % (macAddress, netDeviceName, netDeviceElementID))
                    interfaceOSH = modeling.createInterfaceOSH(
                        macAddress, netDeviceOSH, interfaceDesc,
                        interfaceIndex, interfaceType, adminStatus, operStatus,
                        eval(interfaceSpeed), None, interfaceAlias)
                    returnOSHV.add(interfaceOSH)
                    returnOSHV.add(
                        modeling.createLinkOSH('realization', portOSH,
                                               interfaceOSH))

            ## Add this port to the port-VLAN map
            if vlanName and vlanName != 'N/A' and vlanID and vlanID != '-1' and type(
                    eval(vlanID)) == type(1):
                portVlanIdMapKey = '%s:;:%s' % (vlanName, vlanID)
                if portVlanIdMapKey in portVlanIdMap.keys():
                    ciscoworks_utils.debugPrint(
                        4, '[' + SCRIPT_NAME +
                        ':getNetDevicePortsAndVlans] Adding port <%s> to existing VLAN <%s:%s>'
                        % (portName, vlanName, vlanID))
                    portVlanIdMap[portVlanIdMapKey].append(portOSH)
                else:
                    portVlanIdMap[portVlanIdMapKey] = [portOSH]
                    ciscoworks_utils.debugPrint(
                        4, '[' + SCRIPT_NAME +
                        ':getNetDevicePortsAndVlans] Adding port <%s> to new VLAN <%s:%s>'
                        % (portName, vlanName, vlanID))

        netDevicePortVlanResultSet.close()
        return returnOSHV
    except:
        excInfo = logger.prepareJythonStackTrace('')
        logger.warn('[' + SCRIPT_NAME +
                    ':getNetDevicePortsAndVlans] Exception: <%s>' % excInfo)
        pass
Beispiel #49
0
 def build(self, virtualInterface):
     if not virtualInterface:
         raise ValueError("virtual interface is None")
     if not virtualInterface.getMac():
         raise ValueError("virtual interface has not MAC")
     return modeling.createInterfaceOSH(virtualInterface.getMac())
Beispiel #50
0
 def createPnic(self, pnic):
     mac = pnic.getMac()
     name = pnic.getDevice()
     driver = pnic.getDriver()
     pnicOsh = modeling.createInterfaceOSH(mac, name=name, alias=driver)
     return pnicOsh
def doWMI(client, wmiOSH, ip_address, ip_domain, hostForLinkOSH, host_cmdbid=None, host_key=None, host_macs=None, ucmdb_version=None):
    '''@types: WmiClient, ObjectStateHolder, IPAddress, str, ObjectStateHolder, str, str, list[str], int -> ObjectStateHolderVector
    @param ip_address: Destination IP address
    '''
    wmiProvider = wmiutils.getWmiProvider(client)
    hostDiscoverer = host_win_wmi.WmiHostDiscoverer(wmiProvider)
    hostInfo = hostDiscoverer.discoverHostInfo()
    machineName = hostInfo.hostName

    interfacesDiscover = networking_win_wmi.WmiInterfaceDiscoverer(wmiProvider,
                                                ip_address)

    vector = ObjectStateHolderVector()
    interfaceList = interfacesDiscover.getInterfaces()
    parentLinkList = ObjectStateHolderVector()

    isVirtual = 1
    resultEmpty = 1
    interfacesToUpdateList = []
    for interface in interfaceList:
        ips = interface.ips
        MACAddress = interface.macAddress
        masks = interface.masks
        Description = interface.description
        dhcpEnabled = interface.dhcpEnabled

        resultEmpty = 0
        for ipIndex, ipAddress in enumerate(__iterate_valid_ips(ips)):
            IPSubnet = (masks and masks[ipIndex]) or None
            if str(ip_address) == str(ipAddress):
                isVirtual = 0

            ipOSH = modeling.createIpOSH(ipAddress)

            # Test if the same ip and interface are in the list allready

            logger.debug('Found ip address: ', ipAddress, ', MACAddress: ', MACAddress, ', IPSubnet: ', IPSubnet, ', Description: ', Description)
                # create OSH for IP and add it to the list
                # create OSH for Network and add it to the list
            __vector = getIPNetworkMemebrList(ipAddress, IPSubnet, '', dhcpEnabled, Description)
            if __vector.size() > 0:
                vector.addAll(__vector)

            if netutils.isValidMac(MACAddress):
                # create link interface to its ip only it has an ip defined
                interfaceOSH = modeling.createInterfaceOSH(MACAddress, hostForLinkOSH, Description)
                parentLinkList.add(modeling.createLinkOSH('containment', interfaceOSH, ipOSH))
                interfacesToUpdateList.append(interfaceOSH)

    # Check if the Input IP is virtual, we do not want to return the WMI
    if isVirtual == 1:
        logger.warn('Destination is not among discovered IPs assuming virtual. WMI object will not be reported.')
        vIPOSH = modeling.createIpOSH(ip_address)
        vIPOSH.setBoolAttribute('isvirtual', 1)
        vector.add(vIPOSH)

    if resultEmpty == 1:
        logger.warn('WMI was able to connect, but WMI Query returns no results')
        vector.clear()
        return vector

    # create the host and all the objects
    if len(interfaceList) > 0:
        hostOSH = None
        try:
            hostOSH = modeling.createCompleteHostOSHByInterfaceList('nt',
                            interfaceList, 'Windows', machineName, None,
                            host_cmdbid, host_key, host_macs, ucmdb_version)
        except:
            hostOSH = modeling.createHostOSH(str(ip_address), 'nt')
            logger.debugException('Could not find a valid MAC address for key on ip : %s. Creating incomplete host\n' % ip_address)
            logger.warn('Could not find a valid MAC address for key on ip : %s. Creating incomplete host\n' % ip_address)

        # select from Win32_OperatingSystem
        _wmiQuery = 'select Caption,Version,ServicePackMajorVersion,ServicePackMinorVersion,BuildNumber,Organization,RegisteredUser,TotalVisibleMemorySize,LastBootUpTime,OtherTypeDescription,description from Win32_OperatingSystem'
        resultSet = client.executeQuery(_wmiQuery)  # @@CMD_PERMISION wmi protocol execution
        osinstalltype = None
        if resultSet.next():
            Caption = resultSet.getString(1)
            Version = resultSet.getString(2)
            ServicePackMajorVersion = resultSet.getString(3)
            ServicePackMinorVersion = resultSet.getString(4)
            BuildNumber = resultSet.getString(5)
            Organization = resultSet.getString(6)
            RegisteredUser = resultSet.getString(7)
            TotalVisibleMemorySize = resultSet.getString(8)
            LastBootUpTime = resultSet.getString(9)
            OtherTypeDescription = resultSet.getString(10)
            description = resultSet.getString(11)

            (vendor, osName, osinstalltype) = separateCaption(Caption, OtherTypeDescription)
            hostOSH.setAttribute('host_vendor', vendor)
            modeling.setHostOsName(hostOSH, osName)
            hostOSH.setAttribute('host_osinstalltype', osinstalltype)

            setLastBootUpTime(hostOSH, LastBootUpTime)
            biosUUID = getBIOSUUID(client)
            defaultGateway = getDefaultGateway(client)

            hostOSH.setAttribute('host_osversion', Version)
            sp = ServicePackMajorVersion + '.' + ServicePackMinorVersion
            if checkSpVersion(sp):
                hostOSH.setAttribute('nt_servicepack', sp)
            hostOSH.setAttribute('host_osrelease', str(BuildNumber))
            hostOSH.setAttribute('nt_registrationorg', Organization)
            hostOSH.setAttribute('nt_registeredowner', RegisteredUser)
            hostOSH.setAttribute('nt_physicalmemory', TotalVisibleMemorySize)
            hostOSH.setAttribute('host_hostname', machineName)
            modeling.setHostBiosUuid(hostOSH, biosUUID)
            modeling.setHostDefaultGateway(hostOSH, defaultGateway)
            modeling.setHostOsFamily(hostOSH, 'windows')

            hostOSH = HostBuilder(hostOSH).setDescription(description).build()

        _wmiQuery2 = 'select Manufacturer,NumberOfProcessors,Model,Domain from Win32_ComputerSystem'
        resultSet = client.executeQuery(_wmiQuery2)  # @@CMD_PERMISION wmi protocol execution

        if resultSet.next():
            Manufacturer = resultSet.getString(1)
            if ((Manufacturer != None) and (Manufacturer.find('system manufacturer') == -1)):
                modeling.setHostManufacturerAttribute(hostOSH, Manufacturer.strip())
            NumberOfProcessors = resultSet.getString(2)
            hostOSH.setAttribute('nt_processorsnumber', int(NumberOfProcessors))
            Model = resultSet.getString(3)
            modeling.setHostModelAttribute(hostOSH, Model)
            osDomain = resultSet.getString(4)
            hostOSH.setAttribute('host_osdomain', osDomain.strip())

        biosAssetTag = hostDiscoverer.getBiosAssetTag()
        if biosAssetTag:
            hostOSH.setAttribute('bios_asset_tag', biosAssetTag)

        _wmiQuery4 = 'SELECT SerialNumber FROM Win32_BIOS'
        resultSet = client.executeQuery(_wmiQuery4)  # @@CMD_PERMISSION wmi protocol execution
        if resultSet.next():
            serialNumber = processSerialNumber(resultSet.getString(1))
            if not serialNumber:
                wmiBaseBoardSerialNumber = 'SELECT SerialNumber FROM Win32_BaseBoard'
                resultSet = client.executeQuery(wmiBaseBoardSerialNumber)  # @@CMD_PERMISION wmi protocol execution
                serialNumber = processSerialNumber(str(resultSet))
            modeling.setHostSerialNumberAttribute(hostOSH, serialNumber)

        try:
            paeEnabled = getPAEState(client)
            if paeEnabled and paeEnabled.lower() in ['1', 'true']:
                hostOSH.setBoolAttribute('pae_enabled', 1)
            elif paeEnabled and paeEnabled.lower() in ['0', 'false']:
                hostOSH.setBoolAttribute('pae_enabled', 0)
        except Exception, ex:
            logger.warn('Failed getting PAE state. %s' % ex)

        try:
            osArchitecture = getOsArchitecture(client)
            if osinstalltype and osinstalltype.find('64') != -1:
                osArchitecture = '64-bit'
            if osArchitecture:
                hostOSH.setStringAttribute('os_architecture', osArchitecture)
        except Exception, ex:
            logger.warn('Failed getting OS Architecture value. %s' % ex)
Beispiel #52
0
 def _reportVmInterfaces(self, vm, vmHostOsh, vector):
     for mac in vm._validMacs:
         interfaceOsh = modeling.createInterfaceOSH(mac, vmHostOsh)
         if interfaceOsh is not None:
             vector.add(interfaceOsh)
Beispiel #53
0
 def build(self, ethernetPort):
     if ethernetPort is None: raise ValueError("ethernetPort is None")
     pnicOsh = modeling.createInterfaceOSH(ethernetPort.permanentAddress,
                                           hostOSH=None,
                                           name=ethernetPort.name)
     return pnicOsh
Beispiel #54
0
 def build(self, virtualInterface):
     if not virtualInterface: raise ValueError("virtual interface is None")
     if not virtualInterface.getMac(): raise ValueError("virtual interface has not MAC")
     return modeling.createInterfaceOSH(virtualInterface.getMac())
 def build_vif(self, vif):
     return modeling.createInterfaceOSH(vif.getMAC())
Beispiel #56
0
 def build(self, switch):
     if not switch: raise ValueError("switch is None")
     return modeling.createInterfaceOSH(None, name = switch.backingInterfaceName)
Beispiel #57
0
 def _reportVmInterfaces(self, vm, vmHostOsh, vector):
     for mac in vm._validMacs:
         interfaceOsh = modeling.createInterfaceOSH(mac, vmHostOsh)
         if interfaceOsh is not None:
             vector.add(interfaceOsh)