~corey.bryant/charms/trusty/neutron-api/db-stamp

« back to all changes in this revision

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

  • Committer: james.page at ubuntu
  • Date: 2014-10-01 21:05:24 UTC
  • mfrom: (39.3.25 ipv6)
  • Revision ID: james.page@ubuntu.com-20141001210524-z6uqyljzorphrhy6
[xianghui,dosaboy,r=james-page,t=gema] Add IPv6 support using prefer-ipv6 flag

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
import string
13
13
import subprocess
14
14
import hashlib
 
15
import shutil
 
16
from contextlib import contextmanager
15
17
 
16
18
from collections import OrderedDict
17
19
 
52
54
def service_running(service):
53
55
    """Determine whether a system service is running"""
54
56
    try:
55
 
        output = subprocess.check_output(['service', service, 'status'])
 
57
        output = subprocess.check_output(['service', service, 'status'], stderr=subprocess.STDOUT)
56
58
    except subprocess.CalledProcessError:
57
59
        return False
58
60
    else:
62
64
            return False
63
65
 
64
66
 
 
67
def service_available(service_name):
 
68
    """Determine whether a system service is available"""
 
69
    try:
 
70
        subprocess.check_output(['service', service_name, 'status'], stderr=subprocess.STDOUT)
 
71
    except subprocess.CalledProcessError as e:
 
72
        return 'unrecognized service' not in e.output
 
73
    else:
 
74
        return True
 
75
 
 
76
 
65
77
def adduser(username, password=None, shell='/bin/bash', system_user=False):
66
78
    """Add a user to the system"""
67
79
    try:
197
209
    return system_mounts
198
210
 
199
211
 
200
 
def file_hash(path):
201
 
    """Generate a md5 hash of the contents of 'path' or None if not found """
 
212
def file_hash(path, hash_type='md5'):
 
213
    """
 
214
    Generate a hash checksum of the contents of 'path' or None if not found.
 
215
 
 
216
    :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`,
 
217
                          such as md5, sha1, sha256, sha512, etc.
 
218
    """
202
219
    if os.path.exists(path):
203
 
        h = hashlib.md5()
 
220
        h = getattr(hashlib, hash_type)()
204
221
        with open(path, 'r') as source:
205
222
            h.update(source.read())  # IGNORE:E1101 - it does have update
206
223
        return h.hexdigest()
208
225
        return None
209
226
 
210
227
 
 
228
def check_hash(path, checksum, hash_type='md5'):
 
229
    """
 
230
    Validate a file using a cryptographic checksum.
 
231
 
 
232
    :param str checksum: Value of the checksum used to validate the file.
 
233
    :param str hash_type: Hash algorithm used to generate `checksum`.
 
234
        Can be any hash alrgorithm supported by :mod:`hashlib`,
 
235
        such as md5, sha1, sha256, sha512, etc.
 
236
    :raises ChecksumError: If the file fails the checksum
 
237
 
 
238
    """
 
239
    actual_checksum = file_hash(path, hash_type)
 
240
    if checksum != actual_checksum:
 
241
        raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum))
 
242
 
 
243
 
 
244
class ChecksumError(ValueError):
 
245
    pass
 
246
 
 
247
 
211
248
def restart_on_change(restart_map, stopstart=False):
212
249
    """Restart services based on configuration files changing
213
250
 
320
357
 
321
358
    '''
322
359
    import apt_pkg
 
360
    from charmhelpers.fetch import apt_cache
323
361
    if not pkgcache:
324
 
        apt_pkg.init()
325
 
        # Force Apt to build its cache in memory. That way we avoid race
326
 
        # conditions with other applications building the cache in the same
327
 
        # place.
328
 
        apt_pkg.config.set("Dir::Cache::pkgcache", "")
329
 
        pkgcache = apt_pkg.Cache()
 
362
        pkgcache = apt_cache()
330
363
    pkg = pkgcache[package]
331
364
    return apt_pkg.version_compare(pkg.current_ver.ver_str, revno)
 
365
 
 
366
 
 
367
@contextmanager
 
368
def chdir(d):
 
369
    cur = os.getcwd()
 
370
    try:
 
371
        yield os.chdir(d)
 
372
    finally:
 
373
        os.chdir(cur)
 
374
 
 
375
 
 
376
def chownr(path, owner, group):
 
377
    uid = pwd.getpwnam(owner).pw_uid
 
378
    gid = grp.getgrnam(group).gr_gid
 
379
 
 
380
    for root, dirs, files in os.walk(path):
 
381
        for name in dirs + files:
 
382
            full = os.path.join(root, name)
 
383
            broken_symlink = os.path.lexists(full) and not os.path.exists(full)
 
384
            if not broken_symlink:
 
385
                os.chown(full, uid, gid)