How to use the pyrsistent.PClass function in pyrsistent

To help you get started, we’ve selected a few pyrsistent examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github itamarst / eliot / eliot / testing.py View on Github external
def __new__(cls, message):
        return PClass.__new__(cls, message=message)
github ClusterHQ / flocker / flocker / ca / _validation.py View on Github external
:param reactor: The reactor to use.
    :param FilePath ca_path: Absolute path to the public cluster certificate.
    :param FilePath user_cert_path: Absolute path to the user certificate.
    :param FilePath user_key_path: Absolute path to the user private key.

    :return: ``treq`` compatible object.
    """
    ca = Certificate.loadPEM(ca_path.getContent())
    user_credential = UserCredential.from_files(user_cert_path, user_key_path)
    policy = ControlServicePolicy(
        ca_certificate=ca, client_credential=user_credential.credential)
    return HTTPClient(Agent(reactor, contextFactory=policy))


@implementer(IPolicyForHTTPS)
class KubernetesPolicy(PClass):
    """
    HTTPS TLS policy for validating the Kubernetes master identity.

    :ivar FlockerCredential client_credential: Client's certificate and
        private key pair.
    """
    ca_certificate = field(mandatory=True)
    expected_common_name = field(mandatory=True, type=unicode)

    def creatorForNetloc(self, hostname, port):
        return optionsForClientTLS(
            self.expected_common_name,
            trustRoot=self.ca_certificate,
        )
github ClusterHQ / flocker / benchmark / operations / create_dataset.py View on Github external
from pyrsistent import PClass, field
from zope.interface import implementer

from flocker.common import loop_until

from .._interfaces import IProbe, IOperation


class EmptyClusterError(Exception):
    """
    Exception indicating that the cluster contains no nodes.
    """


@implementer(IProbe)
class CreateDatasetProbe(PClass):
    """
    Probe to create a dataset and wait for it to be mounted.
    """

    reactor = field(mandatory=True)
    control_service = field(mandatory=True)
    primary = field(mandatory=True)
    dataset_id = field(mandatory=True)
    volume_size = field(mandatory=True)

    @classmethod
    def setup(cls, reactor, control_service, dataset_id, volume_size):
        """
        Create a probe.

        :param reactor: Twisted Reactor.
github ClusterHQ / flocker / flocker / common / algebraic.py View on Github external
from hypothesis.strategies import composite, sampled_from

from twisted.python.constants import NamedConstant

__all__ = ["TaggedUnionInvariant"]


class _AttributeSet(CheckedPSet):
    """
    Set of attribute names.
    """
    __type__ = str


class TaggedUnionInvariant(PClass):
    """
    An invariant that ensure the given object has an allowd tag attribute, and
    that all the other specified attributes are present if and only if the
    object has the appropriate tag. The tags must be
    :py:class:`NamedConstant`s.

    .. note:: Attributes that aren't specified by any tag are ignored.

    :param str tag_attribute: The attribute that contains the tag.
    :param dict attributes_for_tag: Dictionary mapping tags to the
        set of attributes allowed by that tag.
    """

    tag_attribute = field(str, mandatory=True)
    attributes_for_tag = pmap_field(
        key_type=NamedConstant,
github ClusterHQ / flocker / flocker / apiclient / _client.py View on Github external
NoneType = type(None)


class ServerResponseMissingElementError(Exception):
    """
    Output the invalid server response if a response does not contain an
    expected JSON object attribute.
    """
    def __init__(self, key, response):
        message = u'{!r} not found in {!r}'.format(key, response)
        Exception.__init__(self, message)


class Dataset(PClass):
    """
    A dataset in the configuration.

    :attr UUID primary: The node where the dataset should manifest.
    :attr int|None maximum_size: Size of the dataset in bytes or ``None``
        if no particular size was requested.
    :attr UUID dataset_id: The UUID of the dataset.
    :attr metadata: A mapping between unicode keys and values.
    """
    dataset_id = field(type=UUID, mandatory=True)
    primary = field(type=UUID, mandatory=True)
    maximum_size = field(type=(int, NoneType), mandatory=True)
    metadata = pmap_field(unicode, unicode)


class DatasetState(PClass):
github LeastAuthority / leastauthority.com / src / lae_automation / subscription_converger.py View on Github external
# We don't ever have to create a Pod.  We'll just delete the ones we don't
    # need anymore.
    deletes = []
    for pod in actual.pods:
        sid = pod.metadata.annotations[u"subscription"]
        if sid not in actual.subscriptions:
            Message.log(condition=u"undesired", subscription=sid)
            deletes.append(pod.metadata)

    def delete(metadata):
        return k8s.delete(k8s.k8s.model.v1.Pod(metadata=metadata))

    return list(partial(delete, metadata) for metadata in deletes)


class _ChangeableConfigMaps(PClass):
    deploy_config = field(type=DeploymentConfiguration)
    k8s_model = field()
    configmaps = field(
        factory=lambda configmaps: {
            c.metadata.annotations[u"subscription"]: c
            for c in configmaps
        },
    )

    def itersubscription_ids(self):
        return sorted(self.configmaps.iterkeys())


    def needs_update(self, subscription):
        actual_configmap = self.configmaps[subscription.subscription_id]
        expected_configmap = create_configuration(
github ClusterHQ / flocker / flocker / provision / _install.py View on Github external
@attributes(['distribution'])
class DistributionNotSupported(NotImplementedError):
    """
    Raised when the provisioning step is not supported on the given
    distribution.

    :ivar bytes distribution: The distribution that isn't supported.
    """
    def __str__(self):
        return "Distribution not supported: %s" % (self.distribution,)


@implementer(INode)
class ManagedNode(PClass):
    """
    A node managed by some other system (eg by hand or by another piece of
    orchestration software).
    """
    address = field(type=bytes, mandatory=True)
    private_address = field(type=(bytes, type(None)),
                            initial=None, mandatory=True)
    distribution = field(type=bytes, mandatory=True)


def ensure_minimal_setup(package_manager):
    """
    Get any system into a reasonable state for installation.

    Although we could publish these commands in the docs, they add a lot
    of noise for many users.  Ensure that systems have sudo enabled.
github ClusterHQ / flocker / flocker / control / configuration_store / interface.py View on Github external
# Copyright ClusterHQ Inc.  See LICENSE file for details.

"""
Interface for cluster configuration storage plugin.
"""
from base64 import b16encode
from mmh3 import hash_bytes as mmh3_hash_bytes
from pyrsistent import PClass, field
from zope.interface import Interface


class Content(PClass):
    data = field(type=(bytes,), mandatory=True)

    @property
    def hash(self):
        return b16encode(mmh3_hash_bytes(self.data)).lower()


class IConfigurationStore(Interface):
    """
    An interface for initializing, getting and setting Flocker configuration.
    """
    def initialize():
        """
        Set up a configuration store.
        The implementation must be idempotent.
        Calling ``initialize`` on an already initialized store must not change
github ClusterHQ / flocker / flocker / control / _model.py View on Github external
for (key, value) in pmap.items():
            if key != getattr(value, attribute):
                return (
                    False, "{} is not correct key for {}".format(key, value)
                )
        return (True, "")
    return key_match_invariant


# An invariant we use a couple times below in mappings from dataset_id to
# Dataset or Manifestation instances (or anything with a "dataset_id"
# attribute, really).
_keys_match_dataset_id = _keys_match("dataset_id")


class Node(PClass):
    """
    Configuration for a single node on which applications will be managed
    (deployed, reconfigured, destroyed, etc).

    Manifestations attached to applications must also be present in the
    ``manifestations`` attribute.

    :ivar UUID uuid: The unique identifier for the node.

    :ivar applications: A ``PSet`` of ``Application`` instances describing
        the applications which are to run on this ``Node``.

    :ivar PMap manifestations: Mapping between dataset IDs and
        corresponding ``Manifestation`` instances that are present on the
        node. Includes both those attached as volumes to any applications,
        and those that are unattached. ``None`` if this information is
github LeastAuthority / txkube / src / txkube / _swagger.py View on Github external
required = field(type=bool)
    default = field()

    def pclass_field_for_attribute(self):
        """
        :return: A pyrsistent field reflecting this attribute and its type model.
        """
        return self.type_model.pclass_field_for_type(
            required=self.required,
            default=self.default,
        )



@implementer(IRangeModel)
class _IntegerRange(PClass):
    """
    ``_IntegerRange`` represents a contiguous range of integer values between
    two boundaries.

    :ivar int min: The lower bound, inclusive.
    :ivar int max: The upper bound, inclusive.
    """
    min = field(type=(int, long))
    max = field(type=(int, long))


    @classmethod
    def from_unsigned_bits(cls, n):
        """
        Create a range corresponding to that of an unsigned integer of ``n``
        bits.