CORD-2748 Automatically restart TOSCA engine when connection terminates

Change-Id: Id70442e274cd68eea47de67c98f6c62b7330f764
diff --git a/src/grpc_client/main.py b/src/grpc_client/main.py
index edda57c..fc64ef3 100644
--- a/src/grpc_client/main.py
+++ b/src/grpc_client/main.py
@@ -49,6 +49,7 @@
             self.client.session_change = True
 
         self.client = InsecureClient(endpoint=self.grpc_insecure_endpoint)
+        self.client.restart_on_disconnect = True
 
         self.client.set_reconnect_callback(functools.partial(deferred.callback, self.client))
         self.client.start()
@@ -66,6 +67,7 @@
         else:
             local_cert = Config.get('local_cert')
             client = SecureClient(endpoint=self.grpc_secure_endpoint, username=username, password=password, cacert=local_cert)
+            client.restart_on_disconnect = True
             client.set_reconnect_callback(functools.partial(self.setup_resources, client, key, deferred, recipe))
             client.start()
         return deferred
diff --git a/src/main.py b/src/main.py
index 6f0db8d..0d56392 100644
--- a/src/main.py
+++ b/src/main.py
@@ -43,6 +43,12 @@
     def start(self):
         print "[XOS-TOSCA] Starting"
 
+        # Remove generated TOSCA and KEYS that may have been downloaded by a previous session. This is done here, rather
+        # than in the generator, to cover the case where the TOSCA engine is restarted and a web request is received
+        # and processed before generate_tosca() has completed. 
+        TOSCA_Generator().clean()
+        TOSCA_Generator().clean_keys()
+
         grpc_setup = GRPC_Client().start()
         grpc_setup.addCallback(self.generate_tosca)
 
diff --git a/src/tosca/generator.py b/src/tosca/generator.py
index 6d82150..13472f9 100644
--- a/src/tosca/generator.py
+++ b/src/tosca/generator.py
@@ -26,15 +26,19 @@
 
 class TOSCA_Generator:
 
-    def _clean(self, dir=TOSCA_DEFS_DIR):
+    def clean(self, dir=TOSCA_DEFS_DIR):
         filesToRemove = [f for f in os.listdir(dir)]
         for f in filesToRemove:
             if not f.startswith('.'):
                 os.remove(dir + '/' + f)
 
+    def clean_keys(self, dir=TOSCA_KEYS_DIR):
+        keys_fn = os.path.join(dir, "KEYS.py")
+        if os.path.exists(keys_fn):
+            os.remove(keys_fn)
+
     def generate(self, client):
         print "[XOS-TOSCA] Generating TOSCA"
-        self._clean()
 
         try:
             xproto = client.utility.GetXproto(Empty())