~niedbalski/charms/trusty/swift-storage/fix-lp-1308557

« back to all changes in this revision

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

  • Committer: James Page
  • Date: 2014-04-16 08:34:53 UTC
  • mfrom: (24.1.17 swift-storage)
  • Revision ID: james.page@canonical.com-20140416083453-3n4gz51lk3p8tojd
[james-page,r=james-page,t=*]

Support for Icehouse on 12.04 and 14.04

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
 
20
20
 
21
21
def service_start(service_name):
 
22
    """Start a system service"""
22
23
    return service('start', service_name)
23
24
 
24
25
 
25
26
def service_stop(service_name):
 
27
    """Stop a system service"""
26
28
    return service('stop', service_name)
27
29
 
28
30
 
29
31
def service_restart(service_name):
 
32
    """Restart a system service"""
30
33
    return service('restart', service_name)
31
34
 
32
35
 
33
36
def service_reload(service_name, restart_on_failure=False):
 
37
    """Reload a system service, optionally falling back to restart if reload fails"""
34
38
    service_result = service('reload', service_name)
35
39
    if not service_result and restart_on_failure:
36
40
        service_result = service('restart', service_name)
38
42
 
39
43
 
40
44
def service(action, service_name):
 
45
    """Control a system service"""
41
46
    cmd = ['service', service_name, action]
42
47
    return subprocess.call(cmd) == 0
43
48
 
44
49
 
45
50
def service_running(service):
 
51
    """Determine whether a system service is running"""
46
52
    try:
47
53
        output = subprocess.check_output(['service', service, 'status'])
48
54
    except subprocess.CalledProcessError:
55
61
 
56
62
 
57
63
def adduser(username, password=None, shell='/bin/bash', system_user=False):
58
 
    """Add a user"""
 
64
    """Add a user to the system"""
59
65
    try:
60
66
        user_info = pwd.getpwnam(username)
61
67
        log('user {0} already exists!'.format(username))
138
144
 
139
145
 
140
146
def mount(device, mountpoint, options=None, persist=False):
141
 
    '''Mount a filesystem'''
 
147
    """Mount a filesystem at a particular mountpoint"""
142
148
    cmd_args = ['mount']
143
149
    if options is not None:
144
150
        cmd_args.extend(['-o', options])
155
161
 
156
162
 
157
163
def umount(mountpoint, persist=False):
158
 
    '''Unmount a filesystem'''
 
164
    """Unmount a filesystem"""
159
165
    cmd_args = ['umount', mountpoint]
160
166
    try:
161
167
        subprocess.check_output(cmd_args)
169
175
 
170
176
 
171
177
def mounts():
172
 
    '''List of all mounted volumes as [[mountpoint,device],[...]]'''
 
178
    """Get a list of all mounted volumes as [[mountpoint,device],[...]]"""
173
179
    with open('/proc/mounts') as f:
174
180
        # [['/mount/point','/dev/path'],[...]]
175
181
        system_mounts = [m[1::-1] for m in [l.strip().split()
178
184
 
179
185
 
180
186
def file_hash(path):
181
 
    ''' Generate a md5 hash of the contents of 'path' or None if not found '''
 
187
    """Generate a md5 hash of the contents of 'path' or None if not found """
182
188
    if os.path.exists(path):
183
189
        h = hashlib.md5()
184
190
        with open(path, 'r') as source:
188
194
        return None
189
195
 
190
196
 
191
 
def restart_on_change(restart_map):
192
 
    ''' Restart services based on configuration files changing
 
197
def restart_on_change(restart_map, stopstart=False):
 
198
    """Restart services based on configuration files changing
193
199
 
194
200
    This function is used a decorator, for example
195
201
 
202
208
    In this example, the cinder-api and cinder-volume services
203
209
    would be restarted if /etc/ceph/ceph.conf is changed by the
204
210
    ceph_client_changed function.
205
 
    '''
 
211
    """
206
212
    def wrap(f):
207
213
        def wrapped_f(*args):
208
214
            checksums = {}
213
219
            for path in restart_map:
214
220
                if checksums[path] != file_hash(path):
215
221
                    restarts += restart_map[path]
216
 
            for service_name in list(OrderedDict.fromkeys(restarts)):
217
 
                service('restart', service_name)
 
222
            services_list = list(OrderedDict.fromkeys(restarts))
 
223
            if not stopstart:
 
224
                for service_name in services_list:
 
225
                    service('restart', service_name)
 
226
            else:
 
227
                for action in ['stop', 'start']:
 
228
                    for service_name in services_list:
 
229
                        service(action, service_name)
218
230
        return wrapped_f
219
231
    return wrap
220
232
 
221
233
 
222
234
def lsb_release():
223
 
    '''Return /etc/lsb-release in a dict'''
 
235
    """Return /etc/lsb-release in a dict"""
224
236
    d = {}
225
237
    with open('/etc/lsb-release', 'r') as lsb:
226
238
        for l in lsb:
230
242
 
231
243
 
232
244
def pwgen(length=None):
233
 
    '''Generate a random pasword.'''
 
245
    """Generate a random pasword."""
234
246
    if length is None:
235
247
        length = random.choice(range(35, 45))
236
248
    alphanumeric_chars = [
239
251
    random_chars = [
240
252
        random.choice(alphanumeric_chars) for _ in range(length)]
241
253
    return(''.join(random_chars))
 
254
 
 
255
 
 
256
def list_nics(nic_type):
 
257
    '''Return a list of nics of given type(s)'''
 
258
    if isinstance(nic_type, basestring):
 
259
        int_types = [nic_type]
 
260
    else:
 
261
        int_types = nic_type
 
262
    interfaces = []
 
263
    for int_type in int_types:
 
264
        cmd = ['ip', 'addr', 'show', 'label', int_type + '*']
 
265
        ip_output = subprocess.check_output(cmd).split('\n')
 
266
        ip_output = (line for line in ip_output if line)
 
267
        for line in ip_output:
 
268
            if line.split()[1].startswith(int_type):
 
269
                interfaces.append(line.split()[1].replace(":", ""))
 
270
    return interfaces
 
271
 
 
272
 
 
273
def set_nic_mtu(nic, mtu):
 
274
    '''Set MTU on a network interface'''
 
275
    cmd = ['ip', 'link', 'set', nic, 'mtu', mtu]
 
276
    subprocess.check_call(cmd)
 
277
 
 
278
 
 
279
def get_nic_mtu(nic):
 
280
    cmd = ['ip', 'addr', 'show', nic]
 
281
    ip_output = subprocess.check_output(cmd).split('\n')
 
282
    mtu = ""
 
283
    for line in ip_output:
 
284
        words = line.split()
 
285
        if 'mtu' in words:
 
286
            mtu = words[words.index("mtu") + 1]
 
287
    return mtu
 
288
 
 
289
 
 
290
def get_nic_hwaddr(nic):
 
291
    cmd = ['ip', '-o', '-0', 'addr', 'show', nic]
 
292
    ip_output = subprocess.check_output(cmd)
 
293
    hwaddr = ""
 
294
    words = ip_output.split()
 
295
    if 'link/ether' in words:
 
296
        hwaddr = words[words.index('link/ether') + 1]
 
297
    return hwaddr