update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
[osm/SO.git] / examples / ping_pong_ns / rift / mano / examples / 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 def enable_service(mgmt_ip, port, vnf_type):
34 curl_cmd = 'curl -D /dev/null -H "Accept: application/json" ' \
35 '-H "Content-Type: application/json" ' \
36 '-X POST -d "{{\\"enable\\":true}}" http://{mgmt_ip}:' \
37 '{mgmt_port}/api/v1/{vnf_type}/adminstatus/state'. \
38 format(
39 mgmt_ip=mgmt_ip,
40 mgmt_port=port,
41 vnf_type=vnf_type)
42
43 count = 0
44 delay = 10
45 max_tries = 10
46 while True:
47 count += 1
48
49 logger.debug("Executing cmd: %s", curl_cmd)
50 proc = subprocess.Popen(curl_cmd, shell=True,
51 stdout=subprocess.PIPE,
52 stderr=subprocess.PIPE)
53
54 proc.wait()
55 logger.debug("Process: {}".format(proc))
56
57 if proc.returncode == 0:
58 # Check if response is 200 OK
59 logger.info("Got success response")
60 break
61
62 elif proc.returncode == 7:
63 # Connection timeout
64 if count >= max_tries:
65 logger.error("Connect failed for {}. Failing".format(count))
66 break
67 # Try after delay
68 time.sleep(delay)
69 else:
70 #Exit the loop incase of errors other than connection timeout and response ok
71 err_resp = proc.stderr.read().decode()
72 logger.error("Got error response: {}".format(err_resp))
73 return proc.returncode
74
75 return proc.returncode
76
77 # Enable pong service first
78 for index, vnfr in yaml_cfg['vnfr'].items():
79 logger.debug("VNFR {}: {}".format(index, vnfr))
80
81 # Check if it is pong vnf
82 if 'pong_vnfd' in vnfr['name']:
83 vnf_type = 'pong'
84 port = 18889
85 rc = enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
86 if rc != 0:
87 logger.error("Enable service for pong failed: {}".
88 format(rc))
89 return rc
90 break
91
92
93 # Add a delay to provide pong port to come up
94 time.sleep(1)
95
96 # Enable ping service next
97 for index, vnfr in yaml_cfg['vnfr'].items():
98 logger.debug("VNFR {}: {}".format(index, vnfr))
99
100 # Check if it is pong vnf
101 if 'ping_vnfd' in vnfr['name']:
102 vnf_type = 'ping'
103 port = 18888
104 rc = enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
105 break
106
107 return rc
108
109
110 def main(argv=sys.argv[1:]):
111 try:
112 parser = argparse.ArgumentParser()
113 parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
114 parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
115 args = parser.parse_args()
116
117 run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
118 if not os.path.exists(run_dir):
119 os.makedirs(run_dir)
120 log_file = "{}/ping_pong_start_traffic-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
121
122 # logging.basicConfig(filename=log_file, level=logging.DEBUG)
123 logger = logging.getLogger('ping-pong-start-traffic')
124 logger.setLevel(logging.DEBUG)
125
126 fh = logging.FileHandler(log_file)
127 fh.setLevel(logging.DEBUG)
128
129 ch = logging.StreamHandler()
130 if args.verbose:
131 ch.setLevel(logging.DEBUG)
132 else:
133 ch.setLevel(logging.INFO)
134
135 # create formatter and add it to the handlers
136 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
137 fh.setFormatter(formatter)
138 ch.setFormatter(formatter)
139 logger.addHandler(fh)
140 logger.addHandler(ch)
141
142 except Exception as e:
143 logger.exception("Exception in {}: {}".format(__file__, e))
144 sys.exit(1)
145
146 try:
147 logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
148 yaml_str = args.yaml_cfg_file.read()
149 yaml_cfg = yaml.load(yaml_str)
150 logger.debug("Input YAML: {}".format(yaml_cfg))
151
152 rc = start_traffic(yaml_cfg, logger)
153 logger.info("Return code: {}".format(rc))
154 sys.exit(rc)
155
156 except Exception as e:
157 logger.exception("Exception in {}: {}".format(__file__, e))
158 sys.exit(1)
159
160 if __name__ == "__main__":
161 main()