summaryrefslogtreecommitdiffstats
path: root/node-admin/scripts/pyroute2/netlink/rtnl/req.py
blob: 268fd7ff6045df2af1848415f52b569327bcafeb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# By Peter V. Saveliev https://pypi.python.org/pypi/pyroute2. Dual licensed under the Apache 2 and GPLv2+ see https://github.com/svinota/pyroute2 for License details.
from socket import AF_INET6
from pyroute2.common import basestring
from pyroute2.netlink.rtnl.ifinfmsg import ifinfmsg
from pyroute2.netlink.rtnl.rtmsg import rtmsg


class IPRequest(dict):

    def __init__(self, obj=None):
        dict.__init__(self)
        if obj is not None:
            self.update(obj)

    def update(self, obj):
        for key in obj:
            if obj[key] is not None:
                self[key] = obj[key]


class IPRouteRequest(IPRequest):
    '''
    Utility class, that converts human-readable dictionary
    into RTNL route request.
    '''

    def __setitem__(self, key, value):
        # fix family
        if isinstance(value, basestring) and value.find(':') >= 0:
            self['family'] = AF_INET6
        # work on the rest
        if key == 'dst':
            if value != 'default':
                value = value.split('/')
                if len(value) == 1:
                    dst = value[0]
                    mask = 0
                elif len(value) == 2:
                    dst = value[0]
                    mask = int(value[1])
                else:
                    raise ValueError('wrong destination')
                dict.__setitem__(self, 'dst', dst)
                dict.__setitem__(self, 'dst_len', mask)
        elif key == 'metrics':
            ret = {'attrs': []}
            for name in value:
                rtax = rtmsg.metrics.name2nla(name)
                ret['attrs'].append([rtax, value[name]])
            dict.__setitem__(self, 'metrics', ret)
        else:
            dict.__setitem__(self, key, value)


class CBRequest(IPRequest):
    '''
    FIXME
    '''
    commands = None
    msg = None

    def __init__(self, *argv, **kwarg):
        self['commands'] = {'attrs': []}

    def __setitem__(self, key, value):
        if value is None:
            return
        if key in self.commands:
            self['commands']['attrs'].\
                append([self.msg.name2nla(key), value])
        else:
            dict.__setitem__(self, key, value)


class IPLinkRequest(IPRequest):
    '''
    Utility class, that converts human-readable dictionary
    into RTNL link request.
    '''
    blacklist = ['carrier',
                 'carrier_changes']

    def __init__(self, *argv, **kwarg):
        self.deferred = []
        IPRequest.__init__(self, *argv, **kwarg)
        if 'index' not in self:
            self['index'] = 0

    def __setitem__(self, key, value):
        # ignore blacklisted attributes
        if key in self.blacklist:
            return

        # there must be no "None" values in the request
        if value is None:
            return

        # all the values must be in ascii
        try:
            if isinstance(value, unicode):
                value = value.encode('ascii')
        except NameError:
            pass

        # set up specific keys
        if key == 'kind':
            self['IFLA_LINKINFO'] = {'attrs': []}
            linkinfo = self['IFLA_LINKINFO']['attrs']
            linkinfo.append(['IFLA_INFO_KIND', value])
            if value in ('vlan', 'bond', 'tuntap', 'veth',
                         'vxlan', 'macvlan', 'macvtap', 'gre'):
                linkinfo.append(['IFLA_INFO_DATA', {'attrs': []}])
        elif key == 'vlan_id':
            nla = ['IFLA_VLAN_ID', value]
            # FIXME: we need to replace, not add
            self.defer_nla(nla, ('IFLA_LINKINFO', 'IFLA_INFO_DATA'),
                           lambda x: x.get('kind', None) == 'vlan')
        elif key == 'gid':
            nla = ['IFTUN_UID', value]
            self.defer_nla(nla, ('IFLA_LINKINFO', 'IFLA_INFO_DATA'),
                           lambda x: x.get('kind', None) == 'tuntap')
        elif key == 'uid':
            nla = ['IFTUN_UID', value]
            self.defer_nla(nla, ('IFLA_LINKINFO', 'IFLA_INFO_DATA'),
                           lambda x: x.get('kind', None) == 'tuntap')
        elif key == 'mode':
            nla = ['IFTUN_MODE', value]
            self.defer_nla(nla, ('IFLA_LINKINFO', 'IFLA_INFO_DATA'),
                           lambda x: x.get('kind', None) == 'tuntap')
            nla = ['IFLA_BOND_MODE', value]
            self.defer_nla(nla, ('IFLA_LINKINFO', 'IFLA_INFO_DATA'),
                           lambda x: x.get('kind', None) == 'bond')
        elif key == 'ifr':
            nla = ['IFTUN_IFR', value]
            self.defer_nla(nla, ('IFLA_LINKINFO', 'IFLA_INFO_DATA'),
                           lambda x: x.get('kind', None) == 'tuntap')
        elif key.startswith('macvtap'):
            nla = [ifinfmsg.name2nla(key), value]
            self.defer_nla(nla, ('IFLA_LINKINFO', 'IFLA_INFO_DATA'),
                           lambda x: x.get('kind', None) == 'macvtap')
        elif key.startswith('macvlan'):
            nla = [ifinfmsg.name2nla(key), value]
            self.defer_nla(nla, ('IFLA_LINKINFO', 'IFLA_INFO_DATA'),
                           lambda x: x.get('kind', None) == 'macvlan')
        elif key.startswith('gre'):
            nla = [ifinfmsg.name2nla(key), value]
            self.defer_nla(nla, ('IFLA_LINKINFO', 'IFLA_INFO_DATA'),
                           lambda x: x.get('kind', None) == 'gre')
        elif key.startswith('vxlan'):
            nla = [ifinfmsg.name2nla(key), value]
            self.defer_nla(nla, ('IFLA_LINKINFO', 'IFLA_INFO_DATA'),
                           lambda x: x.get('kind', None) == 'vxlan')
        elif key == 'peer':
            nla = ['VETH_INFO_PEER', {'attrs': [['IFLA_IFNAME', value]]}]
            self.defer_nla(nla, ('IFLA_LINKINFO', 'IFLA_INFO_DATA'),
                           lambda x: x.get('kind', None) == 'veth')
        dict.__setitem__(self, key, value)
        if self.deferred:
            self.flush_deferred()

    def flush_deferred(self):
        deferred = []
        for nla, path, predicate in self.deferred:
            if predicate(self):
                self.append_nla(nla, path)
            else:
                deferred.append((nla, path, predicate))
        self.deferred = deferred

    def append_nla(self, nla, path):
            pwd = self
            for step in path:
                if step in pwd:
                    pwd = pwd[step]
                else:
                    pwd = [x[1] for x in pwd['attrs']
                           if x[0] == step][0]['attrs']
            pwd.append(nla)

    def defer_nla(self, nla, path, predicate):
        self.deferred.append((nla, path, predicate))
        self.flush_deferred()