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