52
55
def service_running(service):
53
56
"""Determine whether a system service is running"""
55
output = subprocess.check_output(['service', service, 'status'])
58
output = subprocess.check_output(
59
['service', service, 'status'],
60
stderr=subprocess.STDOUT).decode('UTF-8')
56
61
except subprocess.CalledProcessError:
70
def service_available(service_name):
71
"""Determine whether a system service is available"""
73
subprocess.check_output(
74
['service', service_name, 'status'],
75
stderr=subprocess.STDOUT).decode('UTF-8')
76
except subprocess.CalledProcessError as e:
77
return 'unrecognized service' not in e.output
65
82
def adduser(username, password=None, shell='/bin/bash', system_user=False):
66
83
"""Add a user to the system"""
104
def add_group(group_name, system_group=False):
105
"""Add a group to the system"""
107
group_info = grp.getgrnam(group_name)
108
log('group {0} already exists!'.format(group_name))
110
log('creating group {0}'.format(group_name))
113
cmd.append('--system')
118
cmd.append(group_name)
119
subprocess.check_call(cmd)
120
group_info = grp.getgrnam(group_name)
87
124
def add_user_to_group(username, group):
88
125
"""Add a user to a group"""
118
155
subprocess.check_call(cmd)
121
def mkdir(path, owner='root', group='root', perms=0555, force=False):
158
def mkdir(path, owner='root', group='root', perms=0o555, force=False):
122
159
"""Create a directory"""
123
160
log("Making dir {} {}:{} {:o}".format(path, owner, group,
134
171
os.chown(realpath, uid, gid)
137
def write_file(path, content, owner='root', group='root', perms=0444):
174
def write_file(path, content, owner='root', group='root', perms=0o444):
138
175
"""Create or overwrite a file with the contents of a string"""
139
176
log("Writing file {} {}:{} {:o}".format(path, owner, group, perms))
140
177
uid = pwd.getpwnam(owner).pw_uid
165
202
cmd_args.extend([device, mountpoint])
167
204
subprocess.check_output(cmd_args)
168
except subprocess.CalledProcessError, e:
205
except subprocess.CalledProcessError as e:
169
206
log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output))
179
216
cmd_args = ['umount', mountpoint]
181
218
subprocess.check_output(cmd_args)
182
except subprocess.CalledProcessError, e:
219
except subprocess.CalledProcessError as e:
183
220
log('Error unmounting {}\n{}'.format(mountpoint, e.output))
197
234
return system_mounts
201
"""Generate a md5 hash of the contents of 'path' or None if not found """
237
def file_hash(path, hash_type='md5'):
239
Generate a hash checksum of the contents of 'path' or None if not found.
241
:param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`,
242
such as md5, sha1, sha256, sha512, etc.
202
244
if os.path.exists(path):
204
with open(path, 'r') as source:
205
h.update(source.read()) # IGNORE:E1101 - it does have update
245
h = getattr(hashlib, hash_type)()
246
with open(path, 'rb') as source:
247
h.update(source.read())
206
248
return h.hexdigest()
253
def check_hash(path, checksum, hash_type='md5'):
255
Validate a file using a cryptographic checksum.
257
:param str checksum: Value of the checksum used to validate the file.
258
:param str hash_type: Hash algorithm used to generate `checksum`.
259
Can be any hash alrgorithm supported by :mod:`hashlib`,
260
such as md5, sha1, sha256, sha512, etc.
261
:raises ChecksumError: If the file fails the checksum
264
actual_checksum = file_hash(path, hash_type)
265
if checksum != actual_checksum:
266
raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum))
269
class ChecksumError(ValueError):
211
273
def restart_on_change(restart_map, stopstart=False):
212
274
"""Restart services based on configuration files changing
260
322
if length is None:
261
323
length = random.choice(range(35, 45))
262
324
alphanumeric_chars = [
263
l for l in (string.letters + string.digits)
325
l for l in (string.ascii_letters + string.digits)
264
326
if l not in 'l0QD1vAEIOUaeiou']
266
328
random.choice(alphanumeric_chars) for _ in range(length)]
270
332
def list_nics(nic_type):
271
333
'''Return a list of nics of given type(s)'''
272
if isinstance(nic_type, basestring):
334
if isinstance(nic_type, six.string_types):
273
335
int_types = [nic_type]
275
337
int_types = nic_type
277
339
for int_type in int_types:
278
340
cmd = ['ip', 'addr', 'show', 'label', int_type + '*']
279
ip_output = subprocess.check_output(cmd).split('\n')
341
ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n')
280
342
ip_output = (line for line in ip_output if line)
281
343
for line in ip_output:
282
344
if line.split()[1].startswith(int_type):
283
interfaces.append(line.split()[1].replace(":", ""))
345
matched = re.search('.*: (bond[0-9]+\.[0-9]+)@.*', line)
347
interface = matched.groups()[0]
349
interface = line.split()[1].replace(":", "")
350
interfaces.append(interface)
284
352
return interfaces
293
361
def get_nic_mtu(nic):
294
362
cmd = ['ip', 'addr', 'show', nic]
295
ip_output = subprocess.check_output(cmd).split('\n')
363
ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n')
297
365
for line in ip_output:
298
366
words = line.split()
304
372
def get_nic_hwaddr(nic):
305
373
cmd = ['ip', '-o', '-0', 'addr', 'show', nic]
306
ip_output = subprocess.check_output(cmd)
374
ip_output = subprocess.check_output(cmd).decode('UTF-8')
308
376
words = ip_output.split()
309
377
if 'link/ether' in words:
325
pkgcache = apt_pkg.Cache()
392
from charmhelpers.fetch import apt_cache
393
pkgcache = apt_cache()
326
394
pkg = pkgcache[package]
327
395
return apt_pkg.version_compare(pkg.current_ver.ver_str, revno)
407
def chownr(path, owner, group):
408
uid = pwd.getpwnam(owner).pw_uid
409
gid = grp.getgrnam(group).gr_gid
411
for root, dirs, files in os.walk(path):
412
for name in dirs + files:
413
full = os.path.join(root, name)
414
broken_symlink = os.path.lexists(full) and not os.path.exists(full)
415
if not broken_symlink:
416
os.chown(full, uid, gid)