def getMachinesByDict(self, table, params): ctx = self.currentContext return xmlrpcCleanup( map( lambda m: ComputerLocationManager(). doesUserHaveAccessToMachine(ctx.userid, m[0]), Inventory().getMachinesByDict(ctx, table, params)))
def activate(): logger = logging.getLogger() config = InventoryConfig() config.init("inventory") logger.debug("Inventory %s" % str(config.disable)) if config.disable: logger.warning("Plugin inventory: disabled by configuration.") return False # When this module is used by the MMC agent, the global inventory variable is shared. # This means an Inventory instance is not created each time a XML-RPC call is done. if not InventoryLocation().init( config ): # does Inventory().activate() (which does the Inventory().db_check()) return False logger.info("Plugin inventory: Inventory database version is %d" % Inventory().dbversion) ComputerManager().register("inventory", InventoryComputers) ProvisioningManager().register('inventory', InventoryProvisioner) ComputerLocationManager().register('inventory', InventoryLocation) PossibleQueries().init(config) # Register the panel to the DashboardManager try: from mmc.plugins.dashboard.manager import DashboardManager from mmc.plugins.inventory.panel import InventoryPanel DM = DashboardManager() DM.register_panel(InventoryPanel("inventory")) except ImportError: pass return True
def inventoryExists(self, uuid): ctx = self.currentContext if uuid == '': return False # if not ComputerLocationManager().doesUserHaveAccessToMachine(ctx.userid, uuid): # return False return xmlrpcCleanup(Inventory().inventoryExists(ctx, uuid))
def doProvisioning(self, authtoken): userentry = authtoken.getInfos()[1] uid = authtoken.getLogin() if self.config.profileAttr and self.config.profilesEntity: try: profile = userentry[self.config.profileAttr][0].lower() except KeyError: self.logger.info("No profile information for user '%s' in attribute %s" % (uid, self.config.profileAttr)) profile = '' profile = profile.strip() try: entities = self.config.profilesEntity[profile].split() except KeyError: if self.config.profilesEntity.has_key("default"): entities = self.config.profilesEntity["default"].split() self.logger.info("Set the default profile to user.") profile = 'default' else: self.logger.info("No entity defined in configuration file for profile '%s'" % profile) self.logger.info("Setting user's entity to empty") entities = [] if profile and entities: tmp = [] for entity in entities: if entity.startswith('%') and entity.endswith('%'): attr = entity.strip('%') if attr in userentry: tmp.extend(userentry[attr]) else: self.logger.info("The user '%s' doesn't have an attribute '%s'" % (uid, attr)) elif entity.startswith('plugin:'): plugin = entity.replace('plugin:', '') searchpath = os.path.join(os.path.dirname(__file__), 'provisioning_plugins') try: f, p, d = imp.find_module(plugin, [searchpath]) mod = imp.load_module(plugin, f, p, d) klass = mod.PluginEntities found = klass().get(authtoken) if found: self.logger.info("Plugin '%s' found these entities: %s" % (plugin, found)) else: self.logger.info("Plugin '%s' found no matching entity" % plugin) tmp.extend(found) except ImportError: self.logger.error("The plugin '%s' can't be imported" % plugin) except Exception, e: self.logger.error("Error while using the plugin '%s'" % plugin) self.logger.exception(e) else: tmp.append(entity) entities = tmp[:] self.logger.info("Setting user '%s' entities corresponding to user profile '%s': %s" % (uid, profile, str(entities))) Inventory().setUserEntities(uid, entities)
def getLicensesCount(vendor, software, version): ctx = SecurityContext() ctx.userid = "root" def replace_splat(param): if '*' in param: return param.replace('*', '%') return param def check_param(param): if param == '' or param == '*' or param == '%': return None return replace_splat(param) software = check_param(software) vendor = check_param(vendor) version = check_param(version) if software is None: software = '%' return xmlrpcCleanup(Inventory().getAllSoftwaresImproved(ctx, software, vendor=vendor, version=version, count=1))
def validate(self): Inventory() return True
class InventoryComputers(ComputerI): def __init__(self, conffile = None): self.logger = logging.getLogger() self.config = InventoryConfig() self.inventory = Inventory() def getComputer(self, ctx, filt = None, empty_macs=False): ret = self.inventory.getMachinesOnly(ctx, filt) if type(ret) == list and len(ret) == 1: return ret[0].toDN(ctx, True) else: return {} def getMachineMac(self, ctx, filt): # TODO : need to sort! """ @return: dict of computer with their MAC addresses {'UUID1', ['MAC1', 'MAC2'], 'UUID2': ['MAC1']} """ machines = self.inventory.getMachineNetwork(ctx, filt) ret = {} for m in machines: ret[m[2]] = [] for net in m[1]: ret[m[2]].append(net['MACAddress']) return ret def getMachineIp(self, ctx, filt): # TODO : need to sort! machines = self.inventory.getMachineNetwork(ctx, filt) ret = [] for m in machines: ret.append(map(lambda i: i['IP'], m[1])) if len(ret) == 1: return ret[0] return ret def getMachineHostname(self, ctx, filt = None): machines = self.inventory.getMachinesOnly(ctx, filt) ret = [] for m in machines: ret.append(m.toH()) if len(ret) == 1: return ret[0] return ret def getComputersNetwork(self, ctx, filt): computers = self.inventory.getMachinesNetworkSorted(ctx, filt) ret = [] for item in computers: tmp = [False, {'cn' : [item[0]], 'objectUUID':[item[2]]}] if not len(item[1]): tmp[1]['ipHostNumber'] = '' tmp[1]['macAddress'] = '' tmp[1]['subnetMask'] = '' tmp[1]['networkUuids'] = '' else: tmp[1]['ipHostNumber'] = item[1]['IP'] tmp[1]['macAddress'] = item[1]['MACAddress'] tmp[1]['subnetMask'] = item[1]['SubnetMask'] tmp[1]['networkUuids'] = item[1]['networkUuids'] ret.append(tmp) return ret def getComputersList(self, ctx, filt = None): return self.getRestrictedComputersList(ctx, 0, -1, filt) def __restrictLocationsOnImagingServerOrEntity(self, filt, ctx): if filt.has_key('imaging_server') and filt['imaging_server'] != '': # Get main imaging entity uuid self.logger.debug('Get main imaging entity UUID of imaging server %s' % filt['imaging_server']) main_imaging_entity_uuid = ComputerImagingManager().getImagingServerEntityUUID(filt['imaging_server']) if main_imaging_entity_uuid != None: self.logger.debug('Found: %s' % main_imaging_entity_uuid) filt['imaging_entities'] = [main_imaging_entity_uuid] self.logger.debug('Get now children entities of this main imaging entity') # Get childs entities of this main_imaging_entity_uuid # Search only in user context for loc in self.inventory.getUserLocations(ctx.userid): if ComputerImagingManager().isChildOfImagingServer(loc.uuid, main_imaging_entity_uuid): self.logger.debug('Found %s as child entity of %s' % (loc.uuid, main_imaging_entity_uuid)) filt['imaging_entities'].append(loc.uuid) else: self.logger.warn("can't get the entity that correspond to the imaging server %s"%(filt['imaging_server'])) return [False] if 'imaging_entities' in filt: grep_entity = [] for l in ctx.locations: if l.uuid in filt['imaging_entities']: grep_entity.append(l) if grep_entity: filt['ctxlocation'] = grep_entity else: self.logger.warn("the user '%s' try to filter on an entity he shouldn't access '%s'"%(ctx.userid, filt['entity_uuid'])) return [False] return [True, filt] def getRestrictedComputersListLen(self, ctx, filt = {}): if filt == '': filt = {} filt = self.__restrictLocationsOnImagingServerOrEntity(filt, ctx) if not filt[0]: return 0 filt = filt[1] return self.inventory.countMachinesOnly(ctx, filt) def getRestrictedComputersList(self, ctx, min = 0, max = -1, filt = {}, advanced = True, justId = False, toH = False): if filt == '': filt = {} filt = self.__restrictLocationsOnImagingServerOrEntity(filt, ctx) if not filt[0]: return {} filt = filt[1] filt['min'] = min filt['max'] = max if 'imaging_entities' in filt: # imaging group creation machines_uuids = map(lambda m:m.uuid(), self.inventory.getMachinesOnly(ctx, filt)) # display only "imaging compliant" computers uuids = [] networks = self.getComputersNetwork(ctx, {'uuids': machines_uuids}) for network in networks: network = network[1] # Check if computer has macAddress and ipHostNumber if network['macAddress'] and network['ipHostNumber']: uuids.append(network['objectUUID'][0]) else: logging.getLogger().debug("Computer %s cannot be added in an imaging group:" % network['cn']) if not network['macAddress']: logging.getLogger().debug("No MAC found !") if not network['ipHostNumber']: logging.getLogger().debug("No IP address found !") filt['uuids'] = uuids if justId: return map(lambda m:m.uuid(), self.inventory.getMachinesOnly(ctx, filt)) elif toH: return map(lambda m:m.toH(), self.inventory.getMachinesOnly(ctx, filt)) else: if filt.has_key('get'): return map(lambda m:m.toCustom(filt['get']), self.inventory.getMachinesOnly(ctx, filt)) else: return self.inventory.getComputersOptimized(ctx, filt) def getTotalComputerCount(self): return self.inventory.getTotalComputerCount() def getComputerCount(self, ctx, filt = None): return self.getRestrictedComputersListLen(ctx, filt) def canAddComputer(self): return self.inventory.canAddMachine() def canAssociateComputer2Location(self): return True def addComputer(self, ctx, params): name = params["computername"] comment = params["computerdescription"].encode("utf-8") ip = params['computerip'] mac = params['computermac'] net = params['computernet'] location = None if params.has_key('location_uuid'): location = params['location_uuid'] ret = self.inventory.addMachine(name, ip, mac, net, comment, location) return ret def neededParamsAddComputer(self): return [ ['computerip', 'string', 'Computer\'s IP address'], ['computermac', 'string', 'Computer\'s MAC address'], ['computernet', 'string', 'Computer\'s netmask address'] ] def checkComputerName(self, name): return pulse2.utils.checkComputerName(name) def isComputerNameAvailable(self, ctx, locationUUID, name): return self.inventory.isComputerNameAvailable(ctx, locationUUID, name) def canDelComputer(self): return True def delComputer(self, ctx, uuid, backup): return self.inventory.delMachine(uuid) def editComputerName(self, ctx, uuid, name): """ Edit the computer name @param ctx: the context @type: currentContext @param uuid: the machine uuid @type: str @param name: new computer name @type: str @returns: True if the name changed @type: bool """ return self.inventory.editMachineName(uuid, name) def getComputerByMac(self, mac): ret = self.inventory.getMachinesBy(None, 'Network', 'MACAddress', mac, False) if type(ret) == list: if len(ret) != 0: return ret[0] else: return None return ret def getComputersOS(self, uuids): return self.inventory.getComputersOS(uuids) def getComputersListHeaders(self, ctx): """ Computers list header is just hostname as Computer Name and Description as Description """ return self.config.display def getComputerByHostnameAndMacs(self, ctx, hostname, macs): """ Get machine who match given hostname and at least one of macs @param ctx: context @type ctx: dict @param hostname: hostname of wanted machine @type hostname: str @param macs: list of macs @type macs: list @return: UUID of wanted machine or False @rtype: str or None """ return self.inventory.getMachineByHostnameAndMacs(ctx, hostname, macs)
def getContext(self): s = SecurityContext() s.userid = self.userid s.locations = Inventory().getUserLocations(s.userid) s.locationsid = map(lambda e: e.id, s.locations) return s
def getMachinesBy(table, field, value): # TODO : ctx is missing....Inventory ctx = None return Inventory().getMachinesBy(ctx, table, field, value)
def countInventoryHistory(days, only_new, pattern): return Inventory().countInventoryHistory(days, only_new, pattern)
def countMachineInventoryHistory(self, params): ctx = self.currentContext return Inventory().countComputerInventoryHistory(ctx, params)
def getValuesFuzzy(table, field, fuzzy_value): return Inventory().getValuesFuzzy(table, field, fuzzy_value)
def getLastMachineInventoryFull(self, params): ctx = self.currentContext # if not ComputerLocationManager().doesUserHaveAccessToMachine(ctx.userid, uuid): # return False return xmlrpcCleanup(Inventory().getLastMachineInventoryFull( ctx, params))
def getMachineInventoryHistory(self, params): ctx = self.currentContext return xmlrpcCleanup(Inventory().getComputerInventoryHistory( ctx, params))
def getLastMachineInventoryPart2(self, part, params): ctx = self.currentContext # uuid = name # TODO : get uuid from name, or something like that... # ComputerLocationManager().doesUserHaveAccessToMachine(ctx.userid, uuid) return xmlrpcCleanup(Inventory().getLastMachineInventoryPart2( ctx, part, params))
def countLastMachineInventoryPart(self, part, params): ctx = self.currentContext return xmlrpcCleanup(Inventory().countLastMachineInventoryPart( ctx, part, params))
def getUUIDByMachineName(self, name): ctx = self.currentContext return xmlrpcCleanup(Inventory().getUUIDByMachineName(ctx, name))
class InventoryComputers(ComputerI): def __init__(self, conffile = None): self.logger = logging.getLogger() self.config = InventoryConfig() self.inventory = Inventory() def getComputer(self, ctx, filt = None): ret = self.inventory.getMachinesOnly(ctx, filt) if type(ret) == list and len(ret) == 1: return ret[0].toDN(ctx, True) else: return {} def getMachineMac(self, ctx, filt): # TODO : need to sort! """ @return: dict of computer with their MAC addresses {'UUID1', ['MAC1', 'MAC2'], 'UUID2': ['MAC1']} """ machines = self.inventory.getMachineNetwork(ctx, filt) ret = {} for m in machines: ret[m[2]] = [] for net in m[1]: ret[m[2]].append(net['MACAddress']) return ret def getMachineIp(self, ctx, filt): # TODO : need to sort! machines = self.inventory.getMachineNetwork(ctx, filt) ret = [] for m in machines: ret.append(map(lambda i: i['IP'], m[1])) if len(ret) == 1: return ret[0] return ret def getMachineHostname(self, ctx, filt = None): machines = self.inventory.getMachinesOnly(ctx, filt) ret = [] for m in machines: ret.append(m.toH()) if len(ret) == 1: return ret[0] return ret def getComputersNetwork(self, ctx, filt): computers = self.inventory.getMachinesNetworkSorted(ctx, filt) ret = [] for item in computers: tmp = [False, {'cn' : [item[0]], 'objectUUID':[item[2]]}] if not len(item[1]): tmp[1]['ipHostNumber'] = '' tmp[1]['macAddress'] = '' tmp[1]['subnetMask'] = '' tmp[1]['networkUuids'] = '' else: tmp[1]['ipHostNumber'] = item[1]['IP'] tmp[1]['macAddress'] = item[1]['MACAddress'] tmp[1]['subnetMask'] = item[1]['SubnetMask'] tmp[1]['networkUuids'] = item[1]['networkUuids'] ret.append(tmp) return ret def getComputersList(self, ctx, filt = None): return self.getRestrictedComputersList(ctx, 0, -1, filt) def __restrictLocationsOnImagingServerOrEntity(self, filt, ctx): if filt.has_key('imaging_server') and filt['imaging_server'] != '': entity_uuid = ComputerImagingManager().getImagingServerEntityUUID(filt['imaging_server']) if entity_uuid != None: filt['location'] = entity_uuid else: self.logger.warn("can't get the entity that correspond to the imaging server %s"%(filt['imaging_server'])) return [False] if filt.has_key('entity_uuid') and filt['entity_uuid'] != '': grep_entity = None for l in ctx.locations: if l.uuid == filt['entity_uuid']: grep_entity = l if grep_entity != None: filt['location'] = [grep_entity] else: self.logger.warn("the user '%s' try to filter on an entity he shouldn't access '%s'"%(ctx.userid, filt['entity_uuid'])) return [False] return [True, filt] def getRestrictedComputersListLen(self, ctx, filt = {}): if filt == '': filt = {} filt = self.__restrictLocationsOnImagingServerOrEntity(filt, ctx) if not filt[0]: return 0 filt = filt[1] return self.inventory.countMachinesOnly(ctx, filt) def getRestrictedComputersList(self, ctx, min = 0, max = -1, filt = {}, advanced = True, justId = False, toH = False): if filt == '': filt = {} filt = self.__restrictLocationsOnImagingServerOrEntity(filt, ctx) if not filt[0]: return {} filt = filt[1] filt['min'] = min filt['max'] = max if justId: return map(lambda m:m.uuid(), self.inventory.getMachinesOnly(ctx, filt)) elif toH: return map(lambda m:m.toH(), self.inventory.getMachinesOnly(ctx, filt)) else: if filt.has_key('get'): return map(lambda m:m.toCustom(filt['get']), self.inventory.getMachinesOnly(ctx, filt)) else: return self.inventory.getComputersOptimized(ctx, filt) def getTotalComputerCount(self): return self.inventory.getTotalComputerCount() def getComputerCount(self, ctx, filt = None): return self.getRestrictedComputersListLen(ctx, filt) def canAddComputer(self): return True def canAssociateComputer2Location(self): return True def addComputer(self, ctx, params): name = params["computername"] comment = params["computerdescription"].encode("utf-8") ip = params['computerip'] mac = params['computermac'] net = params['computernet'] location = None if params.has_key('location_uuid'): location = params['location_uuid'] ret = self.inventory.addMachine(name, ip, mac, net, comment, location) return ret def neededParamsAddComputer(self): return [ ['computerip', 'string', 'Computer\'s IP address'], ['computermac', 'string', 'Computer\'s MAC address'], ['computernet', 'string', 'Computer\'s netmask address'] ] def checkComputerName(self, name): return pulse2.utils.checkComputerName(name) def isComputerNameAvailable(self, ctx, locationUUID, name): return self.inventory.isComputerNameAvailable(ctx, locationUUID, name) def canDelComputer(self): return True def delComputer(self, ctx, uuid, backup): return self.inventory.delMachine(uuid) def getComputerByMac(self, mac): ret = self.inventory.getMachinesBy(None, 'Network', 'MACAddress', mac, False) if type(ret) == list: if len(ret) != 0: return ret[0] else: return None return ret def getComputersListHeaders(self, ctx): """ Computers list header is just hostname as Computer Name and Description as Description """ return self.config.display
def getMachineInventoryDiff(self, params): ctx = self.currentContext # Use xmlrpcCleanup to clean all None values return xmlrpcCleanup(Inventory().getComputerInventoryDiff(ctx, params))
def getValuesWhere(table, field1, value1, field2): return Inventory().getValuesWhere(table, field1, value1, field2)
def getMachineNumberByState(self): ctx = self.currentContext return xmlrpcCleanup(Inventory().getMachineNumberByState(ctx))
def getValueFuzzyWhere(table, field1, value1, field2, fuzzy_value): return Inventory().getValueFuzzyWhere(table, field1, value1, field2, fuzzy_value)
def getMachineListByState(self, groupName): ctx = self.currentContext return xmlrpcCleanup(Inventory().getMachineListByState(ctx, groupName))
def getInventoryHistory(days, only_new, pattern, max, min): # Use xmlrpcCleanup to clean the date values return xmlrpcCleanup(Inventory().getInventoryHistory( days, only_new, pattern, max, min))
def getMachineByHostnameAndMacs(self, hostname, macs): ctx = self.currentContext return xmlrpcCleanup(Inventory().getMachineByHostnameAndMacs( ctx, hostname, macs))
def getTypeOfAttribute(klass, attr): return Inventory().getTypeOfAttribute(klass, attr)
def getMachines(self, pattern=None): ctx = self.currentContext return xmlrpcCleanup(Inventory().getMachines(ctx, pattern))
def doProvisioning(self, authtoken): from mmc.plugins.base import ldapUserGroupControl self.logger.debug(str(authtoken.getInfos())) l = ldapUserGroupControl() userentry = authtoken.getInfos()[1] uid = userentry[self.config.ldap_uid][0] if l.existUser(uid): self.logger.debug("User %s already exists, so this user won't be added" % uid) else: givenName = userentry[self.config.ldap_givenName][0].decode("utf-8") sn = userentry[self.config.ldap_sn][0].decode("utf-8") l.addUser(uid, authtoken.getPassword(), givenName, sn) if self.config.profileAttr and self.config.profilesAcl: # Set or update the user right try: profile = userentry[self.config.profileAttr][0].lower() except KeyError: self.logger.info("No profile information for user %s in attribute %s" % (uid, self.config.profileAttr)) profile = "" profile = profile.strip() try: entities = self.config.profilesEntity[profile].split() self.logger.info("*******ENTITE '%s' " % (entities)) except KeyError: if self.config.profilesEntity.has_key("default"): entities = self.config.profilesEntity["default"].split() self.logger.info("Set the default profile to user.") profile = 'default' else: self.logger.info("No entity defined in configuration file for profile '%s'" % profile) self.logger.info("Setting user's entity to empty") entities = [] if profile and entities: tmp = [] for entity in entities: if entity.startswith('%') and entity.endswith('%'): attr = entity.strip('%') if attr in userentry: tmp.extend(userentry[attr]) else: self.logger.info("The user '%s' doesn't have an attribute '%s'" % (uid, attr)) elif entity.startswith('plugin:'): plugin = entity.replace('plugin:', '') searchpath = os.path.join(os.path.dirname(__file__), 'provisioning_plugins') try: f, p, d = imp.find_module(plugin, [searchpath]) mod = imp.load_module(plugin, f, p, d) klass = mod.PluginEntities found = klass().get(authtoken) if found: self.logger.info("Plugin '%s' found these entities: %s" % (plugin, found)) else: self.logger.info("Plugin '%s' found no matching entity" % plugin) tmp.extend(found) except ImportError: self.logger.error("The plugin '%s' can't be imported" % plugin) except Exception, e: self.logger.error("Error while using the plugin '%s'" % plugin) self.logger.exception(e) else: tmp.append(entity) entities = tmp[:] self.logger.info("****Setting user '%s' entities corresponding to user profile '%s': %s" % (uid, profile, str(entities))) from pulse2.database.inventory import Inventory Inventory().setUserEntities(uid, entities) try: acls = self.config.profilesAcl[profile] except KeyError: self.logger.info("No ACL defined in configuration file for profile '%s'" % profile) self.logger.info("Setting ACL to empty") acls = None if profile and acls: self.logger.info("Setting MMC ACL corresponding to user profile %s: %s" % (profile, str(acls))) entry = l.getDetailedUser(uid) if not "lmcUserObject" in entry["objectClass"]: entry["objectClass"].append("lmcUserObject") l.changeUserAttributes(uid, "objectClass", entry["objectClass"]) l.changeUserAttributes(uid, "lmcAcl", acls) if self.config.profileGroupMapping: # Set user group membership according to mapping for prof in self.config.profilesAcl: groupname = self.config.profileGroupPrefix + prof if prof != profile: # Delete the user from a group not belonging to her/his # profile try: l.delUserFromGroup(groupname, uid) self.logger.debug('Deleting user %s from group %s' % (uid, groupname)) except ldap.NO_SUCH_OBJECT: # The group does not exist pass else: # Add the user to this group try: l.addGroup(groupname) except ldap.ALREADY_EXISTS: # This group already exists pass self.logger.debug('Adding user %s to group %s' % (uid, groupname)) l.addUserToGroup(groupname, uid)
def __init__(self): self.db = Inventory() self.ctx = SecurityContext() self.ctx.userid = "root"
def getMachineByOwner(self, user): ctx = self.currentContext return xmlrpcCleanup(Inventory().getMachineByOwner(ctx, user))
class InventoryComputers(ComputerI): def __init__(self, conffile = None): self.logger = logging.getLogger() self.config = InventoryConfig() self.inventory = Inventory() def getComputer(self, ctx, filt = None, empty_macs=False): ret = self.inventory.getMachinesOnly(ctx, filt) if type(ret) == list and len(ret) == 1: return ret[0].toDN(ctx, True) else: return {} def getMachineMac(self, ctx, filt): # TODO : need to sort! """ @return: dict of computer with their MAC addresses {'UUID1', ['MAC1', 'MAC2'], 'UUID2': ['MAC1']} """ machines = self.inventory.getMachineNetwork(ctx, filt) ret = {} for m in machines: ret[m[2]] = [] for net in m[1]: ret[m[2]].append(net['MACAddress']) return ret def getMachineIp(self, ctx, filt): # TODO : need to sort! machines = self.inventory.getMachineNetwork(ctx, filt) ret = [] for m in machines: ret.append(map(lambda i: i['IP'], m[1])) if len(ret) == 1: return ret[0] return ret def getMachineHostname(self, ctx, filt = None): machines = self.inventory.getMachinesOnly(ctx, filt) ret = [] for m in machines: ret.append(m.toH()) if len(ret) == 1: return ret[0] return ret def getComputersNetwork(self, ctx, filt): computers = self.inventory.getMachinesNetworkSorted(ctx, filt) ret = [] for item in computers: tmp = [False, {'cn' : [item[0]], 'objectUUID':[item[2]]}] #if not item[1]: if not len(item[1]): tmp[1]['ipHostNumber'] = '' tmp[1]['macAddress'] = '' tmp[1]['subnetMask'] = '' tmp[1]['networkUuids'] = '' else: tmp[1]['ipHostNumber'] = item[1]['IP'] tmp[1]['macAddress'] = item[1]['MACAddress'] tmp[1]['subnetMask'] = item[1]['SubnetMask'] tmp[1]['networkUuids'] = item[1]['networkUuids'] ret.append(tmp) return ret def getComputersList(self, ctx, filt = None): return self.getRestrictedComputersList(ctx, 0, -1, filt) def __restrictLocationsOnImagingServerOrEntity(self, filt, ctx): if 'imaging_server' in filt and filt['imaging_server'] != '': # Get main imaging entity uuid self.logger.debug('Get main imaging entity UUID of imaging server %s' % filt['imaging_server']) main_imaging_entity_uuid = ComputerImagingManager().getImagingServerEntityUUID(filt['imaging_server']) if main_imaging_entity_uuid != None: self.logger.debug('Found: %s' % main_imaging_entity_uuid) filt['imaging_entities'] = [main_imaging_entity_uuid] self.logger.debug('Get now children entities of this main imaging entity') # Get childs entities of this main_imaging_entity_uuid # Search only in user context for loc in self.inventory.getUserLocations(ctx.userid): if ComputerImagingManager().isChildOfImagingServer(loc.uuid, main_imaging_entity_uuid): self.logger.debug('Found %s as child entity of %s' % (loc.uuid, main_imaging_entity_uuid)) filt['imaging_entities'].append(loc.uuid) else: self.logger.warn("can't get the entity that correspond to the imaging server %s"%(filt['imaging_server'])) return [False] if 'imaging_entities' in filt: grep_entity = [] for l in ctx.locations: if l.uuid in filt['imaging_entities']: grep_entity.append(l) if grep_entity: filt['ctxlocation'] = grep_entity else: self.logger.warn("the user '%s' try to filter on an entity he shouldn't access '%s'"%(ctx.userid, filt['entity_uuid'])) return [False] return [True, filt] def getRestrictedComputersListLen(self, ctx, filt = {}): if filt == '' or filt is None: filt = {} filt = self.__restrictLocationsOnImagingServerOrEntity(filt, ctx) if not filt[0]: return 0 filt = filt[1] return self.inventory.countMachinesOnly(ctx, filt) def getRestrictedComputersList(self, ctx, min = 0, max = -1, filt = {}, advanced = True, justId = False, toH = False): if filt == '' or filt is None: filt = {} filt = self.__restrictLocationsOnImagingServerOrEntity(filt, ctx) if not filt[0]: return {} filt = filt[1] filt['min'] = min filt['max'] = max if 'imaging_entities' in filt: # imaging group creation machines_uuids = map(lambda m:m.uuid(), self.inventory.getMachinesOnly(ctx, filt)) # display only "imaging compliant" computers uuids = [] networks = self.getComputersNetwork(ctx, {'uuids': machines_uuids}) for network in networks: network = network[1] # Check if computer has macAddress and ipHostNumber if network['macAddress'] and network['ipHostNumber']: uuids.append(network['objectUUID'][0]) else: logging.getLogger().debug("Computer %s cannot be added in an imaging group:" % network['cn']) if not network['macAddress']: logging.getLogger().debug("No MAC found !") if not network['ipHostNumber']: logging.getLogger().debug("No IP address found !") filt['uuids'] = uuids if justId: return map(lambda m:m.uuid(), self.inventory.getMachinesOnly(ctx, filt)) elif toH: return map(lambda m:m.toH(), self.inventory.getMachinesOnly(ctx, filt)) else: if 'get' in filt: return map(lambda m:m.toCustom(filt['get']), self.inventory.getMachinesOnly(ctx, filt)) else: return self.inventory.getComputersOptimized(ctx, filt) def getTotalComputerCount(self): return self.inventory.getTotalComputerCount() def getComputerCount(self, ctx, filt = None): return self.getRestrictedComputersListLen(ctx, filt) def canAddComputer(self): return self.inventory.canAddMachine() def canAssociateComputer2Location(self): return True def addComputer(self, ctx, params): name = params["computername"] comment = params["computerdescription"].encode("utf-8") ip = params['computerip'] mac = params['computermac'] net = params['computernet'] location = None if 'location_uuid' in params: location = params['location_uuid'] ret = self.inventory.addMachine(name, ip, mac, net, comment, location) return ret def neededParamsAddComputer(self): return [ ['computerip', 'string', 'Computer\'s IP address'], ['computermac', 'string', 'Computer\'s MAC address'], ['computernet', 'string', 'Computer\'s netmask address'] ] def checkComputerName(self, name): return pulse2.utils.checkComputerName(name) def isComputerNameAvailable(self, ctx, locationUUID, name): return self.inventory.isComputerNameAvailable(ctx, locationUUID, name) def canDelComputer(self): return True def delComputer(self, ctx, uuid, backup): return self.inventory.delMachine(uuid) def editComputerName(self, ctx, uuid, name): """ Edit the computer name @param ctx: the context @type: currentContext @param uuid: the machine uuid @type: str @param name: new computer name @type: str @returns: True if the name changed @type: bool """ return self.inventory.editMachineName(uuid, name) def getComputerByMac(self, mac): ret = self.inventory.getMachinesBy(None, 'Network', 'MACAddress', mac, False) if type(ret) == list: if len(ret) != 0: return ret[0] else: return None return ret def getComputersOS(self, uuids): return self.inventory.getComputersOS(uuids) def getComputersListHeaders(self, ctx): """ Computers list header is just hostname as Computer Name and Description as Description """ return self.config.display def getComputerByHostnameAndMacs(self, ctx, hostname, macs): """ Get machine who match given hostname and at least one of macs @param ctx: context @type ctx: dict @param hostname: hostname of wanted machine @type hostname: str @param macs: list of macs @type macs: list @return: UUID of wanted machine or False @rtype: str or None """ return self.inventory.getMachineByHostnameAndMacs(ctx, hostname, macs)
def __init__(self, conffile = None): self.logger = logging.getLogger() self.config = InventoryConfig() self.inventory = Inventory()
def getValues(table, field): return Inventory().getValues(table, field)
class exportedReport(object): def __init__(self): self.db = Inventory() self.ctx = SecurityContext() self.ctx.userid = "root" def _getEntitiesIds(self, entities=[]): """ Return a list of entities ids for the request @param entitites: a list of entities uuids @return: list of entities ids """ # Be sure to get all entities self.ctx.locations = None if hasattr(self.ctx, 'locationsid'): del self.ctx.locationsid # get all entities uuids for the current user if entities == []: entities = [entity.toH()['uuid'] for entity in self.db.getAllEntities(self.ctx)] return [fromUUID(str(entity)) for entity in entities] def _getComputerCountByOSes(self, entities, os_names, results, oper=operator.add): os_results = [] if os_names: for entity in self._getEntitiesIds(entities): self.ctx.locationsid = [entity] os_count = self.db.getMachineByOsLike(self.ctx, os_names, count=1) os_results.append({'entity_id': entity, 'value': os_count}) for os_result in os_results: count = False for result in results: if os_result['entity_id'] == result['entity_id']: if result['value'] is not None and os_result['value'] is not None: result['value'] = oper(result['value'], os_result['value']) else: result['value'] = 0 count = True if not count and oper == operator.add: results.append(os_result) return results def getComputerCountByOSes(self, entities, os_names, exclude_names=[]): """ Get computer count for os_names @param os_names: list of OS names to count @param exclude_names: list of OS names to exclude @return: count of machines by entity """ if isinstance(os_names, basestring): os_names = [os_names] os_names = [os_name.replace('*', '%') for os_name in os_names] exclude_names = [exclude_name.replace('*', '%') for exclude_name in exclude_names] results = self._getComputerCountByOSes(entities, os_names, []) results = self._getComputerCountByOSes(entities, exclude_names, results, operator.sub) return results def getComputerCountByTypes(self, entities, types): """ Get computer count for types @param types: list of computer types to count @return: count of machines by entity """ if isinstance(types, basestring): types = [types] types = [type.replace("*", "%") for type in types] results = [] type_results = [] if types: for entity in self._getEntitiesIds(entities): self.ctx.locationsid = [entity] type_count = self.db.getMachineByType(self.ctx, types, count=1) type_results.append({'entity_id': entity, 'value': type_count}) for type_result in type_results: count = False for result in results: if type_result['entity_id'] == result['entity_id']: result['value'] += type_result['value'] count = True if not count: results.append(type_result) return results def getComputerCountByState(self, entities, state): result = [] state = state.replace("*", "%") for entity in self._getEntitiesIds(entities): self.ctx.locationsid = [entity] state_count = self.db.getMachineByState(self.ctx, state, count=1) result.append({'entity_id': entity, 'value': state_count}) return result def _constructSoftwareTuple(self, soft): """ @param soft: string or dict @return: software tuple: (name, version, vendor) """ name = version = vendor = None if soft and isinstance(soft, basestring): name = soft.replace('*', '%') elif type(soft) == dict: name = soft.get('name', None) if name: name = name.replace('*', '%') version = soft.get('version', None) if version: version = version.replace('*', '%') vendor = soft.get('vendor', None) if vendor: vendor = vendor.replace('*', '%') if name is None: logger.error("Missing software name") return None return (name, version, vendor) def _constructSoftwaresList(self, softs): """ @param softs: dict, string, list of mixed string and dict @return: list of software tuples [(name, version, vendor), (name, version, vendor), (name, version, vendor), ...] """ if type(softs) == list: return [self._constructSoftwareTuple(soft) for soft in softs] if softs: return [self._constructSoftwareTuple(softs)] return [] def _getComputerCountBySoftwares(self, entities, softs, results, oper=operator.add): soft_results= [] if softs: for entity in self._getEntitiesIds(entities): self.ctx.locationsid = [entity] soft_count = self.db.getAllSoftwaresImproved(self.ctx, [soft[0] for soft in softs], version=[soft[1] for soft in softs], vendor=[soft[2] for soft in softs], count=1) soft_results.append({'entity_id': entity, 'value': soft_count}) for soft_result in soft_results: count = False for result in results: if soft_result['entity_id'] == result['entity_id']: if result['value'] is not None and soft_result['value'] is not None: result['value'] = oper(result['value'], soft_result['value']) else: result['value'] = 0 count = True if not count and oper == operator.add: results.append(soft_result) return results def getComputerCountBySoftwares(self, entities, soft_names, exclude_names={}): """ Get computer count for software names @param soft_names: list of softwares to count @param exclude_names: list of softwares to exclude soft_names can be a simple string (ie: 'Mozilla Firefox*') soft_names can be a dict (ie: {'name': 'Mozilla Firefox', 'version': '24.0', vendor:'Mozilla'}) soft_names can be a list of mixed dict and strings Same for exclude_names @return: count of machines by entity """ softs = self._constructSoftwaresList(soft_names) excludes = self._constructSoftwaresList(exclude_names) results = self._getComputerCountBySoftwares(entities, softs, []) results = self._getComputerCountBySoftwares(entities, excludes, results, operator.sub) return results