2bcbc143254dfc57faf21912a58746d770e2af0f
[osm/devops.git] / juju-charms / layers / pingpong / reactive / pingpong.py
1 from charmhelpers.core.hookenv import (
2 action_get,
3 action_fail,
4 action_set,
5 config,
6 status_set,
7 )
8
9 from charms.reactive import (
10 remove_state as remove_flag,
11 set_state as set_flag,
12 when,
13 when_not,
14 )
15 import charms.sshproxy
16 # from subprocess import (
17 # Popen,
18 # CalledProcessError,
19 # PIPE,
20 # )
21
22
23 cfg = config()
24
25
26 @when('config.changed', 'sshproxy.configured')
27 def config_changed():
28 """Verify the configuration.
29 Verify that the charm has been configured
30 """
31 (validated, output) = charms.sshproxy.verify_ssh_credentials()
32 if not validated:
33 status_set('blocked', 'Unable to verify SSH credentials: {}'.format(
34 output
35 ))
36 if all(k in cfg for k in ['mode']):
37 if cfg['mode'] in ['ping', 'pong']:
38 set_flag('pingpong.configured')
39 status_set('active', 'ready!')
40 return
41 status_set('blocked', 'Waiting for configuration')
42
43
44 @when('config.changed')
45 @when_not('sshproxy.configured')
46 def invalid_credentials():
47 status_set('blocked', 'Waiting for SSH credentials.')
48 pass
49
50
51 def is_ping():
52 if cfg['mode'] == 'ping':
53 return True
54 return False
55
56
57 def is_pong():
58 return not is_ping()
59
60
61 def get_port():
62 port = 18888
63 if is_pong():
64 port = 18889
65 return port
66
67
68 @when('pingpong.configured')
69 @when('actions.start')
70 def start():
71 try:
72 # Bring up the eth1 interface.
73 # The selinux label on the file needs to be set correctly
74 cmd = "sudo timeout 5 /sbin/restorecon -v /etc/sysconfig/network-scripts/ifcfg-eth1"
75 result, err = charms.sshproxy._run(cmd)
76 except Exception as e:
77 err = "{}".format(e)
78 action_fail('command failed: {}, errors: {}'.format(err, e.output))
79 remove_flag('actions.start')
80 return
81
82 # Attempt to raise the non-mgmt interface, but ignore failures if
83 # the interface is already up.
84 try:
85 cmd = "sudo timeout 30 /sbin/ifup eth1"
86 result, err = charms.sshproxy._run(cmd)
87 except Exception as e:
88 pass
89
90 try:
91 cmd = "sudo timeout 30 /usr/bin/systemctl start {}". \
92 format(cfg['mode'])
93 result, err = charms.sshproxy._run(cmd)
94 except Exception as e:
95 action_fail('command failed: {}, errors: {}'.format(e, e.output))
96 else:
97 action_set({'stdout': result,
98 'errors': err})
99 finally:
100 remove_flag('actions.start')
101
102
103 @when('pingpong.configured')
104 @when('actions.stop')
105 def stop():
106 try:
107 # Enter the command to stop your service(s)
108 cmd = "sudo timeout 30 /usr/bin/systemctl stop {}".format(cfg['mode'])
109 result, err = charms.sshproxy._run(cmd)
110 except Exception as e:
111 action_fail('command failed: {}, errors: {}'.format(e, e.output))
112 else:
113 action_set({'stdout': result,
114 'errors': err})
115 finally:
116 remove_flag('actions.stop')
117
118
119 @when('pingpong.configured')
120 @when('actions.restart')
121 def restart():
122 try:
123 # Enter the command to restart your service(s)
124 cmd = "sudo timeout 30 /usr/bin/systemctl restart {}".format(cfg['mode'])
125 result, err = charms.sshproxy._run(cmd)
126 except Exception as e:
127 action_fail('command failed: {}, errors: {}'.format(e, e.output))
128 else:
129 action_set({'stdout': result,
130 'errors': err})
131 finally:
132 remove_flag('actions.restart')
133
134
135 @when('pingpong.configured')
136 @when('actions.set-server')
137 def set_server():
138 try:
139 # Get the target service info
140 target_ip = action_get('server-ip')
141 target_port = action_get('server-port')
142
143 data = '{{"ip" : "{}", "port" : {} }}'. \
144 format(target_ip, target_port)
145
146 cmd = format_curl(
147 'POST',
148 '/server',
149 data,
150 )
151
152 result, err = charms.sshproxy._run(cmd)
153 except Exception as e:
154 action_fail('command failed: {}, errors: {}'.format(e, e.output))
155 else:
156 action_set({'stdout': result,
157 'errors': err})
158 finally:
159 remove_flag('actions.set-server')
160
161
162 @when('pingpong.configured')
163 @when('actions.set-rate')
164 def set_rate():
165 try:
166 if is_ping():
167 rate = action_get('rate')
168 cmd = format_curl('POST', '/rate', '{{"rate" : {}}}'.format(rate))
169
170 result, err = charms.sshproxy._run(cmd)
171 except Exception as e:
172 err = "{}".format(e)
173 action_fail('command failed: {}, errors: {}'.format(err, e.output))
174 else:
175 action_set({'stdout': result,
176 'errors': err})
177 finally:
178 remove_flag('actions.set-rate')
179
180
181 @when('pingpong.configured')
182 @when('actions.get-rate')
183 def get_rate():
184 try:
185 if is_ping():
186 cmd = format_curl('GET', '/rate')
187
188 result, err = charms.sshproxy._run(cmd)
189 except Exception as e:
190 action_fail('command failed: {}, errors: {}'.format(e, e.output))
191 else:
192 action_set({'stdout': result,
193 'errors': err})
194 finally:
195 remove_flag('actions.get-rate')
196
197
198 @when('pingpong.configured')
199 @when('actions.get-state')
200 def get_state():
201 try:
202 cmd = format_curl('GET', '/state')
203
204 result, err = charms.sshproxy._run(cmd)
205 except Exception as e:
206 action_fail('command failed: {}, errors: {}'.format(e, e.output))
207 else:
208 action_set({'stdout': result,
209 'errors': err})
210 finally:
211 remove_flag('actions.get-state')
212
213
214 @when('pingpong.configured')
215 @when('actions.get-stats')
216 def get_stats():
217 try:
218 cmd = format_curl('GET', '/stats')
219
220 result, err = charms.sshproxy._run(cmd)
221 except Exception as e:
222 action_fail('command failed: {}, errors: {}'.format(e, e.output))
223 else:
224 action_set({'stdout': result,
225 'errors': err})
226 finally:
227 remove_flag('actions.get-stats')
228
229
230 @when('pingpong.configured')
231 @when('actions.start-traffic')
232 def start_traffic():
233 try:
234 cmd = format_curl('POST', '/adminstatus/state', '{"enable" : true}')
235
236 result, err = charms.sshproxy._run(cmd)
237 except Exception as e:
238 action_fail('command failed: {}, errors: {}'.format(e, e.output))
239 else:
240 action_set({'stdout': result,
241 'errors': err})
242 finally:
243 remove_flag('actions.start-traffic')
244
245
246 @when('pingpong.configured')
247 @when('actions.stop-traffic')
248 def stop_traffic():
249 try:
250 cmd = format_curl('POST', '/adminstatus/state', '{"enable" : false}')
251
252 result, err = charms.sshproxy._run(cmd)
253 except Exception as e:
254 action_fail('command failed: {}, errors: {}'.format(e, e.output))
255 else:
256 action_set({'stdout': result,
257 'errors': err})
258 finally:
259 remove_flag('actions.stop-traffic')
260
261
262 def format_curl(method, path, data=None):
263 """ A utility function to build the curl command line. """
264
265 # method must be GET or POST
266 if method not in ['GET', 'POST']:
267 # Throw exception
268 return None
269
270 # Get our service info
271 host = '127.0.0.1'
272 port = get_port()
273 mode = cfg['mode']
274
275 cmd = ['curl',
276 # '-D', '/dev/stdout',
277 '-H', 'Accept: application/vnd.yang.data+xml',
278 '-H', 'Content-Type: application/vnd.yang.data+json',
279 '-X', method]
280
281 if method == "POST" and data:
282 cmd.append('-d')
283 cmd.append('{}'.format(data))
284
285 cmd.append(
286 'http://{}:{}/api/v1/{}{}'.format(host, port, mode, path)
287 )
288 return cmd