File: bgp_dragentscheduler_db.py

package info (click to toggle)
neutron-dynamic-routing 2%3A9.0.0-1.2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 896 kB
  • ctags: 858
  • sloc: python: 6,104; sh: 168; makefile: 46
file content (216 lines) | stat: -rw-r--r-- 9,111 bytes parent folder | download
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
# Copyright 2016 Huawei Technologies India Pvt. Ltd.
# 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.

from neutron_lib.db import model_base
from oslo_config import cfg
from oslo_db import exception as db_exc
from oslo_log import log as logging
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.orm import exc

from neutron.db import agents_db
from neutron.db import agentschedulers_db as as_db

from neutron_dynamic_routing._i18n import _
from neutron_dynamic_routing._i18n import _LW
from neutron_dynamic_routing.extensions import bgp_dragentscheduler as bgp_dras_ext  # noqa
from neutron_dynamic_routing.services.bgp.common import constants as bgp_consts


LOG = logging.getLogger(__name__)


BGP_DRAGENT_SCHEDULER_OPTS = [
    cfg.StrOpt(
        'bgp_drscheduler_driver',
        default='neutron_dynamic_routing.services.bgp.scheduler'
                '.bgp_dragent_scheduler.ChanceScheduler',
        help=_('Driver used for scheduling BGP speakers to BGP DrAgent'))
]

cfg.CONF.register_opts(BGP_DRAGENT_SCHEDULER_OPTS)


class BgpSpeakerDrAgentBinding(model_base.BASEV2):
    """Represents a mapping between BGP speaker and BGP DRAgent"""

    __tablename__ = 'bgp_speaker_dragent_bindings'

    bgp_speaker_id = sa.Column(sa.String(length=36),
                               sa.ForeignKey("bgp_speakers.id",
                                             ondelete='CASCADE'),
                               nullable=False)
    dragent = orm.relation(agents_db.Agent)
    agent_id = sa.Column(sa.String(length=36),
                         sa.ForeignKey("agents.id",
                                       ondelete='CASCADE'),
                         primary_key=True)


class BgpDrAgentSchedulerDbMixin(bgp_dras_ext.BgpDrSchedulerPluginBase,
                                 as_db.AgentSchedulerDbMixin):

    bgp_drscheduler = None

    def schedule_unscheduled_bgp_speakers(self, context, host):
        if self.bgp_drscheduler:
            return self.bgp_drscheduler.schedule_unscheduled_bgp_speakers(
                context, host)
        else:
            LOG.warning(_LW("Cannot schedule BgpSpeaker to DrAgent. "
                            "Reason: No scheduler registered."))

    def schedule_bgp_speaker(self, context, created_bgp_speaker):
        if self.bgp_drscheduler:
            agents = self.bgp_drscheduler.schedule(context,
                                                   created_bgp_speaker)
            for agent in agents:
                self._bgp_rpc.bgp_speaker_created(context,
                                                  created_bgp_speaker['id'],
                                                  agent.host)
        else:
            LOG.warning(_LW("Cannot schedule BgpSpeaker to DrAgent. "
                            "Reason: No scheduler registered."))

    def add_bgp_speaker_to_dragent(self, context, agent_id, speaker_id):
        """Associate a BgpDrAgent with a BgpSpeaker."""
        try:
            self._save_bgp_speaker_dragent_binding(context,
                                                   agent_id,
                                                   speaker_id)
        except db_exc.DBDuplicateEntry:
            raise bgp_dras_ext.DrAgentAssociationError(
                    agent_id=agent_id)

        LOG.debug('BgpSpeaker %(bgp_speaker_id)s added to '
                  'BgpDrAgent %(agent_id)s',
                  {'bgp_speaker_id': speaker_id, 'agent_id': agent_id})

    def _save_bgp_speaker_dragent_binding(self, context,
                                          agent_id, speaker_id):
        with context.session.begin(subtransactions=True):
            agent_db = self._get_agent(context, agent_id)
            agent_up = agent_db['admin_state_up']
            is_agent_bgp = (agent_db['agent_type'] ==
                            bgp_consts.AGENT_TYPE_BGP_ROUTING)
            if not is_agent_bgp or not agent_up:
                raise bgp_dras_ext.DrAgentInvalid(id=agent_id)

            binding = BgpSpeakerDrAgentBinding()
            binding.bgp_speaker_id = speaker_id
            binding.agent_id = agent_id
            context.session.add(binding)

        self._bgp_rpc.bgp_speaker_created(context, speaker_id, agent_db.host)

    def remove_bgp_speaker_from_dragent(self, context, agent_id, speaker_id):
        with context.session.begin(subtransactions=True):
            agent_db = self._get_agent(context, agent_id)
            is_agent_bgp = (agent_db['agent_type'] ==
                            bgp_consts.AGENT_TYPE_BGP_ROUTING)
            if not is_agent_bgp:
                raise bgp_dras_ext.DrAgentInvalid(id=agent_id)

            query = context.session.query(BgpSpeakerDrAgentBinding)
            query = query.filter_by(bgp_speaker_id=speaker_id,
                                    agent_id=agent_id)

            num_deleted = query.delete()
            if not num_deleted:
                raise bgp_dras_ext.DrAgentNotHostingBgpSpeaker(
                    bgp_speaker_id=speaker_id,
                    agent_id=agent_id)
            LOG.debug('BgpSpeaker %(bgp_speaker_id)s removed from '
                      'BgpDrAgent %(agent_id)s',
                      {'bgp_speaker_id': speaker_id,
                       'agent_id': agent_id})

        self._bgp_rpc.bgp_speaker_removed(context, speaker_id, agent_db.host)

    def get_dragents_hosting_bgp_speakers(self, context, bgp_speaker_ids,
                                          active=None, admin_state_up=None):
        query = context.session.query(BgpSpeakerDrAgentBinding)
        query = query.options(orm.contains_eager(
                              BgpSpeakerDrAgentBinding.dragent))
        query = query.join(BgpSpeakerDrAgentBinding.dragent)

        if len(bgp_speaker_ids) == 1:
            query = query.filter(
                BgpSpeakerDrAgentBinding.bgp_speaker_id == (
                    bgp_speaker_ids[0]))
        elif bgp_speaker_ids:
            query = query.filter(
                BgpSpeakerDrAgentBinding.bgp_speaker_id in bgp_speaker_ids)
        if admin_state_up is not None:
            query = query.filter(agents_db.Agent.admin_state_up ==
                                 admin_state_up)

        return [binding.dragent
                for binding in query
                if as_db.AgentSchedulerDbMixin.is_eligible_agent(
                                                active, binding.dragent)]

    def get_dragent_bgp_speaker_bindings(self, context):
        return context.session.query(BgpSpeakerDrAgentBinding).all()

    def list_dragent_hosting_bgp_speaker(self, context, speaker_id):
        dragents = self.get_dragents_hosting_bgp_speakers(context,
                                                          [speaker_id])
        agent_ids = [dragent.id for dragent in dragents]
        if not agent_ids:
            return {'agents': []}
        return {'agents': self.get_agents(context, filters={'id': agent_ids})}

    def list_bgp_speaker_on_dragent(self, context, agent_id):
        query = context.session.query(BgpSpeakerDrAgentBinding.bgp_speaker_id)
        query = query.filter_by(agent_id=agent_id)

        bgp_speaker_ids = [item[0] for item in query]
        if not bgp_speaker_ids:
            # Exception will be thrown if the requested agent does not exist.
            self._get_agent(context, agent_id)
            return {'bgp_speakers': []}
        return {'bgp_speakers':
                self.get_bgp_speakers(context,
                                      filters={'id': bgp_speaker_ids})}

    def get_bgp_speakers_for_agent_host(self, context, host):
        agent = self._get_agent_by_type_and_host(
            context, bgp_consts.AGENT_TYPE_BGP_ROUTING, host)
        if not agent.admin_state_up:
            return {}

        query = context.session.query(BgpSpeakerDrAgentBinding)
        query = query.filter(BgpSpeakerDrAgentBinding.agent_id == agent.id)
        try:
            binding = query.one()
        except exc.NoResultFound:
            return []
        bgp_speaker = self.get_bgp_speaker_with_advertised_routes(
                                context, binding['bgp_speaker_id'])
        return [bgp_speaker]

    def get_bgp_speaker_by_speaker_id(self, context, bgp_speaker_id):
        try:
            return self.get_bgp_speaker(context, bgp_speaker_id)
        except exc.NoResultFound:
            return {}

    def get_bgp_peer_by_peer_id(self, context, bgp_peer_id):
        try:
            return self.get_bgp_peer(context, bgp_peer_id)
        except exc.NoResultFound:
            return {}