ridtools.py 5.47 KB
Newer Older
Olivier Iffrig's avatar
Olivier Iffrig committed
1 2
# -*- coding: utf-8 -*-
#
3
# RIDTOOLS.PY -- Gestion de la conversion rid <-> IP
Olivier Iffrig's avatar
Olivier Iffrig committed
4 5
#
# Copyright (C) 2010 Olivier Iffrig
6
#           (c) 2010 Nicolas Dandrimont
Olivier Iffrig's avatar
Olivier Iffrig committed
7
# Authors: Olivier Iffrig <iffrig@crans.org>
8
#          Nicolas Dandrimont <olasd@crans.org>
9
# Adapté par Pierre-Elliott Bécue pour cause de changement de schéma.
Olivier Iffrig's avatar
Olivier Iffrig committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

24
import netaddr
25
import itertools
26
import config
Olivier Iffrig's avatar
Olivier Iffrig committed
27

28
class Rid(object):
Olivier Iffrig's avatar
Olivier Iffrig committed
29
    """
30
    Permet de décortiquer un rid et d'obtenir les IP correspondantes
31 32

    Variables d'instance :
33 34 35
     - rid : le rid
     - type : type de rid (cf. config.rid et [1])
     - reste : le "reste" du rid (permettant de calculer l'IP par exemple)
36
     - ipv4_dispo : une IPv4 *publique* *du crans* existe pour ce rid
37 38 39
     - priv : cette machine ne doit pas être accessible de l'extérieur

    [1] http://wiki.crans.org/CransTechnique/PlanAdressage#Machines
Olivier Iffrig's avatar
Olivier Iffrig committed
40 41
    """

42 43
    def __init__(self, rid=None, ipv4=None):
        self.rid = None
44 45 46 47 48
        self.reste = False
        self.type = None
        self.ipv4_dispo = False
        self.priv = False

49 50
        if rid is not None:
            self.__parse(rid)
51 52
        elif ipv4 is not None:
            self.__from_ipv4(ipv4)
53
        else:
54
            raise ValueError("Un des champs rid et ipv4 doit être défini")
55

56 57 58
    def __parse(self, rid):
        """Peuple les champs de l'instance par rapport au rid"""
        self.rid = rid
59

60 61
        self.type = find_rid_plage(int(rid))
        if self.type == 'Inconnu':
62
            raise ValueError("rid inconnu : %d" % rid)
Olivier Iffrig's avatar
Olivier Iffrig committed
63

64
        self.ipv4_dispo = (rid & (1 << 15)) == 0 and self.type != 'special' or self.rid in config.rid_machines_speciales
Olivier Iffrig's avatar
Olivier Iffrig committed
65

66
        self.priv = (rid & (1 << 14)) != 0
Olivier Iffrig's avatar
Olivier Iffrig committed
67

68
        if self.type == 'personnel-ens':
69
            self.reste = rid & 0xff
70
        else:
71
            self.reste = rid & 0x7ff
72 73 74 75 76 77 78 79 80

    def __from_ipv4(self, ip):
        """Peuple les champs à partir de l'ipv4 donnée"""
        if not isinstance(ip, netaddr.IPAddress):
            ip = netaddr.IPAddress(ip)
        try:
            ip.ipv4()
        except netaddr.AddrConversionError:
            raise ValueError("Ceci n'est pas une IPv4... %s" % ip)
Olivier Iffrig's avatar
Olivier Iffrig committed
81

82
        self.ipv4_dispo = True
83 84
        self.priv = ip.is_private()

85 86
        for tp in config.NETs_primaires.keys():
            for net in config.NETs_primaires[tp]:
87 88 89 90
                if ip in netaddr.IPNetwork(net):
                    self.type = tp
                    break
            if self.type:
91
                break
92
        else:
93
            for rid, ip_speciale in config.rid_machines_speciales.items():
94
                if ip == netaddr.IPAddress(ip_speciale):
95
                    self.rid = rid
96 97 98 99
                    self.type = "special"
                    break
            else:
                raise ValueError("%s dans aucun des réseaux gérés par le Cr@ns..." % ip)
100

101
        ranges = itertools.chain(*[xrange(a, b+1) for (a,b) in config.rid[self.type]])
102
        if not self.rid:
103
            self.rid = config.rid[self.type][0][0] + ip.value - netaddr.IPNetwork(config.NETs[self.type][0]).value
104

105 106
        if self.rid not in ranges:
            raise ValueError("%s trop hors des plages prévues pour le réseau '%s'" % (ip, self.type))
107 108

        if self.type == 'personnel-ens':
109
            self.reste = self.rid & 0xff
110
        else:
111 112
            self.reste = self.rid & 0x7ff
        return self.rid
113

114
    def ipv4(self):
Olivier Iffrig's avatar
Olivier Iffrig committed
115 116 117 118
        """
        Génère l'IPv4 associée à la machine
        """
        if not self.ipv4_dispo:
119 120 121
            raise ValueError("Pas d'adresse IPv4 disponible pour la machine %r" % self)

        if not hasattr(self, '__ipv4'):
122 123 124 125
            if self.type != "special":
                net = netaddr.IPNetwork(config.NETs[self.type][0])
                self.__ipv4 = netaddr.IPAddress(net.first + self.reste)
            else:
126
                self.__ipv4 = netaddr.IPAddress(config.rid_machines_speciales[self.rid])
Olivier Iffrig's avatar
Olivier Iffrig committed
127

128
        return self.__ipv4
Olivier Iffrig's avatar
Olivier Iffrig committed
129

130
    def ipv6_network(self):
Olivier Iffrig's avatar
Olivier Iffrig committed
131
        """
132
        Génère le réseau /64 IPv6 associé à la machine
Olivier Iffrig's avatar
Olivier Iffrig committed
133
        """
huber's avatar
huber committed
134 135
        if self.priv:
            raise ValueError("Pas de prefix ipv6 disponible pour cette machine")
Olivier Iffrig's avatar
Olivier Iffrig committed
136

137 138
        global_net = netaddr.IPNetwork(config.prefix["subnet"][0])
        global_net.prefixlen = 64
139
        return global_net.next(self.rid)
140 141 142

    def __repr__(self):
        if self.ipv4_dispo:
143
            return "<Rid(rid=%s, ipv4='%s')>" % (self.rid, self.ipv4())
144
        else:
145
            return "<Rid(%s)>" % self.rid
146

147
    def __int__(self):
148
        return self.rid
149 150 151 152 153 154 155

def find_rid_plage(rid):
    """Trouve la plage du rid fourni"""
    for (tp, plages) in config.rid_primaires.iteritems():
        if isinstance(plages, list):
            for begin, end in plages:
                if begin <= rid <= end:
156
                    return tp, config.rid_primaires[tp][0]
157 158 159 160 161 162
        else:
            (begin, end) = plages
            if begin <= rid <= end:
                return tp, (begin, end)
    else:
        return "Inconnu", (0, 0)