~ajkavanagh/charms/trusty/mongodb/fix-unit-test-lint-lp1533654

« back to all changes in this revision

Viewing changes to hooks/charmhelpers/core/host.py

  • Committer: Jorge Niedbalski
  • Author(s): Mario Splivalo
  • Date: 2014-12-10 15:36:14 UTC
  • mfrom: (61.1.3 mongodb)
  • Revision ID: jorge.niedbalski@canonical.com-20141210153614-epxz8q6bqm5v6vil
[mariosplivalo, r=niedbalski] Upgrades charmhelpers, and adds contrib.hahelpers.cluster, make lint fixes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
6
6
#  Matthew Wedgwood <matthew.wedgwood@canonical.com>
7
7
 
8
8
import os
 
9
import re
9
10
import pwd
10
11
import grp
11
12
import random
12
13
import string
13
14
import subprocess
14
15
import hashlib
15
 
 
 
16
from contextlib import contextmanager
16
17
from collections import OrderedDict
17
18
 
18
 
from hookenv import log
19
 
from fstab import Fstab
 
19
import six
 
20
 
 
21
from .hookenv import log
 
22
from .fstab import Fstab
20
23
 
21
24
 
22
25
def service_start(service_name):
52
55
def service_running(service):
53
56
    """Determine whether a system service is running"""
54
57
    try:
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:
57
62
        return False
58
63
    else:
62
67
            return False
63
68
 
64
69
 
 
70
def service_available(service_name):
 
71
    """Determine whether a system service is available"""
 
72
    try:
 
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
 
78
    else:
 
79
        return True
 
80
 
 
81
 
65
82
def adduser(username, password=None, shell='/bin/bash', system_user=False):
66
83
    """Add a user to the system"""
67
84
    try:
84
101
    return user_info
85
102
 
86
103
 
 
104
def add_group(group_name, system_group=False):
 
105
    """Add a group to the system"""
 
106
    try:
 
107
        group_info = grp.getgrnam(group_name)
 
108
        log('group {0} already exists!'.format(group_name))
 
109
    except KeyError:
 
110
        log('creating group {0}'.format(group_name))
 
111
        cmd = ['addgroup']
 
112
        if system_group:
 
113
            cmd.append('--system')
 
114
        else:
 
115
            cmd.extend([
 
116
                '--group',
 
117
            ])
 
118
        cmd.append(group_name)
 
119
        subprocess.check_call(cmd)
 
120
        group_info = grp.getgrnam(group_name)
 
121
    return group_info
 
122
 
 
123
 
87
124
def add_user_to_group(username, group):
88
125
    """Add a user to a group"""
89
126
    cmd = [
103
140
    cmd.append(from_path)
104
141
    cmd.append(to_path)
105
142
    log(" ".join(cmd))
106
 
    return subprocess.check_output(cmd).strip()
 
143
    return subprocess.check_output(cmd).decode('UTF-8').strip()
107
144
 
108
145
 
109
146
def symlink(source, destination):
118
155
    subprocess.check_call(cmd)
119
156
 
120
157
 
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,
124
161
                                          perms))
134
171
    os.chown(realpath, uid, gid)
135
172
 
136
173
 
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])
166
203
    try:
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))
170
207
        return False
171
208
 
179
216
    cmd_args = ['umount', mountpoint]
180
217
    try:
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))
184
221
        return False
185
222
 
197
234
    return system_mounts
198
235
 
199
236
 
200
 
def file_hash(path):
201
 
    """Generate a md5 hash of the contents of 'path' or None if not found """
 
237
def file_hash(path, hash_type='md5'):
 
238
    """
 
239
    Generate a hash checksum of the contents of 'path' or None if not found.
 
240
 
 
241
    :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`,
 
242
                          such as md5, sha1, sha256, sha512, etc.
 
243
    """
202
244
    if os.path.exists(path):
203
 
        h = hashlib.md5()
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()
207
249
    else:
208
250
        return None
209
251
 
210
252
 
 
253
def check_hash(path, checksum, hash_type='md5'):
 
254
    """
 
255
    Validate a file using a cryptographic checksum.
 
256
 
 
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
 
262
 
 
263
    """
 
264
    actual_checksum = file_hash(path, hash_type)
 
265
    if checksum != actual_checksum:
 
266
        raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum))
 
267
 
 
268
 
 
269
class ChecksumError(ValueError):
 
270
    pass
 
271
 
 
272
 
211
273
def restart_on_change(restart_map, stopstart=False):
212
274
    """Restart services based on configuration files changing
213
275
 
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']
265
327
    random_chars = [
266
328
        random.choice(alphanumeric_chars) for _ in range(length)]
269
331
 
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]
274
336
    else:
275
337
        int_types = nic_type
276
338
    interfaces = []
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)
 
346
                if matched:
 
347
                    interface = matched.groups()[0]
 
348
                else:
 
349
                    interface = line.split()[1].replace(":", "")
 
350
                interfaces.append(interface)
 
351
 
284
352
    return interfaces
285
353
 
286
354
 
292
360
 
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')
296
364
    mtu = ""
297
365
    for line in ip_output:
298
366
        words = line.split()
303
371
 
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')
307
375
    hwaddr = ""
308
376
    words = ip_output.split()
309
377
    if 'link/ether' in words:
321
389
    '''
322
390
    import apt_pkg
323
391
    if not pkgcache:
324
 
        apt_pkg.init()
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)
 
396
 
 
397
 
 
398
@contextmanager
 
399
def chdir(d):
 
400
    cur = os.getcwd()
 
401
    try:
 
402
        yield os.chdir(d)
 
403
    finally:
 
404
        os.chdir(cur)
 
405
 
 
406
 
 
407
def chownr(path, owner, group):
 
408
    uid = pwd.getpwnam(owner).pw_uid
 
409
    gid = grp.getgrnam(group).gr_gid
 
410
 
 
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)