1
# Copyright (c) 2011-2012 OpenStack Foundation.
4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
5
# not use this file except in compliance with the License. You may obtain
6
# a copy of the License at
8
# http://www.apache.org/licenses/LICENSE-2.0
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
# License for the specific language governing permissions and limitations
20
from manila.openstack.common._i18n import _LI
21
from manila.openstack.common import log as logging
22
from manila.openstack.common.scheduler import base_handler
24
LOG = logging.getLogger(__name__)
27
class BaseFilter(object):
28
"""Base class for all filter classes."""
29
def _filter_one(self, obj, filter_properties):
30
"""Return True if it passes the filter, False otherwise.
31
Override this in a subclass.
35
def filter_all(self, filter_obj_list, filter_properties):
36
"""Yield objects that pass the filter.
38
Can be overridden in a subclass, if you need to base filtering
39
decisions on all objects. Otherwise, one can just override
40
_filter_one() to filter a single object.
42
for obj in filter_obj_list:
43
if self._filter_one(obj, filter_properties):
46
# Set to true in a subclass if a filter only needs to be run once
47
# for each request rather than for each instance
48
run_filter_once_per_request = False
50
def run_filter_for_index(self, index):
51
"""Return True if the filter needs to be run for the "index-th"
52
instance in a request. Only need to override this if a filter
53
needs anything other than "first only" or "all" behaviour.
55
return not (self.run_filter_once_per_request and index > 0)
58
class BaseFilterHandler(base_handler.BaseHandler):
59
"""Base class to handle loading filter classes.
61
This class should be subclassed where one needs to use filters.
64
def get_filtered_objects(self, filter_classes, objs,
65
filter_properties, index=0):
66
"""Get objects after filter
68
:param filter_classes: filters that will be used to filter the
70
:param objs: objects that will be filtered
71
:param filter_properties: client filter properties
72
:param index: This value needs to be increased in the caller
73
function of get_filtered_objects when handling
76
list_objs = list(objs)
77
LOG.debug("Starting with %d host(s)", len(list_objs))
78
for filter_cls in filter_classes:
79
cls_name = filter_cls.__name__
80
filter_class = filter_cls()
82
if filter_class.run_filter_for_index(index):
83
objs = filter_class.filter_all(list_objs, filter_properties)
85
LOG.debug("Filter %(cls_name)s says to stop filtering",
86
{'cls_name': cls_name})
88
list_objs = list(objs)
89
msg = (_LI("Filter %(cls_name)s returned %(obj_len)d host(s)")
90
% {'cls_name': cls_name, 'obj_len': len(list_objs)})