update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
[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 set-server cmd: %s", curl_cmd)
84 count = 0
85 delay = 20
86 max_tries = 12
87 rc = 0
88 while True:
89 count += 1
90 proc = subprocess.Popen(curl_cmd, shell=True,
91 stdout=subprocess.PIPE,
92 stderr=subprocess.PIPE)
93
94 proc.wait()
95 logger.debug("Process: {}".format(proc))
96
97 if proc.returncode == 0:
98 logger.info("Success response ")
99 rc = 0
100 break
101
102 elif proc.returncode == 7:
103 # Connection timeout
104 if count >= max_tries:
105 logger.error("Connect failed for {}. Failing".format(count))
106 rc = 7
107 break
108 # Try after delay
109 time.sleep(delay)
110
111 return rc
112
113 # Get the required and optional parameters
114 ping_vnfr = find_vnfr(yaml_cfg['vnfr'], yaml_cfg['vnfr_name'])
115 ping_vnf_mgmt_ip = find_vnfr_mgmt_ip(ping_vnfr)
116 pong_vnfr = yaml_cfg['vnfr'][2]
117 pong_svc_ip = find_cp_ip(pong_vnfr, 'pong_vnfd/cp0')
118
119 # Get the required and optional parameters
120 mgmt_ip = ping_vnf_mgmt_ip
121 mgmt_port = 18888
122 rate = 5
123
124 rc = set_ping_destination(mgmt_ip, mgmt_port, pong_svc_ip, 5555)
125 if rc != 0:
126 return rc
127
128 cmd = 'curl -D /dev/null -H "Accept: application/vnd.yang.data' \
129 '+xml" -H "Content-Type: application/vnd.yang.data+json" ' \
130 '-X POST -d "{{\\"rate\\":{rate}}}" ' \
131 'http://{mgmt_ip}:{mgmt_port}/api/v1/ping/rate'. \
132 format(
133 mgmt_ip=mgmt_ip,
134 mgmt_port=mgmt_port,
135 rate=rate)
136
137 logger.debug("Executing set-rate cmd: %s", cmd)
138 count = 0
139 delay = 10
140 max_tries = 12
141 rc = 0
142
143 while True:
144 count += 1
145 proc = subprocess.Popen(cmd, shell=True,
146 stdout=subprocess.PIPE,
147 stderr=subprocess.PIPE)
148 proc.wait()
149
150 logger.debug("Process: {}".format(proc))
151
152 if proc.returncode == 0:
153 rc = 0
154 break
155
156 elif proc.returncode == 7:
157 # Connection timeout
158 if count >= max_tries:
159 logger.error("Connect failed for {}. Failing".format(count))
160 rc = 7
161 break
162 # Try after delay
163 time.sleep(delay)
164
165 return rc
166
167 def main(argv=sys.argv[1:]):
168 try:
169 parser = argparse.ArgumentParser()
170 parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
171 parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
172 args = parser.parse_args()
173
174 run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
175 if not os.path.exists(run_dir):
176 os.makedirs(run_dir)
177 log_file = "{}/ping_initial_config-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
178
179 # logging.basicConfig(filename=log_file, level=logging.DEBUG)
180 logger = logging.getLogger('ping-initial-config')
181 logger.setLevel(logging.DEBUG)
182
183 fh = logging.FileHandler(log_file)
184 fh.setLevel(logging.DEBUG)
185
186 ch = logging.StreamHandler()
187 if args.verbose:
188 ch.setLevel(logging.DEBUG)
189 else:
190 ch.setLevel(logging.INFO)
191
192 # create formatter and add it to the handlers
193 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
194 fh.setFormatter(formatter)
195 ch.setFormatter(formatter)
196 logger.addHandler(fh)
197 logger.addHandler(ch)
198
199 except Exception as e:
200 logger.exception("Exception in {}: {}".format(__file__, e))
201 sys.exit(1)
202
203 try:
204 logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
205 yaml_str = args.yaml_cfg_file.read()
206 yaml_cfg = yaml.load(yaml_str)
207 logger.debug("Input YAML: {}".format(yaml_cfg))
208
209 rc = ping_initial_config(yaml_cfg, logger)
210 logger.info("Return code: {}".format(rc))
211 sys.exit(rc)
212
213 except Exception as e:
214 logger.exception("Exception in {}: {}".format(__file__, e))
215 sys.exit(1)
216
217 if __name__ == "__main__":
218 main()