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