543e51b0148e866841372e785768b572984befb6
[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 is_vnfr_config_agent_managed(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 True
154 except Exception as e:
155 self._log.debug("Check if VNFR {} is config agent managed: {}".
156 format(vnfr.name, e))
157 return False
158
159 def _on_config_agent(self, config_agent):
160 self._log.debug("Got nsm plugin config agent account: %s", config_agent)
161 try:
162 cap_name = config_agent.name
163 cap_inst = self._config_plugins.class_by_plugin_name(
164 config_agent.account_type)
165 except KeyError as e:
166 msg = "Config agent nsm plugin type not found: {}". \
167 format(config_agent.account_type)
168 self._log.error(msg)
169 raise UnknownAgentTypeError(msg)
170
171 # Check to see if the plugin was already instantiated
172 if cap_name in self._plugin_instances:
173 self._log.debug("Config agent nsm plugin {} already instantiated. " \
174 "Using existing.". format(cap_name))
175 else:
176 # Otherwise, instantiate a new plugin using the config agent account
177 self._log.debug("Instantiting new config agent using class: %s", cap_inst)
178 new_instance = cap_inst(self._dts, self._log, self._loop, config_agent)
179 self._plugin_instances[cap_name] = new_instance
180
181 # TODO (pjoseph): See why this was added, as this deletes the
182 # Rift plugin account when Juju account is added
183 # if self._default_account_added:
184 # # If the user has provided a config account, chuck the default one.
185 # if self.DEFAULT_CAP_TYPE in self._plugin_instances:
186 # del self._plugin_instances[self.DEFAULT_CAP_TYPE]
187
188 def _on_config_agent_delete(self, config_agent):
189 self._log.debug("Got nsm plugin config agent delete, account: %s, type: %s",
190 config_agent.name, config_agent.account_type)
191 cap_name = config_agent.account_type
192 if cap_name in self._plugin_instances:
193 self._log.debug("Config agent nsm plugin exists, deleting it.")
194 del self._plugin_instances[cap_name]
195 else:
196 self._log.error("Error deleting - Config Agent nsm plugin %s does not exist.", cap_name)
197
198
199 @asyncio.coroutine
200 def register(self):
201 self._log.debug("Registering for config agent nsm plugin manager")
202 yield from self._config_handler.register()
203
204 account = rwcfg_agent.ConfigAgentAccount()
205 account.account_type = DEFAULT_CAP_TYPE
206 account.name = "RiftCA"
207 self._on_config_agent(account)
208 self._default_account_added = True
209
210 # Also grab any account already configured
211 config_agents = yield from self._ConfigManagerConfig.cmdts_obj.get_config_agents(name=None)
212 for account in config_agents:
213 self._on_config_agent(account)
214
215 def set_config_agent(self, nsr, vnfr, method):
216 if method == 'juju':
217 agent_type = 'juju'
218 elif method in ['netconf', 'script']:
219 agent_type = DEFAULT_CAP_TYPE
220 else:
221 msg = "Unsupported configuration method ({}) for VNF:{}/{}". \
222 format(method, nsr.name, vnfr.name)
223 self._log.error(msg)
224 raise UnknownAgentTypeError(msg)
225
226 try:
227 acc_map = nsr.nsr_cfg_msg.vnf_cloud_account_map
228 except AttributeError:
229 self._log.debug("Did not find cloud account map for NS {}".
230 format(nsr.name))
231 acc_map = []
232
233 for vnfd in acc_map:
234 if vnfd.config_agent_account is not None:
235 if vnfd.member_vnf_index_ref == vnfr.vnfr_msg.member_index:
236 for agent in self._plugin_instances:
237 # Find the plugin with the same name
238 if agent == vnfd.config_agent_account:
239 # Check if the types are same
240 if self._plugin_instances[agent].agent_type != agent_type:
241 msg = "VNF {} specified config agent {} is not of type {}". \
242 format(vnfr.name, agent, agent_type)
243 self._log.error(msg)
244 raise ConfigAgentVnfrTypeError(msg)
245
246 self._plugin_instances[agent].add_vnfr_managed(vnfr)
247 self._log.debug("Added vnfr {} as config plugin {} managed".
248 format(vnfr.name, agent))
249 return
250
251 # If no config agent specified for the VNF, use the
252 # first available of the same type
253 for agent in self._plugin_instances:
254 if self._plugin_instances[agent].agent_type == agent_type:
255 self._plugin_instances[agent].add_vnfr_managed(vnfr)
256 self._log.debug("Added vnfr {} as config plugin {} managed".
257 format(vnfr.name, agent))
258 return
259
260 msg = "Error finding config agent of type {} for VNF {}". \
261 format(agent_type, vnfr.name)
262 self._log.error(msg)
263 raise ConfigAgentVnfrAddError(msg)