update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
[osm/SO.git] / examples / ping_pong_ns / rift / mano / examples / pong_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 pong_initial_config(yaml_cfg, logger):
31 '''Use curl to configure ping and set the ping rate'''
32 def find_vnfr(vnfr_dict, name):
33 try:
34 for k, v in vnfr_dict.items():
35 if v['name'] == name:
36 return v
37 except KeyError:
38 logger.warn("Could not find vnfr for name : %s", name)
39
40 def find_cp_ip(vnfr, cp_name):
41 for cp in vnfr['connection_point']:
42 logger.debug("Connection point: %s", format(cp))
43 if cp_name in cp['name']:
44 return cp['ip_address']
45
46 raise ValueError("Could not find vnfd %s connection point %s", cp_name)
47
48 def find_vnfr_mgmt_ip(vnfr):
49 return vnfr['mgmt_ip_address']
50
51 def get_vnfr_name(vnfr):
52 return vnfr['name']
53
54 def find_vdur_mgmt_ip(vnfr):
55 return vnfr['vdur'][0]['vm_management_ip']
56
57 def find_param_value(param_list, input_param):
58 for item in param_list:
59 logger.debug("Parameter: %s", format(item))
60 if item['name'] == input_param:
61 return item['value']
62
63 # Get the required and optional parameters
64 pong_vnfr = find_vnfr(yaml_cfg['vnfr'], yaml_cfg['vnfr_name'])
65 pong_vnf_mgmt_ip = find_vnfr_mgmt_ip(pong_vnfr)
66 pong_vnf_svc_ip = find_cp_ip(pong_vnfr, "pong_vnfd/cp0")
67
68
69 # Get the required and optional parameters
70 mgmt_ip = pong_vnf_mgmt_ip
71 mgmt_port = 18889
72 service_ip = pong_vnf_svc_ip
73 service_port = 5555
74
75 config_cmd = 'curl -D /dev/null -H "Accept: application/vnd.yang.data' \
76 '+xml" -H "Content-Type: application/vnd.yang.data+json" ' \
77 '-X POST -d "{{\\"ip\\":\\"{service_ip}\\", \\"port\\":{service_port}}}" ' \
78 'http://{mgmt_ip}:{mgmt_port}/api/v1/pong/server'. \
79 format(
80 mgmt_ip=mgmt_ip,
81 mgmt_port=mgmt_port,
82 service_ip=service_ip,
83 service_port=service_port)
84
85 logger.debug("Executing cmd: %s", config_cmd)
86 count = 0
87 delay = 20
88 max_tries = 12
89 rc = 0
90
91 while True:
92 count += 1
93 proc = subprocess.Popen(config_cmd, shell=True,
94 stdout=subprocess.PIPE,
95 stderr=subprocess.PIPE)
96
97 proc.wait()
98 logger.debug("Process: {}".format(proc))
99
100 if proc.returncode == 0:
101 # Check if response is 200 OK
102 logger.info("Success response ")
103 rc = 0
104 break
105 elif proc.returncode == 7:
106 # Connection timeout
107 if count >= max_tries:
108 logger.error("Connect failed for {}. Failing".format(count))
109 rc = 7
110 break
111 # Try after delay
112 time.sleep(delay)
113
114 return rc
115
116
117 def main(argv=sys.argv[1:]):
118 try:
119 parser = argparse.ArgumentParser()
120 parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
121 parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
122 args = parser.parse_args()
123
124 run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
125 if not os.path.exists(run_dir):
126 os.makedirs(run_dir)
127 log_file = "{}/pong_initial_config-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
128
129 # logging.basicConfig(filename=log_file, level=logging.DEBUG)
130 logger = logging.getLogger('pong-initial-config')
131 logger.setLevel(logging.DEBUG)
132
133 fh = logging.FileHandler(log_file)
134 fh.setLevel(logging.DEBUG)
135
136 ch = logging.StreamHandler()
137 if args.verbose:
138 ch.setLevel(logging.DEBUG)
139 else:
140 ch.setLevel(logging.INFO)
141
142 # create formatter and add it to the handlers
143 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
144 fh.setFormatter(formatter)
145 ch.setFormatter(formatter)
146 logger.addHandler(fh)
147 logger.addHandler(ch)
148
149 except Exception as e:
150 logger.exception("Exception in {}: {}".format(__file__, e))
151 sys.exit(1)
152
153 try:
154 logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
155 yaml_str = args.yaml_cfg_file.read()
156 yaml_cfg = yaml.load(yaml_str)
157 logger.debug("Input YAML: {}".format(yaml_cfg))
158
159 rc = pong_initial_config(yaml_cfg, logger)
160 logger.info("Return code: {}".format(rc))
161 sys.exit(rc)
162
163 except Exception as e:
164 logger.exception("Exception in {}: {}".format(__file__, e))
165 sys.exit(1)
166
167 if __name__ == "__main__":
168 main()