Add VCA details to input file for NS initial-config-primitive
[osm/SO.git] / rwcm / plugins / rwconman / rift / tasklets / rwconmantasklet / rwconman_conagent.py
1 #
2 # Copyright 2016 RIFT.IO Inc
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16
17 import asyncio
18 import rift.tasklets
19
20 from gi.repository import (
21 RwConfigAgentYang as rwcfg_agent,
22 )
23
24 from .riftcm_config_plugin import DEFAULT_CAP_TYPE
25 from . import RiftCA
26 from . import jujuconf
27 import rift.mano.config_agent
28
29
30 class ConfigAgentError(Exception):
31 pass
32
33
34 class ConfigAgentExistsError(ConfigAgentError):
35 pass
36
37
38 class UnknownAgentTypeError(Exception):
39 pass
40
41
42 class ConfigAgentVnfrAddError(Exception):
43 pass
44
45
46 class ConfigAgentVnfrTypeError(Exception):
47 pass
48
49
50 class ConfigAccountHandler(object):
51 def __init__(self, dts, log, loop, on_add_config_agent, on_delete_config_agent):
52 self._log = log
53 self._dts = dts
54 self._loop = loop
55 self._on_add_config_agent = on_add_config_agent
56 self._on_delete_config_agent = on_delete_config_agent
57
58 self._log.debug("creating config account handler")
59 self.cloud_cfg_handler = rift.mano.config_agent.ConfigAgentSubscriber(
60 self._dts, self._log,
61 rift.mano.config_agent.ConfigAgentCallbacks(
62 on_add_apply=self.on_config_account_added,
63 on_delete_apply=self.on_config_account_deleted,
64 )
65 )
66
67 def on_config_account_deleted(self, account):
68 self._log.debug("config account deleted: %s", account.name)
69 self._on_delete_config_agent(account)
70
71 def on_config_account_added(self, account):
72 self._log.debug("config account added")
73 self._log.debug(account.as_dict())
74 self._on_add_config_agent(account)
75
76 @asyncio.coroutine
77 def register(self):
78 self.cloud_cfg_handler.register()
79
80 class RiftCMConfigPlugins(object):
81 """ NSM Config Agent Plugins """
82 def __init__(self):
83 self._plugin_classes = {
84 "juju": jujuconf.JujuConfigPlugin,
85 "riftca": RiftCA.RiftCAConfigPlugin,
86 }
87
88 @property
89 def plugins(self):
90 """ Plugin info """
91 return self._plugin_classes
92
93 def __getitem__(self, name):
94 """ Get item """
95 return self._plugin_classes[name]
96
97 def register(self, plugin_name, plugin_class, *args):
98 """ Register a plugin to this Nsm"""
99 self._plugin_classes[plugin_name] = plugin_class
100
101 def deregister(self, plugin_name, plugin_class, *args):
102 """ Deregister a plugin to this Nsm"""
103 if plugin_name in self._plugin_classes:
104 del self._plugin_classes[plugin_name]
105
106 def class_by_plugin_name(self, name):
107 """ Get class by plugin name """
108 return self._plugin_classes[name]
109
110
111 class RiftCMConfigAgent(object):
112 def __init__(self, dts, log, loop, parent):
113 self._dts = dts
114 self._log = log
115 self._loop = loop
116 self._ConfigManagerConfig = parent
117
118 self._config_plugins = RiftCMConfigPlugins()
119 self._config_handler = ConfigAccountHandler(
120 self._dts, self._log, self._loop, self._on_config_agent, self._on_config_agent_delete)
121 self._plugin_instances = {}
122 self._default_account_added = False
123
124 @asyncio.coroutine
125 def invoke_config_agent_plugins(self, method, nsr, vnfr, *args):
126 # Invoke the methods on all config agent plugins registered
127 rc = False
128 for agent in self._plugin_instances.values():
129 if not agent.is_vnfr_managed(vnfr.id):
130 continue
131 try:
132 self._log.debug("Invoke {} on {}".format(method, agent.name))
133 rc = yield from agent.invoke(method, nsr, vnfr, *args)
134 break
135 except Exception as e:
136 self._log.error("Error invoking {} on {} : {}".
137 format(method, agent.name, e))
138 raise
139
140 self._log.info("vnfr({}), method={}, return rc={}"
141 .format(vnfr.name, method, rc))
142 return rc
143
144 def get_vnfr_config_agent(self, vnfr):
145 # if (not vnfr.has_field('netconf') and
146 # not vnfr.has_field('juju') and
147 # not vnfr.has_field('script')):
148 # return False
149
150 for agent in self._plugin_instances.values():
151 try:
152 if agent.is_vnfr_managed(vnfr.id):
153 return agent
154 except Exception as e:
155 self._log.debug("Check if VNFR {} is config agent managed: {}".
156 format(vnfr.name, e))
157
158 def is_vnfr_config_agent_managed(self, vnfr):
159 if self.get_vnfr_config_agent(vnfr):
160 return True
161 return False
162
163 def _on_config_agent(self, config_agent):
164 self._log.debug("Got nsm plugin config agent account: %s", config_agent)
165 try:
166 cap_name = config_agent.name
167 cap_inst = self._config_plugins.class_by_plugin_name(
168 config_agent.account_type)
169 except KeyError as e:
170 msg = "Config agent nsm plugin type not found: {}". \
171 format(config_agent.account_type)
172 self._log.error(msg)
173 raise UnknownAgentTypeError(msg)
174
175 # Check to see if the plugin was already instantiated
176 if cap_name in self._plugin_instances:
177 self._log.debug("Config agent nsm plugin {} already instantiated. " \
178 "Using existing.". format(cap_name))
179 else:
180 # Otherwise, instantiate a new plugin using the config agent account
181 self._log.debug("Instantiting new config agent using class: %s", cap_inst)
182 new_instance = cap_inst(self._dts, self._log, self._loop, config_agent)
183 self._plugin_instances[cap_name] = new_instance
184
185 # TODO (pjoseph): See why this was added, as this deletes the
186 # Rift plugin account when Juju account is added
187 # if self._default_account_added:
188 # # If the user has provided a config account, chuck the default one.
189 # if self.DEFAULT_CAP_TYPE in self._plugin_instances:
190 # del self._plugin_instances[self.DEFAULT_CAP_TYPE]
191
192 def _on_config_agent_delete(self, config_agent):
193 self._log.debug("Got nsm plugin config agent delete, account: %s, type: %s",
194 config_agent.name, config_agent.account_type)
195 cap_name = config_agent.account_type
196 if cap_name in self._plugin_instances:
197 self._log.debug("Config agent nsm plugin exists, deleting it.")
198 del self._plugin_instances[cap_name]
199 else:
200 self._log.error("Error deleting - Config Agent nsm plugin %s does not exist.", cap_name)
201
202
203 @asyncio.coroutine
204 def register(self):
205 self._log.debug("Registering for config agent nsm plugin manager")
206 yield from self._config_handler.register()
207
208 account = rwcfg_agent.ConfigAgentAccount()
209 account.account_type = DEFAULT_CAP_TYPE
210 account.name = "RiftCA"
211 self._on_config_agent(account)
212 self._default_account_added = True
213
214 # Also grab any account already configured
215 config_agents = yield from self._ConfigManagerConfig.cmdts_obj.get_config_agents(name=None)
216 for account in config_agents:
217 self._on_config_agent(account)
218
219 def set_config_agent(self, nsr, vnfr, method):
220 if method == 'juju':
221 agent_type = 'juju'
222 elif method in ['netconf', 'script']:
223 agent_type = DEFAULT_CAP_TYPE
224 else:
225 msg = "Unsupported configuration method ({}) for VNF:{}/{}". \
226 format(method, nsr.name, vnfr.name)
227 self._log.error(msg)
228 raise UnknownAgentTypeError(msg)
229
230 try:
231 acc_map = nsr.nsr_cfg_msg.vnf_cloud_account_map
232 except AttributeError:
233 self._log.debug("Did not find cloud account map for NS {}".
234 format(nsr.name))
235 acc_map = []
236
237 for vnfd in acc_map:
238 if vnfd.config_agent_account is not None:
239 if vnfd.member_vnf_index_ref == vnfr.vnfr_msg.member_index:
240 for agent in self._plugin_instances:
241 # Find the plugin with the same name
242 if agent == vnfd.config_agent_account:
243 # Check if the types are same
244 if self._plugin_instances[agent].agent_type != agent_type:
245 msg = "VNF {} specified config agent {} is not of type {}". \
246 format(vnfr.name, agent, agent_type)
247 self._log.error(msg)
248 raise ConfigAgentVnfrTypeError(msg)
249
250 self._plugin_instances[agent].add_vnfr_managed(vnfr)
251 self._log.debug("Added vnfr {} as config plugin {} managed".
252 format(vnfr.name, agent))
253 return
254
255 # If no config agent specified for the VNF, use the
256 # first available of the same type
257 for agent in self._plugin_instances:
258 if self._plugin_instances[agent].agent_type == agent_type:
259 self._plugin_instances[agent].add_vnfr_managed(vnfr)
260 self._log.debug("Added vnfr {} as config plugin {} managed".
261 format(vnfr.name, agent))
262 return
263
264 msg = "Error finding config agent of type {} for VNF {}". \
265 format(agent_type, vnfr.name)
266 self._log.error(msg)
267 raise ConfigAgentVnfrAddError(msg)