File: config.py

package info (click to toggle)
pg-activity 3.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,144 kB
  • sloc: python: 3,902; sql: 1,067; sh: 5; makefile: 2
file content (370 lines) | stat: -rw-r--r-- 11,939 bytes parent folder | download | duplicates (2)
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
from __future__ import annotations

import configparser
import enum
import importlib.resources
import io
import os
from collections.abc import ItemsView
from pathlib import Path
from typing import IO, Any, TypeVar, Union

import attr
from attr import validators

from .compat import gt


def read_resource(pkgname: str, dirname: str, *args: str) -> str | None:
    resource = importlib.resources.files(pkgname).joinpath(dirname)
    for arg in args:
        resource = resource.joinpath(arg)
    if resource.is_file():
        return resource.read_text()
    return None


class ConfigurationError(Exception):
    def __init__(self, filename: str, *args: Any) -> None:
        super().__init__(*args)
        self.filename = filename

    @property
    def message(self) -> str:
        return super().__str__()

    def __str__(self) -> str:
        return f"invalid configuration '{self.filename}': {self.message}"


class InvalidSection(ConfigurationError):
    def __init__(self, section: str, *args: Any) -> None:
        super().__init__(*args)
        self.section = section

    @property
    def message(self) -> str:
        return f"invalid section '{self.section}'"


class InvalidOptions(ConfigurationError):
    def __init__(self, section: str, message: str, *args: Any) -> None:
        super().__init__(*args)
        self.section = section
        self._message = message

    @property
    def message(self) -> str:
        return f"invalid option(s) in '{self.section}': {self._message}"


class Flag(enum.Flag):
    """Column flag.

    >>> Flag.names()
    ['database', 'appname', 'client', 'user', 'cpu', 'mem', 'read', 'write', 'time', 'wait', 'relation', 'type', 'mode', 'iowait', 'pid', 'xmin']
    >>> Flag.all()  # doctest: +ELLIPSIS
    <Flag...: 65535>
    """

    DATABASE = enum.auto()
    APPNAME = enum.auto()
    CLIENT = enum.auto()
    USER = enum.auto()
    CPU = enum.auto()
    MEM = enum.auto()
    READ = enum.auto()
    WRITE = enum.auto()
    TIME = enum.auto()
    WAIT = enum.auto()
    RELATION = enum.auto()
    TYPE = enum.auto()
    MODE = enum.auto()
    IOWAIT = enum.auto()
    PID = enum.auto()
    XMIN = enum.auto()

    @classmethod
    def names(cls) -> list[str]:
        rv = []
        for f in cls:
            assert f.name
            rv.append(f.name.lower())
        return rv

    @classmethod
    def all(cls) -> Flag:
        value = cls(0)
        for f in cls:
            value |= f
        return value

    @classmethod
    def from_config(cls, config: Configuration) -> Flag:
        value = cls(0)
        for f in cls:
            assert f.name is not None
            try:
                cfg = config[f.name.lower()]
            except KeyError:
                pass
            else:
                assert isinstance(cfg, UISection)
                if cfg.hidden:
                    continue
            value |= f
        return value

    @classmethod
    def load(
        cls,
        config: Configuration | None,
        *,
        is_local: bool,
        appname: bool | None,
        client: bool | None,
        cpu: bool | None,
        database: bool | None,
        mem: bool | None,
        pid: bool | None,
        read: bool | None,
        time: bool | None,
        user: bool | None,
        wait: bool | None,
        write: bool | None,
        xmin: bool | None,
        **kwargs: Any,
    ) -> Flag:
        """Build a Flag value from command line options."""
        if config:
            flag = cls.from_config(config)
        else:
            flag = cls.all()
        for opt, value in (
            (appname, cls.APPNAME),
            (client, cls.CLIENT),
            (cpu, cls.CPU),
            (database, cls.DATABASE),
            (mem, cls.MEM),
            (pid, cls.PID),
            (read, cls.READ),
            (time, cls.TIME),
            (user, cls.USER),
            (wait, cls.WAIT),
            (write, cls.WRITE),
            (xmin, cls.XMIN),
        ):
            if opt is True:
                flag |= value
            elif opt is False:
                flag ^= value
        # Remove some if no running against local pg server.
        if not is_local and (flag & cls.CPU):
            flag ^= cls.CPU
        if not is_local and (flag & cls.MEM):
            flag ^= cls.MEM
        if not is_local and (flag & cls.READ):
            flag ^= cls.READ
        if not is_local and (flag & cls.WRITE):
            flag ^= cls.WRITE
        if not is_local and (flag & cls.IOWAIT):
            flag ^= cls.IOWAIT
        return flag


class BaseSectionMixin:
    @classmethod
    def check_options(
        cls: type[attr.AttrsInstance], section: configparser.SectionProxy
    ) -> list[str]:
        """Check that items of 'section' conform to known attributes of this class and
        return the list of know options.
        """
        known_options = {f.name for f in attr.fields(cls)}
        unknown_options = set(section) - set(known_options)
        if unknown_options:
            raise ValueError(f"invalid option(s): {', '.join(sorted(unknown_options))}")
        return list(sorted(known_options))


@attr.s(auto_attribs=True, frozen=True, slots=True)
class HeaderSection(BaseSectionMixin):
    show_instance: bool = True
    show_system: bool = True
    show_workers: bool = True

    _T = TypeVar("_T", bound="HeaderSection")

    @classmethod
    def from_config_section(cls: type[_T], section: configparser.SectionProxy) -> _T:
        values: dict[str, bool] = {}
        for optname in cls.check_options(section):
            value = section.getboolean(optname)
            if value is not None:
                values[optname] = value
        return cls(**values)


@attr.s(auto_attribs=True, frozen=True, slots=True)
class UISection(BaseSectionMixin):
    hidden: bool = False
    width: int | None = attr.ib(default=None, validator=validators.optional(gt(0)))
    color: str | None = attr.ib(default=None)

    _T = TypeVar("_T", bound="UISection")

    @classmethod
    def from_config_section(cls: type[_T], section: configparser.SectionProxy) -> _T:
        cls.check_options(section)
        values: dict[str, Any] = {}
        hidden = section.getboolean("hidden")
        if hidden is not None:
            values["hidden"] = hidden
        values["width"] = section.getint("width")
        values["color"] = section.get("color")
        return cls(**values)


@attr.s(auto_attribs=True, frozen=True, slots=True)
class BuiltinProfile:
    name: str
    content: IO[str]

    @classmethod
    def get(cls, name: str) -> BuiltinProfile | None:
        content = read_resource("pgactivity", "profiles", f"{name}.conf")
        if content is not None:
            return cls(name, io.StringIO(content))
        return None


USER_CONFIG_HOME = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
ETC = Path("/etc")


Value = Union[HeaderSection, UISection]


@attr.s(auto_attribs=True, frozen=True, slots=True)
class Configuration:
    name: str
    values: dict[str, Value]

    def __getitem__(self, name: str) -> Value:
        return self.values.__getitem__(name)

    def get(self, name: str, default: Value | None = None) -> Value | None:
        return self.values.get(name, default)

    def items(self) -> ItemsView[str, Value]:
        return self.values.items()

    def header(self) -> HeaderSection | None:
        return self.get("header")  # type: ignore[return-value]

    _T = TypeVar("_T", bound="Configuration")

    @classmethod
    def parse(cls: type[_T], f: IO[str], name: str) -> _T:
        r"""Parse configuration from 'f'.

        >>> from io import StringIO
        >>> from pprint import pprint

        >>> f = StringIO('[header]\nshow_workers=false\n[client]\nhidden=true\ncolor=green\n')
        >>> cfg = Configuration.parse(f, "f.ini")
        >>> cfg.name
        'f.ini'
        >>> pprint(cfg.values)
        {'client': UISection(hidden=True, width=None, color='green'),
         'header': HeaderSection(show_instance=True, show_system=True, show_workers=False)}

        >>> bad = StringIO("[global]\nx=1")
        >>> Configuration.parse(bad, "bad.ini")
        Traceback (most recent call last):
          ...
        pgactivity.config.InvalidSection: invalid configuration 'bad.ini': invalid section 'global'
        >>> bad = StringIO("[xxx]\n")
        >>> Configuration.parse(bad, "bad.ini")
        Traceback (most recent call last):
          ...
        pgactivity.config.InvalidSection: invalid configuration 'bad.ini': invalid section 'xxx'
        >>> bad = StringIO("[cpu]\nx=1")
        >>> Configuration.parse(bad, "bad.ini")
        Traceback (most recent call last):
          ...
        pgactivity.config.InvalidOptions: invalid configuration 'bad.ini': invalid option(s) in 'cpu': invalid option(s): x
        >>> bad = StringIO("[mem]\nwidth=-2")
        >>> Configuration.parse(bad, "bad.ini")
        Traceback (most recent call last):
          ...
        pgactivity.config.InvalidOptions: invalid configuration 'bad.ini': invalid option(s) in 'mem': 'width' must be > 0: -2
        >>> bad = StringIO("[mem]\nwidth=xyz")
        >>> Configuration.parse(bad, "bad.ini")
        Traceback (most recent call last):
          ...
        pgactivity.config.InvalidOptions: invalid configuration 'bad.ini': invalid option(s) in 'mem': invalid literal for int() with base 10: 'xyz'
        >>> bad = StringIO("not some INI??")
        >>> Configuration.parse(bad, "bad.txt")
        Traceback (most recent call last):
          ...
        pgactivity.config.ConfigurationError: invalid configuration 'bad.txt': failed to parse INI: File contains no section headers.
        file: '<???>', line: 1
        'not some INI??'
        """
        p = configparser.ConfigParser(default_section="global", strict=True)
        try:
            p.read_file(f)
        except configparser.Error as e:
            raise ConfigurationError(name, f"failed to parse INI: {e}") from None
        known_sections = set(Flag.names())
        config: dict[str, HeaderSection | UISection] = {}
        for sname, section in p.items():
            if sname == p.default_section:
                if section:
                    raise InvalidSection(p.default_section, name)
                continue
            if sname == "header":
                config[sname] = HeaderSection.from_config_section(section)
                continue
            if sname not in known_sections:
                raise InvalidSection(sname, name)
            try:
                config[sname] = UISection.from_config_section(section)
            except ValueError as e:
                raise InvalidOptions(sname, str(e), name) from None
        return cls(name=name, values=config)

    @classmethod
    def lookup(
        cls: type[_T],
        profile: str | None,
        *,
        user_config_home: Path = USER_CONFIG_HOME,
        etc: Path = ETC,
    ) -> _T | None:
        if profile is None:
            for base in (user_config_home, etc):
                fpath = base / "pg_activity.conf"
                if fpath.exists():
                    with fpath.open() as f:
                        return cls.parse(f, str(fpath))
            return None

        assert profile  # per argument validation
        fname = f"{profile}.conf"
        bases = (user_config_home / "pg_activity", etc / "pg_activity")
        for base in bases:
            fpath = base / fname
            if fpath.exists():
                with fpath.open() as f:
                    return cls.parse(f, str(fpath))

        builtin_profile = BuiltinProfile.get(profile)
        if builtin_profile is not None:
            return cls.parse(builtin_profile.content, builtin_profile.name)

        raise FileNotFoundError(f"profile {profile!r} not found")

    def error(self, message: str) -> ConfigurationError:
        return ConfigurationError(self.name, message)