update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
[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, project, on_add_config_agent, on_delete_config_agent):
52 self._log = log
53 self._dts = dts
54 self._loop = loop
55 self._project = project
56 self._on_add_config_agent = on_add_config_agent
57 self._on_delete_config_agent = on_delete_config_agent
58
59 self._log.debug("creating config account handler")
60 self.cloud_cfg_handler = rift.mano.config_agent.ConfigAgentSubscriber(
61 self._dts, self._log, self._project,
62 rift.mano.config_agent.ConfigAgentCallbacks(
63 on_add_apply=self.on_config_account_added,
64 on_delete_apply=self.on_config_account_deleted,
65 )
66 )
67
68 def on_config_account_deleted(self, account):
69 self._log.debug("config account deleted: %s", account.name)
70 self._on_delete_config_agent(account)
71
72 def on_config_account_added(self, account):
73 self._log.debug("config account added")
74 self._log.debug(account.as_dict())
75 self._on_add_config_agent(account)
76
77 @asyncio.coroutine
78 def register(self):
79 self.cloud_cfg_handler.register()
80
81 def deregister(self):
82 self.cloud_cfg_handler.deregister()
83
84
85 class RiftCMConfigPlugins(object):
86 """ NSM Config Agent Plugins """
87 def __init__(self):
88 self._plugin_classes = {
89 "juju": jujuconf.JujuConfigPlugin,
90 "riftca": RiftCA.RiftCAConfigPlugin,
91 }
92
93 @property
94 def plugins(self):
95 """ Plugin info """
96 return self._plugin_classes
97
98 def __getitem__(self, name):
99 """ Get item """
100 return self._plugin_classes[name]
101
102 def register(self, plugin_name, plugin_class, *args):
103 """ Register a plugin to this Nsm"""
104 self._plugin_classes[plugin_name] = plugin_class
105
106 def deregister(self, plugin_name, plugin_class, *args):
107 """ Deregister a plugin to this Nsm"""
108 if plugin_name in self._plugin_classes:
109 del self._plugin_classes[plugin_name]
110
111 def class_by_plugin_name(self, name):
112 """ Get class by plugin name """
113 return self._plugin_classes[name]
114
115
116 class RiftCMConfigAgent(object):
117 def __init__(self, dts, log, loop, parent):
118 self._dts = dts
119 self._log = log
120 self._loop = loop
121 self._ConfigManagerConfig = parent
122
123 self._config_plugins = RiftCMConfigPlugins()
124 self._config_handler = ConfigAccountHandler(
125 self._dts, self._log, self._loop, parent._project,
126 self._on_config_agent, self._on_config_agent_delete)
127 self._plugin_instances = {}
128 self._default_account_added = False
129
130 @asyncio.coroutine
131 def invoke_config_agent_plugins(self, method, nsr, vnfr, *args):
132 # Invoke the methods on all config agent plugins registered
133 rc = True
134
135 for agent in self._plugin_instances.values():
136 if not agent.is_vnfr_managed(vnfr.id):
137 continue
138 try:
139 self._log.debug("Invoke {} on {}".format(method, agent.name))
140 rc = yield from agent.invoke(method, nsr, vnfr, *args)
141 break
142 except Exception as e:
143 self._log.exception("Error invoking {} on {} : {}".
144 format(method, agent.name, e))
145 raise e
146
147 self._log.info("vnfr({}), method={}, return rc={}"
148 .format(vnfr.name, method, rc))
149 return rc
150
151 def get_vnfr_config_agent(self, vnfr):
152 for agent in self._plugin_instances.values():
153 try:
154 if agent.is_vnfr_managed(vnfr.id):
155 return agent
156 except Exception as e:
157 self._log.debug("Check if VNFR {} is config agent managed: {}".
158 format(vnfr.name, e))
159
160 def is_vnfr_config_agent_managed(self, vnfr):
161 if self.get_vnfr_config_agent(vnfr):
162 return True
163 return False
164
165 def _on_config_agent(self, config_agent):
166 self._log.debug("Got nsm plugin config agent account: %s", config_agent)
167 try:
168 cap_name = config_agent.name
169 cap_inst = self._config_plugins.class_by_plugin_name(
170 config_agent.account_type)
171 except KeyError as e:
172 msg = "Config agent nsm plugin type not found: {}". \
173 format(config_agent.account_type)
174 self._log.error(msg)
175 raise UnknownAgentTypeError(msg)
176
177 # Check to see if the plugin was already instantiated
178 if cap_name in self._plugin_instances:
179 self._log.debug("Config agent nsm plugin {} already instantiated. " \
180 "Using existing.". format(cap_name))
181 else:
182 # Otherwise, instantiate a new plugin using the config agent account
183 self._log.debug("Instantiting new config agent using class: %s", cap_inst)
184 new_instance = cap_inst(self._dts, self._log, self._loop,
185 self._ConfigManagerConfig._project, config_agent)
186 self._plugin_instances[cap_name] = new_instance
187
188 # TODO (pjoseph): See why this was added, as this deletes the
189 # Rift plugin account when Juju account is added
190 # if self._default_account_added:
191 # # If the user has provided a config account, chuck the default one.
192 # if self.DEFAULT_CAP_TYPE in self._plugin_instances:
193 # del self._plugin_instances[self.DEFAULT_CAP_TYPE]
194
195 def _on_config_agent_delete(self, config_agent):
196 self._log.debug("Got nsm plugin config agent delete, account: %s, type: %s",
197 config_agent.name, config_agent.account_type)
198 cap_name = config_agent.name
199 if cap_name in self._plugin_instances:
200 self._log.debug("Config agent nsm plugin exists, deleting it.")
201 del self._plugin_instances[cap_name]
202 else:
203 self._log.error("Error deleting - Config Agent nsm plugin %s does not exist.", cap_name)
204
205
206 @asyncio.coroutine
207 def register(self):
208 self._log.debug("Registering for config agent nsm plugin manager")
209 yield from self._config_handler.register()
210
211 account = rwcfg_agent.YangData_RwProject_Project_ConfigAgent_Account()
212 account.account_type = DEFAULT_CAP_TYPE
213 account.name = "RiftCA"
214 self._on_config_agent(account)
215 self._default_account_added = True
216
217 # Also grab any account already configured
218 config_agents = yield from self._ConfigManagerConfig.cmdts_obj.get_config_agents(name=None)
219 for account in config_agents:
220 self._on_config_agent(account)
221
222 def deregister(self):
223 self._log.debug("De-registering config agent nsm plugin manager".
224 format(self._ConfigManagerConfig._project))
225 self._config_handler.deregister()
226
227 def set_config_agent(self, nsr, vnfr, method):
228 if method == 'juju':
229 agent_type = 'juju'
230 elif method in ['script']:
231 agent_type = DEFAULT_CAP_TYPE
232 else:
233 msg = "Unsupported configuration method ({}) for VNF:{}/{}". \
234 format(method, nsr.name, vnfr.name)
235 self._log.error(msg)
236 raise UnknownAgentTypeError(msg)
237
238 try:
239 acc_map = nsr.nsr_cfg_msg.vnf_cloud_account_map
240 except AttributeError:
241 self._log.debug("Did not find cloud account map for NS {}".
242 format(nsr.name))
243 acc_map = []
244
245 for vnfd in acc_map:
246 if vnfd.config_agent_account is not None:
247 if vnfd.member_vnf_index_ref == vnfr.vnfr_msg.member_index:
248 for agent in self._plugin_instances:
249 # Find the plugin with the same name
250 if agent == vnfd.config_agent_account:
251 # Check if the types are same
252 if self._plugin_instances[agent].agent_type != agent_type:
253 msg = "VNF {} specified config agent {} is not of type {}". \
254 format(vnfr.name, agent, agent_type)
255 self._log.error(msg)
256 raise ConfigAgentVnfrTypeError(msg)
257
258 self._plugin_instances[agent].add_vnfr_managed(vnfr)
259 self._log.debug("Added vnfr {} as config plugin {} managed".
260 format(vnfr.name, agent))
261 return
262
263 # If no config agent specified for the VNF, use the
264 # first available of the same type
265 for agent in self._plugin_instances:
266 if self._plugin_instances[agent].agent_type == agent_type:
267 self._plugin_instances[agent].add_vnfr_managed(vnfr)
268 self._log.debug("Added vnfr from {} from default CAs as config plugin {} managed".
269 format(vnfr.name, agent))
270 return
271
272 msg = "Error finding config agent of type {} for VNF {}". \
273 format(agent_type, vnfr.name)
274 self._log.error(msg)
275 raise ConfigAgentVnfrAddError(msg)