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 collections import OrderedDict
17
from hookenv import log, execution_environment
20
def service_start(service_name):
21
service('start', service_name)
24
def service_stop(service_name):
25
service('stop', service_name)
28
def service_restart(service_name):
29
service('restart', service_name)
32
def service_reload(service_name, restart_on_failure=False):
33
if not service('reload', service_name) and restart_on_failure:
34
service('restart', service_name)
37
def service(action, service_name):
38
cmd = ['service', service_name, action]
39
return subprocess.call(cmd) == 0
42
def adduser(username, password=None, shell='/bin/bash', system_user=False):
45
user_info = pwd.getpwnam(username)
46
log('user {0} already exists!'.format(username))
48
log('creating user {0}'.format(username))
50
if system_user or password is None:
51
cmd.append('--system')
56
'--password', password,
59
subprocess.check_call(cmd)
60
user_info = pwd.getpwnam(username)
64
def add_user_to_group(username, group):
65
"""Add a user to a group"""
71
log("Adding user {} to group {}".format(username, group))
72
subprocess.check_call(cmd)
75
def rsync(from_path, to_path, flags='-r', options=None):
76
"""Replicate the contents of a path"""
77
context = execution_environment()
78
options = options or ['--delete', '--executability']
79
cmd = ['/usr/bin/rsync', flags]
81
cmd.append(from_path.format(**context))
82
cmd.append(to_path.format(**context))
84
return subprocess.check_output(cmd).strip()
87
def symlink(source, destination):
88
"""Create a symbolic link"""
89
context = execution_environment()
90
log("Symlinking {} as {}".format(source, destination))
94
source.format(**context),
95
destination.format(**context)
97
subprocess.check_call(cmd)
100
def mkdir(path, owner='root', group='root', perms=0555, force=False):
101
"""Create a directory"""
102
context = execution_environment()
103
log("Making dir {} {}:{} {:o}".format(path, owner, group,
105
uid = pwd.getpwnam(owner.format(**context)).pw_uid
106
gid = grp.getgrnam(group.format(**context)).gr_gid
107
realpath = os.path.abspath(path)
108
if os.path.exists(realpath):
109
if force and not os.path.isdir(realpath):
110
log("Removing non-directory file {} prior to mkdir()".format(path))
113
os.makedirs(realpath, perms)
114
os.chown(realpath, uid, gid)
117
def write_file(path, fmtstr, owner='root', group='root', perms=0444, **kwargs):
118
"""Create or overwrite a file with the contents of a string"""
119
context = execution_environment()
120
context.update(kwargs)
121
log("Writing file {} {}:{} {:o}".format(path, owner, group,
123
uid = pwd.getpwnam(owner.format(**context)).pw_uid
124
gid = grp.getgrnam(group.format(**context)).gr_gid
125
with open(path.format(**context), 'w') as target:
126
os.fchown(target.fileno(), uid, gid)
127
os.fchmod(target.fileno(), perms)
128
target.write(fmtstr.format(**context))
131
def render_template_file(source, destination, **kwargs):
132
"""Create or overwrite a file using a template"""
133
log("Rendering template {} for {}".format(source,
135
context = execution_environment()
136
with open(source.format(**context), 'r') as template:
137
write_file(destination.format(**context), template.read(),
141
def filter_installed_packages(packages):
142
"""Returns a list of packages that require installation"""
144
cache = apt_pkg.Cache()
146
for package in packages:
149
p.current_ver or _pkgs.append(package)
151
log('Package {} has no installation candidate.'.format(package),
153
_pkgs.append(package)
157
def apt_install(packages, options=None, fatal=False):
158
"""Install one or more packages"""
159
options = options or []
160
cmd = ['apt-get', '-y']
162
cmd.append('install')
163
if isinstance(packages, basestring):
167
log("Installing {} with options: {}".format(packages,
170
subprocess.check_call(cmd)
175
def apt_update(fatal=False):
176
"""Update local apt cache"""
177
cmd = ['apt-get', 'update']
179
subprocess.check_call(cmd)
184
def mount(device, mountpoint, options=None, persist=False):
185
'''Mount a filesystem'''
187
if options is not None:
188
cmd_args.extend(['-o', options])
189
cmd_args.extend([device, mountpoint])
191
subprocess.check_output(cmd_args)
192
except subprocess.CalledProcessError, e:
193
log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output))
201
def umount(mountpoint, persist=False):
202
'''Unmount a filesystem'''
203
cmd_args = ['umount', mountpoint]
205
subprocess.check_output(cmd_args)
206
except subprocess.CalledProcessError, e:
207
log('Error unmounting {}\n{}'.format(mountpoint, e.output))
216
'''List of all mounted volumes as [[mountpoint,device],[...]]'''
217
with open('/proc/mounts') as f:
218
# [['/mount/point','/dev/path'],[...]]
219
system_mounts = [m[1::-1] for m in [l.strip().split()
220
for l in f.readlines()]]
225
''' Generate a md5 hash of the contents of 'path' or None if not found '''
226
if os.path.exists(path):
228
with open(path, 'r') as source:
229
h.update(source.read()) # IGNORE:E1101 - it does have update
235
def restart_on_change(restart_map):
236
''' Restart services based on configuration files changing
238
This function is used a decorator, for example
241
'/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ]
243
def ceph_client_changed():
246
In this example, the cinder-api and cinder-volume services
247
would be restarted if /etc/ceph/ceph.conf is changed by the
248
ceph_client_changed function.
251
def wrapped_f(*args):
253
for path in restart_map:
254
checksums[path] = file_hash(path)
257
for path in restart_map:
258
if checksums[path] != file_hash(path):
259
restarts += restart_map[path]
260
for service_name in list(OrderedDict.fromkeys(restarts)):
261
service('restart', service_name)