summaryrefslogtreecommitdiffstats
path: root/nova/network/api.py
blob: f396ea83e3b7c7f12655e3e22012bda7d6ed0418 (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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2013 IBM Corp.
# All Rights Reserved.
#
#    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.

import functools
import inspect

from nova.cells import rpcapi as cells_rpcapi
from nova.compute import flavors
from nova.db import base
from nova import exception
from nova.network import floating_ips
from nova.network import model as network_model
from nova.network import rpcapi as network_rpcapi
from nova.openstack.common import log as logging
from nova import policy
from nova import utils

LOG = logging.getLogger(__name__)


def refresh_cache(f):
    """
    Decorator to update the instance_info_cache

    Requires context and instance as function args
    """
    argspec = inspect.getargspec(f)

    @functools.wraps(f)
    def wrapper(self, context, *args, **kwargs):
        res = f(self, context, *args, **kwargs)

        try:
            # get the instance from arguments (or raise ValueError)
            instance = kwargs.get('instance')
            if not instance:
                instance = args[argspec.args.index('instance') - 2]
        except ValueError:
            msg = _('instance is a required argument to use @refresh_cache')
            raise Exception(msg)

        update_instance_cache_with_nw_info(self, context, instance,
                nw_info=res, conductor_api=kwargs.get('conductor_api'))

        # return the original function's return value
        return res
    return wrapper


def update_instance_cache_with_nw_info(api, context, instance,
                                       nw_info=None, conductor_api=None,
                                       update_cells=True):
    try:
        if not isinstance(nw_info, network_model.NetworkInfo):
            nw_info = None
        if not nw_info:
            nw_info = api._get_instance_nw_info(context, instance)
        # update cache
        cache = {'network_info': nw_info.json()}
        if conductor_api:
            rv = conductor_api.instance_info_cache_update(context,
                                                          instance,
                                                          cache)
        else:
            rv = api.db.instance_info_cache_update(context,
                                                   instance['uuid'],
                                                   cache)
        if update_cells:
            cells_api = cells_rpcapi.CellsAPI()
            try:
                cells_api.instance_info_cache_update_at_top(context, rv)
            except Exception:
                LOG.exception(_("Failed to notify cells of instance info "
                                "cache update"))
    except Exception:
        LOG.exception(_('Failed storing info cache'), instance=instance)


def wrap_check_policy(func):
    """Check policy corresponding to the wrapped methods prior to execution."""

    @functools.wraps(func)
    def wrapped(self, context, *args, **kwargs):
        action = func.__name__
        check_policy(context, action)
        return func(self, context, *args, **kwargs)

    return wrapped


def check_policy(context, action):
    target = {
        'project_id': context.project_id,
        'user_id': context.user_id,
    }
    _action = 'network:%s' % action
    policy.enforce(context, _action, target)


class API(base.Base):
    """API for doing networking via the nova-network network manager.

    This is a pluggable module - other implementations do networking via
    other services (such as Quantum).
    """
    _sentinel = object()

    def __init__(self, **kwargs):
        self.network_rpcapi = network_rpcapi.NetworkAPI()
        helper = utils.ExceptionHelper
        # NOTE(vish): this local version of floating_manager has to convert
        #             ClientExceptions back since they aren't going over rpc.
        self.floating_manager = helper(floating_ips.LocalManager())
        super(API, self).__init__(**kwargs)

    @wrap_check_policy
    def get_all(self, context):
        try:
            return self.db.network_get_all(context)
        except exception.NoNetworksFound:
            return []

    @wrap_check_policy
    def get(self, context, network_uuid):
        return self.db.network_get_by_uuid(context.elevated(), network_uuid)

    @wrap_check_policy
    def create(self, context, **kwargs):
        return self.network_rpcapi.create_networks(context, **kwargs)

    @wrap_check_policy
    def delete(self, context, network_uuid):
        return self.network_rpcapi.delete_network(context, network_uuid, None)

    @wrap_check_policy
    def disassociate(self, context, network_uuid):
        network = self.get(context, network_uuid)
        self.db.network_disassociate(context, network['id'])

    @wrap_check_policy
    def get_fixed_ip(self, context, id):
        return self.db.fixed_ip_get(context, id)

    @wrap_check_policy
    def get_fixed_ip_by_address(self, context, address):
        return self.db.fixed_ip_get_by_address(context, address)

    @wrap_check_policy
    def get_floating_ip(self, context, id):
        return self.db.floating_ip_get(context, id)

    @wrap_check_policy
    def get_floating_ip_pools(self, context):
        return self.db.floating_ip_get_pools(context)

    @wrap_check_policy
    def get_floating_ip_by_address(self, context, address):
        return self.db.floating_ip_get_by_address(context, address)

    @wrap_check_policy
    def get_floating_ips_by_project(self, context):
        return self.db.floating_ip_get_all_by_project(context,
                                                      context.project_id)

    @wrap_check_policy
    def get_floating_ips_by_fixed_address(self, context, fixed_address):
        floating_ips = self.db.floating_ip_get_by_fixed_address(context,
                                                                fixed_address)
        return [floating_ip['address'] for floating_ip in floating_ips]

    @wrap_check_policy
    def get_instance_id_by_floating_address(self, context, address):
        fixed_ip = self.db.fixed_ip_get_by_floating_address(context, address)
        if fixed_ip is None:
            return None
        else:
            return fixed_ip['instance_uuid']

    @wrap_check_policy
    def get_vifs_by_instance(self, context, instance):
        vifs = self.db.virtual_interface_get_by_instance(context,
                                                         instance['uuid'])
        for vif in vifs:
            if vif.get('network_id') is not None:
                network = self.db.network_get(context, vif['network_id'],
                                              project_only="allow_none")
                vif['net_uuid'] = network['uuid']
        return vifs

    @wrap_check_policy
    def get_vif_by_mac_address(self, context, mac_address):
        vif = self.db.virtual_interface_get_by_address(context,
                                                       mac_address)
        if vif.get('network_id') is not None:
            network = self.db.network_get(context, vif['network_id'],
                                          project_only="allow_none")
            vif['net_uuid'] = network['uuid']
        return vif

    @wrap_check_policy
    def allocate_floating_ip(self, context, pool=None):
        """Adds (allocates) a floating ip to a project from a pool."""
        return self.floating_manager.allocate_floating_ip(context,
                 context.project_id, False, pool)

    @wrap_check_policy
    def release_floating_ip(self, context, address,
                            affect_auto_assigned=False):
        """Removes (deallocates) a floating ip with address from a project."""
        return self.floating_manager.deallocate_floating_ip(context, address,
                 affect_auto_assigned)

    @wrap_check_policy
    @refresh_cache
    def associate_floating_ip(self, context, instance,
                              floating_address, fixed_address,
                              affect_auto_assigned=False):
        """Associates a floating ip with a fixed ip.

        Ensures floating ip is allocated to the project in context.
        Does not verify ownership of the fixed ip. Caller is assumed to have
        checked that the instance is properly owned.

        """
        orig_instance_uuid = self.floating_manager.associate_floating_ip(
                context, floating_address, fixed_address, affect_auto_assigned)

        if orig_instance_uuid:
            msg_dict = dict(address=floating_address,
                            instance_id=orig_instance_uuid)
            LOG.info(_('re-assign floating IP %(address)s from '
                       'instance %(instance_id)s') % msg_dict)
            orig_instance = self.db.instance_get_by_uuid(context,
                                                         orig_instance_uuid)

            # purge cached nw info for the original instance
            update_instance_cache_with_nw_info(self, context, orig_instance)

    @wrap_check_policy
    @refresh_cache
    def disassociate_floating_ip(self, context, instance, address,
                                 affect_auto_assigned=False):
        """Disassociates a floating ip from fixed ip it is associated with."""
        return self.floating_manager.disassociate_floating_ip(context, address,
                affect_auto_assigned)

    @wrap_check_policy
    @refresh_cache
    def allocate_for_instance(self, context, instance, vpn,
                              requested_networks, macs=None,
                              conductor_api=None, security_groups=None):
        """Allocates all network structures for an instance.

        TODO(someone): document the rest of these parameters.

        :param macs: None or a set of MAC addresses that the instance
            should use. macs is supplied by the hypervisor driver (contrast
            with requested_networks which is user supplied).
        :returns: network info as from get_instance_nw_info() below
        """
        # NOTE(vish): We can't do the floating ip allocation here because
        #             this is called from compute.manager which shouldn't
        #             have db access so we do it on the other side of the
        #             rpc.
        instance_type = flavors.extract_flavor(instance)
        args = {}
        args['vpn'] = vpn
        args['requested_networks'] = requested_networks
        args['instance_id'] = instance['uuid']
        args['project_id'] = instance['project_id']
        args['host'] = instance['host']
        args['rxtx_factor'] = instance_type['rxtx_factor']
        args['macs'] = macs
        nw_info = self.network_rpcapi.allocate_for_instance(context, **args)

        return network_model.NetworkInfo.hydrate(nw_info)

    @wrap_check_policy
    def deallocate_for_instance(self, context, instance):
        """Deallocates all network structures related to instance."""
        # NOTE(vish): We can't do the floating ip deallocation here because
        #             this is called from compute.manager which shouldn't
        #             have db access so we do it on the other side of the
        #             rpc.
        args = {}
        args['instance_id'] = instance['uuid']
        args['project_id'] = instance['project_id']
        args['host'] = instance['host']
        self.network_rpcapi.deallocate_for_instance(context, **args)

    # NOTE(danms): Here for quantum compatibility
    def allocate_port_for_instance(self, context, instance, port_id,
                                   network_id=None, requested_ip=None,
                                   conductor_api=None):
        raise NotImplementedError()

    # NOTE(danms): Here for quantum compatibility
    def deallocate_port_for_instance(self, context, instance, port_id,
                                     conductor_api=None):
        raise NotImplementedError()

    # NOTE(danms): Here for quantum compatibility
    def list_ports(self, *args, **kwargs):
        raise NotImplementedError()

    # NOTE(danms): Here for quantum compatibility
    def show_port(self, *args, **kwargs):
        raise NotImplementedError()

    @wrap_check_policy
    @refresh_cache
    def add_fixed_ip_to_instance(self, context, instance, network_id,
                                 conductor_api=None):
        """Adds a fixed ip to instance from specified network."""
        instance_type = flavors.extract_flavor(instance)
        args = {'instance_id': instance['uuid'],
                'rxtx_factor': instance_type['rxtx_factor'],
                'host': instance['host'],
                'network_id': network_id}
        self.network_rpcapi.add_fixed_ip_to_instance(context, **args)

    @wrap_check_policy
    @refresh_cache
    def remove_fixed_ip_from_instance(self, context, instance, address,
                                      conductor_api=None):
        """Removes a fixed ip from instance from specified network."""

        instance_type = flavors.extract_flavor(instance)
        args = {'instance_id': instance['uuid'],
                'rxtx_factor': instance_type['rxtx_factor'],
                'host': instance['host'],
                'address': address}
        self.network_rpcapi.remove_fixed_ip_from_instance(context, **args)

    @wrap_check_policy
    def add_network_to_project(self, context, project_id, network_uuid=None):
        """Force adds another network to a project."""
        self.network_rpcapi.add_network_to_project(context, project_id,
                network_uuid)

    @wrap_check_policy
    def associate(self, context, network_uuid, host=_sentinel,
                  project=_sentinel):
        """Associate or disassociate host or project to network."""
        network_id = self.get(context, network_uuid)['id']
        if host is not API._sentinel:
            if host is None:
                self.db.network_disassociate(context, network_id,
                                             disassociate_host=True,
                                             disassociate_project=False)
            else:
                self.db.network_set_host(context, network_id, host)
        if project is not API._sentinel:
            if project is None:
                self.db.network_disassociate(context, network_id,
                                             disassociate_host=False,
                                             disassociate_project=True)
            else:
                self.db.network_associate(context, project, network_id, True)

    @wrap_check_policy
    def get_instance_nw_info(self, context, instance, conductor_api=None):
        """Returns all network info related to an instance."""
        result = self._get_instance_nw_info(context, instance)
        # NOTE(comstud): Don't update API cell with new info_cache every
        # time we pull network info for an instance.  The periodic healing
        # of info_cache causes too many cells messages.  Healing the API
        # will happen separately.
        update_instance_cache_with_nw_info(self, context, instance,
                                           result, conductor_api,
                                           update_cells=False)
        return result

    def _get_instance_nw_info(self, context, instance):
        """Returns all network info related to an instance."""
        instance_type = flavors.extract_flavor(instance)
        args = {'instance_id': instance['uuid'],
                'rxtx_factor': instance_type['rxtx_factor'],
                'host': instance['host'],
                'project_id': instance['project_id']}
        nw_info = self.network_rpcapi.get_instance_nw_info(context, **args)

        return network_model.NetworkInfo.hydrate(nw_info)

    @wrap_check_policy
    def validate_networks(self, context, requested_networks):
        """validate the networks passed at the time of creating
        the server
        """
        return self.network_rpcapi.validate_networks(context,
                                                     requested_networks)

    @wrap_check_policy
    def get_instance_uuids_by_ip_filter(self, context, filters):
        """Returns a list of dicts in the form of
        {'instance_uuid': uuid, 'ip': ip} that matched the ip_filter
        """
        return self.network_rpcapi.get_instance_uuids_by_ip_filter(context,
                                                                   filters)

    @wrap_check_policy
    def get_dns_domains(self, context):
        """Returns a list of available dns domains.
        These can be used to create DNS entries for floating ips.
        """
        return self.network_rpcapi.get_dns_domains(context)

    @wrap_check_policy
    def add_dns_entry(self, context, address, name, dns_type, domain):
        """Create specified DNS entry for address."""
        args = {'address': address,
                'name': name,
                'dns_type': dns_type,
                'domain': domain}
        return self.network_rpcapi.add_dns_entry(context, **args)

    @wrap_check_policy
    def modify_dns_entry(self, context, name, address, domain):
        """Create specified DNS entry for address."""
        args = {'address': address,
                'name': name,
                'domain': domain}
        return self.network_rpcapi.modify_dns_entry(context, **args)

    @wrap_check_policy
    def delete_dns_entry(self, context, name, domain):
        """Delete the specified dns entry."""
        args = {'name': name, 'domain': domain}
        return self.network_rpcapi.delete_dns_entry(context, **args)

    @wrap_check_policy
    def delete_dns_domain(self, context, domain):
        """Delete the specified dns domain."""
        return self.network_rpcapi.delete_dns_domain(context, domain=domain)

    @wrap_check_policy
    def get_dns_entries_by_address(self, context, address, domain):
        """Get entries for address and domain."""
        args = {'address': address, 'domain': domain}
        return self.network_rpcapi.get_dns_entries_by_address(context, **args)

    @wrap_check_policy
    def get_dns_entries_by_name(self, context, name, domain):
        """Get entries for name and domain."""
        args = {'name': name, 'domain': domain}
        return self.network_rpcapi.get_dns_entries_by_name(context, **args)

    @wrap_check_policy
    def create_private_dns_domain(self, context, domain, availability_zone):
        """Create a private DNS domain with nova availability zone."""
        args = {'domain': domain, 'av_zone': availability_zone}
        return self.network_rpcapi.create_private_dns_domain(context, **args)

    @wrap_check_policy
    def create_public_dns_domain(self, context, domain, project=None):
        """Create a public DNS domain with optional nova project."""
        args = {'domain': domain, 'project': project}
        return self.network_rpcapi.create_public_dns_domain(context, **args)

    @wrap_check_policy
    def setup_networks_on_host(self, context, instance, host=None,
                                                        teardown=False):
        """Setup or teardown the network structures on hosts related to
           instance.
        """
        host = host or instance['host']
        # NOTE(tr3buchet): host is passed in cases where we need to setup
        # or teardown the networks on a host which has been migrated to/from
        # and instance['host'] is not yet or is no longer equal to
        args = {'instance_id': instance['id'],
                'host': host,
                'teardown': teardown}

        self.network_rpcapi.setup_networks_on_host(context, **args)

    def _is_multi_host(self, context, instance):
        try:
            fixed_ips = self.db.fixed_ip_get_by_instance(context,
                                                         instance['uuid'])
        except exception.FixedIpNotFoundForInstance:
            return False
        network = self.db.network_get(context, fixed_ips[0]['network_id'],
                                      project_only='allow_none')
        return network['multi_host']

    def _get_floating_ip_addresses(self, context, instance):
        floating_ips = self.db.instance_floating_address_get_all(context,
                                                            instance['uuid'])
        return floating_ips

    @wrap_check_policy
    def migrate_instance_start(self, context, instance, migration):
        """Start to migrate the network of an instance."""
        instance_type = flavors.extract_flavor(instance)
        args = dict(
            instance_uuid=instance['uuid'],
            rxtx_factor=instance_type['rxtx_factor'],
            project_id=instance['project_id'],
            source_compute=migration['source_compute'],
            dest_compute=migration['dest_compute'],
            floating_addresses=None,
        )

        if self._is_multi_host(context, instance):
            args['floating_addresses'] = \
                self._get_floating_ip_addresses(context, instance)
            args['host'] = migration['source_compute']

        self.network_rpcapi.migrate_instance_start(context, **args)

    @wrap_check_policy
    def migrate_instance_finish(self, context, instance, migration):
        """Finish migrating the network of an instance."""
        instance_type = flavors.extract_flavor(instance)
        args = dict(
            instance_uuid=instance['uuid'],
            rxtx_factor=instance_type['rxtx_factor'],
            project_id=instance['project_id'],
            source_compute=migration['source_compute'],
            dest_compute=migration['dest_compute'],
            floating_addresses=None,
        )

        if self._is_multi_host(context, instance):
            args['floating_addresses'] = \
                self._get_floating_ip_addresses(context, instance)
            args['host'] = migration['dest_compute']

        self.network_rpcapi.migrate_instance_finish(context, **args)