update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
[osm/SO.git] / examples / ping_pong_ns / rift / mano / examples / ping_scale.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 import argparse
20 import logging
21 import os
22 import stat
23 import subprocess
24 import sys
25 import time
26 import yaml
27
28 def ping_config(run_dir, mgmt_ip, mgmt_port, pong_cp, logger, dry_run):
29 sh_file = "{}/ping_config-{}.sh".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
30 logger.debug("Creating script file %s" % sh_file)
31 f = open(sh_file, "w")
32 f.write(r'''
33 #!/bin/bash
34
35 # Rest API config
36 ping_mgmt_ip='{}'
37 ping_mgmt_port={}
38
39 # VNF specific configuration
40 pong_server_ip='{}'
41 ping_rate=5
42 server_port=5555
43 '''.format(mgmt_ip, mgmt_port, pong_cp))
44
45 f.write(r'''
46 # Check if the port is open
47 DELAY=1
48 MAX_TRIES=60
49 COUNT=0
50 while true; do
51 COUNT=$(expr $COUNT + 1)
52 timeout 1 bash -c "cat < /dev/null > /dev/tcp/${ping_mgmt_ip}/${ping_mgmt_port}"
53 rc=$?
54 if [ $rc -ne 0 ]
55 then
56 echo "Failed to connect to server ${ping_mgmt_ip}:${ping_mgmt_port} for ping with $rc!"
57 if [ ${COUNT} -gt ${MAX_TRIES} ]; then
58 exit $rc
59 fi
60 sleep ${DELAY}
61 else
62 break
63 fi
64 done
65
66 # Make rest API calls to configure VNF
67 curl -D /dev/null \
68 -H "Accept: application/json" \
69 -H "Content-Type: application/json" \
70 -X POST \
71 -d "{\"ip\":\"$pong_server_ip\", \"port\":$server_port}" \
72 http://${ping_mgmt_ip}:${ping_mgmt_port}/api/v1/ping/server
73 rc=$?
74 if [ $rc -ne 0 ]
75 then
76 echo "Failed to set server info for ping!"
77 exit $rc
78 fi
79
80 curl -D /dev/null \
81 -H "Accept: application/json" \
82 -H "Content-Type: application/json" \
83 -X POST \
84 -d "{\"rate\":$ping_rate}" \
85 http://${ping_mgmt_ip}:${ping_mgmt_port}/api/v1/ping/rate
86 rc=$?
87 if [ $rc -ne 0 ]
88 then
89 echo "Failed to set ping rate!"
90 exit $rc
91 fi
92
93 output=$(curl -D /dev/null \
94 -H "Accept: application/json" \
95 -H "Content-Type: application/json" \
96 -X POST \
97 -d "{\"enable\":true}" \
98 http://${ping_mgmt_ip}:${ping_mgmt_port}/api/v1/ping/adminstatus/state)
99 if [[ $output == *"Internal Server Error"* ]]
100 then
101 echo $output
102 exit 3
103 else
104 echo $output
105 fi
106
107 exit 0
108 ''')
109 f.close()
110 os.chmod(sh_file, stat.S_IRWXU)
111 if not dry_run:
112 rc = subprocess.call(sh_file, shell=True)
113 if rc:
114 logger.error("Config failed: {}".format(rc))
115 return False
116 return True
117
118
119
120 def main(argv=sys.argv[1:]):
121 try:
122 parser = argparse.ArgumentParser()
123 parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
124 parser.add_argument("--dry-run", action="store_true")
125 parser.add_argument("--quiet", "-q", dest="verbose", action="store_false")
126 args = parser.parse_args()
127
128 run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
129 if not os.path.exists(run_dir):
130 os.makedirs(run_dir)
131 log_file = "{}/rift_ping_scale_config-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
132 logging.basicConfig(filename=log_file, level=logging.DEBUG)
133 logger = logging.getLogger()
134
135 ch = logging.StreamHandler()
136 if args.verbose:
137 ch.setLevel(logging.DEBUG)
138 else:
139 ch.setLevel(logging.INFO)
140
141 # create formatter and add it to the handlers
142 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
143 ch.setFormatter(formatter)
144 logger.addHandler(ch)
145
146 except Exception as e:
147 print("Got exception:{}".format(e))
148 raise e
149
150 try:
151 dry_run = args.dry_run
152
153 yaml_str = args.yaml_cfg_file.read()
154 logger.debug("Input YAML file: {}".format(yaml_str))
155 yaml_cfg = yaml.load(yaml_str)
156 logger.debug("Input YAML: {}".format(yaml_cfg))
157
158 # Check if this is post scale out trigger
159 if yaml_cfg['trigger'] != 'post_scale_out':
160 logger.error("Unexpected trigger {}".
161 format(yaml_cfg['trigger']))
162 raise
163
164 pong_cp = ""
165 for vnfr in yaml_cfg['vnfrs_others']:
166 # Find the pong VNFR, assuming vnfr name will
167 # have pong_vnfd as a substring
168 if 'pong_vnfd' in vnfr['name']:
169 for cp in vnfr['connection_points']:
170 logger.debug("Connection point {}".format(cp))
171 if 'cp0' in cp['name']:
172 pong_cp = cp['ip_address']
173 break
174 if not len(pong_cp):
175 logger.error("Did not get Pong cp0 IP")
176 raise
177
178 for vnfr in yaml_cfg['vnfrs_in_group']:
179 mgmt_ip = vnfr['rw_mgmt_ip']
180 mgmt_port = vnfr['rw_mgmt_port']
181 if ping_config(run_dir, mgmt_ip, mgmt_port, pong_cp, logger, dry_run):
182 logger.info("Successfully configured Ping {} at {}".
183 format(vnfr['name'], mgmt_ip))
184 else:
185 logger.error("Config of ping {} with {} failed".
186 format(vnfr['name'], mgmt_ip))
187 raise
188
189 except Exception as e:
190 logger.error("Got exception {}".format(e))
191 logger.exception(e)
192 raise e
193
194 if __name__ == "__main__":
195 main()