f98bece2c753c30b940ff7043fce10a0790c5792
[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 curl_fmt = 'curl -D /dev/stdout -H "Accept: application/vnd.yang.data' \
34 '+xml" -H "Content-Type: application/vnd.yang.data+json" ' \
35 '-X POST -d "{{ {data} }}" http://{mgmt_ip}:' \
36 '{mgmt_port}/api/v1/{vnf_type}/{url}'
37
38 def setup_service(mgmt_ip, port, vnf_type, service_ip, service_port):
39 data = '\\"ip\\":\\"{}\\", \\"port\\":5555'.format(service_ip)
40 curl_cmd = curl_fmt.format(
41 mgmt_ip=mgmt_ip,
42 mgmt_port=port,
43 vnf_type=vnf_type,
44 data=data,
45 url='server'
46 )
47
48 logger.debug("Executing cmd: %s", curl_cmd)
49 proc = subprocess.run(curl_cmd, shell=True,
50 stdout=subprocess.PIPE,
51 stderr=subprocess.PIPE)
52
53 logger.debug("Process: {}".format(proc))
54
55 return proc.returncode
56
57 def enable_service(mgmt_ip, port, vnf_type):
58 curl_cmd = curl_fmt.format(
59 mgmt_ip=mgmt_ip,
60 mgmt_port=port,
61 vnf_type=vnf_type,
62 data='\\"enable\\":true',
63 url='adminstatus/state'
64 )
65
66 logger.debug("Executing cmd: %s", curl_cmd)
67 proc = subprocess.run(curl_cmd, shell=True,
68 stdout=subprocess.PIPE,
69 stderr=subprocess.PIPE)
70
71 logger.debug("Process: {}".format(proc))
72
73 return proc.returncode
74
75 # Get port from user parameter
76 service_port = yaml_cfg['parameter']['port']
77
78 service_ip = None
79 # Enable pong service first
80 for index, vnfr in yaml_cfg['vnfr'].items():
81 logger.debug("VNFR {}: {}".format(index, vnfr))
82
83 def get_cp_ip(cp_name):
84 for cp in vnfr['connection_point']:
85 if cp['name'].endswith(cp_name):
86 return cp['ip_address']
87
88 # Check if it is pong vnf
89 if 'pong_vnf' in vnfr['name']:
90 vnf_type = 'pong'
91 mgmt_ip = vnfr['mgmt_ip_address']
92 port = vnfr['mgmt_port']
93 service_ip = get_cp_ip('cp1')
94
95 max_tries = 60
96 tries = 0
97 while tries < max_tries:
98 rc = setup_service(mgmt_ip, port, vnf_type, service_ip, service_port)
99 tries += 1
100 if rc != 0:
101 logger.error("Setup service for pong failed ({}): {}".
102 format(tries, rc))
103 if rc != 7:
104 return rc
105 else:
106 time.sleep(1) # Sleep for 1 seconds
107
108 rc = enable_service(mgmt_ip, port, vnf_type)
109 if rc != 0:
110 logger.error("Enable service for pong failed: {}".
111 format(rc))
112 return rc
113 break
114
115 # Add a delay to provide pong port to come up
116 time.sleep(1)
117
118 # Enable ping service next
119 for index, vnfr in yaml_cfg['vnfr'].items():
120 logger.debug("VNFR {}: {}".format(index, vnfr))
121
122 # Check if it is pong vnf
123 if 'ping_vnf' in vnfr['name']:
124 vnf_type = 'ping'
125 mgmt_ip = vnfr['mgmt_ip_address']
126 port = vnfr['mgmt_port']
127 if service_ip is None:
128 logger.error("Did not find pong ip!!")
129 return 1
130
131 max_tries = 30
132 tries = 0
133 while tries < max_tries:
134 rc = setup_service(mgmt_ip, port, vnf_type, service_ip, service_port)
135 tries += 1
136 if rc != 0:
137 logger.error("Setup service for ping failed ({}): {}".
138 format(tries, rc))
139 if rc != 7:
140 return rc
141 else:
142 time.sleep(1) # Sleep for 1 seconds
143
144 rc = enable_service(mgmt_ip, port, vnf_type)
145 if rc != 0:
146 logger.error("Enable service for ping failed: {}".
147 format(rc))
148 break
149
150 return rc
151
152
153 def main(argv=sys.argv[1:]):
154 try:
155 parser = argparse.ArgumentParser()
156 parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
157 parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
158 args = parser.parse_args()
159
160 run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
161 if not os.path.exists(run_dir):
162 os.makedirs(run_dir)
163 log_file = "{}/ping_pong_start_traffic-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
164
165 # logging.basicConfig(filename=log_file, level=logging.DEBUG)
166 logger = logging.getLogger('ping-pong-start-traffic')
167 logger.setLevel(logging.DEBUG)
168
169 fh = logging.FileHandler(log_file)
170 fh.setLevel(logging.DEBUG)
171
172 ch = logging.StreamHandler()
173 if args.verbose:
174 ch.setLevel(logging.DEBUG)
175 else:
176 ch.setLevel(logging.INFO)
177
178 # create formatter and add it to the handlers
179 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
180 fh.setFormatter(formatter)
181 ch.setFormatter(formatter)
182 logger.addHandler(fh)
183 logger.addHandler(ch)
184
185 except Exception as e:
186 logger.exception("Exception in {}: {}".format(__file__, e))
187 sys.exit(1)
188
189 try:
190 logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
191 yaml_str = args.yaml_cfg_file.read()
192 yaml_cfg = yaml.load(yaml_str)
193 logger.debug("Input YAML: {}".format(yaml_cfg))
194
195 rc = start_traffic(yaml_cfg, logger)
196 logger.info("Return code: {}".format(rc))
197 sys.exit(rc)
198
199 except Exception as e:
200 logger.exception("Exception in {}: {}".format(__file__, e))
201 sys.exit(1)
202
203 if __name__ == "__main__":
204 main()