Merge "standardize ssh auth"
[yardstick.git] / yardstick / network_services / vnf_generic / vnfdgen.py
1 # Copyright (c) 2016-2017 Intel Corporation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """ Generic file to map and build vnf discriptor """
15
16 from __future__ import absolute_import
17 import collections
18 import yaml
19
20 from yardstick.common.task_template import TaskTemplate
21
22
23 def generate_vnfd(vnf_model, node):
24     """
25
26     :param vnf_model: VNF definition template, e.g. tg_ping_tpl.yaml
27     :param node: node configuration taken from pod.yaml
28     :return: Complete VNF Descriptor that will be taken
29              as input for GenericVNF.__init__
30     """
31     # get is unused as global method inside template
32     node["get"] = get
33     # Set Node details to default if not defined in pod file
34     rendered_vnfd = TaskTemplate.render(vnf_model, **node)
35     # This is done to get rid of issues with serializing node
36     del node["get"]
37     filled_vnfd = yaml.load(rendered_vnfd)
38     return filled_vnfd
39
40
41 def dict_key_flatten(data):
42     """ Convert nested dict structure to dotted key
43         (e.g. {"a":{"b":1}} -> {"a.b":1}
44
45     :param data: nested dictionary
46     :return: flat dicrionary
47     """
48     next_data = {}
49
50     # check for non-string iterables
51     if not any((isinstance(v, collections.Iterable) and not isinstance(v, str))
52                for v in data.values()):
53         return data
54
55     for key, val in data.items():
56         if isinstance(val, collections.Mapping):
57             for n_k, n_v in val.items():
58                 next_data["%s.%s" % (key, n_k)] = n_v
59         elif isinstance(val, collections.Iterable) and not isinstance(val,
60                                                                       str):
61             for index, item in enumerate(val):
62                 next_data["%s%d" % (key, index)] = item
63         else:
64             next_data[key] = val
65
66     return dict_key_flatten(next_data)
67
68
69 def get(obj, key, *args):
70     """ Get template key from dictionary, get default value or raise an exception
71     """
72     data = dict_key_flatten(obj)
73     return data.get(key, *args)