1
"""Tools for working with the host system"""
2
# Copyright 2012 Canonical Ltd.
5
# Nick Moffitt <nick.moffitt@canonical.com>
6
# Matthew Wedgwood <matthew.wedgwood@canonical.com>
15
from hookenv import log, execution_environment
18
def service_start(service_name):
19
service('start', service_name)
22
def service_stop(service_name):
23
service('stop', service_name)
26
def service_restart(service_name):
27
service('restart', service_name)
30
def service_reload(service_name, restart_on_failure=False):
31
if not service('reload', service_name) and restart_on_failure:
32
service('restart', service_name)
35
def service(action, service_name):
36
cmd = ['service', service_name, action]
37
return subprocess.call(cmd) == 0
40
def adduser(username, password=None, shell='/bin/bash', system_user=False):
43
user_info = pwd.getpwnam(username)
44
log('user {0} already exists!'.format(username))
46
log('creating user {0}'.format(username))
48
if system_user or password is None:
49
cmd.append('--system')
54
'--password', password,
57
subprocess.check_call(cmd)
58
user_info = pwd.getpwnam(username)
62
def add_user_to_group(username, group):
63
"""Add a user to a group"""
69
log("Adding user {} to group {}".format(username, group))
70
subprocess.check_call(cmd)
73
def rsync(from_path, to_path, flags='-r', options=None):
74
"""Replicate the contents of a path"""
75
context = execution_environment()
76
options = options or ['--delete', '--executability']
77
cmd = ['/usr/bin/rsync', flags]
79
cmd.append(from_path.format(**context))
80
cmd.append(to_path.format(**context))
82
return subprocess.check_output(cmd).strip()
85
def symlink(source, destination):
86
"""Create a symbolic link"""
87
context = execution_environment()
88
log("Symlinking {} as {}".format(source, destination))
92
source.format(**context),
93
destination.format(**context)
95
subprocess.check_call(cmd)
98
def mkdir(path, owner='root', group='root', perms=0555, force=False):
99
"""Create a directory"""
100
context = execution_environment()
101
log("Making dir {} {}:{} {:o}".format(path, owner, group,
103
uid = pwd.getpwnam(owner.format(**context)).pw_uid
104
gid = grp.getgrnam(group.format(**context)).gr_gid
105
realpath = os.path.abspath(path)
106
if os.path.exists(realpath):
107
if force and not os.path.isdir(realpath):
108
log("Removing non-directory file {} prior to mkdir()".format(path))
111
os.makedirs(realpath, perms)
112
os.chown(realpath, uid, gid)
115
def write_file(path, fmtstr, owner='root', group='root', perms=0444, **kwargs):
116
"""Create or overwrite a file with the contents of a string"""
117
context = execution_environment()
118
context.update(kwargs)
119
log("Writing file {} {}:{} {:o}".format(path, owner, group,
121
uid = pwd.getpwnam(owner.format(**context)).pw_uid
122
gid = grp.getgrnam(group.format(**context)).gr_gid
123
with open(path.format(**context), 'w') as target:
124
os.fchown(target.fileno(), uid, gid)
125
os.fchmod(target.fileno(), perms)
126
target.write(fmtstr.format(**context))
129
def render_template_file(source, destination, **kwargs):
130
"""Create or overwrite a file using a template"""
131
log("Rendering template {} for {}".format(source,
133
context = execution_environment()
134
with open(source.format(**context), 'r') as template:
135
write_file(destination.format(**context), template.read(),
139
def filter_installed_packages(packages):
140
"""Returns a list of packages that require installation"""
142
cache = apt_pkg.Cache()
144
for package in packages:
147
p.current_ver or _pkgs.append(package)
149
log('Package {} has no installation candidate.'.format(package),
151
_pkgs.append(package)
155
def apt_install(packages, options=None, fatal=False):
156
"""Install one or more packages"""
157
options = options or []
158
cmd = ['apt-get', '-y']
160
cmd.append('install')
161
if isinstance(packages, basestring):
165
log("Installing {} with options: {}".format(packages,
168
subprocess.check_call(cmd)
173
def apt_update(fatal=False):
174
"""Update local apt cache"""
175
cmd = ['apt-get', 'update']
177
subprocess.check_call(cmd)
182
def mount(device, mountpoint, options=None, persist=False):
183
'''Mount a filesystem'''
185
if options is not None:
186
cmd_args.extend(['-o', options])
187
cmd_args.extend([device, mountpoint])
189
subprocess.check_output(cmd_args)
190
except subprocess.CalledProcessError, e:
191
log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output))
199
def umount(mountpoint, persist=False):
200
'''Unmount a filesystem'''
201
cmd_args = ['umount', mountpoint]
203
subprocess.check_output(cmd_args)
204
except subprocess.CalledProcessError, e:
205
log('Error unmounting {}\n{}'.format(mountpoint, e.output))
214
'''List of all mounted volumes as [[mountpoint,device],[...]]'''
215
with open('/proc/mounts') as f:
216
# [['/mount/point','/dev/path'],[...]]
217
system_mounts = [m[1::-1] for m in [l.strip().split()
218
for l in f.readlines()]]
223
''' Generate a md5 hash of the contents of 'path' or None if not found '''
224
if os.path.exists(path):
226
with open(path, 'r') as source:
227
h.update(source.read()) # IGNORE:E1101 - it does have update
233
def restart_on_change(restart_map):
234
''' Restart services based on configuration files changing
236
This function is used a decorator, for example
239
'/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ]
241
def ceph_client_changed():
244
In this example, the cinder-api and cinder-volume services
245
would be restarted if /etc/ceph/ceph.conf is changed by the
246
ceph_client_changed function.
249
def wrapped_f(*args):
251
for path in restart_map:
252
checksums[path] = file_hash(path)
255
for path in restart_map:
256
if checksums[path] != file_hash(path):
257
restarts += restart_map[path]
258
for service_name in list(set(restarts)):
259
service('restart', service_name)