summaryrefslogtreecommitdiff
path: root/python/vyos/xml_ref/definition.py
blob: 64a33e4d0b3c4073a1e6a3eff2eb9e4dddafea98 (plain)
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# Copyright 2023 VyOS maintainers and contributors <maintainers@vyos.io>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library.  If not, see <http://www.gnu.org/licenses/>.

from typing import Union, Optional, Any
from vyos.configdict import dict_merge

class Xml:
    def __init__(self):
        self.ref = {}

    def define(self, ref: dict):
        self.ref = ref

    def _get_ref_node_data(self, node: dict, data: str) -> Union[bool, str]:
        res = node.get('node_data', {})
        if not res:
            raise ValueError("non-existent node data")
        if data not in res:
            raise ValueError("non-existent data field")

        return res.get(data)

    def _get_ref_path(self, path: list) -> dict:
        ref_path = path.copy()
        d = self.ref
        while ref_path and d:
            d = d.get(ref_path[0], {})
            ref_path.pop(0)
            if self._is_tag_node(d) and ref_path:
                ref_path.pop(0)

        return d

    def _is_tag_node(self, node: dict) -> bool:
        res = self._get_ref_node_data(node, 'node_type')
        return res == 'tag'

    def is_tag(self, path: list) -> bool:
        ref_path = path.copy()
        d = self.ref
        while ref_path and d:
            d = d.get(ref_path[0], {})
            ref_path.pop(0)
            if self._is_tag_node(d) and ref_path:
                if len(ref_path) == 1:
                    return False
                ref_path.pop(0)

        return self._is_tag_node(d)

    def is_tag_value(self, path: list) -> bool:
        if len(path) < 2:
            return False

        return self.is_tag(path[:-1])

    def _is_multi_node(self, node: dict) -> bool:
        b = self._get_ref_node_data(node, 'multi')
        assert isinstance(b, bool)
        return b

    def is_multi(self, path: list) -> bool:
        d = self._get_ref_path(path)
        return  self._is_multi_node(d)

    def _is_valueless_node(self, node: dict) -> bool:
        b = self._get_ref_node_data(node, 'valueless')
        assert isinstance(b, bool)
        return b

    def is_valueless(self, path: list) -> bool:
        d = self._get_ref_path(path)
        return  self._is_valueless_node(d)

    def _is_leaf_node(self, node: dict) -> bool:
        res = self._get_ref_node_data(node, 'node_type')
        return res == 'leaf'

    def is_leaf(self, path: list) -> bool:
        d = self._get_ref_path(path)
        return self._is_leaf_node(d)

    def component_version(self) -> dict:
        d = {}
        for k, v in self.ref['component_version']:
            d[k] = int(v)
        return d

    def multi_to_list(self, rpath: list, conf: dict) -> dict:
        if rpath and rpath[-1] in list(conf):
            raise ValueError('rpath should be disjoint from conf keys')

        res = {}

        for k in list(conf):
            d = self._get_ref_path(rpath + [k])
            if self._is_leaf_node(d):
                if self._is_multi_node(d) and not isinstance(conf[k], list):
                    res[k] = [conf[k]]
                else:
                    res[k] = conf[k]
            else:
                res[k] = self.multi_to_list(rpath + [k], conf[k])

        return res

    def _get_default_value(self, node: dict):
        return self._get_ref_node_data(node, "default_value")

    def get_defaults(self, path: list, get_first_key=False) -> dict:
        """Return dict containing default values below path

        Note that descent below path will not proceed beyond an encountered
        tag node, as no tag node value is known. For a default dict relative
        to an existing config dict containing tag node values, see function:
        'relative_defaults'
        """
        res: Any = {}
        d = self._get_ref_path(path)
        if self._is_leaf_node(d):
            default_value = self._get_default_value(d)
            if default_value is not None:
                res = default_value
                if self._is_multi_node(d) and not isinstance(res, list):
                    res = [res]
        elif self.is_tag(path):
            # tag node defaults are used as suggestion, not default value;
            # should this change, append to path and continue recursion
            pass
        else:
            for k in list(d):
                if k in ('node_data', 'component_version') :
                    continue
                pos = self.get_defaults(path + [k])
                res |= pos
        if res:
            if get_first_key or not path:
                if not isinstance(res, dict):
                    raise TypeError("Cannot get_first_key as data under node is not of type dict")
                return res
            return {path[-1]: res}

        return {}

    def _relative_defaults(self, rpath: list, conf: Optional[dict] = None,
                          get_first_key=False) -> dict:
        # Return dict containing defaults along paths of a config dict

        # Note that for conf argument {} or None, this function returns the
        # same result as 'get_defaults' above; for clarity, the functions
        # are individually defined.

        if conf is None:
            conf = {}
        if rpath and rpath[-1] in list(conf):
            raise ValueError('rpath should be disjoint from conf keys')
        res: Any = {}
        d = self._get_ref_path(rpath)
        if self._is_leaf_node(d):
            default_value = self._get_default_value(d)
            if default_value is not None:
                res = default_value
                if self._is_multi_node(d) and not isinstance(res, list):
                    res = [res]
        elif self.is_tag(rpath):
            for k in list(conf):
                pos = self._relative_defaults(rpath + [k], conf[k])
                res |= pos
        else:
            for k in list(d):
                if k in ('node_data', 'component_version') :
                    continue
                pos = self._relative_defaults(rpath + [k], conf.get(k, {}))
                res |= pos
        if res:
            if get_first_key or not rpath:
                if not isinstance(res, dict):
                    raise TypeError("Cannot get_first_key as data under node is not of type dict")
                return res
            return {rpath[-1]: res}

        return {}

    def _defines_config_path(self, path: list, conf: dict) -> bool:
        # test disjoint path + conf for sensible config paths
        def walk(c):
            return [next(iter(c.keys()))] if c else []
        try:
            tmp = walk(conf)
            if self.is_tag_value(path + tmp):
                c = conf[tmp[0]]
                if not isinstance(c, dict):
                    raise ValueError
                tmp = tmp + walk(c)
                self._get_ref_path(path + tmp)
            else:
                self._get_ref_path(path + tmp)
        except ValueError:
            return False
        return True

    def merge_defaults(self, path: list, conf: dict) -> dict:
        """Return config dict with defaults non-destructively merged
        """
        if not path:
            path = [next(iter(conf.keys()))]
        if path[-1] in list(conf):
            config = conf[path[-1]]
            if not isinstance(config, dict):
                raise ValueError('conf at path is not of type dict')
            first = False
        else:
            config = conf
            first = True

        if not self._defines_config_path(path, config):
            print('path + conf do not define config paths; conf returned unchanged')
            return conf

        d = self._relative_defaults(path, conf=config, get_first_key=first)
        d = dict_merge(d, conf)
        return d