BUG 402 : Raising Exception if the charm directory is not found
[osm/SO.git] / rwcm / plugins / rwconman / rift / tasklets / rwconmantasklet / jujuconf.py
index 5068b31..b003df8 100644 (file)
@@ -25,8 +25,9 @@ import rift.mano.utils.juju_api as juju
 from . import riftcm_config_plugin
 
 
-# Charm service name accepts only a to z and -.
 def get_vnf_unique_name(nsr_name, vnfr_name, member_vnf_index):
+    """Get the unique VNF name.
+    Charm names accepts only a to z and non-consecutive - characters."""
     name = "{}-{}-{}".format(nsr_name, vnfr_name, member_vnf_index)
     new_name = ''
     for c in name:
@@ -35,7 +36,7 @@ def get_vnf_unique_name(nsr_name, vnfr_name, member_vnf_index):
         elif not c.isalpha():
             c = "-"
         new_name += c
-    return new_name.lower()
+    return re.sub('\-+', '-', new_name.lower())
 
 
 class JujuConfigPlugin(riftcm_config_plugin.RiftCMConfigPluginBase):
@@ -185,13 +186,15 @@ class JujuConfigPlugin(riftcm_config_plugin.RiftCMConfigPluginBase):
                                 'launchpad/packages/vnfd',
                                 self._project.name,
                                 agent_vnfr.vnfr_msg.vnfd.id,
-                                'charms/trusty',
+                                'charms',
                                 charm)
             self._log.debug("jujuCA: Charm dir is {}".format(path))
             if not os.path.isdir(path):
-                self._log.error("jujuCA: Did not find the charm directory at {}".
-                                format(path))
+                msg = "jujuCA: Did not find the charm directory at {}".format(path)
+                self._log.error(msg)
                 path = None
+                # Return from here instead of forwarding the config request to juju_api
+                raise Exception(msg)
         except Exception as e:
             self.log.exception(e)
             return False
@@ -199,12 +202,13 @@ class JujuConfigPlugin(riftcm_config_plugin.RiftCMConfigPluginBase):
         if vnf_unique_name not in self._tasks:
             self._tasks[vnf_unique_name] = {}
 
-        self._tasks[vnf_unique_name]['deploy'] = self.loop.create_task(
-            self.api.deploy_application(charm, vnf_unique_name, path=path))
-
         self._log.debug("jujuCA: Deploying service %s",
                         vnf_unique_name)
-
+        yield from self.api.deploy_application(
+            charm,
+            vnf_unique_name,
+            path=path,
+        )
         return True
 
     @asyncio.coroutine
@@ -239,19 +243,18 @@ class JujuConfigPlugin(riftcm_config_plugin.RiftCMConfigPluginBase):
             vnfr = agent_vnfr.vnfr
             service = vnfr['vnf_juju_name']
 
-            self._log.debug ("jujuCA: Terminating VNFr %s, %s",
-                             agent_vnfr.name, service)
-            self._tasks[service]['destroy'] = self.loop.create_task(
-                    self.api.remove_application(service)
-                )
+            self._log.debug("jujuCA: Terminating VNFr {}, {}".format(
+                agent_vnfr.name,
+                service,
+            ))
+            yield from self.api.remove_application(service)
 
             del self._juju_vnfs[agent_vnfr.id]
-            self._log.debug ("jujuCA: current vnfrs={}".
-                             format(self._juju_vnfs))
+            self._log.debug("jujuCA: current vnfrs={}".
+                            format(self._juju_vnfs))
             if service in self._tasks:
                 tasks = []
                 for action in self._tasks[service].keys():
-                    #if self.check_task_status(service, action):
                     tasks.append(action)
                 del tasks
         except KeyError as e:
@@ -270,35 +273,6 @@ class JujuConfigPlugin(riftcm_config_plugin.RiftCMConfigPluginBase):
         """
         return True
 
-    def check_task_status(self, service, action):
-        #self.log.debug("jujuCA: check task status for %s, %s" % (service, action))
-        try:
-            task = self._tasks[service][action]
-            if task.done():
-                self.log.debug("jujuCA: Task for %s, %s done" % (service, action))
-                e = task.exception()
-                if e:
-                    self.log.error("jujuCA: Error in task for {} and {} : {}".
-                                   format(service, action, e))
-                    raise Exception(e)
-                r= task.result()
-                if r:
-                    self.log.debug("jujuCA: Task for {} and {}, returned {}".
-                                   format(service, action,r))
-                return True
-            else:
-                self.log.debug("jujuCA: task {}, {} not done".
-                               format(service, action))
-                return False
-        except KeyError as e:
-            self.log.error("jujuCA: KeyError for task for {} and {}: {}".
-                           format(service, action, e))
-        except Exception as e:
-            self.log.error("jujuCA: Error for task for {} and {}: {}".
-                           format(service, action, e))
-            raise
-        return True
-
     @asyncio.coroutine
     def _vnf_config_primitive(self, nsr_id, vnfr_id, primitive,
                               vnf_config=None, wait=False):
@@ -559,6 +533,7 @@ class JujuConfigPlugin(riftcm_config_plugin.RiftCMConfigPluginBase):
 
         try:
             vnfr = self._juju_vnfs[agent_vnfr.id].vnfr
+            service = vnfr['vnf_juju_name']
         except KeyError:
             self._log.debug("Did not find VNFR %s in Juju plugin",
                             agent_vnfr.name)
@@ -587,7 +562,6 @@ class JujuConfigPlugin(riftcm_config_plugin.RiftCMConfigPluginBase):
         if not rc:
             return False
 
-        # action_ids = []
         try:
             if vnfr_msg.mgmt_interface.ip_address:
                 vnfr['tags'].update({'rw_mgmt_ip': vnfr_msg.mgmt_interface.ip_address})
@@ -619,9 +593,6 @@ class JujuConfigPlugin(riftcm_config_plugin.RiftCMConfigPluginBase):
                         self._log.error(msg)
                         return False
 
-                    elif rc == "pending":
-                        action_ids.append(eid)
-
                 elif primitive.name:
                     config = {}
                     if primitive.name == 'config':
@@ -630,57 +601,44 @@ class JujuConfigPlugin(riftcm_config_plugin.RiftCMConfigPluginBase):
                                 val = self.xlate(param.value,
                                                  vnfr['tags'])
                                 config.update({param.name: val})
-            except KeyError as e:
-                self._log.exception("jujuCA:(%s) Initial config error(%s): config=%s",
-                                    vnfr['vnf_juju_name'], str(e), config)
-                config = None
-                return False
-
-            if config:
-                self.juju_log('info', vnfr['vnf_juju_name'],
-                              "Applying Initial config:%s",
-                              config)
-
-                rc = yield from self.api.apply_config(
-                    config,
-                    application=service,
-                )
-                if rc is False:
-                    self.log.error("Service {} is in error state".format(service))
-                    return False
 
                         if config:
                             self.juju_log('info', vnfr['vnf_juju_name'],
                                           "Applying Initial config:%s",
                                           config)
 
-            # Apply any actions specified as part of initial config
-            for primitive in vnfr['config'].initial_config_primitive:
-                if primitive.name != 'config':
-                    self._log.debug("jujuCA:(%s) Initial config action primitive %s",
-                                    vnfr['vnf_juju_name'], primitive)
-                    action = primitive.name
-                    params = {}
-                    for param in primitive.parameter:
-                        val = self.xlate(param.value, vnfr['tags'])
-                        params.update({param.name: val})
-
-                    self._log.info("jujuCA:(%s) Action %s with params %s",
-                                   vnfr['vnf_juju_name'], action, params)
-                    self._log.debug("executing action")
-                    resp = yield from self.api.execute_action(
-                        service,
-                        action,
-                        **params,
-                    )
-                    self._log.debug("executed action")
-                    if 'error' in resp:
-                        self._log.error("Applying initial config on {} failed for {} with {}: {}".
-                                        format(vnfr['vnf_juju_name'], action, params, resp))
-                        return False
-
-                    # action_ids.append(resp['action']['tag'])
-                    # action_ids.append(resp)
+                            rc = yield from self.api.apply_config(
+                                config,
+                                application=service,
+                            )
+                            if rc is False:
+                                self.log.error("Service {} is in error state".format(service))
+                                return False
+                    else:
+                        # Apply any actions specified as part of initial config
+                        for primitive in vnfr['config'].initial_config_primitive:
+                            if primitive.name != 'config':
+                                self._log.debug("jujuCA:(%s) Initial config action primitive %s",
+                                                vnfr['vnf_juju_name'], primitive)
+                                action = primitive.name
+                                params = {}
+                                for param in primitive.parameter:
+                                    val = self.xlate(param.value, vnfr['tags'])
+                                    params.update({param.name: val})
+
+                                self._log.info("jujuCA:(%s) Action %s with params %s",
+                                               vnfr['vnf_juju_name'], action, params)
+                                self._log.debug("executing action")
+                                resp = yield from self.api.execute_action(
+                                    service,
+                                    action,
+                                    **params,
+                                )
+                                self._log.debug("executed action")
+                                if 'error' in resp:
+                                    self._log.error("Applying initial config on {} failed for {} with {}: {}".
+                                                    format(vnfr['vnf_juju_name'], action, params, resp))
+                                    return False
         except KeyError as e:
             self._log.info("Juju config agent(%s): VNFR %s not managed by Juju",
                            vnfr['vnf_juju_name'], agent_vnfr.id)
@@ -748,12 +706,13 @@ class JujuConfigPlugin(riftcm_config_plugin.RiftCMConfigPluginBase):
 
         rc = 'configuring'
 
-        if not self.check_task_status(service, 'deploy'):
-            return rc
-
         try:
-            resp = yield from self.api.get_service_status(application=service)
-            self._log.debug("jujuCA: Get service %s status? %s", service, resp)
+            # Get the status of the application
+            resp = yield from self.api.get_application_status(service)
+
+            # No status means the application is still pending deployment
+            if resp is None:
+                return rc
 
             if resp == 'error':
                 return 'error'