blob: 8f8db268acbed7ab3ddcf43a00d676d13f08f931 [file] [log] [blame]
Adam Israel33779282016-10-05 09:08:16 -07001from charmhelpers.core.hookenv import (
2 config,
3 status_set,
4 action_get,
5 action_set,
6 action_fail,
7 log,
8)
9
10from charms.reactive import (
11 when,
12 when_not,
13 set_state as set_flag,
14 remove_state as remove_flag,
15)
16
17import subprocess
18
19
20@when_not('netutils.ready')
21def ready():
22 status_set('active', 'Ready!')
23 set_flag('netutils.ready')
24
25
26@when('actions.nmap')
27def nmap():
28 err = ''
29 try:
30 result, err = _run('nmap {}'.format(action_get('destination')))
31 except:
32 action_fail('nmap command failed:' + err)
33 else:
34 action_set({'outout': result})
35 finally:
36 remove_flag('actions.nmap')
37
38
39@when('actions.ping')
40def ping():
41 err = ''
42 try:
43 result, err = _run('ping -qc {} {}'.format(
44 action_get('count'), action_get('destination'))
45 )
46
47 except:
48 action_fail('ping command failed:' + err)
49 else:
50 # Here you can send results back from ping, if you had time to parse it
51 action_set({'output': result})
52 finally:
53 remove_flag('actions.ping')
54
55
56
57@when('actions.traceroute')
58def traceroute():
59 try:
60 result, err = _run('traceroute -m {} {}'.format(action_get('hops'), action_get('destination')))
61 except:
62 action_fail('traceroute command failed')
63 else:
64 # Here you can send results back from ping, if you had time to parse it
65 action_set({'output': result})
66 finally:
67 remove_flag('actions.traceroute')
68
69
70
71def _run(cmd, env=None):
72 if isinstance(cmd, str):
73 cmd = cmd.split() if ' ' in cmd else [cmd]
74
75 log(cmd)
76 p = subprocess.Popen(cmd,
77 env=env,
78 stdout=subprocess.PIPE,
79 stderr=subprocess.PIPE)
80 stdout, stderr = p.communicate()
81 retcode = p.poll()
82 if retcode > 0:
83 raise subprocess.CalledProcessError(returncode=retcode,
84 cmd=cmd,
85 output=stderr.decode("utf-8").strip())
86 return (stdout.decode('utf-8'), stderr.decode('utf-8'))