~gnuoy/charms/trusty/ceph/fix-six-bug

« back to all changes in this revision

Viewing changes to hooks/utils.py

  • Committer: Mark Mims
  • Date: 2013-07-14 19:46:24 UTC
  • mfrom: (60.1.20 ceph)
  • Revision ID: mark.mims@canonical.com-20130714194624-4r1gwom6lu7wrmh2
merging lp:~james-page/charms/precise/ceph/charm-helpers as per https://code.launchpad.net/~james-page/charms/precise/ceph/charm-helpers/+merge/173245

Show diffs side-by-side

added added

removed removed

Lines of Context:
7
7
#  Paul Collins <paul.collins@canonical.com>
8
8
#
9
9
 
10
 
import os
11
 
import subprocess
12
10
import socket
13
 
import sys
14
11
import re
15
 
 
16
 
 
17
 
def do_hooks(hooks):
18
 
    hook = os.path.basename(sys.argv[0])
19
 
 
20
 
    try:
21
 
        hook_func = hooks[hook]
22
 
    except KeyError:
23
 
        juju_log('INFO',
24
 
                 "This charm doesn't know how to handle '{}'.".format(hook))
25
 
    else:
26
 
        hook_func()
27
 
 
28
 
 
29
 
def install(*pkgs):
30
 
    cmd = [
31
 
        'apt-get',
32
 
        '-y',
33
 
        'install'
34
 
          ]
35
 
    for pkg in pkgs:
36
 
        cmd.append(pkg)
37
 
    subprocess.check_call(cmd)
 
12
from charmhelpers.core.hookenv import (
 
13
    unit_get,
 
14
    cached
 
15
)
 
16
from charmhelpers.core.host import (
 
17
    apt_install,
 
18
    filter_installed_packages
 
19
)
38
20
 
39
21
TEMPLATES_DIR = 'templates'
40
22
 
41
23
try:
42
24
    import jinja2
43
25
except ImportError:
44
 
    install('python-jinja2')
 
26
    apt_install(filter_installed_packages(['python-jinja2']),
 
27
                fatal=True)
45
28
    import jinja2
46
29
 
47
30
try:
48
31
    import dns.resolver
49
32
except ImportError:
50
 
    install('python-dnspython')
 
33
    apt_install(filter_installed_packages(['python-dnspython']),
 
34
                fatal=True)
51
35
    import dns.resolver
52
36
 
53
37
 
54
38
def render_template(template_name, context, template_dir=TEMPLATES_DIR):
55
39
    templates = jinja2.Environment(
56
 
                    loader=jinja2.FileSystemLoader(template_dir)
57
 
                    )
 
40
        loader=jinja2.FileSystemLoader(template_dir))
58
41
    template = templates.get_template(template_name)
59
42
    return template.render(context)
60
43
 
61
44
 
62
 
CLOUD_ARCHIVE = \
63
 
""" # Ubuntu Cloud Archive
64
 
deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main
65
 
"""
66
 
 
67
 
 
68
 
def configure_source():
69
 
    source = str(config_get('source'))
70
 
    if not source:
71
 
        return
72
 
    if source.startswith('ppa:'):
73
 
        cmd = [
74
 
            'add-apt-repository',
75
 
            source
76
 
            ]
77
 
        subprocess.check_call(cmd)
78
 
    if source.startswith('cloud:'):
79
 
        install('ubuntu-cloud-keyring')
80
 
        pocket = source.split(':')[1]
81
 
        with open('/etc/apt/sources.list.d/cloud-archive.list', 'w') as apt:
82
 
            apt.write(CLOUD_ARCHIVE.format(pocket))
83
 
    if source.startswith('http:'):
84
 
        with open('/etc/apt/sources.list.d/ceph.list', 'w') as apt:
85
 
            apt.write("deb " + source + "\n")
86
 
        key = config_get('key')
87
 
        if key:
88
 
            cmd = [
89
 
                'apt-key',
90
 
                'adv', '--keyserver keyserver.ubuntu.com',
91
 
                '--recv-keys', key
92
 
                ]
93
 
            subprocess.check_call(cmd)
94
 
    cmd = [
95
 
        'apt-get',
96
 
        'update'
97
 
        ]
98
 
    subprocess.check_call(cmd)
99
 
 
100
 
 
101
45
def enable_pocket(pocket):
102
46
    apt_sources = "/etc/apt/sources.list"
103
47
    with open(apt_sources, "r") as sources:
109
53
            else:
110
54
                sources.write(line)
111
55
 
112
 
# Protocols
113
 
TCP = 'TCP'
114
 
UDP = 'UDP'
115
 
 
116
 
 
117
 
def expose(port, protocol='TCP'):
118
 
    cmd = [
119
 
        'open-port',
120
 
        '{}/{}'.format(port, protocol)
121
 
        ]
122
 
    subprocess.check_call(cmd)
123
 
 
124
 
 
125
 
def juju_log(severity, message):
126
 
    cmd = [
127
 
        'juju-log',
128
 
        '--log-level', severity,
129
 
        message
130
 
        ]
131
 
    subprocess.check_call(cmd)
132
 
 
133
 
 
134
 
def relation_ids(relation):
135
 
    cmd = [
136
 
        'relation-ids',
137
 
        relation
138
 
        ]
139
 
    return subprocess.check_output(cmd).split()  # IGNORE:E1103
140
 
 
141
 
 
142
 
def relation_list(rid):
143
 
    cmd = [
144
 
        'relation-list',
145
 
        '-r', rid,
146
 
        ]
147
 
    return subprocess.check_output(cmd).split()  # IGNORE:E1103
148
 
 
149
 
 
150
 
def relation_get(attribute, unit=None, rid=None):
151
 
    cmd = [
152
 
        'relation-get',
153
 
        ]
154
 
    if rid:
155
 
        cmd.append('-r')
156
 
        cmd.append(rid)
157
 
    cmd.append(attribute)
158
 
    if unit:
159
 
        cmd.append(unit)
160
 
    value = str(subprocess.check_output(cmd)).strip()
161
 
    if value == "":
162
 
        return None
163
 
    else:
164
 
        return value
165
 
 
166
 
 
167
 
def relation_set(**kwargs):
168
 
    cmd = [
169
 
        'relation-set'
170
 
        ]
171
 
    args = []
172
 
    for k, v in kwargs.items():
173
 
        if k == 'rid':
174
 
            cmd.append('-r')
175
 
            cmd.append(v)
176
 
        else:
177
 
            args.append('{}={}'.format(k, v))
178
 
    cmd += args
179
 
    subprocess.check_call(cmd)
180
 
 
181
 
 
182
 
def unit_get(attribute):
183
 
    cmd = [
184
 
        'unit-get',
185
 
        attribute
186
 
        ]
187
 
    value = str(subprocess.check_output(cmd)).strip()
188
 
    if value == "":
189
 
        return None
190
 
    else:
191
 
        return value
192
 
 
193
 
 
194
 
def config_get(attribute):
195
 
    cmd = [
196
 
        'config-get',
197
 
        attribute
198
 
        ]
199
 
    value = str(subprocess.check_output(cmd)).strip()
200
 
    if value == "":
201
 
        return None
202
 
    else:
203
 
        return value
204
 
 
205
 
 
 
56
 
 
57
@cached
206
58
def get_unit_hostname():
207
59
    return socket.gethostname()
208
60
 
209
61
 
210
 
def get_host_ip(hostname=unit_get('private-address')):
 
62
@cached
 
63
def get_host_ip(hostname=None):
 
64
    hostname = hostname or unit_get('private-address')
211
65
    try:
212
66
        # Test to see if already an IPv4 address
213
67
        socket.inet_aton(hostname)