File: _utils.py

package info (click to toggle)
netplan.io 1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 4,268 kB
  • sloc: python: 34,640; ansic: 14,096; xml: 4,989; javascript: 2,165; sh: 513; makefile: 118
file content (220 lines) | stat: -rw-r--r-- 7,769 bytes parent folder | download | duplicates (3)
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# Copyright (C) 2023 Canonical, Ltd.
# Author: Lukas Märdian <slyon@ubuntu.com>
#
# 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; version 3.
#
# 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/>.

from collections import defaultdict
from enum import IntEnum
import re

from ._netplan_cffi import ffi, lib


# Errors and error domains

# NOTE: if new errors or domains are added,
# include/types.h must be updated with the new entries
class NETPLAN_ERROR_DOMAINS(IntEnum):
    NETPLAN_PARSER_ERROR = 1
    NETPLAN_VALIDATION_ERROR = 2
    NETPLAN_FILE_ERROR = 3
    NETPLAN_BACKEND_ERROR = 4
    NETPLAN_EMITTER_ERROR = 5
    NETPLAN_FORMAT_ERROR = 6


class NETPLAN_PARSER_ERRORS(IntEnum):
    NETPLAN_ERROR_INVALID_YAML = 0
    NETPLAN_ERROR_INVALID_CONFIG = 1
    NETPLAN_ERROR_INVALID_FLAG = 2


class NETPLAN_VALIDATION_ERRORS(IntEnum):
    NETPLAN_ERROR_CONFIG_GENERIC = 0
    NETPLAN_ERROR_CONFIG_VALIDATION = 1


class NETPLAN_BACKEND_ERRORS(IntEnum):
    NETPLAN_ERROR_UNSUPPORTED = 0
    NETPLAN_ERROR_VALIDATION = 1


class NETPLAN_EMITTER_ERRORS(IntEnum):
    NETPLAN_ERROR_YAML_EMITTER = 0


class NETPLAN_FORMAT_ERRORS(IntEnum):
    NETPLAN_ERROR_FORMAT_INVALID_YAML = 0


class NetplanException(Exception):
    def __init__(self, message=None, domain=None, error=None):
        self.domain = domain
        self.error = error
        self.message = message

    def __str__(self):
        return self.message


class NetplanFileException(NetplanException):
    @property
    def errno(self):
        return self.error


class NetplanValidationException(NetplanException):
    '''
    Netplan Validation errors are expected to contain the YAML file name
    from where the error was found.

    A validation error might happen after the parsing stage. libnetplan walks
    through its internal representation of the network configuration and checks
    if all the requirements are met. For example, if it finds that the key
    "set-name" is used by an interface, it will check if "match" is present.
    As "set-name" requires "match" to work, it will emit a validation error
    if it's not found.
    '''

    SCHEMA_VALIDATION_ERROR_MSG_REGEX = (
            r'(?P<file_path>.*\.yaml): (?P<message>.*)'
            )

    def __init__(self, message=None, domain=None, error=None):
        super().__init__(message, domain, error)

        schema_error = re.match(self.SCHEMA_VALIDATION_ERROR_MSG_REGEX, message)
        if not schema_error:
            # This shouldn't happen
            raise ValueError(f'The validation error message does not have the expected format: {message}')

        self.filename = schema_error["file_path"]
        self.message = schema_error["message"]


class NetplanParserException(NetplanException):
    '''
    Netplan Parser errors are expected to contain the YAML file name
    and line and column numbers from where the error was found.

    A parser error might happen during the parsing stage. Parsing errors
    might be due to invalid YAML files or invalid Netplan grammar. libnetplan
    will check for this kind of issues while it's walking through the YAML
    files, so it has access to the location where the error was found.
    '''

    SCHEMA_PARSER_ERROR_MSG_REGEX = (
            r'(?P<file_path>.*):(?P<error_line>\d+):(?P<error_col>\d+): (?P<message>(\s|.)*)'
            )

    def __init__(self, message=None, domain=None, error=None):
        super().__init__(message, domain, error)

        # Parser errors from libnetplan have the form:
        #
        # filename.yaml:4:14: Error in network definition: invalid boolean value 'falsea'
        #
        schema_error = re.match(self.SCHEMA_PARSER_ERROR_MSG_REGEX, message)
        if not schema_error:
            # This shouldn't happen
            raise ValueError(f'The parser error message does not have the expected format: {message}')

        self.filename = schema_error["file_path"]
        self.line = schema_error["error_line"]
        self.column = schema_error["error_col"]
        self.message = schema_error["message"]


class NetplanParserFlagsException(NetplanException):
    pass


class NetplanBackendException(NetplanException):
    pass


class NetplanEmitterException(NetplanException):
    pass


class NetplanFormatException(NetplanException):
    pass


# Used in case the "domain" received from libnetplan doesn't exist
NETPLAN_EXCEPTIONS_FALLBACK = defaultdict(lambda: NetplanException)

# If a domain that doesn't exist is queried, it will fallback to NETPLAN_EXCEPTIONS_FALLBACK
# which will return NetplanException for any key accessed.
NETPLAN_EXCEPTIONS = defaultdict(lambda: NETPLAN_EXCEPTIONS_FALLBACK, {
        NETPLAN_ERROR_DOMAINS.NETPLAN_PARSER_ERROR: {
            NETPLAN_PARSER_ERRORS.NETPLAN_ERROR_INVALID_YAML: NetplanParserException,
            NETPLAN_PARSER_ERRORS.NETPLAN_ERROR_INVALID_CONFIG: NetplanParserException,
            NETPLAN_PARSER_ERRORS.NETPLAN_ERROR_INVALID_FLAG: NetplanParserFlagsException,
            },

        NETPLAN_ERROR_DOMAINS.NETPLAN_VALIDATION_ERROR: {
            NETPLAN_VALIDATION_ERRORS.NETPLAN_ERROR_CONFIG_GENERIC: NetplanException,
            NETPLAN_VALIDATION_ERRORS.NETPLAN_ERROR_CONFIG_VALIDATION: NetplanValidationException,
            },

        # FILE_ERRORS are "errno" values and they all throw the same exception
        NETPLAN_ERROR_DOMAINS.NETPLAN_FILE_ERROR: defaultdict(lambda: NetplanFileException),

        NETPLAN_ERROR_DOMAINS.NETPLAN_BACKEND_ERROR: {
            NETPLAN_BACKEND_ERRORS.NETPLAN_ERROR_UNSUPPORTED: NetplanBackendException,
            NETPLAN_BACKEND_ERRORS.NETPLAN_ERROR_VALIDATION: NetplanBackendException,
            },

        NETPLAN_ERROR_DOMAINS.NETPLAN_EMITTER_ERROR: {
            NETPLAN_EMITTER_ERRORS.NETPLAN_ERROR_YAML_EMITTER: NetplanEmitterException,
            },

        NETPLAN_ERROR_DOMAINS.NETPLAN_FORMAT_ERROR: {
            NETPLAN_FORMAT_ERRORS.NETPLAN_ERROR_FORMAT_INVALID_YAML: NetplanFormatException,
            }
        })


def _checked_lib_call(fn, *args):
    ref = ffi.new('NetplanError **')
    ret = bool(fn(*args, ref))
    if not ret:
        err = ref[0]
        if err == ffi.NULL:  # pragma: nocover (should never happen)
            raise NetplanException("Unknown error", 0, 0)
        domain_code = lib.netplan_error_code(err)
        error_domain = domain_code >> 32  # upper 32 bits
        error_code = int(ffi.cast('uint32_t', domain_code))  # lower 32 bits
        error_message = _string_realloc_call_no_error(lambda b: lib.netplan_error_message(err, b, len(b)))
        exception = NETPLAN_EXCEPTIONS[error_domain][error_code]
        raise exception(error_message, error_domain, error_code)
    return ret


def _string_realloc_call_no_error(function: callable):
    size = 16
    while size < 1048576:  # 1MB
        buf = ffi.new('char[]', size)
        code = function(buf)
        if code == -2:
            size = size * 2
            continue

        if code < 0:  # pragma: nocover
            raise NetplanException("Unknown error: %d" % code)
        elif code == 0:
            return None  # pragma: nocover as it's hard to trigger for now
        else:
            return ffi.string(buf).decode('utf-8')
    raise NetplanException('Halting due to string buffer size > 1M')  # pragma: nocover