update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
[osm/SO.git] / examples / ping_pong_ns / rift / mano / examples / pong_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 pong_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 = 18889
37 if 'mgmt_port' in params:
38 mgmt_port = params['mgmt_port']
39 service_ip = params['service_ip']
40 service_port = 5555
41 if 'service_port' in params:
42 service_port = params['service_port']
43 rate = 1
44 if 'rate' in params:
45 rate = params['rate']
46
47 config_cmd = 'curl -D /dev/stdout -H "Accept: application/json" ' \
48 '-H "Content-Type: application/json" ' \
49 '-X POST -d "{{\\"ip\\":\\"{service_ip}\\", \\"port\\":{service_port}}}" ' \
50 'http://{mgmt_ip}:{mgmt_port}/api/v1/pong/server'. \
51 format(
52 mgmt_ip=mgmt_ip,
53 mgmt_port=mgmt_port,
54 service_ip=service_ip,
55 service_port=service_port)
56
57 logger.debug("Executing cmd: %s", config_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(config_cmd, shell=True,
66 stdout=subprocess.PIPE,
67 stderr=subprocess.PIPE)
68
69 proc.wait()
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
99 def main(argv=sys.argv[1:]):
100 try:
101 parser = argparse.ArgumentParser()
102 parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
103 parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
104 args = parser.parse_args()
105
106 run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
107 if not os.path.exists(run_dir):
108 os.makedirs(run_dir)
109 log_file = "{}/pong_setup-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
110
111 # logging.basicConfig(filename=log_file, level=logging.DEBUG)
112 logger = logging.getLogger('pong-setup')
113 logger.setLevel(logging.DEBUG)
114
115 fh = logging.FileHandler(log_file)
116 fh.setLevel(logging.DEBUG)
117
118 ch = logging.StreamHandler()
119 if args.verbose:
120 ch.setLevel(logging.DEBUG)
121 else:
122 ch.setLevel(logging.INFO)
123
124 # create formatter and add it to the handlers
125 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
126 fh.setFormatter(formatter)
127 ch.setFormatter(formatter)
128 logger.addHandler(fh)
129 logger.addHandler(ch)
130
131 except Exception as e:
132 logger.exception("Exception in {}: {}".format(__file__, e))
133 sys.exit(1)
134
135 try:
136 logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
137 yaml_str = args.yaml_cfg_file.read()
138 yaml_cfg = yaml.load(yaml_str)
139 logger.debug("Input YAML: {}".format(yaml_cfg))
140
141 rc = pong_setup(yaml_cfg, logger)
142 logger.info("Return code: {}".format(rc))
143 sys.exit(rc)
144
145 except Exception as e:
146 logger.exception("Exception in {}: {}".format(__file__, e))
147 sys.exit(1)
148
149 if __name__ == "__main__":
150 main()