e1508ca0a2bd340e645fadb3fe3734403c6c6295
[osm/SO.git] / charms / layers / sshproxy / reactive / sshproxy.py
1 ##
2 # Copyright 2016 Canonical Ltd.
3 # All rights reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may
6 # not use this file except in compliance with the License. You may obtain
7 # a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 # License for the specific language governing permissions and limitations
15 # under the License.
16 ##
17
18 from charmhelpers.core.hookenv import (
19 action_fail,
20 action_get,
21 action_set,
22 config,
23 )
24 from charms.reactive import (
25 remove_state,
26 set_state,
27 when,
28 )
29 import charms.sshproxy
30 import subprocess
31
32
33 @when('config.changed')
34 def ssh_configured():
35 """ Checks to see if the charm is configured with SSH credentials. If so,
36 set a state flag that can be used to execute ssh-only actions.
37
38 For example:
39
40 @when('sshproxy.configured')
41 def run_remote_command(cmd):
42 ...
43
44 @when_not('sshproxy.configured')
45 def run_local_command(cmd):
46 ...
47 """
48 cfg = config()
49 if all(k in cfg for k in ['ssh-hostname', 'ssh-username',
50 'ssh-password', 'ssh-private-key']):
51 set_state('sshproxy.configured')
52 else:
53 remove_state('sshproxy.configured')
54
55
56 @when('actions.run')
57 def run_command():
58 """
59 Run an arbitrary command, either locally or over SSH with the configured
60 credentials.
61 """
62 try:
63 cmd = action_get('command')
64 output, err = charms.sshproxy._run(cmd)
65 if len(err):
66 action_fail("Command '{}' returned error code {}".format(cmd, err))
67 else:
68 action_set({'output': output})
69 except subprocess.CalledProcessError as e:
70 action_fail('Command failed: %s (%s)' %
71 (' '.join(e.cmd), str(e.output)))
72 finally:
73 remove_state('actions.run')