summaryrefslogtreecommitdiff
path: root/ceilometer/network/services/lbaas.py
blob: 85d63dce1ff7009878130129826f6c0774042a37 (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
#
# Copyright 2014 Cisco Systems,Inc.
#
# 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 abc
import collections
import warnings

from oslo_log import log

from ceilometer.i18n import _
from ceilometer.network.services import base
from ceilometer import neutron_client
from ceilometer import sample

LOG = log.getLogger(__name__)

LBStatsData = collections.namedtuple(
    'LBStats',
    ['active_connections', 'total_connections', 'bytes_in', 'bytes_out']
)

LOAD_BALANCER_STATUS_V2 = {
    'offline': 0,
    'online': 1,
    'no_monitor': 3,
    'error': 4,
    'degraded': 5,
    'disabled': 6
}


class BaseLBPollster(base.BaseServicesPollster):
    """Base Class for Load Balancer pollster"""

    def __init__(self, conf):
        super(BaseLBPollster, self).__init__(conf)
        self.lb_version = self.conf.service_types.neutron_lbaas_version

        warnings.warn('Support for Neutron LBaaS has been deprecated '
                      'and will be removed in a future release.',
                      category=DeprecationWarning, stacklevel=3)

    def get_load_balancer_status_id(self, value):
        if self.lb_version == 'v1':
            resource_status = self.get_status_id(value)
        elif self.lb_version == 'v2':
            status = value.lower()
            resource_status = LOAD_BALANCER_STATUS_V2.get(status, -1)
        return resource_status


class LBPoolPollster(BaseLBPollster):
    """Pollster to capture Load Balancer pool status samples."""

    FIELDS = ['admin_state_up',
              'description',
              'lb_method',
              'name',
              'protocol',
              'provider',
              'status',
              'status_description',
              'subnet_id',
              'vip_id'
              ]

    @property
    def default_discovery(self):
        return 'lb_pools'

    def get_samples(self, manager, cache, resources):
        resources = resources or []

        for pool in resources:
            LOG.debug("Load Balancer Pool : %s" % pool)
            status = self.get_load_balancer_status_id(pool['status'])
            if status == -1:
                # unknown status, skip this sample
                LOG.warning(_("Unknown status %(stat)s received on pool "
                              "%(id)s, skipping sample")
                            % {'stat': pool['status'], 'id': pool['id']})
                continue

            yield sample.Sample(
                name='network.services.lb.pool',
                type=sample.TYPE_GAUGE,
                unit='pool',
                volume=status,
                user_id=None,
                project_id=pool['tenant_id'],
                resource_id=pool['id'],
                resource_metadata=self.extract_metadata(pool)
            )


class LBVipPollster(base.BaseServicesPollster):
    """Pollster to capture Load Balancer Vip status samples."""

    FIELDS = ['admin_state_up',
              'address',
              'connection_limit',
              'description',
              'name',
              'pool_id',
              'port_id',
              'protocol',
              'protocol_port',
              'status',
              'status_description',
              'subnet_id',
              'session_persistence',
              ]

    @property
    def default_discovery(self):
        return 'lb_vips'

    def get_samples(self, manager, cache, resources):
        resources = resources or []

        for vip in resources:
            LOG.debug("Load Balancer Vip : %s" % vip)
            status = self.get_status_id(vip['status'])
            if status == -1:
                # unknown status, skip this sample
                LOG.warning(_("Unknown status %(stat)s received on vip "
                              "%(id)s, skipping sample")
                            % {'stat': vip['status'], 'id': vip['id']})
                continue

            yield sample.Sample(
                name='network.services.lb.vip',
                type=sample.TYPE_GAUGE,
                unit='vip',
                volume=status,
                user_id=None,
                project_id=vip['tenant_id'],
                resource_id=vip['id'],
                resource_metadata=self.extract_metadata(vip)
            )


class LBMemberPollster(BaseLBPollster):
    """Pollster to capture Load Balancer Member status samples."""

    FIELDS = ['admin_state_up',
              'address',
              'pool_id',
              'protocol_port',
              'status',
              'status_description',
              'weight',
              ]

    @property
    def default_discovery(self):
        return 'lb_members'

    def get_samples(self, manager, cache, resources):
        resources = resources or []

        for member in resources:
            LOG.debug("Load Balancer Member : %s" % member)
            status = self.get_load_balancer_status_id(member['status'])
            if status == -1:
                LOG.warning(_("Unknown status %(stat)s received on member "
                              "%(id)s, skipping sample")
                            % {'stat': member['status'], 'id': member['id']})
                continue
            yield sample.Sample(
                name='network.services.lb.member',
                type=sample.TYPE_GAUGE,
                unit='member',
                volume=status,
                user_id=None,
                project_id=member['tenant_id'],
                resource_id=member['id'],
                resource_metadata=self.extract_metadata(member)
            )


class LBHealthMonitorPollster(base.BaseServicesPollster):
    """Pollster to capture Load Balancer Health probes status samples."""

    FIELDS = ['admin_state_up',
              'delay',
              'max_retries',
              'pools',
              'timeout',
              'type'
              ]

    @property
    def default_discovery(self):
        return 'lb_health_probes'

    def get_samples(self, manager, cache, resources):
        for probe in resources:
            LOG.debug("Load Balancer Health probe : %s" % probe)
            yield sample.Sample(
                name='network.services.lb.health_monitor',
                type=sample.TYPE_GAUGE,
                unit='health_monitor',
                volume=1,
                user_id=None,
                project_id=probe['tenant_id'],
                resource_id=probe['id'],
                resource_metadata=self.extract_metadata(probe)
            )


class _LBStatsPollster(base.BaseServicesPollster, metaclass=abc.ABCMeta):
    """Base Statistics pollster.

     It is capturing the statistics info and yielding samples for connections
     and bandwidth.
    """

    def __init__(self, conf):
        super(_LBStatsPollster, self).__init__(conf)
        self.client = neutron_client.Client(self.conf)
        self.lb_version = self.conf.service_types.neutron_lbaas_version

    @staticmethod
    def make_sample_from_pool(pool, name, type, unit, volume,
                              resource_metadata=None):
        if not resource_metadata:
            resource_metadata = {}
        return sample.Sample(
            name=name,
            type=type,
            unit=unit,
            volume=volume,
            user_id=None,
            project_id=pool['tenant_id'],
            resource_id=pool['id'],
            resource_metadata=resource_metadata,
        )

    def _populate_stats_cache(self, pool_id, cache):
        i_cache = cache.setdefault("lbstats", {})
        if pool_id not in i_cache:
            stats = self.client.pool_stats(pool_id)['stats']
            i_cache[pool_id] = LBStatsData(
                active_connections=stats['active_connections'],
                total_connections=stats['total_connections'],
                bytes_in=stats['bytes_in'],
                bytes_out=stats['bytes_out'],
            )
        return i_cache[pool_id]

    def _populate_stats_cache_v2(self, loadbalancer_id, cache):
        i_cache = cache.setdefault("lbstats", {})
        if loadbalancer_id not in i_cache:
            stats = self.client.get_loadbalancer_stats(loadbalancer_id)
            i_cache[loadbalancer_id] = LBStatsData(
                active_connections=stats['active_connections'],
                total_connections=stats['total_connections'],
                bytes_in=stats['bytes_in'],
                bytes_out=stats['bytes_out'],
            )
        return i_cache[loadbalancer_id]

    @property
    def default_discovery(self):
        discovery_resource = 'lb_pools'
        if self.lb_version == 'v2':
            discovery_resource = 'lb_loadbalancers'
        return discovery_resource

    @abc.abstractmethod
    def _get_sample(pool, c_data):
        """Return one Sample."""

    def get_samples(self, manager, cache, resources):
        if self.lb_version == 'v1':
            for pool in resources:
                try:
                    c_data = self._populate_stats_cache(pool['id'], cache)
                    yield self._get_sample(pool, c_data)
                except Exception:
                    LOG.exception('Ignoring pool %(pool_id)s',
                                  {'pool_id': pool['id']})
        elif self.lb_version == 'v2':
            for loadbalancer in resources:
                try:
                    c_data = self._populate_stats_cache_v2(loadbalancer['id'],
                                                           cache)
                    yield self._get_sample(loadbalancer, c_data)
                except Exception:
                    LOG.exception(
                        'Ignoring loadbalancer %(loadbalancer_id)s',
                        {'loadbalancer_id': loadbalancer['id']})


class LBActiveConnectionsPollster(_LBStatsPollster):
    """Pollster to capture Active Load Balancer connections."""

    @staticmethod
    def _get_sample(pool, data):
        return make_sample_from_pool(
            pool,
            name='network.services.lb.active.connections',
            type=sample.TYPE_GAUGE,
            unit='connection',
            volume=data.active_connections,
        )


class LBTotalConnectionsPollster(_LBStatsPollster):
    """Pollster to capture Total Load Balancer connections."""

    @staticmethod
    def _get_sample(pool, data):
        return make_sample_from_pool(
            pool,
            name='network.services.lb.total.connections',
            type=sample.TYPE_CUMULATIVE,
            unit='connection',
            volume=data.total_connections,
        )


class LBBytesInPollster(_LBStatsPollster):
    """Pollster to capture incoming bytes."""

    @staticmethod
    def _get_sample(pool, data):
        return make_sample_from_pool(
            pool,
            name='network.services.lb.incoming.bytes',
            type=sample.TYPE_GAUGE,
            unit='B',
            volume=data.bytes_in,
        )


class LBBytesOutPollster(_LBStatsPollster):
    """Pollster to capture outgoing bytes."""

    @staticmethod
    def _get_sample(pool, data):
        return make_sample_from_pool(
            pool,
            name='network.services.lb.outgoing.bytes',
            type=sample.TYPE_GAUGE,
            unit='B',
            volume=data.bytes_out,
        )


def make_sample_from_pool(pool, name, type, unit, volume,
                          resource_metadata=None):
    resource_metadata = resource_metadata or {}

    return sample.Sample(
        name=name,
        type=type,
        unit=unit,
        volume=volume,
        user_id=None,
        project_id=pool['tenant_id'],
        resource_id=pool['id'],
        resource_metadata=resource_metadata,
    )


class LBListenerPollster(BaseLBPollster):
    """Pollster to capture Load Balancer Listener status samples."""

    FIELDS = ['admin_state_up',
              'connection_limit',
              'description',
              'name',
              'default_pool_id',
              'protocol',
              'protocol_port',
              'operating_status',
              'loadbalancers'
              ]

    @property
    def default_discovery(self):
        return 'lb_listeners'

    def get_samples(self, manager, cache, resources):
        resources = resources or []

        for listener in resources:
            LOG.debug("Load Balancer Listener : %s" % listener)
            status = self.get_load_balancer_status_id(
                listener['operating_status'])
            if status == -1:
                # unknown status, skip this sample
                LOG.warning(_("Unknown status %(stat)s received on listener "
                              "%(id)s, skipping sample")
                            % {'stat': listener['operating_status'],
                               'id': listener['id']})
                continue

            yield sample.Sample(
                name='network.services.lb.listener',
                type=sample.TYPE_GAUGE,
                unit='listener',
                volume=status,
                user_id=None,
                project_id=listener['tenant_id'],
                resource_id=listener['id'],
                resource_metadata=self.extract_metadata(listener)
            )


class LBLoadBalancerPollster(BaseLBPollster):
    """Pollster to capture Load Balancer status samples."""

    FIELDS = ['admin_state_up',
              'description',
              'vip_address',
              'listeners',
              'name',
              'vip_subnet_id',
              'operating_status',
              ]

    @property
    def default_discovery(self):
        return 'lb_loadbalancers'

    def get_samples(self, manager, cache, resources):
        resources = resources or []

        for loadbalancer in resources:
            LOG.debug("Load Balancer: %s" % loadbalancer)
            status = self.get_load_balancer_status_id(
                loadbalancer['operating_status'])
            if status == -1:
                # unknown status, skip this sample
                LOG.warning(_("Unknown status %(stat)s received "
                              "on Load Balancer "
                              "%(id)s, skipping sample")
                            % {'stat': loadbalancer['operating_status'],
                               'id': loadbalancer['id']})
                continue

            yield sample.Sample(
                name='network.services.lb.loadbalancer',
                type=sample.TYPE_GAUGE,
                unit='loadbalancer',
                volume=status,
                user_id=None,
                project_id=loadbalancer['tenant_id'],
                resource_id=loadbalancer['id'],
                resource_metadata=self.extract_metadata(loadbalancer)
            )