update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
[osm/SO.git] / examples / ping_pong_ns / rift / mano / examples / pong_start_stop.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_start_stop(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 start = 'true'
40 if 'start' in params:
41 if not params['start']:
42 start = 'false'
43
44 cmd = 'curl -D /dev/stdout -H "Accept: application/json" ' \
45 '-H "Content-Type: application/json" ' \
46 '-X POST -d "{{\\"enable\\":{start}}}" ' \
47 'http://{mgmt_ip}:{mgmt_port}/api/v1/pong/adminstatus/state'. \
48 format(
49 mgmt_ip=mgmt_ip,
50 mgmt_port=mgmt_port,
51 start=start)
52
53 logger.debug("Executing cmd: %s", cmd)
54 proc = subprocess.Popen(cmd, shell=True,
55 stdout=subprocess.PIPE,
56 stderr=subprocess.PIPE)
57
58 proc.wait()
59 logger.debug("Process: {}".format(proc))
60
61 rc = proc.returncode
62
63 if rc == 0:
64 # Check if we got 200 OK
65 resp = proc.stdout.read().decode()
66 if 'HTTP/1.1 200 OK' not in resp:
67 logger._log.error("Got error response: {}".format(resp))
68 rc = 1
69
70 return rc
71
72
73 def main(argv=sys.argv[1:]):
74 try:
75 parser = argparse.ArgumentParser()
76 parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
77 parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
78 args = parser.parse_args()
79
80 run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
81 if not os.path.exists(run_dir):
82 os.makedirs(run_dir)
83 log_file = "{}/pong_start_stop-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
84
85 # logging.basicConfig(filename=log_file, level=logging.DEBUG)
86 logger = logging.getLogger('pong-start-stop')
87 logger.setLevel(logging.DEBUG)
88
89 fh = logging.FileHandler(log_file)
90 fh.setLevel(logging.DEBUG)
91
92 ch = logging.StreamHandler()
93 if args.verbose:
94 ch.setLevel(logging.DEBUG)
95 else:
96 ch.setLevel(logging.INFO)
97
98 # create formatter and add it to the handlers
99 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
100 fh.setFormatter(formatter)
101 ch.setFormatter(formatter)
102 logger.addHandler(fh)
103 logger.addHandler(ch)
104
105 except Exception as e:
106 logger.exception("Exception in {}: {}".format(__file__, e))
107 sys.exit(1)
108
109 try:
110 logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
111 yaml_str = args.yaml_cfg_file.read()
112 yaml_cfg = yaml.load(yaml_str)
113 logger.debug("Input YAML: {}".format(yaml_cfg))
114
115 rc = pong_start_stop(yaml_cfg, logger)
116 logger.info("Return code: {}".format(rc))
117 sys.exit(rc)
118
119 except Exception as e:
120 logger.exception("Exception in {}: {}".format(__file__, e))
121 sys.exit(1)
122
123 if __name__ == "__main__":
124 main()