Пример #1
0
    def subnet_set_dns_delegated(self, operator, identifier, force=False):
        self.ba.assert_dns_superuser(operator.get_entity_id())

        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)

        subnet_id = "%s/%s" % (s.subnet_ip, s.subnet_mask)

        if s.dns_delegated:
            return ("Subnet %s is already set as " % subnet_id +
                    "being delegated to external DNS server")

        in_use = ""
        if s.has_adresses_in_use():
            if force:
                in_use = "\nNote! Subnet has addresses in use!"
            else:
                raise CerebrumError, (
                    "Subnet '%s' has addresses " % subnet_id +
                    "in use; must force to delegate")

        s.dns_delegated = True
        s.write_db(perform_checks=False)
        return "Subnet %s set as delegated to external DNS server%s" % (
            subnet_id, in_use)
Пример #2
0
    def subnet_set_reserved(self, operator, identifier, new_res):
        self.ba.assert_dns_superuser(operator.get_entity_id())
        
        try:
            int(new_res)
        except:
            raise CerebrumError("The number of reserved addresses must be " +
                                "an integer; '%s' isn't" % new_res)

        if new_res < 0:
            raise CerebrumError("Cannot set number of reserved addresses to " +
                                "a negative number such as '%s'" % new_res)
       
        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)

        old_res = s.no_of_reserved_adr

        s.no_of_reserved_adr = int(new_res)
        s.calculate_reserved_addresses()

        in_use = ""
        if new_res > old_res:
            try:
                s.check_reserved_addresses_in_use()
            except SubnetError, se:
                in_use = "\nFYI: %s" % str(se)
 def _get_subnet_ipv4(self, subnet_identifier):
     try:
         s = Subnet(self.db)
         s.find(subnet_identifier)
         return s
     except (ValueError, SubnetError, DNSError):
         raise CerebrumError("Unable to find subnet %r" % subnet_identifier)
Пример #4
0
    def subnet_set_dns_delegated(self, operator, identifier, force=False):
        self.ba.assert_dns_superuser(operator.get_entity_id())
        
        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)

        subnet_id = "%s/%s" % (s.subnet_ip, s.subnet_mask)

        if s.dns_delegated:
            return ("Subnet %s is already set as " % subnet_id +
                    "being delegated to external DNS server")

        in_use = ""
        if s.has_adresses_in_use():
            if force:
                in_use = "\nNote! Subnet has addresses in use!"
            else:
                raise CerebrumError, ("Subnet '%s' has addresses " % subnet_id +
                                      "in use; must force to delegate")

        s.dns_delegated = True
        s.write_db(perform_checks=False)
        return "Subnet %s set as delegated to external DNS server%s" % (subnet_id, in_use)
Пример #5
0
 def in_subnet(ip):
     from Cerebrum.Utils import Factory
     from Cerebrum.modules.dns.Errors import SubnetError
     from Cerebrum.modules.dns.Subnet import Subnet
     db = Factory.get('Database')()
     sub = Subnet(db)
     try:
         sub.find(ip)
     except SubnetError:
         return False
     return True
Пример #6
0
    def subnet_set_name_prefix(self, operator, identifier, new_prefix):
        self.ba.assert_dns_superuser(operator.get_entity_id())

        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)

        old_prefix = s.name_prefix
        s.name_prefix = new_prefix
        s.write_db(perform_checks=False)
        subnet_id = "%s/%s" % (s.subnet_ip, s.subnet_mask)
        return ("OK; name_prefix for subnet %s updated " % subnet_id +
                "from '%s' to '%s'" % (old_prefix, new_prefix))
Пример #7
0
    def subnet_set_description(self, operator, identifier, new_description):
        raise CerebrumError(
            'Description updates are not allowed for the time beeing.')
        self.ba.assert_dns_superuser(operator.get_entity_id())

        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)

        s.description = new_description
        s.write_db(perform_checks=False)
        subnet_id = "%s/%s" % (s.subnet_ip, s.subnet_mask)
        return "OK; description for subnet %s updated to '%s'" % (
            subnet_id, new_description)
Пример #8
0
    def subnet_set_description(self, operator, identifier, new_description):
        raise CerebrumError('Description updates are not allowed for the time beeing.')
        self.ba.assert_dns_superuser(operator.get_entity_id())
        
        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)

        s.description = new_description
        s.write_db(perform_checks=False)
        subnet_id = "%s/%s" % (s.subnet_ip, s.subnet_mask)
        return "OK; description for subnet %s updated to '%s'" % (subnet_id, new_description)
Пример #9
0
    def subnet_unset_dns_delegated(self, operator, identifier):
        self.ba.assert_dns_superuser(operator.get_entity_id())

        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)

        subnet_id = "%s/%s" % (s.subnet_ip, s.subnet_mask)

        if not s.dns_delegated:
            return ("Subnet %s is already set as not " % subnet_id +
                    "being delegated to external DNS server")

        s.dns_delegated = False
        s.write_db(perform_checks=False)
        return "Subnet %s no longer set as delegated to external DNS server" % subnet_id
Пример #10
0
    def subnet_set_name_prefix(self, operator, identifier, new_prefix):
        self.ba.assert_dns_superuser(operator.get_entity_id())
        
        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)

        old_prefix = s.name_prefix
        s.name_prefix = new_prefix
        s.write_db(perform_checks=False)
        subnet_id = "%s/%s" % (s.subnet_ip, s.subnet_mask)
        return ("OK; name_prefix for subnet %s updated " % subnet_id +
                "from '%s' to '%s'" % (old_prefix, new_prefix))
Пример #11
0
def add_subnet(subnet, description, vlan, perform_checks=True):
    """Utility method for adding a (new) subnet based on the
    information given.

    If errors occur during the addition, Cerebrum- and/or
    Subnet-errors will be raised.

    TODO: parameter doc.
    """
    s = Subnet(db)
    s.clear()
    s.populate(subnet, description, vlan=vlan)
    try:
        s.write_db(perform_checks=perform_checks)
    except db.DatabaseError as m:
        raise CerebrumError("Database error: %s" % m)
Пример #12
0
    def subnet_set_vlan(self, operator, identifier, new_vlan):
        self.ba.assert_dns_superuser(operator.get_entity_id())
        try:
            int(new_vlan)
        except:
            raise CerebrumError("VLAN must be an integer; '%s' isn't" %
                                new_vlan)

        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)
        old_vlan = s.vlan_number
        s.vlan_number = new_vlan
        s.write_db(perform_checks=False)
        subnet_id = "%s/%s" % (s.subnet_ip, s.subnet_mask)
        return "OK; VLAN for subnet %s updated from '%s' to '%s'" % (
            subnet_id, old_vlan, new_vlan)
Пример #13
0
    def same_subnet(s1, s2):
        from Cerebrum.Utils import Factory
        from Cerebrum.modules.dns.Errors import SubnetError
        from Cerebrum.modules.dns.Subnet import Subnet
        db = Factory.get('Database')()
        sub = Subnet(db)
        try:
            sub.find(s1)
            tmp = sub.subnet_ip
            sub.clear()
            sub.find(s2)
        except SubnetError:
            return False

        if tmp == sub.subnet_ip:
            return True
        else:
            return False
Пример #14
0
    def subnet_set_vlan(self, operator, identifier, new_vlan):
        self.ba.assert_dns_superuser(operator.get_entity_id())
        try:
            int(new_vlan)
        except:
            raise CerebrumError("VLAN must be an integer; '%s' isn't" % new_vlan)

        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)
        old_vlan = s.vlan_number
        s.vlan_number = new_vlan
        s.write_db(perform_checks=False)
        subnet_id = "%s/%s" % (s.subnet_ip, s.subnet_mask)
        return "OK; VLAN for subnet %s updated from '%s' to '%s'" % (subnet_id, old_vlan, new_vlan)
Пример #15
0
    def subnet_unset_dns_delegated(self, operator, identifier):
        self.ba.assert_dns_superuser(operator.get_entity_id())
        
        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)

        subnet_id = "%s/%s" % (s.subnet_ip, s.subnet_mask)

        if not s.dns_delegated:
            return ("Subnet %s is already set as not " % subnet_id +
                    "being delegated to external DNS server" )

        s.dns_delegated = False
        s.write_db(perform_checks=False)
        return "Subnet %s no longer set as delegated to external DNS server" % subnet_id
Пример #16
0
def add_subnet(subnet, description, vlan, perform_checks=True):
    """Utility method for adding a (new) subnet based on the
    information given.

    If errors occur during the addition, Cerebrum- and/or
    Subnet-errors will be raised.

    TODO: parameter doc.
    """
    s = Subnet(db)
    s.clear()
    s.populate(subnet, description, vlan=vlan)
    try:
        s.write_db(perform_checks=perform_checks)
    except db.DatabaseError as m:
        raise CerebrumError("Database error: %s" % m)
Пример #17
0
def write_subnet_ldif():
    DN = ldapconf('SUBNETS', 'dn')
    startAttr, endAttr, objectClasses = ldapconf('SUBNETS', 'rangeSchema')
    objectClasses = ('top', 'ipNetwork') + tuple(objectClasses)
    db = Factory.get('Database')()
    f = ldif_outfile('SUBNETS')
    f.write(container_entry_string('SUBNETS'))
    for row in Subnet(db).search():
        cn = "%s/%s" % (row['subnet_ip'], row['subnet_mask'])
        desc = row['description']
        f.write(
            entry_string(
                "cn=%s,%s" % (cn, DN), {
                    'objectClass': objectClasses,
                    'description': (desc and (iso2utf(desc), ) or ()),
                    'ipNetworkNumber': (row['subnet_ip'], ),
                    'ipNetmaskNumber': (netmask_to_ip(row['subnet_mask']), ),
                    startAttr: (str(int(row['ip_min'])), ),
                    endAttr: (str(int(row['ip_max'])), )
                }))
    end_ldif_outfile('SUBNETS', f)
Пример #18
0
def compare_file_to_db(subnets_in_file, force):
    """Analyzes the info obtained from the files that are to be
    imported, compares to content of database and makes changes were
    needed to bring the database in sync with the datafile.

    TODO: parameter doc.
    
    """
    errors = []
    changes = []
    perform_checks = not force
        
    s = Subnet(db)
    subnets_in_db = s.search()
    
    for row in subnets_in_db:
        subnet_ID = "%s/%s" % (row['subnet_ip'], row['subnet_mask'])

        if subnet_ID in subnets_in_file:
            # Subnet is in file; nothing should be done with it
            if row['description'] != subnets_in_file[subnet_ID][1]:
                s.clear()
                s.find(row['entity_id'])
                s.description = subnets_in_file[subnet_ID][1]
                s.write_db(perform_checks=False)
                logger.debug("Updating description of subnet '%s'" % subnet_ID)
                changes.append("Updated description of subnet '%s'" %subnet_ID)
            else:
                logger.debug("Subnet '%s' in both DB and file; " % subnet_ID +
                                "no description update")
            del subnets_in_file[subnet_ID]
        else:
            # Subnet is in DB, but not in file; try to remove it from DB
            try:
                logger.info("Deleting subnet '%s'" % subnet_ID)
                s.clear()
                s.find(subnet_ID)
                description = s.description
                s.delete(perform_checks=perform_checks)
                changes.append("Deleted subnet '%s' (%s)" % (subnet_ID,
                                                                description))
            except CerebrumError, ce:
                logger.error(str(ce))
                errors.append(str(ce))
Пример #19
0
def compare_file_to_db(subnets_in_file, force):
    """Analyzes the info obtained from the files that are to be
    imported, compares to content of database and makes changes were
    needed to bring the database in sync with the datafile.

    TODO: parameter doc.
    """
    errors = []
    changes = []
    perform_checks = not force
    s = Subnet(db)
    subnets_in_db = s.search()
    for row in subnets_in_db:
        subnet = "%s/%s" % (row['subnet_ip'], row['subnet_mask'])

        if subnet in subnets_in_file:
            (description, vlan) = subnets_in_file[subnet]
            # Subnet is in file. Check if description or vlan have changed
            if row['description'] != description:
                s.clear()
                s.find(row['entity_id'])
                s.description = description
                s.write_db(perform_checks=False)
                logger.debug("Updating description of subnet '%s'" % subnet)
                changes.append("Updated description of subnet '%s'" % subnet)
            else:
                logger.debug("Subnet '%s' in both DB and file; " % subnet +
                             "no description update")
            if vlan and row['vlan_number'] != vlan:
                s.clear()
                s.find(row['entity_id'])
                s.vlan_number = vlan
                s.write_db(perform_checks=False)
                logger.debug("Updating vlan for subnet '%s'" % subnet)
                changes.append("Updated vlan for subnet '%s'" % subnet)
            else:
                logger.debug("Subnet '%s' in both DB and file; " % subnet +
                             "no vlan update")
            del subnets_in_file[subnet]
        else:
            # Subnet is in DB, but not in file; try to remove it from DB
            try:
                logger.info("Deleting subnet '%s'" % subnet)
                s.clear()
                s.find(subnet)
                description = s.description
                s.delete(perform_checks=perform_checks)
                changes.append("Deleted subnet '%s' (%s)" % (subnet,
                                                             description))
            except CerebrumError as ce:
                logger.error(str(ce))
                errors.append(str(ce))

    # What is left in subnets_in_file now are subnets that should be added
    for subnet in subnets_in_file:
        try:
            description, vlan = subnets_in_file[subnet]
            logger.info("Adding subnet '%s' (%s)" % (subnet, description))
            add_subnet(subnet, description, vlan,
                       perform_checks=perform_checks)
            changes.append("Added subnet '%s' (%s)" % (subnet, description))
        except CerebrumError as ce:
            logger.error(str(ce))
            errors.append(str(ce))

    return changes, errors
Пример #20
0
 def get(self, target):
     sub = Subnet(self.db)
     sub.find(target.split('/')[0])
     return (sub.entity_id, self.am.const.auth_target_type_dns,
             self.am.const.auth_grant_dns)
Пример #21
0
    def access_list(self, operator, owner, target_type=None):
        """
        List everything an account or group can operate on. Only direct
        ownership is reported: the entities an account can access due to group
        memberships will not be listed. This does not include unpersonal users
        owned by groups.

        :param operator: operator in bofh session
        :param owner: str name of owner object
        :param target_type: the type of the target
        :return: List of everything an account or group can operate on
        """

        ar = BofhdAuthRole(self.db)
        aot = BofhdAuthOpTarget(self.db)
        aos = BofhdAuthOpSet(self.db)
        co = self.const
        owner_id = self.util.get_target(owner,
                                        default_lookup="group",
                                        restrict_to=[]).entity_id
        ret = []
        for role in ar.list(owner_id):
            aos.clear()
            aos.find(role['op_set_id'])
            for r in aot.list(target_id=role['op_target_id']):
                if target_type is not None and r['target_type'] != target_type:
                    continue
                if r['entity_id'] is None:
                    target_name = "N/A"
                elif r['target_type'] == co.auth_target_type_maildomain:
                    # FIXME: EmailDomain is not an Entity.
                    ed = Email.EmailDomain(self.db)
                    try:
                        ed.find(r['entity_id'])
                    except (Errors.NotFoundError, ValueError):
                        self.logger.warn("Non-existing entity (e-mail domain) "
                                         "in auth_op_target {}:{:d}".format(
                                             r['target_type'], r['entity_id']))
                        continue
                    target_name = ed.email_domain_name
                elif r['target_type'] == co.auth_target_type_ou:
                    ou = self.OU_class(self.db)
                    try:
                        ou.find(r['entity_id'])
                    except (Errors.NotFoundError, ValueError):
                        self.logger.warn("Non-existing entity (ou) in "
                                         "auth_op_target %s:%d" %
                                         (r['target_type'], r['entity_id']))
                        continue
                    target_name = "%02d%02d%02d (%s)" % (
                        ou.fakultet, ou.institutt, ou.avdeling, ou.short_name)
                elif r['target_type'] == co.auth_target_type_dns:
                    s = Subnet(self.db)
                    # TODO: should Subnet.find() support ints as input?
                    try:
                        s.find('entity_id:%s' % r['entity_id'])
                    except (Errors.NotFoundError, ValueError, SubnetError):
                        self.logger.warn("Non-existing entity (subnet) in "
                                         "auth_op_target %s:%d" %
                                         (r['target_type'], r['entity_id']))
                        continue
                    target_name = "%s/%s" % (s.subnet_ip, s.subnet_mask)
                else:
                    try:
                        ety = self._get_entity(ident=r['entity_id'])
                        target_name = self._get_name_from_object(ety)
                    except (Errors.NotFoundError, ValueError):
                        self.logger.warn("Non-existing entity in "
                                         "auth_op_target %s:%d" %
                                         (r['target_type'], r['entity_id']))
                        continue
                ret.append({
                    'opset': aos.name,
                    'target_type': r['target_type'],
                    'target': target_name,
                    'attr': r['attr'] or "",
                })
        ret.sort(lambda a, b: (cmp(a['target_type'], b['target_type']) or cmp(
            a['target'], b['target'])))
        return ret
Пример #22
0
def compare_file_to_db(subnets_in_file, force):
    """Analyzes the info obtained from the files that are to be
    imported, compares to content of database and makes changes were
    needed to bring the database in sync with the datafile.

    TODO: parameter doc.
    """
    errors = []
    changes = []
    perform_checks = not force
    s = Subnet(db)
    subnets_in_db = s.search()
    for row in subnets_in_db:
        subnet = "%s/%s" % (row['subnet_ip'], row['subnet_mask'])

        if subnet in subnets_in_file:
            (description, vlan) = subnets_in_file[subnet]
            # Subnet is in file. Check if description or vlan have changed
            if row['description'] != description:
                s.clear()
                s.find(row['entity_id'])
                s.description = description
                s.write_db(perform_checks=False)
                logger.debug("Updating description of subnet '%s'" % subnet)
                changes.append("Updated description of subnet '%s'" % subnet)
            else:
                logger.debug("Subnet '%s' in both DB and file; " % subnet +
                             "no description update")
            if vlan and row['vlan_number'] != vlan:
                s.clear()
                s.find(row['entity_id'])
                s.vlan_number = vlan
                s.write_db(perform_checks=False)
                logger.debug("Updating vlan for subnet '%s'" % subnet)
                changes.append("Updated vlan for subnet '%s'" % subnet)
            else:
                logger.debug("Subnet '%s' in both DB and file; " % subnet +
                             "no vlan update")
            del subnets_in_file[subnet]
        else:
            # Subnet is in DB, but not in file; try to remove it from DB
            try:
                logger.info("Deleting subnet '%s'" % subnet)
                s.clear()
                s.find(subnet)
                description = s.description
                s.delete(perform_checks=perform_checks)
                changes.append("Deleted subnet '%s' (%s)" %
                               (subnet, description))
            except CerebrumError as ce:
                logger.error(str(ce))
                errors.append(str(ce))

    # What is left in subnets_in_file now are subnets that should be added
    for subnet in subnets_in_file:
        try:
            description, vlan = subnets_in_file[subnet]
            logger.info("Adding subnet '%s' (%s)" % (subnet, description))
            add_subnet(subnet,
                       description,
                       vlan,
                       perform_checks=perform_checks)
            changes.append("Added subnet '%s' (%s)" % (subnet, description))
        except CerebrumError as ce:
            logger.error(str(ce))
            errors.append(str(ce))

    return changes, errors
Пример #23
0
    def subnet_info(self, operator, identifier):
        """Lists the following information about the given subnet:

        * Subnett
        * Netmask
        * Entity ID
        * Description
        * Name-prefix
        * VLAN number
        * DNS-delegation status
        * Range of IPs on subnet
        * Number of reserved addresses
        * A list of the reserved adresses
        """
        s = Subnet(self.db)
        ipc = IPCalc
        try:
            s.find(identifier)
        except (ValueError, SubnetError):
            s = IPv6Subnet(self.db)
            s.find(identifier)
            ipc = IPv6Calc

        if s.dns_delegated:
            delegated = "Yes"
        else:
            delegated = "No"

        data = {
            'subnet': "%s/%s" % (s.subnet_ip, s.subnet_mask),
            'entity_id': str(s.entity_id),
            'desc': s.description,
            'delegated': delegated,
            'name_prefix': s.name_prefix,
            'no_of_res_adr': str(s.no_of_reserved_adr)
        }

        if isinstance(s, Subnet):
            data['netmask'] = ipc.netmask_to_ip(s.subnet_mask)
        else:
            data['prefix'] = '/' + str(s.subnet_mask)

        if s.vlan_number is not None:
            data['vlan'] = str(s.vlan_number)
        else:
            data['vlan'] = "(None)"

        data['ip_range'] = "%s - %s" % (ipc.long_to_ip(
            s.ip_min), ipc.long_to_ip(s.ip_max))

        # Calculate number of used and unused IP-addresses on this subnet
        #                              ^^^^^^ excluding reserved addresses
        uip = self._find.count_used_ips(s.subnet_ip)
        data['used'] = str(uip)
        data['unused'] = str(s.ip_max - s.ip_min - uip - 1)

        reserved_adresses = list(s.reserved_adr)

        if reserved_adresses:
            reserved_adresses.sort()
            data["res_adr1"] = "%s (net)" % ipc.long_to_ip(
                reserved_adresses.pop(0))
        else:
            data["res_adr1"] = "(None)"

        ret = [
            data,
        ]

        if reserved_adresses:
            last_ip = reserved_adresses.pop()
            for address in reserved_adresses:
                ret.append({'res_adr': ipc.long_to_ip(address)})
            ret.append({'res_adr': "%s (broadcast)" % ipc.long_to_ip(last_ip)})

        return ret
Пример #24
0
def compare_file_to_db(subnets_in_file, force):
    """Analyzes the info obtained from the files that are to be
    imported, compares to content of database and makes changes were
    needed to bring the database in sync with the datafile.

    TODO: parameter doc.
    
    """
    errors = []
    changes = []
    perform_checks = not force

    s = Subnet(db)
    subnets_in_db = s.search()

    for row in subnets_in_db:
        subnet_ID = "%s/%s" % (row['subnet_ip'], row['subnet_mask'])

        if subnet_ID in subnets_in_file:
            # Subnet is in file; nothing should be done with it
            if row['description'] != subnets_in_file[subnet_ID][1]:
                s.clear()
                s.find(row['entity_id'])
                s.description = subnets_in_file[subnet_ID][1]
                s.write_db(perform_checks=False)
                logger.debug("Updating description of subnet '%s'" % subnet_ID)
                changes.append("Updated description of subnet '%s'" %
                               subnet_ID)
            else:
                logger.debug("Subnet '%s' in both DB and file; " % subnet_ID +
                             "no description update")
            del subnets_in_file[subnet_ID]
        else:
            # Subnet is in DB, but not in file; try to remove it from DB
            try:
                logger.info("Deleting subnet '%s'" % subnet_ID)
                s.clear()
                s.find(subnet_ID)
                description = s.description
                s.delete(perform_checks=perform_checks)
                changes.append("Deleted subnet '%s' (%s)" %
                               (subnet_ID, description))
            except CerebrumError, ce:
                logger.error(str(ce))
                errors.append(str(ce))
Пример #25
0
    def subnet_set_reserved(self, operator, identifier, new_res):
        self.ba.assert_dns_superuser(operator.get_entity_id())

        try:
            int(new_res)
        except:
            raise CerebrumError("The number of reserved addresses must be " +
                                "an integer; '%s' isn't" % new_res)

        if new_res < 0:
            raise CerebrumError("Cannot set number of reserved addresses to " +
                                "a negative number such as '%s'" % new_res)

        s = Subnet(self.db)
        try:
            s.find(identifier)
        except SubnetError:
            s = IPv6Subnet(self.db)
            s.find(identifier)

        old_res = s.no_of_reserved_adr

        s.no_of_reserved_adr = int(new_res)
        s.calculate_reserved_addresses()

        in_use = ""
        if new_res > old_res:
            try:
                s.check_reserved_addresses_in_use()
            except SubnetError, se:
                in_use = "\nFYI: %s" % str(se)
Пример #26
0
    def subnet_info(self, operator, identifier):
        """Lists the following information about the given subnet:

        * Subnett
        * Netmask
        * Entity ID
        * Description
        * Name-prefix
        * VLAN number
        * DNS-delegation status
        * Range of IPs on subnet
        * Number of reserved addresses
        * A list of the reserved adresses
        """
        s = Subnet(self.db)
        ipc = IPCalc
        try:
            s.find(identifier)
        except (ValueError, SubnetError):
            s = IPv6Subnet(self.db)
            s.find(identifier)
            ipc = IPv6Calc
        
        if s.dns_delegated:
            delegated = "Yes"
        else:
            delegated = "No"
            
        data = {'subnet': "%s/%s" % (s.subnet_ip, s.subnet_mask),
               'entity_id': str(s.entity_id),
               'desc': s.description,
               'delegated': delegated,
               'name_prefix': s.name_prefix,
               'no_of_res_adr': str(s.no_of_reserved_adr)}
        
        if isinstance(s, Subnet):
            data['netmask'] = ipc.netmask_to_ip(s.subnet_mask)
        else:
            data['prefix'] = '/' + str(s.subnet_mask)
    

        if s.vlan_number is not None:
            data['vlan'] = str(s.vlan_number)
        else:
            data['vlan'] =  "(None)"

        data['ip_range'] = "%s - %s" % (ipc.long_to_ip(s.ip_min),
                                        ipc.long_to_ip(s.ip_max))

        # Calculate number of used and unused IP-addresses on this subnet
        #                              ^^^^^^ excluding reserved addresses
        uip = self._find.count_used_ips(s.subnet_ip)
        data['used'] = str(uip)
        data['unused'] = str(s.ip_max - s.ip_min - uip - 1)
        
        reserved_adresses = list(s.reserved_adr)

        if reserved_adresses:
            reserved_adresses.sort()
            data["res_adr1"] = "%s (net)" % ipc.long_to_ip(reserved_adresses.pop(0))
        else:
            data["res_adr1"] = "(None)"

        ret = [data,]

        if reserved_adresses:
            last_ip = reserved_adresses.pop()
            for address in reserved_adresses:
                ret.append({'res_adr': ipc.long_to_ip(address)})
            ret.append({'res_adr': "%s (broadcast)" % ipc.long_to_ip(last_ip)})
            
        return ret