update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
[osm/SO.git] / examples / ping_pong_ns / rift / mano / examples / start_traffic.py
index af6f62f..a65321f 100755 (executable)
@@ -31,8 +31,8 @@ def start_traffic(yaml_cfg, logger):
     '''Use curl and set admin status to enable on pong and ping vnfs'''
 
     def enable_service(mgmt_ip, port, vnf_type):
-        curl_cmd = 'curl -D /dev/stdout -H "Accept: application/vnd.yang.data' \
-                   '+xml" -H "Content-Type: application/vnd.yang.data+json" ' \
+        curl_cmd = 'curl -D /dev/null -H "Accept: application/json" ' \
+                   '-H "Content-Type: application/json" ' \
                    '-X POST -d "{{\\"enable\\":true}}" http://{mgmt_ip}:' \
                    '{mgmt_port}/api/v1/{vnf_type}/adminstatus/state'. \
                    format(
@@ -40,8 +40,39 @@ def start_traffic(yaml_cfg, logger):
                        mgmt_port=port,
                        vnf_type=vnf_type)
 
-        logger.debug("Executing cmd: %s", curl_cmd)
-        subprocess.check_call(curl_cmd, shell=True)
+        count = 0
+        delay = 10
+        max_tries = 10
+        while True:
+            count += 1
+
+            logger.debug("Executing cmd: %s", curl_cmd)
+            proc = subprocess.Popen(curl_cmd, shell=True,
+                                stdout=subprocess.PIPE,
+                                stderr=subprocess.PIPE)
+
+            proc.wait()
+            logger.debug("Process: {}".format(proc))
+
+            if proc.returncode == 0:
+                # Check if response is 200 OK
+                logger.info("Got success response")
+                break
+
+            elif proc.returncode == 7:
+                # Connection timeout
+                if count >= max_tries:
+                    logger.error("Connect failed for {}. Failing".format(count))
+                    break
+                # Try after delay
+                time.sleep(delay)
+            else:
+                #Exit the loop incase of errors other than connection timeout and response ok
+                err_resp = proc.stderr.read().decode()
+                logger.error("Got error response: {}".format(err_resp))
+                return proc.returncode
+
+        return proc.returncode
 
     # Enable pong service first
     for index, vnfr in yaml_cfg['vnfr'].items():
@@ -51,11 +82,16 @@ def start_traffic(yaml_cfg, logger):
         if 'pong_vnfd' in vnfr['name']:
             vnf_type = 'pong'
             port = 18889
-            enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
+            rc = enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
+            if rc != 0:
+                logger.error("Enable service for pong failed: {}".
+                             format(rc))
+                return rc
             break
 
+
     # Add a delay to provide pong port to come up
-    time.sleep(0.1)
+    time.sleep(1)
 
     # Enable ping service next
     for index, vnfr in yaml_cfg['vnfr'].items():
@@ -65,9 +101,12 @@ def start_traffic(yaml_cfg, logger):
         if 'ping_vnfd' in vnfr['name']:
             vnf_type = 'ping'
             port = 18888
-            enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
+            rc = enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
             break
 
+    return rc
+
+
 def main(argv=sys.argv[1:]):
     try:
         parser = argparse.ArgumentParser()
@@ -79,14 +118,14 @@ def main(argv=sys.argv[1:]):
         if not os.path.exists(run_dir):
             os.makedirs(run_dir)
         log_file = "{}/ping_pong_start_traffic-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
-        logging.basicConfig(filename=log_file, level=logging.DEBUG)
-        logger = logging.getLogger()
 
-    except Exception as e:
-        print("Exception in {}: {}".format(__file__, e))
-        sys.exit(1)
+        # logging.basicConfig(filename=log_file, level=logging.DEBUG)
+        logger = logging.getLogger('ping-pong-start-traffic')
+        logger.setLevel(logging.DEBUG)
+
+        fh = logging.FileHandler(log_file)
+        fh.setLevel(logging.DEBUG)
 
-    try:
         ch = logging.StreamHandler()
         if args.verbose:
             ch.setLevel(logging.DEBUG)
@@ -95,24 +134,28 @@ def main(argv=sys.argv[1:]):
 
         # create formatter and add it to the handlers
         formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+        fh.setFormatter(formatter)
         ch.setFormatter(formatter)
+        logger.addHandler(fh)
         logger.addHandler(ch)
 
     except Exception as e:
-        logger.exception(e)
-        raise e
+        logger.exception("Exception in {}: {}".format(__file__, e))
+        sys.exit(1)
 
     try:
+        logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
         yaml_str = args.yaml_cfg_file.read()
-        # logger.debug("Input YAML file:\n{}".format(yaml_str))
         yaml_cfg = yaml.load(yaml_str)
         logger.debug("Input YAML: {}".format(yaml_cfg))
 
-        start_traffic(yaml_cfg, logger)
+        rc = start_traffic(yaml_cfg, logger)
+        logger.info("Return code: {}".format(rc))
+        sys.exit(rc)
 
     except Exception as e:
-        logger.exception(e)
-        raise e
+        logger.exception("Exception in {}: {}".format(__file__, e))
+        sys.exit(1)
 
 if __name__ == "__main__":
     main()