Remove config template from use in ping-pong
[osm/SO.git] / examples / ping_pong_ns / rift / mano / examples / ping_initial_config.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 ping_initial_config(yaml_cfg, logger):
31 '''Use curl to configure ping and set the ping rate'''
32
33 def find_vnfr(vnfr_dict, name):
34 try:
35 for k, v in vnfr_dict.items():
36 if v['name'] == name:
37 return v
38 except KeyError:
39 logger.warn("Could not find vnfr for name : %s", name)
40
41 def find_vnfr_by_substring(vnfr_dict, name):
42 try:
43 for k, v in vnfr_dict.items():
44 if name in v['name']:
45 return v
46 except KeyError:
47 logger.warn("Could not find vnfr by name : %s", name)
48
49 def find_cp_ip(vnfr, cp_name):
50 for cp in vnfr['connection_point']:
51 logger.debug("Connection point: %s", format(cp))
52 if cp_name in cp['name']:
53 return cp['ip_address']
54
55 raise ValueError("Could not find vnfd %s connection point %s", cp_name)
56
57 def find_vnfr_mgmt_ip(vnfr):
58 return vnfr['mgmt_ip_address']
59
60 def get_vnfr_name(vnfr):
61 return vnfr['name']
62
63 def find_vdur_mgmt_ip(vnfr):
64 return vnfr['vdur'][0]['vm_management_ip']
65
66 def find_param_value(param_list, input_param):
67 for item in param_list:
68 logger.debug("Parameter: %s", format(item))
69 if item['name'] == input_param:
70 return item['value']
71
72 def set_ping_destination(mgmt_ip, port, pong_ip, pong_port):
73 curl_cmd = 'curl -D /dev/null -H "Accept: application/vnd.yang.data' \
74 '+xml" -H "Content-Type: application/vnd.yang.data+json" ' \
75 '-X POST -d "{{\\"ip\\":\\"{pong_ip}\\", \\"port\\":{pong_port}}}" ' \
76 'http://{mgmt_ip}:{mgmt_port}/api/v1/ping/server'. \
77 format(
78 mgmt_ip=mgmt_ip,
79 mgmt_port=port,
80 pong_ip=pong_ip,
81 pong_port=pong_port)
82
83 logger.debug("Executing cmd: %s", curl_cmd)
84 proc = subprocess.Popen(curl_cmd, shell=True,
85 stdout=subprocess.PIPE,
86 stderr=subprocess.PIPE)
87
88 proc.wait()
89 logger.debug("Process: {}".format(proc))
90
91 return proc.returncode
92
93 # Get the required and optional parameters
94 ping_vnfr = find_vnfr(yaml_cfg['vnfr'], yaml_cfg['vnfr_name'])
95 ping_vnf_mgmt_ip = find_vnfr_mgmt_ip(ping_vnfr)
96 pong_vnfr = yaml_cfg['vnfr'][2]
97 pong_svc_ip = find_cp_ip(pong_vnfr, 'pong_vnfd/cp0')
98
99 # Get the required and optional parameters
100 mgmt_ip = ping_vnf_mgmt_ip
101 mgmt_port = 18888
102 rate = 5
103
104 rc = set_ping_destination(mgmt_ip, mgmt_port, pong_svc_ip, 5555)
105 if rc != 0:
106 return rc
107
108 cmd = 'curl -D /dev/stdout -H "Accept: application/vnd.yang.data' \
109 '+xml" -H "Content-Type: application/vnd.yang.data+json" ' \
110 '-X POST -d "{{\\"rate\\":{rate}}}" ' \
111 'http://{mgmt_ip}:{mgmt_port}/api/v1/ping/rate'. \
112 format(
113 mgmt_ip=mgmt_ip,
114 mgmt_port=mgmt_port,
115 rate=rate)
116
117 logger.debug("Executing cmd: %s", cmd)
118 count = 0
119 delay = 5
120 max_tries = 12
121 rc = 0
122
123 while True:
124 count += 1
125 proc = subprocess.Popen(cmd, shell=True,
126 stdout=subprocess.PIPE,
127 stderr=subprocess.PIPE)
128 proc.wait()
129
130 logger.debug("Process: {}".format(proc))
131
132 if proc.returncode == 0:
133 # Check if response is 200 OK
134 resp = proc.stdout.read().decode()
135 if 'HTTP/1.1 200 OK' in resp:
136 rc = 0
137 break
138 logger.error("Got error response: {}".format(resp))
139 rc = 1
140 break
141
142 elif proc.returncode == 7:
143 # Connection timeout
144 if count >= max_tries:
145 logger.error("Connect failed for {}. Failing".format(count))
146 rc = 7
147 break
148 # Try after delay
149 time.sleep(delay)
150
151 return rc
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_initial_config-{}.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-initial-config')
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 = ping_initial_config(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()