~hopem/charms/trusty/glance/charm-helpers-sync-precise-ipv6-haproxy

« back to all changes in this revision

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

  • Committer: james.page at ubuntu
  • Date: 2014-12-15 09:17:53 UTC
  • mfrom: (82.1.8 glance)
  • Revision ID: james.page@ubuntu.com-20141215091753-23bixw725p75pcdp
[corey.bryant,r=james-page] Sort out charmhelpers issues.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
import subprocess
15
15
import hashlib
16
16
from contextlib import contextmanager
17
 
 
18
17
from collections import OrderedDict
19
18
 
20
 
from hookenv import log
21
 
from fstab import Fstab
 
19
import six
 
20
 
 
21
from .hookenv import log
 
22
from .fstab import Fstab
22
23
 
23
24
 
24
25
def service_start(service_name):
54
55
def service_running(service):
55
56
    """Determine whether a system service is running"""
56
57
    try:
57
 
        output = subprocess.check_output(['service', service, 'status'], stderr=subprocess.STDOUT)
 
58
        output = subprocess.check_output(
 
59
            ['service', service, 'status'],
 
60
            stderr=subprocess.STDOUT).decode('UTF-8')
58
61
    except subprocess.CalledProcessError:
59
62
        return False
60
63
    else:
67
70
def service_available(service_name):
68
71
    """Determine whether a system service is available"""
69
72
    try:
70
 
        subprocess.check_output(['service', service_name, 'status'], stderr=subprocess.STDOUT)
 
73
        subprocess.check_output(
 
74
            ['service', service_name, 'status'],
 
75
            stderr=subprocess.STDOUT).decode('UTF-8')
71
76
    except subprocess.CalledProcessError as e:
72
77
        return 'unrecognized service' not in e.output
73
78
    else:
96
101
    return user_info
97
102
 
98
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
 
99
124
def add_user_to_group(username, group):
100
125
    """Add a user to a group"""
101
126
    cmd = [
115
140
    cmd.append(from_path)
116
141
    cmd.append(to_path)
117
142
    log(" ".join(cmd))
118
 
    return subprocess.check_output(cmd).strip()
 
143
    return subprocess.check_output(cmd).decode('UTF-8').strip()
119
144
 
120
145
 
121
146
def symlink(source, destination):
130
155
    subprocess.check_call(cmd)
131
156
 
132
157
 
133
 
def mkdir(path, owner='root', group='root', perms=0555, force=False):
 
158
def mkdir(path, owner='root', group='root', perms=0o555, force=False):
134
159
    """Create a directory"""
135
160
    log("Making dir {} {}:{} {:o}".format(path, owner, group,
136
161
                                          perms))
146
171
    os.chown(realpath, uid, gid)
147
172
 
148
173
 
149
 
def write_file(path, content, owner='root', group='root', perms=0444):
 
174
def write_file(path, content, owner='root', group='root', perms=0o444):
150
175
    """Create or overwrite a file with the contents of a string"""
151
176
    log("Writing file {} {}:{} {:o}".format(path, owner, group, perms))
152
177
    uid = pwd.getpwnam(owner).pw_uid
177
202
    cmd_args.extend([device, mountpoint])
178
203
    try:
179
204
        subprocess.check_output(cmd_args)
180
 
    except subprocess.CalledProcessError, e:
 
205
    except subprocess.CalledProcessError as e:
181
206
        log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output))
182
207
        return False
183
208
 
191
216
    cmd_args = ['umount', mountpoint]
192
217
    try:
193
218
        subprocess.check_output(cmd_args)
194
 
    except subprocess.CalledProcessError, e:
 
219
    except subprocess.CalledProcessError as e:
195
220
        log('Error unmounting {}\n{}'.format(mountpoint, e.output))
196
221
        return False
197
222
 
218
243
    """
219
244
    if os.path.exists(path):
220
245
        h = getattr(hashlib, hash_type)()
221
 
        with open(path, 'r') as source:
222
 
            h.update(source.read())  # IGNORE:E1101 - it does have update
 
246
        with open(path, 'rb') as source:
 
247
            h.update(source.read())
223
248
        return h.hexdigest()
224
249
    else:
225
250
        return None
297
322
    if length is None:
298
323
        length = random.choice(range(35, 45))
299
324
    alphanumeric_chars = [
300
 
        l for l in (string.letters + string.digits)
 
325
        l for l in (string.ascii_letters + string.digits)
301
326
        if l not in 'l0QD1vAEIOUaeiou']
302
327
    random_chars = [
303
328
        random.choice(alphanumeric_chars) for _ in range(length)]
306
331
 
307
332
def list_nics(nic_type):
308
333
    '''Return a list of nics of given type(s)'''
309
 
    if isinstance(nic_type, basestring):
 
334
    if isinstance(nic_type, six.string_types):
310
335
        int_types = [nic_type]
311
336
    else:
312
337
        int_types = nic_type
313
338
    interfaces = []
314
339
    for int_type in int_types:
315
340
        cmd = ['ip', 'addr', 'show', 'label', int_type + '*']
316
 
        ip_output = subprocess.check_output(cmd).split('\n')
 
341
        ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n')
317
342
        ip_output = (line for line in ip_output if line)
318
343
        for line in ip_output:
319
344
            if line.split()[1].startswith(int_type):
335
360
 
336
361
def get_nic_mtu(nic):
337
362
    cmd = ['ip', 'addr', 'show', nic]
338
 
    ip_output = subprocess.check_output(cmd).split('\n')
 
363
    ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n')
339
364
    mtu = ""
340
365
    for line in ip_output:
341
366
        words = line.split()
346
371
 
347
372
def get_nic_hwaddr(nic):
348
373
    cmd = ['ip', '-o', '-0', 'addr', 'show', nic]
349
 
    ip_output = subprocess.check_output(cmd)
 
374
    ip_output = subprocess.check_output(cmd).decode('UTF-8')
350
375
    hwaddr = ""
351
376
    words = ip_output.split()
352
377
    if 'link/ether' in words:
363
388
 
364
389
    '''
365
390
    import apt_pkg
366
 
    from charmhelpers.fetch import apt_cache
367
391
    if not pkgcache:
 
392
        from charmhelpers.fetch import apt_cache
368
393
        pkgcache = apt_cache()
369
394
    pkg = pkgcache[package]
370
395
    return apt_pkg.version_compare(pkg.current_ver.ver_str, revno)