~heut2008/charms/trusty/keystone/ldap-support-backend

« back to all changes in this revision

Viewing changes to hooks/lib/utils.py

  • Committer: James Page
  • Date: 2014-04-16 08:20:08 UTC
  • mfrom: (52.2.30 keystone)
  • Revision ID: james.page@canonical.com-20140416082008-34w0nyak0y571tfp
[james-page,ivoks,hazmat,yolanda.robla,r=james-page,t=*]

Redux to used charm helpers
Support for Icehouse on 12.04 and 14.04
Support for Active/Active and SSL RabbitMQ
Support for SSL MySQL
Support for SSL endpoints
Support for PostgreSQL

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#
2
 
# Copyright 2012 Canonical Ltd.
3
 
#
4
 
# This file is sourced from lp:openstack-charm-helpers
5
 
#
6
 
# Authors:
7
 
#  James Page <james.page@ubuntu.com>
8
 
#  Paul Collins <paul.collins@canonical.com>
9
 
#  Adam Gandelman <adamg@ubuntu.com>
10
 
#
11
 
 
12
 
import json
13
 
import os
14
 
import subprocess
15
 
import socket
16
 
import sys
17
 
 
18
 
 
19
 
def do_hooks(hooks):
20
 
    hook = os.path.basename(sys.argv[0])
21
 
 
22
 
    try:
23
 
        hook_func = hooks[hook]
24
 
    except KeyError:
25
 
        juju_log('INFO',
26
 
                 "This charm doesn't know how to handle '{}'.".format(hook))
27
 
    else:
28
 
        hook_func()
29
 
 
30
 
 
31
 
def install(*pkgs):
32
 
    cmd = [
33
 
        'apt-get',
34
 
        '-y',
35
 
        'install'
36
 
          ]
37
 
    for pkg in pkgs:
38
 
        cmd.append(pkg)
39
 
    subprocess.check_call(cmd)
40
 
 
41
 
TEMPLATES_DIR = 'templates'
42
 
 
43
 
try:
44
 
    import jinja2
45
 
except ImportError:
46
 
    install('python-jinja2')
47
 
    import jinja2
48
 
 
49
 
try:
50
 
    import dns.resolver
51
 
except ImportError:
52
 
    install('python-dnspython')
53
 
    import dns.resolver
54
 
 
55
 
 
56
 
def render_template(template_name, context, template_dir=TEMPLATES_DIR):
57
 
    templates = jinja2.Environment(
58
 
                    loader=jinja2.FileSystemLoader(template_dir)
59
 
                    )
60
 
    template = templates.get_template(template_name)
61
 
    return template.render(context)
62
 
 
63
 
CLOUD_ARCHIVE = \
64
 
""" # Ubuntu Cloud Archive
65
 
deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main
66
 
"""
67
 
 
68
 
CLOUD_ARCHIVE_POCKETS = {
69
 
    'folsom': 'precise-updates/folsom',
70
 
    'folsom/updates': 'precise-updates/folsom',
71
 
    'folsom/proposed': 'precise-proposed/folsom',
72
 
    'grizzly': 'precise-updates/grizzly',
73
 
    'grizzly/updates': 'precise-updates/grizzly',
74
 
    'grizzly/proposed': 'precise-proposed/grizzly',
75
 
    'havana': 'precise-updates/havana',
76
 
    'havana/updates': 'precise-updates/havana',
77
 
    'havana/proposed': 'precise-proposed/havana',
78
 
    }
79
 
 
80
 
 
81
 
def configure_source():
82
 
    source = str(config_get('openstack-origin'))
83
 
    if not source:
84
 
        return
85
 
    if source.startswith('ppa:'):
86
 
        cmd = [
87
 
            'add-apt-repository',
88
 
            source
89
 
            ]
90
 
        subprocess.check_call(cmd)
91
 
    if source.startswith('cloud:'):
92
 
        # CA values should be formatted as cloud:ubuntu-openstack/pocket, eg:
93
 
        #   cloud:precise-folsom/updates or cloud:precise-folsom/proposed
94
 
        install('ubuntu-cloud-keyring')
95
 
        pocket = source.split(':')[1]
96
 
        pocket = pocket.split('-')[1]
97
 
        with open('/etc/apt/sources.list.d/cloud-archive.list', 'w') as apt:
98
 
            apt.write(CLOUD_ARCHIVE.format(CLOUD_ARCHIVE_POCKETS[pocket]))
99
 
    if source.startswith('deb'):
100
 
        l = len(source.split('|'))
101
 
        if l == 2:
102
 
            (apt_line, key) = source.split('|')
103
 
            cmd = [
104
 
                'apt-key',
105
 
                'adv', '--keyserver keyserver.ubuntu.com',
106
 
                '--recv-keys', key
107
 
                ]
108
 
            subprocess.check_call(cmd)
109
 
        elif l == 1:
110
 
            apt_line = source
111
 
 
112
 
        with open('/etc/apt/sources.list.d/quantum.list', 'w') as apt:
113
 
            apt.write(apt_line + "\n")
114
 
    cmd = [
115
 
        'apt-get',
116
 
        'update'
117
 
        ]
118
 
    subprocess.check_call(cmd)
119
 
 
120
 
# Protocols
121
 
TCP = 'TCP'
122
 
UDP = 'UDP'
123
 
 
124
 
 
125
 
def expose(port, protocol='TCP'):
126
 
    cmd = [
127
 
        'open-port',
128
 
        '{}/{}'.format(port, protocol)
129
 
        ]
130
 
    subprocess.check_call(cmd)
131
 
 
132
 
 
133
 
def juju_log(severity, message):
134
 
    cmd = [
135
 
        'juju-log',
136
 
        '--log-level', severity,
137
 
        message
138
 
        ]
139
 
    subprocess.check_call(cmd)
140
 
 
141
 
 
142
 
cache = {}
143
 
 
144
 
 
145
 
def cached(func):
146
 
    def wrapper(*args, **kwargs):
147
 
        global cache
148
 
        key = str((func, args, kwargs))
149
 
        try:
150
 
            return cache[key]
151
 
        except KeyError:
152
 
            res = func(*args, **kwargs)
153
 
            cache[key] = res
154
 
            return res
155
 
    return wrapper
156
 
 
157
 
 
158
 
@cached
159
 
def relation_ids(relation):
160
 
    cmd = [
161
 
        'relation-ids',
162
 
        relation
163
 
        ]
164
 
    result = str(subprocess.check_output(cmd)).split()
165
 
    if result == "":
166
 
        return None
167
 
    else:
168
 
        return result
169
 
 
170
 
 
171
 
@cached
172
 
def relation_list(rid):
173
 
    cmd = [
174
 
        'relation-list',
175
 
        '-r', rid,
176
 
        ]
177
 
    result = str(subprocess.check_output(cmd)).split()
178
 
    if result == "":
179
 
        return None
180
 
    else:
181
 
        return result
182
 
 
183
 
 
184
 
@cached
185
 
def relation_get(attribute, unit=None, rid=None):
186
 
    cmd = [
187
 
        'relation-get',
188
 
        ]
189
 
    if rid:
190
 
        cmd.append('-r')
191
 
        cmd.append(rid)
192
 
    cmd.append(attribute)
193
 
    if unit:
194
 
        cmd.append(unit)
195
 
    value = subprocess.check_output(cmd).strip()  # IGNORE:E1103
196
 
    if value == "":
197
 
        return None
198
 
    else:
199
 
        return value
200
 
 
201
 
 
202
 
@cached
203
 
def relation_get_dict(relation_id=None, remote_unit=None):
204
 
    """Obtain all relation data as dict by way of JSON"""
205
 
    cmd = [
206
 
        'relation-get', '--format=json'
207
 
        ]
208
 
    if relation_id:
209
 
        cmd.append('-r')
210
 
        cmd.append(relation_id)
211
 
    if remote_unit:
212
 
        cmd.append('-')
213
 
        cmd.append(remote_unit)
214
 
    j = subprocess.check_output(cmd)
215
 
    d = json.loads(j)
216
 
    settings = {}
217
 
    # convert unicode to strings
218
 
    for k, v in d.iteritems():
219
 
        settings[str(k)] = str(v)
220
 
    return settings
221
 
 
222
 
 
223
 
def relation_set(**kwargs):
224
 
    cmd = [
225
 
        'relation-set'
226
 
        ]
227
 
    args = []
228
 
    for k, v in kwargs.items():
229
 
        if k == 'rid':
230
 
            if v:
231
 
                cmd.append('-r')
232
 
                cmd.append(v)
233
 
        else:
234
 
            args.append('{}={}'.format(k, v))
235
 
    cmd += args
236
 
    subprocess.check_call(cmd)
237
 
 
238
 
 
239
 
@cached
240
 
def unit_get(attribute):
241
 
    cmd = [
242
 
        'unit-get',
243
 
        attribute
244
 
        ]
245
 
    value = subprocess.check_output(cmd).strip()  # IGNORE:E1103
246
 
    if value == "":
247
 
        return None
248
 
    else:
249
 
        return value
250
 
 
251
 
 
252
 
@cached
253
 
def config_get(attribute):
254
 
    cmd = [
255
 
        'config-get',
256
 
        '--format',
257
 
        'json',
258
 
        ]
259
 
    out = subprocess.check_output(cmd).strip()  # IGNORE:E1103
260
 
    cfg = json.loads(out)
261
 
 
262
 
    try:
263
 
        return cfg[attribute]
264
 
    except KeyError:
265
 
        return None
266
 
 
267
 
 
268
 
@cached
269
 
def get_unit_hostname():
270
 
    return socket.gethostname()
271
 
 
272
 
 
273
 
@cached
274
 
def get_host_ip(hostname=unit_get('private-address')):
275
 
    try:
276
 
        # Test to see if already an IPv4 address
277
 
        socket.inet_aton(hostname)
278
 
        return hostname
279
 
    except socket.error:
280
 
        answers = dns.resolver.query(hostname, 'A')
281
 
        if answers:
282
 
            return answers[0].address
283
 
    return None
284
 
 
285
 
 
286
 
def _svc_control(service, action):
287
 
    subprocess.check_call(['service', service, action])
288
 
 
289
 
 
290
 
def restart(*services):
291
 
    for service in services:
292
 
        _svc_control(service, 'restart')
293
 
 
294
 
 
295
 
def stop(*services):
296
 
    for service in services:
297
 
        _svc_control(service, 'stop')
298
 
 
299
 
 
300
 
def start(*services):
301
 
    for service in services:
302
 
        _svc_control(service, 'start')
303
 
 
304
 
 
305
 
def reload(*services):
306
 
    for service in services:
307
 
        try:
308
 
            _svc_control(service, 'reload')
309
 
        except subprocess.CalledProcessError:
310
 
            # Reload failed - either service does not support reload
311
 
            # or it was not running - restart will fixup most things
312
 
            _svc_control(service, 'restart')
313
 
 
314
 
 
315
 
def running(service):
316
 
    try:
317
 
        output = subprocess.check_output(['service', service, 'status'])
318
 
    except subprocess.CalledProcessError:
319
 
        return False
320
 
    else:
321
 
        if ("start/running" in output or
322
 
            "is running" in output):
323
 
            return True
324
 
        else:
325
 
            return False
326
 
 
327
 
 
328
 
def is_relation_made(relation, key='private-address'):
329
 
    for r_id in (relation_ids(relation) or []):
330
 
        for unit in (relation_list(r_id) or []):
331
 
            if relation_get(key, rid=r_id, unit=unit):
332
 
                return True
333
 
    return False