summaryrefslogtreecommitdiffstats
path: root/src/lib/yang/translator.cc
blob: acae31538662b8e2fb03b3711f280463bbc60692 (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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright (C) 2018-2022 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <util/encode/base64.h>
#include <yang/adaptor.h>
#include <yang/translator.h>

#include <sysrepo-cpp/utils/exception.hpp>

#include <cstring>
#include <vector>

using namespace std;
using namespace isc::data;
using namespace isc::util::encode;
using namespace libyang;
using namespace sysrepo;

namespace isc {
namespace yang {

Translator::Translator(Session session, const string& model)
    : session_(session), model_(model) {
}

void
Translator::checkAndGetLeaf(ElementPtr& storage,
                            DataNode const& data_node,
                            string const& name) const {
    ElementPtr const& x(getItem(data_node, name));
    if (x) {
        storage->set(name, x);
    }
}

void
Translator::checkAndGetDivergingLeaf(ElementPtr& storage,
                                     DataNode const& data_node,
                                     string const& name,
                                     string const& yang_name) const {
    ElementPtr const& x(getItem(data_node, yang_name));
    if (x) {
        storage->set(name, x);
    }
}

void
Translator::checkAndGetAndJsonifyLeaf(ElementPtr& storage,
                                      DataNode const& data_node,
                                      string const& name) const {
    ElementPtr const& x(getItem(data_node, name));
    if (x) {
        storage->set(name, Element::fromJSON(x->stringValue()));
    }
}

void
Translator::checkAndJsonifyAndSetLeaf(ConstElementPtr const& from,
                                      string const& xpath,
                                      string const& name) {
    ConstElementPtr const& x(from->get(name));
    if (x) {
        ElementPtr const& json(Element::create(x->str()));
        setItem(xpath + "/" + name, json, LeafBaseType::String);
    }
}

void Translator::checkAndSetLeaf(ConstElementPtr const& from,
                                 string const& xpath,
                                 string const& name,
                                 LeafBaseType const type) {
    ConstElementPtr const& x(from->get(name));
    if (x) {
        setItem(xpath + "/" + name, x, type);
    }
}

void Translator::checkAndSetDivergingLeaf(ConstElementPtr const& from,
                                          string const& xpath,
                                          string const& name,
                                          string const& yang_name,
                                          LeafBaseType const type) {
    ConstElementPtr const& x(from->get(name));
    if (x) {
        setItem(xpath + "/" + yang_name, x, type);
    }
}

void Translator::checkAndSetLeafList(ConstElementPtr const& from,
                                     string const& xpath,
                                     string const& name,
                                     LeafBaseType const type) {
    ConstElementPtr const& leaf_list(from->get(name));
    if (leaf_list && !leaf_list->empty()) {
        for (ElementPtr const& leaf : leaf_list->listValue()) {
            setItem(xpath + "/" + name, leaf, type);
        }
    }
}

void Translator::checkAndSetUserContext(ConstElementPtr const& from,
                                        string const& xpath) {
    ConstElementPtr const& user_context(Adaptor::getContext(from));
    if (user_context) {
        setItem(xpath + "/user-context", Element::create(user_context->str()),
                LeafBaseType::String);
    }
}

string
Translator::decode64(string const& input) {
    vector<uint8_t> binary;
    decodeBase64(input, binary);
    string result;
    result.resize(binary.size());
    memmove(&result[0], &binary[0], result.size());
    return (result);
}

void
Translator::deleteItem(string const& xpath) {

    try {
        if (session_.getData(xpath)) {
            session_.deleteItem(xpath);
        }
    } catch (sysrepo::Error const& ex) {
        isc_throw(NetconfError, "deleting item at '" << xpath << "': " << ex.what());
    }
    session_.applyChanges();
}


string
Translator::encode64(string const& input) {
    vector<uint8_t> binary;
    binary.resize(input.size());
    memmove(&binary[0], input.c_str(), binary.size());
    return (encodeBase64(binary));
}

DataNode
Translator::findXPath(string const& xpath) {
    optional<DataNode> const& data_node(getData(xpath));
    if (!data_node) {
        isc_throw(NetconfError, "no data at xpath " << xpath);
    }
    Set<DataNode> at_path(data_node->findXPath(xpath));
    if (at_path.empty()) {
        isc_throw(NetconfError, "no data at xpath " << xpath);
    }
    return at_path.front();
}

optional<DataNode>
Translator::getData(string const& xpath) const {
    optional<DataNode> data_node;
    try {
        data_node = session_.getData(xpath);
    } catch (sysrepo::Error const& ex) {
        isc_throw(NetconfError, "getting item at '" << xpath << "': " << ex.what());
    }

    return data_node;
}

ElementPtr
Translator::getItem(DataNode const& data_node,
                    string const& xpath) const {
    try {
        Set<DataNode> const& nodes(data_node.findXPath(xpath));
        if (nodes.empty()) {
            return ElementPtr();
        }
        DataNode const& front(nodes.front());
        NodeType const node_type(front.schema().nodeType());

        // Leaf
        if (node_type == NodeType::Leaf) {
            return translateFromYang(front);
        } else if (node_type == NodeType::Leaflist) {
            ElementPtr result(Element::createList());
            for (DataNode const& i : nodes) {
                result->add(translateFromYang(i));
            }
            return result;
        } else {
            isc_throw(NotImplemented, "getting node of type "
                                          << int(node_type) << " not supported, xpath is '" << xpath
                                          << "'");
        }

    } catch (sysrepo::Error const& ex) {
        isc_throw(NetconfError, "getting item at '" << xpath << "': " << ex.what());
    }
}

ElementPtr
Translator::getItemFromAbsoluteXpath(string const& xpath) const {
    optional<DataNode> const& data_node(getData(xpath));
    if (!data_node) {
        return ElementPtr();
    }
    return getItem(*data_node, xpath);
}

void
Translator::getMandatoryLeaf(ElementPtr& storage,
                             DataNode const& data_node,
                             string const& name) const {
    ElementPtr const& x(getItem(data_node, name));
    if (!x) {
        isc_throw(MissingNode, name);
    }
    storage->set(name, x);
}


void
Translator::getMandatoryDivergingLeaf(ElementPtr& storage,
                                      DataNode const& data_node,
                                      string const& name,
                                      string const& yang_name) const {
    ElementPtr const& x(getItem(data_node, yang_name));
    if (!x) {
        isc_throw(MissingNode, yang_name);
    }
    storage->set(name, x);
}

Translator::Deserializer
Translator::initializeDeserializer() {
    Deserializer result;

    result.emplace(LeafBaseType::Binary, [](string const& value) -> ElementPtr const {
        return Element::create(decode64(value));
    });

    for (LeafBaseType const& i :
         {LeafBaseType::Bool, LeafBaseType::Dec64, LeafBaseType::Int8, LeafBaseType::Int16,
          LeafBaseType::Int32, LeafBaseType::Int64, LeafBaseType::Uint8, LeafBaseType::Uint16,
          LeafBaseType::Uint32, LeafBaseType::Uint64}) {
        result.emplace(i, [](string const& value) -> ElementPtr const {
            return Element::fromJSON(value);
        });
    }

    // The rest of YANG values can be expressed as strings.
    for (LeafBaseType const& i :
         {LeafBaseType::Bits, LeafBaseType::Empty, LeafBaseType::Enum, LeafBaseType::IdentityRef,
          LeafBaseType::InstanceIdentifier, LeafBaseType::Leafref, LeafBaseType::String,
          LeafBaseType::Union, LeafBaseType::Unknown}) {
        result.emplace(i, [](string const& value) -> ElementPtr const {
            return Element::create(value);
        });
    }

    return result;
}

Translator::Serializer
Translator::initializeSerializer() {
    Serializer result;

    result.emplace(LeafBaseType::Binary, [](string const& value) -> string const {
        return encode64(value);
    });

    // The rest of YANG values can be expressed directly.
    for (LeafBaseType const& i :
         {LeafBaseType::Bits, LeafBaseType::Bool, LeafBaseType::Dec64, LeafBaseType::Empty,
          LeafBaseType::Enum, LeafBaseType::IdentityRef, LeafBaseType::InstanceIdentifier,
          LeafBaseType::Int8, LeafBaseType::Int16, LeafBaseType::Int32, LeafBaseType::Int64,
          LeafBaseType::Leafref, LeafBaseType::String, LeafBaseType::Uint8, LeafBaseType::Uint16,
          LeafBaseType::Uint32, LeafBaseType::Uint64, LeafBaseType::Union, LeafBaseType::Unknown}) {
        result.emplace(i, [](string const& value) -> string const {
            return value;
        });
    }

    return result;
}


bool Translator::schemaNodeExists(string const& xpath) {
    Context const& context(session_.getContext());
    try {
        context.findPath(xpath);
    } catch (libyang::Error const& ex) {
        return false;
    }
    return true;
}

void
Translator::setItem(const string& xpath, ConstElementPtr elem, LeafBaseType type) {
    optional<string> const value(translateToYang(elem, type));
    try {
        session_.setItem(xpath, value);
    } catch (sysrepo::Error const& ex) {
        isc_throw(NetconfError, "setting item '" << (elem ? elem->str() : "nullopt")
                                << "' at '" << xpath << "': " << ex.what());
    }
    session_.applyChanges();
}

void
Translator::setMandatoryLeaf(ConstElementPtr const& from,
                             string const& xpath,
                             string const& name,
                             LeafBaseType const type) {
    ConstElementPtr const& x(from->get(name));
    if (!x) {
        isc_throw(MissingNode, "xpath: " << xpath << ", name: " << name);
    }
    setItem(xpath + "/" + name, x, type);
}

void
Translator::setMandatoryDivergingLeaf(ConstElementPtr const& from,
                                      string const& xpath,
                                      string const& name,
                                      string const& yang_name,
                                      LeafBaseType const type) {
    ConstElementPtr const& x(from->get(name));
    if (!x) {
        isc_throw(MissingNode, "xpath: " << xpath << ", name: " << name);
    }
    setItem(xpath + "/" + yang_name, x, type);
}

ElementPtr
Translator::translateFromYang(optional<DataNode> data_node) {
    NodeType const node_type(data_node->schema().nodeType());
    if (node_type == NodeType::Leaf || node_type == NodeType::Leaflist) {
        DataNodeTerm const& leaf(data_node->asTerm());
        LeafBaseType type;
        if (node_type == NodeType::Leaf) {
            type = leaf.schema().asLeaf().valueType().base();
        } else {
            type = leaf.schema().asLeafList().valueType().base();
        }

        static Deserializer deserializer(initializeDeserializer());
        return deserializer.at(type)(string(leaf.valueStr()));
    }
    return ElementPtr();
}

optional<string>
Translator::translateToYang(ConstElementPtr const& element,
                            libyang::LeafBaseType const type) {
    string string_representation;
    if (!element) {
        // A null ElementPtr is how we signal that this item requires no value.
        // Useful when setting YANG lists which is the only way to set their
        // keys in sysrepo since setting the key itself results in an error.
        return nullopt;
    } else if (element->getType() == Element::map) {
        isc_throw(NotImplemented, "Translator::value(): map element");
    } else if (element->getType() == Element::list) {
        isc_throw(NotImplemented, "Translator::value(): list element");
    } else if (element->getType() == Element::string) {
        // If it's a string, get the variant wthout quotes.
        string_representation = element->stringValue();
    } else {
        // If it's not a string, also get the variant without quotes, but it's a different method.
        string_representation = element->str();
    }

    static Serializer serializer(initializeSerializer());
    return serializer.at(type)(string_representation);
}

}  // namespace yang
}  // namespace isc