~openstack-charmers-archive/charms/trusty/neutron-gateway/trunk

« back to all changes in this revision

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

  • Committer: James Page
  • Date: 2015-10-22 13:23:58 UTC
  • Revision ID: james.page@ubuntu.com-20151022132358-qin1nvlnqn4aezaz
Tags: 15.10
15.10 Charm release

Show diffs side-by-side

added added

removed removed

Lines of Context:
63
63
    return service_result
64
64
 
65
65
 
66
 
def service_pause(service_name, init_dir=None):
 
66
def service_pause(service_name, init_dir="/etc/init", initd_dir="/etc/init.d"):
67
67
    """Pause a system service.
68
68
 
69
69
    Stop it, and prevent it from starting again at boot."""
70
 
    if init_dir is None:
71
 
        init_dir = "/etc/init"
72
70
    stopped = service_stop(service_name)
73
 
    # XXX: Support systemd too
74
 
    override_path = os.path.join(
75
 
        init_dir, '{}.conf.override'.format(service_name))
76
 
    with open(override_path, 'w') as fh:
77
 
        fh.write("manual\n")
 
71
    upstart_file = os.path.join(init_dir, "{}.conf".format(service_name))
 
72
    sysv_file = os.path.join(initd_dir, service_name)
 
73
    if os.path.exists(upstart_file):
 
74
        override_path = os.path.join(
 
75
            init_dir, '{}.override'.format(service_name))
 
76
        with open(override_path, 'w') as fh:
 
77
            fh.write("manual\n")
 
78
    elif os.path.exists(sysv_file):
 
79
        subprocess.check_call(["update-rc.d", service_name, "disable"])
 
80
    else:
 
81
        # XXX: Support SystemD too
 
82
        raise ValueError(
 
83
            "Unable to detect {0} as either Upstart {1} or SysV {2}".format(
 
84
                service_name, upstart_file, sysv_file))
78
85
    return stopped
79
86
 
80
87
 
81
 
def service_resume(service_name, init_dir=None):
 
88
def service_resume(service_name, init_dir="/etc/init",
 
89
                   initd_dir="/etc/init.d"):
82
90
    """Resume a system service.
83
91
 
84
92
    Reenable starting again at boot. Start the service"""
85
 
    # XXX: Support systemd too
86
 
    if init_dir is None:
87
 
        init_dir = "/etc/init"
88
 
    override_path = os.path.join(
89
 
        init_dir, '{}.conf.override'.format(service_name))
90
 
    if os.path.exists(override_path):
91
 
        os.unlink(override_path)
 
93
    upstart_file = os.path.join(init_dir, "{}.conf".format(service_name))
 
94
    sysv_file = os.path.join(initd_dir, service_name)
 
95
    if os.path.exists(upstart_file):
 
96
        override_path = os.path.join(
 
97
            init_dir, '{}.override'.format(service_name))
 
98
        if os.path.exists(override_path):
 
99
            os.unlink(override_path)
 
100
    elif os.path.exists(sysv_file):
 
101
        subprocess.check_call(["update-rc.d", service_name, "enable"])
 
102
    else:
 
103
        # XXX: Support SystemD too
 
104
        raise ValueError(
 
105
            "Unable to detect {0} as either Upstart {1} or SysV {2}".format(
 
106
                service_name, upstart_file, sysv_file))
 
107
 
92
108
    started = service_start(service_name)
93
109
    return started
94
110
 
148
164
    return user_info
149
165
 
150
166
 
 
167
def user_exists(username):
 
168
    """Check if a user exists"""
 
169
    try:
 
170
        pwd.getpwnam(username)
 
171
        user_exists = True
 
172
    except KeyError:
 
173
        user_exists = False
 
174
    return user_exists
 
175
 
 
176
 
151
177
def add_group(group_name, system_group=False):
152
178
    """Add a group to the system"""
153
179
    try:
280
306
    return system_mounts
281
307
 
282
308
 
 
309
def fstab_mount(mountpoint):
 
310
    """Mount filesystem using fstab"""
 
311
    cmd_args = ['mount', mountpoint]
 
312
    try:
 
313
        subprocess.check_output(cmd_args)
 
314
    except subprocess.CalledProcessError as e:
 
315
        log('Error unmounting {}\n{}'.format(mountpoint, e.output))
 
316
        return False
 
317
    return True
 
318
 
 
319
 
283
320
def file_hash(path, hash_type='md5'):
284
321
    """
285
322
    Generate a hash checksum of the contents of 'path' or None if not found.
396
433
    return(''.join(random_chars))
397
434
 
398
435
 
399
 
def list_nics(nic_type):
 
436
def is_phy_iface(interface):
 
437
    """Returns True if interface is not virtual, otherwise False."""
 
438
    if interface:
 
439
        sys_net = '/sys/class/net'
 
440
        if os.path.isdir(sys_net):
 
441
            for iface in glob.glob(os.path.join(sys_net, '*')):
 
442
                if '/virtual/' in os.path.realpath(iface):
 
443
                    continue
 
444
 
 
445
                if interface == os.path.basename(iface):
 
446
                    return True
 
447
 
 
448
    return False
 
449
 
 
450
 
 
451
def get_bond_master(interface):
 
452
    """Returns bond master if interface is bond slave otherwise None.
 
453
 
 
454
    NOTE: the provided interface is expected to be physical
 
455
    """
 
456
    if interface:
 
457
        iface_path = '/sys/class/net/%s' % (interface)
 
458
        if os.path.exists(iface_path):
 
459
            if '/virtual/' in os.path.realpath(iface_path):
 
460
                return None
 
461
 
 
462
            master = os.path.join(iface_path, 'master')
 
463
            if os.path.exists(master):
 
464
                master = os.path.realpath(master)
 
465
                # make sure it is a bond master
 
466
                if os.path.exists(os.path.join(master, 'bonding')):
 
467
                    return os.path.basename(master)
 
468
 
 
469
    return None
 
470
 
 
471
 
 
472
def list_nics(nic_type=None):
400
473
    '''Return a list of nics of given type(s)'''
401
474
    if isinstance(nic_type, six.string_types):
402
475
        int_types = [nic_type]
403
476
    else:
404
477
        int_types = nic_type
 
478
 
405
479
    interfaces = []
406
 
    for int_type in int_types:
407
 
        cmd = ['ip', 'addr', 'show', 'label', int_type + '*']
 
480
    if nic_type:
 
481
        for int_type in int_types:
 
482
            cmd = ['ip', 'addr', 'show', 'label', int_type + '*']
 
483
            ip_output = subprocess.check_output(cmd).decode('UTF-8')
 
484
            ip_output = ip_output.split('\n')
 
485
            ip_output = (line for line in ip_output if line)
 
486
            for line in ip_output:
 
487
                if line.split()[1].startswith(int_type):
 
488
                    matched = re.search('.*: (' + int_type +
 
489
                                        r'[0-9]+\.[0-9]+)@.*', line)
 
490
                    if matched:
 
491
                        iface = matched.groups()[0]
 
492
                    else:
 
493
                        iface = line.split()[1].replace(":", "")
 
494
 
 
495
                    if iface not in interfaces:
 
496
                        interfaces.append(iface)
 
497
    else:
 
498
        cmd = ['ip', 'a']
408
499
        ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n')
409
 
        ip_output = (line for line in ip_output if line)
 
500
        ip_output = (line.strip() for line in ip_output if line)
 
501
 
 
502
        key = re.compile('^[0-9]+:\s+(.+):')
410
503
        for line in ip_output:
411
 
            if line.split()[1].startswith(int_type):
412
 
                matched = re.search('.*: (' + int_type + r'[0-9]+\.[0-9]+)@.*', line)
413
 
                if matched:
414
 
                    interface = matched.groups()[0]
415
 
                else:
416
 
                    interface = line.split()[1].replace(":", "")
417
 
                interfaces.append(interface)
 
504
            matched = re.search(key, line)
 
505
            if matched:
 
506
                iface = matched.group(1)
 
507
                iface = iface.partition("@")[0]
 
508
                if iface not in interfaces:
 
509
                    interfaces.append(iface)
418
510
 
419
511
    return interfaces
420
512
 
474
566
        os.chdir(cur)
475
567
 
476
568
 
477
 
def chownr(path, owner, group, follow_links=True):
 
569
def chownr(path, owner, group, follow_links=True, chowntopdir=False):
 
570
    """
 
571
    Recursively change user and group ownership of files and directories
 
572
    in given path. Doesn't chown path itself by default, only its children.
 
573
 
 
574
    :param bool follow_links: Also Chown links if True
 
575
    :param bool chowntopdir: Also chown path itself if True
 
576
    """
478
577
    uid = pwd.getpwnam(owner).pw_uid
479
578
    gid = grp.getgrnam(group).gr_gid
480
579
    if follow_links:
482
581
    else:
483
582
        chown = os.lchown
484
583
 
 
584
    if chowntopdir:
 
585
        broken_symlink = os.path.lexists(path) and not os.path.exists(path)
 
586
        if not broken_symlink:
 
587
            chown(path, uid, gid)
485
588
    for root, dirs, files in os.walk(path):
486
589
        for name in dirs + files:
487
590
            full = os.path.join(root, name)