summaryrefslogtreecommitdiffstats
path: root/nova/api/openstack/compute/contrib/cloudpipe.py
blob: 20ae87fe17094007f148b69667a592479fe1c205 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#   Copyright 2011 OpenStack, LLC.
#
#   Licensed under the Apache License, Version 2.0 (the "License"); you may
#   not use this file except in compliance with the License. You may obtain
#   a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#   License for the specific language governing permissions and limitations
#   under the License.

"""Connect your vlan to the world."""

from oslo.config import cfg

from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova.cloudpipe import pipelib
from nova import compute
from nova.compute import utils as compute_utils
from nova.compute import vm_states
from nova import db
from nova import exception
from nova import network
from nova.openstack.common import fileutils
from nova.openstack.common import log as logging
from nova.openstack.common import timeutils
from nova import utils

CONF = cfg.CONF
LOG = logging.getLogger(__name__)
authorize = extensions.extension_authorizer('compute', 'cloudpipe')


class CloudpipeTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('cloudpipe')
        elem = xmlutil.SubTemplateElement(root, 'instance_id',
                                          selector='instance_id')
        elem.text = str
        return xmlutil.MasterTemplate(root, 1)


class CloudpipesTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('cloudpipes')
        elem1 = xmlutil.SubTemplateElement(root, 'cloudpipe',
                                           selector='cloudpipes')
        elem2 = xmlutil.SubTemplateElement(elem1, xmlutil.Selector(0),
                                           selector=xmlutil.get_items)
        elem2.text = 1
        return xmlutil.MasterTemplate(root, 1)


class CloudpipeController(object):
    """Handle creating and listing cloudpipe instances."""

    def __init__(self):
        self.compute_api = compute.API()
        self.network_api = network.API()
        self.cloudpipe = pipelib.CloudPipe()
        self.setup()

    def setup(self):
        """Ensure the keychains and folders exist."""
        # NOTE(vish): One of the drawbacks of doing this in the api is
        #             the keys will only be on the api node that launched
        #             the cloudpipe.
        fileutils.ensure_tree(CONF.keys_path)

    def _get_all_cloudpipes(self, context):
        """Get all cloudpipes."""
        instances = self.compute_api.get_all(context,
                                             search_opts={'deleted': False})
        return [instance for instance in instances
                if pipelib.is_vpn_image(instance['image_ref'])
                and instance['vm_state'] != vm_states.DELETED]

    def _get_cloudpipe_for_project(self, context, project_id):
        """Get the cloudpipe instance for a project ID."""
        cloudpipes = self._get_all_cloudpipes(context) or [None]
        return cloudpipes[0]

    def _get_ip_and_port(self, instance):
        pass

    def _vpn_dict(self, context, project_id, instance):
        elevated = context.elevated()
        rv = {'project_id': project_id}
        if not instance:
            rv['state'] = 'pending'
            return rv
        rv['instance_id'] = instance['uuid']
        rv['created_at'] = timeutils.isotime(instance['created_at'])
        nw_info = compute_utils.get_nw_info_for_instance(instance)
        if not nw_info:
            return rv
        vif = nw_info[0]
        ips = [ip for ip in vif.fixed_ips() if ip['version'] == 4]
        if ips:
            rv['internal_ip'] = ips[0]['address']
        # NOTE(vish): Currently network_api.get does an owner check on
        #             project_id. This is probably no longer necessary
        #             but rather than risk changes in the db layer,
        #             we are working around it here by changing the
        #             project_id in the context. This can be removed
        #             if we remove the project_id check in the db.
        elevated.project_id = project_id
        network = self.network_api.get(elevated, vif['network']['id'])
        if network:
            vpn_ip = network['vpn_public_address']
            vpn_port = network['vpn_public_port']
            rv['public_ip'] = vpn_ip
            rv['public_port'] = vpn_port
            if vpn_ip and vpn_port:
                if utils.vpn_ping(vpn_ip, vpn_port):
                    rv['state'] = 'running'
                else:
                    rv['state'] = 'down'
            else:
                rv['state'] = 'invalid'
        return rv

    @wsgi.serializers(xml=CloudpipeTemplate)
    def create(self, req, body):
        """Create a new cloudpipe instance, if none exists.

        Parameters: {cloudpipe: {'project_id': ''}}
        """

        context = req.environ['nova.context']
        authorize(context)
        params = body.get('cloudpipe', {})
        project_id = params.get('project_id', context.project_id)
        # NOTE(vish): downgrade to project context. Note that we keep
        #             the same token so we can still talk to glance
        context.project_id = project_id
        context.user_id = 'project-vpn'
        context.is_admin = False
        context.roles = []
        instance = self._get_cloudpipe_for_project(context, project_id)
        if not instance:
            try:
                result = self.cloudpipe.launch_vpn_instance(context)
                instance = result[0][0]
            except db.NoMoreNetworks:
                msg = _("Unable to claim IP for VPN instances, ensure it "
                        "isn't running, and try again in a few minutes")
                raise exception.HTTPBadRequest(explanation=msg)
        return {'instance_id': instance['uuid']}

    @wsgi.serializers(xml=CloudpipesTemplate)
    def index(self, req):
        """List running cloudpipe instances."""
        context = req.environ['nova.context']
        authorize(context)
        vpns = [self._vpn_dict(context, x['project_id'], x)
                for x in self._get_all_cloudpipes(context)]
        return {'cloudpipes': vpns}


class Cloudpipe(extensions.ExtensionDescriptor):
    """Adds actions to create cloudpipe instances.

    When running with the Vlan network mode, you need a mechanism to route
    from the public Internet to your vlans.  This mechanism is known as a
    cloudpipe.

    At the time of creating this class, only OpenVPN is supported.  Support for
    a SSH Bastion host is forthcoming.
    """

    name = "Cloudpipe"
    alias = "os-cloudpipe"
    namespace = "http://docs.openstack.org/compute/ext/cloudpipe/api/v1.1"
    updated = "2011-12-16T00:00:00+00:00"

    def get_resources(self):
        resources = []
        res = extensions.ResourceExtension('os-cloudpipe',
                                           CloudpipeController())
        resources.append(res)
        return resources