コード例 #1
0
 def rg_addresses(self):
     """Query list of addresses in local vlan+location from directory."""
     d = Directory()
     with exceptions_screened():
         for node in d.list_addresses(self.vlan, self.location):
             if node['rg'] == self.rg:
                 yield netaddr.IPNetwork(node['addr']).ip
コード例 #2
0
 def __init__(self, location, ipversion=4):
     """Initialize instance with location, vlan, and ipversion defaults."""
     self.location = location
     self.ipversion = ipversion
     self.directory = Directory()
     self.hosts = gocept.net.dhcp.Hosts()
     self.networks = {}
コード例 #3
0
class DHCPd(object):
    """dhcpd.conf generator.

    This class retrieves information about configured hosts from the
    directory and creates a dhcpd.conf part that represents that
    information. This part can optionally be merged with one or more
    static includes to assemble a complete dhcpd.conf file.
    """
    def __init__(self, location, ipversion=4):
        """Initialize instance with location, vlan, and ipversion defaults."""
        self.location = location
        self.ipversion = ipversion
        self.directory = Directory()
        self.hosts = gocept.net.dhcp.Hosts()
        self.networks = {}

    def query_directory(self):
        """Retrieve networks and hosts from directory and add them to subnets.
        """
        # Query all networks and their subnet declarations
        vlans = self.directory.lookup_networks_details(self.location,
                                                       self.ipversion)
        for vlan, networks in vlans.items():
            self.networks[vlan] = gocept.net.dhcp.SharedNetwork()
            for network in networks:
                subnet = gocept.net.dhcp.Subnet(
                    netaddr.IPNetwork(network['cidr']), network['dhcp'],
                    self.hosts)
                self.networks[vlan].register(subnet)

        # Query all hosts
        for record in self.directory.list_nodes_addresses(
                self.location, '', self.ipversion):
            try:
                hostaddr = gocept.net.dhcp.HostAddr(
                    record['name'], record['vlan'],
                    netaddr.EUI(record['mac'], dialect=netaddr.mac_unix),
                    netaddr.IPNetwork(record['ip']))
            except (KeyError, ValueError, netaddr.AddrFormatError):
                # XXX Log this?
                continue
            self.hosts.add(hostaddr)

    def render(self, includes=None, inc_dir=None):
        """Assemble complete dhcpd.conf configuration file.

        `includes` is a list of static includes which are read in listed
        order. Includes that don't exist are silently skipped. Returns a
        StringIO object with the rendered configuration file.
        """
        out = ['# auto-generated by localconfig-dhcpd\n\n']
        out += include(includes or [])
        out += [
            str(NetworkFormatter.new(self.ipversion, shnet, vlan, inc_dir))
            for vlan, shnet in sorted(self.networks.iteritems())
        ]
        out.append(str(HostsFormatter.new(self.ipversion, self.hosts)))
        return ''.join(out)
コード例 #4
0
class Mounts(object):
    def __init__(self, box_server, resource_group):
        self.box_server = box_server
        self.resource_group = resource_group
        self.d = Directory()

    def __call__(self):
        if not self.box_server:
            print('No box server. Not configuring.')
            return
        with exceptions_screened():
            self.users = self.d.list_users(os.environ.get('RESOURCE_GROUP'))
        self.users = [u for u in self.users if u['class'] == 'human']
        self.users.sort(key=lambda u: u['uid'])

        self.ensure_symlinks()
        changed = self.ensure_automap()
        if changed:
            subprocess.check_call(['/etc/init.d/autofs', 'restart'])

    def ensure_symlink(self, user, box):
        target = p.join('/mnt/autofs/box', user['uid'])
        if p.islink(box) and os.readlink(box) == target:
            return
        if p.ismount(box):
            print('Box {} is still mounted, unmounting'.format(box))
            subprocess.check_call(['umount', box])
        if p.isdir(box):
            os.rmdir(box)
        else:
            try:
                os.unlink(box)
            except Exception:
                pass
        if not p.exists(box):
            print('Symlinking {}'.format(box))
            os.symlink(target, box)

    def ensure_symlinks(self):
        for user in self.users:
            box = p.join(user['home_directory'], 'box')
            self.ensure_symlink(user, box)

    autofs_template = (
        '{uid} -intr,soft,rsize=8192,wsize=8192 {server}:/srv/nfs/box/{uid}\n')

    def ensure_automap(self):
        fstab = ConfigFile('/etc/autofs/auto.box')
        fstab.write('# Managed by localconfig-box-mounts. '
                    'Manual changes will be overwritten.\n')
        for user in self.users:
            fstab.write(
                self.autofs_template.format(server=self.box_server,
                                            uid=user['uid']))
        return fstab.commit()
コード例 #5
0
 def _load(self):
     directory = Directory()
     with exceptions_screened():
         self.users = directory.list_users(self.resource_group)
         self.permissions = directory.list_permissions()
         self.admins_group = directory.lookup_resourcegroup('admins')
         self.admins_permission = {'description': 'Administrators',
                                   'id': self.admins_group['gid'],
                                   'name': self.admins_group['name']}
         self.rg_info = directory.lookup_resourcegroup(self.resource_group)
コード例 #6
0
def update():
    a = argparse.ArgumentParser()
    a.add_argument('-c',
                   '--config',
                   default='/etc/local/configure-zones.cfg',
                   help='path to configuration file (default: %(default)s)')
    args = a.parse_args()
    config = configobj.ConfigObj(args.config)
    zones = Zones(config)
    directory = Directory()
    with exceptions_screened():
        for node_addr in walk(directory):
            node_addr.inject_records(zones)
    if zones.update() and config['settings'].get('reload'):
        sys.stdout.flush()
        subprocess.check_call([config['settings']['reload']], shell=True)
コード例 #7
0
class Exports(object):

    base = '/srv/nfs/box'

    def __init__(self):
        self.d = Directory()

    def __call__(self):
        with exceptions_screened():
            self.users = self.d.list_users()
        self.users = [u for u in self.users if u['class'] == 'human']
        self.create_boxes()

    def create_boxes(self):
        for u in self.users:
            box = p.join(self.base, u['uid'])
            if not p.exists(box):
                print("Creating {}".format(box))
                os.mkdir(box)
            os.chown(box, u['id'], u['gid'])
            os.chmod(box, 0o755)
コード例 #8
0
 def __init__(self, box_server, resource_group):
     self.box_server = box_server
     self.resource_group = resource_group
     self.d = Directory()
コード例 #9
0
 def __init__(self):
     self.d = Directory()