~niedbalski/charms/trusty/quantum-gateway/lp-1396607

« back to all changes in this revision

Viewing changes to hooks/lib/utils.py

  • Committer: James Page
  • Date: 2013-07-19 09:46:25 UTC
  • mto: (33.1.23 python-redux)
  • mto: This revision was merged to the branch mainline in revision 34.
  • Revision ID: james.page@canonical.com-20130719094625-wqfy6lw11vzhs5ba
Redux to use agree structure and OS templating

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 socket
13
 
from charmhelpers.core.host import (
14
 
    apt_install
15
 
)
16
 
from charmhelpers.core.hookenv import (
17
 
    unit_get,
18
 
    cached
19
 
)
20
 
 
21
 
 
22
 
TEMPLATES_DIR = 'templates'
23
 
 
24
 
try:
25
 
    import jinja2
26
 
except ImportError:
27
 
    apt_install('python-jinja2', fatal=True)
28
 
    import jinja2
29
 
 
30
 
try:
31
 
    import dns.resolver
32
 
except ImportError:
33
 
    apt_install('python-dnspython', fatal=True)
34
 
    import dns.resolver
35
 
 
36
 
 
37
 
def render_template(template_name, context, template_dir=TEMPLATES_DIR):
38
 
    templates = jinja2.Environment(
39
 
        loader=jinja2.FileSystemLoader(template_dir)
40
 
    )
41
 
    template = templates.get_template(template_name)
42
 
    return template.render(context)
43
 
 
44
 
 
45
 
@cached
46
 
def get_unit_hostname():
47
 
    return socket.gethostname()
48
 
 
49
 
 
50
 
@cached
51
 
def get_host_ip(hostname=None):
52
 
    hostname = hostname or unit_get('private-address')
53
 
    try:
54
 
        # Test to see if already an IPv4 address
55
 
        socket.inet_aton(hostname)
56
 
        return hostname
57
 
    except socket.error:
58
 
        answers = dns.resolver.query(hostname, 'A')
59
 
        if answers:
60
 
            return answers[0].address
61
 
    return None