Refactor to make file sys more like class inheritance
[yardstick.git] / yardstick / benchmark / contexts / standalone / __init__.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 """This module handle non managed standalone virtualization node."""
15
16 from __future__ import absolute_import
17 import logging
18 import os
19 import errno
20 import collections
21 import time
22
23 from yardstick.benchmark.contexts.base import Context
24 from yardstick.common.constants import YARDSTICK_ROOT_PATH
25 from yardstick.common.utils import import_modules_from_package, itersubclasses
26 from yardstick.common.yaml_loader import yaml_load
27
28 LOG = logging.getLogger(__name__)
29
30
31 class StandaloneContext(Context):
32     """ This class handles standalone nodes - VM running on Non-Managed NFVi
33     Configuration: vswitch, ovs, ovs-dpdk, sr-iov, linuxbridge
34     """
35
36     __context_type__ = "Standalone"
37
38     def __init__(self):
39         self.name = None
40         self.file_path = None
41         self.nodes = []
42         self.networks = {}
43         self.nfvi_node = []
44         self.nfvi_obj = None
45         self.attrs = {}
46         super(StandaloneContext, self).__init__()
47
48     def read_config_file(self):
49         """Read from config file"""
50
51         with open(self.file_path) as stream:
52             LOG.info("Parsing pod file: %s", self.file_path)
53             cfg = yaml_load(stream)
54         return cfg
55
56     def get_nfvi_obj(self):
57         print("{0}".format(self.nfvi_node[0]['role']))
58         context_type = self.get_context_impl(self.nfvi_node[0]['role'])
59         nfvi_obj = context_type()
60         nfvi_obj.__init__()
61         nfvi_obj.parse_pod_and_get_data(self.file_path)
62         return nfvi_obj
63
64     def init(self, attrs):
65         """initializes itself from the supplied arguments"""
66
67         self.name = attrs["name"]
68         self.file_path = file_path = attrs.get("file", "pod.yaml")
69
70         try:
71             cfg = self.read_config_file()
72         except IOError as io_error:
73             if io_error.errno != errno.ENOENT:
74                 raise
75             self.file_path = os.path.join(YARDSTICK_ROOT_PATH, file_path)
76             cfg = self.read_config_file()
77
78         self.vm_deploy = attrs.get("vm_deploy", True)
79         self.nodes.extend([node for node in cfg["nodes"]
80                            if str(node["role"]) != "Sriov" and
81                            str(node["role"]) != "Ovsdpdk"])
82         for node in cfg["nodes"]:
83             if str(node["role"]) == "Sriov":
84                 self.nfvi_node.extend([node for node in cfg["nodes"]
85                                        if str(node["role"]) == "Sriov"])
86             if str(node["role"]) == "Ovsdpdk":
87                 self.nfvi_node.extend([node for node in cfg["nodes"]
88                                        if str(node["role"]) == "Ovsdpdk"])
89                 LOG.info("{0}".format(node["role"]))
90             else:
91                 LOG.debug("Node role is other than SRIOV and OVS")
92         self.nfvi_obj = self.get_nfvi_obj()
93         self.attrs = attrs
94         # add optional static network definition
95         self.networks.update(cfg.get("networks", {}))
96         self.nfvi_obj = self.get_nfvi_obj()
97         LOG.debug("Nodes: %r", self.nodes)
98         LOG.debug("NFVi Node: %r", self.nfvi_node)
99         LOG.debug("Networks: %r", self.networks)
100
101     def deploy(self):
102         """don't need to deploy"""
103
104         # Todo: NFVi deploy (sriov, vswitch, ovs etc) based on the config.
105         if not self.vm_deploy:
106             return
107
108         #    Todo: NFVi deploy (sriov, vswitch, ovs etc) based on the config.
109         self.nfvi_obj.ssh_remote_machine()
110         if self.nfvi_obj.first_run is True:
111             self.nfvi_obj.install_req_libs()
112
113         nic_details = self.nfvi_obj.get_nic_details()
114         print("{0}".format(nic_details))
115
116         if self.nfvi_node[0]["role"] == "Sriov":
117             self.nfvi_obj.setup_sriov_context(
118                 self.nfvi_obj.sriov[0]['phy_ports'],
119                 nic_details,
120                 self.nfvi_obj.sriov[0]['phy_driver'])
121         if self.nfvi_node[0]["role"] == "Ovsdpdk":
122             self.nfvi_obj.setup_ovs(self.nfvi_obj.ovs[0]["phy_ports"])
123             self.nfvi_obj.start_ovs_serverswitch()
124             time.sleep(5)
125             self.nfvi_obj.setup_ovs_bridge()
126             self.nfvi_obj.add_oflows()
127             self.nfvi_obj.setup_ovs_context(
128                 self.nfvi_obj.ovs[0]['phy_ports'],
129                 nic_details,
130                 self.nfvi_obj.ovs[0]['phy_driver'])
131             pass
132
133     def undeploy(self):
134         """don't need to undeploy"""
135
136         if not self.vm_deploy:
137             return
138         # Todo: NFVi undeploy (sriov, vswitch, ovs etc) based on the config.
139         # self.nfvi_obj = self.get_nfvi_obj()
140         self.nfvi_obj.ssh_remote_machine()
141         self.nfvi_obj.destroy_vm()
142         pass
143
144     def _get_server(self, attr_name):
145         """lookup server info by name from context
146
147         Keyword arguments:
148         attr_name -- A name for a server listed in nodes config file
149         """
150         node_name, name = self.split_name(attr_name)
151         if name is None or self.name != name:
152             return None
153
154         matching_nodes = (n for n in self.nodes if n["name"] == node_name)
155         try:
156             # A clone is created in order to avoid affecting the
157             # original one.
158             node = dict(next(matching_nodes))
159         except StopIteration:
160             return None
161
162         try:
163             duplicate = next(matching_nodes)
164         except StopIteration:
165             pass
166         else:
167             raise ValueError("Duplicate nodes!!! Nodes: %s %s",
168                              (node, duplicate))
169
170         node["name"] = attr_name
171         return node
172
173     def _get_network(self, attr_name):
174         if not isinstance(attr_name, collections.Mapping):
175             network = self.networks.get(attr_name)
176
177         else:
178             # Don't generalize too much  Just support vld_id
179             vld_id = attr_name.get('vld_id', {})
180             # for standalone context networks are dicts
181             iter1 = (n for n in self.networks.values() if n.get('vld_id') == vld_id)
182             network = next(iter1, None)
183
184         if network is None:
185             return None
186
187         result = {
188             # name is required
189             "name": network["name"],
190             "vld_id": network.get("vld_id"),
191             "segmentation_id": network.get("segmentation_id"),
192             "network_type": network.get("network_type"),
193             "physical_network": network.get("physical_network"),
194         }
195         return result
196
197     def get_context_impl(self, nfvi_type):
198         """ Find the implementing class from vnf_model["vnf"]["name"] field
199
200         :param vnf_model: dictionary containing a parsed vnfd
201         :return: subclass of GenericVNF
202         """
203         import_modules_from_package(
204             "yardstick.benchmark.contexts")
205         expected_name = nfvi_type
206         impl = [c for c in itersubclasses(StandaloneContext)
207                 if c.__name__ == expected_name]
208         try:
209             return next(iter(impl))
210         except StopIteration:
211             raise ValueError("No implementation for %s", expected_name)