~gz/pyjuju/0.5_unicode_token_backport

« back to all changes in this revision

Viewing changes to juju/providers/openstack/machine.py

  • Committer: Clint Byrum
  • Author(s): Martin Packman
  • Date: 2012-09-10 08:32:41 UTC
  • Revision ID: clint@ubuntu.com-20120910083241-xueuh0bt5jl44w2b
OpenStack Provider

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""Helpers for mapping Nova api results to the juju machine abstraction"""
 
2
 
 
3
from juju.machine import ProviderMachine
 
4
 
 
5
 
 
6
_SERVER_STATE_MAP = {
 
7
    None: 'pending',
 
8
    'ACTIVE': 'running',
 
9
    'BUILD': 'pending',
 
10
    'BUILDING': 'pending',
 
11
    'REBUILDING': 'pending',
 
12
    'DELETED': 'terminated',
 
13
    'STOPPED': 'stopped',
 
14
    }
 
15
 
 
16
 
 
17
class NovaProviderMachine(ProviderMachine):
 
18
    """Nova-specific ProviderMachine implementation"""
 
19
 
 
20
 
 
21
def get_server_status(server):
 
22
    status = server.get('status')
 
23
    if status is not None and "(" in status:
 
24
        status = status.split("(", 1)[0]
 
25
    return _SERVER_STATE_MAP.get(status, 'unknown')
 
26
 
 
27
 
 
28
def get_server_addresses(server):
 
29
    private_addr = public_addr = None
 
30
    addresses = server.get("addresses")
 
31
    if addresses is not None:
 
32
        # Issue with some setups, have custom network only, use as private
 
33
        network = ()
 
34
        for name in sorted(addresses):
 
35
            if name not in ("private", "public"):
 
36
                network = addresses[name]
 
37
                if network:
 
38
                    break
 
39
        network = addresses.get("private", network)
 
40
        for address in network:
 
41
            if address.get("version", 0) == 4:
 
42
                private_addr = address['addr']
 
43
                break
 
44
        # Issue with HP cloud, public address is second in private network
 
45
        network = addresses.get("public", network[1:])
 
46
        for address in network:
 
47
            if address.get("version", 0) == 4:
 
48
                public_addr = address['addr']
 
49
    return private_addr, public_addr
 
50
 
 
51
 
 
52
def machine_from_instance(server):
 
53
    """Create an :class:`NovaProviderMachine` from a server details dict
 
54
 
 
55
    :param server: a dictionary of server info as given by the Nova api
 
56
 
 
57
    :return: a matching :class:`NovaProviderMachine`
 
58
    """
 
59
    private_addr, public_addr = get_server_addresses(server)
 
60
    # Juju assumes it always needs a public address and loops waiting for one.
 
61
    # In fact a private address is generally fine provided it can be sshed to.
 
62
    if public_addr is None and private_addr is not None:
 
63
        public_addr = private_addr
 
64
    return NovaProviderMachine(
 
65
        server['id'],
 
66
        public_addr,
 
67
        private_addr,
 
68
        get_server_status(server))