summaryrefslogtreecommitdiffstats
path: root/postgresql-dtrace.patch
diff options
context:
space:
mode:
authorPavel Raiskup <praiskup@redhat.com>2015-02-10 13:24:16 +0100
committerPavel Raiskup <praiskup@redhat.com>2015-02-10 13:46:33 +0100
commitbea99d7e37e57d209a146505313280c38c8548f1 (patch)
treedd83745f83b300e4a7158e6f7ab8d3b2351fdcf3 /postgresql-dtrace.patch
parenta494c5b62cd9a22a6a2b3a6cdc49e36af4e8d9bc (diff)
legacy-scripts: generate them from single template
As we do not consider the postgresql@ unit variants (that would require libexec/initscripts/legacy-actions/postgresql@CONCRETE symlink to the default legacy-scripts directory), there is no need to do run-time checks. * Makefile.am (upgrade): Create from legacy-sysv-script.in template. (initdb): Likewise. (systemdlegacyscripts_DATA): Substitute with .. (systemdlegacyscripts_SCRIPTS): .. this to have execute bit after installation. (GENERATED_FILES): Add _SCRIPTS variant for systemdlegacyscripts. * legacy-sysv-script.in: New unified template for legacy scripts. * initdb.in: Remove. * upgrade.in: Likewise. * NEWS: Document.
Diffstat (limited to 'postgresql-dtrace.patch')
0 files changed, 0 insertions, 0 deletions
='#n91'>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 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
# Authors:
#   Jason Gerard DeRose <jderose@redhat.com>
#
# Copyright (C) 2008  Red Hat
# see file 'COPYING' for use and warranty information
#
# 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 3 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
Plugin framework.

The classes in this module make heavy use of Python container emulation. If
you are unfamiliar with this Python feature, see
http://docs.python.org/ref/sequence-types.html
"""

import re
import sys
import inspect
import threading
import os
from os import path
import subprocess
import optparse
import errors
import textwrap

from config import Env
import util
import text
from text import _
from base import ReadOnly, NameSpace, lock, islocked, check_name
from constants import DEFAULT_CONFIG
from ipapython.ipa_log_manager import *
from ipapython.version import VERSION, API_VERSION

# FIXME: Updated constants.TYPE_ERROR to use this clearer format from wehjit:
TYPE_ERROR = '%s: need a %r; got a %r: %r'

def is_production_mode(obj):
    """
    If the object has self.env.mode defined and that mode is
    production return True, otherwise return False.
    """
    if getattr(obj, 'env', None) is None:
        return False
    if getattr(obj.env, 'mode', None) is None:
        return False
    return obj.env.mode == 'production'


class Registry(object):
    """A decorator that makes plugins available to the API

    Usage::

        register = Registry()

        @register()
        class obj_mod(...):
            ...

    For forward compatibility, make sure that the module-level instance of
    this object is named "register".
    """
    # TODO: Instead of auto-loading when plugin modules are imported,
    # plugins should be stored in this object.
    # The API should examine it and load plugins explicitly.
    def __call__(self):
        from ipalib import api

        def decorator(cls):
            api.register(cls)
            return cls

        return decorator


class SetProxy(ReadOnly):
    """
    A read-only container with set/sequence behaviour.

    This container acts as a proxy to an actual set-like object (a set,
    frozenset, or dict) that is passed to the constructor. To the extent
    possible in Python, this underlying set-like object cannot be modified
    through the SetProxy... which just means you wont do it accidentally.
    """
    def __init__(self, s):
        """
        :param s: The target set-like object (a set, frozenset, or dict)
        """
        allowed = (set, frozenset, dict)
        if type(s) not in allowed:
            raise TypeError('%r not in %r' % (type(s), allowed))
        self.__s = s
        if not is_production_mode(self):
            lock(self)

    def __len__(self):
        """
        Return the number of items in this container.
        """
        return len(self.__s)

    def __iter__(self):
        """
        Iterate (in ascending order) through keys.
        """
        for key in sorted(self.__s):
            yield key

    def __contains__(self, key):
        """
        Return True if this container contains ``key``.

        :param key: The key to test for membership.
        """
        return key in self.__s


class DictProxy(SetProxy):
    """
    A read-only container with mapping behaviour.

    This container acts as a proxy to an actual mapping object (a dict) that
    is passed to the constructor. To the extent possible in Python, this
    underlying mapping object cannot be modified through the DictProxy...
    which just means you wont do it accidentally.

    Also see `SetProxy`.
    """
    def __init__(self, d):
        """
        :param d: The target mapping object (a dict)
        """
        if type(d) is not dict:
            raise TypeError('%r is not %r' % (type(d), dict))
        self.__d = d
        super(DictProxy, self).__init__(d)

    def __getitem__(self, key):
        """
        Return the value corresponding to ``key``.

        :param key: The key of the value you wish to retrieve.
        """
        return self.__d[key]

    def __call__(self):
        """
        Iterate (in ascending order by key) through values.
        """
        for key in self:
            yield self.__d[key]


class MagicDict(DictProxy):
    """
    A mapping container whose values can be accessed as attributes.

    For example:

    >>> magic = MagicDict({'the_key': 'the value'})
    >>> magic['the_key']
    'the value'
    >>> magic.the_key
    'the value'

    This container acts as a proxy to an actual mapping object (a dict) that
    is passed to the constructor. To the extent possible in Python, this
    underlying mapping object cannot be modified through the MagicDict...
    which just means you wont do it accidentally.

    Also see `DictProxy` and `SetProxy`.
    """

    def __getattr__(self, name):
        """
        Return the value corresponding to ``name``.

        :param name: The name of the attribute you wish to retrieve.
        """
        try:
            return self[name]
        except KeyError:
            raise AttributeError('no magic attribute %r' % name)


class Plugin(ReadOnly):
    """
    Base class for all plugins.
    """

    finalize_early = True

    label = None

    def __init__(self):
        self.__api = None
        self.__finalize_called = False
        self.__finalized = False
        self.__finalize_lock = threading.RLock()
        cls = self.__class__
        self.name = cls.__name__
        self.module = cls.__module__
        self.fullname = '%s.%s' % (self.module, self.name)
        self.bases = tuple(
            '%s.%s' % (b.__module__, b.__name__) for b in cls.__bases__
        )
        self.doc = _(cls.__doc__)
        if not self.doc.msg:
            self.summary = '<%s>' % self.fullname
        else:
            self.summary = unicode(self.doc).split('\n\n', 1)[0].strip()
        log_mgr.get_logger(self, True)
        if self.label is None:
            self.label = text.FixMe(self.name + '.label')
        if not isinstance(self.label, text.LazyText):
            raise TypeError(
                TYPE_ERROR % (
                    self.fullname + '.label',
                    text.LazyText,
                    type(self.label),
                    self.label
                )
            )

    def __get_api(self):
        """
        Return `API` instance passed to `set_api()`.

        If `set_api()` has not yet been called, None is returned.
        """
        return self.__api
    api = property(__get_api)

    def finalize(self):
        """
        Finalize plugin initialization.

        This method calls `_on_finalize()` and locks the plugin object.

        Subclasses should not override this method. Custom finalization is done
        in `_on_finalize()`.
        """
        with self.__finalize_lock:
            assert self.__finalized is False
            if self.__finalize_called:
                # No recursive calls!
                return
            self.__finalize_called = True
            self._on_finalize()
            self.__finalized = True
            if not is_production_mode(self):
                lock(self)

    def _on_finalize(self):
        """
        Do custom finalization.

        This method is called from `finalize()`. Subclasses can override this
        method in order to add custom finalization.
        """
        pass

    def ensure_finalized(self):
        """
        Finalize plugin initialization if it has not yet been finalized.
        """
        with self.__finalize_lock:
            if not self.__finalized:
                self.finalize()

    class finalize_attr(object):
        """
        Create a stub object for plugin attribute that isn't set until the
        finalization of the plugin initialization.

        When the stub object is accessed, it calls `ensure_finalized()` to make
        sure the plugin initialization is finalized. The stub object is expected
        to be replaced with the actual attribute value during the finalization
        (preferably in `_on_finalize()`), otherwise an `AttributeError` is
        raised.

        This is used to implement on-demand finalization of plugin
        initialization.
        """
        __slots__ = ('name', 'value')

        def __init__(self, name, value=None):
            self.name = name
            self.value = value

        def __get__(self, obj, cls):
            if obj is None or obj.api is None:
                return self.value
            obj.ensure_finalized()
            try:
                return getattr(obj, self.name)
            except RuntimeError:
                # If the actual attribute value is not set in _on_finalize(),
                # getattr() calls __get__() again, which leads to infinite
                # recursion. This can happen only if the plugin is written
                # badly, so advise the developer about that instead of giving
                # them a generic "maximum recursion depth exceeded" error.
                raise AttributeError(
                    "attribute '%s' of plugin '%s' was not set in finalize()" % (self.name, obj.name)
                )

    def set_api(self, api):
        """
        Set reference to `API` instance.
        """
        assert self.__api is None, 'set_api() can only be called once'
        assert api is not None, 'set_api() argument cannot be None'
        self.__api = api
        if not isinstance(api, API):
            return
        for name in api:
            assert not hasattr(self, name)
            setattr(self, name, api[name])
        for name in ('env', 'context'):
            if hasattr(api, name):
                assert not hasattr(self, name)
                setattr(self, name, getattr(api, name))

    def call(self, executable, *args):
        """
        Call ``executable`` with ``args`` using subprocess.call().

        If the call exits with a non-zero exit status,
        `ipalib.errors.SubprocessError` is raised, from which you can retrieve
        the exit code by checking the SubprocessError.returncode attribute.

        This method does *not* return what ``executable`` sent to stdout... for
        that, use `Plugin.callread()`.
        """
        argv = (executable,) + args
        self.debug('Calling %r', argv)
        code = subprocess.call(argv)
        if code != 0:
            raise errors.SubprocessError(returncode=code, argv=argv)

    def __repr__(self):
        """
        Return 'module_name.class_name()' representation.

        This representation could be used to instantiate this Plugin
        instance given the appropriate environment.
        """
        return '%s.%s()' % (
            self.__class__.__module__,
            self.__class__.__name__
        )


class Registrar(DictProxy):
    """
    Collects plugin classes as they are registered.

    The Registrar does not instantiate plugins... it only implements the
    override logic and stores the plugins in a namespace per allowed base
    class.

    The plugins are instantiated when `API.finalize()` is called.
    """
    def __init__(self, *allowed):
        """
        :param allowed: Base classes from which plugins accepted by this
            Registrar must subclass.
        """
        self.__allowed = dict((base, {}) for base in allowed)
        self.__registered = set()
        super(Registrar, self).__init__(
            dict(self.__base_iter())
        )

    def __base_iter(self):
        for (base, sub_d) in self.__allowed.iteritems():
            if not is_production_mode(self):
                assert inspect.isclass(base)
            name = base.__name__
            if not is_production_mode(self):
                assert not hasattr(self, name)
            setattr(self, name, MagicDict(sub_d))
            yield (name, base)

    def __findbases(self, klass):
        """
        Iterates through allowed bases that ``klass`` is a subclass of.

        Raises `errors.PluginSubclassError` if ``klass`` is not a subclass of
        any allowed base.

        :param klass: The plugin class to find bases for.
        """
        if not is_production_mode(self):
            assert inspect.isclass(klass)
        found = False
        for (base, sub_d) in self.__allowed.iteritems():
            if issubclass(klass, base):
                found = True
                yield (base, sub_d)
        if not found:
            raise errors.PluginSubclassError(
                plugin=klass, bases=self.__allowed.keys()
            )

    def __call__(self, klass, override=False):
        """
        Register the plugin ``klass``.

        :param klass: A subclass of `Plugin` to attempt to register.
        :param override: If true, override an already registered plugin.
        """
        if not inspect.isclass(klass):
            raise TypeError('plugin must be a class; got %r' % klass)

        # Raise DuplicateError if this exact class was already registered:
        if klass in self.__registered:
            raise errors.PluginDuplicateError(plugin=klass)

        # Find the base class or raise SubclassError:
        for (base, sub_d) in self.__findbases(klass):
            # Check override:
            if klass.__name__ in sub_d:
                if not override:
                    # Must use override=True to override:
                    raise errors.PluginOverrideError(
                        base=base.__name__,
                        name=klass.__name__,
                        plugin=klass,
                    )
            else:
                if override:
                    # There was nothing already registered to override:
                    raise errors.PluginMissingOverrideError(
                        base=base.__name__,
                        name=klass.__name__,
                        plugin=klass,
                    )

            # The plugin is okay, add to sub_d:
            sub_d[klass.__name__] = klass

        # The plugin is okay, add to __registered:
        self.__registered.add(klass)


class API(DictProxy):
    """
    Dynamic API object through which `Plugin` instances are accessed.
    """

    def __init__(self, *allowed):
        self.__d = dict()
        self.__done = set()
        self.register = Registrar(*allowed)
        self.env = Env()
        super(API, self).__init__(self.__d)