Update ping pong to use charm
[osm/devops.git] / src / nsd / ping_pong_ns / scripts / start_traffic.py
1 #!/usr/bin/env python3
2
3 ############################################################################
4 # Copyright 2016 RIFT.IO Inc #
5 # #
6 # Licensed under the Apache License, Version 2.0 (the "License"); #
7 # you may not use this file except in compliance with the License. #
8 # You may obtain a copy of the License at #
9 # #
10 # http://www.apache.org/licenses/LICENSE-2.0 #
11 # #
12 # Unless required by applicable law or agreed to in writing, software #
13 # distributed under the License is distributed on an "AS IS" BASIS, #
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
15 # See the License for the specific language governing permissions and #
16 # limitations under the License. #
17 ############################################################################
18
19
20 import argparse
21 import logging
22 import os
23 import subprocess
24 import sys
25 import time
26
27 import yaml
28
29
30 def start_traffic(yaml_cfg, logger):
31 '''Use curl and set admin status to enable on pong and ping vnfs'''
32
33 def enable_service(mgmt_ip, port, vnf_type):
34 curl_cmd = 'curl -D /dev/stdout -H "Accept: application/vnd.yang.data' \
35 '+xml" -H "Content-Type: application/vnd.yang.data+json" ' \
36 '-X POST -d "{{\\"enable\\":true}}" http://{mgmt_ip}:' \
37 '{mgmt_port}/api/v1/{vnf_type}/adminstatus/state'. \
38 format(
39 mgmt_ip=mgmt_ip,
40 mgmt_port=port,
41 vnf_type=vnf_type)
42
43 logger.debug("Executing cmd: %s", curl_cmd)
44 proc = subprocess.run(curl_cmd, shell=True,
45 stdout=subprocess.PIPE,
46 stderr=subprocess.PIPE)
47
48 logger.debug("Process: {}".format(proc))
49
50 return proc.returncode
51
52 # Enable pong service first
53 for index, vnfr in yaml_cfg['vnfr'].items():
54 logger.debug("VNFR {}: {}".format(index, vnfr))
55
56 # Check if it is pong vnf
57 if 'pong_vnf' in vnfr['name']:
58 vnf_type = 'pong'
59 port = 18889
60 rc = enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
61 if rc != 0:
62 logger.error("Enable service for pong failed: {}".
63 format(rc))
64 return rc
65 break
66
67 # Add a delay to provide pong port to come up
68 time.sleep(1)
69
70 # Enable ping service next
71 for index, vnfr in yaml_cfg['vnfr'].items():
72 logger.debug("VNFR {}: {}".format(index, vnfr))
73
74 # Check if it is pong vnf
75 if 'ping_vnf' in vnfr['name']:
76 vnf_type = 'ping'
77 port = 18888
78 rc = enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
79 break
80
81 return rc
82
83
84 def main(argv=sys.argv[1:]):
85 try:
86 parser = argparse.ArgumentParser()
87 parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
88 parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
89 args = parser.parse_args()
90
91 run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
92 if not os.path.exists(run_dir):
93 os.makedirs(run_dir)
94 log_file = "{}/ping_pong_start_traffic-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
95
96 # logging.basicConfig(filename=log_file, level=logging.DEBUG)
97 logger = logging.getLogger('ping-pong-start-traffic')
98 logger.setLevel(logging.DEBUG)
99
100 fh = logging.FileHandler(log_file)
101 fh.setLevel(logging.DEBUG)
102
103 ch = logging.StreamHandler()
104 if args.verbose:
105 ch.setLevel(logging.DEBUG)
106 else:
107 ch.setLevel(logging.INFO)
108
109 # create formatter and add it to the handlers
110 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
111 fh.setFormatter(formatter)
112 ch.setFormatter(formatter)
113 logger.addHandler(fh)
114 logger.addHandler(ch)
115
116 except Exception as e:
117 logger.exception("Exception in {}: {}".format(__file__, e))
118 sys.exit(1)
119
120 try:
121 logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
122 yaml_str = args.yaml_cfg_file.read()
123 yaml_cfg = yaml.load(yaml_str)
124 logger.debug("Input YAML: {}".format(yaml_cfg))
125
126 rc = start_traffic(yaml_cfg, logger)
127 logger.info("Return code: {}".format(rc))
128 sys.exit(rc)
129
130 except Exception as e:
131 logger.exception("Exception in {}: {}".format(__file__, e))
132 sys.exit(1)
133
134 if __name__ == "__main__":
135 main()