File: selector.py

package info (click to toggle)
nfsometer 1.9-3.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 836 kB
  • sloc: python: 4,928; sh: 156; javascript: 32; makefile: 5
file content (221 lines) | stat: -rw-r--r-- 6,254 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
217
218
219
220
221
"""
Copyright 2012 NetApp, Inc. All Rights Reserved,
contribution by Weston Andros Adamson <dros@netapp.com>

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
"""

from .config import *

SELECTOR_ORDER=(
    'workload',
    'kernel',
    'mountopt',
    'detect',
    'tag',
    'client',
    'server',
    'path',
)

_valid_things = set(SELECTOR_ORDER)

def _fmt(name, x, default=None, short=True, sep=' '):
    if isinstance(x, (list, tuple)):
        return sep.join([ _fmt(name, y) for y in x ])
    return x

class Selector(object):
    """ This class is used to specify selection of the current query
    """
    def __init__(self, *args):
        things = []

        if len(args) == 0:
            # make all empty args
            args = [ [] for i in range(len(SELECTOR_ORDER)) ]

        assert len(args) == len(SELECTOR_ORDER)

        for idx, name in enumerate(SELECTOR_ORDER):
            obj = args[idx]
            if not isinstance(obj, (list, tuple)):
                obj = [obj]

            setattr(self, name + 's', tuple(obj))

    def __str__(self):
        out = []

        for name in SELECTOR_ORDER:
            obj = getattr(self, name + 's')
            out.append('%s%s: %s' % (name, pluralize(len(obj)), ', '.join(obj)))

        return ', '.join(out)

    def __hash__(self):
        args = []

        for name in SELECTOR_ORDER:
            obj = getattr(self, name + 's')
            assert len(obj) == 1, \
                "Can't hash selector with %s length != 1 - %r" % (name, obj)
            args.append(obj)

        return hash(tuple(args))

    def __eq__(self, other):
        for name in SELECTOR_ORDER:
            if getattr(self, name + 's') != getattr(other, name + 's'):
                return False
        return True

    def __lt__(self, other):
        return NotImplemented

    def __le__(self, other):
        return NotImplemented

    def __gt__(self, other):
        return NotImplemented

    def __ge__(self, other):
        return NotImplemented

    def match_order(self, other, order):
        for name in order:
            if getattr(self, name + 's') != getattr(other, name + 's'):
                return False
        return True

    def __repr__(self):
        args = []

        for name in SELECTOR_ORDER:
            obj = getattr(self, name + 's')
            args.append(obj)

        return 'Selector(%s)' % (', '.join([repr(x) for x in args]),)

    def __getattr__(self, attr):
        superself = super(Selector, self)
        if attr in SELECTOR_ORDER:
            obj = getattr(self, attr + 's')
            assert len(obj) == 1, "%s is not singular" % attr
            return obj[0]
        elif hasattr(superself, attr):
            return getattr(superself, attr)
        else:
            raise AttributeError("invalid attribute: %r" % attr)

    def __add__(self, other):
        new = Selector()
        for name in SELECTOR_ORDER:
            vals = set(getattr(self, name + 's'))
            for x in getattr(other, name + 's'):
                vals.add(x)
            setattr(new, name + 's', list(vals))

        return new

    def html(self):
        out = []

        for name in SELECTOR_ORDER:
            obj = getattr(self, name + 's')
            out.append('%s%s: %s' % (name, pluralize(len(obj)), ', '.join(obj)))

        return '<br>'.join(out)

    def is_valid_key(self):
        for name in SELECTOR_ORDER:
            obj = getattr(self, name + 's')
            if len(obj) != 1:
                return False
        return True

    def _foreach_thing(self, thing):
        if isinstance(thing, (list, tuple)):
            thing = list(thing)
            more_things = thing[1:]
            thing = thing[0]
        else:
            assert thing in _valid_things
            more_things = []

        for x in getattr(self, thing + 's'):
            args = []

            for name in SELECTOR_ORDER:
                if name == thing:
                    obj = x
                else:
                    obj = getattr(self, name + 's')
                args.append(obj)

            sel = Selector(*args)

            if more_things:
                for y in sel._foreach_thing(more_things):
                    yield y
            else:
                yield sel

    def foreach(self, thing=None):
        if thing == None:
            thing = SELECTOR_ORDER

        for x in self._foreach_thing(thing):
            yield x

    def fmt(self, thing, short=True, title=False):
        x = getattr(self, thing + 's')
        return _fmt(thing, x, default = lambda x : ' '.join(x), short=short)

    def title(self, thing):
        x = getattr(self, thing + 's')
        return "%s%s" % (thing, pluralize(len(obj)))

    def display_info(self, all_selector, show_all=False, sep=' ',
                     pre='', post=''):
        display_info = []

        for name in SELECTOR_ORDER:
            obj = getattr(self, name + 's')
            all_obj = getattr(all_selector, name + 's')

            if show_all or obj != all_obj:
                pl = pluralize(len(obj))
                entry = ('%s%s' % (name, pl),
                         pre + str(_fmt(name, obj, sep=sep)) + post)
                display_info.append(entry)

        return display_info

    def contains(self, other):
        for name in SELECTOR_ORDER:
            this = set(getattr(self, name + 's'))
            other_list = getattr(other, name + 's')

            # make sure each element of other is in self
            for o in other_list:
                if not o in this:
                    return False

        return True

def merge_selectors(selectors):
    total = Selector()
    for s in selectors:
        total += s
    return total

def filter_groups(groups, selector):
    return [ g for g in groups if selector.contains(g) ]