repo_name
stringlengths
7
65
path
stringlengths
5
185
copies
stringlengths
1
4
size
stringlengths
4
6
content
stringlengths
977
990k
license
stringclasses
14 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.4
line_max
int64
31
999
alpha_frac
float64
0.25
0.95
ratio
float64
1.5
7.84
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
theislab/scanpy
scanpy/external/pp/_magic.py
1
7212
"""\ Denoise high-dimensional data using MAGIC """ from typing import Union, Sequence, Optional from anndata import AnnData from packaging import version from ... import logging as logg from ..._settings import settings from ..._compat import Literal from ..._utils import AnyRandom MIN_VERSION = "2.0" def magic( adata: AnnData, name_list: Union[Literal['all_genes', 'pca_only'], Sequence[str], None] = None, *, knn: int = 5, decay: Optional[float] = 1, knn_max: Optional[int] = None, t: Union[Literal['auto'], int] = 3, n_pca: Optional[int] = 100, solver: Literal['exact', 'approximate'] = 'exact', knn_dist: str = 'euclidean', random_state: AnyRandom = None, n_jobs: Optional[int] = None, verbose: bool = False, copy: Optional[bool] = None, **kwargs, ) -> Optional[AnnData]: """\ Markov Affinity-based Graph Imputation of Cells (MAGIC) API [vanDijk18]_. MAGIC is an algorithm for denoising and transcript recover of single cells applied to single-cell sequencing data. MAGIC builds a graph from the data and uses diffusion to smooth out noise and recover the data manifold. The algorithm implemented here has changed primarily in two ways compared to the algorithm described in [vanDijk18]_. Firstly, we use the adaptive kernel described in Moon et al, 2019 [Moon17]_ for improved stability. Secondly, data diffusion is applied in the PCA space, rather than the data space, for speed and memory improvements. More information and bug reports `here <https://github.com/KrishnaswamyLab/MAGIC>`__. For help, visit <https://krishnaswamylab.org/get-help>. Parameters ---------- adata An anndata file with `.raw` attribute representing raw counts. name_list Denoised genes to return. The default `'all_genes'`/`None` may require a large amount of memory if the input data is sparse. Another possibility is `'pca_only'`. knn number of nearest neighbors on which to build kernel. decay sets decay rate of kernel tails. If None, alpha decaying kernel is not used. knn_max maximum number of nearest neighbors with nonzero connection. If `None`, will be set to 3 * `knn`. t power to which the diffusion operator is powered. This sets the level of diffusion. If 'auto', t is selected according to the Procrustes disparity of the diffused data. n_pca Number of principal components to use for calculating neighborhoods. For extremely large datasets, using n_pca < 20 allows neighborhoods to be calculated in roughly log(n_samples) time. If `None`, no PCA is performed. solver Which solver to use. "exact" uses the implementation described in van Dijk et al. (2018) [vanDijk18]_. "approximate" uses a faster implementation that performs imputation in the PCA space and then projects back to the gene space. Note, the "approximate" solver may return negative values. knn_dist recommended values: 'euclidean', 'cosine', 'precomputed' Any metric from `scipy.spatial.distance` can be used distance metric for building kNN graph. If 'precomputed', `data` should be an n_samples x n_samples distance or affinity matrix. random_state Random seed. Defaults to the global `numpy` random number generator. n_jobs Number of threads to use in training. All cores are used by default. verbose If `True` or an integer `>= 2`, print status messages. If `None`, `sc.settings.verbosity` is used. copy If true, a copy of anndata is returned. If `None`, `copy` is True if `genes` is not `'all_genes'` or `'pca_only'`. `copy` may only be False if `genes` is `'all_genes'` or `'pca_only'`, as the resultant data will otherwise have different column names from the input data. kwargs Additional arguments to `magic.MAGIC`. Returns ------- If `copy` is True, AnnData object is returned. If `subset_genes` is not `all_genes`, PCA on MAGIC values of cells are stored in `adata.obsm['X_magic']` and `adata.X` is not modified. The raw counts are stored in `.raw` attribute of AnnData object. Examples -------- >>> import scanpy as sc >>> import scanpy.external as sce >>> adata = sc.datasets.paul15() >>> sc.pp.normalize_per_cell(adata) >>> sc.pp.sqrt(adata) # or sc.pp.log1p(adata) >>> adata_magic = sce.pp.magic(adata, name_list=['Mpo', 'Klf1', 'Ifitm1'], knn=5) >>> adata_magic.shape (2730, 3) >>> sce.pp.magic(adata, name_list='pca_only', knn=5) >>> adata.obsm['X_magic'].shape (2730, 100) >>> sce.pp.magic(adata, name_list='all_genes', knn=5) >>> adata.X.shape (2730, 3451) """ try: from magic import MAGIC, __version__ except ImportError: raise ImportError( 'Please install magic package via `pip install --user ' 'git+git://github.com/KrishnaswamyLab/MAGIC.git#subdirectory=python`' ) else: if not version.parse(__version__) >= version.parse(MIN_VERSION): raise ImportError( 'scanpy requires magic-impute >= ' f'v{MIN_VERSION} (detected: v{__version__}). ' 'Please update magic package via `pip install --user ' '--upgrade magic-impute`' ) start = logg.info('computing MAGIC') all_or_pca = isinstance(name_list, (str, type(None))) if all_or_pca and name_list not in {"all_genes", "pca_only", None}: raise ValueError( "Invalid string value for `name_list`: " "Only `'all_genes'` and `'pca_only'` are allowed." ) if copy is None: copy = not all_or_pca elif not all_or_pca and not copy: raise ValueError( "Can only perform MAGIC in-place with `name_list=='all_genes' or " f"`name_list=='pca_only'` (got {name_list}). Consider setting " "`copy=True`" ) adata = adata.copy() if copy else adata n_jobs = settings.n_jobs if n_jobs is None else n_jobs X_magic = MAGIC( knn=knn, decay=decay, knn_max=knn_max, t=t, n_pca=n_pca, solver=solver, knn_dist=knn_dist, random_state=random_state, n_jobs=n_jobs, verbose=verbose, **kwargs, ).fit_transform(adata, genes=name_list) logg.info( ' finished', time=start, deep=( "added\n 'X_magic', PCA on MAGIC coordinates (adata.obsm)" if name_list == "pca_only" else '' ), ) # update AnnData instance if name_list == "pca_only": # special case – update adata.obsm with smoothed values adata.obsm["X_magic"] = X_magic.X elif copy: # just return X_magic X_magic.raw = adata adata = X_magic else: # replace data with smoothed data adata.raw = adata adata.X = X_magic.X if copy: return adata
bsd-3-clause
c0e900ab368f6265814c4c0d22c1bb06
34.693069
85
0.617337
3.703133
false
false
false
false
aaugustin/websockets
src/websockets/legacy/protocol.py
1
62936
from __future__ import annotations import asyncio import codecs import collections import logging import random import ssl import struct import time import uuid import warnings from typing import ( Any, AsyncIterable, AsyncIterator, Awaitable, Callable, Deque, Dict, Iterable, List, Mapping, Optional, Tuple, Union, cast, ) from ..connection import State from ..datastructures import Headers from ..exceptions import ( ConnectionClosed, ConnectionClosedError, ConnectionClosedOK, InvalidState, PayloadTooBig, ProtocolError, ) from ..extensions import Extension from ..frames import ( OK_CLOSE_CODES, OP_BINARY, OP_CLOSE, OP_CONT, OP_PING, OP_PONG, OP_TEXT, Close, Opcode, prepare_ctrl, prepare_data, ) from ..typing import Data, LoggerLike, Subprotocol from .compatibility import loop_if_py_lt_38 from .framing import Frame __all__ = ["WebSocketCommonProtocol", "broadcast"] # In order to ensure consistency, the code always checks the current value of # WebSocketCommonProtocol.state before assigning a new value and never yields # between the check and the assignment. class WebSocketCommonProtocol(asyncio.Protocol): """ WebSocket connection. :class:`WebSocketCommonProtocol` provides APIs shared between WebSocket servers and clients. You shouldn't use it directly. Instead, use :class:`~websockets.client.WebSocketClientProtocol` or :class:`~websockets.server.WebSocketServerProtocol`. This documentation focuses on low-level details that aren't covered in the documentation of :class:`~websockets.client.WebSocketClientProtocol` and :class:`~websockets.server.WebSocketServerProtocol` for the sake of simplicity. Once the connection is open, a Ping_ frame is sent every ``ping_interval`` seconds. This serves as a keepalive. It helps keeping the connection open, especially in the presence of proxies with short timeouts on inactive connections. Set ``ping_interval`` to :obj:`None` to disable this behavior. .. _Ping: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.5.2 If the corresponding Pong_ frame isn't received within ``ping_timeout`` seconds, the connection is considered unusable and is closed with code 1011. This ensures that the remote endpoint remains responsive. Set ``ping_timeout`` to :obj:`None` to disable this behavior. .. _Pong: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.5.3 The ``close_timeout`` parameter defines a maximum wait time for completing the closing handshake and terminating the TCP connection. For legacy reasons, :meth:`close` completes in at most ``5 * close_timeout`` seconds for clients and ``4 * close_timeout`` for servers. See the discussion of :doc:`timeouts <../topics/timeouts>` for details. ``close_timeout`` needs to be a parameter of the protocol because websockets usually calls :meth:`close` implicitly upon exit: * on the client side, when :func:`~websockets.client.connect` is used as a context manager; * on the server side, when the connection handler terminates; To apply a timeout to any other API, wrap it in :func:`~asyncio.wait_for`. The ``max_size`` parameter enforces the maximum size for incoming messages in bytes. The default value is 1 MiB. If a larger message is received, :meth:`recv` will raise :exc:`~websockets.exceptions.ConnectionClosedError` and the connection will be closed with code 1009. The ``max_queue`` parameter sets the maximum length of the queue that holds incoming messages. The default value is ``32``. Messages are added to an in-memory queue when they're received; then :meth:`recv` pops from that queue. In order to prevent excessive memory consumption when messages are received faster than they can be processed, the queue must be bounded. If the queue fills up, the protocol stops processing incoming data until :meth:`recv` is called. In this situation, various receive buffers (at least in :mod:`asyncio` and in the OS) will fill up, then the TCP receive window will shrink, slowing down transmission to avoid packet loss. Since Python can use up to 4 bytes of memory to represent a single character, each connection may use up to ``4 * max_size * max_queue`` bytes of memory to store incoming messages. By default, this is 128 MiB. You may want to lower the limits, depending on your application's requirements. The ``read_limit`` argument sets the high-water limit of the buffer for incoming bytes. The low-water limit is half the high-water limit. The default value is 64 KiB, half of asyncio's default (based on the current implementation of :class:`~asyncio.StreamReader`). The ``write_limit`` argument sets the high-water limit of the buffer for outgoing bytes. The low-water limit is a quarter of the high-water limit. The default value is 64 KiB, equal to asyncio's default (based on the current implementation of ``FlowControlMixin``). See the discussion of :doc:`memory usage <../topics/memory>` for details. Args: logger: logger for this connection; defaults to ``logging.getLogger("websockets.protocol")``; see the :doc:`logging guide <../topics/logging>` for details. ping_interval: delay between keepalive pings in seconds; :obj:`None` to disable keepalive pings. ping_timeout: timeout for keepalive pings in seconds; :obj:`None` to disable timeouts. close_timeout: timeout for closing the connection in seconds; for legacy reasons, the actual timeout is 4 or 5 times larger. max_size: maximum size of incoming messages in bytes; :obj:`None` to disable the limit. max_queue: maximum number of incoming messages in receive buffer; :obj:`None` to disable the limit. read_limit: high-water mark of read buffer in bytes. write_limit: high-water mark of write buffer in bytes. """ # There are only two differences between the client-side and server-side # behavior: masking the payload and closing the underlying TCP connection. # Set is_client = True/False and side = "client"/"server" to pick a side. is_client: bool side: str = "undefined" def __init__( self, *, logger: Optional[LoggerLike] = None, ping_interval: Optional[float] = 20, ping_timeout: Optional[float] = 20, close_timeout: Optional[float] = None, max_size: Optional[int] = 2**20, max_queue: Optional[int] = 2**5, read_limit: int = 2**16, write_limit: int = 2**16, # The following arguments are kept only for backwards compatibility. host: Optional[str] = None, port: Optional[int] = None, secure: Optional[bool] = None, legacy_recv: bool = False, loop: Optional[asyncio.AbstractEventLoop] = None, timeout: Optional[float] = None, ) -> None: if legacy_recv: # pragma: no cover warnings.warn("legacy_recv is deprecated", DeprecationWarning) # Backwards compatibility: close_timeout used to be called timeout. if timeout is None: timeout = 10 else: warnings.warn("rename timeout to close_timeout", DeprecationWarning) # If both are specified, timeout is ignored. if close_timeout is None: close_timeout = timeout # Backwards compatibility: the loop parameter used to be supported. if loop is None: loop = asyncio.get_event_loop() else: warnings.warn("remove loop argument", DeprecationWarning) self.ping_interval = ping_interval self.ping_timeout = ping_timeout self.close_timeout = close_timeout self.max_size = max_size self.max_queue = max_queue self.read_limit = read_limit self.write_limit = write_limit # Unique identifier. For logs. self.id: uuid.UUID = uuid.uuid4() """Unique identifier of the connection. Useful in logs.""" # Logger or LoggerAdapter for this connection. if logger is None: logger = logging.getLogger("websockets.protocol") self.logger: LoggerLike = logging.LoggerAdapter(logger, {"websocket": self}) """Logger for this connection.""" # Track if DEBUG is enabled. Shortcut logging calls if it isn't. self.debug = logger.isEnabledFor(logging.DEBUG) self.loop = loop self._host = host self._port = port self._secure = secure self.legacy_recv = legacy_recv # Configure read buffer limits. The high-water limit is defined by # ``self.read_limit``. The ``limit`` argument controls the line length # limit and half the buffer limit of :class:`~asyncio.StreamReader`. # That's why it must be set to half of ``self.read_limit``. self.reader = asyncio.StreamReader(limit=read_limit // 2, loop=loop) # Copied from asyncio.FlowControlMixin self._paused = False self._drain_waiter: Optional[asyncio.Future[None]] = None self._drain_lock = asyncio.Lock(**loop_if_py_lt_38(loop)) # This class implements the data transfer and closing handshake, which # are shared between the client-side and the server-side. # Subclasses implement the opening handshake and, on success, execute # :meth:`connection_open` to change the state to OPEN. self.state = State.CONNECTING if self.debug: self.logger.debug("= connection is CONNECTING") # HTTP protocol parameters. self.path: str """Path of the opening handshake request.""" self.request_headers: Headers """Opening handshake request headers.""" self.response_headers: Headers """Opening handshake response headers.""" # WebSocket protocol parameters. self.extensions: List[Extension] = [] self.subprotocol: Optional[Subprotocol] = None """Subprotocol, if one was negotiated.""" # Close code and reason, set when a close frame is sent or received. self.close_rcvd: Optional[Close] = None self.close_sent: Optional[Close] = None self.close_rcvd_then_sent: Optional[bool] = None # Completed when the connection state becomes CLOSED. Translates the # :meth:`connection_lost` callback to a :class:`~asyncio.Future` # that can be awaited. (Other :class:`~asyncio.Protocol` callbacks are # translated by ``self.stream_reader``). self.connection_lost_waiter: asyncio.Future[None] = loop.create_future() # Queue of received messages. self.messages: Deque[Data] = collections.deque() self._pop_message_waiter: Optional[asyncio.Future[None]] = None self._put_message_waiter: Optional[asyncio.Future[None]] = None # Protect sending fragmented messages. self._fragmented_message_waiter: Optional[asyncio.Future[None]] = None # Mapping of ping IDs to pong waiters, in chronological order. self.pings: Dict[bytes, Tuple[asyncio.Future[float], float]] = {} self.latency: float = 0 """ Latency of the connection, in seconds. This value is updated after sending a ping frame and receiving a matching pong frame. Before the first ping, :attr:`latency` is ``0``. By default, websockets enables a :ref:`keepalive <keepalive>` mechanism that sends ping frames automatically at regular intervals. You can also send ping frames and measure latency with :meth:`ping`. """ # Task running the data transfer. self.transfer_data_task: asyncio.Task[None] # Exception that occurred during data transfer, if any. self.transfer_data_exc: Optional[BaseException] = None # Task sending keepalive pings. self.keepalive_ping_task: asyncio.Task[None] # Task closing the TCP connection. self.close_connection_task: asyncio.Task[None] # Copied from asyncio.FlowControlMixin async def _drain_helper(self) -> None: # pragma: no cover if self.connection_lost_waiter.done(): raise ConnectionResetError("Connection lost") if not self._paused: return waiter = self._drain_waiter assert waiter is None or waiter.cancelled() waiter = self.loop.create_future() self._drain_waiter = waiter await waiter # Copied from asyncio.StreamWriter async def _drain(self) -> None: # pragma: no cover if self.reader is not None: exc = self.reader.exception() if exc is not None: raise exc if self.transport is not None: if self.transport.is_closing(): # Yield to the event loop so connection_lost() may be # called. Without this, _drain_helper() would return # immediately, and code that calls # write(...); yield from drain() # in a loop would never call connection_lost(), so it # would not see an error when the socket is closed. await asyncio.sleep(0, **loop_if_py_lt_38(self.loop)) await self._drain_helper() def connection_open(self) -> None: """ Callback when the WebSocket opening handshake completes. Enter the OPEN state and start the data transfer phase. """ # 4.1. The WebSocket Connection is Established. assert self.state is State.CONNECTING self.state = State.OPEN if self.debug: self.logger.debug("= connection is OPEN") # Start the task that receives incoming WebSocket messages. self.transfer_data_task = self.loop.create_task(self.transfer_data()) # Start the task that sends pings at regular intervals. self.keepalive_ping_task = self.loop.create_task(self.keepalive_ping()) # Start the task that eventually closes the TCP connection. self.close_connection_task = self.loop.create_task(self.close_connection()) @property def host(self) -> Optional[str]: alternative = "remote_address" if self.is_client else "local_address" warnings.warn(f"use {alternative}[0] instead of host", DeprecationWarning) return self._host @property def port(self) -> Optional[int]: alternative = "remote_address" if self.is_client else "local_address" warnings.warn(f"use {alternative}[1] instead of port", DeprecationWarning) return self._port @property def secure(self) -> Optional[bool]: warnings.warn("don't use secure", DeprecationWarning) return self._secure # Public API @property def local_address(self) -> Any: """ Local address of the connection. For IPv4 connections, this is a ``(host, port)`` tuple. The format of the address depends on the address family; see :meth:`~socket.socket.getsockname`. :obj:`None` if the TCP connection isn't established yet. """ try: transport = self.transport except AttributeError: return None else: return transport.get_extra_info("sockname") @property def remote_address(self) -> Any: """ Remote address of the connection. For IPv4 connections, this is a ``(host, port)`` tuple. The format of the address depends on the address family; see :meth:`~socket.socket.getpeername`. :obj:`None` if the TCP connection isn't established yet. """ try: transport = self.transport except AttributeError: return None else: return transport.get_extra_info("peername") @property def open(self) -> bool: """ :obj:`True` when the connection is open; :obj:`False` otherwise. This attribute may be used to detect disconnections. However, this approach is discouraged per the EAFP_ principle. Instead, you should handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions. .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp """ return self.state is State.OPEN and not self.transfer_data_task.done() @property def closed(self) -> bool: """ :obj:`True` when the connection is closed; :obj:`False` otherwise. Be aware that both :attr:`open` and :attr:`closed` are :obj:`False` during the opening and closing sequences. """ return self.state is State.CLOSED @property def close_code(self) -> Optional[int]: """ WebSocket close code, defined in `section 7.1.5 of RFC 6455`_. .. _section 7.1.5 of RFC 6455: https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5 :obj:`None` if the connection isn't closed yet. """ if self.state is not State.CLOSED: return None elif self.close_rcvd is None: return 1006 else: return self.close_rcvd.code @property def close_reason(self) -> Optional[str]: """ WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_. .. _section 7.1.6 of RFC 6455: https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.6 :obj:`None` if the connection isn't closed yet. """ if self.state is not State.CLOSED: return None elif self.close_rcvd is None: return "" else: return self.close_rcvd.reason async def __aiter__(self) -> AsyncIterator[Data]: """ Iterate on incoming messages. The iterator exits normally when the connection is closed with the close code 1000 (OK) or 1001(going away) or without a close code. It raises a :exc:`~websockets.exceptions.ConnectionClosedError` exception when the connection is closed with any other code. """ try: while True: yield await self.recv() except ConnectionClosedOK: return async def recv(self) -> Data: """ Receive the next message. When the connection is closed, :meth:`recv` raises :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal connection closure and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol error or a network failure. This is how you detect the end of the message stream. Canceling :meth:`recv` is safe. There's no risk of losing the next message. The next invocation of :meth:`recv` will return it. This makes it possible to enforce a timeout by wrapping :meth:`recv` in :func:`~asyncio.wait_for`. Returns: Data: A string (:class:`str`) for a Text_ frame. A bytestring (:class:`bytes`) for a Binary_ frame. .. _Text: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6 .. _Binary: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6 Raises: ConnectionClosed: when the connection is closed. RuntimeError: if two coroutines call :meth:`recv` concurrently. """ if self._pop_message_waiter is not None: raise RuntimeError( "cannot call recv while another coroutine " "is already waiting for the next message" ) # Don't await self.ensure_open() here: # - messages could be available in the queue even if the connection # is closed; # - messages could be received before the closing frame even if the # connection is closing. # Wait until there's a message in the queue (if necessary) or the # connection is closed. while len(self.messages) <= 0: pop_message_waiter: asyncio.Future[None] = self.loop.create_future() self._pop_message_waiter = pop_message_waiter try: # If asyncio.wait() is canceled, it doesn't cancel # pop_message_waiter and self.transfer_data_task. await asyncio.wait( [pop_message_waiter, self.transfer_data_task], return_when=asyncio.FIRST_COMPLETED, **loop_if_py_lt_38(self.loop), ) finally: self._pop_message_waiter = None # If asyncio.wait(...) exited because self.transfer_data_task # completed before receiving a new message, raise a suitable # exception (or return None if legacy_recv is enabled). if not pop_message_waiter.done(): if self.legacy_recv: return None # type: ignore else: # Wait until the connection is closed to raise # ConnectionClosed with the correct code and reason. await self.ensure_open() # Pop a message from the queue. message = self.messages.popleft() # Notify transfer_data(). if self._put_message_waiter is not None: self._put_message_waiter.set_result(None) self._put_message_waiter = None return message async def send( self, message: Union[Data, Iterable[Data], AsyncIterable[Data]], ) -> None: """ Send a message. A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent as a Binary_ frame. .. _Text: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6 .. _Binary: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6 :meth:`send` also accepts an iterable or an asynchronous iterable of strings, bytestrings, or bytes-like objects to enable fragmentation_. Each item is treated as a message fragment and sent in its own frame. All items must be of the same type, or else :meth:`send` will raise a :exc:`TypeError` and the connection will be closed. .. _fragmentation: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.4 :meth:`send` rejects dict-like objects because this is often an error. (If you want to send the keys of a dict-like object as fragments, call its :meth:`~dict.keys` method and pass the result to :meth:`send`.) Canceling :meth:`send` is discouraged. Instead, you should close the connection with :meth:`close`. Indeed, there are only two situations where :meth:`send` may yield control to the event loop and then get canceled; in both cases, :meth:`close` has the same effect and is more clear: 1. The write buffer is full. If you don't want to wait until enough data is sent, your only alternative is to close the connection. :meth:`close` will likely time out then abort the TCP connection. 2. ``message`` is an asynchronous iterator that yields control. Stopping in the middle of a fragmented message will cause a protocol error and the connection will be closed. When the connection is closed, :meth:`send` raises :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal connection closure and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol error or a network failure. Args: message (Union[Data, Iterable[Data], AsyncIterable[Data]): message to send. Raises: ConnectionClosed: when the connection is closed. TypeError: if ``message`` doesn't have a supported type. """ await self.ensure_open() # While sending a fragmented message, prevent sending other messages # until all fragments are sent. while self._fragmented_message_waiter is not None: await asyncio.shield(self._fragmented_message_waiter) # Unfragmented message -- this case must be handled first because # strings and bytes-like objects are iterable. if isinstance(message, (str, bytes, bytearray, memoryview)): opcode, data = prepare_data(message) await self.write_frame(True, opcode, data) # Catch a common mistake -- passing a dict to send(). elif isinstance(message, Mapping): raise TypeError("data is a dict-like object") # Fragmented message -- regular iterator. elif isinstance(message, Iterable): # Work around https://github.com/python/mypy/issues/6227 message = cast(Iterable[Data], message) iter_message = iter(message) try: fragment = next(iter_message) except StopIteration: return opcode, data = prepare_data(fragment) self._fragmented_message_waiter = asyncio.Future() try: # First fragment. await self.write_frame(False, opcode, data) # Other fragments. for fragment in iter_message: confirm_opcode, data = prepare_data(fragment) if confirm_opcode != opcode: raise TypeError("data contains inconsistent types") await self.write_frame(False, OP_CONT, data) # Final fragment. await self.write_frame(True, OP_CONT, b"") except (Exception, asyncio.CancelledError): # We're half-way through a fragmented message and we can't # complete it. This makes the connection unusable. self.fail_connection(1011) raise finally: self._fragmented_message_waiter.set_result(None) self._fragmented_message_waiter = None # Fragmented message -- asynchronous iterator elif isinstance(message, AsyncIterable): # Implement aiter_message = aiter(message) without aiter # Work around https://github.com/python/mypy/issues/5738 aiter_message = cast( Callable[[AsyncIterable[Data]], AsyncIterator[Data]], type(message).__aiter__, )(message) try: # Implement fragment = anext(aiter_message) without anext # Work around https://github.com/python/mypy/issues/5738 fragment = await cast( Callable[[AsyncIterator[Data]], Awaitable[Data]], type(aiter_message).__anext__, )(aiter_message) except StopAsyncIteration: return opcode, data = prepare_data(fragment) self._fragmented_message_waiter = asyncio.Future() try: # First fragment. await self.write_frame(False, opcode, data) # Other fragments. # coverage reports this code as not covered, but it is # exercised by tests - changing it breaks the tests! async for fragment in aiter_message: # pragma: no cover confirm_opcode, data = prepare_data(fragment) if confirm_opcode != opcode: raise TypeError("data contains inconsistent types") await self.write_frame(False, OP_CONT, data) # Final fragment. await self.write_frame(True, OP_CONT, b"") except (Exception, asyncio.CancelledError): # We're half-way through a fragmented message and we can't # complete it. This makes the connection unusable. self.fail_connection(1011) raise finally: self._fragmented_message_waiter.set_result(None) self._fragmented_message_waiter = None else: raise TypeError("data must be str, bytes-like, or iterable") async def close(self, code: int = 1000, reason: str = "") -> None: """ Perform the closing handshake. :meth:`close` waits for the other end to complete the handshake and for the TCP connection to terminate. As a consequence, there's no need to await :meth:`wait_closed` after :meth:`close`. :meth:`close` is idempotent: it doesn't do anything once the connection is closed. Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given that errors during connection termination aren't particularly useful. Canceling :meth:`close` is discouraged. If it takes too long, you can set a shorter ``close_timeout``. If you don't want to wait, let the Python process exit, then the OS will take care of closing the TCP connection. Args: code: WebSocket close code. reason: WebSocket close reason. """ try: await asyncio.wait_for( self.write_close_frame(Close(code, reason)), self.close_timeout, **loop_if_py_lt_38(self.loop), ) except asyncio.TimeoutError: # If the close frame cannot be sent because the send buffers # are full, the closing handshake won't complete anyway. # Fail the connection to shut down faster. self.fail_connection() # If no close frame is received within the timeout, wait_for() cancels # the data transfer task and raises TimeoutError. # If close() is called multiple times concurrently and one of these # calls hits the timeout, the data transfer task will be canceled. # Other calls will receive a CancelledError here. try: # If close() is canceled during the wait, self.transfer_data_task # is canceled before the timeout elapses. await asyncio.wait_for( self.transfer_data_task, self.close_timeout, **loop_if_py_lt_38(self.loop), ) except (asyncio.TimeoutError, asyncio.CancelledError): pass # Wait for the close connection task to close the TCP connection. await asyncio.shield(self.close_connection_task) async def wait_closed(self) -> None: """ Wait until the connection is closed. This coroutine is identical to the :attr:`closed` attribute, except it can be awaited. This can make it easier to detect connection termination, regardless of its cause, in tasks that interact with the WebSocket connection. """ await asyncio.shield(self.connection_lost_waiter) async def ping(self, data: Optional[Data] = None) -> Awaitable[None]: """ Send a Ping_. .. _Ping: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.5.2 A ping may serve as a keepalive, as a check that the remote endpoint received all messages up to this point, or to measure :attr:`latency`. Canceling :meth:`ping` is discouraged. If :meth:`ping` doesn't return immediately, it means the write buffer is full. If you don't want to wait, you should close the connection. Canceling the :class:`~asyncio.Future` returned by :meth:`ping` has no effect. Args: data (Optional[Data]): payload of the ping; a string will be encoded to UTF-8; or :obj:`None` to generate a payload containing four random bytes. Returns: ~asyncio.Future[float]: A future that will be completed when the corresponding pong is received. You can ignore it if you don't intend to wait. The result of the future is the latency of the connection in seconds. :: pong_waiter = await ws.ping() # only if you want to wait for the corresponding pong latency = await pong_waiter Raises: ConnectionClosed: when the connection is closed. RuntimeError: if another ping was sent with the same data and the corresponding pong wasn't received yet. """ await self.ensure_open() if data is not None: data = prepare_ctrl(data) # Protect against duplicates if a payload is explicitly set. if data in self.pings: raise RuntimeError("already waiting for a pong with the same data") # Generate a unique random payload otherwise. while data is None or data in self.pings: data = struct.pack("!I", random.getrandbits(32)) pong_waiter = self.loop.create_future() # Resolution of time.monotonic() may be too low on Windows. ping_timestamp = time.perf_counter() self.pings[data] = (pong_waiter, ping_timestamp) await self.write_frame(True, OP_PING, data) return asyncio.shield(pong_waiter) async def pong(self, data: Data = b"") -> None: """ Send a Pong_. .. _Pong: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.5.3 An unsolicited pong may serve as a unidirectional heartbeat. Canceling :meth:`pong` is discouraged. If :meth:`pong` doesn't return immediately, it means the write buffer is full. If you don't want to wait, you should close the connection. Args: data (Data): payload of the pong; a string will be encoded to UTF-8. Raises: ConnectionClosed: when the connection is closed. """ await self.ensure_open() data = prepare_ctrl(data) await self.write_frame(True, OP_PONG, data) # Private methods - no guarantees. def connection_closed_exc(self) -> ConnectionClosed: exc: ConnectionClosed if ( self.close_rcvd is not None and self.close_rcvd.code in OK_CLOSE_CODES and self.close_sent is not None and self.close_sent.code in OK_CLOSE_CODES ): exc = ConnectionClosedOK( self.close_rcvd, self.close_sent, self.close_rcvd_then_sent, ) else: exc = ConnectionClosedError( self.close_rcvd, self.close_sent, self.close_rcvd_then_sent, ) # Chain to the exception that terminated data transfer, if any. exc.__cause__ = self.transfer_data_exc return exc async def ensure_open(self) -> None: """ Check that the WebSocket connection is open. Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't. """ # Handle cases from most common to least common for performance. if self.state is State.OPEN: # If self.transfer_data_task exited without a closing handshake, # self.close_connection_task may be closing the connection, going # straight from OPEN to CLOSED. if self.transfer_data_task.done(): await asyncio.shield(self.close_connection_task) raise self.connection_closed_exc() else: return if self.state is State.CLOSED: raise self.connection_closed_exc() if self.state is State.CLOSING: # If we started the closing handshake, wait for its completion to # get the proper close code and reason. self.close_connection_task # will complete within 4 or 5 * close_timeout after close(). The # CLOSING state also occurs when failing the connection. In that # case self.close_connection_task will complete even faster. await asyncio.shield(self.close_connection_task) raise self.connection_closed_exc() # Control may only reach this point in buggy third-party subclasses. assert self.state is State.CONNECTING raise InvalidState("WebSocket connection isn't established yet") async def transfer_data(self) -> None: """ Read incoming messages and put them in a queue. This coroutine runs in a task until the closing handshake is started. """ try: while True: message = await self.read_message() # Exit the loop when receiving a close frame. if message is None: break # Wait until there's room in the queue (if necessary). if self.max_queue is not None: while len(self.messages) >= self.max_queue: self._put_message_waiter = self.loop.create_future() try: await asyncio.shield(self._put_message_waiter) finally: self._put_message_waiter = None # Put the message in the queue. self.messages.append(message) # Notify recv(). if self._pop_message_waiter is not None: self._pop_message_waiter.set_result(None) self._pop_message_waiter = None except asyncio.CancelledError as exc: self.transfer_data_exc = exc # If fail_connection() cancels this task, avoid logging the error # twice and failing the connection again. raise except ProtocolError as exc: self.transfer_data_exc = exc self.fail_connection(1002) except (ConnectionError, TimeoutError, EOFError, ssl.SSLError) as exc: # Reading data with self.reader.readexactly may raise: # - most subclasses of ConnectionError if the TCP connection # breaks, is reset, or is aborted; # - TimeoutError if the TCP connection times out; # - IncompleteReadError, a subclass of EOFError, if fewer # bytes are available than requested; # - ssl.SSLError if the other side infringes the TLS protocol. self.transfer_data_exc = exc self.fail_connection(1006) except UnicodeDecodeError as exc: self.transfer_data_exc = exc self.fail_connection(1007) except PayloadTooBig as exc: self.transfer_data_exc = exc self.fail_connection(1009) except Exception as exc: # This shouldn't happen often because exceptions expected under # regular circumstances are handled above. If it does, consider # catching and handling more exceptions. self.logger.error("data transfer failed", exc_info=True) self.transfer_data_exc = exc self.fail_connection(1011) async def read_message(self) -> Optional[Data]: """ Read a single message from the connection. Re-assemble data frames if the message is fragmented. Return :obj:`None` when the closing handshake is started. """ frame = await self.read_data_frame(max_size=self.max_size) # A close frame was received. if frame is None: return None if frame.opcode == OP_TEXT: text = True elif frame.opcode == OP_BINARY: text = False else: # frame.opcode == OP_CONT raise ProtocolError("unexpected opcode") # Shortcut for the common case - no fragmentation if frame.fin: return frame.data.decode("utf-8") if text else frame.data # 5.4. Fragmentation fragments: List[Data] = [] max_size = self.max_size if text: decoder_factory = codecs.getincrementaldecoder("utf-8") decoder = decoder_factory(errors="strict") if max_size is None: def append(frame: Frame) -> None: nonlocal fragments fragments.append(decoder.decode(frame.data, frame.fin)) else: def append(frame: Frame) -> None: nonlocal fragments, max_size fragments.append(decoder.decode(frame.data, frame.fin)) assert isinstance(max_size, int) max_size -= len(frame.data) else: if max_size is None: def append(frame: Frame) -> None: nonlocal fragments fragments.append(frame.data) else: def append(frame: Frame) -> None: nonlocal fragments, max_size fragments.append(frame.data) assert isinstance(max_size, int) max_size -= len(frame.data) append(frame) while not frame.fin: frame = await self.read_data_frame(max_size=max_size) if frame is None: raise ProtocolError("incomplete fragmented message") if frame.opcode != OP_CONT: raise ProtocolError("unexpected opcode") append(frame) return ("" if text else b"").join(fragments) async def read_data_frame(self, max_size: Optional[int]) -> Optional[Frame]: """ Read a single data frame from the connection. Process control frames received before the next data frame. Return :obj:`None` if a close frame is encountered before any data frame. """ # 6.2. Receiving Data while True: frame = await self.read_frame(max_size) # 5.5. Control Frames if frame.opcode == OP_CLOSE: # 7.1.5. The WebSocket Connection Close Code # 7.1.6. The WebSocket Connection Close Reason self.close_rcvd = Close.parse(frame.data) if self.close_sent is not None: self.close_rcvd_then_sent = False try: # Echo the original data instead of re-serializing it with # Close.serialize() because that fails when the close frame # is empty and Close.parse() synthetizes a 1005 close code. await self.write_close_frame(self.close_rcvd, frame.data) except ConnectionClosed: # Connection closed before we could echo the close frame. pass return None elif frame.opcode == OP_PING: # Answer pings, unless connection is CLOSING. if self.state is State.OPEN: try: await self.pong(frame.data) except ConnectionClosed: # Connection closed while draining write buffer. pass elif frame.opcode == OP_PONG: if frame.data in self.pings: pong_timestamp = time.perf_counter() # Sending a pong for only the most recent ping is legal. # Acknowledge all previous pings too in that case. ping_id = None ping_ids = [] for ping_id, (pong_waiter, ping_timestamp) in self.pings.items(): ping_ids.append(ping_id) if not pong_waiter.done(): pong_waiter.set_result(pong_timestamp - ping_timestamp) if ping_id == frame.data: self.latency = pong_timestamp - ping_timestamp break else: # pragma: no cover assert False, "ping_id is in self.pings" # Remove acknowledged pings from self.pings. for ping_id in ping_ids: del self.pings[ping_id] # 5.6. Data Frames else: return frame async def read_frame(self, max_size: Optional[int]) -> Frame: """ Read a single frame from the connection. """ frame = await Frame.read( self.reader.readexactly, mask=not self.is_client, max_size=max_size, extensions=self.extensions, ) if self.debug: self.logger.debug("< %s", frame) return frame def write_frame_sync(self, fin: bool, opcode: int, data: bytes) -> None: frame = Frame(fin, Opcode(opcode), data) if self.debug: self.logger.debug("> %s", frame) frame.write( self.transport.write, mask=self.is_client, extensions=self.extensions, ) async def drain(self) -> None: try: # drain() cannot be called concurrently by multiple coroutines: # http://bugs.python.org/issue29930. Remove this lock when no # version of Python where this bugs exists is supported anymore. async with self._drain_lock: # Handle flow control automatically. await self._drain() except ConnectionError: # Terminate the connection if the socket died. self.fail_connection() # Wait until the connection is closed to raise ConnectionClosed # with the correct code and reason. await self.ensure_open() async def write_frame( self, fin: bool, opcode: int, data: bytes, *, _state: int = State.OPEN ) -> None: # Defensive assertion for protocol compliance. if self.state is not _state: # pragma: no cover raise InvalidState( f"Cannot write to a WebSocket in the {self.state.name} state" ) self.write_frame_sync(fin, opcode, data) await self.drain() async def write_close_frame( self, close: Close, data: Optional[bytes] = None ) -> None: """ Write a close frame if and only if the connection state is OPEN. This dedicated coroutine must be used for writing close frames to ensure that at most one close frame is sent on a given connection. """ # Test and set the connection state before sending the close frame to # avoid sending two frames in case of concurrent calls. if self.state is State.OPEN: # 7.1.3. The WebSocket Closing Handshake is Started self.state = State.CLOSING if self.debug: self.logger.debug("= connection is CLOSING") self.close_sent = close if self.close_rcvd is not None: self.close_rcvd_then_sent = True if data is None: data = close.serialize() # 7.1.2. Start the WebSocket Closing Handshake await self.write_frame(True, OP_CLOSE, data, _state=State.CLOSING) async def keepalive_ping(self) -> None: """ Send a Ping frame and wait for a Pong frame at regular intervals. This coroutine exits when the connection terminates and one of the following happens: - :meth:`ping` raises :exc:`ConnectionClosed`, or - :meth:`close_connection` cancels :attr:`keepalive_ping_task`. """ if self.ping_interval is None: return try: while True: await asyncio.sleep( self.ping_interval, **loop_if_py_lt_38(self.loop), ) # ping() raises CancelledError if the connection is closed, # when close_connection() cancels self.keepalive_ping_task. # ping() raises ConnectionClosed if the connection is lost, # when connection_lost() calls abort_pings(). self.logger.debug("% sending keepalive ping") pong_waiter = await self.ping() if self.ping_timeout is not None: try: await asyncio.wait_for( pong_waiter, self.ping_timeout, **loop_if_py_lt_38(self.loop), ) self.logger.debug("% received keepalive pong") except asyncio.TimeoutError: if self.debug: self.logger.debug("! timed out waiting for keepalive pong") self.fail_connection(1011, "keepalive ping timeout") break # Remove this branch when dropping support for Python < 3.8 # because CancelledError no longer inherits Exception. except asyncio.CancelledError: raise except ConnectionClosed: pass except Exception: self.logger.error("keepalive ping failed", exc_info=True) async def close_connection(self) -> None: """ 7.1.1. Close the WebSocket Connection When the opening handshake succeeds, :meth:`connection_open` starts this coroutine in a task. It waits for the data transfer phase to complete then it closes the TCP connection cleanly. When the opening handshake fails, :meth:`fail_connection` does the same. There's no data transfer phase in that case. """ try: # Wait for the data transfer phase to complete. if hasattr(self, "transfer_data_task"): try: await self.transfer_data_task except asyncio.CancelledError: pass # Cancel the keepalive ping task. if hasattr(self, "keepalive_ping_task"): self.keepalive_ping_task.cancel() # A client should wait for a TCP close from the server. if self.is_client and hasattr(self, "transfer_data_task"): if await self.wait_for_connection_lost(): # Coverage marks this line as a partially executed branch. # I suspect a bug in coverage. Ignore it for now. return # pragma: no cover if self.debug: self.logger.debug("! timed out waiting for TCP close") # Half-close the TCP connection if possible (when there's no TLS). if self.transport.can_write_eof(): if self.debug: self.logger.debug("x half-closing TCP connection") # write_eof() doesn't document which exceptions it raises. # "[Errno 107] Transport endpoint is not connected" happens # but it isn't completely clear under which circumstances. # uvloop can raise RuntimeError here. try: self.transport.write_eof() except (OSError, RuntimeError): # pragma: no cover pass if await self.wait_for_connection_lost(): # Coverage marks this line as a partially executed branch. # I suspect a bug in coverage. Ignore it for now. return # pragma: no cover if self.debug: self.logger.debug("! timed out waiting for TCP close") finally: # The try/finally ensures that the transport never remains open, # even if this coroutine is canceled (for example). await self.close_transport() async def close_transport(self) -> None: """ Close the TCP connection. """ # If connection_lost() was called, the TCP connection is closed. # However, if TLS is enabled, the transport still needs closing. # Else asyncio complains: ResourceWarning: unclosed transport. if self.connection_lost_waiter.done() and self.transport.is_closing(): return # Close the TCP connection. Buffers are flushed asynchronously. if self.debug: self.logger.debug("x closing TCP connection") self.transport.close() if await self.wait_for_connection_lost(): return if self.debug: self.logger.debug("! timed out waiting for TCP close") # Abort the TCP connection. Buffers are discarded. if self.debug: self.logger.debug("x aborting TCP connection") self.transport.abort() # connection_lost() is called quickly after aborting. # Coverage marks this line as a partially executed branch. # I suspect a bug in coverage. Ignore it for now. await self.wait_for_connection_lost() # pragma: no cover async def wait_for_connection_lost(self) -> bool: """ Wait until the TCP connection is closed or ``self.close_timeout`` elapses. Return :obj:`True` if the connection is closed and :obj:`False` otherwise. """ if not self.connection_lost_waiter.done(): try: await asyncio.wait_for( asyncio.shield(self.connection_lost_waiter), self.close_timeout, **loop_if_py_lt_38(self.loop), ) except asyncio.TimeoutError: pass # Re-check self.connection_lost_waiter.done() synchronously because # connection_lost() could run between the moment the timeout occurs # and the moment this coroutine resumes running. return self.connection_lost_waiter.done() def fail_connection(self, code: int = 1006, reason: str = "") -> None: """ 7.1.7. Fail the WebSocket Connection This requires: 1. Stopping all processing of incoming data, which means cancelling :attr:`transfer_data_task`. The close code will be 1006 unless a close frame was received earlier. 2. Sending a close frame with an appropriate code if the opening handshake succeeded and the other side is likely to process it. 3. Closing the connection. :meth:`close_connection` takes care of this once :attr:`transfer_data_task` exits after being canceled. (The specification describes these steps in the opposite order.) """ if self.debug: self.logger.debug("! failing connection with code %d", code) # Cancel transfer_data_task if the opening handshake succeeded. # cancel() is idempotent and ignored if the task is done already. if hasattr(self, "transfer_data_task"): self.transfer_data_task.cancel() # Send a close frame when the state is OPEN (a close frame was already # sent if it's CLOSING), except when failing the connection because of # an error reading from or writing to the network. # Don't send a close frame if the connection is broken. if code != 1006 and self.state is State.OPEN: close = Close(code, reason) # Write the close frame without draining the write buffer. # Keeping fail_connection() synchronous guarantees it can't # get stuck and simplifies the implementation of the callers. # Not drainig the write buffer is acceptable in this context. # This duplicates a few lines of code from write_close_frame(). self.state = State.CLOSING if self.debug: self.logger.debug("= connection is CLOSING") # If self.close_rcvd was set, the connection state would be # CLOSING. Therefore self.close_rcvd isn't set and we don't # have to set self.close_rcvd_then_sent. assert self.close_rcvd is None self.close_sent = close self.write_frame_sync(True, OP_CLOSE, close.serialize()) # Start close_connection_task if the opening handshake didn't succeed. if not hasattr(self, "close_connection_task"): self.close_connection_task = self.loop.create_task(self.close_connection()) def abort_pings(self) -> None: """ Raise ConnectionClosed in pending keepalive pings. They'll never receive a pong once the connection is closed. """ assert self.state is State.CLOSED exc = self.connection_closed_exc() for pong_waiter, _ping_timestamp in self.pings.values(): pong_waiter.set_exception(exc) # If the exception is never retrieved, it will be logged when ping # is garbage-collected. This is confusing for users. # Given that ping is done (with an exception), canceling it does # nothing, but it prevents logging the exception. pong_waiter.cancel() # asyncio.Protocol methods def connection_made(self, transport: asyncio.BaseTransport) -> None: """ Configure write buffer limits. The high-water limit is defined by ``self.write_limit``. The low-water limit currently defaults to ``self.write_limit // 4`` in :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should be all right for reasonable use cases of this library. This is the earliest point where we can get hold of the transport, which means it's the best point for configuring it. """ transport = cast(asyncio.Transport, transport) transport.set_write_buffer_limits(self.write_limit) self.transport = transport # Copied from asyncio.StreamReaderProtocol self.reader.set_transport(transport) def connection_lost(self, exc: Optional[Exception]) -> None: """ 7.1.4. The WebSocket Connection is Closed. """ self.state = State.CLOSED self.logger.debug("= connection is CLOSED") self.abort_pings() # If self.connection_lost_waiter isn't pending, that's a bug, because: # - it's set only here in connection_lost() which is called only once; # - it must never be canceled. self.connection_lost_waiter.set_result(None) if True: # pragma: no cover # Copied from asyncio.StreamReaderProtocol if self.reader is not None: if exc is None: self.reader.feed_eof() else: self.reader.set_exception(exc) # Copied from asyncio.FlowControlMixin # Wake up the writer if currently paused. if not self._paused: return waiter = self._drain_waiter if waiter is None: return self._drain_waiter = None if waiter.done(): return if exc is None: waiter.set_result(None) else: waiter.set_exception(exc) def pause_writing(self) -> None: # pragma: no cover assert not self._paused self._paused = True def resume_writing(self) -> None: # pragma: no cover assert self._paused self._paused = False waiter = self._drain_waiter if waiter is not None: self._drain_waiter = None if not waiter.done(): waiter.set_result(None) def data_received(self, data: bytes) -> None: self.reader.feed_data(data) def eof_received(self) -> None: """ Close the transport after receiving EOF. The WebSocket protocol has its own closing handshake: endpoints close the TCP or TLS connection after sending and receiving a close frame. As a consequence, they never need to write after receiving EOF, so there's no reason to keep the transport open by returning :obj:`True`. Besides, that doesn't work on TLS connections. """ self.reader.feed_eof() def broadcast(websockets: Iterable[WebSocketCommonProtocol], message: Data) -> None: """ Broadcast a message to several WebSocket connections. A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent as a Binary_ frame. .. _Text: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6 .. _Binary: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6 :func:`broadcast` pushes the message synchronously to all connections even if their write buffers are overflowing. There's no backpressure. :func:`broadcast` skips silently connections that aren't open in order to avoid errors on connections where the closing handshake is in progress. If you broadcast messages faster than a connection can handle them, messages will pile up in its write buffer until the connection times out. Keep low values for ``ping_interval`` and ``ping_timeout`` to prevent excessive memory usage by slow connections when you use :func:`broadcast`. Unlike :meth:`~websockets.server.WebSocketServerProtocol.send`, :func:`broadcast` doesn't support sending fragmented messages. Indeed, fragmentation is useful for sending large messages without buffering them in memory, while :func:`broadcast` buffers one copy per connection as fast as possible. Args: websockets (Iterable[WebSocketCommonProtocol]): WebSocket connections to which the message will be sent. message (Data): message to send. Raises: RuntimeError: if a connection is busy sending a fragmented message. TypeError: if ``message`` doesn't have a supported type. """ if not isinstance(message, (str, bytes, bytearray, memoryview)): raise TypeError("data must be str or bytes-like") opcode, data = prepare_data(message) for websocket in websockets: if websocket.state is not State.OPEN: continue if websocket._fragmented_message_waiter is not None: raise RuntimeError("busy sending a fragmented message") websocket.write_frame_sync(True, opcode, data)
bsd-3-clause
a366d58a8307191d5a3d2e1433d9536d
37.65602
87
0.602682
4.520003
false
false
false
false
foauth/foauth.org
services/taskrabbit.py
2
1120
from oauthlib.oauth2.draft25 import utils import foauth.providers class Taskrabbit(foauth.providers.OAuth2): # General info about the provider provider_url = 'https://www.taskrabbit.com/' docs_url = 'http://taskrabbit.github.com/' category = 'Tasks' # URLs to interact with the API # These are temporary until Taskrabbit approves foauth for production use authorize_url = 'https://taskrabbitdev.com/api/authorize' access_token_url = 'https://taskrabbitdev.com/api/oauth/token' api_domain = 'taskrabbitdev.com' available_permissions = [ (None, 'read and write to your tasks'), ] def get_authorize_params(self, *args, **kwargs): params = super(Taskrabbit, self).get_authorize_params(*args, **kwargs) # Prevent the request for credit card information params['card'] = 'false' return params def bearer_type(self, token, r): r.headers['Authorization'] = 'OAuth %s' % token return r def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/v1/account') return r.json()[u'id']
bsd-3-clause
3871a9e01064811179f9bfe33a65d5ae
31
78
0.655357
3.578275
false
false
false
false
foauth/foauth.org
services/dwolla.py
2
1693
from oauthlib.common import add_params_to_uri import foauth.providers class Dwolla(foauth.providers.OAuth2): # General info about the provider provider_url = 'https://dwolla.com/' docs_url = 'http://developers.dwolla.com/dev/docs' category = 'Money' # Required by Dwolla's ToS disclaimer = "This application is not directly supported by Dwolla Corp. Dwolla Corp. makes no claims about this application. This application is not endorsed or certified by Dwolla Corp." # URLs to interact with the API authorize_url = 'https://www.dwolla.com/oauth/v2/authenticate' access_token_url = 'https://www.dwolla.com/oauth/v2/token' api_domain = 'www.dwolla.com' available_permissions = [ (None, 'access your account details'), ('Contacts', 'read your contacts'), ('Transactions', 'read your transaction history'), ('Balance', 'read your current balance'), ('Send', 'send money to others'), ('Request', 'request money from others'), ('Funding', 'view your bank accounts and other funding sources'), ] def bearer_type(self, token, r): r.url = add_params_to_uri(r.url, [((u'oauth_token', token))]) return r def get_authorize_params(self, redirect_uri, scopes): # Always request account info, in order to get the user ID scopes.append('AccountInfoFull') return super(Dwolla, self).get_authorize_params(redirect_uri, scopes) def get_scope_string(self, scopes): return '|'.join(scopes) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/oauth/rest/users/') return unicode(r.json()[u'Response'][u'Id'])
bsd-3-clause
720d9e2b2fa5187e75efc46629038cbb
38.372093
193
0.65505
3.564211
false
false
false
false
scikit-rf/scikit-rf
skrf/vi/sa.py
1
4343
""" .. module:: skrf.vi.sa ++++++++++++++++++++++++++++++++++++++++++++++++++++ Spectrum Analyzers (:mod:`skrf.vi.sa`) ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. autosummary:: :toctree: generated/ HP8500 """ import numpy as npy from ..frequency import Frequency from ..network import Network from .. import mathFunctions as mf from . ivihack import Driver class HP8500(Driver): """ HP8500's series Spectrum Analyzers Examples ----------- Get trace, and store in a Network object >>> from skrf.vi.sa import HP >>> my_sa = HP() # default address is 18 >>> trace = my_sa.get_ntwk() Activate single sweep mode, get a trace, return to continuous sweep >>> my_sa.single_sweep() >>> my_sa.sweep() >>> trace_a = my_sa.trace_a >>> my_sa.cont_sweep() """ def __init__(self, address=18, *args, **kwargs): r""" Initializer Parameters -------------- address : int GPIB address \*args, \*\*kwargs : passed to ``ivi.Driver.__init__`` """ Driver.__init__(self,'GPIB::'+str(address),*args,**kwargs) @property def frequency(self): """ """ f = Frequency(self.f_start, self.f_stop, len(self.trace_a),'hz') f.unit = 'ghz' return f def get_ntwk(self, trace='a', goto_local=False, *args, **kwargs): r""" Get a trace and return the data in a :class:`~skrf.network.Network` format This will save instrument stage to reg 1, activate single sweep mode, sweep, save data, then recal state from reg 1. Returning the data in a the form of a :class:`~skrf.network.Network` allows all the plotting methods and IO functions of that class to be used. Not all the methods of Network make sense for this type of data (scalar), but we assume the user knows this. Parameters ------------ trace : ['a', 'b'] save trace 'a' or trace 'b' goto_local : Boolean Go to local mode after taking a sweep \*args,\*\*kwargs : passed to :func:`~skrf.network.Network.__init__` """ trace = trace.lower() if trace not in ['a','b']: raise ValueError('\'trace\' should be \'a\' or \'b\'') self.save_state() self.single_sweep() self.sweep() #TODO: ask if magnitude is in linear (LN) or log (LG) mode if trace== 'a': s = self.trace_a elif trace == 'b': s = self.trace_b self.recall_state() s = mf.db_2_magnitude(npy.array(s)) freq = self.frequency n = Network(s=s, frequency=freq, z0=1, *args, **kwargs) if goto_local: self.goto_local() return n @property def f_start(self): """ starting frequency """ return float(self.ask('fa?')) @property def f_stop(self): """ stopping frequency """ return float(self.ask('fb?')) @property def trace_a(self): """ trace 'a' """ return self.ask_for_values("tra?") @property def trace_b(self): """ trace 'b' """ return self.ask_for_values("trb?") def sweep(self): """ trigger a sweep, return when done """ self.write('ts') return self.ask('done?') def single_sweep(self): """ Activate single sweep mode """ self.write('sngls') def cont_sweep(self): """ Activate continuous sweep mode """ self.write('conts') def goto_local(self): """ Switches from remote to local control """ pass#visa.vpp43.gpib_control_ren(self.vi,0) def save_state(self, reg_n=1): """ Save current state to a given register """ self.write('saves %i'%reg_n) def recall_state(self, reg_n=1): """ Recall current state to a given register """ self.write('rcls %i'%reg_n)
bsd-3-clause
629cbd11f28071e19c6158eebb5d9674
23.104046
82
0.487221
3.944596
false
false
false
false
scikit-rf/scikit-rf
skrf_qtapps/data_grabber.py
1
2061
from skrf_qtapps.skrf_qtwidgets import NetworkListWidget, NetworkPlotWidget, qt, widgets from qtpy import QtWidgets, QtCore class DataGrabber(QtWidgets.QWidget): def __init__(self, parent=None): super().__init__(parent) # --- Setup UI --- # self.resize(825, 575) self.setWindowTitle("Scikit-RF Data Grabber") self.verticalLayout_main = QtWidgets.QVBoxLayout(self) self.vna_controller = widgets.VnaSelector() self.verticalLayout_main.addWidget(self.vna_controller) self.splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal, self) size_policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) size_policy.setVerticalStretch(1) self.splitter.setSizePolicy(size_policy) self.measurements_widget = QtWidgets.QWidget(self.splitter) self.measurements_widget_layout = QtWidgets.QVBoxLayout(self.measurements_widget) self.measurements_widget_layout.setContentsMargins(0, 0, 0, 0) self.listWidget_measurements = NetworkListWidget(self.measurements_widget) self.measurement_buttons = self.listWidget_measurements.get_input_buttons() self.measurements_widget_layout.addWidget(self.measurement_buttons) self.measurements_widget_layout.addWidget(self.listWidget_measurements) self.save_buttons = self.listWidget_measurements.get_save_buttons() self.measurements_widget_layout.addWidget(self.save_buttons) self.ntwk_plot = NetworkPlotWidget(self.splitter) self.ntwk_plot.corrected_data_enabled = False self.verticalLayout_main.addWidget(self.splitter) self.splitter.setStretchFactor(1, 100) # important that this goes at the end # --- END SETUP UI --- # self.listWidget_measurements.ntwk_plot = self.ntwk_plot self.listWidget_measurements.get_analyzer = self.vna_controller.get_analyzer def main(): qt.single_widget_application(DataGrabber, appid="DataGrabber") if __name__ == "__main__": main()
bsd-3-clause
fbbbb0da3fbea33894d1b5f2c6d098ef
41.958333
109
0.712761
3.948276
false
false
false
false
scikit-rf/scikit-rf
skrf/vectorFitting.py
1
87576
import os import logging import warnings from timeit import default_timer as timer from typing import Any, Tuple, TYPE_CHECKING import numpy as np try: from . import plotting # will perform the correct setup for matplotlib before it is called below import matplotlib.pyplot as mplt from matplotlib.ticker import EngFormatter except ImportError: pass from .util import axes_kwarg, Axes # imports for type hinting if TYPE_CHECKING: from .network import Network class VectorFitting: """ This class provides a Python implementation of the Vector Fitting algorithm and various functions for the fit analysis, passivity evaluation and enforcement, and export of SPICE equivalent circuits. Parameters ---------- network : :class:`skrf.network.Network` Network instance of the :math:`N`-port holding the frequency responses to be fitted, for example a scattering, impedance or admittance matrix. Examples -------- Load the `Network`, create a `VectorFitting` instance, perform the fit with a given number of real and complex-conjugate starting poles: >>> nw_3port = skrf.Network('my3port.s3p') >>> vf = skrf.VectorFitting(nw_3port) >>> vf.vector_fit(n_poles_real=1, n_poles_cmplx=4) Notes ----- The fitting code is based on the original algorithm [#Gustavsen_vectfit]_ and on two improvements for relaxed pole relocation [#Gustavsen_relaxed]_ and efficient (fast) solving [#Deschrijver_fast]_. See also the Vector Fitting website [#vectfit_website]_ for further information and download of the papers listed below. A Matlab implementation is also available there for reference. References ---------- .. [#Gustavsen_vectfit] B. Gustavsen, A. Semlyen, "Rational Approximation of Frequency Domain Responses by Vector Fitting", IEEE Transactions on Power Delivery, vol. 14, no. 3, pp. 1052-1061, July 1999, DOI: https://doi.org/10.1109/61.772353 .. [#Gustavsen_relaxed] B. Gustavsen, "Improving the Pole Relocating Properties of Vector Fitting", IEEE Transactions on Power Delivery, vol. 21, no. 3, pp. 1587-1592, July 2006, DOI: https://doi.org/10.1109/TPWRD.2005.860281 .. [#Deschrijver_fast] D. Deschrijver, M. Mrozowski, T. Dhaene, D. De Zutter, "Marcomodeling of Multiport Systems Using a Fast Implementation of the Vector Fitting Method", IEEE Microwave and Wireless Components Letters, vol. 18, no. 6, pp. 383-385, June 2008, DOI: https://doi.org/10.1109/LMWC.2008.922585 .. [#vectfit_website] Vector Fitting website: https://www.sintef.no/projectweb/vectorfitting/ """ def __init__(self, network: 'Network'): self.network = network """ Instance variable holding the Network to be fitted. This is the Network passed during initialization, which may be changed or set to *None*. """ self.poles = None """ Instance variable holding the list of fitted poles. Will be initialized by :func:`vector_fit`. """ self.residues = None """ Instance variable holding the list of fitted residues. Will be initialized by :func:`vector_fit`. """ self.proportional_coeff = None """ Instance variable holding the list of fitted proportional coefficients. Will be initialized by :func:`vector_fit`. """ self.constant_coeff = None """ Instance variable holding the list of fitted constants. Will be initialized by :func:`vector_fit`. """ self.max_iterations = 100 """ Instance variable specifying the maximum number of iterations for the fitting process and for the passivity enforcement. To be changed by the user before calling :func:`vector_fit` and/or :func:`passivity_enforce`. """ self.max_tol = 1e-6 """ Instance variable specifying the convergence criterion in terms of relative tolerance. To be changed by the user before calling :func:`vector_fit`. """ self.wall_clock_time = 0 """ Instance variable holding the wall-clock time (in seconds) consumed by the most recent fitting process with :func:`vector_fit`. Subsequent calls of :func:`vector_fit` will overwrite this value. """ self.d_res_history = [] self.delta_max_history = [] self.history_max_sigma = [] self.history_cond_A = [] # legacy getter and setter methods to support deprecated 'zeros' attribute (now correctly called 'residues') @property def zeros(self): """ **Deprecated**; Please use :attr:`residues` instead. """ warnings.warn('Attribute `zeros` is deprecated and will be removed in a future version. Please use the new ' 'attribute `residues` instead.', DeprecationWarning, stacklevel=2) return self.residues @zeros.setter def zeros(self, value): warnings.warn('Attribute `zeros` is deprecated and will be removed in a future version. Please use the new ' 'attribute `residues` instead.', DeprecationWarning, stacklevel=2) self.residues = value def vector_fit(self, n_poles_real: int = 2, n_poles_cmplx: int = 2, init_pole_spacing: str = 'lin', parameter_type: str = 's', fit_constant: bool = True, fit_proportional: bool = False) -> None: """ Main work routine performing the vector fit. The results will be stored in the class variables :attr:`poles`, :attr:`residues`, :attr:`proportional_coeff` and :attr:`constant_coeff`. Parameters ---------- n_poles_real : int, optional Number of initial real poles. See notes. n_poles_cmplx : int, optional Number of initial complex conjugate poles. See notes. init_pole_spacing : str, optional Type of initial pole spacing across the frequency interval of the S-matrix. Either linear (lin) or logarithmic (log). parameter_type : str, optional Representation type of the frequency responses to be fitted. Either *scattering* (:attr:`s` or :attr:`S`), *impedance* (:attr:`z` or :attr:`Z`) or *admittance* (:attr:`y` or :attr:`Y`). As scikit-rf can currently only read S parameters from a Touchstone file, the fit should also be performed on the original S parameters. Otherwise, scikit-rf will convert the responses from S to Z or Y, which might work for the fit but can cause other issues. fit_constant : bool, optional Include a constant term **d** in the fit. fit_proportional : bool, optional Include a proportional term **e** in the fit. Returns ------- None No return value. Notes ----- The required number of real or complex conjugate starting poles depends on the behaviour of the frequency responses. To fit a smooth response such as a low-pass characteristic, 1-3 real poles and no complex conjugate poles is usually sufficient. If resonances or other types of peaks are present in some or all of the responses, a similar number of complex conjugate poles is required. Be careful not to use too many poles, as excessive poles will not only increase the computation workload during the fitting and the subsequent use of the model, but they can also introduce unwanted resonances at frequencies well outside the fit interval. """ timer_start = timer() # create initial poles and space them across the frequencies in the provided Touchstone file # use normalized frequencies during the iterations (seems to be more stable during least-squares fit) norm = np.average(self.network.f) freqs_norm = np.array(self.network.f) / norm fmin = np.amin(freqs_norm) fmax = np.amax(freqs_norm) # poles cannot be at f=0; hence, f_min for starting pole must be greater than 0 if fmin == 0.0: # random choice: use 1/1000 of first non-zero frequency fmin = freqs_norm[1] / 1000 if init_pole_spacing == 'log': pole_freqs_real = np.geomspace(fmin, fmax, n_poles_real) pole_freqs_cmplx = np.geomspace(fmin, fmax, n_poles_cmplx) elif init_pole_spacing == 'lin': pole_freqs_real = np.linspace(fmin, fmax, n_poles_real) pole_freqs_cmplx = np.linspace(fmin, fmax, n_poles_cmplx) else: warnings.warn('Invalid choice of initial pole spacing; proceeding with linear spacing.', UserWarning, stacklevel=2) pole_freqs_real = np.linspace(fmin, fmax, n_poles_real) pole_freqs_cmplx = np.linspace(fmin, fmax, n_poles_cmplx) # init poles array of correct length poles = np.zeros(n_poles_real + n_poles_cmplx, dtype=complex) # add real poles for i, f in enumerate(pole_freqs_real): omega = 2 * np.pi * f poles[i] = -1 * omega # add complex-conjugate poles (store only positive imaginary parts) i_offset = len(pole_freqs_real) for i, f in enumerate(pole_freqs_cmplx): omega = 2 * np.pi * f poles[i_offset + i] = (-0.01 + 1j) * omega # save initial poles (un-normalize first) initial_poles = poles * norm max_singular = 1 logging.info('### Starting pole relocation process.\n') n_responses = self.network.nports ** 2 n_freqs = len(freqs_norm) n_samples = n_responses * n_freqs # select network representation type if parameter_type.lower() == 's': nw_responses = self.network.s elif parameter_type.lower() == 'z': nw_responses = self.network.z elif parameter_type.lower() == 'y': nw_responses = self.network.y else: warnings.warn('Invalid choice of matrix parameter type (S, Z, or Y); proceeding with scattering ' 'representation.', UserWarning, stacklevel=2) nw_responses = self.network.s # stack frequency responses as a single vector # stacking order (row-major): # s11, s12, s13, ..., s21, s22, s23, ... freq_responses = [] for i in range(self.network.nports): for j in range(self.network.nports): freq_responses.append(nw_responses[:, i, j]) freq_responses = np.array(freq_responses) # responses will be weighted according to their norm; # alternative: equal weights with weight_response = 1.0 # or anti-proportional weights with weight_response = 1 / np.linalg.norm(freq_response) weights_responses = np.linalg.norm(freq_responses, axis=1) #weights_responses = np.ones(self.network.nports ** 2) # weight of extra equation to avoid trivial solution weight_extra = np.linalg.norm(weights_responses[:, None] * freq_responses) / n_samples # weights w are applied directly to the samples, which get squared during least-squares fitting; hence sqrt(w) weights_responses = np.sqrt(weights_responses) weight_extra = np.sqrt(weight_extra) # ITERATIVE FITTING OF POLES to the provided frequency responses # initial set of poles will be replaced with new poles after every iteration iterations = self.max_iterations self.d_res_history = [] self.delta_max_history = [] self.history_cond_A = [] converged = False omega = 2 * np.pi * freqs_norm s = 1j * omega while iterations > 0: logging.info(f'Iteration {self.max_iterations - iterations + 1}') # count number of rows and columns in final coefficient matrix to solve for (c_res, d_res) # (ratio #real/#complex poles might change during iterations) # We need two columns for complex poles and one column for real poles in A matrix. # poles.imag != 0 is True(1) for complex poles, False (0) for real poles. # Adding one to each element gives 2 columns for complex and 1 column for real poles. n_cols_unused = np.sum((poles.imag != 0) + 1) n_cols_used = n_cols_unused n_cols_used += 1 idx_constant = [] idx_proportional = [] if fit_constant: idx_constant = [n_cols_unused] n_cols_unused += 1 if fit_proportional: idx_proportional = [n_cols_unused] n_cols_unused += 1 real_mask = poles.imag == 0 # list of indices in 'poles' with real values idx_poles_real = np.nonzero(real_mask)[0] # list of indices in 'poles' with complex values idx_poles_complex = np.nonzero(~real_mask)[0] # positions (columns) of coefficients for real and complex-conjugate terms in the rows of A determine the # respective positions of the calculated residues in the results vector. # to have them ordered properly for the subsequent assembly of the test matrix H for eigenvalue extraction, # place real poles first, then complex-conjugate poles with their respective real and imaginary parts: # [r1', r2', ..., (r3', r3''), (r4', r4''), ...] n_real = len(idx_poles_real) n_cmplx = len(idx_poles_complex) idx_res_real = np.arange(n_real) idx_res_complex_re = n_real + 2 * np.arange(n_cmplx) idx_res_complex_im = idx_res_complex_re + 1 # complex coefficient matrix of shape [N_responses, N_freqs, n_cols_unused + n_cols_used] # layout of each row: # [pole1, pole2, ..., (constant), (proportional), pole1, pole2, ..., constant] A = np.empty((n_responses, n_freqs, n_cols_unused + n_cols_used), dtype=complex) # calculate coefficients for real and complex residues in the solution vector # # real pole-residue term (r = r', p = p'): # fractional term is r' / (s - p') # coefficient for r' is 1 / (s - p') coeff_real = 1 / (s[:, None] - poles[None, idx_poles_real]) # complex-conjugate pole-residue pair (r = r' + j r'', p = p' + j p''): # fractional term is r / (s - p) + conj(r) / (s - conj(p)) # = [1 / (s - p) + 1 / (s - conj(p))] * r' + [1j / (s - p) - 1j / (s - conj(p))] * r'' # coefficient for r' is 1 / (s - p) + 1 / (s - conj(p)) # coefficient for r'' is 1j / (s - p) - 1j / (s - conj(p)) coeff_complex_re = (1 / (s[:, None] - poles[None, idx_poles_complex]) + 1 / (s[:, None] - np.conj(poles[None, idx_poles_complex]))) coeff_complex_im = (1j / (s[:, None] - poles[None, idx_poles_complex]) - 1j / (s[:, None] - np.conj(poles[None, idx_poles_complex]))) # part 1: first sum of rational functions (variable c) A[:, :, idx_res_real] = coeff_real A[:, :, idx_res_complex_re] = coeff_complex_re A[:, :, idx_res_complex_im] = coeff_complex_im # part 2: constant (variable d) and proportional term (variable e) A[:, :, idx_constant] = 1 A[:, :, idx_proportional] = s[:, None] # part 3: second sum of rational functions multiplied with frequency response (variable c_res) A[:, :, n_cols_unused + idx_res_real] = -1 * freq_responses[:, :, None] * coeff_real A[:, :, n_cols_unused + idx_res_complex_re] = -1 * freq_responses[:, :, None] * coeff_complex_re A[:, :, n_cols_unused + idx_res_complex_im] = -1 * freq_responses[:, :, None] * coeff_complex_im # part 4: constant (variable d_res) A[:, :, -1] = -1 * freq_responses # QR decomposition #R = np.linalg.qr(np.hstack((A.real, A.imag)), 'r') # direct QR of stacked matrices for linalg.qr() only works with numpy>=1.22.0 # workaround for old numpy: R = np.empty((n_responses, n_cols_unused + n_cols_used, n_cols_unused + n_cols_used)) A_ri = np.hstack((A.real, A.imag)) for i in range(n_responses): R[i] = np.linalg.qr(A_ri[i], mode='r') # only R22 is required to solve for c_res and d_res R22 = R[:, n_cols_unused:, n_cols_unused:] # weighting R22 = weights_responses[:, None, None] * R22 # assemble compressed coefficient matrix A_fast by row-stacking individual upper triangular matrices R22 A_fast = np.empty((n_responses * n_cols_used + 1, n_cols_used)) A_fast[:-1, :] = R22.reshape((n_responses * n_cols_used, n_cols_used)) # extra equation to avoid trivial solution A_fast[-1, idx_res_real] = np.sum(coeff_real.real, axis=0) A_fast[-1, idx_res_complex_re] = np.sum(coeff_complex_re.real, axis=0) A_fast[-1, idx_res_complex_im] = np.sum(coeff_complex_im.real, axis=0) A_fast[-1, -1] = n_freqs # weighting A_fast[-1, :] = weight_extra * A_fast[-1, :] # right hand side vector (weighted) b = np.zeros(n_responses * n_cols_used + 1) b[-1] = weight_extra * n_samples cond_A = np.linalg.cond(A_fast) logging.info(f'Condition number of coeff. matrix A = {int(cond_A)}') self.history_cond_A.append(cond_A) # solve least squares for real parts x, residuals, rank, singular_vals = np.linalg.lstsq(A_fast, b, rcond=None) # assemble individual result vectors from single LS result x c_res = x[:-1] d_res = x[-1] # check if d_res is suited for zeros calculation tol_res = 1e-8 if np.abs(d_res) < tol_res: # d_res is too small, discard solution and proceed the |d_res| = tol_res d_res = tol_res * (d_res / np.abs(d_res)) warnings.warn('Replacing d_res solution as it was too small. This is not a good sign and probably ' 'means that more starting poles are required', RuntimeWarning, stacklevel=2) self.d_res_history.append(d_res) logging.info(f'd_res = {d_res}') # build test matrix H, which will hold the new poles as eigenvalues H = np.zeros((len(c_res), len(c_res))) poles_real = poles[np.nonzero(real_mask)] poles_cplx = poles[np.nonzero(~real_mask)] H[idx_res_real, idx_res_real] = poles_real.real H[idx_res_real] -= c_res / d_res H[idx_res_complex_re, idx_res_complex_re] = poles_cplx.real H[idx_res_complex_re, idx_res_complex_im] = poles_cplx.imag H[idx_res_complex_im, idx_res_complex_re] = -1 * poles_cplx.imag H[idx_res_complex_im, idx_res_complex_im] = poles_cplx.real H[idx_res_complex_re] -= 2 * c_res / d_res poles_new = np.linalg.eigvals(H) # replace poles for next iteration # complex poles need to come in complex conjugate pairs; append only the positive part poles = poles_new[np.nonzero(poles_new.imag >= 0)] # flip real part of unstable poles (real part needs to be negative for stability) poles.real = -1 * np.abs(poles.real) # calculate relative changes in the singular values; stop iteration loop once poles have converged new_max_singular = np.amax(singular_vals) delta_max = np.abs(1 - new_max_singular / max_singular) self.delta_max_history.append(delta_max) logging.info(f'Max. relative change in residues = {delta_max}\n') max_singular = new_max_singular stop = False if delta_max < self.max_tol: if converged: # is really converged, finish logging.info('Pole relocation process converged after {} iterations.'.format( self.max_iterations - iterations + 1)) stop = True else: # might be converged, but do one last run to be sure converged = True else: if converged: # is not really converged, continue converged = False iterations -= 1 if iterations == 0: max_cond = np.amax(self.history_cond_A) if max_cond > 1e10: msg_illcond = 'Hint: the linear system was ill-conditioned (max. condition number = {}). ' \ 'This often means that more poles are required.'.format(max_cond) else: msg_illcond = '' if converged and stop is False: warnings.warn('Vector Fitting: The pole relocation process barely converged to tolerance. ' 'It took the max. number of iterations (N_max = {}). ' 'The results might not have converged properly. '.format(self.max_iterations) + msg_illcond, RuntimeWarning, stacklevel=2) else: warnings.warn('Vector Fitting: The pole relocation process stopped after reaching the ' 'maximum number of iterations (N_max = {}). ' 'The results did not converge properly. '.format(self.max_iterations) + msg_illcond, RuntimeWarning, stacklevel=2) if stop: iterations = 0 # ITERATIONS DONE logging.info('Initial poles before relocation:') logging.info(initial_poles) logging.info('Final poles:') logging.info(poles * norm) logging.info('\n### Starting residues calculation process.\n') # finally, solve for the residues with the previously calculated poles # We need two columns for complex poles and one column for real poles in A matrix. # poles.imag != 0 is True(1) for complex poles, False (0) for real poles. # Adding one to each element gives 2 columns for complex and 1 column for real poles. n_cols = np.sum((poles.imag != 0) + 1) idx_constant = [] idx_proportional = [] if fit_constant: idx_constant = [n_cols] n_cols += 1 if fit_proportional: idx_proportional = [n_cols] n_cols += 1 # list of indices in 'poles' with real and with complex values real_mask = poles.imag == 0 idx_poles_real = np.nonzero(real_mask)[0] idx_poles_complex = np.nonzero(~real_mask)[0] # find and save indices of real and complex poles in the poles list i = 0 idx_res_real = [] idx_res_complex_re = [] idx_res_complex_im = [] for pole in poles: if pole.imag == 0: idx_res_real.append(i) i += 1 else: idx_res_complex_re.append(i) idx_res_complex_im.append(i + 1) i += 2 # complex coefficient matrix of shape [N_freqs, n_cols] # layout of each row: # [pole1, pole2, ..., (constant), (proportional)] A = np.empty((n_freqs, n_cols), dtype=complex) # calculate coefficients for real and complex residues in the solution vector # # real pole-residue term (r = r', p = p'): # fractional term is r' / (s - p') # coefficient for r' is 1 / (s - p') coeff_real = 1 / (s[:, None] - poles[None, idx_poles_real]) # complex-conjugate pole-residue pair (r = r' + j r'', p = p' + j p''): # fractional term is r / (s - p) + conj(r) / (s - conj(p)) # = [1 / (s - p) + 1 / (s - conj(p))] * r' + [1j / (s - p) - 1j / (s - conj(p))] * r'' # coefficient for r' is 1 / (s - p) + 1 / (s - conj(p)) # coefficient for r'' is 1j / (s - p) - 1j / (s - conj(p)) coeff_complex_re = (1 / (s[:, None] - poles[None, idx_poles_complex]) + 1 / (s[:, None] - np.conj(poles[None, idx_poles_complex]))) coeff_complex_im = (1j / (s[:, None] - poles[None, idx_poles_complex]) - 1j / (s[:, None] - np.conj(poles[None, idx_poles_complex]))) # part 1: first sum of rational functions (variable c) A[:, idx_res_real] = coeff_real A[:, idx_res_complex_re] = coeff_complex_re A[:, idx_res_complex_im] = coeff_complex_im # part 2: constant (variable d) and proportional term (variable e) A[:, idx_constant] = 1 A[:, idx_proportional] = s[:, None] logging.info(f'Condition number of coefficient matrix = {int(np.linalg.cond(A))}') # solve least squares and obtain results as stack of real part vector and imaginary part vector x, residuals, rank, singular_vals = np.linalg.lstsq(np.vstack((A.real, A.imag)), np.hstack((freq_responses.real, freq_responses.imag)).transpose(), rcond=None) # align poles and residues arrays to get matching pole-residue pairs poles = np.concatenate((poles[idx_poles_real], poles[idx_poles_complex])) residues = np.concatenate((x[idx_res_real], x[idx_res_complex_re] + 1j * x[idx_res_complex_im]), axis=0).transpose() if fit_constant: constant_coeff = x[idx_constant][0] else: constant_coeff = np.zeros(n_responses) if fit_proportional: proportional_coeff = x[idx_proportional][0] else: proportional_coeff = np.zeros(n_responses) # save poles, residues, d, e in actual frequencies (un-normalized) self.poles = poles * norm self.residues = np.array(residues) * norm self.constant_coeff = np.array(constant_coeff) self.proportional_coeff = np.array(proportional_coeff) / norm timer_stop = timer() self.wall_clock_time = timer_stop - timer_start logging.info(f'\n### Vector fitting finished in {self.wall_clock_time} seconds.\n') # raise a warning if the fitted Network is passive but the fit is not (only without proportional_coeff): if self.network.is_passive() and not fit_proportional: if not self.is_passive(): warnings.warn('The fitted network is passive, but the vector fit is not passive. Consider running ' '`passivity_enforce()` to enforce passivity before using this model.', UserWarning, stacklevel=2) def get_rms_error(self, i=-1, j=-1, parameter_type: str = 's'): r""" Returns the root-mean-square (rms) error magnitude of the fit, i.e. :math:`\sqrt{ \mathrm{mean}(|S - S_\mathrm{fit} |^2) }`, either for an individual response :math:`S_{i+1,j+1}` or for larger slices of the network. Parameters ---------- i : int, optional Row indices of the responses to be evaluated. Either a single row selected by an integer :math:`i \in [0, N_\mathrm{ports}-1]`, or multiple rows selected by a list of integers, or all rows selected by :math:`i = -1` (*default*). j : int, optional Column indices of the responses to be evaluated. Either a single column selected by an integer :math:`j \in [0, N_\mathrm{ports}-1]`, or multiple columns selected by a list of integers, or all columns selected by :math:`j = -1` (*default*). parameter_type: str, optional Representation type of the fitted frequency responses. Either *scattering* (:attr:`s` or :attr:`S`), *impedance* (:attr:`z` or :attr:`Z`) or *admittance* (:attr:`y` or :attr:`Y`). Returns ------- rms_error : ndarray The rms error magnitude between the vector fitted model and the original network data. Raises ------ ValueError If the specified parameter representation type is not :attr:`s`, :attr:`z`, nor :attr:`y`. """ if i == -1: list_i = range(self.network.nports) elif isinstance(i, int): list_i = [i] else: list_i = i if j == -1: list_j = range(self.network.nports) elif isinstance(j, int): list_j = [j] else: list_j = j if parameter_type.lower() == 's': nw_responses = self.network.s elif parameter_type.lower() == 'z': nw_responses = self.network.z elif parameter_type.lower() == 'y': nw_responses = self.network.y else: raise ValueError(f'Invalid parameter type `{parameter_type}`. Valid options: `s`, `z`, or `y`') error_mean_squared = 0 for i in list_i: for j in list_j: nw_ij = nw_responses[:, i, j] fit_ij = self.get_model_response(i, j, self.network.f) error_mean_squared += np.mean(np.square(np.abs(nw_ij - fit_ij))) return np.sqrt(error_mean_squared) def _get_ABCDE(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """ Private method. Returns the real-valued system matrices of the state-space representation of the current rational model, as defined in [#]_. Returns ------- A : ndarray State-space matrix A holding the poles on the diagonal as real values with imaginary parts on the sub- diagonal B : ndarray State-space matrix B holding coefficients (1, 2, or 0), depending on the respective type of pole in A C : ndarray State-space matrix C holding the residues D : ndarray State-space matrix D holding the constants E : ndarray State-space matrix E holding the proportional coefficients (usually 0 in case of fitted S-parameters) Raises ------ ValueError If the model parameters have not been initialized (by running :func:`vector_fit()` or :func:`read_npz()`). References ---------- .. [#] B. Gustavsen and A. Semlyen, "Fast Passivity Assessment for S-Parameter Rational Models Via a Half-Size Test Matrix," in IEEE Transactions on Microwave Theory and Techniques, vol. 56, no. 12, pp. 2701-2708, Dec. 2008, DOI: 10.1109/TMTT.2008.2007319. """ # initial checks if self.poles is None: raise ValueError('self.poles = None; nothing to do. You need to run vector_fit() first.') if self.residues is None: raise ValueError('self.residues = None; nothing to do. You need to run vector_fit() first.') if self.proportional_coeff is None: raise ValueError('self.proportional_coeff = None; nothing to do. You need to run vector_fit() first.') if self.constant_coeff is None: raise ValueError('self.constant_coeff = None; nothing to do. You need to run vector_fit() first.') # assemble real-valued state-space matrices A, B, C, D, E from fitted complex-valued pole-residue model # determine size of the matrix system n_ports = int(np.sqrt(len(self.constant_coeff))) n_poles_real = 0 n_poles_cplx = 0 for pole in self.poles: if np.imag(pole) == 0.0: n_poles_real += 1 else: n_poles_cplx += 1 n_matrix = (n_poles_real + 2 * n_poles_cplx) * n_ports # state-space matrix A holds the poles on the diagonal as real values with imaginary parts on the sub-diagonal # state-space matrix B holds coefficients (1, 2, or 0), depending on the respective type of pole in A # assemble A = [[poles_real, 0, 0], # [0, real(poles_cplx), imag(poles_cplx], # [0, -imag(poles_cplx), real(poles_cplx]] A = np.identity(n_matrix) B = np.zeros(shape=(n_matrix, n_ports)) i_A = 0 # index on diagonal of A for j in range(n_ports): for pole in self.poles: if np.imag(pole) == 0.0: # adding a real pole A[i_A, i_A] = np.real(pole) B[i_A, j] = 1 i_A += 1 else: # adding a complex-conjugate pole A[i_A, i_A] = np.real(pole) A[i_A, i_A + 1] = np.imag(pole) A[i_A + 1, i_A] = -1 * np.imag(pole) A[i_A + 1, i_A + 1] = np.real(pole) B[i_A, j] = 2 i_A += 2 # state-space matrix C holds the residues # assemble C = [[R1.11, R1.12, R1.13, ...], [R2.11, R2.12, R2.13, ...], ...] C = np.zeros(shape=(n_ports, n_matrix)) for i in range(n_ports): for j in range(n_ports): # i: row index # j: column index i_response = i * n_ports + j j_residues = 0 for zero in self.residues[i_response]: if np.imag(zero) == 0.0: C[i, j * (n_poles_real + 2 * n_poles_cplx) + j_residues] = np.real(zero) j_residues += 1 else: C[i, j * (n_poles_real + 2 * n_poles_cplx) + j_residues] = np.real(zero) C[i, j * (n_poles_real + 2 * n_poles_cplx) + j_residues + 1] = np.imag(zero) j_residues += 2 # state-space matrix D holds the constants # assemble D = [[d11, d12, ...], [d21, d22, ...], ...] D = np.zeros(shape=(n_ports, n_ports)) for i in range(n_ports): for j in range(n_ports): # i: row index # j: column index i_response = i * n_ports + j D[i, j] = self.constant_coeff[i_response] # state-space matrix E holds the proportional coefficients (usually 0 in case of fitted S-parameters) # assemble E = [[e11, e12, ...], [e21, e22, ...], ...] E = np.zeros(shape=(n_ports, n_ports)) for i in range(n_ports): for j in range(n_ports): # i: row index # j: column index i_response = i * n_ports + j E[i, j] = self.proportional_coeff[i_response] return A, B, C, D, E @staticmethod def _get_s_from_ABCDE(freqs: np.ndarray, A: np.ndarray, B: np.ndarray, C: np.ndarray, D: np.ndarray, E: np.ndarray) -> np.ndarray: """ Private method. Returns the S-matrix of the vector fitted model calculated from the real-valued system matrices of the state- space representation, as provided by `_get_ABCDE()`. Parameters ---------- freqs : ndarray Frequencies (in Hz) at which to calculate the S-matrices. A : ndarray B : ndarray C : ndarray D : ndarray E : ndarray Returns ------- ndarray Complex-valued S-matrices (fxNxN) calculated at frequencies `freqs`. """ dim_A = np.shape(A)[0] stsp_poles = np.linalg.inv(2j * np.pi * freqs[:, None, None] * np.identity(dim_A)[None, :, :] - A[None, :, :]) stsp_S = np.matmul(np.matmul(C, stsp_poles), B) stsp_S += D + 2j * np.pi * freqs[:, None, None] * E return stsp_S def passivity_test(self, parameter_type: str = 's') -> np.ndarray: """ Evaluates the passivity of reciprocal vector fitted models by means of a half-size test matrix [#]_. Any existing frequency bands of passivity violations will be returned as a sorted list. Parameters ---------- parameter_type: str, optional Representation type of the fitted frequency responses. Either *scattering* (:attr:`s` or :attr:`S`), *impedance* (:attr:`z` or :attr:`Z`) or *admittance* (:attr:`y` or :attr:`Y`). Currently, only scattering parameters are supported for passivity evaluation. Raises ------ NotImplementedError If the function is called for `parameter_type` different than `S` (scattering). ValueError If the function is used with a model containing nonzero proportional coefficients. Returns ------- violation_bands : ndarray NumPy array with frequency bands of passivity violation: `[[f_start_1, f_stop_1], [f_start_2, f_stop_2], ...]`. See Also -------- is_passive : Query the model passivity as a boolean value. passivity_enforce : Enforces the passivity of the vector fitted model, if required. Examples -------- Load and fit the `Network`, then evaluate the model passivity: >>> nw_3port = skrf.Network('my3port.s3p') >>> vf = skrf.VectorFitting(nw_3port) >>> vf.vector_fit(n_poles_real=1, n_poles_cmplx=4) >>> violations = vf.passivity_test() References ---------- .. [#] B. Gustavsen and A. Semlyen, "Fast Passivity Assessment for S-Parameter Rational Models Via a Half-Size Test Matrix," in IEEE Transactions on Microwave Theory and Techniques, vol. 56, no. 12, pp. 2701-2708, Dec. 2008, DOI: 10.1109/TMTT.2008.2007319. """ if parameter_type.lower() != 's': raise NotImplementedError('Passivity testing is currently only supported for scattering (S) parameters.') if parameter_type.lower() == 's' and len(np.flatnonzero(self.proportional_coeff)) > 0: raise ValueError('Passivity testing of scattering parameters with nonzero proportional coefficients does ' 'not make any sense; you need to run vector_fit() with option `fit_proportional=False` ' 'first.') # # the network needs to be reciprocal for this passivity test method to work: S = transpose(S) # if not np.allclose(self.residues, np.transpose(self.residues)) or \ # not np.allclose(self.constant_coeff, np.transpose(self.constant_coeff)) or \ # not np.allclose(self.proportional_coeff, np.transpose(self.proportional_coeff)): # logging.error('Passivity testing with unsymmetrical model parameters is not supported. ' # 'The model needs to be reciprocal.') # return # get state-space matrices A, B, C, D, E = self._get_ABCDE() n_ports = np.shape(D)[0] # build half-size test matrix P from state-space matrices A, B, C, D inv_neg = np.linalg.inv(D - np.identity(n_ports)) inv_pos = np.linalg.inv(D + np.identity(n_ports)) prod_neg = np.matmul(np.matmul(B, inv_neg), C) prod_pos = np.matmul(np.matmul(B, inv_pos), C) P = np.matmul(A - prod_neg, A - prod_pos) # extract eigenvalues of P P_eigs = np.linalg.eigvals(P) # purely imaginary square roots of eigenvalues identify frequencies (2*pi*f) of borders of passivity violations freqs_violation = [] for sqrt_eigenval in np.sqrt(P_eigs): if np.real(sqrt_eigenval) == 0.0: freqs_violation.append(np.imag(sqrt_eigenval) / 2 / np.pi) # include dc (0) unless it's already included if len(np.nonzero(np.array(freqs_violation) == 0.0)[0]) == 0: freqs_violation.append(0.0) # sort the output from lower to higher frequencies freqs_violation = np.sort(freqs_violation) # identify frequency bands of passivity violations # sweep the bands between crossover frequencies and identify bands of passivity violations violation_bands = [] for i, freq in enumerate(freqs_violation): if i == len(freqs_violation) - 1: # last band stops always at infinity f_start = freq f_stop = np.inf f_center = 1.1 * f_start # 1.1 is chosen arbitrarily to have any frequency for evaluation else: # intermediate band between this frequency and the previous one f_start = freq f_stop = freqs_violation[i + 1] f_center = 0.5 * (f_start + f_stop) # calculate singular values at the center frequency between crossover frequencies to identify violations s_center = self._get_s_from_ABCDE(np.array([f_center]), A, B, C, D, E) sigma = np.linalg.svd(s_center[0], compute_uv=False) passive = True for singval in sigma: if singval > 1: # passivity violation in this band passive = False if not passive: # add this band to the list of passivity violations if violation_bands is None: violation_bands = [[f_start, f_stop]] else: violation_bands.append([f_start, f_stop]) return np.array(violation_bands) def is_passive(self, parameter_type: str = 's') -> bool: """ Returns the passivity status of the model as a boolean value. Parameters ---------- parameter_type : str, optional Representation type of the fitted frequency responses. Either *scattering* (:attr:`s` or :attr:`S`), *impedance* (:attr:`z` or :attr:`Z`) or *admittance* (:attr:`y` or :attr:`Y`). Currently, only scattering parameters are supported for passivity evaluation. Returns ------- passivity : bool :attr:`True` if model is passive, else :attr:`False`. See Also -------- passivity_test : Verbose passivity evaluation routine. passivity_enforce : Enforces the passivity of the vector fitted model, if required. Examples -------- Load and fit the `Network`, then check whether or not the model is passive: >>> nw_3port = skrf.Network('my3port.s3p') >>> vf = skrf.VectorFitting(nw_3port) >>> vf.vector_fit(n_poles_real=1, n_poles_cmplx=4) >>> vf.is_passive() # returns True or False """ viol_bands = self.passivity_test(parameter_type) if len(viol_bands) == 0: return True else: return False def passivity_enforce(self, n_samples: int = 200, f_max: float = None, parameter_type: str = 's') -> None: """ Enforces the passivity of the vector fitted model, if required. This is an implementation of the method presented in [#]_. Passivity is achieved by updating the residues and the constants. Parameters ---------- n_samples : int, optional Number of linearly spaced frequency samples at which passivity will be evaluated and enforced. (Default: 100) f_max : float or None, optional Highest frequency of interest for the passivity enforcement (in Hz, not rad/s). This limit usually equals the highest sample frequency of the fitted Network. If None, the highest frequency in :attr:`self.network` is used, which must not be None is this case. If `f_max` is not None, it overrides the highest frequency in :attr:`self.network`. parameter_type : str, optional Representation type of the fitted frequency responses. Either *scattering* (:attr:`s` or :attr:`S`), *impedance* (:attr:`z` or :attr:`Z`) or *admittance* (:attr:`y` or :attr:`Y`). Currently, only scattering parameters are supported for passivity evaluation. Returns ------- None Raises ------ NotImplementedError If the function is called for `parameter_type` different than `S` (scattering). ValueError If the function is used with a model containing nonzero proportional coefficients. Or if both `f_max` and :attr:`self.network` are None. See Also -------- is_passive : Returns the passivity status of the model as a boolean value. passivity_test : Verbose passivity evaluation routine. plot_passivation : Convergence plot for passivity enforcement iterations. Examples -------- Load and fit the `Network`, then enforce the passivity of the model: >>> nw_3port = skrf.Network('my3port.s3p') >>> vf = skrf.VectorFitting(nw_3port) >>> vf.vector_fit(n_poles_real=1, n_poles_cmplx=4) >>> vf.passivity_enforce() # won't do anything if model is already passive References ---------- .. [#] T. Dhaene, D. Deschrijver and N. Stevens, "Efficient Algorithm for Passivity Enforcement of S-Parameter- Based Macromodels," in IEEE Transactions on Microwave Theory and Techniques, vol. 57, no. 2, pp. 415-420, Feb. 2009, DOI: 10.1109/TMTT.2008.2011201. """ if parameter_type.lower() != 's': raise NotImplementedError('Passivity testing is currently only supported for scattering (S) parameters.') if parameter_type.lower() == 's' and len(np.flatnonzero(self.proportional_coeff)) > 0: raise ValueError('Passivity testing of scattering parameters with nonzero proportional coefficients does ' 'not make any sense; you need to run vector_fit() with option `fit_proportional=False` ' 'first.') # always run passivity test first; this will write 'self.violation_bands' if self.is_passive(): # model is already passive; do nothing and return logging.info('Passivity enforcement: The model is already passive. Nothing to do.') return # find the highest relevant frequency; either # 1) the highest frequency of passivity violation (f_viol_max) # or # 2) the highest fitting frequency (f_samples_max) violation_bands = self.passivity_test() f_viol_max = violation_bands[-1, 1] if f_max is None: if self.network is None: raise RuntimeError('Both `self.network` and parameter `f_max` are None. One of them is required to ' 'specify the frequency band of interest for the passivity enforcement.') else: f_samples_max = self.network.f[-1] else: f_samples_max = f_max # deal with unbounded violation interval (f_viol_max == np.inf) if np.isinf(f_viol_max): f_viol_max = 1.5 * violation_bands[-1, 0] warnings.warn('Passivity enforcement: The passivity violations of this model are unbounded. Passivity ' 'enforcement might still work, but consider re-fitting with a lower number of poles and/or ' 'without the constants (`fit_constant=False`) if the results are not satisfactory.', UserWarning, stacklevel=2) # the frequency band for the passivity evaluation is from dc to 20% above the highest relevant frequency if f_viol_max < f_samples_max: f_eval_max = 1.2 * f_samples_max else: f_eval_max = 1.2 * f_viol_max freqs_eval = np.linspace(0, f_eval_max, n_samples) A, B, C, D, E = self._get_ABCDE() dim_A = np.shape(A)[0] C_t = C # only include constant if it has been fitted (not zero) if len(np.nonzero(D)[0]) == 0: D_t = None else: D_t = D if self.network is not None: # find highest singular value among all frequencies and responses to use as target for the perturbation # singular value decomposition sigma = np.linalg.svd(self.network.s, compute_uv=False) delta = np.amax(sigma) if delta > 0.999: delta = 0.999 else: delta = 0.999 # predefined tolerance parameter (users should not need to change this) # calculate coefficient matrix A_freq = np.linalg.inv(2j * np.pi * freqs_eval[:, None, None] * np.identity(dim_A)[None, :, :] - A[None, :, :]) # construct coefficient matrix with an extra column for the constants (if present) if D_t is not None: coeffs = np.empty((len(freqs_eval), np.shape(B)[0] + 1, np.shape(B)[1]), dtype=complex) coeffs[:, :-1, :] = np.matmul(A_freq, B[None, :, :]) coeffs[:, -1, :] = 1 else: coeffs = np.matmul(A_freq, B[None, :, :]) # iterative compensation of passivity violations t = 0 self.history_max_sigma = [] while t < self.max_iterations: logging.info(f'Passivity enforcement; Iteration {t + 1}') # calculate S-matrix at this frequency (shape fxNxN) if D_t is not None: s_eval = self._get_s_from_ABCDE(freqs_eval, A, B, C_t, D_t, E) else: s_eval = self._get_s_from_ABCDE(freqs_eval, A, B, C_t, D, E) # singular value decomposition u, sigma, vh = np.linalg.svd(s_eval, full_matrices=False) # keep track of the greatest singular value in every iteration step sigma_max = np.amax(sigma) # find and perturb singular values that cause passivity violations idx_viol = np.nonzero(sigma > delta) sigma_viol = np.zeros_like(sigma) sigma_viol[idx_viol] = sigma[idx_viol] - delta # construct a stack of diagonal matrices with the perturbed singular values on the diagonal sigma_viol_diag = np.zeros_like(u, dtype=float) idx_diag = np.arange(np.shape(sigma)[1]) sigma_viol_diag[:, idx_diag, idx_diag] = sigma_viol # calculate violation S-responses s_viol = np.matmul(np.matmul(u, sigma_viol_diag), vh) # fit perturbed residues C_t for each response S_{i,j} for i in range(np.shape(s_viol)[1]): for j in range(np.shape(s_viol)[2]): # mind the transpose of the system to compensate for the exchanged order of matrix multiplication: # wanting to solve S = C_t * coeffs # but actually solving S = coeffs * C_t # S = C_t * coeffs <==> transpose(S) = transpose(coeffs) * transpose(C_t) # solve least squares (real-valued) x, residuals, rank, singular_vals = np.linalg.lstsq(np.vstack((np.real(coeffs[:, :, i]), np.imag(coeffs[:, :, i]))), np.hstack((np.real(s_viol[:, j, i]), np.imag(s_viol[:, j, i]))), rcond=None) # perturb residues by subtracting respective row and column in C_t # one half of the solution will always be 0 due to construction of A and B # also perturb constants (if present) if D_t is not None: C_t[j, :] = C_t[j, :] - x[:-1] D_t[j, i] = D_t[j, i] - x[-1] else: C_t[j, :] = C_t[j, :] - x t += 1 self.history_max_sigma.append(sigma_max) # stop iterations when model is passive if sigma_max < 1.0: break # PASSIVATION PROCESS DONE; model is either passive or max. number of iterations have been exceeded if t == self.max_iterations: warnings.warn('Passivity enforcement: Aborting after the max. number of iterations has been exceeded.', RuntimeWarning, stacklevel=2) # save/update model parameters (perturbed residues) self.history_max_sigma = np.array(self.history_max_sigma) n_ports = np.shape(D)[0] for i in range(n_ports): k = 0 # column index in C_t for j in range(n_ports): i_response = i * n_ports + j z = 0 # column index self.residues for pole in self.poles: if np.imag(pole) == 0.0: # real pole --> real residue self.residues[i_response, z] = C_t[i, k] k += 1 else: # complex-conjugate pole --> complex-conjugate residue self.residues[i_response, z] = C_t[i, k] + 1j * C_t[i, k + 1] k += 2 z += 1 if D_t is not None: self.constant_coeff[i_response] = D_t[i, j] # run final passivity test to make sure passivation was successful violation_bands = self.passivity_test() if len(violation_bands) > 0: warnings.warn('Passivity enforcement was not successful.\nModel is still non-passive in these frequency ' 'bands: {}.\nTry running this routine again with a larger number of samples (parameter ' '`n_samples`).'.format(violation_bands), RuntimeWarning, stacklevel=2) def write_npz(self, path: str) -> None: """ Writes the model parameters in :attr:`poles`, :attr:`residues`, :attr:`proportional_coeff` and :attr:`constant_coeff` to a labeled NumPy .npz file. Parameters ---------- path : str Target path without filename for the export. The filename will be added automatically based on the network name in :attr:`network` Returns ------- None See Also -------- read_npz : Reads all model parameters from a .npz file Examples -------- Load and fit the `Network`, then export the model parameters to a .npz file: >>> nw_3port = skrf.Network('my3port.s3p') >>> vf = skrf.VectorFitting(nw_3port) >>> vf.vector_fit(n_poles_real=1, n_poles_cmplx=4) >>> vf.write_npz('./data/') The filename depends on the network name stored in `nw_3port.name` and will have the prefix `coefficients_`, for example `coefficients_my3port.npz`. The coefficients can then be read using NumPy's load() function: >>> coeffs = numpy.load('./data/coefficients_my3port.npz') >>> poles = coeffs['poles'] >>> residues = coeffs['residues'] >>> prop_coeffs = coeffs['proportionals'] >>> constants = coeffs['constants'] Alternatively, the coefficients can be read directly into a new instance of `VectorFitting`, see :func:`read_npz`. """ if self.poles is None: warnings.warn('Nothing to export; Poles have not been fitted.', RuntimeWarning, stacklevel=2) return if self.residues is None: warnings.warn('Nothing to export; Residues have not been fitted.', RuntimeWarning, stacklevel=2) return if self.proportional_coeff is None: warnings.warn('Nothing to export; Proportional coefficients have not been fitted.', RuntimeWarning, stacklevel=2) return if self.constant_coeff is None: warnings.warn('Nothing to export; Constants have not been fitted.', RuntimeWarning, stacklevel=2) return filename = self.network.name logging.info(f'Exporting results as compressed NumPy array to {path}') np.savez_compressed(os.path.join(path, f'coefficients_{filename}'), poles=self.poles, residues=self.residues, proportionals=self.proportional_coeff, constants=self.constant_coeff) def read_npz(self, file: str) -> None: """ Reads all model parameters :attr:`poles`, :attr:`residues`, :attr:`proportional_coeff` and :attr:`constant_coeff` from a labeled NumPy .npz file. Parameters ---------- file : str NumPy .npz file containing the parameters. See notes. Returns ------- None Raises ------ ValueError If the shapes of the coefficient arrays in the provided file are not compatible. Notes ----- The .npz file needs to include the model parameters as individual NumPy arrays (ndarray) labeled '*poles*', '*residues*', '*proportionals*' and '*constants*'. The shapes of those arrays need to match the network properties in :class:`network` (correct number of ports). Preferably, the .npz file was created by :func:`write_npz`. See Also -------- write_npz : Writes all model parameters to a .npz file Examples -------- Create an empty `VectorFitting` instance (with or without the fitted `Network`) and load the model parameters: >>> vf = skrf.VectorFitting(None) >>> vf.read_npz('./data/coefficients_my3port.npz') This can be useful to analyze or process a previous vector fit instead of fitting it again, which sometimes takes a long time. For example, the model passivity can be evaluated and enforced: >>> vf.passivity_enforce() """ with np.load(file) as data: poles = data['poles'] # legacy support for exported residues if 'zeros' in data: # old .npz file from deprecated write_npz() with residues called 'zeros' residues = data['zeros'] else: # new .npz file from current write_npz() residues = data['residues'] proportional_coeff = data['proportionals'] constant_coeff = data['constants'] n_ports = int(np.sqrt(len(constant_coeff))) n_resp = n_ports ** 2 if np.shape(residues)[0] == np.shape(proportional_coeff)[0] == np.shape(constant_coeff)[0] == n_resp: self.poles = poles self.residues = residues self.proportional_coeff = proportional_coeff self.constant_coeff = constant_coeff else: raise ValueError('The shapes of the provided parameters are not compatible. The coefficient file needs ' 'to contain NumPy arrays labled `poles`, `residues`, `proportionals`, and ' '`constants`. Their shapes must match the number of network ports and the number of ' 'frequencies.') def get_model_response(self, i: int, j: int, freqs: Any = None) -> np.ndarray: """ Returns one of the frequency responses :math:`H_{i+1,j+1}` of the fitted model :math:`H`. Parameters ---------- i : int Row index of the response in the response matrix. j : int Column index of the response in the response matrix. freqs : list of float or ndarray or None, optional List of frequencies for the response plot. If None, the sample frequencies of the fitted network in :attr:`network` are used. Returns ------- response : ndarray Model response :math:`H_{i+1,j+1}` at the frequencies specified in `freqs` (complex-valued Numpy array). Examples -------- Get fitted S11 at 101 frequencies from 0 Hz to 10 GHz: >>> import skrf >>> vf = skrf.VectorFitting(skrf.data.ring_slot) >>> vf.vector_fit(3, 0) >>> s11_fit = vf.get_model_response(0, 0, numpy.linspace(0, 10e9, 101)) """ if self.poles is None: warnings.warn('Returning a zero-vector; Poles have not been fitted.', RuntimeWarning, stacklevel=2) return np.zeros_like(freqs) if self.residues is None: warnings.warn('Returning a zero-vector; Residues have not been fitted.', RuntimeWarning, stacklevel=2) return np.zeros_like(freqs) if self.proportional_coeff is None: warnings.warn('Returning a zero-vector; Proportional coefficients have not been fitted.', RuntimeWarning, stacklevel=2) return np.zeros_like(freqs) if self.constant_coeff is None: warnings.warn('Returning a zero-vector; Constants have not been fitted.', RuntimeWarning, stacklevel=2) return np.zeros_like(freqs) if freqs is None: freqs = np.linspace(np.amin(self.network.f), np.amax(self.network.f), 1000) s = 2j * np.pi * np.array(freqs) n_ports = int(np.sqrt(len(self.constant_coeff))) i_response = i * n_ports + j residues = self.residues[i_response] resp = self.proportional_coeff[i_response] * s + self.constant_coeff[i_response] for i, pole in enumerate(self.poles): if np.imag(pole) == 0.0: # real pole resp += residues[i] / (s - pole) else: # complex conjugate pole resp += residues[i] / (s - pole) + np.conjugate(residues[i]) / (s - np.conjugate(pole)) return resp @axes_kwarg def plot(self, component: str, i: int = -1, j: int = -1, freqs: Any = None, parameter: str = 's', *, ax: Axes = None) -> Axes: """ Plots the specified component of the parameter :math:`H_{i+1,j+1}` in the fit, where :math:`H` is either the scattering (:math:`S`), the impedance (:math:`Z`), or the admittance (:math:`H`) response specified in `parameter`. Parameters ---------- component : str The component to be plotted. Must be one of the following items: ['db', 'mag', 'deg', 'deg_unwrap', 're', 'im']. `db` for magnitude in decibels, `mag` for magnitude in linear scale, `deg` for phase in degrees (wrapped), `deg_unwrap` for phase in degrees (unwrapped/continuous), `re` for real part in linear scale, `im` for imaginary part in linear scale. i : int, optional Row index of the response. `-1` to plot all rows. j : int, optional Column index of the response. `-1` to plot all columns. freqs : list of float or ndarray or None, optional List of frequencies for the response plot. If None, the sample frequencies of the fitted network in :attr:`network` are used. This only works if :attr:`network` is not `None`. parameter : str, optional The network representation to be used. This is only relevant for the plot of the original sampled response in :attr:`network` that is used for comparison with the fit. Must be one of the following items unless :attr:`network` is `None`: ['s', 'z', 'y'] for *scattering* (default), *impedance*, or *admittance*. ax : :class:`matplotlib.Axes` object or None matplotlib axes to draw on. If None, the current axes is fetched with :func:`gca()`. Returns ------- :class:`matplotlib.Axes` matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current figure. Raises ------ ValueError If the `freqs` parameter is not specified while the Network in :attr:`network` is `None`. Also if `component` and/or `parameter` are not valid. """ components = ['db', 'mag', 'deg', 'deg_unwrap', 're', 'im'] if component.lower() in components: if self.residues is None or self.poles is None: raise RuntimeError('Poles and/or residues have not been fitted. Cannot plot the model response.') n_ports = int(np.sqrt(np.shape(self.residues)[0])) if i == -1: list_i = range(n_ports) elif isinstance(i, int): list_i = [i] else: list_i = i if j == -1: list_j = range(n_ports) elif isinstance(j, int): list_j = [j] else: list_j = j if self.network is not None: # plot the original network response at each sample frequency (scatter plot) if parameter.lower() == 's': responses = self.network.s elif parameter.lower() == 'z': responses = self.network.z elif parameter.lower() == 'y': responses = self.network.y else: raise ValueError('The network parameter type is not valid, must be `s`, `z`, or `y`, ' 'got `{}`.'.format(parameter)) i_samples = 0 for i in list_i: for j in list_j: if i_samples == 0: label = 'Samples' else: label = '_nolegend_' i_samples += 1 y_vals = None if component.lower() == 'db': y_vals = 20 * np.log10(np.abs(responses[:, i, j])) elif component.lower() == 'mag': y_vals = np.abs(responses[:, i, j]) elif component.lower() == 'deg': y_vals = np.rad2deg(np.angle(responses[:, i, j])) elif component.lower() == 'deg_unwrap': y_vals = np.rad2deg(np.unwrap(np.angle(responses[:, i, j]))) elif component.lower() == 're': y_vals = np.real(responses[:, i, j]) elif component.lower() == 'im': y_vals = np.imag(responses[:, i, j]) ax.scatter(self.network.f, y_vals, color='r', label=label) if freqs is None: # get frequency array from the network freqs = self.network.f if freqs is None: raise ValueError( 'Neither `freqs` nor `self.network` is specified. Cannot plot model response without any ' 'frequency information.') # plot the fitted responses y_label = '' i_fit = 0 for i in list_i: for j in list_j: if i_fit == 0: label = 'Fit' else: label = '_nolegend_' i_fit += 1 y_model = self.get_model_response(i, j, freqs) y_vals = None if component.lower() == 'db': y_vals = 20 * np.log10(np.abs(y_model)) y_label = 'Magnitude (dB)' elif component.lower() == 'mag': y_vals = np.abs(y_model) y_label = 'Magnitude' elif component.lower() == 'deg': y_vals = np.rad2deg(np.angle(y_model)) y_label = 'Phase (Degrees)' elif component.lower() == 'deg_unwrap': y_vals = np.rad2deg(np.unwrap(np.angle(y_model))) y_label = 'Phase (Degrees)' elif component.lower() == 're': y_vals = np.real(y_model) y_label = 'Real Part' elif component.lower() == 'im': y_vals = np.imag(y_model) y_label = 'Imaginary Part' ax.plot(freqs, y_vals, color='k', label=label) ax.set_xlabel('Frequency (Hz)') ax.set_ylabel(y_label) ax.legend(loc='best') # only print title if a single response is shown if i_fit == 1: ax.set_title(f'Response i={i}, j={j}') return ax else: raise ValueError(f'The specified component ("{component}") is not valid. Must be in {components}.') def plot_s_db(self, *args, **kwargs) -> Axes: """ Plots the magnitude in dB of the scattering parameter response(s) in the fit. Parameters ---------- *args : any, optional Additonal arguments to be passed to :func:`plot`. **kwargs : dict, optional Additonal keyword arguments to be passed to :func:`plot`. Returns ------- :class:`matplotlib.Axes` matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current figure. Notes ----- This simply calls ``plot('db', *args, **kwargs)``. """ return self.plot('db', *args, **kwargs) def plot_s_mag(self, *args, **kwargs) -> Axes: """ Plots the magnitude in linear scale of the scattering parameter response(s) in the fit. Parameters ---------- *args : any, optional Additonal arguments to be passed to :func:`plot`. **kwargs : dict, optional Additonal keyword arguments to be passed to :func:`plot`. Returns ------- :class:`matplotlib.Axes` matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current figure. Notes ----- This simply calls ``plot('mag', *args, **kwargs)``. """ return self.plot('mag', *args, **kwargs) def plot_s_deg(self, *args, **kwargs) -> Axes: """ Plots the phase in degrees of the scattering parameter response(s) in the fit. Parameters ---------- *args : any, optional Additonal arguments to be passed to :func:`plot`. **kwargs : dict, optional Additonal keyword arguments to be passed to :func:`plot`. Returns ------- :class:`matplotlib.Axes` matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current figure. Notes ----- This simply calls ``plot('deg', *args, **kwargs)``. """ return self.plot('deg', *args, **kwargs) def plot_s_deg_unwrap(self, *args, **kwargs) -> Axes: """ Plots the unwrapped phase in degrees of the scattering parameter response(s) in the fit. Parameters ---------- *args : any, optional Additonal arguments to be passed to :func:`plot`. **kwargs : dict, optional Additonal keyword arguments to be passed to :func:`plot`. Returns ------- :class:`matplotlib.Axes` matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current figure. Notes ----- This simply calls ``plot('deg_unwrap', *args, **kwargs)``. """ return self.plot('deg_unwrap', *args, **kwargs) def plot_s_re(self, *args, **kwargs) -> Axes: """ Plots the real part of the scattering parameter response(s) in the fit. Parameters ---------- *args : any, optional Additonal arguments to be passed to :func:`plot`. **kwargs : dict, optional Additonal keyword arguments to be passed to :func:`plot`. Returns ------- :class:`matplotlib.Axes` matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current figure. Notes ----- This simply calls ``plot('re', *args, **kwargs)``. """ return self.plot('re', *args, **kwargs) def plot_s_im(self, *args, **kwargs) -> Axes: """ Plots the imaginary part of the scattering parameter response(s) in the fit. Parameters ---------- *args : any, optional Additonal arguments to be passed to :func:`plot`. **kwargs : dict, optional Additonal keyword arguments to be passed to :func:`plot`. Returns ------- :class:`matplotlib.Axes` matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current figure. Notes ----- This simply calls ``plot('im', *args, **kwargs)``. """ return self.plot('im', *args, **kwargs) @axes_kwarg def plot_s_singular(self, freqs: Any = None, *, ax: Axes = None) -> Axes: """ Plots the singular values of the vector fitted S-matrix in linear scale. Parameters ---------- freqs : list of float or ndarray or None, optional List of frequencies for the response plot. If None, the sample frequencies of the fitted network in :attr:`network` are used. This only works if :attr:`network` is not `None`. ax : :class:`matplotlib.Axes` object or None matplotlib axes to draw on. If None, the current axes is fetched with :func:`gca()`. Returns ------- :class:`matplotlib.Axes` matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current figure. Raises ------ ValueError If the `freqs` parameter is not specified while the Network in :attr:`network` is `None`. """ if freqs is None: if self.network is None: raise ValueError( 'Neither `freqs` nor `self.network` is specified. Cannot plot model response without any ' 'frequency information.') else: freqs = self.network.f # get system matrices of state-space representation A, B, C, D, E = self._get_ABCDE() n_ports = np.shape(D)[0] singvals = np.zeros((n_ports, len(freqs))) # calculate and save singular values for each frequency u, sigma, vh = np.linalg.svd(self._get_s_from_ABCDE(freqs, A, B, C, D, E)) # plot the frequency response of each singular value for n in range(n_ports): ax.plot(freqs, sigma[:, n], label=fr'$\sigma_{n + 1}$') ax.set_xlabel('Frequency (Hz)') ax.set_ylabel('Magnitude') ax.legend(loc='best') return ax @axes_kwarg def plot_convergence(self, ax: Axes = None) -> Axes: """ Plots the history of the model residue parameter **d_res** during the iterative pole relocation process of the vector fitting, which should eventually converge to a fixed value. Additionally, the relative change of the maximum singular value of the coefficient matrix **A** are plotted, which serve as a convergence indicator. Parameters ---------- ax : :class:`matplotlib.Axes` object or None matplotlib axes to draw on. If None, the current axes is fetched with :func:`gca()`. Returns ------- :class:`matplotlib.Axes` matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current figure. """ ax.semilogy(np.arange(len(self.delta_max_history)) + 1, self.delta_max_history, color='darkblue') ax.set_xlabel('Iteration step') ax.set_ylabel('Max. relative change', color='darkblue') ax2 = ax.twinx() ax2.plot(np.arange(len(self.d_res_history)) + 1, self.d_res_history, color='orangered') ax2.set_ylabel('Residue', color='orangered') return ax @axes_kwarg def plot_passivation(self, ax: Axes = None) -> Axes: """ Plots the history of the greatest singular value during the iterative passivity enforcement process, which should eventually converge to a value slightly lower than 1.0 or stop after reaching the maximum number of iterations specified in the class variable :attr:`max_iterations`. Parameters ---------- ax : :class:`matplotlib.Axes` object or None matplotlib axes to draw on. If None, the current axes is fetched with :func:`gca()`. Returns ------- :class:`matplotlib.Axes` matplotlib axes used for drawing. Either the passed :attr:`ax` argument or the one fetch from the current figure. """ ax.plot(np.arange(len(self.history_max_sigma)) + 1, self.history_max_sigma) ax.set_xlabel('Iteration step') ax.set_ylabel('Max. singular value') return ax def write_spice_subcircuit_s(self, file: str, fitted_model_name: str = "s_equivalent") -> None: """ Creates an equivalent N-port SPICE subcircuit based on its vector fitted S parameter responses. Parameters ---------- file : str Path and filename including file extension (usually .sp) for the SPICE subcircuit file. fitted_model_name: str Name of the resulting model, default "s_equivalent" Returns ------- None Notes ----- In the SPICE subcircuit, all ports will share a common reference node (global SPICE ground on node 0). The equivalent circuit uses linear dependent current sources on all ports, which are controlled by the currents through equivalent admittances modelling the parameters from a vector fit. This approach is based on [#]_. Examples -------- Load and fit the `Network`, then export the equivalent SPICE subcircuit: >>> nw_3port = skrf.Network('my3port.s3p') >>> vf = skrf.VectorFitting(nw_3port) >>> vf.vector_fit(n_poles_real=1, n_poles_cmplx=4) >>> vf.write_spice_subcircuit_s('/my3port_model.sp') References ---------- .. [#] G. Antonini, "SPICE Equivalent Circuits of Frequency-Domain Responses", IEEE Transactions on Electromagnetic Compatibility, vol. 45, no. 3, pp. 502-512, August 2003, DOI: https://doi.org/10.1109/TEMC.2003.815528 """ # list of subcircuits for the equivalent admittances subcircuits = [] # provides a unique SPICE subcircuit identifier (X1, X2, X3, ...) def get_new_subckt_identifier(): subcircuits.append(f'X{len(subcircuits) + 1}') return subcircuits[-1] # use engineering notation for the numbers in the SPICE file (1000 --> 1k) formatter = EngFormatter(sep="", places=3, usetex=False) # replace "micron" sign by "u" and "mega" sign by "meg" letters_dict = formatter.ENG_PREFIXES letters_dict.update({-6: 'u', 6: 'meg'}) formatter.ENG_PREFIXES = letters_dict with open(file, 'w') as f: # write title line f.write('* EQUIVALENT CIRCUIT FOR VECTOR FITTED S-MATRIX\n') f.write('* Created using scikit-rf vectorFitting.py\n') f.write('*\n') # define the complete equivalent circuit as a subcircuit with one input node per port # those port nodes are labeled p1, p2, p3, ... # all ports share a common node for ground reference (node 0) str_input_nodes = '' for n in range(self.network.nports): str_input_nodes += f'p{n + 1} ' f.write(f'.SUBCKT {fitted_model_name} {str_input_nodes}\n') for n in range(self.network.nports): f.write('*\n') f.write(f'* port {n + 1}\n') # add port reference impedance z0 (has to be resistive, no imaginary part) f.write(f'R{n + 1} a{n + 1} 0 {np.real(self.network.z0[0, n])}\n') # add dummy voltage sources (V=0) to measure the input current f.write(f'V{n + 1} p{n + 1} a{n + 1} 0\n') # CCVS and VCVS driving the transfer admittances with a = V/2/sqrt(Z0) + I/2*sqrt(Z0) # In f.write(f'H{n + 1} nt{n + 1} nts{n + 1} V{n + 1} {np.real(self.network.z0[0, n])}\n') # Vn f.write(f'E{n + 1} nts{n + 1} 0 p{n + 1} 0 {1}\n') for j in range(self.network.nports): f.write(f'* transfer network for s{n + 1}{j + 1}\n') # stacking order in VectorFitting class variables: # s11, s12, s13, ..., s21, s22, s23, ... i_response = n * self.network.nports + j # add CCCS to generate the scattered current I_nj at port n # control current is measured by the dummy voltage source at the transfer network Y_nj # the scattered current is injected into the port (source positive connected to ground) f.write('F{}{} 0 a{} V{}{} {}\n'.format(n + 1, j + 1, n + 1, n + 1, j + 1, formatter(1 / np.real(self.network.z0[0, n])))) f.write('F{}{}_inv a{} 0 V{}{}_inv {}\n'.format(n + 1, j + 1, n + 1, n + 1, j + 1, formatter(1 / np.real(self.network.z0[0, n])))) # add dummy voltage source (V=0) in series with Y_nj to measure current through transfer admittance f.write(f'V{n + 1}{j + 1} nt{j + 1} nt{n + 1}{j + 1} 0\n') f.write(f'V{n + 1}{j + 1}_inv nt{j + 1} nt{n + 1}{j + 1}_inv 0\n') # add corresponding transfer admittance Y_nj, which is modulating the control current # the transfer admittance is a parallel circuit (sum) of individual admittances f.write(f'* transfer admittances for S{n + 1}{j + 1}\n') # start with proportional and constant term of the model # H(s) = d + s * e model # Y(s) = G + s * C equivalent admittance g = self.constant_coeff[i_response] c = self.proportional_coeff[i_response] # add R for constant term if g < 0: f.write(f'R{n + 1}{j + 1} nt{n + 1}{j + 1}_inv 0 {formatter(np.abs(1 / g))}\n') elif g > 0: f.write(f'R{n + 1}{j + 1} nt{n + 1}{j + 1} 0 {formatter(1 / g)}\n') # add C for proportional term if c < 0: f.write(f'C{n + 1}{j + 1} nt{n + 1}{j + 1}_inv 0 {formatter(np.abs(c))}\n') elif c > 0: f.write(f'C{n + 1}{j + 1} nt{n + 1}{j + 1} 0 {formatter(c)}\n') # add pairs of poles and residues for i_pole in range(len(self.poles)): pole = self.poles[i_pole] residue = self.residues[i_response, i_pole] node = get_new_subckt_identifier() + f' nt{n + 1}{j + 1}' if np.real(residue) < 0.0: # multiplication with -1 required, otherwise the values for RLC would be negative # this gets compensated by inverting the transfer current direction for this subcircuit residue = -1 * residue node += '_inv' if np.imag(pole) == 0.0: # real pole; add rl_admittance l = 1 / np.real(residue) r = -1 * np.real(pole) / np.real(residue) f.write(node + f' 0 rl_admittance res={formatter(r)} ind={formatter(l)}\n') else: # complex pole of a conjugate pair; add rcl_vccs_admittance l = 1 / (2 * np.real(residue)) b = -2 * (np.real(residue) * np.real(pole) + np.imag(residue) * np.imag(pole)) r = -1 * np.real(pole) / np.real(residue) c = 2 * np.real(residue) / (np.abs(pole) ** 2) gm_add = b * l * c if gm_add < 0: m = -1 else: m = 1 f.write(node + ' 0 rcl_vccs_admittance res={} cap={} ind={} gm={} mult={}\n'.format( formatter(r), formatter(c), formatter(l), formatter(np.abs(gm_add)), int(m))) f.write('.ENDS s_equivalent\n') f.write('*\n') # subcircuit for an active RCL+VCCS equivalent admittance Y(s) of a complex-conjugate pole-residue pair H(s) # Residue: c = c' + j * c" # Pole: p = p' + j * p" # H(s) = c / (s - p) + conj(c) / (s - conj(p)) # = (2 * c' * s - 2 * (c'p' + c"p")) / (s ** 2 - 2 * p' * s + |p| ** 2) # Y(S) = (1 / L * s + b) / (s ** 2 + R / L * s + 1 / (L * C)) f.write('.SUBCKT rcl_vccs_admittance n_pos n_neg res=1k cap=1n ind=100p gm=1m mult=1\n') f.write('L1 n_pos 1 {ind}\n') f.write('C1 1 2 {cap}\n') f.write('R1 2 n_neg {res}\n') f.write('G1 n_pos n_neg 1 2 {gm * mult}\n') f.write('.ENDS rcl_vccs_admittance\n') f.write('*\n') # subcircuit for a passive RL equivalent admittance Y(s) of a real pole-residue pair H(s) # H(s) = c / (s - p) # Y(s) = 1 / L / (s + s * R / L) f.write('.SUBCKT rl_admittance n_pos n_neg res=1k ind=100p\n') f.write('L1 n_pos 1 {ind}\n') f.write('R1 1 n_neg {res}\n') f.write('.ENDS rl_admittance\n')
bsd-3-clause
1a0b3eb3c4442b40a4dbda97863ea860
43.432268
126
0.549831
3.940959
false
false
false
false
scikit-rf/scikit-rf
skrf/frequency.py
1
20119
""" .. currentmodule:: skrf.frequency ======================================== frequency (:mod:`skrf.frequency`) ======================================== Provides a frequency object and related functions. Most of the functionality is provided as methods and properties of the :class:`Frequency` Class. Frequency Class =============== .. autosummary:: :toctree: generated/ Frequency Functions ========= .. autosummary:: :toctree: generated/ overlap_freq Misc ==== .. autosummary:: :toctree: generated/ InvalidFrequencyWarning """ # from matplotlib.pyplot import gca,plot, autoscale from typing import List import warnings from numbers import Number from .constants import NumberLike, ZERO from typing import Union from numpy import pi, linspace, geomspace import numpy as npy from numpy import gradient # used to center attribute `t` at 0 import re from .util import slice_domain, find_nearest_index class InvalidFrequencyWarning(UserWarning): """Thrown if frequency values aren't monotonously increasing """ pass class Frequency: """ A frequency band. The frequency object provides a convenient way to work with and access a frequency band. It contains a frequency vector as well as a frequency unit. This allows a frequency vector in a given unit to be available (:attr:`f_scaled`), as well as an absolute frequency axis in 'Hz' (:attr:`f`). A Frequency object can be created from either (start, stop, npoints) using the default constructor, :func:`__init__`. Or, it can be created from an arbitrary frequency vector by using the class method :func:`from_f`. Internally, the frequency information is stored in the `f` property combined with the `unit` property. All other properties, `start` `stop`, etc are generated from these. """ unit_dict = { 'hz': 'Hz', 'khz': 'kHz', 'mhz': 'MHz', 'ghz': 'GHz', 'thz': 'THz' } """ Dictionnary to convert unit string with correct capitalization for display. """ multiplier_dict={ 'hz': 1, 'khz': 1e3, 'mhz': 1e6, 'ghz': 1e9, 'thz': 1e12 } """ Frequency unit multipliers. """ def __init__(self, start: float = 0, stop: float = 0, npoints: int = 0, unit: str = None, sweep_type: str = 'lin') -> None: """ Frequency initializer. Creates a Frequency object from start/stop/npoints and a unit. Alternatively, the class method :func:`from_f` can be used to create a Frequency object from a frequency vector instead. Parameters ---------- start : number, optional start frequency in units of `unit`. Default is 0. stop : number, optional stop frequency in units of `unit`. Default is 0. npoints : int, optional number of points in the band. Default is 0. unit : string, optional Frequency unit of the band: 'hz', 'khz', 'mhz', 'ghz', 'thz'. This is used to create the attribute :attr:`f_scaled`. It is also used by the :class:`~skrf.network.Network` class for plots vs. frequency. Default is 'ghz'. sweep_type : string, optional Type of the sweep: 'lin' or 'log'. 'lin' for linear and 'log' for logarithmic. Default is 'lin'. Note ---- The attribute `unit` sets the frequency multiplier, which is used to scale the frequency when `f_scaled` is referenced. Note ---- The attribute `unit` is not case sensitive. Hence, for example, 'GHz' or 'ghz' is the same. See Also -------- from_f : constructs a Frequency object from a frequency vector instead of start/stop/npoints. :attr:`unit` : frequency unit of the band Examples -------- >>> wr1p5band = Frequency(500, 750, 401, 'ghz') """ if unit is None: warnings.warn(''' Frequency unit not passed: currently uses 'GHz' per default. The future versions of scikit-rf will use 'Hz' per default instead, so it is recommended to specify explicitly the frequency unit to obtain similar results with future versions. ''', DeprecationWarning, stacklevel=2) unit = 'ghz' self._unit = unit.lower() start = self.multiplier * start stop = self.multiplier * stop if sweep_type.lower() == 'lin': self._f = linspace(start, stop, npoints) elif sweep_type.lower() == 'log' and start > 0: self._f = geomspace(start, stop, npoints) else: raise ValueError('Sweep Type not recognized') def __str__(self) -> str: """ """ try: output = \ '%s-%s %s, %i pts' % \ (self.f_scaled[0], self.f_scaled[-1], self.unit, self.npoints) except (IndexError): output = "[no freqs]" return output def __repr__(self) -> str: """ """ return self.__str__() def __getitem__(self, key: Union[str, int, slice]) -> 'Frequency': """ Slices a Frequency object based on an index, or human readable string. Parameters ---------- key : str, int, or slice if int, then it is interpreted as the index of the frequency if str, then should be like '50.1-75.5ghz', or just '50'. If the frequency unit is omitted then :attr:`unit` is used. Examples -------- >>> b = rf.Frequency(50, 100, 101, 'ghz') >>> a = b['80-90ghz'] >>> a.plot_s_db() """ output = self.copy() if isinstance(key, str): # they passed a string try and do some interpretation re_numbers = re.compile(r'.*\d') re_hyphen = re.compile(r'\s*-\s*') re_letters = re.compile('[a-zA-Z]+') freq_unit = re.findall(re_letters,key) if len(freq_unit) == 0: freq_unit = self.unit else: freq_unit = freq_unit[0] key_nounit = re.sub(re_letters,'',key) edges = re.split(re_hyphen,key_nounit) edges_freq = Frequency.from_f([float(k) for k in edges], unit = freq_unit) if len(edges_freq) ==2: slicer=slice_domain(output.f, edges_freq.f) elif len(edges_freq)==1: key = find_nearest_index(output.f, edges_freq.f[0]) slicer = slice(key,key+1,1) else: raise ValueError() try: output._f = npy.array(output.f[slicer]).reshape(-1) return output except(IndexError): raise IndexError('slicing frequency is incorrect') if output.f.shape[0] > 0: output._f = npy.array(output.f[key]).reshape(-1) else: output._f = npy.empty(shape=(0)) return output @classmethod def from_f(cls, f: NumberLike, *args,**kwargs) -> 'Frequency': """ Construct Frequency object from a frequency vector. The unit is set by kwarg 'unit' Parameters ---------- f : scalar or array-like frequency vector *args, **kwargs : arguments, keyword arguments passed on to :func:`__init__`. Returns ------- myfrequency : :class:`Frequency` object the Frequency object Raises ------ InvalidFrequencyWarning: If frequency points are not monotonously increasing Examples -------- >>> f = npy.linspace(75,100,101) >>> rf.Frequency.from_f(f, unit='ghz') """ if npy.isscalar(f): f = [f] temp_freq = cls(0,0,0,*args, **kwargs) temp_freq._f = npy.array(f) * temp_freq.multiplier temp_freq.check_monotonic_increasing() return temp_freq def __eq__(self, other: object) -> bool: #return (list(self.f) == list(other.f)) # had to do this out of practicality if not isinstance(other, self.__class__): return False if len(self.f) != len(other.f): return False elif len(self.f) == len(other.f) == 0: return True else: return (max(abs(self.f-other.f)) < ZERO) def __ne__(self,other: object) -> bool: return (not self.__eq__(other)) def __len__(self) -> int: """ The number of frequency points """ return self.npoints def __mul__(self,other: 'Frequency') -> 'Frequency': out = self.copy() out.f = self.f*other return out def __rmul__(self,other: 'Frequency') -> 'Frequency': out = self.copy() out.f = self.f*other return out def __div__(self,other: 'Frequency') -> 'Frequency': out = self.copy() out.f = self.f/other return out def check_monotonic_increasing(self) -> None: """Validate the frequency values Raises ------ InvalidFrequencyWarning: If frequency points are not monotonously increasing """ increase = npy.diff(self.f) > 0 if not increase.all(): warnings.warn("Frequency values are not monotonously increasing!\n" "To get rid of the invalid values call `drop_non_monotonic_increasing`", InvalidFrequencyWarning) def drop_non_monotonic_increasing(self) -> List[int]: """Drop duplicate and invalid frequency values and return the dropped indices Returns: list[int]: The dropped indices """ invalid = npy.zeros(len(self.f), dtype=bool) for i, val in enumerate(self.f): if not i: last_valid = val else: if val > last_valid: last_valid = val else: invalid[i] = True self._f = self._f[~invalid] return list(npy.flatnonzero(invalid)) @property def start(self) -> float: """ Starting frequency in Hz. """ return self.f[0] @property def start_scaled(self) -> float: """ Starting frequency in :attr:`unit`'s. """ return self.f_scaled[0] @property def stop_scaled(self) -> float: """ Stop frequency in :attr:`unit`'s. """ return self.f_scaled[-1] @property def stop(self) -> float: """ Stop frequency in Hz. """ return self.f[-1] @property def npoints(self) -> int: """ Number of points in the frequency. """ return len(self.f) @npoints.setter def npoints(self, n: int) -> None: """ Set the number of points in the frequency. """ warnings.warn('Possibility to set the npoints parameter will removed in the next release.', DeprecationWarning, stacklevel=2) if self.sweep_type == 'lin': self.f = linspace(self.start, self.stop, n) elif self.sweep_type == 'log': self.f = geomspace(self.start, self.stop, n) else: raise ValueError( 'Unable to change number of points for sweep type', self.sweep_type) @property def center(self) -> float: """ Center frequency in Hz. Returns ------- center : number the exact center frequency in units of Hz """ return self.start + (self.stop-self.start)/2. @property def center_idx(self) -> int: """ Closes idx of :attr:`f` to the center frequency. """ return self.npoints // 2 @property def center_scaled(self) -> float: """ Center frequency in :attr:`unit`'s. Returns ------- center : number the exact center frequency in units of :attr:`unit`'s """ return self.start_scaled + (self.stop_scaled-self.start_scaled)/2. @property def step(self) -> float: """ The inter-frequency step size (in Hz) for evenly-spaced frequency sweeps See Also -------- df : for general case """ return self.span/(self.npoints-1.) @property def step_scaled(self) -> float: """ The inter-frequency step size (in :attr:`unit`) for evenly-spaced frequency sweeps. See Also -------- df : for general case """ return self.span_scaled/(self.npoints-1.) @property def span(self) -> float: """ The frequency span. """ return abs(self.stop-self.start) @property def span_scaled(self) -> float: """ The frequency span. """ return abs(self.stop_scaled-self.start_scaled) @property def f(self) -> npy.ndarray: """ Frequency vector in Hz. Returns ---------- f : :class:`numpy.ndarray` The frequency vector in Hz See Also ---------- f_scaled : frequency vector in units of :attr:`unit` w : angular frequency vector in rad/s """ return self._f @f.setter def f(self,new_f: NumberLike) -> None: """ Sets the frequency object by passing a vector in Hz. Raises ------ InvalidFrequencyWarning: If frequency points are not monotonously increasing """ warnings.warn('Possibility to set the f parameter will removed in the next release.', DeprecationWarning, stacklevel=2) self._f = npy.array(new_f) self.check_monotonic_increasing() @property def f_scaled(self) -> npy.ndarray: """ Frequency vector in units of :attr:`unit`. Returns ------- f_scaled : numpy.ndarray A frequency vector in units of :attr:`unit` See Also -------- f : frequency vector in Hz w : frequency vector in rad/s """ return self.f/self.multiplier @property def w(self) -> npy.ndarray: r""" Angular frequency in radians/s. Angular frequency is defined as :math:`\omega=2\pi f` [#]_ Returns ------- w : :class:`numpy.ndarray` Angular frequency in rad/s References ---------- .. [#] https://en.wikipedia.org/wiki/Angular_frequency See Also -------- f_scaled : frequency vector in units of :attr:`unit` f : frequency vector in Hz """ return 2*pi*self.f @property def df(self) -> npy.ndarray: """ The gradient of the frequency vector. Note ---- The gradient is calculated using:: `gradient(self.f)` """ return gradient(self.f) @property def df_scaled(self) -> npy.ndarray: """ The gradient of the frequency vector (in unit of :attr:`unit`). Note ---- The gradient is calculated using:: `gradient(self.f_scaled)` """ return gradient(self.f_scaled) @property def dw(self) -> npy.ndarray: """ The gradient of the frequency vector (in radians). Note ---- The gradient is calculated using:: `gradient(self.w)` """ return gradient(self.w) @property def unit(self) -> str: """ Unit of this frequency band. Possible strings for this attribute are: 'hz', 'khz', 'mhz', 'ghz', 'thz' Setting this attribute is not case sensitive. Returns ------- unit : string lower-case string representing the frequency units """ return self.unit_dict[self._unit] @unit.setter def unit(self, unit: str) -> None: self._unit = unit.lower() @property def multiplier(self) -> float: """ Multiplier for formatting axis. This accesses the internal dictionary `multiplier_dict` using the value of :attr:`unit` Returns ------- multiplier : number multiplier for this Frequencies unit """ return self.multiplier_dict[self._unit] def copy(self) -> 'Frequency': """ Returns a new copy of this frequency. """ freq = Frequency.from_f(self.f, unit='hz') freq.unit = self.unit return freq @property def t(self) -> npy.ndarray: """ Time vector in s. t_period = 1/f_step """ return linspace(-.5/self.step , .5/self.step, self.npoints) @property def t_ns(self) -> npy.ndarray: """ Time vector in ns. t_period = 1/f_step """ return self.t*1e9 def round_to(self, val: Union[str, Number] = 'hz') -> None: """ Round off frequency values to a specified precision. This is useful for dealing with finite precision limitations of VNA's and/or other software Parameters ---------- val : string or number if val is a string it should be a frequency :attr:`unit` (ie 'hz', 'mhz',etc). if its a number, then this returns f = f-f%val Examples -------- >>> f = skrf.Frequency.from_f([.1,1.2,3.5],unit='hz') >>> f.round_to('hz') """ if isinstance(val, str): val = self.multiplier_dict[val.lower()] self.f = npy.round_(self.f/val)*val def overlap(self,f2: 'Frequency') -> 'Frequency': """ Calculates overlapping frequency between self and f2. See Also -------- overlap_freq """ return overlap_freq(self, f2) @property def sweep_type(self) -> str: """ Frequency sweep type. Returns ------- sweep_type: str 'lin' if linearly increasing, 'log' or 'unknown'. """ if npy.allclose(self.f, linspace(self.f[0], self.f[-1], self.npoints)): sweep_type = 'lin' elif self.f[0] and npy.allclose(self.f, geomspace(self.f[0], self.f[-1], self.npoints)): sweep_type = 'log' else: sweep_type = 'unknown' return sweep_type def overlap_freq(f1: 'Frequency',f2: 'Frequency') -> Frequency: """ Calculates overlapping frequency between f1 and f2. Or, put more accurately, this returns a Frequency that is the part of f1 that is overlapped by f2. The resultant start frequency is the smallest f1.f that is greater than f2.f.start, and the stop frequency is the largest f1.f that is smaller than f2.f.stop. This way the new frequency overlays onto f1. Parameters ---------- f1 : :class:`Frequency` a frequency object f2 : :class:`Frequency` a frequency object Returns ------- f3 : :class:`Frequency` part of f1 that is overlapped by f2 """ if f1.start > f2.stop: raise ValueError('Out of bounds. f1.start > f2.stop') elif f2.start > f1.stop: raise ValueError('Out of bounds. f2.start > f1.stop') start = max(f1.start, f2.start) stop = min(f1.stop, f2.stop) f = f1.f[(f1.f>=start) & (f1.f<=stop)] freq = Frequency.from_f(f, unit = 'hz') freq.unit = f1.unit return freq
bsd-3-clause
c0e864e4589a0208de015f2a7ef8bae4
26.005369
99
0.529748
4.121057
false
false
false
false
scikit-rf/scikit-rf
skrf/__init__.py
1
2142
""" skrf is an object-oriented approach to microwave engineering, implemented in Python. """ __version__ = '0.24.1' ## Import all module names for coherent reference of name-space #import io from . import frequency from . import network from . import networkSet from . import media from . import circuit from . import calibration from . import mathFunctions from . import tlineFunctions from . import taper from . import constants from . import util from . import io from . import instances from . import vectorFitting from . import qfactor # Import contents into current namespace for ease of calling from .frequency import * from .network import * from .networkSet import * from .calibration import * from .util import * from .circuit import * from .mathFunctions import * from .tlineFunctions import * from .io import * from .constants import * from .taper import * from .instances import * from .vectorFitting import * from .qfactor import * # Try to import vi, but if except if pyvisa not installed try: import vi from vi import * except(ImportError): pass # try to import data but if it fails whatever. it fails if some pickles # dont unpickle. but its not important try: from . import data except: pass ## built-in imports from copy import deepcopy as copy ## Shorthand Names F = Frequency N = Network NS = NetworkSet C = Circuit lat = load_all_touchstones # saf = save_all_figs saf = None stylely = None def setup_pylab(): try: import matplotlib except ImportError: print("matplotlib not found while setting up plotting") return False from . import plotting plotting.setup_matplotlib_plotting() global saf, stylely saf = plotting.save_all_figs stylely = plotting.stylely return True def setup_plotting(): plotting_environment = os.environ.get('SKRF_PLOT_ENV', "pylab").lower() if plotting_environment == "pylab": setup_pylab() elif plotting_environment == "pylab-skrf-style": if setup_pylab(): stylely() # elif some different plotting environment # set that up setup_plotting()
bsd-3-clause
8e9dd31aa203552bb08d273cd8c57cdb
20
75
0.707283
3.818182
false
false
false
false
scikit-rf/scikit-rf
skrf/media/rectangularWaveguide.py
1
12574
""" rectangularWaveguide (:mod:`skrf.media.rectangularWaveguide`) ================================================================ Represents a single mode of a homogeneously filled rectangular waveguide of cross-section `a` x `b`. The mode is determined by `mode-type` (`'te'` or `'tm'`) and mode indices ( `m` and `n` ). ==================================== ============= =============== Quantity Symbol Variable ==================================== ============= =============== Characteristic Wave Number :math:`k_0` :attr:`k0` Cut-off Wave Number :math:`k_c` :attr:`kc` Longitudinal Wave Number :math:`k_z` :attr:`gamma` Transverse Wave Number (a) :math:`k_x` :attr:`kx` Transverse Wave Number (b) :math:`k_y` :attr:`ky` Characteristic Impedance :math:`z_0` :attr:`Z0` ==================================== ============= =============== .. autosummary:: :toctree: generated/ RectangularWaveguide """ from ast import Num from numbers import Number from numpy.lib.arraysetops import unique from scipy.constants import epsilon_0, mu_0, pi, c from numpy import sqrt, exp, where import numpy as npy from .media import Media from ..data import materials from ..tlineFunctions import skin_depth from .freespace import Freespace from ..constants import NumberLike from typing import Union, TYPE_CHECKING if TYPE_CHECKING: from .. frequency import Frequency from .. network import Network class RectangularWaveguide(Media): r""" A single mode of a homogeneously filled rectangular waveguide. Parameters ---------- frequency : :class:`~skrf.frequency.Frequency` object frequency band of this transmission line medium z0 : number, array-like, or None the port impedance for media. Only needed if its different from the characteristic impedance of the transmission line. if z0 is None then will default to Z0. a : number, optional width of waveguide, in meters. Default is 1. b : number or None, optional height of waveguide, in meters. If `None` defaults to a/2. Default is None mode_type : ['te','tm'] mode type, transverse electric (te) or transverse magnetic (tm) to-z. where z is direction of propagation m : int mode index in 'a'-direction n : int mode index in 'b'-direction ep_r : number, array-like, filling material's relative permittivity mu_r : number, array-like filling material's relative permeability rho : number, array-like, string resistivity (ohm-m) of the conductor walls. If array-like must be same length as frequency. if str, it must be a key in :data:`skrf.data.materials`. roughness : number, or array-like surface roughness of the conductor walls in units of RMS deviation from surface \*args, \*\*kwargs : arguments, keyword arguments passed to :class:`~skrf.media.media.Media`'s constructor (:func:`~skrf.media.media.Media.__init__` Examples -------- Most common usage is standard aspect ratio (2:1) dominant mode, TE10 mode of wr10 waveguide can be constructed by >>> freq = rf.Frequency(75,110,101,'ghz') >>> rf.RectangularWaveguide(freq,a= 100*mil) """ def __init__(self, frequency: Union['Frequency', None] = None, z0: Union[NumberLike, None] = None, a: float = 1, b: Union[float, None] = None, mode_type: str = 'te', m: int = 1, n: int = 0, ep_r: Union[None, NumberLike] = 1, mu_r: Union[None, NumberLike] = 1, rho: Union[None, NumberLike] = None, roughness: Union[None, NumberLike] = None, *args, **kwargs): Media.__init__(self, frequency=frequency,z0=z0) if b is None: b = a/2. if mode_type.lower() not in ['te','tm']: raise ValueError('mode_type must be either \'te\' or \'tm\'') self.a = a self.b = b self.mode_type = mode_type.lower() self.m = m self.n = n self.ep_r = ep_r self.mu_r = mu_r self.rho = rho self.roughness = roughness def __str__(self): f=self.frequency output = \ 'Rectangular Waveguide Media. %i-%i %s. %i points'%\ (f.f_scaled[0],f.f_scaled[-1],f.unit, f.npoints) + \ '\n a= %.2em, b= %.2em'% \ (self.a,self.b) return output def __repr__(self): return self.__str__() @classmethod def from_Z0(cls, frequency: 'Frequency', Z0: NumberLike, f: Number, ep_r=1, mu_r=1, **kw) -> Media: """ Initialize from specified impedance at a given frequency, assuming the fundamental TE10 mode. Parameters ---------- frequency : Frequency Object Z0 : number /array characteristic impedance to create at `f` f : number frequency (in Hz) at which the resultant waveguide has the characteristic impedance Z0 ep_r : number, array-like, filling material's relative permittivity mu_r : number, array-like filling material's relative permeability """ mu = mu_0*mu_r ep = epsilon_0*ep_r w = 2*pi*f a =pi/(w*mu) * 1./sqrt(1/(Z0*1j)**2+ep/mu) kw.update(dict(frequency=frequency,a=a, m=1, n=0, ep_r=ep_r, mu_r=mu_r)) return cls(**kw) @property def ep(self) -> NumberLike: r""" The permittivity of the filling material. .. math: \varepsilon = \varepsilon_r \varepsilon_0 Returns ------- ep : number filling material's permittivity in F/m. """ return self.ep_r * epsilon_0 @property def mu(self) -> NumberLike: r""" The permeability of the filling material. .. math:: \mu = \mu_r \mu_0 Returns ------- mu : number filling material's permeability in H/m. """ return self.mu_r * mu_0 @property def k0(self) -> NumberLike: r""" Characteristic wave number. .. math:: k_0 = \frac{\omega}{v} = \omega \sqrt{\varepsilon_r \mu_r} Returns ------- k0 : number characteristic wave number """ return 2*pi*self.frequency.f*sqrt(self.ep * self.mu) @property def ky(self) -> NumberLike: r""" Eigenvalue in the `b` direction. Defined as .. math:: k_y = n \frac{\pi}{b} Returns ------- ky : number eigenvalue in `b` direction """ return self.n*pi/self.b @property def kx(self) -> NumberLike: r""" Eigenvalue in the 'a' direction. Defined as .. math:: k_x = m \frac{\pi}{a} Returns ------- kx : number eigenvalue in `a` direction """ return self.m*pi/self.a @property def kc(self) -> NumberLike: r""" Cut-off wave number. Defined as .. math:: k_c = \sqrt {k_x^2 + k_y^2} = \sqrt { {m \frac{\pi}{a}}^2 + {n \frac{\pi}{b}}^2} Returns ------- kc : number cut-off wavenumber """ return sqrt( self.kx**2 + self.ky**2) @property def f_cutoff(self) -> NumberLike: r""" cutoff frequency for this mode. .. math:: f_c = \frac{v}{2 \pi} \sqrt { {m \frac{\pi}{a}}^2 + {n \frac{\pi}{b}}^2} where :math:`v= 1/\sqrt{\varepsilon \mu}`. """ v = 1/sqrt(self.ep*self.mu) return v* self.kc/(2*npy.pi) @property def f_norm(self) -> NumberLike: """ Frequency vector normalized to cutoff. """ return self.frequency.f/self.f_cutoff @property def rho(self) -> NumberLike: """ Conductivity of sidewalls in ohm*m. Parameters ---------- val : float, array-like or str the conductivity in ohm*m. If array-like must be same length as self.frequency. if str, it must be a key in :data:`skrf.data.materials`. Examples --------- >>> wg.rho = 2.8e-8 >>> wg.rho = 2.8e-8 * ones(len(wg.frequency)) >>> wg.rho = 'al' >>> wg.rho = 'aluminum' """ if self.roughness != None: delta = skin_depth(self.frequency.f, self._rho, self.mu_r) k_w = 1. +exp(-(delta/(2*self.roughness))**1.6) return self._rho*k_w**2 return self._rho @rho.setter def rho(self, val: Union[NumberLike, str]): if isinstance(val, str): self._rho = materials[val.lower()]['resistivity(ohm*m)'] else: self._rho=val @property def lambda_guide(self) -> NumberLike: r""" Guide wavelength. .. math:: \lambda_g = \frac{2\pi}{\beta} The distance in which the phase of the field increases by 2 pi. See Also -------- k0 """ return 2*pi/self.beta @property def lambda_cutoff(self) -> NumberLike: r""" Cutoff wavelength. .. math:: \lambda_c = v/f_c where :math:`v= 1/\sqrt{\varepsilon \mu}` and :math:`f_c` the cut-off frequency. See Also -------- f_cutoff """ v = 1/sqrt(self.ep*self.mu) return v/self.f_cutoff @property def gamma(self) -> NumberLike: r""" The propagation constant (aka Longitudinal wave number). Defined as .. math:: k_z = \pm j \sqrt {k_0^2 - k_c^2} This is: * IMAGINARY for propagating modes * REAL for non-propagating modes, Returns ------- gamma : number The propagation constant """ ## haringtons form if False: #self.m==1 and self.n==0: fs = Freespace(frequency=self.frequency, ep_r=self.ep_r, mu_r=self.mu_r) g = where(self.f_norm>1., sqrt(1-self.f_norm**(-2))*fs.gamma, # cutton -1j*sqrt(1-self.f_norm**(2))*fs.gamma) # cutoff else: # TODO: fix this for lossy ep/mu (remove abs?) k0, kc = self.k0, self.kc g = 1j*sqrt(abs(k0**2 - kc**2)) * (k0>kc) +\ sqrt(abs(kc**2- k0**2))*(k0<kc) + \ 0*(kc==k0) g = g + self.alpha_c *(self.rho is not None) return g @property def alpha_c(self) -> NumberLike: r""" Loss due to finite conductivity and roughness of sidewalls. In units of np/m See property `rho` for setting conductivity. Effects of finite conductivity are taken from [#]_. If :attr:`roughness` is not None, then its effects the conductivity by .. math:: \sigma_c = \frac{\sigma}{k_w^2} where .. math:: k_w = 1 + e^{(-\delta/2h)^{1.6}} \delta = \mbox{skin depth} h = \mbox{surface roughness } This is taken from Ansoft HFSS help documents. References ---------- .. [#] Chapter 9, (eq 9.8.1) of Electromagnetic Waves and Antennas by Sophocles J. Orfanidis http://eceweb1.rutgers.edu/~orfanidi/ewa/ """ if self.rho is None: return 0 a,b,w,ep,rho,f_n = self.a, self.b, self.frequency.w, self.ep, \ self.rho, self.f_norm return 1./b * sqrt( (w*ep)/(2./rho) ) * (1+2.*b/a*(1/f_n)**2)/\ sqrt(1-(1/f_n)**2) @property def Z0(self) -> NumberLike: """ The characteristic impedance. The characteristic impedance depends of the mode ('te' or 'tm'). """ omega = self.frequency.w impedance_dict = {'te': 1j*omega*self.mu/(self.gamma), 'tm': -1j*self.gamma/(omega*self.ep),\ } return impedance_dict[self.mode_type]
bsd-3-clause
32b37e6bf38e5a8d2ababfaa6a1c895e
25.925054
100
0.507794
3.627813
false
false
false
false
scikit-rf/scikit-rf
skrf/vi/vna/nanovna_v2.py
1
17964
from . import abcvna import numpy as np import skrf from time import sleep # Communication commands and register addresses are listed in the user manual at # https://nanorfe.com/nanovna-v2-user-manual.html # See also `python/nanovna.py` in the NanoVNA project repository at https://github.com/nanovna-v2/NanoVNA2-firmware # # # COMMAND SUMMARY: # # No operation: # cmd = [0x00] # # Indicate; 1 byte reply (always 0x32) # cmd = [0x0d] # # Read 1 byte from address 0xAA; 1 byte reply # cmd = [0x10, 0xAA] # # Read 2 bytes from address 0xAA; 2 byte reply # cmd = [0x11, 0xAA] # # Read 4 bytes from address 0xAA; 4 byte reply # cmd = [0x12, 0xAA] # # Read 0xNN values from FIFO at address 0xAA; 0xNN byte reply # cmd = [0x18, 0xAA, 0xNN] # # Write 1 byte (0xBB) to address 0xAA; no reply # cmd = [0x20, 0xAA, 0xBB] # # Write 2 bytes (0xB0 0xB1) to addresses 0xAA and following; no reply # 0xB0 will be written to 0xAA; 0xB1 will be written to 0xAB # cmd = [0x21, 0xAA, 0xB0, 0xB1] # # Write 4 bytes (0xB0 to 0xB3) to addresses 0xAA and following; no reply # 0xB0 will be written to 0xAA; 0xB1 will be written to 0xAB; ... # cmd = [0x22, 0xAA, 0xB0, 0xB1, 0xB2, 0xB3] # # Write 8 bytes (0xB0 to 0xB7) to addresses 0xAA and following; no reply # 0xB0 will be written to 0xAA; 0xB1 will be written to 0xAB; ... # cmd = [0x23, 0xAA, 0xB0, 0xB1, ..., 0xB7] # # Write 0xNN bytes to FIFO at address 0xAA and following; no reply # cmd = [0x28, 0xAA, 0xNN, 0xB0, 0xB1, ..., 0xBNN] # # # FIFO DATA FORMAT (encoding: little endian): # 0x03 to 0x00: real part of channel 0 outgoing wave; fwd0re (4 bytes; int32) # 0x07 to 0x04: imaginary part of channel 0 outgoing wave; fwd0im (4 bytes; int32) # 0x0b to 0x08: real part of channel 0 incoming wave; rev0re (4 bytes; int32) # 0x0f to 0x0c: imaginary part of channel 0 incoming wave; rev0im (4 bytes; int32) # 0x13 to 0x10: real part of channel 1 incoming wave; rev1re (4 bytes; int32) # 0x17 to 0x14: imaginary part of channel 1 incoming wave; rev1im (4 bytes; int32) # 0x19 0x18: frequency index of the sample (0 to sweep_points - 1); 2 bytes; uint16 # # # REGISTER ADDRESSES (encoding: little endian): # 0x07 to 0x00: sweep start frequency in Hz (8 bytes; uint64) # 0x17 to 0x10: sweep step in Hz (8 bytes; uint64) # 0x21 0x20: number of sweep frequency points (2 bytes; uint16) # 0x23 0x22: number of data points to output for each frequency (2 bytes; uint16) class NanoVNAv2(abcvna.VNA): """ Python class for NanoVNA V2 network analyzers [#website]_. Parameters ---------- address : str SCPI identifier of the serial port for the NanoVNA. For example `'ASRL1::INSTR'` for `COM1` on Windows, or `'ASRL/dev/ttyACM0::INSTR'` for `/dev/ttyACM0` on Linux. Examples -------- Load and initialize NanoVNA on `COM1` (Windows OS, see Device Manager): >>> from skrf.vi import vna >>> nanovna = vna.NanoVNAv2('ASRL1::INSTR') Load and initialize NanoVNA on `/dev/ttyACM0` (Linux OS, see dmesg): >>> from skrf.vi import vna >>> nanovna = vna.NanoVNAv2('ASRL/dev/ttyACM0::INSTR') Configure frequency sweep (from 20 MHz to 4 GHz with 200 points, i.e. 20 MHz step): >>> nanovna.set_frequency_sweep(20e6, 4e9, 200) Get S11 and S21 as NumPy arrays: >>> s11, s21 = nanovna.get_s11_s21() Get list of available traces (will always return both channels, regardless of trace configuration): >>> traces_avail = nanovna.get_list_of_traces() Get 1-port networks of one or both of the traces listed in `get_list_of_traces()`: >>> nws_all = nanovna.get_traces(traces_avail) >>> nw_s11 = nws_all[0] >>> nw_s21 = nws_all[1] Get S11 as a 1-port skrf.Network: >>> nw_1 = nanovna.get_snp_network(ports=(0,)) Get S11 and S12 as s 2-port skrf.Network (incomplete with S21=S22=0): >>> nw_2 = nanovna.get_snp_network(ports=(0, 1)) Get S21 and S22 in a 2-port skrf.Network (incomplete with S11=S12=0): >>> nw_3 = nanovna.get_snp_network(ports=(1, 0)) References ---------- .. [#website] Website of NanoVNA V2: https://nanorfe.com/nanovna-v2.html """ def __init__(self, address: str = 'ASRL/dev/ttyACM0::INSTR'): super().__init__(address=address, visa_library='@py') self._protocol_reset() self._frequency = np.linspace(1e6, 10e6, 101) self.set_frequency_sweep(1e6, 10e6, 101) def idn(self) -> str: """ Returns the identification string of the device. Returns ------- str Identification string, e.g. `NanoVNA_v2`. """ # send 1-byte READ (0x10) of address 0xf0 to retrieve device variant code self.resource.write_raw([0x10, 0xf0]) v_byte = self.resource.read_bytes(1) v = int.from_bytes(v_byte, byteorder='little') if v == 2: return 'NanoVNA_v2' else: return f'Unknown device, got deviceVariant={v}' def reset(self): raise NotImplementedError def wait_until_finished(self): raise NotImplementedError def _protocol_reset(self): # send 8x NOP (0x00) to reset the communication protocol self.resource.write_raw([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) def get_s11_s21(self) -> (np.ndarray, np.ndarray): """ Returns individual NumPy arrays of the measured data of the sweep. Being a 1.5-port analyzer, the results only include :math:`S_{1,1}` and :math:`S_{2,1}`. Returns ------- tuple[np.ndarray, np.ndarray] List of NumPy arrays with :math:`S_{1,1}` and :math:`S_{2,1}`. Notes ----- Regardless of the calibration state of the NanoVNA, the results returned by this method are always raw, i.e. uncalibrated. The user needs to apply a manual calibration in postprocessing, if required. See Also -------- set_frequency_sweep get_traces :mod:`Calibration` """ # data is continuously being sampled and stored in the FIFO (address 0x30) # writing any value to 0x30 clears the FIFO, which enables on-demand readings f_points = len(self._frequency) # write any byte to register 0x30 to clear FIFO self.resource.write_raw([0x20, 0x30, 0x00]) data_raw = [] f_remaining = f_points while f_remaining > 0: # can only read 255 values in one take if f_remaining > 255: len_segment = 255 else: len_segment = f_remaining f_remaining = f_remaining - len_segment # read 'len_segment' values from FIFO (32 * len_segment bytes) self.resource.write_raw([0x18, 0x30, len_segment]) data_raw.extend(self.resource.read_bytes(32 * len_segment)) # parse FIFO data data_s11 = np.zeros(f_points, dtype=complex) data_s21 = np.zeros_like(data_s11) for i in range(f_points): i_start = i * 32 i_stop = (i + 1) * 32 data_chunk = data_raw[i_start:i_stop] fwd0re = int.from_bytes(data_chunk[0:4], 'little', signed=True) fwd0im = int.from_bytes(data_chunk[4:8], 'little', signed=True) rev0re = int.from_bytes(data_chunk[8:12], 'little', signed=True) rev0im = int.from_bytes(data_chunk[12:16], 'little', signed=True) rev1re = int.from_bytes(data_chunk[16:20], 'little', signed=True) rev1im = int.from_bytes(data_chunk[20:24], 'little', signed=True) freqIndex = int.from_bytes(data_chunk[24:26], 'little', signed=False) a1 = complex(fwd0re, fwd0im) b1 = complex(rev0re, rev0im) b2 = complex(rev1re, rev1im) data_s11[freqIndex] = b1 / a1 data_s21[freqIndex] = b2 / a1 return data_s11, data_s21 def set_frequency_sweep(self, start_freq: float, stop_freq: float, num_points: int = 201, **kwargs) -> None: """ Configures the frequency sweep. Only linear spacing is supported. Parameters ---------- start_freq : float Start frequency in Hertz stop_freq : float Stop frequency in Hertz num_points : int, optional Number of frequencies in the sweep. kwargs : dict, optional Returns ------- None """ f_step = 0.0 if num_points > 1: f_step = (stop_freq - start_freq) / (num_points - 1) self._frequency = np.linspace(start_freq, stop_freq, num_points) # set f_start by writing 8 bytes (cmd=0x23) to (0x00...0x07) cmd = b'\x23\x00' + int.to_bytes(int(start_freq), 8, byteorder='little', signed=False) self.resource.write_raw(cmd) # set f_step by writing 8 bytes (cmd=0x23) to (0x10...0x17) cmd = b'\x23\x10' + int.to_bytes(int(f_step), 8, byteorder='little', signed=False) self.resource.write_raw(cmd) # set f_points by writing 2 bytes (cmd=0x21) to (0x20 0x21) cmd = b'\x21\x20' + int.to_bytes(int(num_points), 2, byteorder='little', signed=False) self.resource.write_raw(cmd) # wait 1s for changes to be effective sleep(1) def get_list_of_traces(self, **kwargs) -> list: """ Returns a list of dictionaries describing all available measurement traces. In case of the NanoVNA_v2, this is just a static list of the two measurement channels `[{'channel': 0, 'parameter': 'S11'}, {'channel': 1, 'parameter': 'S21'}]`. Parameters ---------- kwargs : dict, optional Returns ------- list """ return [{'channel': 0, 'parameter': 'S11'}, {'channel': 1, 'parameter': 'S21'}] def get_traces(self, traces: list = None, **kwargs) -> list: """ Returns the data of the traces listed in `traces` as 1-port networks. Parameters ---------- traces: list of dict, optional Traces selected from :func:`get_list_of_traces`. kwargs: list Returns ------- list of skrf.Network List with trace data as individual 1-port networks. """ data_s11, data_s21 = self.get_s11_s21() frequency = skrf.Frequency.from_f(self._frequency, unit='hz') nw_s11 = skrf.Network(frequency=frequency, s=data_s11, name='Trace0') nw_s21 = skrf.Network(frequency=frequency, s=data_s21, name='Trace1') traces_valid = self.get_list_of_traces() networks = [] for trace in traces: if trace in traces_valid: if trace['channel'] == 0: networks.append(nw_s11) elif trace['channel'] == 1: networks.append(nw_s21) return networks def get_snp_network(self, ports: tuple = (0, 1), **kwargs) -> skrf.Network: """ Returns a :math:`N`-port network containing the measured parameters at the positions specified in `ports`. The remaining responses will be 0. The rows and the column to be populated in the network are selected implicitly based on the position and the order of the entries in `ports`. See the parameter desciption for details. This function can be useful for sliced measurements of larger networks with an analyzer that does not have enough ports, for example when measuring a 3-port (e.g a balun) with the 1.5-port NanoVNA (example below). Parameters ---------- ports: tuple of int or None, optional Specifies the position and order of the measured responses in the returned `N`-port network. Valid entries are `0`, `1`, or `None`. The length of the tuple defines the size `N` of the network, the entries define the type (forward/reverse) and position (indices of the rows and the column to be populated). Number `0` refers to the source port (`s11` from the NanoVNA), `1` refers to the receiver port (`s21` from the NanoVNA), and `None` skips this position (required to increase `N`). For `N>1`, the colum index is determined by the position of the source port `0` in `ports`. See examples below. kwargs: list Additional parameters will be ignored. Returns ------- skrf.Network Examples -------- To get the measured S-matrix of a 3-port from six individual measurements, the slices (s11, s21), (s11, s31), (s12, s22), (s22, s32), (s13, s33), and (s23, s33) can be obtained directly as (incomplete) 3-port networks with the results stored at the correct positions, which helps combining them afterwards. >>> from skrf.vi import vna >>> nanovna = vna.NanoVNAv2() 1st slice: connect VNA_P1=P1 and VNA_P2=P2 to measure s11 and s21: >>> nw_s1 = nanovna.get_snp_network(ports=(0, 1, None)) This will return a 3-port network with [[s11_vna, 0, 0], [s21_vnas, 0, 0], [0, 0, 0]]. 2nd slice: connect VNA_P1=P1 and VNA_P2=P3 to measure s11 and s31: >>> nw_s2 = nanovna.get_snp_network(ports=(0, None, 1)) This will return a 3-port network with [[s11_vna, 0, 0], [0, 0, 0], [s21_vna, 0, 0]]. 3rd slice: connect VNA_P1=P2 and VNA_P2=P1 to measure s22 and s12: >>> nw_s3 = nanovna.get_snp_network(ports=(1, 0, None)) This will return a 3-port network with [[0, s21_vna, 0], [0, s11_vna, 0], [0, 0, 0]]. 4th slice: connect VNA_P1=P2 and VNA_P2=P3 to measure s22 and s32: >>> nw_s4 = nanovna.get_snp_network(ports=(None, 0, 1)) This will return a 3-port network with [[0, 0, 0], [0, s11_vna, 0], [0, s21_vna, 0]]. 5th slice: connect VNA_P1=P3 and VNA_P2=P1 to measure s13 and s33: >>> nw_s5 = nanovna.get_snp_network(ports=(1, None, 0)) This will return a 3-port network with [[0, 0, s21_vna], [0, 0, 0], [0, 0, s11_vna]]. 6th slice: connect VNA_P1=P3 and VNA_P2=P2 to measure s23 and s33: >>> nw_s6 = nanovna.get_snp_network(ports=(None, 1, 0)) This will return a 3-port network with [[0, 0, 0], [0, 0, s21_vna], [0, 0, s11_vna]]. Now, the six incomplete networks can simply be added to get to complete network of the 3-port: >>> nw = nw_s1 + nw_s2 + nw_s3 + nw_s4 + nw_s5 + nw_s6 The reflection coefficients s11, s22, s33 have been measured twice, so the sum still needs to be divided by 2 to get the correct result: >>> nw.s[:, 0, 0] = 0.5 * nw.s[:, 0, 0] >>> nw.s[:, 1, 1] = 0.5 * nw.s[:, 1, 1] >>> nw.s[:, 2, 2] = 0.5 * nw.s[:, 2, 2] This gives the average, but you could also replace it with just one of the measurements. This function can also be used for smaller networks: Get a 1-port network with `s11`, i.e. [s11_meas]: >>> nw = nanovna.get_snp_network(ports=(0, )) Get a 1-port network with `s21`, i.e. [s21_meas]: >>> nw = nanovna.get_snp_network(ports=(1, )) Get a 2-port network (incomplete) with `(s11, s21) = measurement, (s12, S22) = 0`, i.e. [[s11_meas, 0], [s21_meas, 0]]: >>> nw = nanovna.get_snp_network(ports=(0, 1)) Get a 2-port network (incomplete) with `(s12, s22) = measurement, (s11, S21) = 0`, i.e. [[0, s21_meas], [0, s11_meas]]: >>> nw = nanovna.get_snp_network(ports=(1, 0)) """ # load s11, s21 from NanoVNA data_s11, data_s21 = self.get_s11_s21() frequency = skrf.Frequency.from_f(self._frequency, unit='hz') # prepare empty S matrix to be populated s = np.zeros((len(frequency), len(ports), len(ports)), dtype=complex) # get trace indices from 'ports' (without None) rows = [] col = -1 for i_port, port in enumerate(ports): if port is not None: # get row indices directly from entries in `ports` rows.append(i_port) # try to get column index from from position of `0` entry (if present) if port == 0: col = i_port if col == -1: # `0` entry was not present to specify the column index if len(ports) == 1: # not a problem; it's a 1-port col = 0 else: # problem: column index is ambiguous raise ValueError('Source port index `0` is missing in `ports` with length > 1. Column index is ambiguous.') # populate N-port network with s11 and s21 k = 0 for _, port in enumerate(ports): if port is not None: if port == 0: s[:, rows[k], col] = data_s11 elif port == 1: s[:, rows[k], col] = data_s21 else: raise ValueError(f'Invalid port index `{port}` in `ports`') k += 1 return skrf.Network(frequency=frequency, s=s) def get_switch_terms(self, ports=(1, 2), **kwargs): raise NotImplementedError @property def s11(self) -> skrf.Network: """ Measures :math:`S_{1,1}` and returns it as a 1-port Network. Returns ------- skrf.Network """ traces = self.get_list_of_traces() ntwk = self.get_traces([traces[0]])[0] ntwk.name = 'NanoVNA_S11' return ntwk @property def s21(self) -> skrf.Network: """ Measures :math:`S_{2,1}` and returns it as a 1-port Network. Returns ------- skrf.Network """ traces = self.get_list_of_traces() ntwk = self.get_traces([traces[1]])[0] ntwk.name = 'NanoVNA_S21' return ntwk
bsd-3-clause
3985123d9dfbe52a8686a3ceca8c37eb
35.072289
123
0.588232
3.288905
false
false
false
false
wagtail/wagtail
wagtail/utils/version.py
4
1478
# This file is heavily inspired by django.utils.version def get_version(version): """Return a PEP 440-compliant version number from VERSION.""" version = get_complete_version(version) # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|rc}N - for alpha, beta, and rc releases main = get_main_version(version) sub = "" if version[3] != "final": mapping = {"alpha": "a", "beta": "b", "rc": "rc", "dev": ".dev"} sub = mapping[version[3]] + str(version[4]) return main + sub def get_main_version(version=None): """Return main version (X.Y[.Z]) from VERSION.""" version = get_complete_version(version) parts = 2 if version[2] == 0 else 3 return ".".join(str(x) for x in version[:parts]) def get_complete_version(version=None): """ Return a tuple of the Wagtail version. If version argument is non-empty, check for correctness of the tuple provided. """ if version is None: from wagtail import VERSION as version else: assert len(version) == 5 assert version[3] in ("dev", "alpha", "beta", "rc", "final") return version def get_semver_version(version): "Returns the semver version (X.Y.Z[-(alpha|beta)]) from VERSION" main = ".".join(str(x) for x in version[:3]) sub = "" if version[3] != "final": sub = "-{}.{}".format(*version[3:]) return main + sub
bsd-3-clause
875e0fad6fb8fc1ea4225198ce7f72f1
27.980392
76
0.602842
3.485849
false
false
false
false
wagtail/wagtail
wagtail/test/snippets/migrations/0001_initial.py
4
2139
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="AlphaSnippet", fields=[ ( "id", models.AutoField( serialize=False, verbose_name="ID", auto_created=True, primary_key=True, ), ), ("text", models.CharField(max_length=255)), ], options={}, bases=(models.Model,), ), migrations.CreateModel( name="RegisterDecorator", fields=[ ( "id", models.AutoField( serialize=False, verbose_name="ID", auto_created=True, primary_key=True, ), ), ], options={}, bases=(models.Model,), ), migrations.CreateModel( name="RegisterFunction", fields=[ ( "id", models.AutoField( serialize=False, verbose_name="ID", auto_created=True, primary_key=True, ), ), ], options={}, bases=(models.Model,), ), migrations.CreateModel( name="ZuluSnippet", fields=[ ( "id", models.AutoField( serialize=False, verbose_name="ID", auto_created=True, primary_key=True, ), ), ("text", models.CharField(max_length=255)), ], options={}, bases=(models.Model,), ), ]
bsd-3-clause
9291d285eb2167160823cee3f8903a84
27.144737
59
0.338943
6.2
false
false
false
false
wagtail/wagtail
wagtail/contrib/settings/tests/site_specific/base.py
4
1027
from django.http import HttpRequest from wagtail.models import Page, Site from wagtail.test.testapp.models import TestSiteSetting class SiteSettingsTestMixin: def setUp(self): root = Page.objects.first() other_home = Page(title="Other Root") root.add_child(instance=other_home) self.default_site = Site.objects.get(is_default_site=True) self.default_settings = TestSiteSetting.objects.create( title="Site title", email="initial@example.com", site=self.default_site ) self.other_site = Site.objects.create(hostname="other", root_page=other_home) self.other_settings = TestSiteSetting.objects.create( title="Other title", email="other@other.com", site=self.other_site ) def get_request(self, site=None): if site is None: site = self.default_site request = HttpRequest() request.META["HTTP_HOST"] = site.hostname request.META["SERVER_PORT"] = site.port return request
bsd-3-clause
e9cffb7033c5a617cb306b23d27ca51a
34.413793
85
0.657254
3.965251
false
true
false
false
wagtail/wagtail
wagtail/admin/views/mixins.py
4
11492
import csv import datetime from collections import OrderedDict from io import BytesIO from django.core.exceptions import FieldDoesNotExist from django.http import FileResponse, StreamingHttpResponse from django.utils import timezone from django.utils.dateformat import Formatter from django.utils.encoding import force_str from django.utils.formats import get_format from openpyxl import Workbook from openpyxl.cell import WriteOnlyCell from wagtail.coreutils import multigetattr class Echo: """An object that implements just the write method of the file-like interface.""" def write(self, value): """Write the value by returning it, instead of storing in a buffer.""" return value.encode("UTF-8") def list_to_str(value): return force_str(", ".join(value)) class ExcelDateFormatter(Formatter): data = None # From: https://docs.djangoproject.com/en/stable/ref/templates/builtins/#date # To: https://support.microsoft.com/en-us/office/format-numbers-as-dates-or-times-418bd3fe-0577-47c8-8caa-b4d30c528309#bm2 _formats = { # Day of the month, 2 digits with leading zeros. "d": "dd", # Day of the month without leading zeros. "j": "d", # Day of the week, textual, 3 letters. "D": "ddd", # Day of the week, textual, full. "l": "dddd", # English ordinal suffix for the day of the month, 2 characters. "S": "", # Not supported in Excel # Day of the week, digits without leading zeros. "w": "", # Not supported in Excel # Day of the year. "z": "", # Not supported in Excel # ISO-8601 week number of year, with weeks starting on Monday. "W": "", # Not supported in Excel # Month, 2 digits with leading zeros. "m": "mm", # Month without leading zeros. "n": "m", # Month, textual, 3 letters. "M": "mmm", # Month, textual, 3 letters, lowercase. (Not supported in Excel) "b": "mmm", # Month, locale specific alternative representation usually used for long date representation. "E": "mmmm", # Not supported in Excel # Month, textual, full. "F": "mmmm", # Month abbreviation in Associated Press style. Proprietary extension. "N": "mmm.", # Approximation, wrong for May # Number of days in the given month. "t": "", # Not supported in Excel # Year, 2 digits with leading zeros. "y": "yy", # Year, 4 digits with leading zeros. "Y": "yyyy", # Whether it's a leap year. "L": "", # Not supported in Excel # ISO-8601 week-numbering year. "o": "yyyy", # Approximation, same as Y # Hour, 12-hour format without leading zeros. "g": "h", # Only works when combined with AM/PM, 24-hour format is used otherwise # Hour, 24-hour format without leading zeros. "G": "hH", # Hour, 12-hour format with leading zeros. "h": "hh", # Only works when combined with AM/PM, 24-hour format is used otherwise # Hour, 24-hour format with leading zeros. "H": "hh", # Minutes. "i": "mm", # Seconds. "s": "ss", # Microseconds. "u": ".00", # Only works when combined with ss # 'a.m.' or 'p.m.'. "a": "AM/PM", # Approximation, uses AM/PM and only works when combined with h/hh # AM/PM. "A": "AM/PM", # Only works when combined with h/hh # Time, in 12-hour hours and minutes, with minutes left off if they’re zero. "f": "h:mm", # Approximation, uses 24-hour format and minutes are never left off # Time, in 12-hour hours, minutes and ‘a.m.’/’p.m.’, with minutes left off if they’re zero and the special-case strings ‘midnight’ and ‘noon’ if appropriate. "P": "h:mm AM/PM", # Approximation, minutes are never left off, no special case strings # Timezone name. "e": "", # Not supported in Excel # Daylight saving time, whether it’s in effect or not. "I": "", # Not supported in Excel # Difference to Greenwich time in hours. "O": "", # Not supported in Excel # Time zone of this machine. "T": "", # Not supported in Excel # Timezone offset in seconds. "Z": "", # Not supported in Excel # ISO 8601 format. "c": "yyyy-mm-ddThh:mm:ss.00", # RFC 5322 formatted date. "r": "ddd, d mmm yyyy hh:mm:ss", # Seconds since the Unix epoch. "U": "", # Not supported in Excel } def get(self): format = get_format("SHORT_DATETIME_FORMAT") return self.format(format) def __getattr__(self, name): if name in self._formats: return lambda: self._formats[name] raise AttributeError( f"'{type(self).__name__}' object has no attribute '{name}'" ) class SpreadsheetExportMixin: """A mixin for views, providing spreadsheet export functionality in csv and xlsx formats""" FORMAT_XLSX = "xlsx" FORMAT_CSV = "csv" FORMATS = (FORMAT_XLSX, FORMAT_CSV) # A list of fields or callables (without arguments) to export from each item in the queryset (dotted paths allowed) list_export = [] # A dictionary of custom preprocessing functions by field and format (expected value would be of the form {field_name: {format: function}}) # If a valid field preprocessing function is found, any applicable value preprocessing functions will not be used custom_field_preprocess = {} # A dictionary of preprocessing functions by value class and format custom_value_preprocess = { datetime.datetime: { FORMAT_XLSX: lambda value: ( value if timezone.is_naive(value) else timezone.make_naive(value, timezone.utc) ) }, (datetime.date, datetime.time): {FORMAT_XLSX: None}, list: {FORMAT_CSV: list_to_str, FORMAT_XLSX: list_to_str}, } # A dictionary of column heading overrides in the format {field: heading} export_headings = {} def get_filename(self): """Gets the base filename for the exported spreadsheet, without extensions""" return "spreadsheet-export" def to_row_dict(self, item): """Returns an OrderedDict (in the order given by list_export) of the exportable information for a model instance""" row_dict = OrderedDict( (field, multigetattr(item, field)) for field in self.list_export ) return row_dict def get_preprocess_function(self, field, value, export_format): """Returns the preprocessing function for a given field name, field value, and export format""" # Try to find a field specific function and return it format_dict = self.custom_field_preprocess.get(field, {}) if export_format in format_dict: return format_dict[export_format] # Otherwise check for a value class specific function for value_classes, format_dict in self.custom_value_preprocess.items(): if isinstance(value, value_classes) and export_format in format_dict: return format_dict[export_format] # Finally resort to force_str to prevent encoding errors return force_str def preprocess_field_value(self, field, value, export_format): """Preprocesses a field value before writing it to the spreadsheet""" preprocess_function = self.get_preprocess_function(field, value, export_format) if preprocess_function is not None: return preprocess_function(value) else: return value def generate_xlsx_row(self, worksheet, row_dict, date_format=None): """Generate cells to append to the worksheet""" for field, value in row_dict.items(): cell = WriteOnlyCell( worksheet, self.preprocess_field_value(field, value, self.FORMAT_XLSX) ) if date_format and isinstance(value, datetime.datetime): cell.number_format = date_format yield cell def write_csv_row(self, writer, row_dict): return writer.writerow( { field: self.preprocess_field_value(field, value, self.FORMAT_CSV) for field, value in row_dict.items() } ) def get_heading(self, queryset, field): """Get the heading label for a given field for a spreadsheet generated from queryset""" heading_override = self.export_headings.get(field) if heading_override: return force_str(heading_override) try: return force_str(queryset.model._meta.get_field(field).verbose_name.title()) except (AttributeError, FieldDoesNotExist): return force_str(field) def stream_csv(self, queryset): """Generate a csv file line by line from queryset, to be used in a StreamingHTTPResponse""" writer = csv.DictWriter(Echo(), fieldnames=self.list_export) yield writer.writerow( {field: self.get_heading(queryset, field) for field in self.list_export} ) for item in queryset: yield self.write_csv_row(writer, self.to_row_dict(item)) def write_xlsx(self, queryset, output): """Write an xlsx workbook from a queryset""" workbook = Workbook(write_only=True, iso_dates=True) worksheet = workbook.create_sheet(title="Sheet1") worksheet.append( self.get_heading(queryset, field) for field in self.list_export ) date_format = ExcelDateFormatter().get() for item in queryset: worksheet.append( self.generate_xlsx_row( worksheet, self.to_row_dict(item), date_format=date_format ) ) workbook.save(output) def write_xlsx_response(self, queryset): """Write an xlsx file from a queryset and return a FileResponse""" output = BytesIO() self.write_xlsx(queryset, output) output.seek(0) return FileResponse( output, as_attachment=True, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename=f"{self.get_filename()}.xlsx", ) def write_csv_response(self, queryset): stream = self.stream_csv(queryset) response = StreamingHttpResponse(stream, content_type="text/csv") response["Content-Disposition"] = 'attachment; filename="{}.csv"'.format( self.get_filename() ) return response def as_spreadsheet(self, queryset, spreadsheet_format): """Return a response with a spreadsheet representing the exported data from queryset, in the format specified""" if spreadsheet_format == self.FORMAT_CSV: return self.write_csv_response(queryset) elif spreadsheet_format == self.FORMAT_XLSX: return self.write_xlsx_response(queryset) def get_export_url(self, format): params = self.request.GET.copy() params["export"] = format return self.request.path + "?" + params.urlencode() @property def xlsx_export_url(self): return self.get_export_url("xlsx") @property def csv_export_url(self): return self.get_export_url("csv")
bsd-3-clause
0a1f4c9b160265d1158fbaf6b037b696
38.965157
165
0.617786
4.048712
false
false
false
false
wagtail/wagtail
wagtail/test/snippets/migrations/0008_filterablesnippet.py
4
1189
# Generated by Django 4.0.5 on 2022-07-18 07:15 from django.db import migrations, models import wagtail.search.index class Migration(migrations.Migration): dependencies = [ ("snippetstests", "0007_translatablesnippet"), ] operations = [ migrations.CreateModel( name="FilterableSnippet", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("text", models.CharField(max_length=255)), ( "country_code", models.CharField( choices=[ ("ID", "Indonesia"), ("PH", "Philippines"), ("UK", "United Kingdom"), ], max_length=2, ), ), ], bases=(wagtail.search.index.Indexed, models.Model), ), ]
bsd-3-clause
232000d6ce685c0c10b11798ee286038
28
63
0.385198
5.429224
false
false
false
false
wagtail/wagtail
wagtail/contrib/table_block/blocks.py
4
6786
import json from django import forms from django.template.loader import render_to_string from django.utils import translation from django.utils.functional import cached_property from django.utils.translation import gettext as _ from wagtail.admin.staticfiles import versioned_static from wagtail.blocks import FieldBlock from wagtail.telepath import register from wagtail.widget_adapters import WidgetAdapter DEFAULT_TABLE_OPTIONS = { "minSpareRows": 0, "startRows": 3, "startCols": 3, "colHeaders": False, "rowHeaders": False, "contextMenu": [ "row_above", "row_below", "---------", "col_left", "col_right", "---------", "remove_row", "remove_col", "---------", "undo", "redo", ], "editor": "text", "stretchH": "all", "height": 108, "renderer": "text", "autoColumnSize": False, } class TableInput(forms.HiddenInput): def __init__(self, table_options=None, attrs=None): self.table_options = table_options super().__init__(attrs=attrs) @cached_property def media(self): return forms.Media( css={ "all": [ versioned_static( "table_block/css/vendor/handsontable-6.2.2.full.min.css" ), ] }, js=[ versioned_static( "table_block/js/vendor/handsontable-6.2.2.full.min.js" ), versioned_static("table_block/js/table.js"), ], ) class TableInputAdapter(WidgetAdapter): js_constructor = "wagtail.widgets.TableInput" def js_args(self, widget): strings = { "Row header": _("Row header"), "Display the first row as a header.": _( "Display the first row as a header." ), "Column header": _("Column header"), "Display the first column as a header.": _( "Display the first column as a header." ), "Table caption": _("Table caption"), "A heading that identifies the overall topic of the table, and is useful for screen reader users": _( "A heading that identifies the overall topic of the table, and is useful for screen reader users" ), "Table": _("Table"), } return [ widget.table_options, strings, ] register(TableInputAdapter(), TableInput) class TableBlock(FieldBlock): def __init__(self, required=True, help_text=None, table_options=None, **kwargs): """ CharField's 'label' and 'initial' parameters are not exposed, as Block handles that functionality natively (via 'label' and 'default') CharField's 'max_length' and 'min_length' parameters are not exposed as table data needs to have arbitrary length """ self.table_options = self.get_table_options(table_options=table_options) self.field_options = {"required": required, "help_text": help_text} super().__init__(**kwargs) @cached_property def field(self): return forms.CharField( widget=TableInput(table_options=self.table_options), **self.field_options ) def value_from_form(self, value): return json.loads(value) def value_for_form(self, value): return json.dumps(value) def get_form_state(self, value): # pass state to frontend as a JSON-ish dict - do not serialise to a JSON string return value def is_html_renderer(self): return self.table_options["renderer"] == "html" def get_searchable_content(self, value): content = [] if value: for row in value.get("data", []): content.extend([v for v in row if v]) return content def render(self, value, context=None): template = getattr(self.meta, "template", None) if template and value: table_header = ( value["data"][0] if value.get("data", None) and len(value["data"]) > 0 and value.get("first_row_is_table_header", False) else None ) first_col_is_header = value.get("first_col_is_header", False) if context is None: new_context = {} else: new_context = dict(context) new_context.update( { "self": value, self.TEMPLATE_VAR: value, "table_header": table_header, "first_col_is_header": first_col_is_header, "html_renderer": self.is_html_renderer(), "table_caption": value.get("table_caption"), "data": value["data"][1:] if table_header else value.get("data", []), } ) if value.get("cell"): new_context["classnames"] = {} for meta in value["cell"]: if "className" in meta: new_context["classnames"][(meta["row"], meta["col"])] = meta[ "className" ] return render_to_string(template, new_context) else: return self.render_basic(value or "", context=context) def get_table_options(self, table_options=None): """ Return a dict of table options using the defaults unless custom options provided table_options can contain any valid handsontable options: https://handsontable.com/docs/6.2.2/Options.html contextMenu: if value from table_options is True, still use default language: if value is not in table_options, attempt to get from environment """ collected_table_options = DEFAULT_TABLE_OPTIONS.copy() if table_options is not None: if table_options.get("contextMenu", None) is True: # explicitly check for True, as value could also be array # delete to ensure the above default is kept for contextMenu del table_options["contextMenu"] collected_table_options.update(table_options) if "language" not in collected_table_options: # attempt to gather the current set language of not provided language = translation.get_language() collected_table_options["language"] = language return collected_table_options class Meta: default = None template = "table_block/blocks/table.html" icon = "table"
bsd-3-clause
981024d4ffa80081e34e0ae4ba3157b0
31.941748
113
0.549808
4.420847
false
false
false
false
wagtail/wagtail
wagtail/users/migrations/0004_capitalizeverbose.py
4
1389
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("wagtailusers", "0003_add_verbose_names"), ] operations = [ migrations.AlterModelOptions( name="userprofile", options={"verbose_name": "user profile"}, ), migrations.AlterField( model_name="userprofile", name="approved_notifications", field=models.BooleanField( default=True, help_text="Receive notification when your page edit is approved", verbose_name="approved notifications", ), ), migrations.AlterField( model_name="userprofile", name="rejected_notifications", field=models.BooleanField( default=True, help_text="Receive notification when your page edit is rejected", verbose_name="rejected notifications", ), ), migrations.AlterField( model_name="userprofile", name="submitted_notifications", field=models.BooleanField( default=True, help_text="Receive notification when a page is submitted for moderation", verbose_name="submitted notifications", ), ), ]
bsd-3-clause
f3ee47cd89b95e86dc0b70e5aa878550
31.302326
89
0.548596
5.533865
false
false
false
false
wagtail/wagtail
wagtail/admin/panels.py
3
46535
import functools from warnings import warn from django import forms from django.apps import apps from django.conf import settings from django.contrib.auth import get_user_model from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured from django.core.signals import setting_changed from django.dispatch import receiver from django.forms import Media from django.forms.formsets import DELETION_FIELD_NAME, ORDERING_FIELD_NAME from django.forms.models import fields_for_model from django.utils.functional import cached_property from django.utils.safestring import mark_safe from django.utils.text import format_lazy from django.utils.translation import gettext_lazy from modelcluster.models import get_serializable_data_for_fields from wagtail.admin import compare from wagtail.admin.forms.comments import CommentForm from wagtail.admin.staticfiles import versioned_static from wagtail.admin.templatetags.wagtailadmin_tags import avatar_url, user_display_name from wagtail.admin.ui.components import Component from wagtail.admin.widgets import AdminPageChooser from wagtail.admin.widgets.datetime import AdminDateTimeInput from wagtail.blocks import BlockField from wagtail.coreutils import safe_snake_case from wagtail.models import COMMENTS_RELATION_NAME, DraftStateMixin, Page from wagtail.utils.decorators import cached_classmethod from wagtail.utils.deprecation import RemovedInWagtail50Warning # DIRECT_FORM_FIELD_OVERRIDES, FORM_FIELD_OVERRIDES are imported for backwards # compatibility, as people are likely importing them from here and then # appending their own overrides from .forms.models import ( # NOQA DIRECT_FORM_FIELD_OVERRIDES, FORM_FIELD_OVERRIDES, WagtailAdminDraftStateFormMixin, WagtailAdminModelForm, formfield_for_dbfield, ) from .forms.pages import WagtailAdminPageForm def get_form_for_model( model, form_class=WagtailAdminModelForm, **kwargs, ): """ Construct a ModelForm subclass using the given model and base form class. Any additional keyword arguments are used to populate the form's Meta class. """ # This is really just Django's modelform_factory, tweaked to accept arbitrary kwargs. meta_class_attrs = kwargs meta_class_attrs["model"] = model # The kwargs passed here are expected to come from EditHandler.get_form_options, which collects # them by descending the tree of child edit handlers. If there are no edit handlers that # specify form fields, this can legitimately result in both 'fields' and 'exclude' being # absent, which ModelForm doesn't normally allow. In this case, explicitly set fields to []. if "fields" not in meta_class_attrs and "exclude" not in meta_class_attrs: meta_class_attrs["fields"] = [] # Give this new form class a reasonable name. class_name = model.__name__ + "Form" bases = (form_class.Meta,) if hasattr(form_class, "Meta") else () Meta = type("Meta", bases, meta_class_attrs) form_class_attrs = {"Meta": Meta} metaclass = type(form_class) bases = [form_class] if issubclass(model, DraftStateMixin): bases.insert(0, WagtailAdminDraftStateFormMixin) return metaclass(class_name, tuple(bases), form_class_attrs) def extract_panel_definitions_from_model_class(model, exclude=None): if hasattr(model, "panels"): return model.panels panels = [] _exclude = [] if exclude: _exclude.extend(exclude) fields = fields_for_model( model, exclude=_exclude, formfield_callback=formfield_for_dbfield ) for field_name, field in fields.items(): try: panel_class = field.widget.get_panel() except AttributeError: panel_class = FieldPanel panel = panel_class(field_name) panels.append(panel) return panels class Panel: """ Defines part (or all) of the edit form interface for pages and other models within the Wagtail admin. Each model has an associated panel definition, consisting of a nested structure of Panel objects - this provides methods for obtaining a ModelForm subclass, with the field list and other parameters collated from all panels in the structure. It then handles rendering that form as HTML. """ def __init__( self, heading="", classname="", help_text="", base_form_class=None, icon="", ): self.heading = heading self.classname = classname self.help_text = help_text self.base_form_class = base_form_class self.icon = icon self.model = None def clone(self): """ Create a clone of this panel definition. By default, constructs a new instance, passing the keyword arguments returned by ``clone_kwargs``. """ return self.__class__(**self.clone_kwargs()) def clone_kwargs(self): """ Return a dictionary of keyword arguments that can be used to create a clone of this panel definition. """ return { "icon": self.icon, "heading": self.heading, "classname": self.classname, "help_text": self.help_text, "base_form_class": self.base_form_class, } def get_form_options(self): """ Return a dictionary of attributes such as 'fields', 'formsets' and 'widgets' which should be incorporated into the form class definition to generate a form that this panel can use. This will only be called after binding to a model (i.e. self.model is available). """ options = {} if not getattr(self.widget_overrides, "is_original_method", False): warn( "The `widget_overrides` method (on %r) is deprecated; " "these should be returned from `get_form_options` as a " "`widgets` item instead." % type(self), category=RemovedInWagtail50Warning, ) options["widgets"] = self.widget_overrides() if not getattr(self.required_fields, "is_original_method", False): warn( "The `required_fields` method (on %r) is deprecated; " "these should be returned from `get_form_options` as a " "`fields` item instead." % type(self), category=RemovedInWagtail50Warning, ) options["fields"] = self.required_fields() if not getattr(self.required_formsets, "is_original_method", False): warn( "The `required_formsets` method (on %r) is deprecated; " "these should be returned from `get_form_options` as a " "`formsets` item instead." % type(self), category=RemovedInWagtail50Warning, ) options["formsets"] = self.required_formsets() return options # RemovedInWagtail50Warning - edit handlers should override get_form_options instead def widget_overrides(self): return {} widget_overrides.is_original_method = True # RemovedInWagtail50Warning - edit handlers should override get_form_options instead def required_fields(self): return [] required_fields.is_original_method = True # RemovedInWagtail50Warning - edit handlers should override get_form_options instead def required_formsets(self): return {} required_formsets.is_original_method = True def get_form_class(self): """ Construct a form class that has all the fields and formsets named in the children of this edit handler. """ form_options = self.get_form_options() # If a custom form class was passed to the EditHandler, use it. # Otherwise, use the base_form_class from the model. # If that is not defined, use WagtailAdminModelForm. model_form_class = getattr(self.model, "base_form_class", WagtailAdminModelForm) base_form_class = self.base_form_class or model_form_class return get_form_for_model( self.model, form_class=base_form_class, **form_options, ) def bind_to_model(self, model): """ Create a clone of this panel definition with a ``model`` attribute pointing to the linked model class. """ new = self.clone() new.model = model new.on_model_bound() return new def bind_to(self, model=None, instance=None, request=None, form=None): warn( "The %s.bind_to() method has been replaced by bind_to_model(model) and get_bound_panel(instance=instance, request=request, form=form)" % type(self).__name__, category=RemovedInWagtail50Warning, stacklevel=2, ) return self.get_bound_panel(instance=instance, request=request, form=form) def get_bound_panel(self, instance=None, request=None, form=None, prefix="panel"): """ Return a ``BoundPanel`` instance that can be rendered onto the template as a component. By default, this creates an instance of the panel class's inner ``BoundPanel`` class, which must inherit from ``Panel.BoundPanel``. """ if self.model is None: raise ImproperlyConfigured( "%s.bind_to_model(model) must be called before get_bound_panel" % type(self).__name__ ) if not issubclass(self.BoundPanel, EditHandler.BoundPanel): raise ImproperlyConfigured( "%s.BoundPanel must be a subclass of EditHandler.BoundPanel" % type(self).__name__ ) return self.BoundPanel( panel=self, instance=instance, request=request, form=form, prefix=prefix ) def on_model_bound(self): """ Called after the panel has been associated with a model class and the ``self.model`` attribute is available; panels can override this method to perform additional initialisation related to the model. """ pass def __repr__(self): return "<%s with model=%s>" % ( self.__class__.__name__, self.model, ) def classes(self): """ Additional CSS classnames to add to whatever kind of object this is at output. Subclasses of Panel should override this, invoking super().classes() to append more classes specific to the situation. """ if self.classname: return [self.classname] return [] def id_for_label(self): """ The ID to be used as the 'for' attribute of any <label> elements that refer to this object but are rendered outside of it. Leave blank if this object does not render as a single input field. """ return "" @property def clean_name(self): """ A name for this panel, consisting only of ASCII alphanumerics and underscores, suitable for use in identifiers. Usually generated from the panel heading. Note that this is not guaranteed to be unique or non-empty; anything making use of this and requiring uniqueness should validate and modify the return value as needed. """ return safe_snake_case(self.heading) class BoundPanel(Component): """ A template component for a panel that has been associated with a model instance, form, and request. """ def __init__(self, panel, instance, request, form, prefix): #: The panel definition corresponding to this bound panel self.panel = panel #: The model instance associated with this panel self.instance = instance #: The request object associated with this panel self.request = request #: The form object associated with this panel self.form = form #: A unique prefix for this panel, for use in HTML IDs self.prefix = prefix self.heading = self.panel.heading self.help_text = self.panel.help_text @property def classname(self): return self.panel.classname def classes(self): return self.panel.classes() @property def icon(self): return self.panel.icon def id_for_label(self): """ Returns an HTML ID to be used as the target for any label referencing this panel. """ return self.panel.id_for_label() def is_shown(self): """ Whether this panel should be rendered; if false, it is skipped in the template output. """ return True def show_panel_furniture(self): """ Whether this panel shows the panel furniture instead of being rendered outside of it. """ return self.is_shown() def is_required(self): return False def render_as_object(self): warn( "Panel.render_as_object is deprecated. Use render_html instead", category=RemovedInWagtail50Warning, stacklevel=2, ) return self.render_html() def render_as_field(self): warn( "Panel.render_as_field is deprecated. Use render_html instead", category=RemovedInWagtail50Warning, stacklevel=2, ) return self.render_html() def get_context_data(self, parent_context=None): context = super().get_context_data(parent_context) context["self"] = self return context def get_comparison(self): return [] def render_missing_fields(self): """ Helper function: render all of the fields that are defined on the form but not "claimed" by any panels via required_fields. These fields are most likely to be hidden fields introduced by the forms framework itself, such as ORDER / DELETE fields on formset members. (If they aren't actually hidden fields, then they will appear as ugly unstyled / label-less fields outside of the panel furniture. But there's not much we can do about that.) """ rendered_fields = self.panel.get_form_options().get("fields", []) missing_fields_html = [ str(self.form[field_name]) for field_name in self.form.fields if field_name not in rendered_fields ] return mark_safe("".join(missing_fields_html)) def render_form_content(self): """ Render this as an 'object', ensuring that all fields necessary for a valid form submission are included """ return mark_safe(self.render_html() + self.render_missing_fields()) def __repr__(self): return "<%s with model=%s instance=%s request=%s form=%s>" % ( self.__class__.__name__, self.panel.model, self.instance, self.request, self.form.__class__.__name__, ) class EditHandler(Panel): def __init__(self, *args, **kwargs): warn( "wagtail.admin.edit_handlers.EditHandler has been renamed to wagtail.admin.panels.Panel", category=RemovedInWagtail50Warning, stacklevel=2, ) super().__init__(*args, **kwargs) class PanelGroup(Panel): """ Abstract class for panels that manage a set of sub-panels. Concrete subclasses must attach a 'children' property """ def __init__(self, children=(), *args, **kwargs): permission = kwargs.pop("permission", None) super().__init__(*args, **kwargs) self.children = children self.permission = permission def clone_kwargs(self): kwargs = super().clone_kwargs() kwargs["children"] = self.children kwargs["permission"] = self.permission return kwargs def get_form_options(self): if self.model is None: raise AttributeError( "%s is not bound to a model yet. Use `.bind_to_model(model)` " "before using this method." % self.__class__.__name__ ) options = {} # Merge in form options from each child in turn, combining values that are types that we # know how to combine (i.e. lists, dicts and sets) for child in self.children: child_options = child.get_form_options() for key, new_val in child_options.items(): if key not in options: # if val is a known mutable container type that we're going to merge subsequent # child values into, create a copy so that we don't risk that change leaking # back into the child's internal state if ( isinstance(new_val, list) or isinstance(new_val, dict) or isinstance(new_val, set) ): options[key] = new_val.copy() else: options[key] = new_val else: current_val = options[key] if isinstance(current_val, list) and isinstance( new_val, (list, tuple) ): current_val.extend(new_val) elif isinstance(current_val, tuple) and isinstance( new_val, (list, tuple) ): options[key] = list(current_val).extend(new_val) elif isinstance(current_val, dict) and isinstance(new_val, dict): current_val.update(new_val) elif isinstance(current_val, set) and isinstance(new_val, set): current_val.update(new_val) else: raise ValueError( "Don't know how to merge values %r and %r for form option %r" % (current_val, new_val, key) ) return options def on_model_bound(self): self.children = [child.bind_to_model(self.model) for child in self.children] @cached_property def child_identifiers(self): """ A list of identifiers corresponding to child panels in ``self.children``, formed from the clean_name property but validated to be unique and non-empty. """ used_names = set() result = [] for panel in self.children: base_name = panel.clean_name or "panel" candidate_name = base_name suffix = 0 while candidate_name in used_names: suffix += 1 candidate_name = "%s%d" % (base_name, suffix) result.append(candidate_name) used_names.add(candidate_name) return result class BoundPanel(Panel.BoundPanel): @cached_property def children(self): return [ child.get_bound_panel( instance=self.instance, request=self.request, form=self.form, prefix=("%s-child-%s" % (self.prefix, identifier)), ) for child, identifier in zip( self.panel.children, self.panel.child_identifiers ) ] @cached_property def visible_children(self): return [child for child in self.children if child.is_shown()] @cached_property def visible_children_with_identifiers(self): return [ (child, identifier) for child, identifier in zip( self.children, self.panel.child_identifiers ) if child.is_shown() ] def show_panel_furniture(self): return any(child.show_panel_furniture() for child in self.children) def is_shown(self): """ Check permissions on the panel group overall then check if any children are shown. """ if self.panel.permission: if not self.request.user.has_perm(self.panel.permission): return False return any(child.is_shown() for child in self.children) @property def media(self): media = Media() for item in self.visible_children: media += item.media return media def get_comparison(self): comparators = [] for child in self.children: comparators.extend(child.get_comparison()) return comparators class BaseCompositeEditHandler(PanelGroup): def __init__(self, *args, **kwargs): warn( "wagtail.admin.edit_handlers.BaseCompositeEditHandler has been renamed to wagtail.admin.panels.PanelGroup", category=RemovedInWagtail50Warning, stacklevel=2, ) super().__init__(*args, **kwargs) class TabbedInterface(PanelGroup): class BoundPanel(PanelGroup.BoundPanel): template_name = "wagtailadmin/panels/tabbed_interface.html" class ObjectList(PanelGroup): class BoundPanel(PanelGroup.BoundPanel): template_name = "wagtailadmin/panels/object_list.html" class FieldRowPanel(PanelGroup): class BoundPanel(PanelGroup.BoundPanel): template_name = "wagtailadmin/panels/field_row_panel.html" class MultiFieldPanel(PanelGroup): class BoundPanel(PanelGroup.BoundPanel): template_name = "wagtailadmin/panels/multi_field_panel.html" class HelpPanel(Panel): def __init__( self, content="", template="wagtailadmin/panels/help_panel.html", **kwargs, ): super().__init__(**kwargs) self.content = content self.template = template def clone_kwargs(self): kwargs = super().clone_kwargs() del kwargs["help_text"] kwargs.update( content=self.content, template=self.template, ) return kwargs @property def clean_name(self): return super().clean_name or "help" class BoundPanel(Panel.BoundPanel): def __init__(self, **kwargs): super().__init__(**kwargs) self.template_name = self.panel.template self.content = self.panel.content class FieldPanel(Panel): TEMPLATE_VAR = "field_panel" def __init__( self, field_name, widget=None, disable_comments=None, permission=None, **kwargs ): super().__init__(**kwargs) self.field_name = field_name self.widget = widget self.disable_comments = disable_comments self.permission = permission def clone_kwargs(self): kwargs = super().clone_kwargs() kwargs.update( field_name=self.field_name, widget=self.widget, disable_comments=self.disable_comments, permission=self.permission, ) return kwargs def get_form_options(self): opts = { "fields": [self.field_name], } if self.widget: opts["widgets"] = {self.field_name: self.widget} if self.permission: opts["field_permissions"] = {self.field_name: self.permission} return opts def get_comparison_class(self): try: field = self.db_field if field.choices: return compare.ChoiceFieldComparison comparison_class = compare.comparison_class_registry.get(field) if comparison_class: return comparison_class if field.is_relation: if field.many_to_many: return compare.M2MFieldComparison return compare.ForeignObjectComparison except FieldDoesNotExist: pass return compare.FieldComparison @cached_property def db_field(self): try: model = self.model except AttributeError: raise ImproperlyConfigured( "%r must be bound to a model before calling db_field" % self ) return model._meta.get_field(self.field_name) @property def clean_name(self): return self.field_name def __repr__(self): return "<%s '%s' with model=%s>" % ( self.__class__.__name__, self.field_name, self.model, ) class BoundPanel(Panel.BoundPanel): template_name = "wagtailadmin/panels/field_panel.html" def __init__(self, **kwargs): super().__init__(**kwargs) if self.form is None: self.bound_field = None return try: self.bound_field = self.form[self.field_name] except KeyError: self.bound_field = None return if self.panel.heading: self.heading = self.bound_field.label = self.panel.heading else: self.heading = self.bound_field.label self.help_text = self.panel.help_text or self.bound_field.help_text @property def field_name(self): return self.panel.field_name def is_shown(self): if self.form is not None and self.bound_field is None: # this field is missing from the form return False if ( self.panel.permission and self.request and not self.request.user.has_perm(self.panel.permission) ): return False return True def is_required(self): return self.bound_field.field.required def classes(self): is_streamfield = isinstance(self.bound_field.field, BlockField) extra_classes = ["w-panel--nested"] if is_streamfield else [] return self.panel.classes() + extra_classes @property def icon(self): """ Display a different icon depending on the field’s type. """ field_icons = { # Icons previously-defined as StreamField block icons. # Commented out until they can be reviewed for appropriateness in this new context. # "DateField": "date", # "TimeField": "time", # "DateTimeField": "date", # "URLField": "site", # "ClusterTaggableManager": "tag", # "EmailField": "mail", # "TextField": "pilcrow", # "FloatField": "plus-inverse", # "DecimalField": "plus-inverse", # "RegexField": "code", # "BooleanField": "tick-inverse", } field_type = self.bound_field.field.__class__.__name__ return self.panel.icon or field_icons.get(field_type, None) def id_for_label(self): return self.bound_field.id_for_label @property def comments_enabled(self): if self.panel.disable_comments is None: # by default, enable comments on all fields except StreamField (which has its own comment handling) return not isinstance(self.bound_field.field, BlockField) else: return not self.panel.disable_comments def get_context_data(self, parent_context=None): context = super().get_context_data(parent_context) widget_described_by_ids = [] help_text = self.bound_field.help_text help_text_id = "%s-helptext" % self.prefix error_message_id = "%s-errors" % self.prefix if help_text: widget_described_by_ids.append(help_text_id) if self.bound_field.errors: widget = self.bound_field.field.widget if hasattr(widget, "render_with_errors"): widget_attrs = { "id": self.bound_field.auto_id, } if widget_described_by_ids: widget_attrs["aria-describedby"] = " ".join( widget_described_by_ids ) rendered_field = widget.render_with_errors( self.bound_field.html_name, self.bound_field.value(), attrs=widget_attrs, errors=self.bound_field.errors, ) else: widget_described_by_ids.append(error_message_id) rendered_field = self.bound_field.as_widget( attrs={ "aria-invalid": "true", "aria-describedby": " ".join(widget_described_by_ids), } ) else: widget_attrs = {} if widget_described_by_ids: widget_attrs["aria-describedby"] = " ".join(widget_described_by_ids) rendered_field = self.bound_field.as_widget(attrs=widget_attrs) context.update( { "field": self.bound_field, "rendered_field": rendered_field, "help_text": help_text, "help_text_id": help_text_id, "error_message_id": error_message_id, "show_add_comment_button": self.comments_enabled and getattr( self.bound_field.field.widget, "show_add_comment_button", True ), } ) return context def get_comparison(self): comparator_class = self.panel.get_comparison_class() if comparator_class and self.is_shown(): try: return [functools.partial(comparator_class, self.panel.db_field)] except FieldDoesNotExist: return [] return [] def __repr__(self): return "<%s '%s' with model=%s instance=%s request=%s form=%s>" % ( self.__class__.__name__, self.field_name, self.panel.model, self.instance, self.request, self.form.__class__.__name__, ) class RichTextFieldPanel(FieldPanel): def __init__(self, *args, **kwargs): warn( "RichTextFieldPanel is no longer required for rich text fields, and should be replaced by FieldPanel. " "RichTextFieldPanel will be removed in a future release. " "See https://docs.wagtail.org/en/stable/releases/3.0.html#removal-of-special-purpose-field-panel-types", category=RemovedInWagtail50Warning, stacklevel=2, ) super().__init__(*args, **kwargs) class BaseChooserPanel(FieldPanel): def __init__(self, *args, **kwargs): warn( "wagtail.admin.edit_handlers.BaseChooserPanel is obsolete and should be replaced by wagtail.admin.panels.FieldPanel", category=RemovedInWagtail50Warning, stacklevel=2, ) super().__init__(*args, **kwargs) class PageChooserPanel(FieldPanel): def __init__(self, field_name, page_type=None, can_choose_root=False): super().__init__(field_name=field_name) self.page_type = page_type self.can_choose_root = can_choose_root def clone_kwargs(self): return { "field_name": self.field_name, "page_type": self.page_type, "can_choose_root": self.can_choose_root, } def get_form_options(self): opts = super().get_form_options() if self.page_type or self.can_choose_root: widgets = opts.setdefault("widgets", {}) widgets[self.field_name] = AdminPageChooser( target_models=self.page_type, can_choose_root=self.can_choose_root ) return opts class InlinePanel(Panel): def __init__( self, relation_name, panels=None, heading="", label="", min_num=None, max_num=None, *args, **kwargs, ): super().__init__(*args, **kwargs) self.relation_name = relation_name self.panels = panels self.heading = heading or label self.label = label self.min_num = min_num self.max_num = max_num def clone_kwargs(self): kwargs = super().clone_kwargs() kwargs.update( relation_name=self.relation_name, panels=self.panels, label=self.label, min_num=self.min_num, max_num=self.max_num, ) return kwargs @cached_property def panel_definitions(self): # Look for a panels definition in the InlinePanel declaration if self.panels is not None: return self.panels # Failing that, get it from the model return extract_panel_definitions_from_model_class( self.db_field.related_model, exclude=[self.db_field.field.name] ) @cached_property def child_edit_handler(self): panels = self.panel_definitions child_edit_handler = MultiFieldPanel(panels, heading=self.heading) return child_edit_handler.bind_to_model(self.db_field.related_model) def get_form_options(self): child_form_opts = self.child_edit_handler.get_form_options() return { "formsets": { self.relation_name: { "fields": child_form_opts.get("fields", []), "widgets": child_form_opts.get("widgets", {}), "min_num": self.min_num, "validate_min": self.min_num is not None, "max_num": self.max_num, "validate_max": self.max_num is not None, "formsets": child_form_opts.get("formsets"), } } } def on_model_bound(self): manager = getattr(self.model, self.relation_name) self.db_field = manager.rel def classes(self): return super().classes() + ["w-panel--nested"] class BoundPanel(Panel.BoundPanel): template_name = "wagtailadmin/panels/inline_panel.html" def __init__(self, **kwargs): super().__init__(**kwargs) self.label = self.panel.label if self.form is None: return self.formset = self.form.formsets[self.panel.relation_name] self.child_edit_handler = self.panel.child_edit_handler self.children = [] for index, subform in enumerate(self.formset.forms): # override the DELETE field to have a hidden input subform.fields[DELETION_FIELD_NAME].widget = forms.HiddenInput() # ditto for the ORDER field, if present if self.formset.can_order: subform.fields[ORDERING_FIELD_NAME].widget = forms.HiddenInput() self.children.append( self.child_edit_handler.get_bound_panel( instance=subform.instance, request=self.request, form=subform, prefix=("%s-%d" % (self.prefix, index)), ) ) # if this formset is valid, it may have been re-ordered; respect that # in case the parent form errored and we need to re-render if self.formset.can_order and self.formset.is_valid(): self.children.sort( key=lambda child: child.form.cleaned_data[ORDERING_FIELD_NAME] or 1 ) empty_form = self.formset.empty_form empty_form.fields[DELETION_FIELD_NAME].widget = forms.HiddenInput() if self.formset.can_order: empty_form.fields[ORDERING_FIELD_NAME].widget = forms.HiddenInput() self.empty_child = self.child_edit_handler.get_bound_panel( instance=empty_form.instance, request=self.request, form=empty_form, prefix=("%s-__prefix__" % self.prefix), ) def get_comparison(self): field_comparisons = [] for index, panel in enumerate(self.panel.child_edit_handler.children): field_comparisons.extend( panel.get_bound_panel( instance=None, request=self.request, form=None, prefix=("%s-%d" % (self.prefix, index)), ).get_comparison() ) return [ functools.partial( compare.ChildRelationComparison, self.panel.db_field, field_comparisons, label=self.label, ) ] def get_context_data(self, parent_context=None): context = super().get_context_data(parent_context) context["can_order"] = self.formset.can_order return context # This allows users to include the publishing panel in their own per-model override # without having to write these fields out by hand, potentially losing 'classname' # and therefore the associated styling of the publishing panel class PublishingPanel(MultiFieldPanel): def __init__(self, **kwargs): js_overlay_parent_selector = "#schedule-publishing-dialog" updated_kwargs = { "children": [ FieldRowPanel( [ FieldPanel( "go_live_at", widget=AdminDateTimeInput( js_overlay_parent_selector=js_overlay_parent_selector, ), ), FieldPanel( "expire_at", widget=AdminDateTimeInput( js_overlay_parent_selector=js_overlay_parent_selector, ), ), ], ), ], "classname": "publishing", } updated_kwargs.update(kwargs) super().__init__(**updated_kwargs) @property def clean_name(self): return super().clean_name or "publishing" class BoundPanel(PanelGroup.BoundPanel): template_name = "wagtailadmin/panels/publishing/schedule_publishing_panel.html" def get_context_data(self, parent_context=None): context = super().get_context_data(parent_context) context["request"] = self.request context["instance"] = self.instance context["classname"] = self.classname if isinstance(self.instance, Page): context["page"] = self.instance return context def show_panel_furniture(self): return False @property def media(self): return super().media + Media( js=[versioned_static("wagtailadmin/js/schedule-publishing.js")], ) class CommentPanel(Panel): def get_form_options(self): # add the comments formset return { # Adds the comment notifications field to the form. # Note, this field is defined directly on WagtailAdminPageForm. "fields": ["comment_notifications"], "formsets": { COMMENTS_RELATION_NAME: { "form": CommentForm, "fields": ["text", "contentpath", "position"], "formset_name": "comments", "inherit_kwargs": ["for_user"], } }, } @property def clean_name(self): return super().clean_name or "commments" class BoundPanel(Panel.BoundPanel): template_name = "wagtailadmin/panels/comments/comment_panel.html" def get_context_data(self, parent_context=None): context = super().get_context_data(parent_context) def user_data(user): return {"name": user_display_name(user), "avatar_url": avatar_url(user)} user = getattr(self.request, "user", None) user_pks = {user.pk} serialized_comments = [] bound = self.form.is_bound comment_formset = self.form.formsets.get("comments") comment_forms = comment_formset.forms if comment_formset else [] for form in comment_forms: # iterate over comments to retrieve users (to get display names) and serialized versions replies = [] for reply_form in form.formsets["replies"].forms: user_pks.add(reply_form.instance.user_id) reply_data = get_serializable_data_for_fields(reply_form.instance) reply_data["deleted"] = ( reply_form.cleaned_data.get("DELETE", False) if bound else False ) replies.append(reply_data) user_pks.add(form.instance.user_id) data = get_serializable_data_for_fields(form.instance) data["deleted"] = ( form.cleaned_data.get("DELETE", False) if bound else False ) data["resolved"] = ( form.cleaned_data.get("resolved", False) if bound else form.instance.resolved_at is not None ) data["replies"] = replies serialized_comments.append(data) authors = { str(user.pk): user_data(user) for user in get_user_model() .objects.filter(pk__in=user_pks) .select_related("wagtail_userprofile") } comments_data = { "comments": serialized_comments, "user": user.pk, "authors": authors, } context["comments_data"] = comments_data return context def show_panel_furniture(self): return False # Now that we've defined panels, we can set up wagtailcore.Page to have some. def set_default_page_edit_handlers(cls): cls.content_panels = [ FieldPanel( "title", classname="title", widget=forms.TextInput( attrs={ "placeholder": format_lazy( "{title}*", title=gettext_lazy("Page title") ) } ), ), ] cls.promote_panels = [ MultiFieldPanel( [ FieldPanel("slug"), FieldPanel("seo_title"), FieldPanel("search_description"), ], gettext_lazy("For search engines"), ), MultiFieldPanel( [ FieldPanel("show_in_menus"), ], gettext_lazy("For site menus"), ), ] cls.settings_panels = [ PublishingPanel(), ] if getattr(settings, "WAGTAILADMIN_COMMENTS_ENABLED", True): cls.settings_panels.append(CommentPanel()) cls.base_form_class = WagtailAdminPageForm set_default_page_edit_handlers(Page) @cached_classmethod def _get_page_edit_handler(cls): """ Get the panel to use in the Wagtail admin when editing this page type. """ if hasattr(cls, "edit_handler"): edit_handler = cls.edit_handler else: # construct a TabbedInterface made up of content_panels, promote_panels # and settings_panels, skipping any which are empty tabs = [] if cls.content_panels: tabs.append(ObjectList(cls.content_panels, heading=gettext_lazy("Content"))) if cls.promote_panels: tabs.append(ObjectList(cls.promote_panels, heading=gettext_lazy("Promote"))) if cls.settings_panels: tabs.append( ObjectList(cls.settings_panels, heading=gettext_lazy("Settings")) ) edit_handler = TabbedInterface(tabs, base_form_class=cls.base_form_class) return edit_handler.bind_to_model(cls) Page.get_edit_handler = _get_page_edit_handler @functools.lru_cache(maxsize=None) def get_edit_handler(model): """ Get the panel to use in the Wagtail admin when editing this model. """ if hasattr(model, "edit_handler"): # use the edit handler specified on the model class panel = model.edit_handler else: panels = extract_panel_definitions_from_model_class(model) panel = ObjectList(panels) return panel.bind_to_model(model) @receiver(setting_changed) def reset_edit_handler_cache(**kwargs): """ Clear page edit handler cache when global WAGTAILADMIN_COMMENTS_ENABLED settings are changed """ if kwargs["setting"] == "WAGTAILADMIN_COMMENTS_ENABLED": set_default_page_edit_handlers(Page) for model in apps.get_models(): if issubclass(model, Page): model.get_edit_handler.cache_clear() get_edit_handler.cache_clear() class StreamFieldPanel(FieldPanel): def __init__(self, *args, **kwargs): warn( "StreamFieldPanel is no longer required when using StreamField, and should be replaced by FieldPanel. " "StreamFieldPanel will be removed in a future release. " "See https://docs.wagtail.org/en/stable/releases/3.0.html#removal-of-special-purpose-field-panel-types", category=RemovedInWagtail50Warning, stacklevel=2, ) super().__init__(*args, **kwargs)
bsd-3-clause
a32b19fdaaad5e5dc4d6b0cf182b071d
34.14577
146
0.563836
4.507265
false
false
false
false
wagtail/wagtail
wagtail/test/emailuser/migrations/0001_initial.py
4
2337
# Generated by Django 3.2.3 on 2021-05-25 13:26 from django.db import migrations, models import uuid class Migration(migrations.Migration): initial = True dependencies = [ ("auth", "0012_alter_user_first_name_max_length"), ] operations = [ migrations.CreateModel( name="EmailUser", fields=[ ("password", models.CharField(max_length=128, verbose_name="password")), ( "last_login", models.DateTimeField( blank=True, null=True, verbose_name="last login" ), ), ( "uuid", models.UUIDField( default=uuid.uuid4, primary_key=True, serialize=False ), ), ("email", models.EmailField(max_length=255, unique=True)), ("is_staff", models.BooleanField(default=True)), ("is_active", models.BooleanField(default=True)), ("first_name", models.CharField(blank=True, max_length=50)), ("last_name", models.CharField(blank=True, max_length=50)), ("is_superuser", models.BooleanField(default=False)), ( "groups", models.ManyToManyField( blank=True, help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.", related_name="user_set", related_query_name="user", to="auth.Group", verbose_name="groups", ), ), ( "user_permissions", models.ManyToManyField( blank=True, help_text="Specific permissions for this user.", related_name="user_set", related_query_name="user", to="auth.Permission", verbose_name="user permissions", ), ), ], options={ "abstract": False, }, ), ]
bsd-3-clause
83abd2f918cdf626c456c0904280ea92
34.953846
134
0.434745
5.372414
false
false
false
false
wagtail/wagtail
wagtail/admin/views/reports/audit_logging.py
4
7681
import datetime from collections import defaultdict import django_filters from django import forms from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.db.models import IntegerField, Value from django.utils.encoding import force_str from django.utils.translation import gettext_lazy as _ from wagtail.admin.admin_url_finder import AdminURLFinder from wagtail.admin.filters import ( ContentTypeFilter, DateRangePickerWidget, WagtailFilterSet, ) from wagtail.coreutils import get_content_type_label from wagtail.log_actions import registry as log_action_registry from wagtail.models import PageLogEntry from .base import ReportView def get_users_for_filter(): user_ids = set() for log_model in log_action_registry.get_log_entry_models(): user_ids.update(log_model.objects.all().get_user_ids()) User = get_user_model() return User.objects.filter(pk__in=user_ids).order_by(User.USERNAME_FIELD) def get_content_types_for_filter(): content_type_ids = set() for log_model in log_action_registry.get_log_entry_models(): content_type_ids.update(log_model.objects.all().get_content_type_ids()) return ContentType.objects.filter(pk__in=content_type_ids).order_by("model") class SiteHistoryReportFilterSet(WagtailFilterSet): action = django_filters.ChoiceFilter( label=_("Action"), choices=log_action_registry.get_choices, ) hide_commenting_actions = django_filters.BooleanFilter( label=_("Hide commenting actions"), method="filter_hide_commenting_actions", widget=forms.CheckboxInput, ) timestamp = django_filters.DateFromToRangeFilter( label=_("Date"), widget=DateRangePickerWidget ) label = django_filters.CharFilter(label=_("Name"), lookup_expr="icontains") user = django_filters.ModelChoiceFilter( label=_("User"), field_name="user", queryset=lambda request: get_users_for_filter(), ) object_type = ContentTypeFilter( label=_("Type"), method="filter_object_type", queryset=lambda request: get_content_types_for_filter(), ) def filter_hide_commenting_actions(self, queryset, name, value): if value: queryset = queryset.exclude(action__startswith="wagtail.comments") return queryset def filter_object_type(self, queryset, name, value): return queryset.filter_on_content_type(value) class Meta: model = PageLogEntry fields = [ "object_type", "label", "action", "user", "timestamp", "hide_commenting_actions", ] class LogEntriesView(ReportView): template_name = "wagtailadmin/reports/site_history.html" title = _("Site history") header_icon = "history" filterset_class = SiteHistoryReportFilterSet export_headings = { "object_id": _("ID"), "label": _("Name"), "content_type": _("Type"), "action": _("Action type"), "user_display_name": _("User"), "timestamp": _("Date/Time"), } list_export = [ "object_id", "label", "content_type", "action", "user_display_name", "timestamp", ] def __init__(self, **kwargs): super().__init__(**kwargs) self.custom_field_preprocess = self.custom_field_preprocess.copy() self.custom_field_preprocess["action"] = { self.FORMAT_CSV: self.get_action_label, self.FORMAT_XLSX: self.get_action_label, } self.custom_field_preprocess["content_type"] = { self.FORMAT_CSV: get_content_type_label, self.FORMAT_XLSX: get_content_type_label, } def get_filename(self): return "audit-log-{}".format(datetime.datetime.today().strftime("%Y-%m-%d")) def get_filtered_queryset(self): """ Since this report combines records from multiple log models, the standard pattern of returning a queryset from get_queryset() to be filtered by filter_queryset() is not possible - the subquery for each log model must be filtered separately before joining with union(). Additionally, a union() on standard model-based querysets will return a queryset based on the first model in the union, so instances of the other model(s) would be returned as the wrong type. To avoid this, we construct values() querysets as follows: 1. For each model, construct a values() queryset consisting of id, timestamp and an annotation to indicate which model it is, and filter this with filter_queryset 2. Form a union() queryset from these queries, and order it by -timestamp (this is the result returned from get_filtered_queryset) 3. Apply pagination (done in MultipleObjectMixin.get_context_data) 4. (In decorate_paginated_queryset:) For each model included in the result set, look up the set of model instances by ID. Use these to form a final list of model instances in the same order as the query. """ queryset = None filters = None # Retrieve the set of registered log models, and cast it to a list so that we assign # an index number to each one; this index number will be used to distinguish models # in the combined results self.log_models = list(log_action_registry.get_log_entry_models()) for log_model_index, log_model in enumerate(self.log_models): sub_queryset = ( log_model.objects.viewable_by_user(self.request.user) .values("pk", "timestamp") .annotate( log_model_index=Value(log_model_index, output_field=IntegerField()) ) ) filters, sub_queryset = self.filter_queryset(sub_queryset) # disable any native ordering on the queryset; we will re-apply it on the combined result sub_queryset = sub_queryset.order_by() if queryset is None: queryset = sub_queryset else: queryset = queryset.union(sub_queryset) return filters, queryset.order_by("-timestamp") def decorate_paginated_queryset(self, queryset): # build lists of ids from queryset, grouped by log model index pks_by_log_model_index = defaultdict(list) for row in queryset: pks_by_log_model_index[row["log_model_index"]].append(row["pk"]) url_finder = AdminURLFinder(self.request.user) # for each log model found in the queryset, look up the set of log entries by id # and build a lookup table object_lookup = {} for log_model_index, pks in pks_by_log_model_index.items(): log_entries = ( self.log_models[log_model_index] .objects.prefetch_related("user__wagtail_userprofile", "content_type") .filter(pk__in=pks) .with_instances() ) for log_entry, instance in log_entries: # annotate log entry with an 'edit_url' property log_entry.edit_url = url_finder.get_edit_url(instance) object_lookup[(log_model_index, log_entry.pk)] = log_entry # return items from our lookup table in the order of the original queryset return [object_lookup[(row["log_model_index"], row["pk"])] for row in queryset] def get_action_label(self, action): return force_str(log_action_registry.get_action_label(action))
bsd-3-clause
fdf529431627c2c4f290cd9a2ef28c6a
37.59799
101
0.637547
4.142934
false
false
false
false
wagtail/wagtail
wagtail/models/collections.py
4
6430
from django.contrib.auth.models import Group, Permission from django.db import models from django.utils.html import format_html from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from treebeard.mp_tree import MP_Node from wagtail.query import TreeQuerySet from wagtail.search import index from .view_restrictions import BaseViewRestriction class CollectionQuerySet(TreeQuerySet): def get_indented_choices(self): """ Return a list of (id, label) tuples for use as a list of choices in a collection chooser dropdown, where the label is formatted with get_indented_name to provide a tree layout. The indent level is chosen to place the minimum-depth collection at indent 0. """ min_depth = self.aggregate(models.Min("depth"))["depth__min"] or 2 return [ (collection.pk, collection.get_indented_name(min_depth, html=True)) for collection in self ] class BaseCollectionManager(models.Manager): def get_queryset(self): return CollectionQuerySet(self.model).order_by("path") CollectionManager = BaseCollectionManager.from_queryset(CollectionQuerySet) class CollectionViewRestriction(BaseViewRestriction): collection = models.ForeignKey( "Collection", verbose_name=_("collection"), related_name="view_restrictions", on_delete=models.CASCADE, ) passed_view_restrictions_session_key = "passed_collection_view_restrictions" class Meta: verbose_name = _("collection view restriction") verbose_name_plural = _("collection view restrictions") class Collection(MP_Node): """ A location in which resources such as images and documents can be grouped """ name = models.CharField(max_length=255, verbose_name=_("name")) objects = CollectionManager() # Tell treebeard to order Collections' paths such that they are ordered by name at each level. node_order_by = ["name"] def __str__(self): return self.name def get_ancestors(self, inclusive=False): return Collection.objects.ancestor_of(self, inclusive) def get_descendants(self, inclusive=False): return Collection.objects.descendant_of(self, inclusive) def get_siblings(self, inclusive=True): return Collection.objects.sibling_of(self, inclusive) def get_next_siblings(self, inclusive=False): return self.get_siblings(inclusive).filter(path__gte=self.path).order_by("path") def get_prev_siblings(self, inclusive=False): return ( self.get_siblings(inclusive).filter(path__lte=self.path).order_by("-path") ) def get_view_restrictions(self): """Return a query set of all collection view restrictions that apply to this collection""" return CollectionViewRestriction.objects.filter( collection__in=self.get_ancestors(inclusive=True) ) def get_indented_name(self, indentation_start_depth=2, html=False): """ Renders this Collection's name as a formatted string that displays its hierarchical depth via indentation. If indentation_start_depth is supplied, the Collection's depth is rendered relative to that depth. indentation_start_depth defaults to 2, the depth of the first non-Root Collection. Pass html=True to get a HTML representation, instead of the default plain-text. Example text output: " ↳ Pies" Example HTML output: "&nbsp;&nbsp;&nbsp;&nbsp;&#x21b3 Pies" """ display_depth = self.depth - indentation_start_depth # A Collection with a display depth of 0 or less (Root's can be -1), should have no indent. if display_depth <= 0: return self.name # Indent each level of depth by 4 spaces (the width of the ↳ character in our admin font), then add ↳ # before adding the name. if html: # NOTE: &#x21b3 is the hex HTML entity for ↳. return format_html( "{indent}{icon} {name}", indent=mark_safe("&nbsp;" * 4 * display_depth), icon=mark_safe("&#x21b3"), name=self.name, ) # Output unicode plain-text version return "{}↳ {}".format(" " * 4 * display_depth, self.name) class Meta: verbose_name = _("collection") verbose_name_plural = _("collections") def get_root_collection_id(): return Collection.get_first_root_node().id class CollectionMember(models.Model): """ Base class for models that are categorised into collections """ collection = models.ForeignKey( Collection, default=get_root_collection_id, verbose_name=_("collection"), related_name="+", on_delete=models.CASCADE, ) search_fields = [ index.FilterField("collection"), ] class Meta: abstract = True class GroupCollectionPermissionManager(models.Manager): def get_by_natural_key(self, group, collection, permission): return self.get(group=group, collection=collection, permission=permission) class GroupCollectionPermission(models.Model): """ A rule indicating that a group has permission for some action (e.g. "create document") within a specified collection. """ group = models.ForeignKey( Group, verbose_name=_("group"), related_name="collection_permissions", on_delete=models.CASCADE, ) collection = models.ForeignKey( Collection, verbose_name=_("collection"), related_name="group_permissions", on_delete=models.CASCADE, ) permission = models.ForeignKey( Permission, verbose_name=_("permission"), on_delete=models.CASCADE ) def __str__(self): return "Group %d ('%s') has permission '%s' on collection %d ('%s')" % ( self.group.id, self.group, self.permission, self.collection.id, self.collection, ) def natural_key(self): return (self.group, self.collection, self.permission) objects = GroupCollectionPermissionManager() class Meta: unique_together = ("group", "collection", "permission") verbose_name = _("group collection permission") verbose_name_plural = _("group collection permissions")
bsd-3-clause
aad5a392ba85a155206f93f539df26be
32.789474
114
0.65296
4.28
false
false
false
false
wagtail/wagtail
wagtail/users/models.py
4
2661
import os import uuid from django.conf import settings from django.db import models from django.utils.translation import get_language from django.utils.translation import gettext_lazy as _ def upload_avatar_to(instance, filename): filename, ext = os.path.splitext(filename) return os.path.join( "avatar_images", "avatar_{uuid}_{filename}{ext}".format( uuid=uuid.uuid4(), filename=filename, ext=ext ), ) class UserProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="wagtail_userprofile", ) submitted_notifications = models.BooleanField( verbose_name=_("submitted notifications"), default=True, help_text=_("Receive notification when a page is submitted for moderation"), ) approved_notifications = models.BooleanField( verbose_name=_("approved notifications"), default=True, help_text=_("Receive notification when your page edit is approved"), ) rejected_notifications = models.BooleanField( verbose_name=_("rejected notifications"), default=True, help_text=_("Receive notification when your page edit is rejected"), ) updated_comments_notifications = models.BooleanField( verbose_name=_("updated comments notifications"), default=True, help_text=_( "Receive notification when comments have been created, resolved, or deleted on a page that you have subscribed to receive comment notifications on" ), ) preferred_language = models.CharField( verbose_name=_("preferred language"), max_length=10, help_text=_("Select language for the admin"), default="", ) current_time_zone = models.CharField( verbose_name=_("current time zone"), max_length=40, help_text=_("Select your current time zone"), default="", ) avatar = models.ImageField( verbose_name=_("profile picture"), upload_to=upload_avatar_to, blank=True, ) dismissibles = models.JSONField(default=dict, blank=True) @classmethod def get_for_user(cls, user): return cls.objects.get_or_create(user=user)[0] def get_preferred_language(self): return self.preferred_language or get_language() def get_current_time_zone(self): return self.current_time_zone or settings.TIME_ZONE def __str__(self): return self.user.get_username() class Meta: verbose_name = _("user profile") verbose_name_plural = _("user profiles")
bsd-3-clause
fe9aa038e5bb785906fe1924f22a08d7
28.566667
159
0.644495
4.472269
false
false
false
false
wagtail/wagtail
wagtail/contrib/routable_page/models.py
4
7470
import logging from functools import partial from django.core.checks import Warning from django.http import Http404 from django.template.response import TemplateResponse from django.urls import URLResolver from django.urls import path as path_func from django.urls import re_path as re_path_func from django.urls.resolvers import RegexPattern, RoutePattern from wagtail.models import Page from wagtail.url_routing import RouteResult _creation_counter = 0 logger = logging.getLogger("wagtail.routablepage") def _path(pattern, name=None, func=None): def decorator(view_func): global _creation_counter _creation_counter += 1 # Make sure page has _routablepage_routes attribute if not hasattr(view_func, "_routablepage_routes"): view_func._routablepage_routes = [] # Add new route to view view_func._routablepage_routes.append( ( func(pattern, view_func, name=(name or view_func.__name__)), _creation_counter, ) ) return view_func return decorator re_path = partial(_path, func=re_path_func) path = partial(_path, func=path_func) # Make route an alias of re_path for backwards compatibility. route = re_path class RoutablePageMixin: """ This class can be mixed in to a Page model, allowing extra routes to be added to it. """ @path("") def index_route(self, request, *args, **kwargs): request.is_preview = getattr(request, "is_preview", False) return TemplateResponse( request, self.get_template(request, *args, **kwargs), self.get_context(request, *args, **kwargs), ) @classmethod def get_subpage_urls(cls): routes = [] # Loop over this class's defined routes, in method resolution order. # Routes defined in the immediate class take precedence, followed by # immediate superclass and so on for klass in cls.__mro__: routes_for_class = [] for val in klass.__dict__.values(): if hasattr(val, "_routablepage_routes"): routes_for_class.extend(val._routablepage_routes) # sort routes by _creation_counter so that ones earlier in the class definition # take precedence routes_for_class.sort(key=lambda route: route[1]) routes.extend(route[0] for route in routes_for_class) return tuple(routes) @classmethod def get_resolver(cls): if "_routablepage_urlresolver" not in cls.__dict__: subpage_urls = cls.get_subpage_urls() cls._routablepage_urlresolver = URLResolver( RegexPattern(r"^/"), subpage_urls ) return cls._routablepage_urlresolver @classmethod def check(cls, **kwargs): errors = super().check(**kwargs) errors.extend(cls._check_path_with_regex()) return errors @classmethod def _check_path_with_regex(cls): routes = cls.get_subpage_urls() errors = [] for route in routes: if isinstance(route.pattern, RoutePattern): pattern = route.pattern._route if ( "(?P<" in pattern or pattern.startswith("^") or pattern.endswith("$") ): errors.append( Warning( ( f"Your URL pattern {route.name or route.callback.__name__} has a " "route that contains '(?P<', begins with a '^', or ends with a '$'." ), hint="Decorate your view with re_path if you want to use regexp.", obj=cls, id="wagtailroutablepage.W001", ) ) return errors def reverse_subpage(self, name, args=None, kwargs=None): """ This method takes a route name/arguments and returns a URL path. """ args = args or [] kwargs = kwargs or {} return self.get_resolver().reverse(name, *args, **kwargs) def resolve_subpage(self, path): """ This method takes a URL path and finds the view to call. """ view, args, kwargs = self.get_resolver().resolve(path) # Bind the method view = view.__get__(self, type(self)) return view, args, kwargs def route(self, request, path_components): """ This hooks the subpage URLs into Wagtail's routing. """ if self.live: try: path = "/" if path_components: path += "/".join(path_components) + "/" view, args, kwargs = self.resolve_subpage(path) return RouteResult(self, args=(view, args, kwargs)) except Http404: pass return super().route(request, path_components) def serve(self, request, view=None, args=None, kwargs=None): if args is None: args = [] if kwargs is None: kwargs = {} if view is None: return super().serve(request, *args, **kwargs) return view(request, *args, **kwargs) def render(self, request, *args, template=None, context_overrides=None, **kwargs): """ This method replicates what ``Page.serve()`` usually does when ``RoutablePageMixin`` is not used. By default, ``Page.get_template()`` is called to derive the template to use for rendering, and ``Page.get_context()`` is always called to gather the data to be included in the context. You can use the ``context_overrides`` keyword argument as a shortcut to override or add new values to the context. For example: .. code-block:: python @path('') # override the default route def upcoming_events(self, request): return self.render(request, context_overrides={ 'title': "Current events", 'events': EventPage.objects.live().future(), }) You can also use the ``template`` argument to specify an alternative template to use for rendering. For example: .. code-block:: python @path('past/') def past_events(self, request): return self.render( request, context_overrides={ 'title': "Past events", 'events': EventPage.objects.live().past(), }, template="events/event_index_historical.html", ) """ if template is None: template = self.get_template(request, *args, **kwargs) context = self.get_context(request, *args, **kwargs) context.update(context_overrides or {}) return TemplateResponse(request, template, context) def serve_preview(self, request, mode_name): view, args, kwargs = self.resolve_subpage("/") return view(request, *args, **kwargs) class RoutablePage(RoutablePageMixin, Page): """ This class extends Page by adding methods which allows extra routes to be added to it. """ class Meta: abstract = True
bsd-3-clause
f24691ef8832e177b3552e5873bf6882
32.053097
100
0.561044
4.527273
false
false
false
false
wagtail/wagtail
wagtail/users/views/users.py
4
8746
from django.conf import settings from django.contrib.auth import get_user_model, update_session_auth_hash from django.contrib.auth.models import Group from django.core.exceptions import PermissionDenied from django.db.models import Q from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy from wagtail.admin.views.generic import CreateView, DeleteView, EditView, IndexView from wagtail.compat import AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME from wagtail.permission_policies import ModelPermissionPolicy from wagtail.users.forms import UserCreationForm, UserEditForm from wagtail.users.utils import user_can_delete_user from wagtail.utils.loading import get_custom_form User = get_user_model() # Typically we would check the permission 'auth.change_user' (and 'auth.add_user' / # 'auth.delete_user') for user management actions, but this may vary according to # the AUTH_USER_MODEL setting add_user_perm = "{0}.add_{1}".format(AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME.lower()) change_user_perm = "{0}.change_{1}".format( AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME.lower() ) delete_user_perm = "{0}.delete_{1}".format( AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME.lower() ) def get_user_creation_form(): form_setting = "WAGTAIL_USER_CREATION_FORM" if hasattr(settings, form_setting): return get_custom_form(form_setting) else: return UserCreationForm def get_user_edit_form(): form_setting = "WAGTAIL_USER_EDIT_FORM" if hasattr(settings, form_setting): return get_custom_form(form_setting) else: return UserEditForm def get_users_filter_query(q, model_fields): conditions = Q() for term in q.split(): if "username" in model_fields: conditions |= Q(username__icontains=term) if "first_name" in model_fields: conditions |= Q(first_name__icontains=term) if "last_name" in model_fields: conditions |= Q(last_name__icontains=term) if "email" in model_fields: conditions |= Q(email__icontains=term) return conditions class Index(IndexView): """ Lists the users for management within the admin. """ any_permission_required = ["add", "change", "delete"] permission_policy = ModelPermissionPolicy(User) model = User context_object_name = "users" index_url_name = "wagtailusers_users:index" add_url_name = "wagtailusers_users:add" edit_url_name = "wagtailusers_users:edit" default_ordering = "name" paginate_by = 20 template_name = None is_searchable = True page_title = gettext_lazy("Users") def setup(self, request, *args, **kwargs): super().setup(request, *args, **kwargs) setattr(self, "template_name", self.get_template()) self.group = get_object_or_404(Group, id=args[0]) if args else None self.group_filter = Q(groups=self.group) if self.group else Q() self.model_fields = [f.name for f in User._meta.get_fields()] def get_valid_orderings(self): return ["name", "username"] def get_queryset(self): if self.is_searching: conditions = get_users_filter_query(self.search_query, self.model_fields) users = User.objects.filter(self.group_filter & conditions) else: users = User.objects.filter(self.group_filter) if self.locale: users = users.filter(locale=self.locale) if "last_name" in self.model_fields and "first_name" in self.model_fields: users = users.order_by("last_name", "first_name") if self.get_ordering() == "username": users = users.order_by(User.USERNAME_FIELD) return users def get_template(self): if self.request.headers.get("x-requested-with") == "XMLHttpRequest": return "wagtailusers/users/results.html" else: return "wagtailusers/users/index.html" def get_context_data(self, *args, object_list=None, **kwargs): context_data = super().get_context_data( *args, object_list=object_list, **kwargs ) context_data["ordering"] = self.get_ordering() context_data["group"] = self.group if self.request.headers.get("x-requested-with") == "XMLHttpRequest": return context_data context_data.update( { "app_label": User._meta.app_label, "model_name": User._meta.model_name, } ) return context_data class Create(CreateView): """ Provide the ability to create a user within the admin. """ permission_policy = ModelPermissionPolicy(User) permission_required = "add" form_class = get_user_creation_form() template_name = "wagtailusers/users/create.html" add_url_name = "wagtailusers_users:add" index_url_name = "wagtailusers_users:index" edit_url_name = "wagtailusers_users:edit" success_message = "User '{0}' created." page_title = gettext_lazy("Add user") def run_before_hook(self): return self.run_hook( "before_create_user", self.request, ) def run_after_hook(self): return self.run_hook( "after_create_user", self.request, self.object, ) def get_add_url(self): return None class Edit(EditView): """ Provide the ability to edit a user within the admin. """ model = User permission_policy = ModelPermissionPolicy(User) form_class = get_user_edit_form() template_name = "wagtailusers/users/edit.html" index_url_name = "wagtailusers_users:index" edit_url_name = "wagtailusers_users:edit" delete_url_name = "wagtailusers_users:delete" success_message = _("User '{0}' updated.") context_object_name = "user" error_message = gettext_lazy("The user could not be saved due to errors.") def get_page_title(self): return _("Editing %s") % self.object.get_username() def get_page_subtitle(self): return "" def setup(self, request, *args, **kwargs): super().setup(request, *args, **kwargs) self.object = self.get_object() self.can_delete = user_can_delete_user(request.user, self.object) self.editing_self = request.user == self.object def save_instance(self): instance = super().save_instance() if self.object == self.request.user and "password1" in self.form.changed_data: # User is changing their own password; need to update their session hash update_session_auth_hash(self.request, self.object) return instance def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update( { "editing_self": self.editing_self, } ) return kwargs def run_before_hook(self): return self.run_hook( "before_edit_user", self.request, self.object, ) def run_after_hook(self): return self.run_hook( "after_edit_user", self.request, self.object, ) def get_edit_url(self): return reverse(self.edit_url_name, args=(self.object.pk,)) def get_delete_url(self): return reverse(self.delete_url_name, args=(self.object.pk,)) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.pop("action_url") context["can_delete"] = self.can_delete return context class Delete(DeleteView): """ Provide the ability to delete a user within the admin. """ permission_policy = ModelPermissionPolicy(User) permission_required = "delete" model = User template_name = "wagtailusers/users/confirm_delete.html" delete_url_name = "wagtailusers_users:delete" index_url_name = "wagtailusers_users:index" page_title = gettext_lazy("Delete user") context_object_name = "user" success_message = _("User '{0}' deleted.") def dispatch(self, request, *args, **kwargs): self.object = self.get_object() if not user_can_delete_user(self.request.user, self.object): raise PermissionDenied return super().dispatch(request, *args, **kwargs) def run_before_hook(self): return self.run_hook( "before_delete_user", self.request, self.object, ) def run_after_hook(self): return self.run_hook( "after_delete_user", self.request, self.object, )
bsd-3-clause
e25b16aa8b51d52b50cc393aacebe9ed
31.03663
87
0.631031
3.75526
false
false
false
false
wagtail/wagtail
wagtail/query.py
4
22648
import posixpath import warnings from collections import defaultdict from typing import Any, Dict, Iterable, Tuple from django.apps import apps from django.contrib.contenttypes.models import ContentType from django.db.models import CharField, Prefetch, Q from django.db.models.expressions import Exists, OuterRef from django.db.models.functions import Cast, Length, Substr from django.db.models.query import BaseIterable, ModelIterable from treebeard.mp_tree import MP_NodeQuerySet from wagtail.models.sites import Site from wagtail.search.queryset import SearchableQuerySetMixin class TreeQuerySet(MP_NodeQuerySet): """ Extends Treebeard's MP_NodeQuerySet with additional useful tree-related operations. """ def delete(self): """Redefine the delete method unbound, so we can set the queryset_only parameter.""" super().delete() delete.queryset_only = True def descendant_of_q(self, other, inclusive=False): q = Q(path__startswith=other.path) & Q(depth__gte=other.depth) if not inclusive: q &= ~Q(pk=other.pk) return q def descendant_of(self, other, inclusive=False): """ This filters the QuerySet to only contain pages that descend from the specified page. If inclusive is set to True, it will also contain the page itself (instead of just its descendants). """ return self.filter(self.descendant_of_q(other, inclusive)) def not_descendant_of(self, other, inclusive=False): """ This filters the QuerySet to not contain any pages that descend from the specified page. If inclusive is set to True, it will also exclude the specified page. """ return self.exclude(self.descendant_of_q(other, inclusive)) def child_of_q(self, other): return self.descendant_of_q(other) & Q(depth=other.depth + 1) def child_of(self, other): """ This filters the QuerySet to only contain pages that are direct children of the specified page. """ return self.filter(self.child_of_q(other)) def not_child_of(self, other): """ This filters the QuerySet to not contain any pages that are direct children of the specified page. """ return self.exclude(self.child_of_q(other)) def ancestor_of_q(self, other, inclusive=False): paths = [ other.path[0:pos] for pos in range(0, len(other.path) + 1, other.steplen)[1:] ] q = Q(path__in=paths) if not inclusive: q &= ~Q(pk=other.pk) return q def ancestor_of(self, other, inclusive=False): """ This filters the QuerySet to only contain pages that are ancestors of the specified page. If inclusive is set to True, it will also include the specified page. """ return self.filter(self.ancestor_of_q(other, inclusive)) def not_ancestor_of(self, other, inclusive=False): """ This filters the QuerySet to not contain any pages that are ancestors of the specified page. If inclusive is set to True, it will also exclude the specified page. """ return self.exclude(self.ancestor_of_q(other, inclusive)) def parent_of_q(self, other): return Q(path=self.model._get_parent_path_from_path(other.path)) def parent_of(self, other): """ This filters the QuerySet to only contain the parent of the specified page. """ return self.filter(self.parent_of_q(other)) def not_parent_of(self, other): """ This filters the QuerySet to exclude the parent of the specified page. """ return self.exclude(self.parent_of_q(other)) def sibling_of_q(self, other, inclusive=True): q = Q(path__startswith=self.model._get_parent_path_from_path(other.path)) & Q( depth=other.depth ) if not inclusive: q &= ~Q(pk=other.pk) return q def sibling_of(self, other, inclusive=True): """ This filters the QuerySet to only contain pages that are siblings of the specified page. By default, inclusive is set to True so it will include the specified page in the results. If inclusive is set to False, the page will be excluded from the results. """ return self.filter(self.sibling_of_q(other, inclusive)) def not_sibling_of(self, other, inclusive=True): """ This filters the QuerySet to not contain any pages that are siblings of the specified page. By default, inclusive is set to True so it will exclude the specified page from the results. If inclusive is set to False, the page will be included in the results. """ return self.exclude(self.sibling_of_q(other, inclusive)) class PageQuerySet(SearchableQuerySetMixin, TreeQuerySet): def __init__(self, *args, **kwargs): """Set custom instance attributes""" super().__init__(*args, **kwargs) # set by defer_streamfields() self._defer_streamfields = False def _clone(self): """Ensure clones inherit custom attribute values.""" clone = super()._clone() clone._defer_streamfields = self._defer_streamfields return clone def live_q(self): return Q(live=True) def live(self): """ This filters the QuerySet to only contain published pages. """ return self.filter(self.live_q()) def not_live(self): """ This filters the QuerySet to only contain unpublished pages. """ return self.exclude(self.live_q()) def in_menu_q(self): return Q(show_in_menus=True) def in_menu(self): """ This filters the QuerySet to only contain pages that are in the menus. """ return self.filter(self.in_menu_q()) def not_in_menu(self): """ This filters the QuerySet to only contain pages that are not in the menus. """ return self.exclude(self.in_menu_q()) def page_q(self, other): return Q(id=other.id) def page(self, other): """ This filters the QuerySet so it only contains the specified page. """ return self.filter(self.page_q(other)) def not_page(self, other): """ This filters the QuerySet so it doesn't contain the specified page. """ return self.exclude(self.page_q(other)) def type_q(self, *types): all_subclasses = { model for model in apps.get_models() if issubclass(model, types) } content_types = ContentType.objects.get_for_models(*all_subclasses) return Q(content_type__in=list(content_types.values())) def type(self, *types): """ This filters the QuerySet to only contain pages that are an instance of the specified model(s) (including subclasses). """ return self.filter(self.type_q(*types)) def not_type(self, *types): """ This filters the QuerySet to exclude any pages which are an instance of the specified model(s). """ return self.exclude(self.type_q(*types)) def exact_type_q(self, *types): content_types = ContentType.objects.get_for_models(*types) return Q(content_type__in=list(content_types.values())) def exact_type(self, *types): """ This filters the QuerySet to only contain pages that are an instance of the specified model(s) (matching the model exactly, not subclasses). """ return self.filter(self.exact_type_q(*types)) def not_exact_type(self, *types): """ This filters the QuerySet to exclude any pages which are an instance of the specified model(s) (matching the model exactly, not subclasses). """ return self.exclude(self.exact_type_q(*types)) def private_q(self): from wagtail.models import PageViewRestriction q = Q() for restriction in PageViewRestriction.objects.select_related("page").all(): q |= self.descendant_of_q(restriction.page, inclusive=True) # do not match any page if no private section exists. return q if q else Q(pk__in=[]) def public(self): """ Filters the QuerySet to only contain pages that are not in a private section and their descendants. """ return self.exclude(self.private_q()) def not_public(self): """ Filters the QuerySet to only contain pages that are in a private section and their descendants. """ return self.filter(self.private_q()) def private(self): """ Filters the QuerySet to only contain pages that are in a private section and their descendants. """ return self.filter(self.private_q()) def first_common_ancestor(self, include_self=False, strict=False): """ Find the first ancestor that all pages in this queryset have in common. For example, consider a page hierarchy like:: - Home/ - Foo Event Index/ - Foo Event Page 1/ - Foo Event Page 2/ - Bar Event Index/ - Bar Event Page 1/ - Bar Event Page 2/ The common ancestors for some queries would be: .. code-block:: python >>> Page.objects\\ ... .type(EventPage)\\ ... .first_common_ancestor() <Page: Home> >>> Page.objects\\ ... .type(EventPage)\\ ... .filter(title__contains='Foo')\\ ... .first_common_ancestor() <Page: Foo Event Index> This method tries to be efficient, but if you have millions of pages scattered across your page tree, it will be slow. If `include_self` is True, the ancestor can be one of the pages in the queryset: .. code-block:: python >>> Page.objects\\ ... .filter(title__contains='Foo')\\ ... .first_common_ancestor() <Page: Foo Event Index> >>> Page.objects\\ ... .filter(title__exact='Bar Event Index')\\ ... .first_common_ancestor() <Page: Bar Event Index> A few invalid cases exist: when the queryset is empty, when the root Page is in the queryset and ``include_self`` is False, and when there are multiple page trees with no common root (a case Wagtail does not support). If ``strict`` is False (the default), then the first root node is returned in these cases. If ``strict`` is True, then a ``ObjectDoesNotExist`` is raised. """ # An empty queryset has no ancestors. This is a problem if not self.exists(): if strict: raise self.model.DoesNotExist("Can not find ancestor of empty queryset") return self.model.get_first_root_node() if include_self: # Get all the paths of the matched pages. paths = self.order_by().values_list("path", flat=True) else: # Find all the distinct parent paths of all matched pages. # The empty `.order_by()` ensures that `Page.path` is not also # selected to order the results, which makes `.distinct()` works. paths = ( self.order_by() .annotate( parent_path=Substr( "path", 1, Length("path") - self.model.steplen, output_field=CharField(max_length=255), ) ) .values_list("parent_path", flat=True) .distinct() ) # This method works on anything, not just file system paths. common_parent_path = posixpath.commonprefix(paths) # That may have returned a path like (0001, 0002, 000), which is # missing some chars off the end. Fix this by trimming the path to a # multiple of `Page.steplen` extra_chars = len(common_parent_path) % self.model.steplen if extra_chars != 0: common_parent_path = common_parent_path[:-extra_chars] if common_parent_path == "": # This should only happen when there are multiple trees, # a situation that Wagtail does not support; # or when the root node itself is part of the queryset. if strict: raise self.model.DoesNotExist("No common ancestor found!") # Assuming the situation is the latter, just return the root node. # The root node is not its own ancestor, so this is technically # incorrect. If you want very correct operation, use `strict=True` # and receive an error. return self.model.get_first_root_node() # Assuming the database is in a consistent state, this page should # *always* exist. If your database is not in a consistent state, you've # got bigger problems. return self.model.objects.get(path=common_parent_path) def unpublish(self): """ This unpublishes all live pages in the QuerySet. """ for page in self.live(): page.unpublish() def defer_streamfields(self): """ Apply to a queryset to prevent fetching/decoding of StreamField values on evaluation. Useful when working with potentially large numbers of results, where StreamField values are unlikely to be needed. For example, when generating a sitemap or a long list of page links. """ clone = self._clone() clone._defer_streamfields = True # used by specific_iterator() streamfield_names = self.model.get_streamfield_names() if not streamfield_names: return clone return clone.defer(*streamfield_names) def specific(self, defer=False): """ This efficiently gets all the specific pages for the queryset, using the minimum number of queries. When the "defer" keyword argument is set to True, only generic page field values will be loaded and all specific fields will be deferred. """ clone = self._clone() if defer: clone._iterable_class = DeferredSpecificIterable else: clone._iterable_class = SpecificIterable return clone def in_site(self, site): """ This filters the QuerySet to only contain pages within the specified site. """ return self.descendant_of(site.root_page, inclusive=True) def translation_of_q(self, page, inclusive): q = Q(translation_key=page.translation_key) if not inclusive: q &= ~Q(pk=page.pk) return q def translation_of(self, page, inclusive=False): """ This filters the QuerySet to only contain pages that are translations of the specified page. If inclusive is True, the page itself is returned. """ return self.filter(self.translation_of_q(page, inclusive)) def not_translation_of(self, page, inclusive=False): """ This filters the QuerySet to only contain pages that are not translations of the specified page. Note, this will include the page itself as the page is technically not a translation of itself. If inclusive is True, we consider the page to be a translation of itself so this excludes the page from the results. """ return self.exclude(self.translation_of_q(page, inclusive)) def prefetch_workflow_states(self): """ Performance optimisation for listing pages. Prefetches the active workflow states on each page in this queryset. Used by `workflow_in_progress` and `current_workflow_progress` properties on `wagtailcore.models.Page`. """ from .models import WorkflowState workflow_states = WorkflowState.objects.active().select_related( "current_task_state__task" ) return self.prefetch_related( Prefetch( "workflow_states", queryset=workflow_states, to_attr="_current_workflow_states", ) ) def annotate_approved_schedule(self): """ Performance optimisation for listing pages. Annotates each page with the existence of an approved go live time. Used by `approved_schedule` property on `wagtailcore.models.Page`. """ from .models import Revision return self.annotate( _approved_schedule=Exists( Revision.page_revisions.exclude( approved_go_live_at__isnull=True ).filter(object_id=Cast(OuterRef("pk"), output_field=CharField())) ) ) def annotate_site_root_state(self): """ Performance optimisation for listing pages. Annotates each object with whether it is a root page of any site. Used by `is_site_root` method on `wagtailcore.models.Page`. """ return self.annotate( _is_site_root=Exists( Site.objects.filter( root_page__translation_key=OuterRef("translation_key") ) ) ) class SpecificIterable(BaseIterable): def __iter__(self): """ Identify and return all specific pages in a queryset, and return them in the same order, with any annotations intact. """ from wagtail.models import Page qs = self.queryset annotation_aliases = qs.query.annotations.keys() values_qs = qs.values("pk", "content_type", *annotation_aliases) # Gather pages in batches to reduce peak memory usage for values in self._get_chunks(values_qs): annotations_by_pk = defaultdict(list) if annotation_aliases: # Extract annotation results keyed by pk so we can reapply to fetched pages. for data in values: annotations_by_pk[data["pk"]] = { k: v for k, v in data.items() if k in annotation_aliases } pks_and_types = [[v["pk"], v["content_type"]] for v in values] pks_by_type = defaultdict(list) for pk, content_type in pks_and_types: pks_by_type[content_type].append(pk) # Content types are cached by ID, so this will not run any queries. content_types = { pk: ContentType.objects.get_for_id(pk) for _, pk in pks_and_types } # Get the specific instances of all pages, one model class at a time. pages_by_type = {} missing_pks = [] for content_type, pks in pks_by_type.items(): # look up model class for this content type, falling back on the original # model (i.e. Page) if the more specific one is missing model = content_types[content_type].model_class() or qs.model pages = model.objects.filter(pk__in=pks) if qs._defer_streamfields: pages = pages.defer_streamfields() pages_for_type = {page.pk: page for page in pages} pages_by_type[content_type] = pages_for_type missing_pks.extend(pk for pk in pks if pk not in pages_for_type) # Fetch generic pages to supplement missing items if missing_pks: generic_pages = ( Page.objects.filter(pk__in=missing_pks) .select_related("content_type") .in_bulk() ) warnings.warn( "Specific versions of the following pages could not be found. " "This is most likely because a database migration has removed " "the relevant table or record since the page was created:\n{}".format( [ {"id": p.id, "title": p.title, "type": p.content_type} for p in generic_pages.values() ] ), category=RuntimeWarning, ) else: generic_pages = {} # Yield all pages in the order they occurred in the original query. for pk, content_type in pks_and_types: try: page = pages_by_type[content_type][pk] except KeyError: page = generic_pages[pk] if annotation_aliases: # Reapply annotations before returning for annotation, value in annotations_by_pk.get(page.pk, {}).items(): setattr(page, annotation, value) yield page def _get_chunks(self, queryset) -> Iterable[Tuple[Dict[str, Any]]]: if not self.chunked_fetch: # The entire result will be stored in memory, so there is no # benefit to splitting the result yield tuple(queryset) else: # Iterate through the queryset, returning the rows in manageable # chunks for self.__iter__() to fetch full pages for current_chunk = [] for r in queryset.iterator(self.chunk_size): current_chunk.append(r) if len(current_chunk) == self.chunk_size: yield tuple(current_chunk) current_chunk.clear() # Return any left-overs if current_chunk: yield tuple(current_chunk) class DeferredSpecificIterable(ModelIterable): def __iter__(self): for obj in super().__iter__(): if obj.specific_class: yield obj.specific_deferred else: warnings.warn( "A specific version of the following page could not be returned " "because the specific page model is not present on the active " f"branch: <Page id='{obj.id}' title='{obj.title}' " f"type='{obj.content_type}'>", category=RuntimeWarning, ) yield obj
bsd-3-clause
fe73d4e3a03dd910b529464dc625271e
36.127869
108
0.585747
4.50169
false
false
false
false
wagtail/wagtail
wagtail/whitelist.py
4
5662
""" A generic HTML whitelisting engine, designed to accommodate subclassing to override specific rules. """ import re from bs4 import BeautifulSoup, Comment, NavigableString, Tag from django.utils.html import escape ALLOWED_URL_SCHEMES = ["http", "https", "ftp", "mailto", "tel"] PROTOCOL_RE = re.compile("^[a-z0-9][-+.a-z0-9]*:") def check_url(url_string): # Remove control characters and other disallowed characters # Browsers sometimes ignore these, so that 'jav\tascript:alert("XSS")' # is treated as a valid javascript: link unescaped = url_string.lower() unescaped = unescaped.replace("&lt;", "<") unescaped = unescaped.replace("&gt;", ">") unescaped = unescaped.replace("&amp;", "&") unescaped = re.sub(r"[`\000-\040\177-\240\s]+", "", unescaped) unescaped = unescaped.replace("\ufffd", "") if PROTOCOL_RE.match(unescaped): protocol = unescaped.split(":", 1)[0] if protocol not in ALLOWED_URL_SCHEMES: return None return url_string def attribute_rule(allowed_attrs): """ Generator for functions that can be used as entries in Whitelister.element_rules. These functions accept a tag, and modify its attributes by looking each attribute up in the 'allowed_attrs' dict defined here: * if the lookup fails, drop the attribute * if the lookup returns a callable, replace the attribute with the result of calling it - for example `{'title': uppercase}` will replace 'title' with the result of uppercasing the title. If the callable returns None, the attribute is dropped. * if the lookup returns a truthy value, keep the attribute; if falsy, drop it """ def fn(tag): for attr, val in list(tag.attrs.items()): rule = allowed_attrs.get(attr) if rule: if callable(rule): new_val = rule(val) if new_val is None: del tag[attr] else: tag[attr] = new_val else: # rule is not callable, just truthy - keep the attribute pass else: # rule is falsy or absent - remove the attribute del tag[attr] return fn allow_without_attributes = attribute_rule({}) DEFAULT_ELEMENT_RULES = { "[document]": allow_without_attributes, "a": attribute_rule({"href": check_url}), "b": allow_without_attributes, "br": allow_without_attributes, "div": allow_without_attributes, "em": allow_without_attributes, "h1": allow_without_attributes, "h2": allow_without_attributes, "h3": allow_without_attributes, "h4": allow_without_attributes, "h5": allow_without_attributes, "h6": allow_without_attributes, "hr": allow_without_attributes, "i": allow_without_attributes, "img": attribute_rule( {"src": check_url, "width": True, "height": True, "alt": True} ), "li": allow_without_attributes, "ol": allow_without_attributes, "p": allow_without_attributes, "strong": allow_without_attributes, "sub": allow_without_attributes, "sup": allow_without_attributes, "ul": allow_without_attributes, } class Whitelister: element_rules = DEFAULT_ELEMENT_RULES def clean(self, html): """Clean up an HTML string to contain just the allowed elements / attributes""" doc = BeautifulSoup(html, "html5lib") self.clean_node(doc, doc) # Pass strings through django.utils.html.escape when generating the final HTML. # This differs from BeautifulSoup's default EntitySubstitution.substitute_html formatter # in that it escapes " to &quot; as well as escaping < > & - if we don't do this, then # BeautifulSoup will try to be clever and use single-quotes to wrap attribute values, # which confuses our regexp-based db-HTML-to-real-HTML conversion. return doc.decode(formatter=escape) def clean_node(self, doc, node): """Clean a BeautifulSoup document in-place""" if isinstance(node, NavigableString): self.clean_string_node(doc, node) elif isinstance(node, Tag): self.clean_tag_node(doc, node) # This branch is here in case node is a BeautifulSoup object that does # not inherit from NavigableString or Tag. I can't find any examples # of such a thing at the moment, so this branch is untested. else: # pragma: no cover self.clean_unknown_node(doc, node) def clean_string_node(self, doc, node): # Remove comments if isinstance(node, Comment): node.extract() return # by default, nothing needs to be done to whitelist string nodes pass def clean_tag_node(self, doc, tag): # first, whitelist the contents of this tag # NB tag.contents will change while this iteration is running, so we need # to capture the initial state into a static list() and iterate over that # to avoid losing our place in the sequence. for child in list(tag.contents): self.clean_node(doc, child) # see if there is a rule in element_rules for this tag type try: rule = self.element_rules[tag.name] except KeyError: # don't recognise this tag name, so KILL IT WITH FIRE tag.unwrap() return # apply the rule rule(tag) def clean_unknown_node(self, doc, node): # don't know what type of object this is, so KILL IT WITH FIRE node.decompose()
bsd-3-clause
3b84113bbc5ba91615eb6ec42e2546b3
35.529032
96
0.625044
4.044286
false
false
false
false
nephila/djangocms-blog
djangocms_blog/migrations/0011_auto_20151024_1809.py
1
3170
import aldryn_apphooks_config.fields import django.utils.timezone from django.db import migrations, models from djangocms_blog.settings import get_setting class Migration(migrations.Migration): dependencies = [ ("djangocms_blog", "0010_auto_20150923_1151"), ] operations = [ migrations.AddField( model_name="blogconfigtranslation", name="object_name", field=models.CharField( verbose_name="object name", default=get_setting("DEFAULT_OBJECT_NAME"), max_length=234 ), ), migrations.AlterField( model_name="authorentriesplugin", name="app_config", field=aldryn_apphooks_config.fields.AppHookConfigField( blank=True, help_text="When selecting a value, the form is reloaded to get the updated default", to="djangocms_blog.BlogConfig", verbose_name="app. config", null=True, ), ), migrations.AlterField( model_name="blogcategory", name="app_config", field=aldryn_apphooks_config.fields.AppHookConfigField( help_text="When selecting a value, the form is reloaded to get the updated default", to="djangocms_blog.BlogConfig", verbose_name="app. config", null=True, ), ), migrations.AlterField( model_name="genericblogplugin", name="app_config", field=aldryn_apphooks_config.fields.AppHookConfigField( blank=True, help_text="When selecting a value, the form is reloaded to get the updated default", to="djangocms_blog.BlogConfig", verbose_name="app. config", null=True, ), ), migrations.AlterField( model_name="latestpostsplugin", name="app_config", field=aldryn_apphooks_config.fields.AppHookConfigField( blank=True, help_text="When selecting a value, the form is reloaded to get the updated default", to="djangocms_blog.BlogConfig", verbose_name="app. config", null=True, ), ), migrations.AlterField( model_name="post", name="app_config", field=aldryn_apphooks_config.fields.AppHookConfigField( help_text="When selecting a value, the form is reloaded to get the updated default", to="djangocms_blog.BlogConfig", verbose_name="app. config", null=True, ), ), migrations.AlterField( model_name="post", name="date_published", field=models.DateTimeField(verbose_name="published since", default=django.utils.timezone.now), ), migrations.AlterField( model_name="post", name="date_published_end", field=models.DateTimeField(blank=True, verbose_name="published until", null=True), ), ]
bsd-3-clause
c56e5865a22a8dcd3541a97cfd2319f3
36.294118
106
0.555836
4.561151
false
true
false
false
nephila/djangocms-blog
tests/media_app/models.py
1
1822
import re import requests from cms.models import CMSPlugin from django.db import models from djangocms_blog.media.base import MediaAttachmentPluginMixin class YoutTubeVideo(MediaAttachmentPluginMixin, CMSPlugin): url = models.URLField("video URL") _media_autoconfiguration = { "params": [ re.compile("^https://youtu.be/(?P<media_id>[-\\w]+)$"), re.compile("^https://www.youtube.com/watch\\?v=(?P<media_id>[-\\w]+)$"), ], "thumb_url": "https://img.youtube.com/vi/%(media_id)s/hqdefault.jpg", "main_url": "https://img.youtube.com/vi/%(media_id)s/maxresdefault.jpg", "callable": None, } def __str__(self): return self.url @property def media_url(self): return self.url class Vimeo(MediaAttachmentPluginMixin, CMSPlugin): url = models.URLField("Video URL") _media_autoconfiguration = { "params": [re.compile("^https://vimeo.com/(?P<media_id>[-0-9]+)$")], "thumb_url": "%(thumb_url)s", "main_url": "%(main_url)s", "callable": "vimeo_data", } def __str__(self): return self.url @property def media_url(self): return self.url @property def media_title(self): try: return self.media_params["title"] except KeyError: return None def vimeo_data(self, media_id): response = requests.get( "https://vimeo.com/api/v2/video/{media_id}.json".format( media_id=media_id, ) ) json = response.json() data = {} if json: data = json[0] data.update( {"media_id": media_id, "main_url": data["thumbnail_large"], "thumb_url": data["thumbnail_medium"]} ) return data
bsd-3-clause
27bc45cb1c7bfbb736934a3f9bcda438
25.794118
114
0.555982
3.544747
false
false
false
false
ros/ros
core/roslib/src/roslib/resources.py
1
4541
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # """ Warning: do not use this library. It is unstable and most of the routines here have been superseded by other libraries (e.g. rospkg). These routines will likely be *deleted* in future releases. """ import os import roslib.manifest import roslib.names import roslib.packages def _get_manifest_by_dir(package_dir): """ Helper routine for loading Manifest instances @param package_dir: package directory location @type package_dir: str @return: manifest for package @rtype: Manifest """ f = os.path.join(package_dir, roslib.manifest.MANIFEST_FILE) if f: return roslib.manifest.parse_file(f) else: return None def list_package_resources_by_dir(package_dir, include_depends, subdir, rfilter=os.path.isfile): """ List resources in a package directory within a particular subdirectory. This is useful for listing messages, services, etc... @param package_dir: package directory location @type package_dir: str @param subdir: name of subdirectory @type subdir: str @param include_depends: if True, include resources in dependencies as well @type include_depends: bool @param rfilter: resource filter function that returns true if filename is the desired resource type @type rfilter: fn(filename)->bool """ package = os.path.basename(package_dir) resources = [] dir = roslib.packages._get_pkg_subdir_by_dir(package_dir, subdir, False) if os.path.isdir(dir): resources = [roslib.names.resource_name(package, f, my_pkg=package) for f in os.listdir(dir) if rfilter(os.path.join(dir, f))] else: resources = [] if include_depends: depends = _get_manifest_by_dir(package_dir).depends dirs = [roslib.packages.get_pkg_subdir(d.package, subdir, False) for d in depends] for (dep, dir_) in zip(depends, dirs): # py3k if not dir_ or not os.path.isdir(dir_): continue resources.extend( [roslib.names.resource_name(dep.package, f, my_pkg=package) for f in os.listdir(dir_) if rfilter(os.path.join(dir_, f))]) return resources def list_package_resources(package, include_depends, subdir, rfilter=os.path.isfile): """ List resources in a package within a particular subdirectory. This is useful for listing messages, services, etc... @param package: package name @type package: str @param subdir: name of subdirectory @type subdir: str @param include_depends: if True, include resources in dependencies as well @type include_depends: bool @param rfilter: resource filter function that returns true if filename is the desired resource type @type rfilter: fn(filename)->bool """ package_dir = roslib.packages.get_pkg_dir(package) return list_package_resources_by_dir(package_dir, include_depends, subdir, rfilter)
bsd-3-clause
50b1e30d5f19c5c92902ac1c11edeafa
40.66055
103
0.713499
4.018584
false
false
false
false
ros/ros
tools/rosboost_cfg/src/rosboost_cfg/rosboost_cfg.py
1
14144
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2010, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from __future__ import print_function import os import platform import sys from glob import glob from optparse import OptionParser lib_suffix = 'so' if (sys.platform == 'darwin'): lib_suffix = 'dylib' link_static = 'ROS_BOOST_LINK' in os.environ and os.environ['ROS_BOOST_LINK'] == 'static' if (link_static): lib_suffix = 'a' no_L_or_I = 'ROS_BOOST_NO_L_OR_I' in os.environ boost_version = None if ('ROS_BOOST_VERSION' in os.environ and len(os.environ['ROS_BOOST_VERSION']) > 0): ver = os.environ['ROS_BOOST_VERSION'] ver = ver.split('.') boost_version = [int(v) for v in ver] if (len(boost_version) == 2): boost_version.append(0) def print_usage_and_exit(): print('Usage: rosboost-cfg --lflags [thread,regex,graph,...]') print(' rosboost-cfg --cflags') print(' rosboost-cfg --libs [thread,regex,graph,...]') print(' rosboost-cfg --include_dirs') print(' rosboost-cfg --lib_dirs') print(' rosboost-cfg --root') sys.exit(1) class BoostError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Version(object): def __init__(self, major, minor, patch, root, include_dir, lib_dir, is_default_search_location): self.major = major self.minor = minor self.patch = patch self.root = root self.include_dir = include_dir self.lib_dir = lib_dir self.is_default_search_location = is_default_search_location self.is_system_install = os.path.split(self.include_dir)[0] == self.root def __cmp__(self, other): if (self.major != other.major): if self.major < other.major: return -1 else: return 1 if (self.minor != other.minor): if self.minor < other.minor: return -1 else: return 1 if (self.patch != other.patch): if self.patch < other.patch: return -1 else: return 1 return 0 def __repr__(self): return repr((self.major, self.minor, self.patch, self.root, self.include_dir, self.is_default_search_location, self.is_system_install)) def find_lib_dir(root_dir, multiarch=''): # prefer lib64 unless explicitly specified in the environment if ('ROS_BOOST_LIB_DIR_NAME' in os.environ): possible_dirs = [os.path.join(root_dir, os.environ['ROS_BOOST_LIB_DIR_NAME'])] else: possible_dirs = [os.path.join(root_dir, 'lib64'), os.path.join(root_dir, 'lib')] if multiarch: possible_dirs = [os.path.join(root_dir, 'lib/%s' % multiarch)] + possible_dirs for p in possible_dirs: glob_files = glob('%s*' % (os.path.join(p, 'libboost*'))) if (len(glob_files) > 0): return p return None def extract_versions(dir, is_default_search_location, multiarch=''): version_paths = [os.path.join(dir, 'version.hpp'), os.path.join(dir, 'boost', 'version.hpp')] glob_dirs = glob('%s*' % (os.path.join(dir, 'boost-'))) [version_paths.append(os.path.join(gdir, 'boost', 'version.hpp')) for gdir in glob_dirs] versions = [] for p in version_paths: ver_string = '' if (os.path.isfile(p)): fh = open(p, 'r') lines = fh.readlines() fh.close() for line in lines: if line.find('#define BOOST_VERSION ') > -1: def_string = line.split() ver_string = def_string[2] ver_int = int(ver_string) patch = ver_int % 100 minor = ver_int / 100 % 1000 major = ver_int / 100000 include_dir = os.path.split(os.path.split(p)[0])[0] root_dir = os.path.split(dir)[0] lib_dir = find_lib_dir(root_dir, multiarch) versions.append(Version(major, minor, patch, root_dir, include_dir, lib_dir, is_default_search_location)) return versions def find_versions(search_paths, multiarch=''): vers = [] for path, system in search_paths: path = os.path.join(path, 'include') pvers = extract_versions(path, system, multiarch) [vers.append(ver) for ver in pvers] if (len(vers) == 0): return None if (boost_version is not None): for v in vers: if (v.major == boost_version[0] and v.minor == boost_version[1] and v.patch == boost_version[2]): return [v] raise BoostError('Could not find boost version %s required by ROS_BOOST_VERSION environment variable' % (boost_version)) vers.sort() return vers def find_boost(search_paths, multiarch=''): result = find_versions(search_paths, multiarch) if result is None: return None if len(result) > 1: sys.stderr.write("WARN, found multiple boost versions '%s', using latest" % result) return result[-1] def search_paths(sysroot): _search_paths = [(sysroot+'/usr', True), (sysroot+'/usr/local', True), (None if 'INCLUDE_DIRS' not in os.environ else os.environ['INCLUDE_DIRS'], True), (None if 'CPATH' not in os.environ else os.environ['CPATH'], True), (None if 'C_INCLUDE_PATH' not in os.environ else os.environ['C_INCLUDE_PATH'], True), (None if 'CPLUS_INCLUDE_PATH' not in os.environ else os.environ['CPLUS_INCLUDE_PATH'], True), (None if 'ROS_BOOST_ROOT' not in os.environ else os.environ['ROS_BOOST_ROOT'], False)] search_paths = [] for (str, system) in _search_paths: if (str is not None): dirs = str.split(':') for dir in dirs: if (len(dir) > 0): if (dir.endswith('/include')): dir = dir[:-len('/include')] search_paths.append((dir, system)) return search_paths def lib_dir(ver): return ver.lib_dir def find_lib(ver, name, full_lib=link_static): global lib_suffix global link_static dynamic_search_paths = [] static_search_paths = [] if (ver.is_system_install): dynamic_search_paths = ['libboost_%s-mt.%s' % (name, lib_suffix), 'libboost_%s.%s' % (name, lib_suffix)] static_search_paths = ['libboost_%s-mt.a' % (name), 'libboost_%s.a' % (name)] else: dynamic_search_paths = ['libboost_%s*%s_%s*.%s' % (name, ver.major, ver.minor, lib_suffix), 'libboost_%s-mt*.%s' % (name, lib_suffix), 'libboost_%s*.%s' % (name, lib_suffix)] static_search_paths = ['libboost_%s*%s_%s*.a' % (name, ver.major, ver.minor), 'libboost_%s-mt*.a' % (name), 'libboost_%s*.a' % (name)] # Boost.Python needs some special handling on some systems (Karmic), since it may have per-python-version libs if (name == 'python'): python_ver = platform.python_version().split('.') dynamic_search_paths = ['libboost_%s-mt-py%s%s.%s' % (name, python_ver[0], python_ver[1], lib_suffix), 'libboost_%s-py%s%s.%s' % (name, python_ver[0], python_ver[1], lib_suffix)] + dynamic_search_paths static_search_paths = ['libboost_%s-mt-py%s%s.a' % (name, python_ver[0], python_ver[1]), 'libboost_%s-py%s%s.a' % (name, python_ver[0], python_ver[1])] + static_search_paths search_paths = static_search_paths if link_static else dynamic_search_paths dir = lib_dir(ver) if dir is None: raise BoostError('Could not locate library [%s], version %s' % (name, ver)) for p in search_paths: globstr = os.path.join(dir, p) libs = glob(globstr) if (len(libs) > 0): if (full_lib): return libs[0] else: return os.path.basename(libs[0]) raise BoostError('Could not locate library [%s], version %s in lib directory [%s]' % (name, ver, dir)) def include_dirs(ver, prefix=''): if ver.is_system_install or no_L_or_I: return '' return ' %s%s' % (prefix, ver.include_dir) def cflags(ver): return include_dirs(ver, '-I') def lib_dir_flags(ver): if not ver.is_default_search_location: dir = lib_dir(ver) return ' -L%s -Wl,-rpath,%s' % (dir, dir) return '' def lib_flags(ver, name): lib = find_lib(ver, name) if (link_static): return ' %s' % (lib) else: # Cut off "lib" and extension (.so/.a/.dylib/etc.) return ' -l%s' % (os.path.splitext(lib)[0][len('lib'):]) def lflags(ver, libs): s = lib_dir_flags(ver) + ' ' for lib in libs: s += lib_flags(ver, lib) + ' ' return s def libs(ver, libs): s = '' for lib in libs: s += find_lib(ver, lib, True) + ' ' return s def lib_dirs(ver): if (ver.is_default_search_location or no_L_or_I): return '' return lib_dir(ver) OPTIONS = ['libs', 'include_dirs', 'lib_dirs', 'cflags', 'lflags', 'root', 'print_versions', 'version'] def check_one_option(options, key): for k in dir(options): if (k in OPTIONS): v = getattr(options, k) if (k != key and v): raise BoostError('Only one option (excepting sysroot) is allowed at a time') def main(): if (len(sys.argv) < 2): print_usage_and_exit() parser = OptionParser() parser.add_option('-l', '--libs', dest='libs', type='string', help='') parser.add_option('-i', '--include_dirs', dest='include_dirs', action='store_true', default=False, help='') parser.add_option('-d', '--lib_dirs', dest='lib_dirs', action='store_true', help='') parser.add_option('-c', '--cflags', dest='cflags', action='store_true', default=False, help='') parser.add_option('-f', '--lflags', dest='lflags', type='string', help='') parser.add_option('-r', '--root', dest='root', action='store_true', default=False, help='') parser.add_option('-p', '--print_versions', dest='print_versions', action='store_true', default=False, help='') parser.add_option('-v', '--version', dest='version', action='store_true', default=False, help='') parser.add_option('-s', '--sysroot', dest='sysroot', type='string', default='', help='Location of the system root (usually toolchain root).') parser.add_option('-m', '--multiarch', dest='multiarch', type='string', default='', help="Name of multiarch to search below 'lib' folder for libraries.") (options, args) = parser.parse_args() if (options.print_versions): check_one_option(options, 'print_versions') for ver in find_versions(search_paths(options.sysroot), options.multiarch): print('%s.%s.%s root=%s include_dir=%s' % (ver.major, ver.minor, ver.patch, ver.root, ver.include_dir)) return ver = find_boost(search_paths(options.sysroot), options.multiarch) if ver is None: raise BoostError('Cannot find boost in any of %s' % search_paths(options.sysroot)) sys.exit(0) if options.version: check_one_option(options, 'version') print('%s.%s.%s root=%s include_dir=%s' % (ver.major, ver.minor, ver.patch, ver.root, ver.include_dir)) return if ver.major < 1 or (ver.major == 1 and ver.minor < 37): raise BoostError('Boost version %s.%s.%s does not meet the minimum requirements of boost 1.37.0' % (ver.major, ver.minor, ver.patch)) output = '' if (options.root): check_one_option(options, 'root') output = ver.root elif (options.libs): check_one_option(options, 'libs') output = libs(ver, options.libs.split(',')) elif (options.include_dirs): check_one_option(options, 'include_dirs') output = include_dirs(ver) elif (options.lib_dirs): check_one_option(options, 'lib_dirs') output = lib_dirs(ver) elif (options.cflags): check_one_option(options, 'cflags') output = cflags(ver) elif (options.lflags): check_one_option(options, 'lflags') output = lflags(ver, options.lflags.split(',')) else: print_usage_and_exit() print(output.strip()) if __name__ == '__main__': main()
bsd-3-clause
6b166889b3cf7b65bfaf8301556ae3b1
35.266667
157
0.590003
3.527182
false
false
false
false
mwaskom/seaborn
seaborn/_compat.py
1
5742
import numpy as np import matplotlib as mpl from seaborn.external.version import Version def MarkerStyle(marker=None, fillstyle=None): """ Allow MarkerStyle to accept a MarkerStyle object as parameter. Supports matplotlib < 3.3.0 https://github.com/matplotlib/matplotlib/pull/16692 """ if isinstance(marker, mpl.markers.MarkerStyle): if fillstyle is None: return marker else: marker = marker.get_marker() return mpl.markers.MarkerStyle(marker, fillstyle) def norm_from_scale(scale, norm): """Produce a Normalize object given a Scale and min/max domain limits.""" # This is an internal maplotlib function that simplifies things to access # It is likely to become part of the matplotlib API at some point: # https://github.com/matplotlib/matplotlib/issues/20329 if isinstance(norm, mpl.colors.Normalize): return norm if scale is None: return None if norm is None: vmin = vmax = None else: vmin, vmax = norm # TODO more helpful error if this fails? class ScaledNorm(mpl.colors.Normalize): def __call__(self, value, clip=None): # From github.com/matplotlib/matplotlib/blob/v3.4.2/lib/matplotlib/colors.py # See github.com/matplotlib/matplotlib/tree/v3.4.2/LICENSE value, is_scalar = self.process_value(value) self.autoscale_None(value) if self.vmin > self.vmax: raise ValueError("vmin must be less or equal to vmax") if self.vmin == self.vmax: return np.full_like(value, 0) if clip is None: clip = self.clip if clip: value = np.clip(value, self.vmin, self.vmax) # ***** Seaborn changes start **** t_value = self.transform(value).reshape(np.shape(value)) t_vmin, t_vmax = self.transform([self.vmin, self.vmax]) # ***** Seaborn changes end ***** if not np.isfinite([t_vmin, t_vmax]).all(): raise ValueError("Invalid vmin or vmax") t_value -= t_vmin t_value /= (t_vmax - t_vmin) t_value = np.ma.masked_invalid(t_value, copy=False) return t_value[0] if is_scalar else t_value new_norm = ScaledNorm(vmin, vmax) new_norm.transform = scale.get_transform().transform return new_norm def scale_factory(scale, axis, **kwargs): """ Backwards compatability for creation of independent scales. Matplotlib scales require an Axis object for instantiation on < 3.4. But the axis is not used, aside from extraction of the axis_name in LogScale. """ modify_transform = False if Version(mpl.__version__) < Version("3.4"): if axis[0] in "xy": modify_transform = True axis = axis[0] base = kwargs.pop("base", None) if base is not None: kwargs[f"base{axis}"] = base nonpos = kwargs.pop("nonpositive", None) if nonpos is not None: kwargs[f"nonpos{axis}"] = nonpos if isinstance(scale, str): class Axis: axis_name = axis axis = Axis() scale = mpl.scale.scale_factory(scale, axis, **kwargs) if modify_transform: transform = scale.get_transform() transform.base = kwargs.get("base", 10) if kwargs.get("nonpositive") == "mask": # Setting a private attribute, but we only get here # on an old matplotlib, so this won't break going forwards transform._clip = False return scale def set_scale_obj(ax, axis, scale): """Handle backwards compatability with setting matplotlib scale.""" if Version(mpl.__version__) < Version("3.4"): # The ability to pass a BaseScale instance to Axes.set_{}scale was added # to matplotlib in version 3.4.0: GH: matplotlib/matplotlib/pull/19089 # Workaround: use the scale name, which is restrictive only if the user # wants to define a custom scale; they'll need to update the registry too. if scale.name is None: # Hack to support our custom Formatter-less CatScale return method = getattr(ax, f"set_{axis}scale") kws = {} if scale.name == "function": trans = scale.get_transform() kws["functions"] = (trans._forward, trans._inverse) method(scale.name, **kws) axis_obj = getattr(ax, f"{axis}axis") scale.set_default_locators_and_formatters(axis_obj) else: ax.set(**{f"{axis}scale": scale}) def get_colormap(name): """Handle changes to matplotlib colormap interface in 3.6.""" try: return mpl.colormaps[name] except AttributeError: return mpl.cm.get_cmap(name) def register_colormap(name, cmap): """Handle changes to matplotlib colormap interface in 3.6.""" try: if name not in mpl.colormaps: mpl.colormaps.register(cmap, name=name) except AttributeError: mpl.cm.register_cmap(name, cmap) def set_layout_engine(fig, engine): """Handle changes to auto layout engine interface in 3.6""" if hasattr(fig, "set_layout_engine"): fig.set_layout_engine(engine) else: if engine == "tight": fig.set_tight_layout(True) elif engine == "constrained": fig.set_constrained_layout(True) def share_axis(ax0, ax1, which): """Handle changes to post-hoc axis sharing.""" if Version(mpl.__version__) < Version("3.5.0"): group = getattr(ax0, f"get_shared_{which}_axes")() group.join(ax1, ax0) else: getattr(ax1, f"share{which}")(ax0)
bsd-3-clause
15f6d48d88ca8809b71c6a60f0d830e1
34.012195
88
0.606235
3.922131
false
false
false
false
mwaskom/seaborn
doc/sphinxext/gallery_generator.py
1
10739
""" Sphinx plugin to run example scripts and create a gallery page. Lightly modified from the mpld3 project. """ import os import os.path as op import re import glob import token import tokenize import shutil import warnings import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # noqa: E402 # Python 3 has no execfile def execfile(filename, globals=None, locals=None): with open(filename, "rb") as fp: exec(compile(fp.read(), filename, 'exec'), globals, locals) RST_TEMPLATE = """ .. currentmodule:: seaborn .. _{sphinx_tag}: {docstring} .. image:: {img_file} **seaborn components used:** {components} .. literalinclude:: {fname} :lines: {end_line}- """ INDEX_TEMPLATE = """ :html_theme.sidebar_secondary.remove: .. raw:: html <style type="text/css"> .thumb {{ position: relative; float: left; width: 180px; height: 180px; margin: 0; }} .thumb img {{ position: absolute; display: inline; left: 0; width: 170px; height: 170px; opacity:1.0; filter:alpha(opacity=100); /* For IE8 and earlier */ }} .thumb:hover img {{ -webkit-filter: blur(3px); -moz-filter: blur(3px); -o-filter: blur(3px); -ms-filter: blur(3px); filter: blur(3px); opacity:1.0; filter:alpha(opacity=100); /* For IE8 and earlier */ }} .thumb span {{ position: absolute; display: inline; left: 0; width: 170px; height: 170px; background: #000; color: #fff; visibility: hidden; opacity: 0; z-index: 100; }} .thumb p {{ position: absolute; top: 45%; width: 170px; font-size: 110%; color: #fff; }} .thumb:hover span {{ visibility: visible; opacity: .4; }} .caption {{ position: absolute; width: 180px; top: 170px; text-align: center !important; }} </style> .. _{sphinx_tag}: Example gallery =============== {toctree} {contents} .. raw:: html <div style="clear: both"></div> """ def create_thumbnail(infile, thumbfile, width=275, height=275, cx=0.5, cy=0.5, border=4): baseout, extout = op.splitext(thumbfile) im = matplotlib.image.imread(infile) rows, cols = im.shape[:2] x0 = int(cx * cols - .5 * width) y0 = int(cy * rows - .5 * height) xslice = slice(x0, x0 + width) yslice = slice(y0, y0 + height) thumb = im[yslice, xslice] thumb[:border, :, :3] = thumb[-border:, :, :3] = 0 thumb[:, :border, :3] = thumb[:, -border:, :3] = 0 dpi = 100 fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi) ax = fig.add_axes([0, 0, 1, 1], aspect='auto', frameon=False, xticks=[], yticks=[]) if all(thumb.shape): ax.imshow(thumb, aspect='auto', resample=True, interpolation='bilinear') else: warnings.warn( f"Bad thumbnail crop. {thumbfile} will be empty." ) fig.savefig(thumbfile, dpi=dpi) return fig def indent(s, N=4): """indent a string""" return s.replace('\n', '\n' + N * ' ') class ExampleGenerator: """Tools for generating an example page from a file""" def __init__(self, filename, target_dir): self.filename = filename self.target_dir = target_dir self.thumbloc = .5, .5 self.extract_docstring() with open(filename) as fid: self.filetext = fid.read() outfilename = op.join(target_dir, self.rstfilename) # Only actually run it if the output RST file doesn't # exist or it was modified less recently than the example file_mtime = op.getmtime(filename) if not op.exists(outfilename) or op.getmtime(outfilename) < file_mtime: self.exec_file() else: print(f"skipping {self.filename}") @property def dirname(self): return op.split(self.filename)[0] @property def fname(self): return op.split(self.filename)[1] @property def modulename(self): return op.splitext(self.fname)[0] @property def pyfilename(self): return self.modulename + '.py' @property def rstfilename(self): return self.modulename + ".rst" @property def htmlfilename(self): return self.modulename + '.html' @property def pngfilename(self): pngfile = self.modulename + '.png' return "_images/" + pngfile @property def thumbfilename(self): pngfile = self.modulename + '_thumb.png' return pngfile @property def sphinxtag(self): return self.modulename @property def pagetitle(self): return self.docstring.strip().split('\n')[0].strip() @property def plotfunc(self): match = re.search(r"sns\.(.+plot)\(", self.filetext) if match: return match.group(1) match = re.search(r"sns\.(.+map)\(", self.filetext) if match: return match.group(1) match = re.search(r"sns\.(.+Grid)\(", self.filetext) if match: return match.group(1) return "" @property def components(self): objects = re.findall(r"sns\.(\w+)\(", self.filetext) refs = [] for obj in objects: if obj[0].isupper(): refs.append(f":class:`{obj}`") else: refs.append(f":func:`{obj}`") return ", ".join(refs) def extract_docstring(self): """ Extract a module-level docstring """ lines = open(self.filename).readlines() start_row = 0 if lines[0].startswith('#!'): lines.pop(0) start_row = 1 docstring = '' first_par = '' line_iter = lines.__iter__() tokens = tokenize.generate_tokens(lambda: next(line_iter)) for tok_type, tok_content, _, (erow, _), _ in tokens: tok_type = token.tok_name[tok_type] if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'): continue elif tok_type == 'STRING': docstring = eval(tok_content) # If the docstring is formatted with several paragraphs, # extract the first one: paragraphs = '\n'.join(line.rstrip() for line in docstring.split('\n') ).split('\n\n') if len(paragraphs) > 0: first_par = paragraphs[0] break thumbloc = None for i, line in enumerate(docstring.split("\n")): m = re.match(r"^_thumb: (\.\d+),\s*(\.\d+)", line) if m: thumbloc = float(m.group(1)), float(m.group(2)) break if thumbloc is not None: self.thumbloc = thumbloc docstring = "\n".join([l for l in docstring.split("\n") if not l.startswith("_thumb")]) self.docstring = docstring self.short_desc = first_par self.end_line = erow + 1 + start_row def exec_file(self): print(f"running {self.filename}") plt.close('all') my_globals = {'pl': plt, 'plt': plt} execfile(self.filename, my_globals) fig = plt.gcf() fig.canvas.draw() pngfile = op.join(self.target_dir, self.pngfilename) thumbfile = op.join("example_thumbs", self.thumbfilename) self.html = f"<img src=../{self.pngfilename}>" fig.savefig(pngfile, dpi=75, bbox_inches="tight") cx, cy = self.thumbloc create_thumbnail(pngfile, thumbfile, cx=cx, cy=cy) def toctree_entry(self): return f" ./{op.splitext(self.htmlfilename)[0]}\n\n" def contents_entry(self): return (".. raw:: html\n\n" " <div class='thumb align-center'>\n" " <a href=./{}>\n" " <img src=../_static/{}>\n" " <span class='thumb-label'>\n" " <p>{}</p>\n" " </span>\n" " </a>\n" " </div>\n\n" "\n\n" "".format(self.htmlfilename, self.thumbfilename, self.plotfunc)) def main(app): static_dir = op.join(app.builder.srcdir, '_static') target_dir = op.join(app.builder.srcdir, 'examples') image_dir = op.join(app.builder.srcdir, 'examples/_images') thumb_dir = op.join(app.builder.srcdir, "example_thumbs") source_dir = op.abspath(op.join(app.builder.srcdir, '..', 'examples')) if not op.exists(static_dir): os.makedirs(static_dir) if not op.exists(target_dir): os.makedirs(target_dir) if not op.exists(image_dir): os.makedirs(image_dir) if not op.exists(thumb_dir): os.makedirs(thumb_dir) if not op.exists(source_dir): os.makedirs(source_dir) banner_data = [] toctree = ("\n\n" ".. toctree::\n" " :hidden:\n\n") contents = "\n\n" # Write individual example files for filename in sorted(glob.glob(op.join(source_dir, "*.py"))): ex = ExampleGenerator(filename, target_dir) banner_data.append({"title": ex.pagetitle, "url": op.join('examples', ex.htmlfilename), "thumb": op.join(ex.thumbfilename)}) shutil.copyfile(filename, op.join(target_dir, ex.pyfilename)) output = RST_TEMPLATE.format(sphinx_tag=ex.sphinxtag, docstring=ex.docstring, end_line=ex.end_line, components=ex.components, fname=ex.pyfilename, img_file=ex.pngfilename) with open(op.join(target_dir, ex.rstfilename), 'w') as f: f.write(output) toctree += ex.toctree_entry() contents += ex.contents_entry() if len(banner_data) < 10: banner_data = (4 * banner_data)[:10] # write index file index_file = op.join(target_dir, 'index.rst') with open(index_file, 'w') as index: index.write(INDEX_TEMPLATE.format(sphinx_tag="example_gallery", toctree=toctree, contents=contents)) def setup(app): app.connect('builder-inited', main)
bsd-3-clause
dcaf128639d537cae392eba3c4e3570e
26.3257
79
0.525375
3.732708
false
false
false
false
mwaskom/seaborn
tests/_core/test_properties.py
1
19306
import numpy as np import pandas as pd import matplotlib as mpl from matplotlib.colors import same_color, to_rgb, to_rgba import pytest from numpy.testing import assert_array_equal from seaborn.external.version import Version from seaborn._core.rules import categorical_order from seaborn._core.scales import Nominal, Continuous from seaborn._core.properties import ( Alpha, Color, Coordinate, EdgeWidth, Fill, LineStyle, LineWidth, Marker, PointSize, ) from seaborn._compat import MarkerStyle, get_colormap from seaborn.palettes import color_palette class DataFixtures: @pytest.fixture def num_vector(self, long_df): return long_df["s"] @pytest.fixture def num_order(self, num_vector): return categorical_order(num_vector) @pytest.fixture def cat_vector(self, long_df): return long_df["a"] @pytest.fixture def cat_order(self, cat_vector): return categorical_order(cat_vector) @pytest.fixture def dt_num_vector(self, long_df): return long_df["t"] @pytest.fixture def dt_cat_vector(self, long_df): return long_df["d"] @pytest.fixture def vectors(self, num_vector, cat_vector): return {"num": num_vector, "cat": cat_vector} class TestCoordinate(DataFixtures): def test_bad_scale_arg_str(self, num_vector): err = "Unknown magic arg for x scale: 'xxx'." with pytest.raises(ValueError, match=err): Coordinate("x").infer_scale("xxx", num_vector) def test_bad_scale_arg_type(self, cat_vector): err = "Magic arg for x scale must be str, not list." with pytest.raises(TypeError, match=err): Coordinate("x").infer_scale([1, 2, 3], cat_vector) class TestColor(DataFixtures): def assert_same_rgb(self, a, b): assert_array_equal(a[:, :3], b[:, :3]) def test_nominal_default_palette(self, cat_vector, cat_order): m = Color().get_mapping(Nominal(), cat_vector) n = len(cat_order) actual = m(np.arange(n)) expected = color_palette(None, n) for have, want in zip(actual, expected): assert same_color(have, want) def test_nominal_default_palette_large(self): vector = pd.Series(list("abcdefghijklmnopqrstuvwxyz")) m = Color().get_mapping(Nominal(), vector) actual = m(np.arange(26)) expected = color_palette("husl", 26) for have, want in zip(actual, expected): assert same_color(have, want) def test_nominal_named_palette(self, cat_vector, cat_order): palette = "Blues" m = Color().get_mapping(Nominal(palette), cat_vector) n = len(cat_order) actual = m(np.arange(n)) expected = color_palette(palette, n) for have, want in zip(actual, expected): assert same_color(have, want) def test_nominal_list_palette(self, cat_vector, cat_order): palette = color_palette("Reds", len(cat_order)) m = Color().get_mapping(Nominal(palette), cat_vector) actual = m(np.arange(len(palette))) expected = palette for have, want in zip(actual, expected): assert same_color(have, want) def test_nominal_dict_palette(self, cat_vector, cat_order): colors = color_palette("Greens") palette = dict(zip(cat_order, colors)) m = Color().get_mapping(Nominal(palette), cat_vector) n = len(cat_order) actual = m(np.arange(n)) expected = colors for have, want in zip(actual, expected): assert same_color(have, want) def test_nominal_dict_with_missing_keys(self, cat_vector, cat_order): palette = dict(zip(cat_order[1:], color_palette("Purples"))) with pytest.raises(ValueError, match="No entry in color dict"): Color("color").get_mapping(Nominal(palette), cat_vector) def test_nominal_list_too_short(self, cat_vector, cat_order): n = len(cat_order) - 1 palette = color_palette("Oranges", n) msg = rf"The edgecolor list has fewer values \({n}\) than needed \({n + 1}\)" with pytest.warns(UserWarning, match=msg): Color("edgecolor").get_mapping(Nominal(palette), cat_vector) def test_nominal_list_too_long(self, cat_vector, cat_order): n = len(cat_order) + 1 palette = color_palette("Oranges", n) msg = rf"The edgecolor list has more values \({n}\) than needed \({n - 1}\)" with pytest.warns(UserWarning, match=msg): Color("edgecolor").get_mapping(Nominal(palette), cat_vector) def test_continuous_default_palette(self, num_vector): cmap = color_palette("ch:", as_cmap=True) m = Color().get_mapping(Continuous(), num_vector) self.assert_same_rgb(m(num_vector), cmap(num_vector)) def test_continuous_named_palette(self, num_vector): pal = "flare" cmap = color_palette(pal, as_cmap=True) m = Color().get_mapping(Continuous(pal), num_vector) self.assert_same_rgb(m(num_vector), cmap(num_vector)) def test_continuous_tuple_palette(self, num_vector): vals = ("blue", "red") cmap = color_palette("blend:" + ",".join(vals), as_cmap=True) m = Color().get_mapping(Continuous(vals), num_vector) self.assert_same_rgb(m(num_vector), cmap(num_vector)) def test_continuous_callable_palette(self, num_vector): cmap = get_colormap("viridis") m = Color().get_mapping(Continuous(cmap), num_vector) self.assert_same_rgb(m(num_vector), cmap(num_vector)) def test_continuous_missing(self): x = pd.Series([1, 2, np.nan, 4]) m = Color().get_mapping(Continuous(), x) assert np.isnan(m(x)[2]).all() def test_bad_scale_values_continuous(self, num_vector): with pytest.raises(TypeError, match="Scale values for color with a Continuous"): Color().get_mapping(Continuous(["r", "g", "b"]), num_vector) def test_bad_scale_values_nominal(self, cat_vector): with pytest.raises(TypeError, match="Scale values for color with a Nominal"): Color().get_mapping(Nominal(get_colormap("viridis")), cat_vector) def test_bad_inference_arg(self, cat_vector): with pytest.raises(TypeError, match="A single scale argument for color"): Color().infer_scale(123, cat_vector) @pytest.mark.parametrize( "data_type,scale_class", [("cat", Nominal), ("num", Continuous)] ) def test_default(self, data_type, scale_class, vectors): scale = Color().default_scale(vectors[data_type]) assert isinstance(scale, scale_class) def test_default_numeric_data_category_dtype(self, num_vector): scale = Color().default_scale(num_vector.astype("category")) assert isinstance(scale, Nominal) def test_default_binary_data(self): x = pd.Series([0, 0, 1, 0, 1], dtype=int) scale = Color().default_scale(x) assert isinstance(scale, Continuous) # TODO default scales for other types @pytest.mark.parametrize( "values,data_type,scale_class", [ ("viridis", "cat", Nominal), # Based on variable type ("viridis", "num", Continuous), # Based on variable type ("muted", "num", Nominal), # Based on qualitative palette (["r", "g", "b"], "num", Nominal), # Based on list palette ({2: "r", 4: "g", 8: "b"}, "num", Nominal), # Based on dict palette (("r", "b"), "num", Continuous), # Based on tuple / variable type (("g", "m"), "cat", Nominal), # Based on tuple / variable type (get_colormap("inferno"), "num", Continuous), # Based on callable ] ) def test_inference(self, values, data_type, scale_class, vectors): scale = Color().infer_scale(values, vectors[data_type]) assert isinstance(scale, scale_class) assert scale.values == values def test_inference_binary_data(self): x = pd.Series([0, 0, 1, 0, 1], dtype=int) scale = Color().infer_scale("viridis", x) assert isinstance(scale, Nominal) def test_standardization(self): f = Color().standardize assert f("C3") == to_rgb("C3") assert f("dodgerblue") == to_rgb("dodgerblue") assert f((.1, .2, .3)) == (.1, .2, .3) assert f((.1, .2, .3, .4)) == (.1, .2, .3, .4) assert f("#123456") == to_rgb("#123456") assert f("#12345678") == to_rgba("#12345678") if Version(mpl.__version__) >= Version("3.4.0"): assert f("#123") == to_rgb("#123") assert f("#1234") == to_rgba("#1234") class ObjectPropertyBase(DataFixtures): def assert_equal(self, a, b): assert self.unpack(a) == self.unpack(b) def unpack(self, x): return x @pytest.mark.parametrize("data_type", ["cat", "num"]) def test_default(self, data_type, vectors): scale = self.prop().default_scale(vectors[data_type]) assert isinstance(scale, Nominal) @pytest.mark.parametrize("data_type", ["cat", "num"]) def test_inference_list(self, data_type, vectors): scale = self.prop().infer_scale(self.values, vectors[data_type]) assert isinstance(scale, Nominal) assert scale.values == self.values @pytest.mark.parametrize("data_type", ["cat", "num"]) def test_inference_dict(self, data_type, vectors): x = vectors[data_type] values = dict(zip(categorical_order(x), self.values)) scale = self.prop().infer_scale(values, x) assert isinstance(scale, Nominal) assert scale.values == values def test_dict_missing(self, cat_vector): levels = categorical_order(cat_vector) values = dict(zip(levels, self.values[:-1])) scale = Nominal(values) name = self.prop.__name__.lower() msg = f"No entry in {name} dictionary for {repr(levels[-1])}" with pytest.raises(ValueError, match=msg): self.prop().get_mapping(scale, cat_vector) @pytest.mark.parametrize("data_type", ["cat", "num"]) def test_mapping_default(self, data_type, vectors): x = vectors[data_type] mapping = self.prop().get_mapping(Nominal(), x) n = x.nunique() for i, expected in enumerate(self.prop()._default_values(n)): actual, = mapping([i]) self.assert_equal(actual, expected) @pytest.mark.parametrize("data_type", ["cat", "num"]) def test_mapping_from_list(self, data_type, vectors): x = vectors[data_type] scale = Nominal(self.values) mapping = self.prop().get_mapping(scale, x) for i, expected in enumerate(self.standardized_values): actual, = mapping([i]) self.assert_equal(actual, expected) @pytest.mark.parametrize("data_type", ["cat", "num"]) def test_mapping_from_dict(self, data_type, vectors): x = vectors[data_type] levels = categorical_order(x) values = dict(zip(levels, self.values[::-1])) standardized_values = dict(zip(levels, self.standardized_values[::-1])) scale = Nominal(values) mapping = self.prop().get_mapping(scale, x) for i, level in enumerate(levels): actual, = mapping([i]) expected = standardized_values[level] self.assert_equal(actual, expected) def test_mapping_with_null_value(self, cat_vector): mapping = self.prop().get_mapping(Nominal(self.values), cat_vector) actual = mapping(np.array([0, np.nan, 2])) v0, _, v2 = self.standardized_values expected = [v0, self.prop.null_value, v2] for a, b in zip(actual, expected): self.assert_equal(a, b) def test_unique_default_large_n(self): n = 24 x = pd.Series(np.arange(n)) mapping = self.prop().get_mapping(Nominal(), x) assert len({self.unpack(x_i) for x_i in mapping(x)}) == n def test_bad_scale_values(self, cat_vector): var_name = self.prop.__name__.lower() with pytest.raises(TypeError, match=f"Scale values for a {var_name} variable"): self.prop().get_mapping(Nominal(("o", "s")), cat_vector) class TestMarker(ObjectPropertyBase): prop = Marker values = ["o", (5, 2, 0), MarkerStyle("^")] standardized_values = [MarkerStyle(x) for x in values] def unpack(self, x): return ( x.get_path(), x.get_joinstyle(), x.get_transform().to_values(), x.get_fillstyle(), ) class TestLineStyle(ObjectPropertyBase): prop = LineStyle values = ["solid", "--", (1, .5)] standardized_values = [LineStyle._get_dash_pattern(x) for x in values] def test_bad_type(self): p = LineStyle() with pytest.raises(TypeError, match="^Linestyle must be .+, not list.$"): p.standardize([1, 2]) def test_bad_style(self): p = LineStyle() with pytest.raises(ValueError, match="^Linestyle string must be .+, not 'o'.$"): p.standardize("o") def test_bad_dashes(self): p = LineStyle() with pytest.raises(TypeError, match="^Invalid dash pattern"): p.standardize((1, 2, "x")) class TestFill(DataFixtures): @pytest.fixture def vectors(self): return { "cat": pd.Series(["a", "a", "b"]), "num": pd.Series([1, 1, 2]), "bool": pd.Series([True, True, False]) } @pytest.fixture def cat_vector(self, vectors): return vectors["cat"] @pytest.fixture def num_vector(self, vectors): return vectors["num"] @pytest.mark.parametrize("data_type", ["cat", "num", "bool"]) def test_default(self, data_type, vectors): x = vectors[data_type] scale = Fill().default_scale(x) assert isinstance(scale, Nominal) @pytest.mark.parametrize("data_type", ["cat", "num", "bool"]) def test_inference_list(self, data_type, vectors): x = vectors[data_type] scale = Fill().infer_scale([True, False], x) assert isinstance(scale, Nominal) assert scale.values == [True, False] @pytest.mark.parametrize("data_type", ["cat", "num", "bool"]) def test_inference_dict(self, data_type, vectors): x = vectors[data_type] values = dict(zip(x.unique(), [True, False])) scale = Fill().infer_scale(values, x) assert isinstance(scale, Nominal) assert scale.values == values def test_mapping_categorical_data(self, cat_vector): mapping = Fill().get_mapping(Nominal(), cat_vector) assert_array_equal(mapping([0, 1, 0]), [True, False, True]) def test_mapping_numeric_data(self, num_vector): mapping = Fill().get_mapping(Nominal(), num_vector) assert_array_equal(mapping([0, 1, 0]), [True, False, True]) def test_mapping_list(self, cat_vector): mapping = Fill().get_mapping(Nominal([False, True]), cat_vector) assert_array_equal(mapping([0, 1, 0]), [False, True, False]) def test_mapping_truthy_list(self, cat_vector): mapping = Fill().get_mapping(Nominal([0, 1]), cat_vector) assert_array_equal(mapping([0, 1, 0]), [False, True, False]) def test_mapping_dict(self, cat_vector): values = dict(zip(cat_vector.unique(), [False, True])) mapping = Fill().get_mapping(Nominal(values), cat_vector) assert_array_equal(mapping([0, 1, 0]), [False, True, False]) def test_cycle_warning(self): x = pd.Series(["a", "b", "c"]) with pytest.warns(UserWarning, match="The variable assigned to fill"): Fill().get_mapping(Nominal(), x) def test_values_error(self): x = pd.Series(["a", "b"]) with pytest.raises(TypeError, match="Scale values for fill must be"): Fill().get_mapping(Nominal("bad_values"), x) class IntervalBase(DataFixtures): def norm(self, x): return (x - x.min()) / (x.max() - x.min()) @pytest.mark.parametrize("data_type,scale_class", [ ("cat", Nominal), ("num", Continuous), ]) def test_default(self, data_type, scale_class, vectors): x = vectors[data_type] scale = self.prop().default_scale(x) assert isinstance(scale, scale_class) @pytest.mark.parametrize("arg,data_type,scale_class", [ ((1, 3), "cat", Nominal), ((1, 3), "num", Continuous), ([1, 2, 3], "cat", Nominal), ([1, 2, 3], "num", Nominal), ({"a": 1, "b": 3, "c": 2}, "cat", Nominal), ({2: 1, 4: 3, 8: 2}, "num", Nominal), ]) def test_inference(self, arg, data_type, scale_class, vectors): x = vectors[data_type] scale = self.prop().infer_scale(arg, x) assert isinstance(scale, scale_class) assert scale.values == arg def test_mapped_interval_numeric(self, num_vector): mapping = self.prop().get_mapping(Continuous(), num_vector) assert_array_equal(mapping([0, 1]), self.prop().default_range) def test_mapped_interval_categorical(self, cat_vector): mapping = self.prop().get_mapping(Nominal(), cat_vector) n = cat_vector.nunique() assert_array_equal(mapping([n - 1, 0]), self.prop().default_range) def test_bad_scale_values_numeric_data(self, num_vector): prop_name = self.prop.__name__.lower() err_stem = ( f"Values for {prop_name} variables with Continuous scale must be 2-tuple" ) with pytest.raises(TypeError, match=f"{err_stem}; not <class 'str'>."): self.prop().get_mapping(Continuous("abc"), num_vector) with pytest.raises(TypeError, match=f"{err_stem}; not 3-tuple."): self.prop().get_mapping(Continuous((1, 2, 3)), num_vector) def test_bad_scale_values_categorical_data(self, cat_vector): prop_name = self.prop.__name__.lower() err_text = f"Values for {prop_name} variables with Nominal scale" with pytest.raises(TypeError, match=err_text): self.prop().get_mapping(Nominal("abc"), cat_vector) class TestAlpha(IntervalBase): prop = Alpha class TestLineWidth(IntervalBase): prop = LineWidth def test_rcparam_default(self): with mpl.rc_context({"lines.linewidth": 2}): assert self.prop().default_range == (1, 4) class TestEdgeWidth(IntervalBase): prop = EdgeWidth def test_rcparam_default(self): with mpl.rc_context({"patch.linewidth": 2}): assert self.prop().default_range == (1, 4) class TestPointSize(IntervalBase): prop = PointSize def test_areal_scaling_numeric(self, num_vector): limits = 5, 10 scale = Continuous(limits) mapping = self.prop().get_mapping(scale, num_vector) x = np.linspace(0, 1, 6) expected = np.sqrt(np.linspace(*np.square(limits), num=len(x))) assert_array_equal(mapping(x), expected) def test_areal_scaling_categorical(self, cat_vector): limits = (2, 4) scale = Nominal(limits) mapping = self.prop().get_mapping(scale, cat_vector) assert_array_equal(mapping(np.arange(3)), [4, np.sqrt(10), 2])
bsd-3-clause
3b8ce62e0470ebe89a07fa845ca62709
32.171821
88
0.600694
3.481695
false
true
false
false
mwaskom/seaborn
tests/test_rcmod.py
1
8965
import pytest import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import numpy.testing as npt from seaborn import rcmod, palettes, utils def has_verdana(): """Helper to verify if Verdana font is present""" # This import is relatively lengthy, so to prevent its import for # testing other tests in this module not requiring this knowledge, # import font_manager here import matplotlib.font_manager as mplfm try: verdana_font = mplfm.findfont('Verdana', fallback_to_default=False) except: # noqa # if https://github.com/matplotlib/matplotlib/pull/3435 # gets accepted return False # otherwise check if not matching the logic for a 'default' one try: unlikely_font = mplfm.findfont("very_unlikely_to_exist1234", fallback_to_default=False) except: # noqa # if matched verdana but not unlikely, Verdana must exist return True # otherwise -- if they match, must be the same default return verdana_font != unlikely_font class RCParamFixtures: @pytest.fixture(autouse=True) def reset_params(self): yield rcmod.reset_orig() def flatten_list(self, orig_list): iter_list = map(np.atleast_1d, orig_list) flat_list = [item for sublist in iter_list for item in sublist] return flat_list def assert_rc_params(self, params): for k, v in params.items(): # Various subtle issues in matplotlib lead to unexpected # values for the backend rcParam, which isn't relevant here if k == "backend": continue if isinstance(v, np.ndarray): npt.assert_array_equal(mpl.rcParams[k], v) else: assert mpl.rcParams[k] == v def assert_rc_params_equal(self, params1, params2): for key, v1 in params1.items(): # Various subtle issues in matplotlib lead to unexpected # values for the backend rcParam, which isn't relevant here if key == "backend": continue v2 = params2[key] if isinstance(v1, np.ndarray): npt.assert_array_equal(v1, v2) else: assert v1 == v2 class TestAxesStyle(RCParamFixtures): styles = ["white", "dark", "whitegrid", "darkgrid", "ticks"] def test_default_return(self): current = rcmod.axes_style() self.assert_rc_params(current) def test_key_usage(self): _style_keys = set(rcmod._style_keys) for style in self.styles: assert not set(rcmod.axes_style(style)) ^ _style_keys def test_bad_style(self): with pytest.raises(ValueError): rcmod.axes_style("i_am_not_a_style") def test_rc_override(self): rc = {"axes.facecolor": "blue", "foo.notaparam": "bar"} out = rcmod.axes_style("darkgrid", rc) assert out["axes.facecolor"] == "blue" assert "foo.notaparam" not in out def test_set_style(self): for style in self.styles: style_dict = rcmod.axes_style(style) rcmod.set_style(style) self.assert_rc_params(style_dict) def test_style_context_manager(self): rcmod.set_style("darkgrid") orig_params = rcmod.axes_style() context_params = rcmod.axes_style("whitegrid") with rcmod.axes_style("whitegrid"): self.assert_rc_params(context_params) self.assert_rc_params(orig_params) @rcmod.axes_style("whitegrid") def func(): self.assert_rc_params(context_params) func() self.assert_rc_params(orig_params) def test_style_context_independence(self): assert set(rcmod._style_keys) ^ set(rcmod._context_keys) def test_set_rc(self): rcmod.set_theme(rc={"lines.linewidth": 4}) assert mpl.rcParams["lines.linewidth"] == 4 rcmod.set_theme() def test_set_with_palette(self): rcmod.reset_orig() rcmod.set_theme(palette="deep") assert utils.get_color_cycle() == palettes.color_palette("deep", 10) rcmod.reset_orig() rcmod.set_theme(palette="deep", color_codes=False) assert utils.get_color_cycle() == palettes.color_palette("deep", 10) rcmod.reset_orig() pal = palettes.color_palette("deep") rcmod.set_theme(palette=pal) assert utils.get_color_cycle() == palettes.color_palette("deep", 10) rcmod.reset_orig() rcmod.set_theme(palette=pal, color_codes=False) assert utils.get_color_cycle() == palettes.color_palette("deep", 10) rcmod.reset_orig() rcmod.set_theme() def test_reset_defaults(self): rcmod.reset_defaults() self.assert_rc_params(mpl.rcParamsDefault) rcmod.set_theme() def test_reset_orig(self): rcmod.reset_orig() self.assert_rc_params(mpl.rcParamsOrig) rcmod.set_theme() def test_set_is_alias(self): rcmod.set_theme(context="paper", style="white") params1 = mpl.rcParams.copy() rcmod.reset_orig() rcmod.set_theme(context="paper", style="white") params2 = mpl.rcParams.copy() self.assert_rc_params_equal(params1, params2) rcmod.set_theme() class TestPlottingContext(RCParamFixtures): contexts = ["paper", "notebook", "talk", "poster"] def test_default_return(self): current = rcmod.plotting_context() self.assert_rc_params(current) def test_key_usage(self): _context_keys = set(rcmod._context_keys) for context in self.contexts: missing = set(rcmod.plotting_context(context)) ^ _context_keys assert not missing def test_bad_context(self): with pytest.raises(ValueError): rcmod.plotting_context("i_am_not_a_context") def test_font_scale(self): notebook_ref = rcmod.plotting_context("notebook") notebook_big = rcmod.plotting_context("notebook", 2) font_keys = [ "font.size", "axes.labelsize", "axes.titlesize", "xtick.labelsize", "ytick.labelsize", "legend.fontsize", "legend.title_fontsize", ] for k in font_keys: assert notebook_ref[k] * 2 == notebook_big[k] def test_rc_override(self): key, val = "grid.linewidth", 5 rc = {key: val, "foo": "bar"} out = rcmod.plotting_context("talk", rc=rc) assert out[key] == val assert "foo" not in out def test_set_context(self): for context in self.contexts: context_dict = rcmod.plotting_context(context) rcmod.set_context(context) self.assert_rc_params(context_dict) def test_context_context_manager(self): rcmod.set_context("notebook") orig_params = rcmod.plotting_context() context_params = rcmod.plotting_context("paper") with rcmod.plotting_context("paper"): self.assert_rc_params(context_params) self.assert_rc_params(orig_params) @rcmod.plotting_context("paper") def func(): self.assert_rc_params(context_params) func() self.assert_rc_params(orig_params) class TestPalette(RCParamFixtures): def test_set_palette(self): rcmod.set_palette("deep") assert utils.get_color_cycle() == palettes.color_palette("deep", 10) rcmod.set_palette("pastel6") assert utils.get_color_cycle() == palettes.color_palette("pastel6", 6) rcmod.set_palette("dark", 4) assert utils.get_color_cycle() == palettes.color_palette("dark", 4) rcmod.set_palette("Set2", color_codes=True) assert utils.get_color_cycle() == palettes.color_palette("Set2", 8) assert mpl.colors.same_color( mpl.rcParams["patch.facecolor"], palettes.color_palette()[0] ) class TestFonts(RCParamFixtures): _no_verdana = not has_verdana() @pytest.mark.skipif(_no_verdana, reason="Verdana font is not present") def test_set_font(self): rcmod.set_theme(font="Verdana") _, ax = plt.subplots() ax.set_xlabel("foo") assert ax.xaxis.label.get_fontname() == "Verdana" rcmod.set_theme() def test_set_serif_font(self): rcmod.set_theme(font="serif") _, ax = plt.subplots() ax.set_xlabel("foo") assert ax.xaxis.label.get_fontname() in mpl.rcParams["font.serif"] rcmod.set_theme() @pytest.mark.skipif(_no_verdana, reason="Verdana font is not present") def test_different_sans_serif(self): rcmod.set_theme() rcmod.set_style(rc={"font.sans-serif": ["Verdana"]}) _, ax = plt.subplots() ax.set_xlabel("foo") assert ax.xaxis.label.get_fontname() == "Verdana" rcmod.set_theme()
bsd-3-clause
79267bd65fc911485912a0210789e4ca
27.826367
78
0.603904
3.578842
false
true
false
false
mwaskom/seaborn
examples/heat_scatter.py
2
1187
""" Scatterplot heatmap ------------------- _thumb: .5, .5 """ import seaborn as sns sns.set_theme(style="whitegrid") # Load the brain networks dataset, select subset, and collapse the multi-index df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) used_networks = [1, 5, 6, 7, 8, 12, 13, 17] used_columns = (df.columns .get_level_values("network") .astype(int) .isin(used_networks)) df = df.loc[:, used_columns] df.columns = df.columns.map("-".join) # Compute a correlation matrix and convert to long-form corr_mat = df.corr().stack().reset_index(name="correlation") # Draw each cell as a scatter point with varying size and color g = sns.relplot( data=corr_mat, x="level_0", y="level_1", hue="correlation", size="correlation", palette="vlag", hue_norm=(-1, 1), edgecolor=".7", height=10, sizes=(50, 250), size_norm=(-.2, .8), ) # Tweak the figure to finalize g.set(xlabel="", ylabel="", aspect="equal") g.despine(left=True, bottom=True) g.ax.margins(.02) for label in g.ax.get_xticklabels(): label.set_rotation(90) for artist in g.legend.legendHandles: artist.set_edgecolor(".7")
bsd-3-clause
725896fa49f34b2137f7e09e90720ccd
27.95122
78
0.636057
3.028061
false
false
false
false
mwaskom/seaborn
seaborn/_stats/aggregation.py
1
3267
from __future__ import annotations from dataclasses import dataclass from typing import ClassVar, Callable import pandas as pd from pandas import DataFrame from seaborn._core.scales import Scale from seaborn._core.groupby import GroupBy from seaborn._stats.base import Stat from seaborn._statistics import EstimateAggregator from seaborn._core.typing import Vector @dataclass class Agg(Stat): """ Aggregate data along the value axis using given method. Parameters ---------- func : str or callable Name of a :class:`pandas.Series` method or a vector -> scalar function. See Also -------- objects.Est : Aggregation with error bars. Examples -------- .. include:: ../docstrings/objects.Agg.rst """ func: str | Callable[[Vector], float] = "mean" group_by_orient: ClassVar[bool] = True def __call__( self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], ) -> DataFrame: var = {"x": "y", "y": "x"}.get(orient) res = ( groupby .agg(data, {var: self.func}) .dropna(subset=[var]) .reset_index(drop=True) ) return res @dataclass class Est(Stat): """ Calculate a point estimate and error bar interval. For additional information about the various `errorbar` choices, see the :doc:`errorbar tutorial </tutorial/error_bars>`. Parameters ---------- func : str or callable Name of a :class:`numpy.ndarray` method or a vector -> scalar function. errorbar : str, (str, float) tuple, or callable Name of errorbar method (one of "ci", "pi", "se" or "sd"), or a tuple with a method name ane a level parameter, or a function that maps from a vector to a (min, max) interval. n_boot : int Number of bootstrap samples to draw for "ci" errorbars. seed : int Seed for the PRNG used to draw bootstrap samples. Examples -------- .. include:: ../docstrings/objects.Est.rst """ func: str | Callable[[Vector], float] = "mean" errorbar: str | tuple[str, float] = ("ci", 95) n_boot: int = 1000 seed: int | None = None group_by_orient: ClassVar[bool] = True def _process( self, data: DataFrame, var: str, estimator: EstimateAggregator ) -> DataFrame: # Needed because GroupBy.apply assumes func is DataFrame -> DataFrame # which we could probably make more general to allow Series return res = estimator(data, var) return pd.DataFrame([res]) def __call__( self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale], ) -> DataFrame: boot_kws = {"n_boot": self.n_boot, "seed": self.seed} engine = EstimateAggregator(self.func, self.errorbar, **boot_kws) var = {"x": "y", "y": "x"}[orient] res = ( groupby .apply(data, self._process, var, engine) .dropna(subset=[var]) .reset_index(drop=True) ) res = res.fillna({f"{var}min": res[var], f"{var}max": res[var]}) return res @dataclass class Rolling(Stat): ... def __call__(self, data, groupby, orient, scales): ...
bsd-3-clause
8f2d1a8febbd05a7e0d5d4580c425056
26.686441
87
0.601163
3.870853
false
false
false
false
mwaskom/seaborn
examples/many_facets.py
1
1110
""" Plotting on a large number of facets ==================================== _thumb: .4, .3 """ import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set_theme(style="ticks") # Create a dataset with many short random walks rs = np.random.RandomState(4) pos = rs.randint(-1, 2, (20, 5)).cumsum(axis=1) pos -= pos[:, 0, np.newaxis] step = np.tile(range(5), 20) walk = np.repeat(range(20), 5) df = pd.DataFrame(np.c_[pos.flat, step, walk], columns=["position", "step", "walk"]) # Initialize a grid of plots with an Axes for each walk grid = sns.FacetGrid(df, col="walk", hue="walk", palette="tab20c", col_wrap=4, height=1.5) # Draw a horizontal line to show the starting point grid.refline(y=0, linestyle=":") # Draw a line plot to show the trajectory of each random walk grid.map(plt.plot, "step", "position", marker="o") # Adjust the tick positions and labels grid.set(xticks=np.arange(5), yticks=[-3, 3], xlim=(-.5, 4.5), ylim=(-3.5, 3.5)) # Adjust the arrangement of the plots grid.fig.tight_layout(w_pad=1)
bsd-3-clause
2216100e8521d169c35b2bfe764032eb
27.461538
66
0.636937
3
false
false
false
false
janelia-flyem/gala
gala/iterprogress.py
2
1826
import logging class NoProgressBar(object): def __init__(self, *args, **kwargs): pass def start(self, *args, **kwargs): pass def update(self, *args, **kwargs): pass def update_i(self, *args, **kwargs): pass def finish(self, *args, **kwargs): pass def set_title(self, *args, **kwargs): pass def with_progress(collection, length=None, title=None, pbar=NoProgressBar()): if length is None: length = len(collection) if title is not None: pbar.set_title(title) pbar.start(length) for elem in collection: yield elem pbar.update() try: from progressbar import ProgressBar, Percentage, Bar, ETA, RotatingMarker except ImportError: StandardProgressBar = NoProgressBar else: class StandardProgressBar(object): def __init__(self, title='Progress: '): self.title = title self.is_finished = False def start(self, total, widgets=None): if widgets is None: widgets = [self.title, RotatingMarker(), ' ', Percentage(), ' ', Bar(marker='='), ' ', ETA()] self.pbar = ProgressBar(widgets=widgets, maxval=total) self.pbar.start() self.i = 0 def update(self, step=1): self.i += step self.pbar.update(self.i) if self.i == self.pbar.maxval: self.finish() def update_i(self, value): self.i = value self.pbar.update(value) if value == self.pbar.maxval: self.finish() def finish(self): if self.is_finished: pass else: self.pbar.finish() self.is_finished = True def set_title(self, title): self.title = title
bsd-3-clause
f202a33224a171af60ac2b418575c31b
29.433333
77
0.548193
3.926882
false
false
false
false
janelia-flyem/gala
gala/features/squiggliness.py
2
1624
import numpy as np from . import base def compute_bounding_box(indices, shape): d = len(shape) unraveled_indices = np.concatenate( np.unravel_index(list(indices), shape)).reshape((-1,d), order='F') m = unraveled_indices.min(axis=0) M = unraveled_indices.max(axis=0) + np.ones(d) return m, M class Manager(base.Null): def __init__(self, ndim=3, *args, **kwargs): super(Manager, self).__init__() self.ndim = ndim def write_fm(self, json_fm={}): if 'feature_list' not in json_fm: json_fm['feature_list'] = [] json_fm['feature_list'].append('squiggliness') json_fm['squiggliness'] = {'ndim': self.ndim} return json_fm # cache is min and max coordinates of bounding box def create_edge_cache(self, g, n1, n2): edge_idxs = g.boundary(n1, n2) return np.concatenate( compute_bounding_box(edge_idxs, g.watershed.shape)) def update_edge_cache(self, g, e1, e2, dst, src): dst[:self.ndim] = np.concatenate( (dst[np.newaxis,:self.ndim], src[np.newaxis,:self.ndim]), axis=0).min(axis=0) dst[self.ndim:] = np.concatenate( (dst[np.newaxis,self.ndim:], src[np.newaxis,self.ndim:]), axis=0).max(axis=0) def compute_edge_features(self, g, n1, n2, cache=None): if cache is None: cache = g[n1][n2][self.default_cache] m, M = cache[:self.ndim], cache[self.ndim:] plane_surface = np.sort(M-m)[1:].prod() * (3.0-g.pad_thickness) return np.array([len(set(g.boundary(n1, n2))) / plane_surface])
bsd-3-clause
4ba64cbb0eeef27de3d30c54ec27d1ec
35.909091
74
0.586207
3.075758
false
false
false
false
janelia-flyem/gala
gala/features/base.py
1
5302
import numpy as np from .. import evaluate as ev class Null(object): def __init__(self, *args, **kwargs): self.default_cache = 'feature-cache' def __call__(self, g, n1, n2=None): return self.compute_features(g, n1, n2) def write_fm(self, json_fm={}): return json_fm def compute_features(self, g, n1, n2=None): if n2 is None: c1 = g.nodes[n1][self.default_cache] return self.compute_node_features(g, n1, c1) if g.nodes[n1]['size'] > g.nodes[n2]['size']: n1, n2 = n2, n1 # smaller node first c1, c2, ce = [d[self.default_cache] for d in [g.nodes[n1], g.nodes[n2], g.edges[n1, n2]]] return np.concatenate(( self.compute_node_features(g, n1, c1), self.compute_node_features(g, n2, c2), self.compute_edge_features(g, n1, n2, ce), self.compute_difference_features(g, n1, n2, c1, c2) )) def create_node_cache(self, *args, **kwargs): return np.array([]) def create_edge_cache(self, *args, **kwargs): return np.array([]) def update_node_cache(self, *args, **kwargs): pass def update_edge_cache(self, *args, **kwargs): pass def compute_node_features(self, *args, **kwargs): return np.array([]) def compute_edge_features(self, *args, **kwargs): return np.array([]) def compute_difference_features(self, *args, **kwargs): return np.array([]) class Composite(Null): def __init__(self, children=[], *args, **kwargs): super(Composite, self).__init__() self.children = children def write_fm(self, json_fm={}): for child in self.children: json_fm.update(child.write_fm(json_fm)) return json_fm def create_node_cache(self, *args, **kwargs): return [c.create_node_cache(*args, **kwargs) for c in self.children] def create_edge_cache(self, *args, **kwargs): return [c.create_edge_cache(*args, **kwargs) for c in self.children] def update_node_cache(self, g, n1, n2, dst, src): for i, child in enumerate(self.children): child.update_node_cache(g, n1, n2, dst[i], src[i]) def update_edge_cache(self, g, e1, e2, dst, src): for i, child in enumerate(self.children): child.update_edge_cache(g, e1, e2, dst[i], src[i]) def compute_node_features(self, g, n, cache=None): if cache is None: cache = g.nodes[n][self.default_cache] features = [] for i, child in enumerate(self.children): features.append(child.compute_node_features(g, n, cache[i])) return np.concatenate(features) def compute_edge_features(self, g, n1, n2, cache=None): if cache is None: cache = g.edges[n1, n2][self.default_cache] features = [] for i, child in enumerate(self.children): features.append(child.compute_edge_features(g, n1, n2, cache[i])) return np.concatenate(features) def compute_difference_features(self, g, n1, n2, cache1=None, cache2=None): if cache1 is None: cache1 = g.nodes[n1][self.default_cache] if cache2 is None: cache2 = g.nodes[n2][self.default_cache] features = [] for i, child in enumerate(self.children): features.append(child.compute_difference_features( g, n1, n2, cache1[i], cache2[i])) return np.concatenate(features) def _compute_delta_vi(ctable, fragments0, fragments1): c0 = np.sum(ctable[list(fragments0)], axis=0) c1 = np.sum(ctable[list(fragments1)], axis=0) cr = c0 + c1 p0 = np.sum(c0) p1 = np.sum(c1) pr = np.sum(cr) p0g = np.sum(ev.xlogx(c0)) p1g = np.sum(ev.xlogx(c1)) prg = np.sum(ev.xlogx(cr)) return (pr * np.log2(pr) - p0 * np.log2(p0) - p1 * np.log2(p1) - 2 * (prg - p0g - p1g)) class Mock(Null): ''' Mock feature manager to verify agglomerative learning works. This manager learns a different feature map for fragments vs agglomerated segments. It relies on knowing the ground truth for a given fragmentation. Parameters ---------- frag, gt : array of int, same shape The fragmentation and ground truth volumes. Must have same shape. ''' def __init__(self, frag, gt): super().__init__() self.ctable = ev.contingency_table(frag, gt, ignore_seg=[], ignore_gt=[]).toarray() self._std = 0.1 # standard deviation of feature computations def eps(self): return np.random.randn(2) * self._std def compute_features(self, g, n1, n2=None): if n2 is None: return np.array([]) f1, f2 = g.nodes[n1]['fragments'], g.nodes[n2]['fragments'] f1 -= {g.boundary_body} f2 -= {g.boundary_body} should_merge = _compute_delta_vi(self.ctable, f1, f2) < 0 if should_merge: return np.array([0., 0.]) + self.eps() else: if len(f1) + len(f2) == 2: # single-fragment merge return np.array([1., 0.]) + self.eps() else: # multi-fragment merge return np.array([0., 1.]) + self.eps()
bsd-3-clause
d96bf400798829c5b3270f382a5c1c7f
36.338028
79
0.571105
3.289082
false
false
false
false
janelia-flyem/gala
gala/classify.py
1
10542
#!/usr/bin/env python # system modules import os import logging import random import pickle as pck # libraries import h5py import numpy as np np.seterr(divide='ignore') from sklearn.ensemble import RandomForestClassifier import joblib try: from vigra.learning import RandomForest as BaseVigraRandomForest from vigra.__version__ import version as vigra_version vigra_version = tuple(map(int, vigra_version.split('.'))) except ImportError: vigra_available = False else: vigra_available = True def default_classifier_extension(cl, use_joblib=True): """ Return the default classifier file extension for the given classifier. Parameters ---------- cl : sklearn estimator or VigraRandomForest object A classifier to be saved. use_joblib : bool, optional Whether or not joblib will be used to save the classifier. Returns ------- ext : string File extension Examples -------- >>> cl = RandomForestClassifier() >>> default_classifier_extension(cl) '.classifier.joblib' >>> default_classifier_extension(cl, False) '.classifier' """ if isinstance(cl, VigraRandomForest): return ".classifier.h5" elif use_joblib: return ".classifier.joblib" else: return ".classifier" def load_classifier(fn): """Load a classifier previously saved to disk, given a filename. Supported classifier types are: - scikit-learn classifiers saved using either pickle or joblib persistence - vigra random forest classifiers saved in HDF5 format Parameters ---------- fn : string Filename in which the classifier is stored. Returns ------- cl : classifier object cl is one of the supported classifier types; these support at least the standard scikit-learn interface of `fit()` and `predict_proba()` """ if not os.path.exists(fn): raise IOError("No such file or directory: '%s'" % fn) try: with open(fn, 'r') as f: cl = pck.load(f) return cl except (pck.UnpicklingError, UnicodeDecodeError): pass try: cl = joblib.load(fn) return cl except KeyError: pass if vigra_available: cl = VigraRandomForest() try: cl.load_from_disk(fn) return cl except IOError as e: logging.error(e) except RuntimeError as e: logging.error(e) raise IOError("File '%s' does not appear to be a valid classifier file" % fn) def save_classifier(cl, fn, use_joblib=True, **kwargs): """Save a classifier to disk. Parameters ---------- cl : classifier object Pickleable object or a classify.VigraRandomForest object. fn : string Writeable path/filename. use_joblib : bool, optional Whether to prefer joblib persistence to pickle. kwargs : keyword arguments Keyword arguments to be passed on to either `pck.dump` or `joblib.dump`. Returns ------- None Notes ----- For joblib persistence, `compress=3` is the default. """ if isinstance(cl, VigraRandomForest): cl.save_to_disk(fn) elif use_joblib: if 'compress' not in kwargs: kwargs['compress'] = 3 joblib.dump(cl, fn, **kwargs) else: with open(fn, 'wb') as f: pck.dump(cl, f, protocol=kwargs.get('protocol', 2)) def get_classifier(name='random forest', *args, **kwargs): """Return a classifier given a name. Parameters ---------- name : string The name of the classifier, e.g. 'random forest' or 'naive bayes'. *args, **kwargs : Additional arguments to pass to the constructor of the classifier. Returns ------- cl : classifier A classifier object implementing the scikit-learn interface. Raises ------ NotImplementedError If the classifier name is not recognized. Examples -------- >>> cl = get_classifier('random forest', n_estimators=47) >>> isinstance(cl, RandomForestClassifier) True >>> cl.n_estimators 47 >>> from numpy.testing import assert_raises >>> assert_raises(NotImplementedError, get_classifier, 'perfect class') """ name = name.lower() is_random_forest = name.find('random') > -1 and name.find('forest') > -1 is_naive_bayes = name.find('naive') > -1 is_logistic = name.startswith('logis') if vigra_available and is_random_forest: if 'random_state' in kwargs: del kwargs['random_state'] return VigraRandomForest(*args, **kwargs) elif is_random_forest: return DefaultRandomForest(*args, **kwargs) elif is_naive_bayes: from sklearn.naive_bayes import GaussianNB if 'random_state' in kwargs: del kwargs['random_state'] return GaussianNB(*args, **kwargs) elif is_logistic: from sklearn.linear_model import LogisticRegression return LogisticRegression(*args, **kwargs) else: raise NotImplementedError('Classifier "%s" is either not installed ' 'or not implemented in Gala.') class DefaultRandomForest(RandomForestClassifier): def __init__(self, n_estimators=100, criterion='entropy', max_depth=20, bootstrap=False, random_state=None, n_jobs=-1): super(DefaultRandomForest, self).__init__( n_estimators=n_estimators, criterion=criterion, max_depth=max_depth, bootstrap=bootstrap, random_state=random_state, n_jobs=n_jobs) class VigraRandomForest(object): def __init__(self, ntrees=255, use_feature_importance=False, sample_classes_individually=False): self.rf = BaseVigraRandomForest(treeCount=ntrees, sample_classes_individually=sample_classes_individually) self.use_feature_importance = use_feature_importance self.sample_classes_individually = sample_classes_individually def fit(self, features, labels): features = self.check_features_vector(features) labels = self.check_labels_vector(labels) if self.use_feature_importance: self.oob, self.feature_importance = \ self.rf.learnRFWithFeatureSelection(features, labels) else: self.oob = self.rf.learnRF(features, labels) return self def predict_proba(self, features): features = self.check_features_vector(features) return self.rf.predictProbabilities(features) def predict(self, features): features = self.check_features_vector(features) return self.rf.predictLabels(features) def check_features_vector(self, features): if features.dtype != np.float32: features = features.astype(np.float32) if features.ndim == 1: features = features[np.newaxis, :] return features def check_labels_vector(self, labels): if labels.dtype != np.uint32: if len(np.unique(labels[labels < 0])) == 1 \ and not (labels==0).any(): labels[labels < 0] = 0 else: labels = labels + labels.min() labels = labels.astype(np.uint32) labels = labels.reshape((labels.size, 1)) return labels def save_to_disk(self, fn, rfgroupname='rf'): self.rf.writeHDF5(fn, rfgroupname) attr_list = ['oob', 'feature_importance', 'use_feature_importance', 'feature_description'] f = h5py.File(fn) for attr in attr_list: if hasattr(self, attr): f[rfgroupname].attrs[attr] = getattr(self, attr) def load_from_disk(self, fn, rfgroupname='rf'): self.rf = BaseVigraRandomForest(str(fn), rfgroupname) f = h5py.File(fn, 'r') for attr in f[rfgroupname].attrs: print("f[%s] = %s" % (attr, f[rfgroupname].attrs[attr])) setattr(self, attr, f[rfgroupname].attrs[attr]) def read_rf_info(fn): f = h5py.File(fn) return list(map(np.array, [f['oob'], f['feature_importance']])) def concatenate_data_elements(alldata): """Return one big learning set from a list of learning sets. A learning set is a list/tuple of length 4 containing features, labels, weights, and node merge history. """ return list(map(np.concatenate, zip(*alldata))) def unique_learning_data_elements(alldata): if type(alldata[0]) not in (list, tuple): alldata = [alldata] f, l, w, h = concatenate_data_elements(alldata) af = f.view('|S%d'%(f.itemsize*(len(f[0])))) _, uids, iids = np.unique(af, return_index=True, return_inverse=True) bcs = np.bincount(iids) logging.debug( 'repeat feature vec min %d, mean %.2f, median %.2f, max %d.' % (bcs.min(), np.mean(bcs), np.median(bcs), bcs.max()) ) def get_uniques(ar): return ar[uids] return list(map(get_uniques, [f, l, w, h])) def sample_training_data(features, labels, num_samples=None): """Get a random sample from a classification training dataset. Parameters ---------- features: np.ndarray [M x N] The M (number of samples) by N (number of features) feature matrix. labels: np.ndarray [M] or [M x 1] The training label for each feature vector. num_samples: int, optional The size of the training sample to draw. Return full dataset if `None` or if num_samples >= M. Returns ------- feat: np.ndarray [num_samples x N] The sampled feature vectors. lab: np.ndarray [num_samples] or [num_samples x 1] The sampled training labels """ m = len(features) if num_samples is None or num_samples >= m: return features, labels idxs = random.sample(list(range(m)), num_samples) return features[idxs], labels[idxs] def save_training_data_to_disk(data, fn, names=None, info='N/A'): if names is None: names = ['features', 'labels', 'weights', 'history'] fout = h5py.File(fn, 'w') for data_elem, name in zip(data, names): fout[name] = data_elem fout.attrs['info'] = info fout.close() def load_training_data_from_disk(fn, names=None, info='N/A'): if names is None: names = ['features', 'labels', 'weights', 'history'] fin = h5py.File(fn, 'r') data = [] for name in names: data.append(np.array(fin[name])) return data
bsd-3-clause
7b958e975c2e41bf25612d192e589e12
31.436923
78
0.618194
3.861538
false
false
false
false
astropy/ccdproc
ccdproc/log_meta.py
2
5533
# Licensed under a 3-clause BSD style license - see LICENSE.rst from functools import wraps import inspect from itertools import chain import numpy as np from astropy.nddata import NDData from astropy import units as u from astropy.io import fits import ccdproc # Really only need Keyword from ccdproc __all__ = [] _LOG_ARGUMENT = 'add_keyword' _LOG_ARG_HELP = \ """ {arg} : str, `~ccdproc.Keyword` or dict-like, optional Item(s) to add to metadata of result. Set to False or None to completely disable logging. Default is to add a dictionary with a single item: The key is the name of this function and the value is a string containing the arguments the function was called with, except the value of this argument. """.format(arg=_LOG_ARGUMENT) def _insert_in_metadata_fits_safe(ccd, key, value): from .core import _short_names if key in _short_names: # This keyword was (hopefully) added by autologging but the # combination of it and its value not FITS-compliant in two # ways: the keyword name may be more than 8 characters and # the value may be too long. FITS cannot handle both of # those problems at once, so this fixes one of those # problems... # Shorten, sort of... short_name = _short_names[key] if isinstance(ccd.meta, fits.Header): ccd.meta['HIERARCH {0}'.format(key.upper())] = ( short_name, "Shortened name for ccdproc command") else: ccd.meta[key] = ( short_name, "Shortened name for ccdproc command") ccd.meta[short_name] = value else: ccd.meta[key] = value def log_to_metadata(func): """ Decorator that adds logging to ccdproc functions. The decorator adds the optional argument _LOG_ARGUMENT to function signature and updates the function's docstring to reflect that. It also sets the default value of the argument to the name of the function and the arguments it was called with. """ func.__doc__ = func.__doc__.format(log=_LOG_ARG_HELP) argspec = inspect.getfullargspec(func) original_args, varargs, keywords, defaults = (argspec.args, argspec.varargs, argspec.varkw, argspec.defaults) # original_args = argspec.args # varargs = argspec.varargs # keywords = argspec.varkw # defaults = argspec.defaults # Grab the names of positional arguments for use in automatic logging try: original_positional_args = original_args[:-len(defaults)] except TypeError: original_positional_args = original_args # Add logging keyword and its default value for docstring original_args.append(_LOG_ARGUMENT) try: defaults = list(defaults) except TypeError: defaults = [] defaults.append(True) signature_with_arg_added = inspect.signature(func) signature_with_arg_added = "{0}{1}".format(func.__name__, signature_with_arg_added) func.__doc__ = "\n".join([signature_with_arg_added, func.__doc__]) @wraps(func) def wrapper(*args, **kwd): # Grab the logging keyword, if it is present. log_result = kwd.pop(_LOG_ARGUMENT, True) result = func(*args, **kwd) if not log_result: # No need to add metadata.... meta_dict = {} elif log_result is not True: meta_dict = _metadata_to_dict(log_result) else: # Logging is not turned off, but user did not provide a value # so construct one unless the config parameter auto_logging is set to False if ccdproc.conf.auto_logging: key = func.__name__ # Get names of arguments, which may or may not have # been called as keywords. positional_args = original_args[:len(args)] all_args = chain(zip(positional_args, args), kwd.items()) all_args = ["{0}={1}".format(name, _replace_array_with_placeholder(val)) for name, val in all_args] log_val = ", ".join(all_args) log_val = log_val.replace("\n", "") meta_dict = {key: log_val} else: meta_dict = {} for k, v in meta_dict.items(): _insert_in_metadata_fits_safe(result, k, v) return result return wrapper def _metadata_to_dict(arg): if isinstance(arg, str): # add the key, no value return {arg: None} elif isinstance(arg, ccdproc.Keyword): return {arg.name: arg.value} else: return arg def _replace_array_with_placeholder(value): return_type_not_value = False if isinstance(value, u.Quantity): return_type_not_value = not value.isscalar elif isinstance(value, (NDData, np.ndarray)): try: length = len(value) except TypeError: # Value has no length... try: # ...but if it is NDData its .data will have a length length = len(value.data) except TypeError: # No idea what this data is, assume length is not 1 length = 42 return_type_not_value = length > 1 if return_type_not_value: return "<{0}>".format(value.__class__.__name__) else: return value
bsd-3-clause
f2be34d65b68176752299878ae799bc9
33.58125
87
0.590819
4.119881
false
false
false
false
astropy/ccdproc
ccdproc/extern/bitfield.py
1
19025
# External license! License can be found in "licenses/LICENSE_STSCI_TOOLS.txt". """ A module that provides functions for manipulating bitmasks and data quality (DQ) arrays. :Authors: Mihai Cara (contact: help@stsci.edu) :License: `<http://www.stsci.edu/resources/software_hardware/pyraf/LICENSE>`_ """ import sys import warnings import numpy as np __version__ = '1.1.1' __vdate__ = '30-January-2018' __author__ = 'Mihai Cara' __all__ = ['bitfield_to_boolean_mask', 'interpret_bit_flags', 'is_bit_flag'] # Revision history: # 0.1.0 (29-March-2015) - initial release based on code from stsci.skypac # 0.1.1 (21-February-2017) - documentation typo fix # 0.2.0 (23-February-2017) - performance and stability improvements. Changed # default output mask type from numpy.uint8 to numpy.bool_. # 1.0.0 (16-March-2017) - Multiple enhancements: # 1. Deprecated 'interpret_bits_value()'in favor of # 'interpret_bit_flags()' which now takes 'flip_bits' argument to flip # bits in (list of) integer flags. # 2. Deprecated 'bitmask2mask()' in favor of 'bitfield_to_boolean_mask()' # which now also takes 'flip_bits' argument. # 3. Renamed arguments of 'interpret_bit_flags()' and # 'bitfield_to_boolean_mask()' to be more technically correct. # 4. 'interpret_bit_flags()' and 'bitfield_to_boolean_mask()' now # accept Python lists of bit flags (in addition to integer bitmasks # and string comma- (or '+') separated lists of bit flags). # 5. Added 'is_bit_flag()' function to check if an integer number has # only one bit set (i.e., that it is a power of 2). # 1.1.0 (29-January-2018) - Multiple enhancements: # 1. Added support for long type in Python 2.7 in # `interpret_bit_flags()` and `bitfield_to_boolean_mask()`. # 2. `interpret_bit_flags()` now always returns `int` (or `int` or `long` # in Python 2.7). Previously when input was of integer-like type # (i.e., `numpy.uint64`), it was not converted to Python `int`. # 3. `bitfield_to_boolean_mask()` will no longer crash when # `ignore_flags` argument contains bit flags beyond what the type of # the argument `bitfield` can hold. # 1.1.1 (30-January-2018) - Improved filtering of high bits in flags. # INT_TYPE = (int, long,) if sys.version_info < (3,) else (int,) MAX_UINT_TYPE = np.maximum_sctype(np.uint) SUPPORTED_FLAGS = int(np.bitwise_not( 0, dtype=MAX_UINT_TYPE, casting='unsafe' )) def is_bit_flag(n): """ Verifies if the input number is a bit flag (i.e., an integer number that is an integer power of 2). Parameters ---------- n : int A positive integer number. Non-positive integers are considered not to be "flags". Returns ------- bool ``True`` if input ``n`` is a bit flag and ``False`` if it is not. """ if n < 1: return False return bin(n).count('1') == 1 def _is_int(n): return ( (isinstance(n, INT_TYPE) and not isinstance(n, bool)) or (isinstance(n, np.generic) and np.issubdtype(n, np.integer)) ) def interpret_bit_flags(bit_flags, flip_bits=None): """ Converts input bit flags to a single integer value (bitmask) or `None`. When input is a list of flags (either a Python list of integer flags or a sting of comma- or '+'-separated list of flags), the returned bitmask is obtained by summing input flags. .. note:: In order to flip the bits of the returned bitmask, for input of `str` type, prepend '~' to the input string. '~' must be prepended to the *entire string* and not to each bit flag! For input that is already a bitmask or a Python list of bit flags, set `flip_bits` for `True` in order to flip the bits of the returned bitmask. Parameters ---------- bit_flags : int, str, list, None An integer bitmask or flag, `None`, a string of comma- or '+'-separated list of integer bit flags, or a Python list of integer bit flags. If `bit_flags` is a `str` and if it is prepended with '~', then the output bitmask will have its bits flipped (compared to simple sum of input flags). For input `bit_flags` that is already a bitmask or a Python list of bit flags, bit-flipping can be controlled through `flip_bits` parameter. flip_bits : bool, None Indicates whether or not to flip the bits of the returned bitmask obtained from input bit flags. This parameter must be set to `None` when input `bit_flags` is either `None` or a Python list of flags. Returns ------- bitmask : int or None Returns and integer bit mask formed from the input bit value or `None` if input `bit_flags` parameter is `None` or an empty string. If input string value was prepended with '~' (or `flip_bits` was set to `True`), then returned value will have its bits flipped (inverse mask). Examples -------- >>> from ccdproc.extern.bitfield import interpret_bit_flags >>> "{0:016b}".format(0xFFFF & interpret_bit_flags(28)) '0000000000011100' >>> "{0:016b}".format(0xFFFF & interpret_bit_flags('4,8,16')) '0000000000011100' >>> "{0:016b}".format(0xFFFF & interpret_bit_flags('~4,8,16')) '1111111111100011' >>> "{0:016b}".format(0xFFFF & interpret_bit_flags('~(4+8+16)')) '1111111111100011' >>> "{0:016b}".format(0xFFFF & interpret_bit_flags([4, 8, 16])) '0000000000011100' >>> "{0:016b}".format(0xFFFF & interpret_bit_flags([4, 8, 16], flip_bits=True)) '1111111111100011' """ has_flip_bits = flip_bits is not None flip_bits = bool(flip_bits) allow_non_flags = False if _is_int(bit_flags): return (~int(bit_flags) if flip_bits else int(bit_flags)) elif bit_flags is None: if has_flip_bits: raise TypeError( "Keyword argument 'flip_bits' must be set to 'None' when " "input 'bit_flags' is None." ) return None elif isinstance(bit_flags, str): if has_flip_bits: raise TypeError( "Keyword argument 'flip_bits' is not permitted for " "comma-separated string lists of bit flags. Prepend '~' to " "the string to indicate bit-flipping." ) bit_flags = str(bit_flags).strip() if bit_flags.upper() in ['', 'NONE', 'INDEF']: return None # check whether bitwise-NOT is present and if it is, check that it is # in the first position: bitflip_pos = bit_flags.find('~') if bitflip_pos == 0: flip_bits = True bit_flags = bit_flags[1:].lstrip() else: if bitflip_pos > 0: raise ValueError("Bitwise-NOT must precede bit flag list.") flip_bits = False # basic check for correct use of parenthesis: while True: nlpar = bit_flags.count('(') nrpar = bit_flags.count(')') if nlpar == 0 and nrpar == 0: break if nlpar != nrpar: raise ValueError("Unbalanced parantheses in bit flag list.") lpar_pos = bit_flags.find('(') rpar_pos = bit_flags.rfind(')') if lpar_pos > 0 or rpar_pos < (len(bit_flags) - 1): raise ValueError("Incorrect syntax (incorrect use of " "parenthesis) in bit flag list.") bit_flags = bit_flags[1:-1].strip() if ',' in bit_flags: bit_flags = bit_flags.split(',') elif '+' in bit_flags: bit_flags = bit_flags.split('+') else: if bit_flags == '': raise ValueError( "Empty bit flag lists not allowed when either bitwise-NOT " "or parenthesis are present." ) bit_flags = [bit_flags] allow_non_flags = len(bit_flags) == 1 elif hasattr(bit_flags, '__iter__'): if not all([_is_int(flag) for flag in bit_flags]): raise TypeError("Each bit flag in a list must be an integer.") else: raise TypeError("Unsupported type for argument 'bit_flags'.") bitset = set(map(int, bit_flags)) if len(bitset) != len(bit_flags): warnings.warn("Duplicate bit flags will be ignored") bitmask = 0 for v in bitset: if not is_bit_flag(v) and not allow_non_flags: raise ValueError("Input list contains invalid (not powers of two) " "bit flags") bitmask += v if flip_bits: bitmask = ~bitmask return bitmask def bitfield_to_boolean_mask(bitfield, ignore_flags=0, flip_bits=None, good_mask_value=True, dtype=np.bool_): r""" bitfield_to_boolean_mask(bitfield, ignore_flags=None, flip_bits=None, \ good_mask_value=True, dtype=numpy.bool\_) Converts an array of bit fields to a boolean (or integer) mask array according to a bitmask constructed from the supplied bit flags (see ``ignore_flags`` parameter). This function is particularly useful to convert data quality arrays to boolean masks with selective filtering of DQ flags. Parameters ---------- bitfield : numpy.ndarray An array of bit flags. By default, values different from zero are interpreted as "bad" values and values equal to zero are considered as "good" values. However, see ``ignore_flags`` parameter on how to selectively ignore some bits in the ``bitfield`` array data. ignore_flags : int, str, list, None (Default = 0) An integer bitmask, a Python list of bit flags, a comma- or '+'-separated string list of integer bit flags that indicate what bits in the input ``bitfield`` should be *ignored* (i.e., zeroed), or `None`. | Setting ``ignore_flags`` to `None` effectively will make `bitfield_to_boolean_mask` interpret all ``bitfield`` elements as "good" regardless of their value. | When ``ignore_flags`` argument is an integer bitmask, it will be combined using bitwise-NOT and bitwise-AND with each element of the input ``bitfield`` array (``~ignore_flags & bitfield``). If the resultant bitfield element is non-zero, that element will be interpreted as a "bad" in the output boolean mask and it will be interpreted as "good" otherwise. ``flip_bits`` parameter may be used to flip the bits (``bitwise-NOT``) of the bitmask thus effectively changing the meaning of the ``ignore_flags`` parameter from "ignore" to "use only" these flags. .. note:: Setting ``ignore_flags`` to 0 effectively will assume that all non-zero elements in the input ``bitfield`` array are to be interpreted as "bad". | When ``ignore_flags`` argument is an Python list of integer bit flags, these flags are added together to create an integer bitmask. Each item in the list must be a flag, i.e., an integer that is an integer power of 2. In order to flip the bits of the resultant bitmask, use ``flip_bits`` parameter. | Alternatively, ``ignore_flags`` may be a string of comma- or '+'-separated list of integer bit flags that should be added together to create an integer bitmask. For example, both ``'4,8'`` and ``'4+8'`` are equivalent and indicate that bit flags 4 and 8 in the input ``bitfield`` array should be ignored when generating boolean mask. .. note:: ``'None'``, ``'INDEF'``, and empty (or all white space) strings are special values of string ``ignore_flags`` that are interpreted as `None`. .. note:: Each item in the list must be a flag, i.e., an integer that is an integer power of 2. In addition, for convenience, an arbitrary **single** integer is allowed and it will be interpretted as an integer bitmask. For example, instead of ``'4,8'`` one could simply provide string ``'12'``. .. note:: When ``ignore_flags`` is a `str` and when it is prepended with '~', then the meaning of ``ignore_flags`` parameters will be reversed: now it will be interpreted as a list of bit flags to be *used* (or *not ignored*) when deciding which elements of the input ``bitfield`` array are "bad". Following this convention, an ``ignore_flags`` string value of ``'~0'`` would be equivalent to setting ``ignore_flags=None``. .. warning:: Because prepending '~' to a string ``ignore_flags`` is equivalent to setting ``flip_bits`` to `True`, ``flip_bits`` cannot be used with string ``ignore_flags`` and it must be set to `None`. flip_bits : bool, None (Default = None) Specifies whether or not to invert the bits of the bitmask either supplied directly through ``ignore_flags`` parameter or built from the bit flags passed through ``ignore_flags`` (only when bit flags are passed as Python lists of integer bit flags). Occasionally, it may be useful to *consider only specific bit flags* in the ``bitfield`` array when creating a boolean mask as opposite to *ignoring* specific bit flags as ``ignore_flags`` behaves by default. This can be achieved by inverting/flipping the bits of the bitmask created from ``ignore_flags`` flags which effectively changes the meaning of the ``ignore_flags`` parameter from "ignore" to "use only" these flags. Setting ``flip_bits`` to `None` means that no bit flipping will be performed. Bit flipping for string lists of bit flags must be specified by prepending '~' to string bit flag lists (see documentation for ``ignore_flags`` for more details). .. warning:: This parameter can be set to either `True` or `False` **ONLY** when ``ignore_flags`` is either an integer bitmask or a Python list of integer bit flags. When ``ignore_flags`` is either `None` or a string list of flags, ``flip_bits`` **MUST** be set to `None`. good_mask_value : int, bool (Default = True) This parameter is used to derive the values that will be assigned to the elements in the output boolean mask array that correspond to the "good" bit fields (that are 0 after zeroing bits specified by ``ignore_flags``) in the input ``bitfield`` array. When ``good_mask_value`` is non-zero or `True` then values in the output boolean mask array corresponding to "good" bit fields in ``bitfield`` will be `True` (if ``dtype`` is `numpy.bool_`) or 1 (if ``dtype`` is of numerical type) and values of corresponding to "bad" flags will be `False` (or 0). When ``good_mask_value`` is zero or `False` then the values in the output boolean mask array corresponding to "good" bit fields in ``bitfield`` will be `False` (if ``dtype`` is `numpy.bool_`) or 0 (if ``dtype`` is of numerical type) and values of corresponding to "bad" flags will be `True` (or 1). dtype : data-type (Default = numpy.bool\_) The desired data-type for the output binary mask array. Returns ------- mask : numpy.ndarray Returns an array of the same dimensionality as the input ``bitfield`` array whose elements can have two possible values, e.g., `True` or `False` (or 1 or 0 for integer ``dtype``) according to values of to the input ``bitfield`` elements, ``ignore_flags`` parameter, and the ``good_mask_value`` parameter. Examples -------- >>> from ccdproc.extern import bitfield >>> import numpy as np >>> dqbits = np.asarray([[0, 0, 1, 2, 0, 8, 12, 0], ... [10, 4, 0, 0, 0, 16, 6, 0]]) >>> bitfield.bitfield_to_boolean_mask(dqbits, ignore_flags=0, ... dtype=int) array([[1, 1, 0, 0, 1, 0, 0, 1], [0, 0, 1, 1, 1, 0, 0, 1]]) >>> bitfield.bitfield_to_boolean_mask(dqbits, ignore_flags=0, ... dtype=bool) array([[ True, True, False, False, True, False, False, True], [False, False, True, True, True, False, False, True]]...) >>> bitfield.bitfield_to_boolean_mask(dqbits, ignore_flags=6, ... good_mask_value=0, dtype=int) array([[0, 0, 1, 0, 0, 1, 1, 0], [1, 0, 0, 0, 0, 1, 0, 0]]) >>> bitfield.bitfield_to_boolean_mask(dqbits, ignore_flags=~6, ... good_mask_value=0, dtype=int) array([[0, 0, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0]]) >>> bitfield.bitfield_to_boolean_mask(dqbits, ignore_flags=6, dtype=int, ... flip_bits=True, good_mask_value=0) array([[0, 0, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0]]) >>> bitfield.bitfield_to_boolean_mask(dqbits, ignore_flags='~(2+4)', ... good_mask_value=0, dtype=int) array([[0, 0, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0]]) >>> bitfield.bitfield_to_boolean_mask(dqbits, ignore_flags=[2, 4], ... flip_bits=True, good_mask_value=0, ... dtype=int) array([[0, 0, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0]]) """ bitfield = np.asarray(bitfield) if not np.issubdtype(bitfield.dtype, np.integer): raise TypeError("Input bitfield array must be of integer type.") ignore_mask = interpret_bit_flags(ignore_flags, flip_bits=flip_bits) if ignore_mask is None: if good_mask_value: mask = np.ones_like(bitfield, dtype=dtype) else: mask = np.zeros_like(bitfield, dtype=dtype) return mask # filter out bits beyond the maximum supported by the data type: ignore_mask = ignore_mask & SUPPORTED_FLAGS # invert the "ignore" mask: ignore_mask = np.bitwise_not(ignore_mask, dtype=bitfield.dtype, casting='unsafe') mask = np.empty_like(bitfield, dtype=np.bool_) np.bitwise_and(bitfield, ignore_mask, out=mask, casting='unsafe') if good_mask_value: np.logical_not(mask, out=mask) return mask.astype(dtype=dtype, subok=False, copy=False)
bsd-3-clause
6ed21a683ae65804fe37078721bf2bb5
41.277778
87
0.59159
3.875535
false
false
false
false
pinax/symposion
symposion/conference/migrations/0001_initial.py
4
1830
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import timezone_field.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Conference', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100, verbose_name='Title')), ('start_date', models.DateField(null=True, blank=True, verbose_name='Start date')), ('end_date', models.DateField(null=True, blank=True, verbose_name='End date')), ('timezone', timezone_field.fields.TimeZoneField(blank=True, verbose_name='timezone')), ], options={ 'verbose_name_plural': 'conferences', 'verbose_name': 'conference', }, ), migrations.CreateModel( name='Section', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100, verbose_name='Name')), ('slug', models.SlugField(verbose_name='Slug')), ('start_date', models.DateField(null=True, blank=True, verbose_name='Start date')), ('end_date', models.DateField(null=True, blank=True, verbose_name='End date')), ('conference', models.ForeignKey(to='symposion_conference.Conference', verbose_name='Conference')), ], options={ 'ordering': ['start_date'], 'verbose_name_plural': 'sections', 'verbose_name': 'section', }, ), ]
bsd-3-clause
9479af1e975ec9ea20528807dd0faea9
40.590909
115
0.553552
4.42029
false
false
false
false
dask/distributed
distributed/chaos.py
1
1947
from __future__ import annotations import asyncio import ctypes import random import sys from typing import Literal from dask.utils import parse_timedelta from distributed.diagnostics.plugin import WorkerPlugin class KillWorker(WorkerPlugin): """Kill Workers Randomly This kills workers in a cluster randomly. It is intended to be used in stress testing. Parameters ---------- delay: str The expected amount of time for a worker to live. The actual time will vary, treating worker death as a poisson process. mode: str or "graceful" which calls worker.close(...) Either "sys.exit" which calls sys.exit(0) or "segfault" which triggers a segfault """ def __init__( self, delay: str | int | float = "100 s", mode: Literal["sys.exit", "graceful", "segfault"] = "sys.exit", ): self.delay = parse_timedelta(delay) if mode not in ("sys.exit", "graceful", "segfault"): raise ValueError( f"Three modes supported, 'sys.exit', 'graceful', and 'segfault'. " f"got {mode!r}" ) self.mode = mode async def setup(self, worker): self.worker = worker if self.mode == "graceful": f = self.graceful elif self.mode == "sys.exit": f = self.sys_exit elif self.mode == "segfault": f = self.segfault self.worker.loop.asyncio_loop.call_later( delay=random.expovariate(1 / self.delay), callback=f, ) def graceful(self): asyncio.create_task(self.worker.close(nanny=False, executor_wait=False)) def sys_exit(self): sys.exit(0) def segfault(self): """ Magic, from https://gist.github.com/coolreader18/6dbe0be2ae2192e90e1a809f1624c694?permalink_comment_id=3874116#gistcomment-3874116 """ ctypes.string_at(0)
bsd-3-clause
f0474efd05e6f5f51a8475e1eea0faa4
27.632353
138
0.602979
3.773256
false
false
false
false
scikit-optimize/scikit-optimize
examples/interruptible-optimization.py
4
4670
""" ================================================ Interruptible optimization runs with checkpoints ================================================ Christian Schell, Mai 2018 Reformatted by Holger Nahrstaedt 2020 .. currentmodule:: skopt Problem statement ================= Optimization runs can take a very long time and even run for multiple days. If for some reason the process has to be interrupted results are irreversibly lost, and the routine has to start over from the beginning. With the help of the :class:`callbacks.CheckpointSaver` callback the optimizer's current state can be saved after each iteration, allowing to restart from that point at any time. This is useful, for example, * if you don't know how long the process will take and cannot hog computational resources forever * if there might be system failures due to shaky infrastructure (or colleagues...) * if you want to adjust some parameters and continue with the already obtained results """ print(__doc__) import sys import numpy as np np.random.seed(777) import os ############################################################################# # Simple example # ============== # # We will use pretty much the same optimization problem as in the # :ref:`sphx_glr_auto_examples_bayesian-optimization.py` # notebook. Additionally we will instantiate the :class:`callbacks.CheckpointSaver` # and pass it to the minimizer: from skopt import gp_minimize from skopt import callbacks from skopt.callbacks import CheckpointSaver noise_level = 0.1 def obj_fun(x, noise_level=noise_level): return np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2)) + np.random.randn() \ * noise_level checkpoint_saver = CheckpointSaver("./checkpoint.pkl", compress=9) # keyword arguments will be passed to `skopt.dump` gp_minimize(obj_fun, # the function to minimize [(-20.0, 20.0)], # the bounds on each dimension of x x0=[-20.], # the starting point acq_func="LCB", # the acquisition function (optional) n_calls=10, # number of evaluations of f including at x0 n_random_starts=3, # the number of random initial points callback=[checkpoint_saver], # a list of callbacks including the checkpoint saver random_state=777) ############################################################################# # Now let's assume this did not finish at once but took some long time: you # started this on Friday night, went out for the weekend and now, Monday # morning, you're eager to see the results. However, instead of the # notebook server you only see a blank page and your colleague Garry # tells you that he had had an update scheduled for Sunday noon – who # doesn't like updates? # # :class:`gp_minimize` did not finish, and there is no `res` variable with the # actual results! # # Restoring the last checkpoint # ============================= # # Luckily we employed the :class:`callbacks.CheckpointSaver` and can now restore the latest # result with :class:`skopt.load` # (see :ref:`sphx_glr_auto_examples_store-and-load-results.py` for more # information on that) from skopt import load res = load('./checkpoint.pkl') res.fun ############################################################################# # Continue the search # =================== # # The previous results can then be used to continue the optimization process: x0 = res.x_iters y0 = res.func_vals gp_minimize(obj_fun, # the function to minimize [(-20.0, 20.0)], # the bounds on each dimension of x x0=x0, # already examined values for x y0=y0, # observed values for x0 acq_func="LCB", # the acquisition function (optional) n_calls=10, # number of evaluations of f including at x0 n_random_starts=3, # the number of random initialization points callback=[checkpoint_saver], random_state=777) ############################################################################# # Possible problems # ================= # # * **changes in search space:** You can use this technique to interrupt # the search, tune the search space and continue the optimization. Note # that the optimizers will complain if `x0` contains parameter values not # covered by the dimension definitions, so in many cases shrinking the # search space will not work without deleting the offending runs from # `x0` and `y0`. # * see :ref:`sphx_glr_auto_examples_store-and-load-results.py` # # for more information on how the results get saved and possible caveats
bsd-3-clause
b63bfd60b037cf1113cc3b26e45cf117
36.95122
117
0.62425
4.098332
false
false
false
false
dask/distributed
conftest.py
1
1168
# https://pytest.org/latest/example/simple.html#control-skipping-of-tests-according-to-command-line-option from __future__ import annotations import pytest # Uncomment to enable more logging and checks # (https://docs.python.org/3/library/asyncio-dev.html) # Note this makes things slower and might consume much memory. # os.environ["PYTHONASYNCIODEBUG"] = "1" try: import faulthandler except ImportError: pass else: try: faulthandler.enable() except Exception: pass # Make all fixtures available from distributed.utils_test import * # noqa def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_collection_modifyitems(config, items): if config.getoption("--runslow"): # --runslow given in cli: do not skip slow tests return skip_slow = pytest.mark.skip(reason="need --runslow option to run") for item in items: if "slow" in item.keywords: item.add_marker(skip_slow) if "ws" in item.fixturenames: item.add_marker(pytest.mark.workerstate) pytest_plugins = ["distributed.pytest_resourceleaks"]
bsd-3-clause
0400a0ca3173f23e070b5a346dbd57d6
26.809524
106
0.695205
3.661442
false
true
false
false
dask/distributed
distributed/dashboard/scheduler.py
1
5485
from __future__ import annotations from urllib.parse import urljoin from tlz import memoize from tornado import web from tornado.ioloop import IOLoop from distributed.dashboard.components.nvml import ( gpu_doc, gpu_memory_doc, gpu_utilization_doc, ) from distributed.dashboard.components.scheduler import ( AggregateAction, BandwidthTypes, BandwidthWorkers, ClusterMemory, ComputePerKey, CurrentLoad, EventLoop, ExceptionsTable, MemoryByKey, Occupancy, SystemMonitor, SystemTimeseries, TaskGraph, TaskGroupGraph, TaskGroupProgress, TaskProgress, TaskStream, WorkerNetworkBandwidth, WorkersMemory, WorkersTransferBytes, WorkerTable, events_doc, exceptions_doc, graph_doc, hardware_doc, individual_doc, individual_profile_doc, individual_profile_server_doc, profile_doc, profile_server_doc, shuffling_doc, status_doc, stealing_doc, systemmonitor_doc, tasks_doc, tg_graph_doc, workers_doc, ) from distributed.dashboard.core import BokehApplication from distributed.dashboard.worker import counters_doc applications = { "/system": systemmonitor_doc, "/shuffle": shuffling_doc, "/stealing": stealing_doc, "/workers": workers_doc, "/exceptions": exceptions_doc, "/events": events_doc, "/counters": counters_doc, "/tasks": tasks_doc, "/status": status_doc, "/profile": profile_doc, "/profile-server": profile_server_doc, "/graph": graph_doc, "/hardware": hardware_doc, "/groups": tg_graph_doc, "/gpu": gpu_doc, "/individual-task-stream": individual_doc( TaskStream, 100, n_rectangles=1000, clear_interval="10s" ), "/individual-progress": individual_doc(TaskProgress, 100, height=160), "/individual-graph": individual_doc(TaskGraph, 200), "/individual-groups": individual_doc(TaskGroupGraph, 200), "/individual-group-progress": individual_doc(TaskGroupProgress, 200), "/individual-workers-memory": individual_doc(WorkersMemory, 100), "/individual-cluster-memory": individual_doc(ClusterMemory, 100), "/individual-workers-transfer-bytes": individual_doc(WorkersTransferBytes, 100), "/individual-cpu": individual_doc(CurrentLoad, 100, fig_attr="cpu_figure"), "/individual-nprocessing": individual_doc( CurrentLoad, 100, fig_attr="processing_figure" ), "/individual-occupancy": individual_doc(Occupancy, 100), "/individual-workers": individual_doc(WorkerTable, 500), "/individual-exceptions": individual_doc(ExceptionsTable, 1000), "/individual-bandwidth-types": individual_doc(BandwidthTypes, 500), "/individual-bandwidth-workers": individual_doc(BandwidthWorkers, 500), "/individual-workers-network": individual_doc( WorkerNetworkBandwidth, 500, fig_attr="bandwidth" ), "/individual-workers-disk": individual_doc( WorkerNetworkBandwidth, 500, fig_attr="disk" ), "/individual-workers-network-timeseries": individual_doc( SystemTimeseries, 500, fig_attr="bandwidth" ), "/individual-workers-cpu-timeseries": individual_doc( SystemTimeseries, 500, fig_attr="cpu" ), "/individual-workers-memory-timeseries": individual_doc( SystemTimeseries, 500, fig_attr="memory" ), "/individual-workers-disk-timeseries": individual_doc( SystemTimeseries, 500, fig_attr="disk" ), "/individual-memory-by-key": individual_doc(MemoryByKey, 500), "/individual-compute-time-per-key": individual_doc(ComputePerKey, 500), "/individual-aggregate-time-per-action": individual_doc(AggregateAction, 500), "/individual-scheduler-system": individual_doc(SystemMonitor, 500), "/individual-event-loop": individual_doc(EventLoop, 500), "/individual-profile": individual_profile_doc, "/individual-profile-server": individual_profile_server_doc, "/individual-gpu-memory": gpu_memory_doc, "/individual-gpu-utilization": gpu_utilization_doc, } @memoize def template_variables(): from distributed.diagnostics.nvml import device_get_count template_variables = { "pages": [ "status", "workers", "tasks", "system", *(["gpu"] if device_get_count() > 0 else []), "profile", "graph", "groups", "info", ], "plots": [ { "url": x.strip("/"), "name": " ".join(x.strip("/").split("-")[1:]) .title() .replace("Cpu", "CPU") .replace("Gpu", "GPU"), } for x in applications if "individual" in x ] + [{"url": "hardware", "name": "Hardware"}], } template_variables["plots"] = sorted( template_variables["plots"], key=lambda d: d["name"] ) return template_variables def connect(application, http_server, scheduler, prefix=""): bokeh_app = BokehApplication( applications, scheduler, prefix=prefix, template_variables=template_variables() ) application.add_application(bokeh_app) bokeh_app.initialize(IOLoop.current()) bokeh_app.add_handlers( r".*", [ ( r"/", web.RedirectHandler, {"url": urljoin((prefix or "").strip("/") + "/", r"status")}, ) ], ) bokeh_app.start()
bsd-3-clause
499cada40442f20c3bf4fff23231b6d7
30.522989
87
0.632999
3.966016
false
false
false
false
scikit-optimize/scikit-optimize
skopt/space/space.py
1
38720
import numbers import numpy as np import yaml from scipy.stats.distributions import randint from scipy.stats.distributions import rv_discrete from scipy.stats.distributions import uniform from sklearn.utils import check_random_state from sklearn.utils.fixes import sp_version from .transformers import CategoricalEncoder from .transformers import StringEncoder from .transformers import LabelEncoder from .transformers import Normalize from .transformers import Identity from .transformers import LogN from .transformers import Pipeline # helper class to be able to print [1, ..., 4] instead of [1, '...', 4] class _Ellipsis: def __repr__(self): return '...' def _transpose_list_array(x): """Transposes a list matrix """ n_dims = len(x) assert n_dims > 0 n_samples = len(x[0]) rows = [None] * n_samples for i in range(n_samples): r = [None] * n_dims for j in range(n_dims): r[j] = x[j][i] rows[i] = r return rows def check_dimension(dimension, transform=None): """Turn a provided dimension description into a dimension object. Checks that the provided dimension falls into one of the supported types. For a list of supported types, look at the documentation of ``dimension`` below. If ``dimension`` is already a ``Dimension`` instance, return it. Parameters ---------- dimension : Dimension Search space Dimension. Each search dimension can be defined either as - a `(lower_bound, upper_bound)` tuple (for `Real` or `Integer` dimensions), - a `(lower_bound, upper_bound, "prior")` tuple (for `Real` dimensions), - as a list of categories (for `Categorical` dimensions), or - an instance of a `Dimension` object (`Real`, `Integer` or `Categorical`). transform : "identity", "normalize", "string", "label", "onehot" optional - For `Categorical` dimensions, the following transformations are supported. - "onehot" (default) one-hot transformation of the original space. - "label" integer transformation of the original space - "string" string transformation of the original space. - "identity" same as the original space. - For `Real` and `Integer` dimensions, the following transformations are supported. - "identity", (default) the transformed space is the same as the original space. - "normalize", the transformed space is scaled to be between 0 and 1. Returns ------- dimension : Dimension Dimension instance. """ if isinstance(dimension, Dimension): return dimension if not isinstance(dimension, (list, tuple, np.ndarray)): raise ValueError("Dimension has to be a list or tuple.") # A `Dimension` described by a single value is assumed to be # a `Categorical` dimension. This can be used in `BayesSearchCV` # to define subspaces that fix one value, e.g. to choose the # model type, see "sklearn-gridsearchcv-replacement.py" # for examples. if len(dimension) == 1: return Categorical(dimension, transform=transform) if len(dimension) == 2: if any([isinstance(d, (str, bool)) or isinstance(d, np.bool_) for d in dimension]): return Categorical(dimension, transform=transform) elif all([isinstance(dim, numbers.Integral) for dim in dimension]): return Integer(*dimension, transform=transform) elif any([isinstance(dim, numbers.Real) for dim in dimension]): return Real(*dimension, transform=transform) else: raise ValueError("Invalid dimension {}. Read the documentation for" " supported types.".format(dimension)) if len(dimension) == 3: if (any([isinstance(dim, int) for dim in dimension[:2]]) and dimension[2] in ["uniform", "log-uniform"]): return Integer(*dimension, transform=transform) elif (any([isinstance(dim, (float, int)) for dim in dimension[:2]]) and dimension[2] in ["uniform", "log-uniform"]): return Real(*dimension, transform=transform) else: return Categorical(dimension, transform=transform) if len(dimension) == 4: if (any([isinstance(dim, int) for dim in dimension[:2]]) and dimension[2] == "log-uniform" and isinstance(dimension[3], int)): return Integer(*dimension, transform=transform) elif (any([isinstance(dim, (float, int)) for dim in dimension[:2]]) and dimension[2] == "log-uniform" and isinstance(dimension[3], int)): return Real(*dimension, transform=transform) if len(dimension) > 3: return Categorical(dimension, transform=transform) raise ValueError("Invalid dimension {}. Read the documentation for " "supported types.".format(dimension)) class Dimension(object): """Base class for search space dimensions.""" prior = None def rvs(self, n_samples=1, random_state=None): """Draw random samples. Parameters ---------- n_samples : int or None The number of samples to be drawn. random_state : int, RandomState instance, or None (default) Set random state to something other than None for reproducible results. """ rng = check_random_state(random_state) samples = self._rvs.rvs(size=n_samples, random_state=rng) return self.inverse_transform(samples) def transform(self, X): """Transform samples form the original space to a warped space.""" return self.transformer.transform(X) def inverse_transform(self, Xt): """Inverse transform samples from the warped space back into the original space. """ return self.transformer.inverse_transform(Xt) def set_transformer(self): raise NotImplementedError @property def size(self): return 1 @property def transformed_size(self): return 1 @property def bounds(self): raise NotImplementedError @property def is_constant(self): raise NotImplementedError @property def transformed_bounds(self): raise NotImplementedError @property def name(self): return self._name @name.setter def name(self, value): if isinstance(value, str) or value is None: self._name = value else: raise ValueError("Dimension's name must be either string or None.") def _uniform_inclusive(loc=0.0, scale=1.0): # like scipy.stats.distributions but inclusive of `high` # XXX scale + 1. might not actually be a float after scale if # XXX scale is very large. return uniform(loc=loc, scale=np.nextafter(scale, scale + 1.)) class Real(Dimension): """Search space dimension that can take on any real value. Parameters ---------- low : float Lower bound (inclusive). high : float Upper bound (inclusive). prior : "uniform" or "log-uniform", default="uniform" Distribution to use when sampling random points for this dimension. - If `"uniform"`, points are sampled uniformly between the lower and upper bounds. - If `"log-uniform"`, points are sampled uniformly between `log(lower, base)` and `log(upper, base)` where log has base `base`. base : int The logarithmic base to use for a log-uniform prior. - Default 10, otherwise commonly 2. transform : "identity", "normalize", optional The following transformations are supported. - "identity", (default) the transformed space is the same as the original space. - "normalize", the transformed space is scaled to be between 0 and 1. name : str or None Name associated with the dimension, e.g., "learning rate". dtype : str or dtype, default=float float type which will be used in inverse_transform, can be float. """ def __init__(self, low, high, prior="uniform", base=10, transform=None, name=None, dtype=float): if high <= low: raise ValueError("the lower bound {} has to be less than the" " upper bound {}".format(low, high)) if prior not in ["uniform", "log-uniform"]: raise ValueError("prior should be 'uniform' or 'log-uniform'" " got {}".format(prior)) self.low = low self.high = high self.prior = prior self.base = base self.log_base = np.log10(base) self.name = name self.dtype = dtype self._rvs = None self.transformer = None self.transform_ = transform if isinstance(self.dtype, str) and self.dtype\ not in ['float', 'float16', 'float32', 'float64']: raise ValueError("dtype must be 'float', 'float16', 'float32'" "or 'float64'" " got {}".format(self.dtype)) elif isinstance(self.dtype, type) and \ not np.issubdtype(self.dtype, np.floating): raise ValueError("dtype must be a np.floating subtype;" " got {}".format(self.dtype)) if transform is None: transform = "identity" self.set_transformer(transform) def set_transformer(self, transform="identity"): """Define rvs and transformer spaces. Parameters ---------- transform : str Can be 'normalize' or 'identity' """ self.transform_ = transform if self.transform_ not in ["normalize", "identity"]: raise ValueError("transform should be 'normalize' or 'identity'" " got {}".format(self.transform_)) # XXX: The _rvs is for sampling in the transformed space. # The rvs on Dimension calls inverse_transform on the points sampled # using _rvs if self.transform_ == "normalize": # set upper bound to next float after 1. to make the numbers # inclusive of upper edge self._rvs = _uniform_inclusive(0., 1.) if self.prior == "uniform": self.transformer = Pipeline( [Identity(), Normalize(self.low, self.high)]) else: self.transformer = Pipeline( [LogN(self.base), Normalize(np.log10(self.low) / self.log_base, np.log10(self.high) / self.log_base)] ) else: if self.prior == "uniform": self._rvs = _uniform_inclusive(self.low, self.high - self.low) self.transformer = Identity() else: self._rvs = _uniform_inclusive( np.log10(self.low) / self.log_base, np.log10(self.high) / self.log_base - np.log10(self.low) / self.log_base) self.transformer = LogN(self.base) def __eq__(self, other): return (type(self) is type(other) and np.allclose([self.low], [other.low]) and np.allclose([self.high], [other.high]) and self.prior == other.prior and self.transform_ == other.transform_) def __repr__(self): return "Real(low={}, high={}, prior='{}', transform='{}')".format( self.low, self.high, self.prior, self.transform_) def inverse_transform(self, Xt): """Inverse transform samples from the warped space back into the original space. """ inv_transform = super(Real, self).inverse_transform(Xt) if isinstance(inv_transform, list): inv_transform = np.array(inv_transform) inv_transform = np.clip(inv_transform, self.low, self.high).astype(self.dtype) if self.dtype == float or self.dtype == 'float': # necessary, otherwise the type is converted to a numpy type return getattr(inv_transform, "tolist", lambda: value)() else: return inv_transform @property def bounds(self): return (self.low, self.high) @property def is_constant(self): return self.low == self.high def __contains__(self, point): if isinstance(point, list): point = np.array(point) return self.low <= point <= self.high @property def transformed_bounds(self): if self.transform_ == "normalize": return 0.0, 1.0 else: if self.prior == "uniform": return self.low, self.high else: return np.log10(self.low), np.log10(self.high) def distance(self, a, b): """Compute distance between point `a` and `b`. Parameters ---------- a : float First point. b : float Second point. """ if not (a in self and b in self): raise RuntimeError("Can only compute distance for values within " "the space, not %s and %s." % (a, b)) return abs(a - b) class Integer(Dimension): """Search space dimension that can take on integer values. Parameters ---------- low : int Lower bound (inclusive). high : int Upper bound (inclusive). prior : "uniform" or "log-uniform", default="uniform" Distribution to use when sampling random integers for this dimension. - If `"uniform"`, integers are sampled uniformly between the lower and upper bounds. - If `"log-uniform"`, integers are sampled uniformly between `log(lower, base)` and `log(upper, base)` where log has base `base`. base : int The logarithmic base to use for a log-uniform prior. - Default 10, otherwise commonly 2. transform : "identity", "normalize", optional The following transformations are supported. - "identity", (default) the transformed space is the same as the original space. - "normalize", the transformed space is scaled to be between 0 and 1. name : str or None Name associated with dimension, e.g., "number of trees". dtype : str or dtype, default=np.int64 integer type which will be used in inverse_transform, can be int, np.int16, np.uint32, np.int32, np.int64 (default). When set to int, `inverse_transform` returns a list instead of a numpy array """ def __init__(self, low, high, prior="uniform", base=10, transform=None, name=None, dtype=np.int64): if high <= low: raise ValueError("the lower bound {} has to be less than the" " upper bound {}".format(low, high)) if prior not in ["uniform", "log-uniform"]: raise ValueError("prior should be 'uniform' or 'log-uniform'" " got {}".format(prior)) self.low = low self.high = high self.prior = prior self.base = base self.log_base = np.log10(base) self.name = name self.dtype = dtype self.transform_ = transform self._rvs = None self.transformer = None if isinstance(self.dtype, str) and self.dtype\ not in ['int', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64']: raise ValueError("dtype must be 'int', 'int8', 'int16'," "'int32', 'int64', 'uint8'," "'uint16', 'uint32', or" "'uint64', but got {}".format(self.dtype)) elif isinstance(self.dtype, type) and self.dtype\ not in [int, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64]: raise ValueError("dtype must be 'int', 'np.int8', 'np.int16'," "'np.int32', 'np.int64', 'np.uint8'," "'np.uint16', 'np.uint32', or" "'np.uint64', but got {}".format(self.dtype)) if transform is None: transform = "identity" self.set_transformer(transform) def set_transformer(self, transform="identity"): """Define _rvs and transformer spaces. Parameters ---------- transform : str Can be 'normalize' or 'identity' """ self.transform_ = transform if transform not in ["normalize", "identity"]: raise ValueError("transform should be 'normalize' or 'identity'" " got {}".format(self.transform_)) if self.transform_ == "normalize": self._rvs = _uniform_inclusive(0.0, 1.0) if self.prior == "uniform": self.transformer = Pipeline( [Identity(), Normalize(self.low, self.high, is_int=True)]) else: self.transformer = Pipeline( [LogN(self.base), Normalize(np.log10(self.low) / self.log_base, np.log10(self.high) / self.log_base)] ) else: if self.prior == "uniform": self._rvs = randint(self.low, self.high + 1) self.transformer = Identity() else: self._rvs = _uniform_inclusive( np.log10(self.low) / self.log_base, np.log10(self.high) / self.log_base - np.log10(self.low) / self.log_base) self.transformer = LogN(self.base) def __eq__(self, other): return (type(self) is type(other) and np.allclose([self.low], [other.low]) and np.allclose([self.high], [other.high])) def __repr__(self): return "Integer(low={}, high={}, prior='{}', transform='{}')".format( self.low, self.high, self.prior, self.transform_) def inverse_transform(self, Xt): """Inverse transform samples from the warped space back into the original space. """ # The concatenation of all transformed dimensions makes Xt to be # of type float, hence the required cast back to int. inv_transform = super(Integer, self).inverse_transform(Xt) if isinstance(inv_transform, list): inv_transform = np.array(inv_transform) inv_transform = np.clip(inv_transform, self.low, self.high) if self.dtype == int or self.dtype == 'int': # necessary, otherwise the type is converted to a numpy type return getattr(np.round(inv_transform).astype(self.dtype), "tolist", lambda: value)() else: return np.round(inv_transform).astype(self.dtype) @property def bounds(self): return (self.low, self.high) @property def is_constant(self): return self.low == self.high def __contains__(self, point): if isinstance(point, list): point = np.array(point) return self.low <= point <= self.high @property def transformed_bounds(self): if self.transform_ == "normalize": return 0., 1. else: return (self.low, self.high) def distance(self, a, b): """Compute distance between point `a` and `b`. Parameters ---------- a : int First point. b : int Second point. """ if not (a in self and b in self): raise RuntimeError("Can only compute distance for values within " "the space, not %s and %s." % (a, b)) return abs(a - b) class Categorical(Dimension): """Search space dimension that can take on categorical values. Parameters ---------- categories : list, shape=(n_categories,) Sequence of possible categories. prior : list, shape=(categories,), default=None Prior probabilities for each category. By default all categories are equally likely. transform : "onehot", "string", "identity", "label", default="onehot" - "identity", the transformed space is the same as the original space. - "string", the transformed space is a string encoded representation of the original space. - "label", the transformed space is a label encoded representation (integer) of the original space. - "onehot", the transformed space is a one-hot encoded representation of the original space. name : str or None Name associated with dimension, e.g., "colors". """ def __init__(self, categories, prior=None, transform=None, name=None): self.categories = tuple(categories) self.name = name if transform is None: transform = "onehot" self.transform_ = transform self.transformer = None self._rvs = None self.prior = prior if prior is None: self.prior_ = np.tile(1. / len(self.categories), len(self.categories)) else: self.prior_ = prior self.set_transformer(transform) def set_transformer(self, transform="onehot"): """Define _rvs and transformer spaces. Parameters ---------- transform : str Can be 'normalize', 'onehot', 'string', 'label', or 'identity' """ self.transform_ = transform if transform not in ["identity", "onehot", "string", "normalize", "label"]: raise ValueError("Expected transform to be 'identity', 'string'," "'label' or 'onehot' got {}".format(transform)) if transform == "onehot": self.transformer = CategoricalEncoder() self.transformer.fit(self.categories) elif transform == "string": self.transformer = StringEncoder() self.transformer.fit(self.categories) elif transform == "label": self.transformer = LabelEncoder() self.transformer.fit(self.categories) elif transform == "normalize": self.transformer = Pipeline( [LabelEncoder(list(self.categories)), Normalize(0, len(self.categories) - 1, is_int=True)]) else: self.transformer = Identity() self.transformer.fit(self.categories) if transform == "normalize": self._rvs = _uniform_inclusive(0.0, 1.0) else: # XXX check that sum(prior) == 1 self._rvs = rv_discrete( values=(range(len(self.categories)), self.prior_) ) def __eq__(self, other): return (type(self) is type(other) and self.categories == other.categories and np.allclose(self.prior_, other.prior_)) def __repr__(self): if len(self.categories) > 7: cats = self.categories[:3] + (_Ellipsis(),) + self.categories[-3:] else: cats = self.categories if self.prior is not None and len(self.prior) > 7: prior = self.prior[:3] + [_Ellipsis()] + self.prior[-3:] else: prior = self.prior return "Categorical(categories={}, prior={})".format(cats, prior) def inverse_transform(self, Xt): """Inverse transform samples from the warped space back into the original space. """ # The concatenation of all transformed dimensions makes Xt to be # of type float, hence the required cast back to int. inv_transform = super(Categorical, self).inverse_transform(Xt) if isinstance(inv_transform, list): inv_transform = np.array(inv_transform) return inv_transform def rvs(self, n_samples=None, random_state=None): choices = self._rvs.rvs(size=n_samples, random_state=random_state) if isinstance(choices, numbers.Integral): return self.categories[choices] elif self.transform_ == "normalize" and isinstance(choices, float): return self.inverse_transform([(choices)]) elif self.transform_ == "normalize": return self.inverse_transform(list(choices)) else: return [self.categories[c] for c in choices] @property def transformed_size(self): if self.transform_ == "onehot": size = len(self.categories) # when len(categories) == 2, CategoricalEncoder outputs a # single value return size if size != 2 else 1 return 1 @property def bounds(self): return self.categories @property def is_constant(self): return len(self.categories) <= 1 def __contains__(self, point): return point in self.categories @property def transformed_bounds(self): if self.transformed_size == 1: return 0.0, 1.0 else: return [(0.0, 1.0) for i in range(self.transformed_size)] def distance(self, a, b): """Compute distance between category `a` and `b`. As categories have no order the distance between two points is one if a != b and zero otherwise. Parameters ---------- a : category First category. b : category Second category. """ if not (a in self and b in self): raise RuntimeError("Can only compute distance for values within" " the space, not {} and {}.".format(a, b)) return 1 if a != b else 0 class Space(object): """Initialize a search space from given specifications. Parameters ---------- dimensions : list, shape=(n_dims,) List of search space dimensions. Each search dimension can be defined either as - a `(lower_bound, upper_bound)` tuple (for `Real` or `Integer` dimensions), - a `(lower_bound, upper_bound, "prior")` tuple (for `Real` dimensions), - as a list of categories (for `Categorical` dimensions), or - an instance of a `Dimension` object (`Real`, `Integer` or `Categorical`). .. note:: The upper and lower bounds are inclusive for `Integer` dimensions. """ def __init__(self, dimensions): self.dimensions = [check_dimension(dim) for dim in dimensions] def __eq__(self, other): return all([a == b for a, b in zip(self.dimensions, other.dimensions)]) def __repr__(self): if len(self.dimensions) > 31: dims = self.dimensions[:15] + [_Ellipsis()] + self.dimensions[-15:] else: dims = self.dimensions return "Space([{}])".format(',\n '.join(map(str, dims))) def __iter__(self): return iter(self.dimensions) @property def dimension_names(self): """ Names of all the dimensions in the search-space. """ index = 0 names = [] for dim in self.dimensions: if dim.name is None: names.append("X_%d" % index) else: names.append(dim.name) index += 1 return names @property def is_real(self): """ Returns true if all dimensions are Real """ return all([isinstance(dim, Real) for dim in self.dimensions]) @classmethod def from_yaml(cls, yml_path, namespace=None): """Create Space from yaml configuration file Parameters ---------- yml_path : str Full path to yaml configuration file, example YaML below: Space: - Integer: low: -5 high: 5 - Categorical: categories: - a - b - Real: low: 1.0 high: 5.0 prior: log-uniform namespace : str, default=None Namespace within configuration file to use, will use first namespace if not provided Returns ------- space : Space Instantiated Space object """ with open(yml_path, 'rb') as f: config = yaml.safe_load(f) dimension_classes = {'real': Real, 'integer': Integer, 'categorical': Categorical} # Extract space options for configuration file if isinstance(config, dict): if namespace is None: options = next(iter(config.values())) else: options = config[namespace] elif isinstance(config, list): options = config else: raise TypeError('YaML does not specify a list or dictionary') # Populate list with Dimension objects dimensions = [] for option in options: key = next(iter(option.keys())) # Make configuration case insensitive dimension_class = key.lower() values = {k.lower(): v for k, v in option[key].items()} if dimension_class in dimension_classes: # Instantiate Dimension subclass and add it to the list dimension = dimension_classes[dimension_class](**values) dimensions.append(dimension) space = cls(dimensions=dimensions) return space def rvs(self, n_samples=1, random_state=None): """Draw random samples. The samples are in the original space. They need to be transformed before being passed to a model or minimizer by `space.transform()`. Parameters ---------- n_samples : int, default=1 Number of samples to be drawn from the space. random_state : int, RandomState instance, or None (default) Set random state to something other than None for reproducible results. Returns ------- points : list of lists, shape=(n_points, n_dims) Points sampled from the space. """ rng = check_random_state(random_state) # Draw columns = [] for dim in self.dimensions: columns.append(dim.rvs(n_samples=n_samples, random_state=rng)) # Transpose return _transpose_list_array(columns) def set_transformer(self, transform): """Sets the transformer of all dimension objects to `transform` Parameters ---------- transform : str or list of str Sets all transformer,, when `transform` is a string. Otherwise, transform must be a list with strings with the same length as `dimensions` """ # Transform for j in range(self.n_dims): if isinstance(transform, list): self.dimensions[j].set_transformer(transform[j]) else: self.dimensions[j].set_transformer(transform) def set_transformer_by_type(self, transform, dim_type): """Sets the transformer of `dim_type` objects to `transform` Parameters ---------- transform : str Sets all transformer of type `dim_type` to `transform` dim_type : type Can be `skopt.space.Real`, `skopt.space.Integer` or `skopt.space.Categorical` """ # Transform for j in range(self.n_dims): if isinstance(self.dimensions[j], dim_type): self.dimensions[j].set_transformer(transform) def get_transformer(self): """Returns all transformers as list""" return [self.dimensions[j].transform_ for j in range(self.n_dims)] def transform(self, X): """Transform samples from the original space into a warped space. Note: this transformation is expected to be used to project samples into a suitable space for numerical optimization. Parameters ---------- X : list of lists, shape=(n_samples, n_dims) The samples to transform. Returns ------- Xt : array of floats, shape=(n_samples, transformed_n_dims) The transformed samples. """ # Pack by dimension columns = [] for dim in self.dimensions: columns.append([]) for i in range(len(X)): for j in range(self.n_dims): columns[j].append(X[i][j]) # Transform for j in range(self.n_dims): columns[j] = self.dimensions[j].transform(columns[j]) # Repack as an array Xt = np.hstack([np.asarray(c).reshape((len(X), -1)) for c in columns]) return Xt def inverse_transform(self, Xt): """Inverse transform samples from the warped space back to the original space. Parameters ---------- Xt : array of floats, shape=(n_samples, transformed_n_dims) The samples to inverse transform. Returns ------- X : list of lists, shape=(n_samples, n_dims) The original samples. """ # Inverse transform columns = [] start = 0 Xt = np.asarray(Xt) for j in range(self.n_dims): dim = self.dimensions[j] offset = dim.transformed_size if offset == 1: columns.append(dim.inverse_transform(Xt[:, start])) else: columns.append( dim.inverse_transform(Xt[:, start:start + offset])) start += offset # Transpose return _transpose_list_array(columns) @property def n_dims(self): """The dimensionality of the original space.""" return len(self.dimensions) @property def transformed_n_dims(self): """The dimensionality of the warped space.""" return sum([dim.transformed_size for dim in self.dimensions]) @property def bounds(self): """The dimension bounds, in the original space.""" b = [] for dim in self.dimensions: if dim.size == 1: b.append(dim.bounds) else: b.extend(dim.bounds) return b def __contains__(self, point): """Check that `point` is within the bounds of the space.""" for component, dim in zip(point, self.dimensions): if component not in dim: return False return True def __getitem__(self, dimension_names): """ Lookup and return the search-space dimension with the given name. This allows for dict-like lookup of dimensions, for example: `space['foo']` returns the dimension named 'foo' if it exists, otherwise `None` is returned. It also allows for lookup of a list of dimension-names, for example: `space[['foo', 'bar']]` returns the two dimensions named 'foo' and 'bar' if they exist. Parameters ---------- dimension_names : str or list(str) Name of a single search-space dimension (str). List of names for search-space dimensions (list(str)). Returns ------- dims tuple (index, Dimension), list(tuple(index, Dimension)), \ (None, None) A single search-space dimension with the given name, or a list of search-space dimensions with the given names. """ def _get(dimension_name): """Helper-function for getting a single dimension.""" index = 0 # Get the index of the search-space dimension using its name. for dim in self.dimensions: if dimension_name == dim.name: return (index, dim) elif dimension_name == index: return (index, dim) index += 1 return (None, None) if isinstance(dimension_names, (str, int)): # Get a single search-space dimension. dims = _get(dimension_name=dimension_names) elif isinstance(dimension_names, (list, tuple)): # Get a list of search-space dimensions. # Note that we do not check whether the names are really strings. dims = [_get(dimension_name=name) for name in dimension_names] else: msg = "Dimension name should be either string or" \ "list of strings, but got {}." raise ValueError(msg.format(type(dimension_names))) return dims @property def transformed_bounds(self): """The dimension bounds, in the warped space.""" b = [] for dim in self.dimensions: if dim.transformed_size == 1: b.append(dim.transformed_bounds) else: b.extend(dim.transformed_bounds) return b @property def is_categorical(self): """Space contains exclusively categorical dimensions""" return all([isinstance(dim, Categorical) for dim in self.dimensions]) @property def is_partly_categorical(self): """Space contains any categorical dimensions""" return any([isinstance(dim, Categorical) for dim in self.dimensions]) @property def n_constant_dimensions(self): """Returns the number of constant dimensions which have zero degree of freedom, e.g. an Integer dimensions with (0., 0.) as bounds. """ n = 0 for dim in self.dimensions: if dim.is_constant: n += 1 return n def distance(self, point_a, point_b): """Compute distance between two points in this space. Parameters ---------- point_a : array First point. point_b : array Second point. """ distance = 0. for a, b, dim in zip(point_a, point_b, self.dimensions): distance += dim.distance(a, b) return distance
bsd-3-clause
2b5c86a109cdb443d531df234254b89a
32.964912
79
0.560511
4.512821
false
false
false
false
dask/distributed
distributed/tests/test_client.py
1
226630
from __future__ import annotations import asyncio import concurrent.futures import functools import gc import inspect import logging import operator import os import pathlib import pickle import random import subprocess import sys import threading import traceback import types import warnings import weakref import zipfile from collections import deque, namedtuple from collections.abc import Generator from contextlib import ExitStack, contextmanager, nullcontext from functools import partial from operator import add from threading import Semaphore from time import sleep from typing import Any from unittest import mock import psutil import pytest import yaml from tlz import concat, first, identity, isdistinct, merge, pluck, valmap from tornado.ioloop import IOLoop import dask import dask.bag as db from dask import delayed from dask.optimization import SubgraphCallable from dask.utils import parse_timedelta, stringify, tmpfile from distributed import ( CancelledError, Event, LocalCluster, Lock, Nanny, TimeoutError, Worker, fire_and_forget, get_client, get_worker, performance_report, profile, secede, ) from distributed.client import ( Client, Future, _get_global_client, as_completed, default_client, ensure_default_client, futures_of, get_task_metadata, temp_default_client, tokenize, wait, ) from distributed.cluster_dump import load_cluster_dump from distributed.comm import CommClosedError from distributed.compatibility import LINUX, WINDOWS from distributed.core import Status from distributed.diagnostics.plugin import WorkerPlugin from distributed.metrics import time from distributed.scheduler import CollectTaskMetaDataPlugin, KilledWorker, Scheduler from distributed.sizeof import sizeof from distributed.utils import ( NoOpAwaitable, get_mp_context, is_valid_xml, open_port, sync, tmp_text, ) from distributed.utils_test import ( NO_AMM, BlockedGatherDep, TaskStateMetadataPlugin, _UnhashableCallable, async_wait_for, asyncinc, block_on_event, captured_logger, cluster, dec, div, double, gen_cluster, gen_test, get_cert, inc, map_varying, nodebug, popen, randominc, save_sys_modules, slowadd, slowdec, slowinc, throws, tls_only_security, varying, wait_for, wait_for_state, ) pytestmark = pytest.mark.ci1 @gen_cluster(client=True) async def test_submit(c, s, a, b): x = c.submit(inc, 10, key="x") assert not x.done() assert isinstance(x, Future) assert x.client is c result = await x assert result == 11 assert x.done() y = c.submit(inc, 20, key="y") z = c.submit(add, x, y) result = await z assert result == 11 + 21 s.validate_state() @gen_cluster(client=True) async def test_map(c, s, a, b): L1 = c.map(inc, range(5)) assert len(L1) == 5 assert isdistinct(x.key for x in L1) assert all(isinstance(x, Future) for x in L1) result = await L1[0] assert result == inc(0) assert len(s.tasks) == 5 L2 = c.map(inc, L1) result = await L2[1] assert result == inc(inc(1)) assert len(s.tasks) == 10 # assert L1[0].key in s.tasks[L2[0].key] total = c.submit(sum, L2) result = await total assert result == sum(map(inc, map(inc, range(5)))) L3 = c.map(add, L1, L2) result = await L3[1] assert result == inc(1) + inc(inc(1)) L4 = c.map(add, range(3), range(4)) results = await c.gather(L4) assert results == list(map(add, range(3), range(4))) def f(x, y=10): return x + y L5 = c.map(f, range(5), y=5) results = await c.gather(L5) assert results == list(range(5, 10)) y = c.submit(f, 10) L6 = c.map(f, range(5), y=y) results = await c.gather(L6) assert results == list(range(20, 25)) s.validate_state() @gen_cluster(client=True) async def test_map_empty(c, s, a, b): L1 = c.map(inc, [], pure=False) assert len(L1) == 0 results = await c.gather(L1) assert results == [] @gen_cluster(client=True) async def test_map_keynames(c, s, a, b): futures = c.map(inc, range(4), key="INC") assert all(f.key.startswith("INC") for f in futures) assert isdistinct(f.key for f in futures) futures2 = c.map(inc, [5, 6, 7, 8], key="INC") assert [f.key for f in futures] != [f.key for f in futures2] keys = ["inc-1", "inc-2", "inc-3", "inc-4"] futures = c.map(inc, range(4), key=keys) assert [f.key for f in futures] == keys @gen_cluster(client=True) async def test_map_retries(c, s, a, b): args = [ [ZeroDivisionError("one"), 2, 3], [4, 5, 6], [ZeroDivisionError("seven"), ZeroDivisionError("eight"), 9], ] x, y, z = c.map(*map_varying(args), retries=2) assert await x == 2 assert await y == 4 assert await z == 9 x, y, z = c.map(*map_varying(args), retries=1, pure=False) assert await x == 2 assert await y == 4 with pytest.raises(ZeroDivisionError, match="eight"): await z x, y, z = c.map(*map_varying(args), retries=0, pure=False) with pytest.raises(ZeroDivisionError, match="one"): await x assert await y == 4 with pytest.raises(ZeroDivisionError, match="seven"): await z @gen_cluster(client=True) async def test_map_batch_size(c, s, a, b): result = c.map(inc, range(100), batch_size=10) result = await c.gather(result) assert result == list(range(1, 101)) result = c.map(add, range(100), range(100), batch_size=10) result = await c.gather(result) assert result == list(range(0, 200, 2)) # mismatch shape result = c.map(add, range(100, 200), range(10), batch_size=2) result = await c.gather(result) assert result == list(range(100, 120, 2)) @gen_cluster(client=True) async def test_custom_key_with_batches(c, s, a, b): """Test of <https://github.com/dask/distributed/issues/4588>""" futs = c.map( lambda x: x**2, range(10), batch_size=5, key=[str(x) for x in range(10)], ) assert len(futs) == 10 await wait(futs) @gen_cluster(client=True) async def test_compute_retries(c, s, a, b): args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] # Sanity check for varying() use x = c.compute(delayed(varying(args))()) with pytest.raises(ZeroDivisionError, match="one"): await x # Same retries for all x = c.compute(delayed(varying(args))(), retries=1) with pytest.raises(ZeroDivisionError, match="two"): await x x = c.compute(delayed(varying(args))(), retries=2) assert await x == 3 args.append(4) x = c.compute(delayed(varying(args))(), retries=2) assert await x == 3 @gen_cluster(client=True) async def test_compute_retries_annotations(c, s, a, b): # Per-future retries xargs = [ZeroDivisionError("one"), ZeroDivisionError("two"), 30, 40] yargs = [ZeroDivisionError("five"), ZeroDivisionError("six"), 70] zargs = [80, 90, 100] with dask.annotate(retries=2): x = delayed(varying(xargs))() y = delayed(varying(yargs))() x, y = c.compute([x, y], optimize_graph=False) assert await x == 30 with pytest.raises(ZeroDivisionError, match="five"): await y x = delayed(varying(xargs))() with dask.annotate(retries=2): y = delayed(varying(yargs))() z = delayed(varying(zargs))() x, y, z = c.compute([x, y, z], optimize_graph=False) with pytest.raises(ZeroDivisionError, match="one"): await x assert await y == 70 assert await z == 80 def test_retries_get(c): args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] x = delayed(varying(args))() assert x.compute(retries=5) == 3 args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] x = delayed(varying(args))() with pytest.raises(ZeroDivisionError): x.compute() @gen_cluster(client=True) async def test_compute_persisted_retries(c, s, a, b): args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] # Sanity check x = c.persist(delayed(varying(args))()) fut = c.compute(x) with pytest.raises(ZeroDivisionError, match="one"): await fut x = c.persist(delayed(varying(args))()) fut = c.compute(x, retries=1) with pytest.raises(ZeroDivisionError, match="two"): await fut x = c.persist(delayed(varying(args))()) fut = c.compute(x, retries=2) assert await fut == 3 args.append(4) x = c.persist(delayed(varying(args))()) fut = c.compute(x, retries=3) assert await fut == 3 @gen_cluster(client=True) async def test_persist_retries(c, s, a, b): # Same retries for all args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] x = c.persist(delayed(varying(args))(), retries=1) x = c.compute(x) with pytest.raises(ZeroDivisionError, match="two"): await x x = c.persist(delayed(varying(args))(), retries=2) x = c.compute(x) assert await x == 3 @gen_cluster(client=True) async def test_persist_retries_annotations(c, s, a, b): # Per-key retries xargs = [ZeroDivisionError("one"), ZeroDivisionError("two"), 30, 40] yargs = [ZeroDivisionError("five"), ZeroDivisionError("six"), 70] zargs = [80, 90, 100] x = delayed(varying(xargs))() with dask.annotate(retries=2): y = delayed(varying(yargs))() z = delayed(varying(zargs))() x, y, z = c.persist([x, y, z], optimize_graph=False) x, y, z = c.compute([x, y, z]) with pytest.raises(ZeroDivisionError, match="one"): await x assert await y == 70 assert await z == 80 @gen_cluster(client=True) async def test_retries_dask_array(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones((10, 10), chunks=(3, 3)) future = c.compute(x.sum(), retries=2) y = await future assert y == 100 @gen_cluster(client=True) async def test_future_repr(c, s, a, b): pd = pytest.importorskip("pandas") x = c.submit(inc, 10) y = c.submit(pd.DataFrame, {"x": [1, 2, 3]}) await x await y for func in [repr, lambda x: x._repr_html_()]: assert str(x.key) in func(x) assert str(x.status) in func(x) assert str(x.status) in repr(c.futures[x.key]) assert "int" in func(x) assert "pandas" in func(y) assert "DataFrame" in func(y) @gen_cluster(client=True) async def test_future_tuple_repr(c, s, a, b): da = pytest.importorskip("dask.array") y = da.arange(10, chunks=(5,)).persist() f = futures_of(y)[0] for func in [repr, lambda x: x._repr_html_()]: for k in f.key: assert str(k) in func(f) @gen_cluster(client=True) async def test_Future_exception(c, s, a, b): x = c.submit(div, 1, 0) result = await x.exception() assert isinstance(result, ZeroDivisionError) x = c.submit(div, 1, 1) result = await x.exception() assert result is None def test_Future_exception_sync(c): x = c.submit(div, 1, 0) assert isinstance(x.exception(), ZeroDivisionError) x = c.submit(div, 1, 1) assert x.exception() is None @gen_cluster(client=True) async def test_Future_release(c, s, a, b): # Released Futures should be removed timely from the Client x = c.submit(div, 1, 1) await x x.release() await asyncio.sleep(0) assert not c.futures x = c.submit(slowinc, 1, delay=0.5) x.release() await asyncio.sleep(0) assert not c.futures x = c.submit(div, 1, 0) await x.exception() x.release() await asyncio.sleep(0) assert not c.futures def test_Future_release_sync(c): # Released Futures should be removed timely from the Client x = c.submit(div, 1, 1) x.result() x.release() wait_for(lambda: not c.futures, timeout=0.3) x = c.submit(slowinc, 1, delay=0.8) x.release() wait_for(lambda: not c.futures, timeout=0.3) x = c.submit(div, 1, 0) x.exception() x.release() wait_for(lambda: not c.futures, timeout=0.3) def test_short_tracebacks(loop, c): tblib = pytest.importorskip("tblib") future = c.submit(div, 1, 0) try: future.result() except Exception: _, _, tb = sys.exc_info() tb = tblib.Traceback(tb).to_dict() n = 0 while tb is not None: n += 1 tb = tb["tb_next"] assert n < 5 @gen_cluster(client=True) async def test_map_naming(c, s, a, b): L1 = c.map(inc, range(5)) L2 = c.map(inc, range(5)) assert [x.key for x in L1] == [x.key for x in L2] L3 = c.map(inc, [1, 1, 1, 1]) assert len({x._state for x in L3}) == 1 L4 = c.map(inc, [1, 1, 1, 1], pure=False) assert len({x._state for x in L4}) == 4 @gen_cluster(client=True) async def test_submit_naming(c, s, a, b): a = c.submit(inc, 1) b = c.submit(inc, 1) assert a._state is b._state c = c.submit(inc, 1, pure=False) assert c.key != a.key @gen_cluster(client=True) async def test_exceptions(c, s, a, b): x = c.submit(div, 1, 2) result = await x assert result == 1 / 2 x = c.submit(div, 1, 0) with pytest.raises(ZeroDivisionError): await x x = c.submit(div, 10, 2) # continues to operate result = await x assert result == 10 / 2 @gen_cluster() async def test_gc(s, a, b): async with Client(s.address, asynchronous=True) as c: x = c.submit(inc, 10) await x assert s.tasks[x.key].who_has x.__del__() await async_wait_for( lambda: x.key not in s.tasks or not s.tasks[x.key].who_has, timeout=0.3 ) def test_thread(c): x = c.submit(inc, 1) assert x.result() == 2 x = c.submit(slowinc, 1, delay=0.3) with pytest.raises(TimeoutError): x.result(timeout="10 ms") assert x.result() == 2 def test_sync_exceptions(c): x = c.submit(div, 10, 2) assert x.result() == 5 y = c.submit(div, 10, 0) try: y.result() assert False except ZeroDivisionError: pass z = c.submit(div, 10, 5) assert z.result() == 2 @gen_cluster(client=True) async def test_gather(c, s, a, b): x = c.submit(inc, 10) y = c.submit(inc, x) result = await c.gather(x) assert result == 11 result = await c.gather([x]) assert result == [11] result = await c.gather({"x": x, "y": [y]}) assert result == {"x": 11, "y": [12]} @gen_cluster(client=True) async def test_gather_mismatched_client(c, s, a, b): async with Client(s.address, asynchronous=True) as c2: x = c.submit(inc, 10) y = c2.submit(inc, 5) with pytest.raises(ValueError, match="Futures created by another client"): await c.gather([x, y]) @gen_cluster(client=True) async def test_gather_lost(c, s, a, b): [x] = await c.scatter([1], workers=a.address) y = c.submit(inc, 1, workers=b.address) await a.close() with pytest.raises(Exception): await c.gather([x, y]) def test_gather_sync(c): x = c.submit(inc, 1) assert c.gather(x) == 2 y = c.submit(div, 1, 0) with pytest.raises(ZeroDivisionError): c.gather([x, y]) [xx] = c.gather([x, y], errors="skip") assert xx == 2 @gen_cluster(client=True) async def test_gather_strict(c, s, a, b): x = c.submit(div, 2, 1) y = c.submit(div, 1, 0) with pytest.raises(ZeroDivisionError): await c.gather([x, y]) [xx] = await c.gather([x, y], errors="skip") assert xx == 2 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)]) async def test_gather_skip(c, s, a): x = c.submit(div, 1, 0, priority=10) y = c.submit(slowinc, 1, delay=0.5) with captured_logger(logging.getLogger("distributed.scheduler")) as sched: with captured_logger(logging.getLogger("distributed.client")) as client: L = await c.gather([x, y], errors="skip") assert L == [2] assert not client.getvalue() assert not sched.getvalue() @gen_cluster(client=True) async def test_limit_concurrent_gathering(c, s, a, b): futures = c.map(inc, range(100)) await c.gather(futures) assert len(a.transfer_outgoing_log) + len(b.transfer_outgoing_log) < 100 @gen_cluster(client=True) async def test_get(c, s, a, b): future = c.get({"x": (inc, 1)}, "x", sync=False) assert isinstance(future, Future) result = await future assert result == 2 futures = c.get({"x": (inc, 1)}, ["x"], sync=False) assert isinstance(futures[0], Future) result = await c.gather(futures) assert result == [2] futures = c.get({}, [], sync=False) result = await c.gather(futures) assert result == [] result = await c.get( {("x", 1): (inc, 1), ("x", 2): (inc, ("x", 1))}, ("x", 2), sync=False ) assert result == 3 def test_get_sync(c): assert c.get({"x": (inc, 1)}, "x") == 2 def test_no_future_references(c): """Test that there are neither global references to Future objects nor circular references that need to be collected by gc """ ws = weakref.WeakSet() futures = c.map(inc, range(10)) ws.update(futures) del futures with profile.lock: assert not list(ws) def test_get_sync_optimize_graph_passes_through(c): bag = db.range(10, npartitions=3).map(inc) dask.compute(bag.sum(), optimize_graph=False) @gen_cluster(client=True) async def test_gather_errors(c, s, a, b): def f(a, b): raise TypeError def g(a, b): raise AttributeError future_f = c.submit(f, 1, 2) future_g = c.submit(g, 1, 2) with pytest.raises(TypeError): await c.gather(future_f) with pytest.raises(AttributeError): await c.gather(future_g) await a.close() @gen_cluster(client=True) async def test_wait(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 1) z = c.submit(inc, 2) done, not_done = await wait([x, y, z]) assert done == {x, y, z} assert not_done == set() assert x.status == y.status == "finished" @gen_cluster(client=True) async def test_wait_first_completed(c, s, a, b): event = Event() x = c.submit(block_on_event, event) y = c.submit(block_on_event, event) z = c.submit(inc, 2) done, not_done = await wait([x, y, z], return_when="FIRST_COMPLETED") assert done == {z} assert not_done == {x, y} assert z.status == "finished" assert x.status == "pending" assert y.status == "pending" await event.set() @gen_cluster(client=True) async def test_wait_timeout(c, s, a, b): future = c.submit(sleep, 0.3) with pytest.raises(TimeoutError): await wait(future, timeout=0.01) # Ensure timeout can be a string future = c.submit(sleep, 0.3) with pytest.raises(TimeoutError): await wait(future, timeout="0.01 s") def test_wait_sync(c): x = c.submit(inc, 1) y = c.submit(inc, 2) done, not_done = wait([x, y]) assert done == {x, y} assert not_done == set() assert x.status == y.status == "finished" future = c.submit(sleep, 0.3) with pytest.raises(TimeoutError): wait(future, timeout=0.01) def test_wait_informative_error_for_timeouts(c): x = c.submit(inc, 1) y = c.submit(inc, 2) try: wait(x, y) except Exception as e: assert "timeout" in str(e) assert "list" in str(e) @gen_cluster(client=True) async def test_garbage_collection(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 1) assert c.refcount[x.key] == 2 x.__del__() await asyncio.sleep(0) assert c.refcount[x.key] == 1 z = c.submit(inc, y) y.__del__() await asyncio.sleep(0) result = await z assert result == 3 ykey = y.key y.__del__() await asyncio.sleep(0) assert ykey not in c.futures @gen_cluster(client=True) async def test_garbage_collection_with_scatter(c, s, a, b): [future] = await c.scatter([1]) assert future.key in c.futures assert future.status == "finished" assert {cs.client_key for cs in s.tasks[future.key].who_wants} == {c.id} key = future.key assert c.refcount[key] == 1 future.__del__() await asyncio.sleep(0) assert c.refcount[key] == 0 while key in s.tasks and s.tasks[key].who_has: await asyncio.sleep(0.1) @gen_cluster(client=True) async def test_recompute_released_key(c, s, a, b): x = c.submit(inc, 100) result1 = await x xkey = x.key del x with profile.lock: await asyncio.sleep(0) assert c.refcount[xkey] == 0 # 1 second batching needs a second action to trigger while xkey in s.tasks and s.tasks[xkey].who_has or xkey in a.data or xkey in b.data: await asyncio.sleep(0.1) x = c.submit(inc, 100) assert x.key in c.futures result2 = await x assert result1 == result2 @pytest.mark.slow @gen_cluster(client=True) async def test_long_tasks_dont_trigger_timeout(c, s, a, b): from time import sleep x = c.submit(sleep, 3) await x @pytest.mark.skip @gen_cluster(client=True) async def test_missing_data_heals(c, s, a, b): a.validate = False b.validate = False x = c.submit(inc, 1) y = c.submit(inc, x) z = c.submit(inc, y) await wait([x, y, z]) # Secretly delete y's key if y.key in a.data: del a.data[y.key] a.release_key(y.key, stimulus_id="test") if y.key in b.data: del b.data[y.key] b.release_key(y.key, stimulus_id="test") await asyncio.sleep(0) w = c.submit(add, y, z) result = await w assert result == 3 + 4 @pytest.mark.skip @gen_cluster(client=True) async def test_gather_robust_to_missing_data(c, s, a, b): a.validate = False b.validate = False x, y, z = c.map(inc, range(3)) await wait([x, y, z]) # everything computed for f in [x, y]: for w in [a, b]: if f.key in w.data: del w.data[f.key] await asyncio.sleep(0) w.release_key(f.key, stimulus_id="test") xx, yy, zz = await c.gather([x, y, z]) assert (xx, yy, zz) == (1, 2, 3) @pytest.mark.skip @gen_cluster(client=True) async def test_gather_robust_to_nested_missing_data(c, s, a, b): a.validate = False b.validate = False w = c.submit(inc, 1) x = c.submit(inc, w) y = c.submit(inc, x) z = c.submit(inc, y) await wait([z]) for worker in [a, b]: for datum in [y, z]: if datum.key in worker.data: del worker.data[datum.key] await asyncio.sleep(0) worker.release_key(datum.key, stimulus_id="test") result = await c.gather([z]) assert result == [inc(inc(inc(inc(1))))] @gen_cluster(client=True) async def test_tokenize_on_futures(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 1) tok = tokenize(x) assert tokenize(x) == tokenize(x) assert tokenize(x) == tokenize(y) c.futures[x.key].finish() assert tok == tokenize(y) @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True, config=NO_AMM) async def test_restrictions_submit(c, s, a, b): x = c.submit(inc, 1, workers={a.ip}) y = c.submit(inc, x, workers={b.ip}) await wait([x, y]) assert s.tasks[x.key].host_restrictions == {a.ip} assert x.key in a.data assert s.tasks[y.key].host_restrictions == {b.ip} assert y.key in b.data @gen_cluster(client=True, config=NO_AMM) async def test_restrictions_ip_port(c, s, a, b): x = c.submit(inc, 1, workers={a.address}) y = c.submit(inc, x, workers={b.address}) await wait([x, y]) assert s.tasks[x.key].worker_restrictions == {a.address} assert x.key in a.data assert s.tasks[y.key].worker_restrictions == {b.address} assert y.key in b.data @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_restrictions_map(c, s, a, b): L = c.map(inc, range(5), workers={a.ip}) await wait(L) assert set(a.data) == {x.key for x in L} assert not b.data for x in L: assert s.tasks[x.key].host_restrictions == {a.ip} @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_restrictions_get(c, s, a, b): dsk = {"x": 1, "y": (inc, "x"), "z": (inc, "y")} futures = c.get(dsk, ["y", "z"], workers=a.ip, sync=False) result = await c.gather(futures) assert result == [2, 3] assert "y" in a.data assert "z" in a.data assert len(b.data) == 0 @gen_cluster(client=True, config=NO_AMM) async def test_restrictions_get_annotate(c, s, a, b): x = 1 with dask.annotate(workers=a.address): y = delayed(inc)(x) with dask.annotate(workers=b.address): z = delayed(inc)(y) futures = c.get(z.__dask_graph__(), [y.key, z.key], sync=False) result = await c.gather(futures) assert result == [2, 3] assert y.key in a.data assert z.key in b.data @gen_cluster(client=True) async def dont_test_bad_restrictions_raise_exception(c, s, a, b): z = c.submit(inc, 2, workers={"bad-address"}) try: await z assert False except ValueError as e: assert "bad-address" in str(e) assert z.key in str(e) @gen_cluster(client=True) async def test_remove_worker(c, s, a, b): L = c.map(inc, range(20)) await wait(L) await b.close() assert b.address not in s.workers result = await c.gather(L) assert result == list(map(inc, range(20))) @gen_cluster(nthreads=[("127.0.0.1", 1)], client=True) async def test_errors_dont_block(c, s, w): L = [c.submit(inc, 1), c.submit(throws, 1), c.submit(inc, 2), c.submit(throws, 2)] while not (L[0].status == L[2].status == "finished"): await asyncio.sleep(0.01) result = await c.gather([L[0], L[2]]) assert result == [2, 3] def assert_list(x, z=None): if z is None: z = [] return isinstance(x, list) and isinstance(z, list) @gen_cluster(client=True) async def test_submit_quotes(c, s, a, b): x = c.submit(assert_list, [1, 2, 3]) result = await x assert result x = c.submit(assert_list, [1, 2, 3], z=[4, 5, 6]) result = await x assert result x = c.submit(inc, 1) y = c.submit(inc, 2) z = c.submit(assert_list, [x, y]) result = await z assert result @gen_cluster(client=True) async def test_map_quotes(c, s, a, b): L = c.map(assert_list, [[1, 2, 3], [4]]) result = await c.gather(L) assert all(result) L = c.map(assert_list, [[1, 2, 3], [4]], z=[10]) result = await c.gather(L) assert all(result) L = c.map(assert_list, [[1, 2, 3], [4]], [[]] * 3) result = await c.gather(L) assert all(result) @gen_cluster() async def test_two_consecutive_clients_share_results(s, a, b): async with Client(s.address, asynchronous=True) as c: x = c.submit(random.randint, 0, 1000, pure=True) xx = await x async with Client(s.address, asynchronous=True) as f: y = f.submit(random.randint, 0, 1000, pure=True) yy = await y assert xx == yy @gen_cluster(client=True) async def test_submit_then_get_with_Future(c, s, a, b): x = c.submit(slowinc, 1) dsk = {"y": (inc, x)} result = await c.get(dsk, "y", sync=False) assert result == 3 @gen_cluster(client=True) async def test_aliases(c, s, a, b): x = c.submit(inc, 1) dsk = {"y": x} result = await c.get(dsk, "y", sync=False) assert result == 2 @gen_cluster(client=True) async def test_aliases_2(c, s, a, b): dsk_keys = [ ({"x": (inc, 1), "y": "x", "z": "x", "w": (add, "y", "z")}, ["y", "w"]), ({"x": "y", "y": 1}, ["x"]), ({"x": 1, "y": "x", "z": "y", "w": (inc, "z")}, ["w"]), ] for dsk, keys in dsk_keys: result = await c.gather(c.get(dsk, keys, sync=False)) assert list(result) == list(dask.get(dsk, keys)) await asyncio.sleep(0) @gen_cluster(client=True) async def test_scatter(c, s, a, b): d = await c.scatter({"y": 20}) assert isinstance(d["y"], Future) assert a.data.get("y") == 20 or b.data.get("y") == 20 y_who_has = s.get_who_has(keys=["y"])["y"] assert a.address in y_who_has or b.address in y_who_has assert s.get_nbytes(summary=False) == {"y": sizeof(20)} yy = await c.gather([d["y"]]) assert yy == [20] [x] = await c.scatter([10]) assert isinstance(x, Future) assert a.data.get(x.key) == 10 or b.data.get(x.key) == 10 xx = await c.gather([x]) x_who_has = s.get_who_has(keys=[x.key])[x.key] assert s.tasks[x.key].who_has assert ( s.workers[a.address] in s.tasks[x.key].who_has or s.workers[b.address] in s.tasks[x.key].who_has ) assert s.get_nbytes(summary=False) == {"y": sizeof(20), x.key: sizeof(10)} assert xx == [10] z = c.submit(add, x, d["y"]) # submit works on Future result = await z assert result == 10 + 20 result = await c.gather([z, x]) assert result == [30, 10] @gen_cluster(client=True) async def test_scatter_types(c, s, a, b): d = await c.scatter({"x": 1}) assert isinstance(d, dict) assert list(d) == ["x"] for seq in [[1], (1,), {1}, frozenset([1])]: L = await c.scatter(seq) assert isinstance(L, type(seq)) assert len(L) == 1 s.validate_state() seq = await c.scatter(range(5)) assert isinstance(seq, list) assert len(seq) == 5 s.validate_state() @gen_cluster(client=True) async def test_scatter_non_list(c, s, a, b): x = await c.scatter(1) assert isinstance(x, Future) result = await x assert result == 1 @gen_cluster(client=True) async def test_scatter_tokenize_local(c, s, a, b): from dask.base import normalize_token class MyObj: pass L = [] @normalize_token.register(MyObj) def f(x): L.append(x) return "x" obj = MyObj() future = await c.scatter(obj) assert L and L[0] is obj @gen_cluster(client=True) async def test_scatter_singletons(c, s, a, b): np = pytest.importorskip("numpy") pd = pytest.importorskip("pandas") for x in [1, np.ones(5), pd.DataFrame({"x": [1, 2, 3]})]: future = await c.scatter(x) result = await future assert str(result) == str(x) @gen_cluster(client=True) async def test_scatter_typename(c, s, a, b): future = await c.scatter(123) assert future.key.startswith("int") @gen_cluster(client=True) async def test_scatter_hash(c, s, a, b): x = await c.scatter(123) y = await c.scatter(123) assert x.key == y.key z = await c.scatter(123, hash=False) assert z.key != y.key @gen_cluster(client=True) async def test_scatter_hash_2(c, s, a, b): [a] = await c.scatter([1]) [b] = await c.scatter([1]) assert a.key == b.key s.validate_state() @gen_cluster(client=True) async def test_get_releases_data(c, s, a, b): await c.gather(c.get({"x": (inc, 1)}, ["x"], sync=False)) while c.refcount["x"]: await asyncio.sleep(0.01) def test_current(s, a, b, loop_in_thread): loop = loop_in_thread with Client(s["address"], loop=loop) as c: assert Client.current() is c with pytest.raises( ValueError, match=r"No clients found" r"\nStart a client and point it to the scheduler address" r"\n from distributed import Client" r"\n client = Client\('ip-addr-of-scheduler:8786'\)", ): Client.current() with Client(s["address"], loop=loop) as c: assert Client.current() is c def test_global_clients(loop): assert _get_global_client() is None with pytest.raises( ValueError, match=r"No clients found" r"\nStart a client and point it to the scheduler address" r"\n from distributed import Client" r"\n client = Client\('ip-addr-of-scheduler:8786'\)", ): default_client() with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: assert _get_global_client() is c assert default_client() is c with Client(s["address"], loop=loop) as f: assert _get_global_client() is f assert default_client() is f assert default_client(c) is c assert default_client(f) is f assert _get_global_client() is None @gen_cluster(client=True) async def test_exception_on_exception(c, s, a, b): x = c.submit(lambda: 1 / 0) y = c.submit(inc, x) with pytest.raises(ZeroDivisionError): await y z = c.submit(inc, y) with pytest.raises(ZeroDivisionError): await z @gen_cluster(client=True) async def test_get_task_prefix_states(c, s, a, b): x = await c.submit(inc, 1) res = s.get_task_prefix_states() data = { "inc": { "erred": 0, "memory": 1, "processing": 0, "released": 0, "waiting": 0, } } assert res == data del x while s.get_task_prefix_states() == data: await asyncio.sleep(0.01) res = s.get_task_prefix_states() assert res == {} @gen_cluster(client=True) async def test_get_nbytes(c, s, a, b): [x] = await c.scatter([1]) assert s.get_nbytes(summary=False) == {x.key: sizeof(1)} y = c.submit(inc, x) await y assert s.get_nbytes(summary=False) == {x.key: sizeof(1), y.key: sizeof(2)} @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_nbytes_determines_worker(c, s, a, b): x = c.submit(identity, 1, workers=[a.ip]) y = c.submit(identity, tuple(range(100)), workers=[b.ip]) await c.gather([x, y]) z = c.submit(lambda x, y: None, x, y) await z assert s.tasks[z.key].who_has == {s.workers[b.address]} @gen_cluster(client=True) async def test_if_intermediates_clear_on_error(c, s, a, b): x = delayed(div, pure=True)(1, 0) y = delayed(div, pure=True)(1, 2) z = delayed(add, pure=True)(x, y) f = c.compute(z) with pytest.raises(ZeroDivisionError): await f s.validate_state() assert not any(ts.who_has for ts in s.tasks.values()) @gen_cluster( client=True, config={"distributed.scheduler.default-task-durations": {"f": "1ms"}} ) async def test_pragmatic_move_small_data_to_large_data(c, s, a, b): np = pytest.importorskip("numpy") lists = c.map(np.ones, [10000] * 10, pure=False) sums = c.map(np.sum, lists) total = c.submit(sum, sums) def f(x, y): return None results = c.map(f, lists, [total] * 10) await wait([total]) await wait(results) assert ( sum( s.tasks[r.key].who_has.issubset(s.tasks[l.key].who_has) for l, r in zip(lists, results) ) >= 9 ) @gen_cluster(client=True) async def test_get_with_non_list_key(c, s, a, b): dsk = {("x", 0): (inc, 1), 5: (inc, 2)} x = await c.get(dsk, ("x", 0), sync=False) y = await c.get(dsk, 5, sync=False) assert x == 2 assert y == 3 @gen_cluster(client=True) async def test_get_with_error(c, s, a, b): dsk = {"x": (div, 1, 0), "y": (inc, "x")} with pytest.raises(ZeroDivisionError): await c.get(dsk, "y", sync=False) def test_get_with_error_sync(c): dsk = {"x": (div, 1, 0), "y": (inc, "x")} with pytest.raises(ZeroDivisionError): c.get(dsk, "y") @gen_cluster(client=True) async def test_directed_scatter(c, s, a, b): await c.scatter([1, 2, 3], workers=[a.address]) assert len(a.data) == 3 assert not b.data await c.scatter([4, 5], workers=[b.name]) assert len(b.data) == 2 @gen_cluster(client=True) async def test_scatter_direct(c, s, a, b): future = await c.scatter(123, direct=True) assert future.key in a.data or future.key in b.data assert s.tasks[future.key].who_has assert future.status == "finished" result = await future assert result == 123 assert not s.counters["op"].components[0]["scatter"] result = await future assert not s.counters["op"].components[0]["gather"] result = await c.gather(future) assert not s.counters["op"].components[0]["gather"] @gen_cluster() async def test_scatter_direct_2(s, a, b): async with Client(s.address, asynchronous=True, heartbeat_interval=10) as c: last = s.clients[c.id].last_seen while s.clients[c.id].last_seen == last: await asyncio.sleep(0.10) @gen_cluster(client=True) async def test_scatter_direct_numpy(c, s, a, b): np = pytest.importorskip("numpy") x = np.ones(5) future = await c.scatter(x, direct=True) result = await future assert np.allclose(x, result) assert not s.counters["op"].components[0]["scatter"] @gen_cluster(client=True, config=NO_AMM) async def test_scatter_direct_broadcast(c, s, a, b): future2 = await c.scatter(456, direct=True, broadcast=True) assert future2.key in a.data assert future2.key in b.data assert s.tasks[future2.key].who_has == {s.workers[a.address], s.workers[b.address]} result = await future2 assert result == 456 assert not s.counters["op"].components[0]["scatter"] @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_scatter_direct_balanced(c, s, *workers): futures = await c.scatter([1, 2, 3], direct=True) assert sorted(len(w.data) for w in workers) == [0, 1, 1, 1] @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4, config=NO_AMM) async def test_scatter_direct_broadcast_target(c, s, *workers): futures = await c.scatter([123, 456], direct=True, workers=workers[0].address) assert futures[0].key in workers[0].data assert futures[1].key in workers[0].data futures = await c.scatter( [123, 456], direct=True, broadcast=True, workers=[w.address for w in workers[:3]], ) assert ( f.key in w.data and w.address in s.tasks[f.key].who_has for f in futures for w in workers[:3] ) @gen_cluster(client=True, nthreads=[]) async def test_scatter_direct_empty(c, s): with pytest.raises((ValueError, TimeoutError)): await c.scatter(123, direct=True, timeout=0.1) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 5) async def test_scatter_direct_spread_evenly(c, s, *workers): futures = [] for i in range(10): future = await c.scatter(i, direct=True) futures.append(future) assert all(w.data for w in workers) @pytest.mark.parametrize("direct", [True, False]) @pytest.mark.parametrize("broadcast", [True, False]) def test_scatter_gather_sync(c, direct, broadcast): futures = c.scatter([1, 2, 3], direct=direct, broadcast=broadcast) results = c.gather(futures, direct=direct) assert results == [1, 2, 3] delayed(inc)(1).compute(direct=direct) @gen_cluster(client=True) async def test_gather_direct(c, s, a, b): futures = await c.scatter([1, 2, 3]) data = await c.gather(futures, direct=True) assert data == [1, 2, 3] @gen_cluster(client=True) async def test_many_submits_spread_evenly(c, s, a, b): L = [c.submit(inc, i) for i in range(10)] await wait(L) assert a.data and b.data @gen_cluster(client=True) async def test_traceback(c, s, a, b): x = c.submit(div, 1, 0) tb = await x.traceback() assert any("x / y" in line for line in pluck(3, traceback.extract_tb(tb))) @gen_cluster(client=True) async def test_get_traceback(c, s, a, b): try: await c.get({"x": (div, 1, 0)}, "x", sync=False) except ZeroDivisionError: exc_type, exc_value, exc_traceback = sys.exc_info() L = traceback.format_tb(exc_traceback) assert any("x / y" in line for line in L) @gen_cluster(client=True) async def test_gather_traceback(c, s, a, b): x = c.submit(div, 1, 0) try: await c.gather(x) except ZeroDivisionError: exc_type, exc_value, exc_traceback = sys.exc_info() L = traceback.format_tb(exc_traceback) assert any("x / y" in line for line in L) def test_traceback_sync(c): x = c.submit(div, 1, 0) tb = x.traceback() assert any( "x / y" in line for line in concat(traceback.extract_tb(tb)) if isinstance(line, str) ) y = c.submit(inc, x) tb2 = y.traceback() assert set(pluck(3, traceback.extract_tb(tb2))).issuperset( set(pluck(3, traceback.extract_tb(tb))) ) z = c.submit(div, 1, 2) tb = z.traceback() assert tb is None @gen_cluster(client=True) async def test_upload_file(c, s, a, b): def g(): import myfile return myfile.f() with save_sys_modules(): for value in [123, 456]: with tmp_text("myfile.py", f"def f():\n return {value}") as fn: await c.upload_file(fn) x = c.submit(g, pure=False) result = await x assert result == value @gen_cluster(client=True) async def test_upload_file_refresh_delayed(c, s, a, b): with save_sys_modules(): for value in [123, 456]: with tmp_text("myfile.py", f"def f():\n return {value}") as fn: await c.upload_file(fn) sys.path.append(os.path.dirname(fn)) from myfile import f b = delayed(f)() bb = c.compute(b, sync=False) result = await c.gather(bb) assert result == value @gen_cluster(client=True) async def test_upload_file_no_extension(c, s, a, b): with tmp_text("myfile", "") as fn: await c.upload_file(fn) @gen_cluster(client=True) async def test_upload_file_zip(c, s, a, b): def g(): import myfile return myfile.f() with save_sys_modules(): try: for value in [123, 456]: with tmp_text( "myfile.py", f"def f():\n return {value}" ) as fn_my_file: with zipfile.ZipFile("myfile.zip", "w") as z: z.write(fn_my_file, arcname=os.path.basename(fn_my_file)) await c.upload_file("myfile.zip") x = c.submit(g, pure=False) result = await x assert result == value finally: if os.path.exists("myfile.zip"): os.remove("myfile.zip") @pytest.mark.slow @gen_cluster(client=True) async def test_upload_file_egg(c, s, a, b): pytest.importorskip("setuptools") def g(): import package_1 import package_2 return package_1.a, package_2.b # c.upload_file tells each worker to # - put this file in their local_directory # - modify their sys.path to include it # we don't care about the local_directory # but we do care about restoring the path with save_sys_modules(): for value in [123, 456]: with tmpfile() as dirname: os.mkdir(dirname) with open(os.path.join(dirname, "setup.py"), "w") as f: f.write("from setuptools import setup, find_packages\n") f.write( 'setup(name="my_package", packages=find_packages(), ' f'version="{value}")\n' ) # test a package with an underscore in the name package_1 = os.path.join(dirname, "package_1") os.mkdir(package_1) with open(os.path.join(package_1, "__init__.py"), "w") as f: f.write(f"a = {value}\n") # test multiple top-level packages package_2 = os.path.join(dirname, "package_2") os.mkdir(package_2) with open(os.path.join(package_2, "__init__.py"), "w") as f: f.write(f"b = {value}\n") # compile these into an egg subprocess.check_call( [sys.executable, "setup.py", "bdist_egg"], cwd=dirname ) egg_root = os.path.join(dirname, "dist") # first file ending with '.egg' egg_name = [ fname for fname in os.listdir(egg_root) if fname.endswith(".egg") ][0] egg_path = os.path.join(egg_root, egg_name) await c.upload_file(egg_path) os.remove(egg_path) x = c.submit(g, pure=False) result = await x assert result == (value, value) # _upload_large_file internally calls replicate, which makes it incompatible with AMM @gen_cluster(client=True, config=NO_AMM) async def test_upload_large_file(c, s, a, b): assert a.local_directory assert b.local_directory with tmp_text("myfile", "abc") as fn: with tmp_text("myfile2", "def") as fn2: await c._upload_large_file(fn, remote_filename="x") await c._upload_large_file(fn2) for w in [a, b]: assert os.path.exists(os.path.join(w.local_directory, "x")) assert os.path.exists(os.path.join(w.local_directory, "myfile2")) with open(os.path.join(w.local_directory, "x")) as f: assert f.read() == "abc" with open(os.path.join(w.local_directory, "myfile2")) as f: assert f.read() == "def" def test_upload_file_sync(c): def g(): import myfile return myfile.x with tmp_text("myfile.py", "x = 123") as fn: c.upload_file(fn) x = c.submit(g) assert x.result() == 123 @gen_cluster(client=True) async def test_upload_file_exception(c, s, a, b): with tmp_text("myfile.py", "syntax-error!") as fn: with pytest.raises(SyntaxError): await c.upload_file(fn) def test_upload_file_exception_sync(c): with tmp_text("myfile.py", "syntax-error!") as fn: with pytest.raises(SyntaxError): c.upload_file(fn) @gen_cluster(client=True, nthreads=[]) async def test_upload_file_new_worker(c, s): def g(): import myfile return myfile.x with tmp_text("myfile.py", "x = 123") as fn: await c.upload_file(fn) async with Worker(s.address): x = await c.submit(g) assert x == 123 @pytest.mark.skip @gen_cluster() async def test_multiple_clients(s, a, b): a = await Client(s.address, asynchronous=True) b = await Client(s.address, asynchronous=True) x = a.submit(inc, 1) y = b.submit(inc, 2) assert x.client is a assert y.client is b xx = await x yy = await y assert xx == 2 assert yy == 3 z = a.submit(add, x, y) assert z.client is a zz = await z assert zz == 5 await a.close() await b.close() @gen_cluster(client=True) async def test_async_compute(c, s, a, b): from dask.delayed import delayed x = delayed(1) y = delayed(inc)(x) z = delayed(dec)(x) [yy, zz, aa] = c.compute([y, z, 3], sync=False) assert isinstance(yy, Future) assert isinstance(zz, Future) assert aa == 3 result = await c.gather([yy, zz]) assert result == [2, 0] assert isinstance(c.compute(y), Future) assert isinstance(c.compute([y]), (tuple, list)) @gen_cluster(client=True) async def test_async_compute_with_scatter(c, s, a, b): d = await c.scatter({("x", 1): 1, ("y", 1): 2}) x, y = d[("x", 1)], d[("y", 1)] from dask.delayed import delayed z = delayed(add)(delayed(inc)(x), delayed(inc)(y)) zz = c.compute(z) [result] = await c.gather([zz]) assert result == 2 + 3 def test_sync_compute(c): x = delayed(1) y = delayed(inc)(x) z = delayed(dec)(x) yy, zz = c.compute([y, z], sync=True) assert (yy, zz) == (2, 0) @gen_cluster(client=True) async def test_remote_scatter_gather(c, s, a, b): x, y, z = await c.scatter([1, 2, 3]) assert x.key in a.data or x.key in b.data assert y.key in a.data or y.key in b.data assert z.key in a.data or z.key in b.data xx, yy, zz = await c.gather([x, y, z]) assert (xx, yy, zz) == (1, 2, 3) @gen_cluster(client=True) async def test_remote_submit_on_Future(c, s, a, b): x = c.submit(lambda x: x + 1, 1) y = c.submit(lambda x: x + 1, x) result = await y assert result == 3 def test_start_is_idempotent(c): c.start() c.start() c.start() x = c.submit(inc, 1) assert x.result() == 2 @gen_cluster(client=True) async def test_client_with_scheduler(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 2) z = c.submit(add, x, y) result = await x assert result == 1 + 1 result = await z assert result == 1 + 1 + 1 + 2 A, B, C = await c.scatter([1, 2, 3]) AA, BB, xx = await c.gather([A, B, x]) assert (AA, BB, xx) == (1, 2, 2) result = await c.get({"x": (inc, 1), "y": (add, "x", 10)}, "y", sync=False) assert result == 12 @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_allow_restrictions(c, s, a, b): aws = s.workers[a.address] bws = s.workers[a.address] x = c.submit(inc, 1, workers=a.ip) await x assert s.tasks[x.key].who_has == {aws} assert not any(ts.loose_restrictions for ts in s.tasks.values()) x = c.submit(inc, 2, workers=a.ip, allow_other_workers=True) await x assert s.tasks[x.key].who_has == {aws} assert s.tasks[x.key].loose_restrictions L = c.map(inc, range(3, 13), workers=a.ip, allow_other_workers=True) await wait(L) assert all(s.tasks[f.key].who_has == {aws} for f in L) for f in L: assert s.tasks[f.key].loose_restrictions x = c.submit(inc, 15, workers="127.0.0.3", allow_other_workers=True) await x assert s.tasks[x.key].who_has assert s.tasks[x.key].loose_restrictions L = c.map(inc, range(15, 25), workers="127.0.0.3", allow_other_workers=True) await wait(L) assert all(s.tasks[f.key].who_has for f in L) for f in L: assert s.tasks[f.key].loose_restrictions with pytest.raises(ValueError): c.submit(inc, 1, allow_other_workers=True) with pytest.raises(ValueError): c.map(inc, [1], allow_other_workers=True) with pytest.raises(TypeError): c.submit(inc, 20, workers="127.0.0.1", allow_other_workers="Hello!") with pytest.raises(TypeError): c.map(inc, [20], workers="127.0.0.1", allow_other_workers="Hello!") def test_bad_address(loop): with pytest.raises(OSError, match="connect"): Client("123.123.123.123:1234", timeout=0.1, loop=loop) with pytest.raises(OSError, match="connect"): Client("127.0.0.1:1234", timeout=0.1, loop=loop) def test_informative_error_on_cluster_type(): with pytest.raises( TypeError, match=r"Scheduler address must be a string or a Cluster instance" ): Client(LocalCluster) @gen_cluster(client=True) async def test_long_error(c, s, a, b): def bad(x): raise ValueError("a" * 100000) x = c.submit(bad, 10) try: await x except ValueError as e: assert len(str(e)) < 100000 tb = await x.traceback() assert all( len(line) < 100000 for line in concat(traceback.extract_tb(tb)) if isinstance(line, str) ) @gen_cluster(client=True) async def test_map_on_futures_with_kwargs(c, s, a, b): def f(x, y=10): return x + y futures = c.map(inc, range(10)) futures2 = c.map(f, futures, y=20) results = await c.gather(futures2) assert results == [i + 1 + 20 for i in range(10)] future = c.submit(inc, 100) future2 = c.submit(f, future, y=200) result = await future2 assert result == 100 + 1 + 200 class BadlySerializedObject: def __getstate__(self): return 1 def __setstate__(self, state): raise TypeError("hello!") class FatallySerializedObject: def __getstate__(self): return 1 def __setstate__(self, state): print("This should never have been deserialized, closing") import sys sys.exit(0) @gen_cluster(client=True) async def test_badly_serialized_input(c, s, a, b): o = BadlySerializedObject() future = c.submit(inc, o) futures = c.map(inc, range(10)) L = await c.gather(futures) assert list(L) == list(map(inc, range(10))) assert future.status == "error" with pytest.raises(Exception) as info: await future assert "hello!" in str(info.value) @pytest.mark.skip @gen_test() async def test_badly_serialized_input_stderr(capsys, c): o = BadlySerializedObject() future = c.submit(inc, o) while True: sleep(0.01) out, err = capsys.readouterr() if "hello!" in err: break assert future.status == "error" @pytest.mark.parametrize( "func", [ str, repr, operator.methodcaller("_repr_html_"), ], ) def test_repr(loop, func): with cluster(nworkers=3, worker_kwargs={"memory_limit": "2 GiB"}) as (s, [a, b, c]): with Client(s["address"], loop=loop) as c: text = func(c) assert c.scheduler.address in text assert "threads=3" in text or "Total threads: </strong>" in text assert "6.00 GiB" in text if "<table" not in text: assert len(text) < 80 text = func(c) assert "No scheduler connected" in text @gen_cluster(client=True) async def test_repr_async(c, s, a, b): c._repr_html_() @gen_cluster(client=True, worker_kwargs={"memory_limit": None}) async def test_repr_no_memory_limit(c, s, a, b): c._repr_html_() @gen_test() async def test_repr_localcluster(): async with LocalCluster( processes=False, dashboard_address=":0", asynchronous=True ) as cluster, Client(cluster, asynchronous=True) as client: text = client._repr_html_() assert cluster.scheduler.address in text assert is_valid_xml(client._repr_html_()) @gen_cluster(client=True) async def test_forget_simple(c, s, a, b): x = c.submit(inc, 1, retries=2) y = c.submit(inc, 2) z = c.submit(add, x, y, workers=[a.ip], allow_other_workers=True) await wait([x, y, z]) assert not s.tasks[x.key].waiting_on assert not s.tasks[y.key].waiting_on assert set(s.tasks) == {x.key, y.key, z.key} s.client_releases_keys(keys=[x.key], client=c.id) assert x.key in s.tasks s.client_releases_keys(keys=[z.key], client=c.id) assert x.key not in s.tasks assert z.key not in s.tasks assert not s.tasks[y.key].dependents s.client_releases_keys(keys=[y.key], client=c.id) assert not s.tasks @gen_cluster(client=True) async def test_forget_complex(e, s, A, B): a, b, c, d = await e.scatter(list(range(4))) ab = e.submit(add, a, b) cd = e.submit(add, c, d) ac = e.submit(add, a, c) acab = e.submit(add, ac, ab) await wait([a, b, c, d, ab, ac, cd, acab]) assert set(s.tasks) == {f.key for f in [ab, ac, cd, acab, a, b, c, d]} s.client_releases_keys(keys=[ab.key], client=e.id) assert set(s.tasks) == {f.key for f in [ab, ac, cd, acab, a, b, c, d]} s.client_releases_keys(keys=[b.key], client=e.id) assert set(s.tasks) == {f.key for f in [ac, cd, acab, a, c, d]} s.client_releases_keys(keys=[acab.key], client=e.id) assert set(s.tasks) == {f.key for f in [ac, cd, a, c, d]} assert b.key not in s.tasks while b.key in A.data or b.key in B.data: await asyncio.sleep(0.01) s.client_releases_keys(keys=[ac.key], client=e.id) assert set(s.tasks) == {f.key for f in [cd, a, c, d]} @gen_cluster(client=True) async def test_forget_in_flight(e, s, A, B): delayed2 = partial(delayed, pure=True) a, b, c, d = (delayed2(slowinc)(i) for i in range(4)) ab = delayed2(slowadd)(a, b, dask_key_name="ab") cd = delayed2(slowadd)(c, d, dask_key_name="cd") ac = delayed2(slowadd)(a, c, dask_key_name="ac") acab = delayed2(slowadd)(ac, ab, dask_key_name="acab") x, y = e.compute([ac, acab]) s.validate_state() for _ in range(5): await asyncio.sleep(0.01) s.validate_state() s.client_releases_keys(keys=[y.key], client=e.id) s.validate_state() for k in [acab.key, ab.key, b.key]: assert k not in s.tasks @gen_cluster(client=True) async def test_forget_errors(c, s, a, b): x = c.submit(div, 1, 0) y = c.submit(inc, x) z = c.submit(inc, y) await wait([y]) assert s.tasks[x.key].exception assert s.tasks[x.key].exception_blame assert s.tasks[y.key].exception_blame assert s.tasks[z.key].exception_blame s.client_releases_keys(keys=[z.key], client=c.id) assert s.tasks[x.key].exception assert s.tasks[x.key].exception_blame assert s.tasks[y.key].exception_blame assert z.key not in s.tasks s.client_releases_keys(keys=[x.key], client=c.id) assert s.tasks[x.key].exception assert s.tasks[x.key].exception_blame assert s.tasks[y.key].exception_blame assert z.key not in s.tasks s.client_releases_keys(keys=[y.key], client=c.id) assert x.key not in s.tasks assert y.key not in s.tasks assert z.key not in s.tasks def test_repr_sync(c): s = str(c) r = repr(c) assert c.scheduler.address in s assert c.scheduler.address in r assert str(2) in s # nworkers assert "cores" in s or "threads" in s @gen_cluster() async def test_multi_client(s, a, b): async with Client(s.address, asynchronous=True) as f: async with Client(s.address, asynchronous=True) as c: assert set(s.client_comms) == {c.id, f.id} x = c.submit(inc, 1) y = f.submit(inc, 2) y2 = c.submit(inc, 2) assert y.key == y2.key await wait([x, y]) assert {ts.key for ts in s.clients[c.id].wants_what} == {x.key, y.key} assert {ts.key for ts in s.clients[f.id].wants_what} == {y.key} while c.id in s.clients: await asyncio.sleep(0.01) assert c.id not in s.clients assert c.id not in s.tasks[y.key].who_wants assert x.key not in s.tasks while s.tasks: await asyncio.sleep(0.01) @contextmanager def _pristine_loop(): IOLoop.clear_instance() IOLoop.clear_current() loop = IOLoop() loop.make_current() assert IOLoop.current() is loop try: yield loop finally: try: loop.close(all_fds=True) except (KeyError, ValueError): pass IOLoop.clear_instance() IOLoop.clear_current() def long_running_client_connection(address): with _pristine_loop(): c = Client(address) x = c.submit(lambda x: x + 1, 10) x.result() sleep(100) @gen_cluster() async def test_cleanup_after_broken_client_connection(s, a, b): proc = get_mp_context().Process( target=long_running_client_connection, args=(s.address,) ) proc.daemon = True proc.start() while not s.tasks: await asyncio.sleep(0.01) proc.terminate() while s.tasks: await asyncio.sleep(0.01) @gen_cluster() async def test_multi_garbage_collection(s, a, b): async with Client(s.address, asynchronous=True) as c, Client( s.address, asynchronous=True ) as f: x = c.submit(inc, 1) y = f.submit(inc, 2) y2 = c.submit(inc, 2) assert y.key == y2.key await wait([x, y]) x.__del__() while x.key in a.data or x.key in b.data: await asyncio.sleep(0.01) assert {ts.key for ts in s.clients[c.id].wants_what} == {y.key} assert {ts.key for ts in s.clients[f.id].wants_what} == {y.key} y.__del__() while x.key in {ts.key for ts in s.clients[f.id].wants_what}: await asyncio.sleep(0.01) await asyncio.sleep(0.1) assert y.key in a.data or y.key in b.data assert {ts.key for ts in s.clients[c.id].wants_what} == {y.key} assert not s.clients[f.id].wants_what y2.__del__() while y.key in a.data or y.key in b.data: await asyncio.sleep(0.01) assert not s.tasks @gen_cluster(client=True, config=NO_AMM) async def test__broadcast(c, s, a, b): x, y = await c.scatter([1, 2], broadcast=True) assert a.data == b.data == {x.key: 1, y.key: 2} @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4, config=NO_AMM) async def test__broadcast_integer(c, s, *workers): x, y = await c.scatter([1, 2], broadcast=2) assert len(s.tasks[x.key].who_has) == 2 assert len(s.tasks[y.key].who_has) == 2 @gen_cluster(client=True, config=NO_AMM) async def test__broadcast_dict(c, s, a, b): d = await c.scatter({"x": 1}, broadcast=True) assert a.data == b.data == {"x": 1} @gen_cluster(client=True) async def test_proxy(c, s, a, b): msg = await c.scheduler.proxy(msg={"op": "identity"}, worker=a.address) assert msg["id"] == a.identity()["id"] @gen_cluster(client=True) async def test_cancel(c, s, a, b): x = c.submit(slowinc, 1) y = c.submit(slowinc, x) while y.key not in s.tasks: await asyncio.sleep(0.01) await c.cancel([x]) assert x.cancelled() assert "cancel" in str(x) s.validate_state() while not y.cancelled(): await asyncio.sleep(0.01) assert not s.tasks s.validate_state() @gen_cluster(client=True) async def test_cancel_tuple_key(c, s, a, b): x = c.submit(inc, 1, key=("x", 0, 1)) await x await c.cancel(x) with pytest.raises(CancelledError): await x @gen_cluster() async def test_cancel_multi_client(s, a, b): async with Client(s.address, asynchronous=True, name="c") as c: async with Client(s.address, asynchronous=True, name="f") as f: x = c.submit(slowinc, 1) y = f.submit(slowinc, 1) assert x.key == y.key # Ensure both clients are known to the scheduler. await y await x await c.cancel([x]) # Give the scheduler time to pass messages await asyncio.sleep(0.1) assert x.cancelled() assert not y.cancelled() out = await y assert out == 2 with pytest.raises(CancelledError): await x @gen_cluster(nthreads=[("", 1)], client=True) async def test_cancel_before_known_to_scheduler(c, s, a): with captured_logger("distributed.scheduler") as slogs: f = c.submit(inc, 1) await c.cancel([f]) with pytest.raises(CancelledError): await f assert "Scheduler cancels key" in slogs.getvalue() @gen_cluster(client=True) async def test_cancel_collection(c, s, a, b): L = c.map(double, [[1], [2], [3]]) x = db.Bag({("b", i): f for i, f in enumerate(L)}, "b", 3) await c.cancel(x) await c.cancel([x]) assert all(f.cancelled() for f in L) while s.tasks: await asyncio.sleep(0.01) def test_cancel_sync(c): x = c.submit(slowinc, 1, key="x") y = c.submit(slowinc, x, key="y") z = c.submit(slowinc, y, key="z") c.cancel([y]) start = time() while not z.cancelled(): sleep(0.01) assert time() < start + 30 assert x.result() == 2 z.cancel() assert z.cancelled() @gen_cluster(client=True) async def test_future_type(c, s, a, b): x = c.submit(inc, 1) await wait([x]) assert x.type == int assert "int" in str(x) @gen_cluster(client=True) async def test_traceback_clean(c, s, a, b): x = c.submit(div, 1, 0) try: await x except Exception as e: f = e exc_type, exc_value, tb = sys.exc_info() while tb: assert "scheduler" not in tb.tb_frame.f_code.co_filename assert "worker" not in tb.tb_frame.f_code.co_filename tb = tb.tb_next @gen_cluster(client=True) async def test_map_differnet_lengths(c, s, a, b): assert len(c.map(add, [1, 2], [1, 2, 3])) == 2 def test_Future_exception_sync_2(loop, capsys): with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: assert dask.base.get_scheduler() == c.get out, err = capsys.readouterr() assert len(out.strip().split("\n")) == 1 assert dask.base.get_scheduler() != c.get @gen_cluster(timeout=60, client=True) async def test_async_persist(c, s, a, b): from dask.delayed import Delayed, delayed x = delayed(1) y = delayed(inc)(x) z = delayed(dec)(x) w = delayed(add)(y, z) yy, ww = c.persist([y, w]) assert type(yy) == type(y) assert type(ww) == type(w) assert len(yy.dask) == 1 assert len(ww.dask) == 1 assert len(w.dask) > 1 assert y.__dask_keys__() == yy.__dask_keys__() assert w.__dask_keys__() == ww.__dask_keys__() while y.key not in s.tasks and w.key not in s.tasks: await asyncio.sleep(0.01) assert {cs.client_key for cs in s.tasks[y.key].who_wants} == {c.id} assert {cs.client_key for cs in s.tasks[w.key].who_wants} == {c.id} yyf, wwf = c.compute([yy, ww]) yyy, www = await c.gather([yyf, wwf]) assert yyy == inc(1) assert www == add(inc(1), dec(1)) assert isinstance(c.persist(y), Delayed) assert isinstance(c.persist([y]), (list, tuple)) @gen_cluster(client=True) async def test__persist(c, s, a, b): pytest.importorskip("dask.array") import dask.array as da x = da.ones((10, 10), chunks=(5, 10)) y = 2 * (x + 1) assert len(y.dask) == 6 yy = c.persist(y) assert len(y.dask) == 6 assert len(yy.dask) == 2 assert all(isinstance(v, Future) for v in yy.dask.values()) assert yy.__dask_keys__() == y.__dask_keys__() g, h = c.compute([y, yy]) gg, hh = await c.gather([g, h]) assert (gg == hh).all() def test_persist(c): pytest.importorskip("dask.array") import dask.array as da x = da.ones((10, 10), chunks=(5, 10)) y = 2 * (x + 1) assert len(y.dask) == 6 yy = c.persist(y) assert len(y.dask) == 6 assert len(yy.dask) == 2 assert all(isinstance(v, Future) for v in yy.dask.values()) assert yy.__dask_keys__() == y.__dask_keys__() zz = yy.compute() z = y.compute() assert (zz == z).all() @gen_cluster(timeout=60, client=True) async def test_long_traceback(c, s, a, b): from distributed.protocol.pickle import dumps def deep(n): if n == 0: 1 / 0 else: return deep(n - 1) x = c.submit(deep, 200) await wait([x]) assert len(dumps(c.futures[x.key].traceback)) < 10000 assert isinstance(c.futures[x.key].exception, ZeroDivisionError) @gen_cluster(client=True) async def test_wait_on_collections(c, s, a, b): L = c.map(double, [[1], [2], [3]]) x = db.Bag({("b", i): f for i, f in enumerate(L)}, "b", 3) await wait(x) assert all(f.key in a.data or f.key in b.data for f in L) @gen_cluster(client=True) async def test_futures_of_get(c, s, a, b): x, y, z = c.map(inc, [1, 2, 3]) assert set(futures_of(0)) == set() assert set(futures_of(x)) == {x} assert set(futures_of([x, y, z])) == {x, y, z} assert set(futures_of([x, [y], [[z]]])) == {x, y, z} assert set(futures_of({"x": x, "y": [y]})) == {x, y} b = db.Bag({("b", i): f for i, f in enumerate([x, y, z])}, "b", 3) assert set(futures_of(b)) == {x, y, z} sg = SubgraphCallable( {"x": x, "y": y, "z": z, "out": (add, (add, (add, x, y), z), "in")}, "out", ("in",), ) assert set(futures_of(sg)) == {x, y, z} def test_futures_of_class(): da = pytest.importorskip("dask.array") assert futures_of([da.Array]) == [] @gen_cluster(client=True) async def test_futures_of_cancelled_raises(c, s, a, b): x = c.submit(inc, 1) await c.cancel([x]) with pytest.raises(CancelledError): await x with pytest.raises(CancelledError): await c.get({"x": (inc, x), "y": (inc, 2)}, ["x", "y"], sync=False) with pytest.raises(CancelledError): c.submit(inc, x) with pytest.raises(CancelledError): c.submit(add, 1, y=x) with pytest.raises(CancelledError): c.map(add, [1], y=x) assert "y" not in s.tasks @pytest.mark.skip @gen_cluster(nthreads=[("127.0.0.1", 1)], client=True) async def test_dont_delete_recomputed_results(c, s, w): x = c.submit(inc, 1) # compute first time await wait([x]) x.__del__() # trigger garbage collection await asyncio.sleep(0) xx = c.submit(inc, 1) # compute second time start = time() while xx.key not in w.data: # data shows up await asyncio.sleep(0.01) assert time() < start + 1 while time() < start + (s.delete_interval + 100) / 1000: # and stays assert xx.key in w.data await asyncio.sleep(0.01) @gen_cluster(nthreads=[], client=True) async def test_fatally_serialized_input(c, s): o = FatallySerializedObject() future = c.submit(inc, o) while not s.tasks: await asyncio.sleep(0.01) @pytest.mark.skip(reason="Use fast random selection now") @gen_cluster(client=True) async def test_balance_tasks_by_stacks(c, s, a, b): x = c.submit(inc, 1) await wait(x) y = c.submit(inc, 2) await wait(y) assert len(a.data) == len(b.data) == 1 @gen_cluster(client=True) async def test_run(c, s, a, b): results = await c.run(inc, 1) assert results == {a.address: 2, b.address: 2} results = await c.run(inc, 1, workers=[a.address]) assert results == {a.address: 2} results = await c.run(inc, 1, workers=[]) assert results == {} @gen_cluster(client=True) async def test_run_handles_picklable_data(c, s, a, b): futures = c.map(inc, range(10)) await wait(futures) def func(): return {}, set(), [], (), 1, "hello", b"100" results = await c.run_on_scheduler(func) assert results == func() results = await c.run(func) assert results == {w.address: func() for w in [a, b]} def test_run_sync(c, s, a, b): def func(x, y=10): return x + y result = c.run(func, 1, y=2) assert result == {a["address"]: 3, b["address"]: 3} result = c.run(func, 1, y=2, workers=[a["address"]]) assert result == {a["address"]: 3} @gen_cluster(client=True) async def test_run_coroutine(c, s, a, b): results = await c.run(asyncinc, 1, delay=0.05) assert results == {a.address: 2, b.address: 2} results = await c.run(asyncinc, 1, delay=0.05, workers=[a.address]) assert results == {a.address: 2} results = await c.run(asyncinc, 1, workers=[]) assert results == {} with pytest.raises(RuntimeError, match="hello"): await c.run(throws, 1) results = await c.run(asyncinc, 2, delay=0.01) assert results == {a.address: 3, b.address: 3} def test_run_coroutine_sync(c, s, a, b): result = c.run(asyncinc, 2, delay=0.01) assert result == {a["address"]: 3, b["address"]: 3} result = c.run(asyncinc, 2, workers=[a["address"]]) assert result == {a["address"]: 3} t1 = time() result = c.run(asyncinc, 2, delay=10, wait=False) t2 = time() assert result is None assert t2 - t1 <= 1.0 @gen_cluster(client=True) async def test_run_exception(c, s, a, b): class MyError(Exception): pass def raise_exception(dask_worker, addr): if addr == dask_worker.address: raise MyError("informative message") return 123 with pytest.raises(MyError, match="informative message"): await c.run(raise_exception, addr=a.address) with pytest.raises(MyError, match="informative message"): await c.run(raise_exception, addr=a.address, on_error="raise") with pytest.raises(ValueError, match="on_error must be"): await c.run(raise_exception, addr=a.address, on_error="invalid") out = await c.run(raise_exception, addr=a.address, on_error="return") assert isinstance(out[a.address], MyError) assert out[b.address] == 123 out = await c.run(raise_exception, addr=a.address, on_error="ignore") assert out == {b.address: 123} @gen_cluster(client=True, config={"distributed.comm.timeouts.connect": "200ms"}) async def test_run_rpc_error(c, s, a, b): a.stop() with pytest.raises(OSError, match="Timed out trying to connect"): await c.run(inc, 1) with pytest.raises(OSError, match="Timed out trying to connect"): await c.run(inc, 1, on_error="raise") out = await c.run(inc, 1, on_error="return") assert isinstance(out[a.address], OSError) assert out[b.address] == 2 out = await c.run(inc, 1, on_error="ignore") assert out == {b.address: 2} def test_diagnostic_ui(loop): with cluster() as (s, [a, b]): a_addr = a["address"] b_addr = b["address"] with Client(s["address"], loop=loop) as c: d = c.nthreads() assert d == {a_addr: 1, b_addr: 1} d = c.nthreads([a_addr]) assert d == {a_addr: 1} d = c.nthreads(a_addr) assert d == {a_addr: 1} d = c.nthreads(a["address"]) assert d == {a_addr: 1} x = c.submit(inc, 1) y = c.submit(inc, 2) z = c.submit(inc, 3) wait([x, y, z]) d = c.who_has() assert set(d) == {x.key, y.key, z.key} assert all(w in [a_addr, b_addr] for v in d.values() for w in v) assert all(d.values()) d = c.who_has([x, y]) assert set(d) == {x.key, y.key} d = c.who_has(x) assert set(d) == {x.key} d = c.has_what() assert set(d) == {a_addr, b_addr} assert all(k in [x.key, y.key, z.key] for v in d.values() for k in v) d = c.has_what([a_addr]) assert set(d) == {a_addr} d = c.has_what(a_addr) assert set(d) == {a_addr} def test_diagnostic_nbytes_sync(c): incs = c.map(inc, [1, 2, 3]) doubles = c.map(double, [1, 2, 3]) wait(incs + doubles) assert c.nbytes(summary=False) == {k.key: sizeof(1) for k in incs + doubles} assert c.nbytes(summary=True) == {"inc": sizeof(1) * 3, "double": sizeof(1) * 3} @gen_cluster(client=True) async def test_diagnostic_nbytes(c, s, a, b): incs = c.map(inc, [1, 2, 3]) doubles = c.map(double, [1, 2, 3]) await wait(incs + doubles) assert s.get_nbytes(summary=False) == {k.key: sizeof(1) for k in incs + doubles} assert s.get_nbytes(summary=True) == {"inc": sizeof(1) * 3, "double": sizeof(1) * 3} @gen_cluster(client=True, nthreads=[]) async def test_worker_aliases(c, s): a = Worker(s.address, name="alice") b = Worker(s.address, name="bob") w = Worker(s.address, name=3) await asyncio.gather(a, b, w) L = c.map(inc, range(10), workers="alice") future = await c.scatter(123, workers=3) await wait(L) assert len(a.data) == 10 assert len(b.data) == 0 assert dict(w.data) == {future.key: 123} for i, alias in enumerate([3, [3], "alice"]): result = await c.submit(lambda x: x + 1, i, workers=alias) assert result == i + 1 await asyncio.gather(a.close(), b.close(), w.close()) def test_persist_get_sync(c): x, y = delayed(1), delayed(2) xx = delayed(add)(x, x) yy = delayed(add)(y, y) xxyy = delayed(add)(xx, yy) xxyy2 = c.persist(xxyy) xxyy3 = delayed(add)(xxyy2, 10) assert xxyy3.compute() == ((1 + 1) + (2 + 2)) + 10 @gen_cluster(client=True) async def test_persist_get(c, s, a, b): x, y = delayed(1), delayed(2) xx = delayed(add)(x, x) yy = delayed(add)(y, y) xxyy = delayed(add)(xx, yy) xxyy2 = c.persist(xxyy) xxyy3 = delayed(add)(xxyy2, 10) await asyncio.sleep(0.5) result = await c.gather(c.get(xxyy3.dask, xxyy3.__dask_keys__(), sync=False)) assert result[0] == ((1 + 1) + (2 + 2)) + 10 result = await c.compute(xxyy3) assert result == ((1 + 1) + (2 + 2)) + 10 result = await c.compute(xxyy3) assert result == ((1 + 1) + (2 + 2)) + 10 result = await c.compute(xxyy3) assert result == ((1 + 1) + (2 + 2)) + 10 @pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows") def test_client_num_fds(loop): with cluster() as (s, [a, b]): proc = psutil.Process() with Client(s["address"], loop=loop) as c: # first client to start loop before = proc.num_fds() # measure for _ in range(4): with Client(s["address"], loop=loop): # start more clients pass start = time() while proc.num_fds() > before: sleep(0.01) assert time() < start + 10, (before, proc.num_fds()) @gen_cluster() async def test_startup_close_startup(s, a, b): async with Client(s.address, asynchronous=True): pass async with Client(s.address, asynchronous=True): pass @pytest.mark.filterwarnings("ignore:There is no current event loop:DeprecationWarning") @pytest.mark.filterwarnings("ignore:make_current is deprecated:DeprecationWarning") def test_startup_close_startup_sync(loop): with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: sleep(0.1) with Client(s["address"], loop=None) as c: pass with Client(s["address"], loop=None) as c: pass sleep(0.1) with Client(s["address"], loop=None) as c: pass @gen_cluster(client=True) async def test_badly_serialized_exceptions(c, s, a, b): def f(): class BadlySerializedException(Exception): def __reduce__(self): raise TypeError() raise BadlySerializedException("hello world") x = c.submit(f) with pytest.raises(Exception, match="hello world"): await x # Set rebalance() to work predictably on small amounts of managed memory. By default, it # uses optimistic memory, which would only be possible to test by allocating very large # amounts of managed memory, so that they would hide variations in unmanaged memory. REBALANCE_MANAGED_CONFIG = merge( NO_AMM, { "distributed.worker.memory.rebalance.measure": "managed", "distributed.worker.memory.rebalance.sender-min": 0, "distributed.worker.memory.rebalance.sender-recipient-gap": 0, }, ) @gen_cluster(client=True, config=REBALANCE_MANAGED_CONFIG) async def test_rebalance(c, s, a, b): """Test Client.rebalance(). These are just to test the Client wrapper around Scheduler.rebalance(); for more thorough tests on the latter see test_scheduler.py. """ futures = await c.scatter(range(100), workers=[a.address]) assert len(a.data) == 100 assert len(b.data) == 0 await c.rebalance() assert len(a.data) == 50 assert len(b.data) == 50 @gen_cluster(nthreads=[("", 1)] * 3, client=True, config=REBALANCE_MANAGED_CONFIG) async def test_rebalance_workers_and_keys(client, s, a, b, c): """Test Client.rebalance(). These are just to test the Client wrapper around Scheduler.rebalance(); for more thorough tests on the latter see test_scheduler.py. """ futures = await client.scatter(range(100), workers=[a.address]) assert (len(a.data), len(b.data), len(c.data)) == (100, 0, 0) # Passing empty iterables is not the same as omitting the arguments await client.rebalance([]) await client.rebalance(workers=[]) assert (len(a.data), len(b.data), len(c.data)) == (100, 0, 0) # Limit rebalancing to two arbitrary keys and two arbitrary workers. await client.rebalance([futures[3], futures[7]], [a.address, b.address]) assert (len(a.data), len(b.data), len(c.data)) == (98, 2, 0) with pytest.raises(KeyError): await client.rebalance(workers=["notexist"]) def test_rebalance_sync(loop): with dask.config.set(REBALANCE_MANAGED_CONFIG): with Client( n_workers=2, processes=False, dashboard_address=":0", loop=loop ) as c: s = c.cluster.scheduler a = c.cluster.workers[0] b = c.cluster.workers[1] futures = c.scatter(range(100), workers=[a.address]) assert len(a.data) == 100 assert len(b.data) == 0 c.rebalance() assert len(a.data) == 50 assert len(b.data) == 50 @gen_cluster(client=True, config=NO_AMM) async def test_rebalance_unprepared(c, s, a, b): """Client.rebalance() internally waits for unfinished futures""" futures = c.map(slowinc, range(10), delay=0.05, workers=a.address) # Let the futures reach the scheduler await asyncio.sleep(0.1) # We didn't wait enough for futures to complete. However, Client.rebalance() will # block until all futures are completed before invoking Scheduler.rebalance(). await c.rebalance(futures) s.validate_state() @gen_cluster(client=True, config=NO_AMM) async def test_rebalance_raises_on_explicit_missing_data(c, s, a, b): """rebalance() raises KeyError if explicitly listed futures disappear""" f = Future("x", client=c, state="memory") with pytest.raises(KeyError, match="Could not rebalance keys:"): await c.rebalance(futures=[f]) @gen_cluster(client=True) async def test_receive_lost_key(c, s, a, b): x = c.submit(inc, 1, workers=[a.address]) await x await a.close() while x.status == "finished": await asyncio.sleep(0.01) @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_unrunnable_task_runs(c, s, a, b): x = c.submit(inc, 1, workers=[a.ip]) await x await a.close() while x.status == "finished": await asyncio.sleep(0.01) assert s.tasks[x.key] in s.unrunnable assert s.get_task_status(keys=[x.key]) == {x.key: "no-worker"} async with Worker(s.address): while x.status != "finished": await asyncio.sleep(0.01) assert s.tasks[x.key] not in s.unrunnable result = await x assert result == 2 @gen_cluster(client=True, nthreads=[]) async def test_add_worker_after_tasks(c, s): futures = c.map(inc, range(10)) async with Nanny(s.address, nthreads=2): await c.gather(futures) @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True, config=NO_AMM) async def test_workers_register_indirect_data(c, s, a, b): [x] = await c.scatter([1], workers=a.address) y = c.submit(inc, x, workers=b.ip) await y assert b.data[x.key] == 1 assert s.tasks[x.key].who_has == {s.workers[a.address], s.workers[b.address]} assert s.workers[b.address].has_what == {s.tasks[x.key], s.tasks[y.key]} s.validate_state() @gen_cluster(client=True) async def test_submit_on_cancelled_future(c, s, a, b): x = c.submit(inc, 1) await x await c.cancel(x) with pytest.raises(CancelledError): c.submit(inc, x) @gen_cluster( client=True, nthreads=[("127.0.0.1", 1)] * 10, config=NO_AMM, ) async def test_replicate(c, s, *workers): [a, b] = await c.scatter([1, 2]) await s.replicate(keys=[a.key, b.key], n=5) s.validate_state() assert len(s.tasks[a.key].who_has) == 5 assert len(s.tasks[b.key].who_has) == 5 assert sum(a.key in w.data for w in workers) == 5 assert sum(b.key in w.data for w in workers) == 5 @gen_cluster(client=True, config=NO_AMM) async def test_replicate_tuple_keys(c, s, a, b): x = delayed(inc)(1, dask_key_name=("x", 1)) f = c.persist(x) await c.replicate(f, n=5) s.validate_state() assert a.data and b.data await c.rebalance(f) s.validate_state() @gen_cluster( client=True, nthreads=[("127.0.0.1", 1)] * 10, config=NO_AMM, ) async def test_replicate_workers(c, s, *workers): [a, b] = await c.scatter([1, 2], workers=[workers[0].address]) await s.replicate( keys=[a.key, b.key], n=5, workers=[w.address for w in workers[:5]] ) assert len(s.tasks[a.key].who_has) == 5 assert len(s.tasks[b.key].who_has) == 5 assert sum(a.key in w.data for w in workers[:5]) == 5 assert sum(b.key in w.data for w in workers[:5]) == 5 assert sum(a.key in w.data for w in workers[5:]) == 0 assert sum(b.key in w.data for w in workers[5:]) == 0 await s.replicate(keys=[a.key, b.key], n=1) assert len(s.tasks[a.key].who_has) == 1 assert len(s.tasks[b.key].who_has) == 1 assert sum(a.key in w.data for w in workers) == 1 assert sum(b.key in w.data for w in workers) == 1 s.validate_state() await s.replicate(keys=[a.key, b.key], n=None) # all assert len(s.tasks[a.key].who_has) == 10 assert len(s.tasks[b.key].who_has) == 10 s.validate_state() await s.replicate( keys=[a.key, b.key], n=1, workers=[w.address for w in workers[:5]] ) assert sum(a.key in w.data for w in workers[:5]) == 1 assert sum(b.key in w.data for w in workers[:5]) == 1 assert sum(a.key in w.data for w in workers[5:]) == 5 assert sum(b.key in w.data for w in workers[5:]) == 5 s.validate_state() class CountSerialization: def __init__(self): self.n = 0 def __setstate__(self, n): self.n = n + 1 def __getstate__(self): return self.n @gen_cluster( client=True, nthreads=[("127.0.0.1", 1)] * 10, config=NO_AMM, ) async def test_replicate_tree_branching(c, s, *workers): obj = CountSerialization() [future] = await c.scatter([obj]) await s.replicate(keys=[future.key], n=10) max_count = max(w.data[future.key].n for w in workers) assert max_count > 1 @gen_cluster( client=True, nthreads=[("127.0.0.1", 1)] * 10, config=NO_AMM, ) async def test_client_replicate(c, s, *workers): x = c.submit(inc, 1) y = c.submit(inc, 2) await c.replicate([x, y], n=5) assert len(s.tasks[x.key].who_has) == 5 assert len(s.tasks[y.key].who_has) == 5 await c.replicate([x, y], n=3) assert len(s.tasks[x.key].who_has) == 3 assert len(s.tasks[y.key].who_has) == 3 await c.replicate([x, y]) s.validate_state() assert len(s.tasks[x.key].who_has) == 10 assert len(s.tasks[y.key].who_has) == 10 @pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost") @gen_cluster( client=True, nthreads=[("127.0.0.1", 1), ("127.0.0.2", 1), ("127.0.0.2", 1)], config=NO_AMM, ) async def test_client_replicate_host(client, s, a, b, c): aws = s.workers[a.address] bws = s.workers[b.address] cws = s.workers[c.address] x = client.submit(inc, 1, workers="127.0.0.2") await wait([x]) assert s.tasks[x.key].who_has == {bws} or s.tasks[x.key].who_has == {cws} await client.replicate([x], workers=["127.0.0.2"]) assert s.tasks[x.key].who_has == {bws, cws} await client.replicate([x], workers=["127.0.0.1"]) assert s.tasks[x.key].who_has == {aws, bws, cws} def test_client_replicate_sync(client_no_amm): c = client_no_amm x = c.submit(inc, 1) y = c.submit(inc, 2) c.replicate([x, y], n=2) who_has = c.who_has() assert len(who_has[x.key]) == len(who_has[y.key]) == 2 with pytest.raises(ValueError): c.replicate([x], n=0) assert y.result() == 3 @pytest.mark.skipif(WINDOWS, reason="Windows timer too coarse-grained") @gen_cluster(client=True, nthreads=[("127.0.0.1", 4)] * 1) async def test_task_load_adapts_quickly(c, s, a): future = c.submit(slowinc, 1, delay=0.2) # slow await wait(future) assert 0.15 < s.task_prefixes["slowinc"].duration_average < 0.4 futures = c.map(slowinc, range(10), delay=0) # very fast await wait(futures) assert 0 < s.task_prefixes["slowinc"].duration_average < 0.1 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 2) async def test_even_load_after_fast_functions(c, s, a, b): x = c.submit(inc, 1, workers=a.address) # very fast y = c.submit(inc, 2, workers=b.address) # very fast await wait([x, y]) futures = c.map(inc, range(2, 11)) await wait(futures) assert any(f.key in a.data for f in futures) assert any(f.key in b.data for f in futures) # assert abs(len(a.data) - len(b.data)) <= 3 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 2) async def test_even_load_on_startup(c, s, a, b): x, y = c.map(inc, [1, 2]) await wait([x, y]) assert len(a.data) == len(b.data) == 1 @pytest.mark.skip @gen_cluster(client=True, nthreads=[("127.0.0.1", 2)] * 2) async def test_contiguous_load(c, s, a, b): w, x, y, z = c.map(inc, [1, 2, 3, 4]) await wait([w, x, y, z]) groups = [set(a.data), set(b.data)] assert {w.key, x.key} in groups assert {y.key, z.key} in groups @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_balanced_with_submit(c, s, *workers): L = [c.submit(slowinc, i) for i in range(4)] await wait(L) for w in workers: assert len(w.data) == 1 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4, config=NO_AMM) async def test_balanced_with_submit_and_resident_data(c, s, *workers): [x] = await c.scatter([10], broadcast=True) L = [c.submit(slowinc, x, pure=False) for i in range(4)] await wait(L) for w in workers: assert len(w.data) == 2 @gen_cluster(client=True, nthreads=[("127.0.0.1", 20)] * 2) async def test_scheduler_saturates_cores(c, s, a, b): for delay in [0, 0.01, 0.1]: futures = c.map(slowinc, range(100), delay=delay) futures = c.map(slowinc, futures, delay=delay / 10) while not s.tasks: if s.tasks: assert all( len(p) >= 20 for w in s.workers.values() for p in w.processing.values() ) await asyncio.sleep(0.01) @gen_cluster(client=True, nthreads=[("127.0.0.1", 20)] * 2) async def test_scheduler_saturates_cores_random(c, s, a, b): futures = c.map(randominc, range(100), scale=0.1) while not s.tasks: if s.tasks: assert all( len(p) >= 20 for w in s.workers.values() for p in w.processing.values() ) await asyncio.sleep(0.01) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_cancel_clears_processing(c, s, *workers): da = pytest.importorskip("dask.array") x = c.submit(slowinc, 1, delay=0.2) while not s.tasks: await asyncio.sleep(0.01) await c.cancel(x) while any(v for w in s.workers.values() for v in w.processing): await asyncio.sleep(0.01) s.validate_state() def test_default_get(loop_in_thread): loop = loop_in_thread with cluster() as (s, [a, b]): pre_get = dask.base.get_scheduler() pytest.raises(KeyError, dask.config.get, "shuffle") with Client(s["address"], set_as_default=True, loop=loop) as c: assert dask.base.get_scheduler() == c.get assert dask.config.get("shuffle") == "tasks" assert dask.base.get_scheduler() == pre_get pytest.raises(KeyError, dask.config.get, "shuffle") c = Client(s["address"], set_as_default=False, loop=loop) assert dask.base.get_scheduler() == pre_get pytest.raises(KeyError, dask.config.get, "shuffle") c.close() c = Client(s["address"], set_as_default=True, loop=loop) assert dask.config.get("shuffle") == "tasks" assert dask.base.get_scheduler() == c.get c.close() assert dask.base.get_scheduler() == pre_get pytest.raises(KeyError, dask.config.get, "shuffle") with Client(s["address"], loop=loop) as c: assert dask.base.get_scheduler() == c.get with Client(s["address"], set_as_default=False, loop=loop) as c: assert dask.base.get_scheduler() != c.get assert dask.base.get_scheduler() != c.get with Client(s["address"], set_as_default=True, loop=loop) as c1: assert dask.base.get_scheduler() == c1.get with Client(s["address"], set_as_default=True, loop=loop) as c2: assert dask.base.get_scheduler() == c2.get assert dask.base.get_scheduler() == c1.get assert dask.base.get_scheduler() == pre_get @gen_cluster(client=True) async def test_ensure_default_client(c, s, a, b): assert c is default_client() async with Client(s.address, set_as_default=False, asynchronous=True) as c2: assert c is default_client() assert c2 is not default_client() ensure_default_client(c2) assert c is not default_client() assert c2 is default_client() @gen_cluster() async def test_set_as_default(s, a, b): with pytest.raises(ValueError): default_client() async with Client(s.address, set_as_default=False, asynchronous=True) as c1: with pytest.raises(ValueError): default_client() async with Client(s.address, set_as_default=True, asynchronous=True) as c2: assert default_client() is c2 async with Client(s.address, set_as_default=True, asynchronous=True) as c3: assert default_client() is c3 async with Client( s.address, set_as_default=False, asynchronous=True ) as c4: assert default_client() is c3 await c4.scheduler_comm.close() while c4.status != "running": await asyncio.sleep(0.01) assert default_client() is c3 with pytest.raises(ValueError): default_client() @gen_cluster(client=True) async def test_get_foo(c, s, a, b): futures = c.map(inc, range(10)) await wait(futures) x = await c.scheduler.nbytes(summary=False) assert x == s.get_nbytes(summary=False) x = await c.scheduler.nbytes(keys=[futures[0].key], summary=False) assert x == {futures[0].key: s.tasks[futures[0].key].nbytes} x = await c.scheduler.who_has() assert valmap(set, x) == { key: {ws.address for ws in ts.who_has} for key, ts in s.tasks.items() } x = await c.scheduler.who_has(keys=[futures[0].key]) assert valmap(set, x) == { futures[0].key: {ws.address for ws in s.tasks[futures[0].key].who_has} } def assert_dict_key_equal(expected, actual): assert set(expected.keys()) == set(actual.keys()) for k in actual.keys(): ev = expected[k] av = actual[k] assert list(ev) == list(av) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 3) async def test_get_foo_lost_keys(c, s, u, v, w): x = c.submit(inc, 1, workers=[u.address]) y = await c.scatter(3, workers=[v.address]) await wait([x, y]) ua, va, wa = u.address, v.address, w.address d = await c.scheduler.has_what() assert_dict_key_equal(d, {ua: [x.key], va: [y.key], wa: []}) d = await c.scheduler.has_what(workers=[ua, va]) assert_dict_key_equal(d, {ua: [x.key], va: [y.key]}) d = await c.scheduler.who_has() assert_dict_key_equal(d, {x.key: [ua], y.key: [va]}) d = await c.scheduler.who_has(keys=[x.key, y.key]) assert_dict_key_equal(d, {x.key: [ua], y.key: [va]}) await u.close() await v.close() d = await c.scheduler.has_what() assert_dict_key_equal(d, {wa: []}) d = await c.scheduler.has_what(workers=[ua, va]) assert_dict_key_equal(d, {ua: [], va: []}) # The scattered key cannot be recomputed so it is forgotten d = await c.scheduler.who_has() assert_dict_key_equal(d, {x.key: []}) # ... but when passed explicitly, it is included in the result d = await c.scheduler.who_has(keys=[x.key, y.key]) assert_dict_key_equal(d, {x.key: [], y.key: []}) @pytest.mark.slow @gen_cluster( client=True, Worker=Nanny, clean_kwargs={"threads": False, "processes": False} ) async def test_bad_tasks_fail(c, s, a, b): f = c.submit(sys.exit, 0) with captured_logger(logging.getLogger("distributed.scheduler")) as logger: with pytest.raises(KilledWorker) as info: await f text = logger.getvalue() assert f.key in text assert info.value.last_worker.nanny in {a.address, b.address} await asyncio.gather(a.close(), b.close()) def test_get_processing_sync(c, s, a, b): processing = c.processing() assert not any(v for v in processing.values()) futures = c.map( slowinc, range(10), delay=0.1, workers=[a["address"]], allow_other_workers=False ) sleep(0.2) aa = a["address"] bb = b["address"] processing = c.processing() assert set(c.processing(aa)) == {aa} assert set(c.processing([aa])) == {aa} c.cancel(futures) def test_close_idempotent(c): c.close() c.close() c.close() def test_get_returns_early(c): event = Event() def block(ev): ev.wait() with pytest.raises(RuntimeError): result = c.get({"x": (throws, 1), "y": (block, event)}, ["x", "y"]) # Futures should be released and forgotten wait_for(lambda: not c.futures, timeout=1) event.set() wait_for(lambda: not any(c.processing().values()), timeout=3) x = c.submit(inc, 1) x.result() with pytest.raises(RuntimeError): result = c.get({"x": (throws, 1), x.key: (inc, 1)}, ["x", x.key]) assert x.key in c.futures @pytest.mark.slow @gen_cluster(client=True) async def test_Client_clears_references_after_restart(c, s, a, b): x = c.submit(inc, 1) assert x.key in c.refcount assert x.key in c.futures with pytest.raises(TimeoutError): await c.restart(timeout=5) assert x.key not in c.refcount assert not c.futures key = x.key del x with profile.lock: await asyncio.sleep(0) assert key not in c.refcount def test_get_stops_work_after_error(c): with pytest.raises(RuntimeError): c.get({"x": (throws, 1), "y": (sleep, 1.5)}, ["x", "y"]) start = time() while any(c.processing().values()): sleep(0.01) assert time() < start + 0.5 def test_as_completed_list(c): seq = c.map(inc, range(5)) seq2 = list(as_completed(seq)) assert set(c.gather(seq2)) == {1, 2, 3, 4, 5} def test_as_completed_results(c): seq = c.map(inc, range(5)) seq2 = list(as_completed(seq, with_results=True)) assert set(pluck(1, seq2)) == {1, 2, 3, 4, 5} assert set(pluck(0, seq2)) == set(seq) @pytest.mark.parametrize("with_results", [True, False]) def test_as_completed_batches(c, with_results): n = 50 futures = c.map(slowinc, range(n), delay=0.01) out = [] for batch in as_completed(futures, with_results=with_results).batches(): assert isinstance(batch, (tuple, list)) sleep(0.05) out.extend(batch) assert len(out) == n if with_results: assert set(pluck(1, out)) == set(range(1, n + 1)) else: assert set(out) == set(futures) def test_as_completed_next_batch(c): futures = c.map(slowinc, range(2), delay=0.1) ac = as_completed(futures) assert not ac.is_empty() assert ac.next_batch(block=False) == [] assert set(ac.next_batch(block=True)).issubset(futures) while not ac.is_empty(): assert set(ac.next_batch(block=True)).issubset(futures) assert ac.is_empty() assert not ac.has_ready() @gen_cluster(nthreads=[]) async def test_status(s): async with Client(s.address, asynchronous=True) as c: assert c.status == "running" x = c.submit(inc, 1) assert c.status == "closed" @gen_cluster(client=True) async def test_persist_optimize_graph(c, s, a, b): i = 10 for method in [c.persist, c.compute]: b = db.range(i, npartitions=2) i += 1 b2 = b.map(inc) b3 = b2.map(inc) b4 = method(b3, optimize_graph=False) await wait(b4) assert set(map(stringify, b3.__dask_keys__())).issubset(s.tasks) b = db.range(i, npartitions=2) i += 1 b2 = b.map(inc) b3 = b2.map(inc) b4 = method(b3, optimize_graph=True) await wait(b4) assert not any(stringify(k) in s.tasks for k in b2.__dask_keys__()) @gen_cluster(client=True, nthreads=[]) async def test_scatter_raises_if_no_workers(c, s): with pytest.raises(TimeoutError): await c.scatter(1, timeout=0.5) @gen_test() async def test_reconnect(): port = open_port() stack = ExitStack() proc = popen(["dask-scheduler", "--no-dashboard", f"--port={port}"]) stack.enter_context(proc) async with Client(f"127.0.0.1:{port}", asynchronous=True) as c, Worker( f"127.0.0.1:{port}" ) as w: await c.wait_for_workers(1, timeout=10) x = c.submit(inc, 1) assert (await x) == 2 stack.close() start = time() while c.status != "connecting": assert time() < start + 10 await asyncio.sleep(0.01) assert x.status == "cancelled" with pytest.raises(CancelledError): await x with popen(["dask-scheduler", "--no-dashboard", f"--port={port}"]): start = time() while c.status != "running": await asyncio.sleep(0.1) assert time() < start + 10 await w.finished() async with Worker(f"127.0.0.1:{port}"): start = time() while len(await c.nthreads()) != 1: await asyncio.sleep(0.05) assert time() < start + 10 x = c.submit(inc, 1) assert (await x) == 2 start = time() while True: assert time() < start + 10 try: await x assert False except CommClosedError: continue except CancelledError: break await c._close(fast=True) class UnhandledExceptions(Exception): pass @contextmanager def catch_unhandled_exceptions() -> Generator[None, None, None]: loop = asyncio.get_running_loop() ctxs: list[dict[str, Any]] = [] old_handler = loop.get_exception_handler() @loop.set_exception_handler def _(loop: object, context: dict[str, Any]) -> None: ctxs.append(context) try: yield finally: loop.set_exception_handler(old_handler) if ctxs: msgs = [] for i, ctx in enumerate(ctxs, 1): msgs.append(ctx["message"]) print( f"------ Unhandled exception {i}/{len(ctxs)}: {ctx['message']!r} ------" ) print(ctx) if exc := ctx.get("exception"): traceback.print_exception(type(exc), exc, exc.__traceback__) raise UnhandledExceptions(", ".join(msgs)) @gen_cluster(client=True, nthreads=[], client_kwargs={"timeout": 0.5}) async def test_reconnect_timeout(c, s): with catch_unhandled_exceptions(), captured_logger( logging.getLogger("distributed.client") ) as logger: await s.close() while c.status != "closed": await asyncio.sleep(0.05) text = logger.getvalue() assert "Failed to reconnect" in text @pytest.mark.avoid_ci(reason="hangs on github actions ubuntu-latest CI") @pytest.mark.slow @pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows") @pytest.mark.parametrize("worker,count,repeat", [(Worker, 100, 5), (Nanny, 10, 20)]) def test_open_close_many_workers(loop, worker, count, repeat): proc = psutil.Process() with cluster(nworkers=0, active_rpc_timeout=2) as (s, _): gc.collect() before = proc.num_fds() done = Semaphore(0) running = weakref.WeakKeyDictionary() workers = set() status = True async def start_worker(sleep, duration, repeat=1): for _ in range(repeat): await asyncio.sleep(sleep) if not status: return w = worker(s["address"], loop=loop) running[w] = None await w workers.add(w) addr = w.worker_address running[w] = addr await asyncio.sleep(duration) await w.close() del w await asyncio.sleep(0) done.release() for _ in range(count): loop.add_callback( start_worker, random.random() / 5, random.random() / 5, repeat=repeat ) with Client(s["address"], loop=loop) as c: sleep(1) for _ in range(count): done.acquire(timeout=5) gc.collect() if not running: break start = time() while c.nthreads(): sleep(0.2) assert time() < start + 10 while len(workers) < count * repeat: sleep(0.2) status = False [c.sync(w.close) for w in list(workers)] for w in workers: assert w.status == Status.closed start = time() while proc.num_fds() > before: print("fds:", before, proc.num_fds()) sleep(0.1) if time() > start + 10: if worker == Worker: # this is an esoteric case print("File descriptors did not clean up") break else: raise ValueError("File descriptors did not clean up") @gen_cluster() async def test_idempotence(s, a, b): async with Client(s.address, asynchronous=True) as c, Client( s.address, asynchronous=True ) as f: # Submit x = c.submit(inc, 1) await x log = list(s.transition_log) len_single_submit = len(log) # see last assert y = f.submit(inc, 1) assert x.key == y.key await y await asyncio.sleep(0.1) log2 = list(s.transition_log) assert log == log2 # Error a = c.submit(div, 1, 0) await wait(a) assert a.status == "error" log = list(s.transition_log) b = f.submit(div, 1, 0) assert a.key == b.key await wait(b) await asyncio.sleep(0.1) log2 = list(s.transition_log) assert log == log2 s.transition_log.clear() # Simultaneous Submit d = c.submit(inc, 2) e = c.submit(inc, 2) await wait([d, e]) assert len(s.transition_log) == len_single_submit def test_scheduler_info(c): info = c.scheduler_info() assert isinstance(info, dict) assert len(info["workers"]) == 2 assert isinstance(info["started"], float) def test_write_scheduler_file(c, loop): info = c.scheduler_info() with tmpfile("json") as scheduler_file: c.write_scheduler_file(scheduler_file) with Client(scheduler_file=scheduler_file, loop=loop) as c2: info2 = c2.scheduler_info() assert c.scheduler.address == c2.scheduler.address # test that a ValueError is raised if the scheduler_file # attribute is already set with pytest.raises(ValueError): c.write_scheduler_file(scheduler_file) def test_get_versions_sync(c): requests = pytest.importorskip("requests") v = c.get_versions() assert v["scheduler"] is not None assert v["client"] is not None assert len(v["workers"]) == 2 for wv in v["workers"].values(): assert wv is not None c.get_versions(check=True) # smoke test for versions # that this does not raise v = c.get_versions(packages=["requests"]) assert v["client"]["packages"]["requests"] == requests.__version__ @gen_cluster(client=True) async def test_get_versions_async(c, s, a, b): v = await c.get_versions(check=True) assert v.keys() == {"scheduler", "client", "workers"} @gen_cluster(client=True, config={"distributed.comm.timeouts.connect": "200ms"}) async def test_get_versions_rpc_error(c, s, a, b): a.stop() v = await c.get_versions() assert v.keys() == {"scheduler", "client", "workers"} assert v["workers"].keys() == {b.address} def test_threaded_get_within_distributed(c): import dask.multiprocessing for get in [dask.local.get_sync, dask.multiprocessing.get, dask.threaded.get]: def f(get): return get({"x": (lambda: 1,)}, "x") future = c.submit(f, get) assert future.result() == 1 @gen_cluster(client=True) async def test_lose_scattered_data(c, s, a, b): [x] = await c.scatter([1], workers=a.address) await a.close() await asyncio.sleep(0.1) assert x.status == "cancelled" assert x.key not in s.tasks @gen_cluster( client=True, nthreads=[("127.0.0.1", 1)] * 3, config=NO_AMM, ) async def test_partially_lose_scattered_data(e, s, a, b, c): x = await e.scatter(1, workers=a.address) await e.replicate(x, n=2) await a.close() await asyncio.sleep(0.1) assert x.status == "finished" assert s.get_task_status(keys=[x.key]) == {x.key: "memory"} @gen_cluster(client=True, nthreads=[("", 1)]) async def test_scatter_compute_lose(c, s, a): x = (await c.scatter({"x": 1}, workers=[a.address]))["x"] async with BlockedGatherDep(s.address) as b: y = c.submit(inc, x, key="y", workers=[b.address]) await wait_for_state("x", "flight", b) await a.close() b.block_gather_dep.set() with pytest.raises(CancelledError): await wait(y) assert x.status == "cancelled" assert y.status == "cancelled" @gen_cluster(client=True) async def test_scatter_compute_store_lose(c, s, a, b): """ Create irreplaceable data on one machine, cause a dependent computation to occur on another and complete Kill the machine with the irreplaceable data. What happens to the complete result? How about after it GCs and tries to come back? """ x = await c.scatter(1, workers=a.address) xx = c.submit(inc, x, workers=a.address) y = c.submit(inc, 1) z = c.submit(slowadd, xx, y, delay=0.2, workers=b.address) await wait(z) await a.close() while x.status == "finished": await asyncio.sleep(0.01) # assert xx.status == 'finished' assert y.status == "finished" assert z.status == "finished" zz = c.submit(inc, z) await wait(zz) zkey = z.key del z while s.get_task_status(keys=[zkey]) != {zkey: "released"}: await asyncio.sleep(0.01) xxkey = xx.key del xx while x.key in s.tasks and zkey not in s.tasks and xxkey not in s.tasks: await asyncio.sleep(0.01) @gen_cluster(client=True) async def test_scatter_compute_store_lose_processing(c, s, a, b): """ Create irreplaceable data on one machine, cause a dependent computation to occur on another and complete Kill the machine with the irreplaceable data. What happens to the complete result? How about after it GCs and tries to come back? """ [x] = await c.scatter([1], workers=a.address) y = c.submit(slowinc, x, delay=0.2) z = c.submit(inc, y) await asyncio.sleep(0.1) await a.close() while x.status == "finished": await asyncio.sleep(0.01) assert y.status == "cancelled" assert z.status == "cancelled" @gen_cluster() async def test_serialize_future(s, a, b): async with Client(s.address, asynchronous=True) as c1, Client( s.address, asynchronous=True ) as c2: future = c1.submit(lambda: 1) result = await future for ci in (c1, c2): for ctxman in lambda ci: ci.as_current(), lambda ci: temp_default_client( ci ): with ctxman(ci): future2 = pickle.loads(pickle.dumps(future)) assert future2.client is ci assert stringify(future2.key) in ci.futures result2 = await future2 assert result == result2 @gen_cluster() async def test_temp_default_client(s, a, b): async with Client(s.address, asynchronous=True) as c1, Client( s.address, asynchronous=True ) as c2: with temp_default_client(c1): assert default_client() is c1 assert default_client(c2) is c2 with temp_default_client(c2): assert default_client() is c2 assert default_client(c1) is c1 @gen_cluster(client=True) async def test_as_current(c, s, a, b): async with Client(s.address, asynchronous=True) as c1, Client( s.address, asynchronous=True ) as c2: with temp_default_client(c): assert Client.current() is c with pytest.raises(ValueError): Client.current(allow_global=False) with c1.as_current(): assert Client.current() is c1 assert Client.current(allow_global=True) is c1 with c2.as_current(): assert Client.current() is c2 assert Client.current(allow_global=True) is c2 def test_as_current_is_thread_local(s, loop): parties = 2 cm_after_enter = threading.Barrier(parties=parties, timeout=5) cm_before_exit = threading.Barrier(parties=parties, timeout=5) def run(): with Client(s["address"], loop=loop) as c: with c.as_current(): cm_after_enter.wait() try: # This line runs only when all parties are inside the # context manager assert Client.current(allow_global=False) is c finally: cm_before_exit.wait() with concurrent.futures.ThreadPoolExecutor(max_workers=parties) as tpe: for fut in concurrent.futures.as_completed( [tpe.submit(run) for _ in range(parties)] ): fut.result() @gen_cluster() async def test_as_current_is_task_local(s, a, b): l1 = asyncio.Lock() l2 = asyncio.Lock() l3 = asyncio.Lock() l4 = asyncio.Lock() await l1.acquire() await l2.acquire() await l3.acquire() await l4.acquire() async def run1(): async with Client(s.address, asynchronous=True) as c: with c.as_current(): await l1.acquire() l2.release() try: # This line runs only when both run1 and run2 are inside the # context manager assert Client.current(allow_global=False) is c finally: await l3.acquire() l4.release() async def run2(): async with Client(s.address, asynchronous=True) as c: with c.as_current(): l1.release() await l2.acquire() try: # This line runs only when both run1 and run2 are inside the # context manager assert Client.current(allow_global=False) is c finally: l3.release() await l4.acquire() await asyncio.gather(run1(), run2()) @nodebug # test timing is fragile @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True, config=NO_AMM) async def test_persist_workers_annotate(e, s, a, b, c): with dask.annotate(workers=a.address, allow_other_workers=False): L1 = [delayed(inc)(i) for i in range(4)] with dask.annotate(workers=b.address, allow_other_workers=False): total = delayed(sum)(L1) with dask.annotate(workers=c.address, allow_other_workers=True): L2 = [delayed(add)(i, total) for i in L1] with dask.annotate(workers=b.address, allow_other_workers=True): total2 = delayed(sum)(L2) # TODO: once annotations are faithfully forwarded upon graph optimization, # we shouldn't need to disable that here. out = e.persist(L1 + L2 + [total, total2], optimize_graph=False) await wait(out) assert all(v.key in a.data for v in L1) assert total.key in b.data assert s.tasks[total2.key].loose_restrictions for v in L2: assert s.tasks[v.key].loose_restrictions @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True) async def test_persist_workers_annotate2(e, s, a, b, c): def key_to_worker(key): return a.address L1 = [delayed(inc)(i) for i in range(4)] for x in L1: assert all(layer.annotations is None for layer in x.dask.layers.values()) with dask.annotate(workers=key_to_worker): out = e.persist(L1, optimize_graph=False) await wait(out) for x in L1: assert all(layer.annotations is None for layer in x.dask.layers.values()) for v in L1: assert s.tasks[v.key].worker_restrictions == {a.address} @nodebug # test timing is fragile @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True) async def test_persist_workers(e, s, a, b, c): L1 = [delayed(inc)(i) for i in range(4)] total = delayed(sum)(L1) L2 = [delayed(add)(i, total) for i in L1] total2 = delayed(sum)(L2) out = e.persist( L1 + L2 + [total, total2], workers=[a.address, b.address], allow_other_workers=True, ) await wait(out) for v in L1 + L2 + [total, total2]: assert s.tasks[v.key].worker_restrictions == {a.address, b.address} assert not any(c.address in ts.worker_restrictions for ts in s.tasks.values()) assert s.tasks[total.key].loose_restrictions for v in L1 + L2: assert s.tasks[v.key].loose_restrictions @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True) async def test_compute_workers_annotate(e, s, a, b, c): with dask.annotate(workers=a.address, allow_other_workers=True): L1 = [delayed(inc)(i) for i in range(4)] with dask.annotate(workers=b.address, allow_other_workers=True): total = delayed(sum)(L1) with dask.annotate(workers=[c.address]): L2 = [delayed(add)(i, total) for i in L1] # TODO: once annotations are faithfully forwarded upon graph optimization, # we shouldn't need to disable that here. out = e.compute(L1 + L2 + [total], optimize_graph=False) await wait(out) for v in L1: assert s.tasks[v.key].worker_restrictions == {a.address} for v in L2: assert s.tasks[v.key].worker_restrictions == {c.address} assert s.tasks[total.key].worker_restrictions == {b.address} assert s.tasks[total.key].loose_restrictions for v in L1: assert s.tasks[v.key].loose_restrictions @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True) async def test_compute_workers(e, s, a, b, c): L1 = [delayed(inc)(i) for i in range(4)] total = delayed(sum)(L1) L2 = [delayed(add)(i, total) for i in L1] out = e.compute( L1 + L2 + [total], workers=[a.address, b.address], allow_other_workers=True, ) await wait(out) for v in L1 + L2 + [total]: assert s.tasks[v.key].worker_restrictions == {a.address, b.address} assert not any(c.address in ts.worker_restrictions for ts in s.tasks.values()) assert s.tasks[total.key].loose_restrictions for v in L1 + L2: assert s.tasks[v.key].loose_restrictions @gen_cluster(client=True) async def test_compute_nested_containers(c, s, a, b): da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") x = da.ones(10, chunks=(5,)) + 1 future = c.compute({"x": [x], "y": 123}) result = await future assert isinstance(result, dict) assert (result["x"][0] == np.ones(10) + 1).all() assert result["y"] == 123 @gen_cluster(client=True) async def test_scatter_type(c, s, a, b): [future] = await c.scatter([1]) assert future.type == int d = await c.scatter({"x": 1.0}) assert d["x"].type == float @gen_cluster(client=True) async def test_retire_workers_2(c, s, a, b): [x] = await c.scatter([1], workers=a.address) await s.retire_workers(workers=[a.address]) assert b.data == {x.key: 1} assert {ws.address for ws in s.tasks[x.key].who_has} == {b.address} assert {ts.key for ts in s.workers[b.address].has_what} == {x.key} assert a.address not in s.workers @gen_cluster(client=True, nthreads=[("", 1)] * 10) async def test_retire_many_workers(c, s, *workers): futures = await c.scatter(list(range(100))) await s.retire_workers(workers=[w.address for w in workers[:7]]) results = await c.gather(futures) assert results == list(range(100)) while len(s.workers) != 3: await asyncio.sleep(0.01) assert len(s.workers) == 3 assert all(future.done() for future in futures) assert all(s.tasks[future.key].state == "memory" for future in futures) assert await c.gather(futures) == list(range(100)) # Don't count how many task landed on each worker. # Normally, tasks would be distributed evenly over the surviving workers. However, # here all workers share the same process memory, so you'll get an unintuitive # distribution of tasks if for any reason one transfer take longer than 2 seconds # and as a consequence the Active Memory Manager ends up running for two iterations. # This is something that will happen more frequently on low-powered CI machines. # See test_active_memory_manager.py for tests that robustly verify the statistical # distribution of tasks after worker retirement. @gen_cluster( client=True, nthreads=[("127.0.0.1", 3)] * 2, config={ "distributed.scheduler.work-stealing": False, "distributed.scheduler.default-task-durations": {"f": "10ms"}, }, ) async def test_weight_occupancy_against_data_movement(c, s, a, b): def f(x, y=0, z=0): sleep(0.01) return x y = await c.scatter([[1, 2, 3, 4]], workers=[a.address]) z = await c.scatter([1], workers=[b.address]) futures = c.map(f, [1, 2, 3, 4], y=y, z=z) await wait(futures) assert sum(f.key in a.data for f in futures) >= 2 assert sum(f.key in b.data for f in futures) >= 1 @gen_cluster( client=True, nthreads=[("127.0.0.1", 1), ("127.0.0.1", 10)], config=merge( NO_AMM, { "distributed.scheduler.work-stealing": False, "distributed.scheduler.default-task-durations": {"f": "10ms"}, }, ), ) async def test_distribute_tasks_by_nthreads(c, s, a, b): def f(x, y=0): sleep(0.01) return x y = await c.scatter([1], broadcast=True) futures = c.map(f, range(20), y=y) await wait(futures) assert len(b.data) > 2 * len(a.data) @gen_cluster(client=True, clean_kwargs={"threads": False}) async def test_add_done_callback(c, s, a, b): S = set() def f(future): future.add_done_callback(g) def g(future): S.add((future.key, future.status)) u = c.submit(inc, 1, key="u") v = c.submit(throws, "hello", key="v") w = c.submit(slowinc, 2, delay=0.3, key="w") x = c.submit(inc, 3, key="x") u.add_done_callback(f) v.add_done_callback(f) w.add_done_callback(f) await wait((u, v, w, x)) x.add_done_callback(f) while len(S) < 4: await asyncio.sleep(0.01) assert S == {(f.key, f.status) for f in (u, v, w, x)} @gen_cluster(client=True) async def test_normalize_collection(c, s, a, b): x = delayed(inc)(1) y = delayed(inc)(x) z = delayed(inc)(y) yy = c.persist(y) zz = c.normalize_collection(z) assert len(z.dask) == len(y.dask) + 1 assert isinstance(zz.dask[y.key], Future) assert len(zz.dask) < len(z.dask) @gen_cluster(client=True) async def test_normalize_collection_dask_array(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones(10, chunks=(5,)) y = x + 1 yy = c.persist(y) z = y.sum() zdsk = dict(z.dask) zz = c.normalize_collection(z) assert z.dask == zdsk # do not mutate input assert len(z.dask) > len(zz.dask) assert any(isinstance(v, Future) for v in zz.dask.values()) for k, v in yy.dask.items(): assert zz.dask[k].key == v.key result1 = await c.compute(z) result2 = await c.compute(zz) assert result1 == result2 @pytest.mark.slow def test_normalize_collection_with_released_futures(c): da = pytest.importorskip("dask.array") x = da.arange(2**20, chunks=2**10) y = x.persist() wait(y) sol = y.sum().compute() # Start releasing futures del y # Try to reuse futures. Previously this was a race condition, # and the call to `.compute()` would error out due to missing # futures on the scheduler at compute time. normalized = c.normalize_collection(x) res = normalized.sum().compute() assert res == sol @pytest.mark.xfail(reason="https://github.com/dask/distributed/issues/4404") @gen_cluster(client=True) async def test_auto_normalize_collection(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones(10, chunks=5) assert len(x.dask) == 2 with dask.config.set(optimizations=[c._optimize_insert_futures]): y = x.map_blocks(inc, dtype=x.dtype) yy = c.persist(y) await wait(yy) start = time() future = c.compute(y.sum()) await future end = time() assert end - start < 1 start = time() z = c.persist(y + 1) await wait(z) end = time() assert end - start < 1 @pytest.mark.xfail(reason="https://github.com/dask/distributed/issues/4404") def test_auto_normalize_collection_sync(c): da = pytest.importorskip("dask.array") x = da.ones(10, chunks=5) y = x.map_blocks(inc, dtype=x.dtype) yy = c.persist(y) wait(yy) with dask.config.set(optimizations=[c._optimize_insert_futures]): start = time() y.sum().compute() end = time() assert end - start < 1 def assert_no_data_loss(scheduler): for key, start, finish, recommendations, _, _ in scheduler.transition_log: if start == "memory" and finish == "released": for k, v in recommendations.items(): assert not (k == key and v == "waiting") @gen_cluster(client=True) async def test_interleave_computations(c, s, a, b): import distributed distributed.g = s xs = [delayed(slowinc)(i, delay=0.02) for i in range(30)] ys = [delayed(slowdec)(x, delay=0.02) for x in xs] zs = [delayed(slowadd)(x, y, delay=0.02) for x, y in zip(xs, ys)] total = delayed(sum)(zs) future = c.compute(total) done = ("memory", "released") await asyncio.sleep(0.1) x_keys = [x.key for x in xs] y_keys = [y.key for y in ys] z_keys = [z.key for z in zs] while not s.tasks or any(w.processing for w in s.workers.values()): await asyncio.sleep(0.05) x_done = sum(state in done for state in s.get_task_status(keys=x_keys).values()) y_done = sum(state in done for state in s.get_task_status(keys=y_keys).values()) z_done = sum(state in done for state in s.get_task_status(keys=z_keys).values()) assert x_done >= y_done >= z_done assert x_done < y_done + 10 assert y_done < z_done + 10 assert_no_data_loss(s) @pytest.mark.skip(reason="Now prefer first-in-first-out") @gen_cluster(client=True) async def test_interleave_computations_map(c, s, a, b): xs = c.map(slowinc, range(30), delay=0.02) ys = c.map(slowdec, xs, delay=0.02) zs = c.map(slowadd, xs, ys, delay=0.02) done = ("memory", "released") x_keys = [x.key for x in xs] y_keys = [y.key for y in ys] z_keys = [z.key for z in zs] while not s.tasks or any(w.processing for w in s.workers.values()): await asyncio.sleep(0.05) x_done = sum(state in done for state in s.get_task_status(keys=x_keys).values()) y_done = sum(state in done for state in s.get_task_status(keys=y_keys).values()) z_done = sum(state in done for state in s.get_task_status(keys=z_keys).values()) assert x_done >= y_done >= z_done assert x_done < y_done + 10 assert y_done < z_done + 10 @gen_cluster(client=True) async def test_scatter_dict_workers(c, s, a, b): await c.scatter({"a": 10}, workers=[a.address, b.address]) assert "a" in a.data or "a" in b.data @pytest.mark.slow @gen_test() async def test_client_timeout(): """`await Client(...)` keeps retrying for 10 seconds if it can't find the Scheduler straight away """ port = open_port() stop_event = asyncio.Event() async def run_client(): try: async with Client(f"127.0.0.1:{port}", asynchronous=True) as c: return await c.run_on_scheduler(lambda: 123) finally: stop_event.set() async def run_scheduler_after_2_seconds(): # TODO: start a scheduler that waits for the first connection and # closes it await asyncio.sleep(2) async with Scheduler(port=port, dashboard_address=":0"): await stop_event.wait() with dask.config.set({"distributed.comm.timeouts.connect": "10s"}): assert await asyncio.gather( run_client(), run_scheduler_after_2_seconds(), ) == [123, None] @gen_cluster(client=True) async def test_submit_list_kwargs(c, s, a, b): futures = await c.scatter([1, 2, 3]) def f(L=None): return sum(L) future = c.submit(f, L=futures) result = await future assert result == 1 + 2 + 3 @gen_cluster(client=True) async def test_map_list_kwargs(c, s, a, b): futures = await c.scatter([1, 2, 3]) def f(i, L=None): return i + sum(L) futures = c.map(f, range(10), L=futures) results = await c.gather(futures) assert results == [i + 6 for i in range(10)] @gen_cluster(client=True) async def test_recreate_error_delayed(c, s, a, b): x0 = delayed(dec)(2) y0 = delayed(dec)(1) x = delayed(div)(1, x0) y = delayed(div)(1, y0) tot = delayed(sum)(x, y) f = c.compute(tot) assert f.status == "pending" error_f = await c._get_errored_future(f) function, args, kwargs = await c._get_components_from_future(error_f) assert f.status == "error" assert function.__name__ == "div" assert args == (1, 0) with pytest.raises(ZeroDivisionError): function(*args, **kwargs) @gen_cluster(client=True) async def test_recreate_error_futures(c, s, a, b): x0 = c.submit(dec, 2) y0 = c.submit(dec, 1) x = c.submit(div, 1, x0) y = c.submit(div, 1, y0) tot = c.submit(sum, x, y) f = c.compute(tot) assert f.status == "pending" error_f = await c._get_errored_future(f) function, args, kwargs = await c._get_components_from_future(error_f) assert f.status == "error" assert function.__name__ == "div" assert args == (1, 0) with pytest.raises(ZeroDivisionError): function(*args, **kwargs) @gen_cluster(client=True) async def test_recreate_error_collection(c, s, a, b): b = db.range(10, npartitions=4) b = b.map(lambda x: 1 / x) b = b.persist() f = c.compute(b) error_f = await c._get_errored_future(f) function, args, kwargs = await c._get_components_from_future(error_f) with pytest.raises(ZeroDivisionError): function(*args, **kwargs) dd = pytest.importorskip("dask.dataframe") import pandas as pd df = dd.from_pandas(pd.DataFrame({"a": [0, 1, 2, 3, 4]}), chunksize=2) def make_err(x): # because pandas would happily work with NaN if x == 0: raise ValueError return x df2 = df.a.map(make_err) f = c.compute(df2) error_f = await c._get_errored_future(f) function, args, kwargs = await c._get_components_from_future(error_f) with pytest.raises(ValueError): function(*args, **kwargs) # with persist df3 = c.persist(df2) error_f = await c._get_errored_future(df3) function, args, kwargs = await c._get_components_from_future(error_f) with pytest.raises(ValueError): function(*args, **kwargs) @gen_cluster(client=True) async def test_recreate_error_array(c, s, a, b): da = pytest.importorskip("dask.array") pytest.importorskip("scipy") z = (da.linalg.inv(da.zeros((10, 10), chunks=10)) + 1).sum() zz = z.persist() error_f = await c._get_errored_future(zz) function, args, kwargs = await c._get_components_from_future(error_f) assert "0.,0.,0." in str(args).replace(" ", "") # args contain actual arrays def test_recreate_error_sync(c): x0 = c.submit(dec, 2) y0 = c.submit(dec, 1) x = c.submit(div, 1, x0) y = c.submit(div, 1, y0) tot = c.submit(sum, x, y) f = c.compute(tot) with pytest.raises(ZeroDivisionError): c.recreate_error_locally(f) assert f.status == "error" def test_recreate_error_not_error(c): f = c.submit(dec, 2) with pytest.raises(ValueError, match="No errored futures passed"): c.recreate_error_locally(f) @gen_cluster(client=True) async def test_recreate_task_delayed(c, s, a, b): x0 = delayed(dec)(2) y0 = delayed(dec)(2) x = delayed(div)(1, x0) y = delayed(div)(1, y0) tot = delayed(sum)([x, y]) f = c.compute(tot) assert f.status == "pending" function, args, kwargs = await c._get_components_from_future(f) assert f.status == "finished" assert function.__name__ == "sum" assert args == ([1, 1],) assert function(*args, **kwargs) == 2 @gen_cluster(client=True) async def test_recreate_task_futures(c, s, a, b): x0 = c.submit(dec, 2) y0 = c.submit(dec, 2) x = c.submit(div, 1, x0) y = c.submit(div, 1, y0) tot = c.submit(sum, [x, y]) f = c.compute(tot) assert f.status == "pending" function, args, kwargs = await c._get_components_from_future(f) assert f.status == "finished" assert function.__name__ == "sum" assert args == ([1, 1],) assert function(*args, **kwargs) == 2 @gen_cluster(client=True) async def test_recreate_task_collection(c, s, a, b): b = db.range(10, npartitions=4) b = b.map(lambda x: int(3628800 / (x + 1))) b = b.persist() f = c.compute(b) function, args, kwargs = await c._get_components_from_future(f) assert function(*args, **kwargs) == [ 3628800, 1814400, 1209600, 907200, 725760, 604800, 518400, 453600, 403200, 362880, ] dd = pytest.importorskip("dask.dataframe") import pandas as pd df = dd.from_pandas(pd.DataFrame({"a": [0, 1, 2, 3, 4]}), chunksize=2) df2 = df.a.map(lambda x: x + 1) f = c.compute(df2) function, args, kwargs = await c._get_components_from_future(f) expected = pd.DataFrame({"a": [1, 2, 3, 4, 5]})["a"] assert function(*args, **kwargs).equals(expected) # with persist df3 = c.persist(df2) # recreate_task_locally only works with futures with pytest.raises(AttributeError): function, args, kwargs = await c._get_components_from_future(df3) f = c.compute(df3) function, args, kwargs = await c._get_components_from_future(f) assert function(*args, **kwargs).equals(expected) @gen_cluster(client=True) async def test_recreate_task_array(c, s, a, b): da = pytest.importorskip("dask.array") z = (da.zeros((10, 10), chunks=10) + 1).sum() f = c.compute(z) function, args, kwargs = await c._get_components_from_future(f) assert function(*args, **kwargs) == 100 def test_recreate_task_sync(c): x0 = c.submit(dec, 2) y0 = c.submit(dec, 2) x = c.submit(div, 1, x0) y = c.submit(div, 1, y0) tot = c.submit(sum, [x, y]) f = c.compute(tot) assert c.recreate_task_locally(f) == 2 @gen_cluster(client=True) async def test_retire_workers(c, s, a, b): assert set(s.workers) == {a.address, b.address} await c.retire_workers(workers=[a.address], close_workers=True) assert set(s.workers) == {b.address} while a.status != Status.closed: await asyncio.sleep(0.01) class WorkerStartTime(WorkerPlugin): def setup(self, worker): worker.start_time = time() @gen_cluster(client=True, Worker=Nanny, worker_kwargs={"plugins": [WorkerStartTime()]}) async def test_restart_workers(c, s, a, b): # Get initial worker start times results = await c.run(lambda dask_worker: dask_worker.start_time) a_start_time = results[a.worker_address] b_start_time = results[b.worker_address] assert set(s.workers) == {a.worker_address, b.worker_address} # Persist futures and perform a computation da = pytest.importorskip("dask.array") size = 100 x = da.ones(size, chunks=10) x = x.persist() assert await c.compute(x.sum()) == size # Restart a single worker await c.restart_workers(workers=[a.worker_address]) assert set(s.workers) == {a.worker_address, b.worker_address} # Make sure worker start times are as expected results = await c.run(lambda dask_worker: dask_worker.start_time) assert results[b.worker_address] == b_start_time assert results[a.worker_address] > a_start_time # Ensure computation still completes after worker restart assert await c.compute(x.sum()) == size @gen_cluster(client=True) async def test_restart_workers_no_nanny_raises(c, s, a, b): with pytest.raises(ValueError) as excinfo: await c.restart_workers(workers=[a.address]) msg = str(excinfo.value).lower() assert "restarting workers requires a nanny" in msg assert a.address in msg class SlowKillNanny(Nanny): async def kill(self, timeout=2, **kwargs): await asyncio.sleep(2) return await super().kill(timeout=timeout) @gen_cluster(client=True, Worker=SlowKillNanny) async def test_restart_workers_timeout(c, s, a, b): with pytest.raises(TimeoutError) as excinfo: await c.restart_workers(workers=[a.worker_address], timeout=0.001) msg = str(excinfo.value).lower() assert "workers failed to restart" in msg assert a.worker_address in msg class MyException(Exception): pass @gen_cluster(client=True) async def test_robust_unserializable(c, s, a, b): class Foo: def __getstate__(self): raise MyException() with pytest.raises(MyException): future = c.submit(identity, Foo()) futures = c.map(inc, range(10)) results = await c.gather(futures) assert results == list(map(inc, range(10))) assert a.data and b.data @gen_cluster(client=True) async def test_robust_undeserializable(c, s, a, b): class Foo: def __getstate__(self): return 1 def __setstate__(self, state): raise MyException("hello") future = c.submit(identity, Foo()) with pytest.raises(MyException): await future futures = c.map(inc, range(10)) results = await c.gather(futures) assert results == list(map(inc, range(10))) assert a.data and b.data @gen_cluster(client=True) async def test_robust_undeserializable_function(c, s, a, b): class Foo: def __getstate__(self): return 1 def __setstate__(self, state): raise MyException("hello") def __call__(self, *args): return 1 future = c.submit(Foo(), 1) with pytest.raises(MyException): await future futures = c.map(inc, range(10)) results = await c.gather(futures) assert results == list(map(inc, range(10))) assert a.data and b.data @gen_cluster(client=True) async def test_fire_and_forget(c, s, a, b): future = c.submit(slowinc, 1, delay=0.1) import distributed def f(x): distributed.foo = 123 try: fire_and_forget(c.submit(f, future)) while not hasattr(distributed, "foo"): await asyncio.sleep(0.01) assert distributed.foo == 123 finally: del distributed.foo while len(s.tasks) > 1: await asyncio.sleep(0.01) assert set(s.tasks) == {future.key} assert s.tasks[future.key].who_wants @gen_cluster(client=True) async def test_fire_and_forget_err(c, s, a, b): fire_and_forget(c.submit(div, 1, 0)) await asyncio.sleep(0.1) # erred task should clear out quickly start = time() while s.tasks: await asyncio.sleep(0.01) assert time() < start + 1 def test_quiet_client_close(loop): with captured_logger(logging.getLogger("distributed")) as logger: with Client( loop=loop, processes=False, dashboard_address=":0", threads_per_worker=4, ) as c: futures = c.map(slowinc, range(1000), delay=0.01) sleep(0.200) # stop part-way sleep(0.1) # let things settle out = logger.getvalue() lines = out.strip().split("\n") assert len(lines) <= 2 for line in lines: assert ( not line or "heartbeat from unregistered worker" in line or "unaware of this worker" in line or "garbage" in line or set(line) == {"-"} ), line @pytest.mark.slow def test_quiet_client_close_when_cluster_is_closed_before_client(loop): with captured_logger(logging.getLogger("tornado.application")) as logger: cluster = LocalCluster(loop=loop, n_workers=1, dashboard_address=":0") client = Client(cluster, loop=loop) cluster.close() client.close() out = logger.getvalue() assert "CancelledError" not in out @gen_cluster() async def test_close(s, a, b): async with Client(s.address, asynchronous=True) as c: future = c.submit(inc, 1) await wait(future) assert c.id in s.clients await c.close() while c.id in s.clients or s.tasks: await asyncio.sleep(0.01) def test_threadsafe(c): def f(_): d = deque(maxlen=50) for _ in range(100): future = c.submit(inc, random.randint(0, 100)) d.append(future) sleep(0.001) c.gather(list(d)) total = c.submit(sum, list(d)) return total.result() from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(20) as e: results = list(e.map(f, range(20))) assert results and all(results) del results @pytest.mark.slow def test_threadsafe_get(c): da = pytest.importorskip("dask.array") x = da.arange(100, chunks=(10,)) def f(_): total = 0 for _ in range(20): total += (x + random.randint(0, 20)).sum().compute() sleep(0.001) return total from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(30) as e: results = list(e.map(f, range(30))) assert results and all(results) @pytest.mark.slow def test_threadsafe_compute(c): da = pytest.importorskip("dask.array") x = da.arange(100, chunks=(10,)) def f(_): total = 0 for _ in range(20): future = c.compute((x + random.randint(0, 20)).sum()) total += future.result() sleep(0.001) return total from concurrent.futures import ThreadPoolExecutor e = ThreadPoolExecutor(30) results = list(e.map(f, range(30))) assert results and all(results) @gen_cluster(client=True) async def test_identity(c, s, a, b): assert c.id.lower().startswith("client") assert a.id.lower().startswith("worker") assert b.id.lower().startswith("worker") assert s.id.lower().startswith("scheduler") @gen_cluster(client=True, nthreads=[("127.0.0.1", 4)] * 2) async def test_get_client(c, s, a, b): assert get_client() is c assert c.asynchronous def f(x): import distributed client = get_client() assert not client.asynchronous assert client is distributed.tmp_client future = client.submit(inc, x) return future.result() import distributed distributed.tmp_client = c try: futures = c.map(f, range(5)) results = await c.gather(futures) assert results == list(map(inc, range(5))) finally: del distributed.tmp_client def test_get_client_no_cluster(): # Clean up any global workers added by other tests. This test requires that # there are no global workers. Worker._instances.clear() msg = "No global client found and no address provided" with pytest.raises(ValueError, match=rf"^{msg}$"): get_client() @gen_cluster(client=True) async def test_serialize_collections(c, s, a, b): da = pytest.importorskip("dask.array") x = da.arange(10, chunks=(5,)).persist() def f(x): assert isinstance(x, da.Array) return x.sum().compute() future = c.submit(f, x) result = await future assert result == sum(range(10)) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 1) async def test_secede_simple(c, s, a): def f(): client = get_client() secede() return client.submit(inc, 1).result() result = await c.submit(f) assert result == 2 @gen_cluster(client=True) async def test_secede_balances(c, s, a, b): """Ensure that tasks scheduled from a seceded thread can be scheduled elsewhere""" def f(x): client = get_client() secede() futures = client.map(inc, range(10), pure=False) total = client.submit(sum, futures).result() return total futures = c.map(f, range(10), workers=[a.address]) results = await c.gather(futures) # We dispatch 10 tasks and every task generates 11 more tasks # 10 * 11 + 10 assert a.state.executed_count + b.state.executed_count == 120 assert a.state.executed_count >= 10 assert b.state.executed_count > 0 assert results == [sum(map(inc, range(10)))] * 10 @pytest.mark.parametrize("raise_exception", [True, False]) @gen_cluster(client=True, nthreads=[("", 1)]) async def test_long_running_not_in_occupancy(c, s, a, raise_exception): # https://github.com/dask/distributed/issues/5332 # See also test_long_running_removal_clean l = Lock() entered = Event() await l.acquire() def long_running(lock, entered): entered.set() secede() lock.acquire() if raise_exception: raise RuntimeError("Exception in task") f = c.submit(long_running, l, entered) await entered.wait() ts = s.tasks[f.key] ws = s.workers[a.address] assert ws.occupancy == parse_timedelta( dask.config.get("distributed.scheduler.unknown-task-duration") ) while ws.occupancy: await asyncio.sleep(0.01) await a.heartbeat() assert s.workers[a.address].occupancy == 0 assert s.total_occupancy == 0 assert ws.occupancy == 0 await l.release() with ( pytest.raises(RuntimeError, match="Exception in task") if raise_exception else nullcontext() ): await f assert s.total_occupancy == 0 assert ws.occupancy == 0 assert not ws.long_running @pytest.mark.parametrize("ordinary_task", [True, False]) @gen_cluster(client=True, nthreads=[("", 1)]) async def test_long_running_removal_clean(c, s, a, ordinary_task): # https://github.com/dask/distributed/issues/5975 which could reduce # occupancy to negative values upon finishing long running tasks # See also test_long_running_not_in_occupancy l = Lock() entered = Event() l2 = Lock() entered2 = Event() await l.acquire() await l2.acquire() def long_running_secede(lock, entered): entered.set() secede() lock.acquire() def long_running(lock, entered): entered.set() lock.acquire() f = c.submit(long_running_secede, l, entered) await entered.wait() if ordinary_task: f2 = c.submit(long_running, l2, entered2) await entered2.wait() await l.release() await f ws = s.workers[a.address] if ordinary_task: # Should be exactly 0.5 but if for whatever reason this test runs slow, # some approximation may kick in increasing this number assert s.total_occupancy >= 0.5 assert ws.occupancy >= 0.5 await l2.release() await f2 # In the end, everything should be reset assert s.total_occupancy == 0 assert ws.occupancy == 0 assert not ws.long_running @gen_cluster(client=True) async def test_sub_submit_priority(c, s, a, b): def func(): client = get_client() f = client.submit(slowinc, 1, delay=0.5, key="slowinc") client.gather(f) future = c.submit(func, key="f") while len(s.tasks) != 2: await asyncio.sleep(0.001) # lower values schedule first assert s.tasks["f"].priority > s.tasks["slowinc"].priority, ( s.tasks["f"].priority, s.tasks["slowinc"].priority, ) def test_get_client_sync(c, s, a, b): results = c.run(lambda: get_worker().scheduler.address) assert results == {w["address"]: s["address"] for w in [a, b]} results = c.run(lambda: get_client().scheduler.address) assert results == {w["address"]: s["address"] for w in [a, b]} @gen_cluster(client=True) async def test_serialize_collections_of_futures(c, s, a, b): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") from dask.dataframe.utils import assert_eq df = pd.DataFrame({"x": [1, 2, 3]}) ddf = dd.from_pandas(df, npartitions=2).persist() future = await c.scatter(ddf) ddf2 = await future df2 = await c.compute(ddf2) assert_eq(df, df2) def test_serialize_collections_of_futures_sync(c): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") from dask.dataframe.utils import assert_eq df = pd.DataFrame({"x": [1, 2, 3]}) ddf = dd.from_pandas(df, npartitions=2).persist() future = c.scatter(ddf) result = future.result() assert_eq(result.compute(), df) assert future.type == dd.DataFrame assert c.submit(lambda x, y: assert_eq(x.compute(), y), future, df).result() def _dynamic_workload(x, delay=0.01): if delay == "random": sleep(random.random() / 2) else: sleep(delay) if x > 4: return 4 secede() client = get_client() futures = client.map( _dynamic_workload, [x + i + 1 for i in range(2)], pure=False, delay=delay ) total = client.submit(sum, futures) return total.result() def test_dynamic_workloads_sync(c): future = c.submit(_dynamic_workload, 0, delay=0.02) assert future.result(timeout=20) == 52 @pytest.mark.slow def test_dynamic_workloads_sync_random(c): future = c.submit(_dynamic_workload, 0, delay="random") assert future.result(timeout=20) == 52 @gen_cluster(client=True) async def test_bytes_keys(c, s, a, b): key = b"inc-123" future = c.submit(inc, 1, key=key) result = await future assert type(future.key) is bytes assert set(s.tasks) == {key} assert key in a.data or key in b.data assert result == 2 @gen_cluster(client=True) async def test_unicode_ascii_keys(c, s, a, b): uni_type = str key = "inc-123" future = c.submit(inc, 1, key=key) result = await future assert type(future.key) is uni_type assert set(s.tasks) == {key} assert key in a.data or key in b.data assert result == 2 @gen_cluster(client=True) async def test_unicode_keys(c, s, a, b): uni_type = str key = "inc-123\u03bc" future = c.submit(inc, 1, key=key) result = await future assert type(future.key) is uni_type assert set(s.tasks) == {key} assert key in a.data or key in b.data assert result == 2 future2 = c.submit(inc, future) result2 = await future2 assert result2 == 3 future3 = await c.scatter({"data-123": 123}) result3 = await future3["data-123"] assert result3 == 123 def test_use_synchronous_client_in_async_context(loop, c): async def f(): x = await c.scatter(123) y = c.submit(inc, x) z = await c.gather(y) return z z = sync(loop, f) assert z == 124 def test_quiet_quit_when_cluster_leaves(loop_in_thread): loop = loop_in_thread with LocalCluster(loop=loop, dashboard_address=":0", silence_logs=False) as cluster: with captured_logger("distributed.comm") as sio: with Client(cluster, loop=loop) as client: futures = client.map(lambda x: x + 1, range(10)) sleep(0.05) cluster.close() sleep(0.05) text = sio.getvalue() assert not text @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_future(c, s, a, b): x = c.submit(slowdec, 1, delay=0.5) future = c.submit(slowinc, 1, delay=0.5) await asyncio.sleep(0.1) results = await asyncio.gather( c.call_stack(future), c.call_stack(keys=[future.key]) ) assert all(list(first(result.values())) == [future.key] for result in results) assert results[0] == results[1] result = results[0] ts = a.state.tasks.get(future.key) if ts is not None and ts.state == "executing": w = a else: w = b assert list(result) == [w.address] assert list(result[w.address]) == [future.key] assert "slowinc" in str(result) assert "slowdec" not in str(result) @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_all(c, s, a, b): future = c.submit(slowinc, 1, delay=0.8) while not a.state.executing_count and not b.state.executing_count: await asyncio.sleep(0.01) result = await c.call_stack() w = a if a.state.executing_count else b assert list(result) == [w.address] assert list(result[w.address]) == [future.key] assert "slowinc" in str(result) @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_collections(c, s, a, b): da = pytest.importorskip("dask.array") x = da.random.random(100, chunks=(10,)).map_blocks(slowinc, delay=0.5).persist() while not a.state.executing_count and not b.state.executing_count: await asyncio.sleep(0.001) result = await c.call_stack(x) assert result @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_collections_all(c, s, a, b): da = pytest.importorskip("dask.array") x = da.random.random(100, chunks=(10,)).map_blocks(slowinc, delay=0.5).persist() while not a.state.executing_count and not b.state.executing_count: await asyncio.sleep(0.001) result = await c.call_stack() assert result @pytest.mark.flaky(condition=WINDOWS, reruns=10, reruns_delay=5) @gen_cluster( client=True, config={ "distributed.worker.profile.enabled": True, "distributed.worker.profile.cycle": "100ms", }, ) async def test_profile(c, s, a, b): futures = c.map(slowinc, range(10), delay=0.05, workers=a.address) await wait(futures) x = await c.profile(start=time() + 10, stop=time() + 20) assert not x["count"] x = await c.profile(start=0, stop=time()) assert ( x["count"] == sum(p["count"] for _, p in a.profile_history) + a.profile_recent["count"] ) y = await c.profile(start=time() - 0.300, stop=time()) assert 0 < y["count"] < x["count"] assert not any(p["count"] for _, p in b.profile_history) result = await c.profile(workers=b.address) assert not result["count"] @gen_cluster( client=True, config={ "distributed.worker.profile.enabled": False, "distributed.worker.profile.cycle": "100ms", }, ) async def test_profile_disabled(c, s, a, b): futures = c.map(slowinc, range(10), delay=0.05, workers=a.address) await wait(futures) x = await c.profile(start=time() + 10, stop=time() + 20) assert x["count"] == 0 x = await c.profile(start=0, stop=time()) assert x["count"] == 0 y = await c.profile(start=time() - 0.300, stop=time()) assert 0 == y["count"] == x["count"] @gen_cluster( client=True, config={ "distributed.worker.profile.cycle": "100ms", }, ) async def test_profile_keys(c, s, a, b): x = c.map(slowinc, range(10), delay=0.05, workers=a.address) y = c.map(slowdec, range(10), delay=0.05, workers=a.address) await wait(x + y) xp = await c.profile("slowinc") yp = await c.profile("slowdec") p = await c.profile() assert p["count"] == xp["count"] + yp["count"] with captured_logger(logging.getLogger("distributed")) as logger: prof = await c.profile("does-not-exist") assert prof == profile.create() out = logger.getvalue() assert not out @gen_cluster() async def test_client_with_name(s, a, b): with captured_logger("distributed.scheduler") as sio: async with Client(s.address, asynchronous=True, name="foo") as client: assert "foo" in client.id text = sio.getvalue() assert "foo" in text @gen_cluster(client=True) async def test_future_defaults_to_default_client(c, s, a, b): x = c.submit(inc, 1) await wait(x) future = Future(x.key) assert future.client is c @gen_cluster(client=True) async def test_future_auto_inform(c, s, a, b): x = c.submit(inc, 1) await wait(x) async with Client(s.address, asynchronous=True) as client: future = Future(x.key, client) while future.status != "finished": await asyncio.sleep(0.01) @pytest.mark.filterwarnings("ignore:There is no current event loop:DeprecationWarning") @pytest.mark.filterwarnings("ignore:make_current is deprecated:DeprecationWarning") @pytest.mark.filterwarnings("ignore:clear_current is deprecated:DeprecationWarning") def test_client_async_before_loop_starts(cleanup): async def close(): async with client: pass with _pristine_loop() as loop: with pytest.warns( DeprecationWarning, match=r"Constructing LoopRunner\(loop=loop\) without a running loop is deprecated", ): client = Client(asynchronous=True, loop=loop) assert client.asynchronous assert isinstance(client.close(), NoOpAwaitable) loop.run_sync(close) # TODO: client.close() does not unset global client @pytest.mark.slow @gen_cluster(client=True, Worker=Nanny, timeout=60, nthreads=[("127.0.0.1", 3)] * 2) async def test_nested_compute(c, s, a, b): def fib(x): assert get_worker().get_current_task() if x < 2: return x a = delayed(fib)(x - 1) b = delayed(fib)(x - 2) c = a + b return c.compute() future = c.submit(fib, 8) result = await future assert result == 21 assert len(s.transition_log) > 50 @gen_cluster(client=True) async def test_task_metadata(c, s, a, b): with pytest.raises(KeyError): await c.get_metadata("x") with pytest.raises(KeyError): await c.get_metadata(["x"]) result = await c.get_metadata("x", None) assert result is None result = await c.get_metadata(["x"], None) assert result is None with pytest.raises(KeyError): await c.get_metadata(["x", "y"]) result = await c.get_metadata(["x", "y"], None) assert result is None await c.set_metadata("x", 1) result = await c.get_metadata("x") assert result == 1 with pytest.raises(TypeError): await c.get_metadata(["x", "y"]) with pytest.raises(TypeError): await c.get_metadata(["x", "y"], None) future = c.submit(inc, 1) key = future.key await wait(future) await c.set_metadata(key, 123) result = await c.get_metadata(key) assert result == 123 del future while key in s.tasks: await asyncio.sleep(0.01) with pytest.raises(KeyError): await c.get_metadata(key) result = await c.get_metadata(key, None) assert result is None await c.set_metadata(["x", "a"], 1) result = await c.get_metadata("x") assert result == {"a": 1} await c.set_metadata(["x", "b"], 2) result = await c.get_metadata("x") assert result == {"a": 1, "b": 2} result = await c.get_metadata(["x", "a"]) assert result == 1 await c.set_metadata(["x", "a", "c", "d"], 1) result = await c.get_metadata("x") assert result == {"a": {"c": {"d": 1}}, "b": 2} @gen_cluster(client=True, Worker=Nanny) async def test_logs(c, s, a, b): await wait(c.map(inc, range(5))) logs = await c.get_scheduler_logs(n=5) assert logs for _, msg in logs: assert "distributed.scheduler" in msg w_logs = await c.get_worker_logs(n=5) assert set(w_logs.keys()) == {a.worker_address, b.worker_address} for log in w_logs.values(): for _, msg in log: assert "distributed.worker" in msg n_logs = await c.get_worker_logs(nanny=True) assert set(n_logs.keys()) == {a.worker_address, b.worker_address} for log in n_logs.values(): for _, msg in log: assert "distributed.nanny" in msg n_logs = await c.get_worker_logs(nanny=True, workers=[a.worker_address]) assert set(n_logs.keys()) == {a.worker_address} for log in n_logs.values(): for _, msg in log: assert "distributed.nanny" in msg @gen_cluster(client=True, nthreads=[("", 1)], Worker=Nanny) async def test_logs_from_worker_submodules(c, s, a): def on_worker(dask_worker): from distributed.worker import logger as l1 from distributed.worker_state_machine import logger as l2 l1.info("AAA") l2.info("BBB") dask_worker.memory_manager.logger.info("CCC") await c.run(on_worker) logs = await c.get_worker_logs() logs = [row[1].partition(" - ")[2] for row in logs[a.worker_address]] assert logs[-3:] == [ "distributed.worker - INFO - AAA", "distributed.worker.state_machine - INFO - BBB", "distributed.worker.memory - INFO - CCC", ] def on_nanny(dask_worker): from distributed.nanny import logger as l3 l3.info("DDD") dask_worker.memory_manager.logger.info("EEE") await c.run(on_nanny, nanny=True) logs = await c.get_worker_logs(nanny=True) logs = [row[1].partition(" - ")[2] for row in logs[a.worker_address]] assert logs[-2:] == [ "distributed.nanny - INFO - DDD", "distributed.nanny.memory - INFO - EEE", ] @gen_cluster(client=True) async def test_avoid_delayed_finalize(c, s, a, b): x = delayed(inc)(1) future = c.compute(x) result = await future assert result == 2 assert list(s.tasks) == [future.key] == [x.key] @gen_cluster() async def test_config_scheduler_address(s, a, b): with dask.config.set({"scheduler-address": s.address}): with captured_logger("distributed.client") as sio: async with Client(asynchronous=True) as c: assert c.scheduler.address == s.address assert sio.getvalue() == f"Config value `scheduler-address` found: {s.address}\n" @gen_cluster(client=True) async def test_warn_when_submitting_large_values(c, s, a, b): with pytest.warns( UserWarning, match=r"Large object of size (2\.00 MB|1.91 MiB) detected in task graph:" r" \n \(b'00000000000000000000000000000000000000000000000 \.\.\. 000000000000',\)" r"\nConsider scattering large objects ahead of time.*", ): future = c.submit(lambda x: x + 1, b"0" * 2000000) with warnings.catch_warnings(record=True) as record: data = b"0" * 2000000 for i in range(10): future = c.submit(lambda x, y: x, data, i) assert not record @gen_cluster(client=True) async def test_unhashable_function(c, s, a, b): func = _UnhashableCallable() result = await c.submit(func, 1) assert result == 2 @gen_cluster() async def test_client_name(s, a, b): with dask.config.set({"client-name": "hello-world"}): async with Client(s.address, asynchronous=True) as c: assert any("hello-world" in name for name in list(s.clients)) def test_client_doesnt_close_given_loop(loop_in_thread, s, a, b): with Client(s["address"], loop=loop_in_thread) as c: assert c.submit(inc, 1).result() == 2 with Client(s["address"], loop=loop_in_thread) as c: assert c.submit(inc, 2).result() == 3 @gen_cluster(client=True, nthreads=[]) async def test_quiet_scheduler_loss(c, s): c._periodic_callbacks["scheduler-info"].interval = 10 with captured_logger(logging.getLogger("distributed.client")) as logger: await s.close() text = logger.getvalue() assert "BrokenPipeError" not in text def test_dashboard_link(loop, monkeypatch): monkeypatch.setenv("USER", "myusername") with cluster(scheduler_kwargs={"dashboard_address": ":12355"}) as (s, [a, b]): with Client(s["address"], loop=loop) as c: with dask.config.set( {"distributed.dashboard.link": "{scheme}://foo-{USER}:{port}/status"} ): link = "http://foo-myusername:12355/status" assert link == c.dashboard_link text = c._repr_html_() assert link in text @gen_test() async def test_dashboard_link_inproc(): async with Client(processes=False, asynchronous=True, dashboard_address=":0") as c: with dask.config.set({"distributed.dashboard.link": "{host}"}): assert "/" not in c.dashboard_link @gen_test() async def test_client_timeout_2(): port = open_port() with dask.config.set({"distributed.comm.timeouts.connect": "10ms"}): start = time() c = Client(f"127.0.0.1:{port}", asynchronous=True) with pytest.raises((TimeoutError, IOError)): async with c: pass stop = time() assert c.status == "closed" assert stop - start < 1 @gen_test() async def test_client_active_bad_port(): import tornado.httpserver import tornado.web application = tornado.web.Application([(r"/", tornado.web.RequestHandler)]) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8080) with dask.config.set({"distributed.comm.timeouts.connect": "10ms"}): c = Client("127.0.0.1:8080", asynchronous=True) with pytest.raises((TimeoutError, IOError)): async with c: pass http_server.stop() @pytest.mark.parametrize("direct", [True, False]) @gen_cluster(client=True, client_kwargs={"serializers": ["dask", "msgpack"]}) async def test_turn_off_pickle(c, s, a, b, direct): np = pytest.importorskip("numpy") assert (await c.submit(inc, 1)) == 2 await c.submit(np.ones, 5) await c.scatter(1) # Can't send complex data with pytest.raises(TypeError): await c.scatter(inc) # can send complex tasks (this uses pickle regardless) future = c.submit(lambda x: x, inc) await wait(future) # but can't receive complex results with pytest.raises(TypeError): await c.gather(future, direct=direct) # Run works result = await c.run(lambda: 1) assert list(result.values()) == [1, 1] result = await c.run_on_scheduler(lambda: 1) assert result == 1 # But not with complex return values with pytest.raises(TypeError): await c.run(lambda: inc) with pytest.raises(TypeError): await c.run_on_scheduler(lambda: inc) @gen_cluster() async def test_de_serialization(s, a, b): np = pytest.importorskip("numpy") async with Client( s.address, asynchronous=True, serializers=["msgpack", "pickle"], deserializers=["msgpack"], ) as c: # Can send complex data future = await c.scatter(np.ones(5)) # But can not retrieve it with pytest.raises(TypeError): result = await future @gen_cluster() async def test_de_serialization_none(s, a, b): np = pytest.importorskip("numpy") async with Client(s.address, asynchronous=True, deserializers=["msgpack"]) as c: # Can send complex data future = await c.scatter(np.ones(5)) # But can not retrieve it with pytest.raises(TypeError): result = await future @gen_cluster() async def test_client_repr_closed(s, a, b): async with Client(s.address, asynchronous=True) as c: pass assert "No scheduler connected." in c._repr_html_() @pytest.mark.skip def test_client_repr_closed_sync(loop): with Client(loop=loop, processes=False, dashboard_address=":0") as c: pass assert "No scheduler connected." in c._repr_html_() @pytest.mark.xfail(reason="https://github.com/dask/dask/pull/6807") @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)]) async def test_nested_prioritization(c, s, w): x = delayed(inc)(1, dask_key_name=("a", 2)) y = delayed(inc)(2, dask_key_name=("a", 10)) o = dask.order.order(merge(x.__dask_graph__(), y.__dask_graph__())) fx, fy = c.compute([x, y]) await wait([fx, fy]) assert (o[x.key] < o[y.key]) == ( s.tasks[stringify(fx.key)].priority < s.tasks[stringify(fy.key)].priority ) @gen_cluster(client=True) async def test_scatter_error_cancel(c, s, a, b): # https://github.com/dask/distributed/issues/2038 def bad_fn(x): raise Exception("lol") x = await c.scatter(1) y = c.submit(bad_fn, x) del x await wait(y) assert y.status == "error" await asyncio.sleep(0.1) assert y.status == "error" # not cancelled @pytest.mark.parametrize("workers_arg", [False, True]) @pytest.mark.parametrize("direct", [False, True]) @pytest.mark.parametrize("broadcast", [False, True, 10]) @gen_cluster( client=True, nthreads=[("", 1)] * 10, config=merge(NO_AMM, {"distributed.worker.memory.pause": False}), ) async def test_scatter_and_replicate_avoid_paused_workers( c, s, *workers, workers_arg, direct, broadcast ): paused_workers = [w for i, w in enumerate(workers) if i not in (3, 7)] for w in paused_workers: w.status = Status.paused while any(s.workers[w.address].status != Status.paused for w in paused_workers): await asyncio.sleep(0.01) f = await c.scatter( {"x": 1}, workers=[w.address for w in workers[1:-1]] if workers_arg else None, broadcast=broadcast, direct=direct, ) if not broadcast: await c.replicate(f, n=10) expect = [i in (3, 7) for i in range(10)] actual = [("x" in w.data) for w in workers] assert actual == expect @pytest.mark.xfail(reason="GH#5409 Dask-Default-Threads are frequently detected") def test_no_threads_lingering(): if threading.active_count() < 40: return active = dict(threading._active) print(f"==== Found {len(active)} active threads: ====") for t in active.values(): print(t) assert False @gen_cluster() async def test_direct_async(s, a, b): async with Client(s.address, asynchronous=True, direct_to_workers=True) as c: assert c.direct_to_workers async with Client(s.address, asynchronous=True, direct_to_workers=False) as c: assert not c.direct_to_workers def test_direct_sync(c): assert not c.direct_to_workers def f(): return get_client().direct_to_workers assert c.submit(f).result() @gen_cluster() async def test_mixing_clients(s, a, b): async with Client(s.address, asynchronous=True) as c1, Client( s.address, asynchronous=True ) as c2: future = c1.submit(inc, 1) with pytest.raises(ValueError): c2.submit(inc, future) assert not c2.futures # Don't create Futures on second Client @gen_cluster(client=True) async def test_tuple_keys(c, s, a, b): x = dask.delayed(inc)(1, dask_key_name=("x", 1)) y = dask.delayed(inc)(x, dask_key_name=("y", 1)) future = c.compute(y) assert (await future) == 3 @gen_cluster(client=True) async def test_multiple_scatter(c, s, a, b): futures = await asyncio.gather(*(c.scatter(1, direct=True) for _ in range(5))) x = await futures[0] x = await futures[0] @gen_cluster(client=True) async def test_map_large_kwargs_in_graph(c, s, a, b): np = pytest.importorskip("numpy") x = np.random.random(100000) futures = c.map(lambda a, b: a + b, range(100), b=x) while not s.tasks: await asyncio.sleep(0.01) assert len(s.tasks) == 101 assert any(k.startswith("ndarray") for k in s.tasks) @gen_cluster(client=True) async def test_retry(c, s, a, b): def f(): assert dask.config.get("foo") with dask.config.set(foo=False): future = c.submit(f) with pytest.raises(AssertionError): await future with dask.config.set(foo=True): await future.retry() await future @gen_cluster(client=True) async def test_retry_dependencies(c, s, a, b): def f(): return dask.config.get("foo") x = c.submit(f) y = c.submit(inc, x) with pytest.raises(KeyError): await y with dask.config.set(foo=100): await y.retry() result = await y assert result == 101 await y.retry() await x.retry() result = await y assert result == 101 @gen_cluster(client=True) async def test_released_dependencies(c, s, a, b): def f(x): return dask.config.get("foo") + 1 x = c.submit(inc, 1, key="x") y = c.submit(f, x, key="y") del x with pytest.raises(KeyError): await y with dask.config.set(foo=100): await y.retry() result = await y assert result == 101 @gen_cluster(client=True, clean_kwargs={"threads": False}) async def test_profile_bokeh(c, s, a, b): pytest.importorskip("bokeh.plotting") from bokeh.model import Model await c.gather(c.map(slowinc, range(10), delay=0.2)) state, figure = await c.profile(plot=True) assert isinstance(figure, Model) with tmpfile("html") as fn: try: await c.profile(filename=fn) except PermissionError: if WINDOWS: pytest.xfail() assert os.path.exists(fn) @gen_cluster(client=True) async def test_get_mix_futures_and_SubgraphCallable(c, s, a, b): future = c.submit(add, 1, 2) subgraph = SubgraphCallable( {"_2": (add, "_0", "_1"), "_3": (add, future, "_2")}, "_3", ("_0", "_1") ) dsk = {"a": 1, "b": 2, "c": (subgraph, "a", "b"), "d": (subgraph, "c", "b")} future2 = c.get(dsk, "d", sync=False) result = await future2 assert result == 11 # Nested subgraphs subgraph2 = SubgraphCallable( { "_2": (subgraph, "_0", "_1"), "_3": (subgraph, "_2", "_1"), "_4": (add, "_3", future2), }, "_4", ("_0", "_1"), ) dsk2 = {"e": 1, "f": 2, "g": (subgraph2, "e", "f")} result = await c.get(dsk2, "g", sync=False) assert result == 22 @gen_cluster(client=True) async def test_get_mix_futures_and_SubgraphCallable_dask_dataframe(c, s, a, b): dd = pytest.importorskip("dask.dataframe") import pandas as pd df = pd.DataFrame({"x": range(1, 11)}) ddf = dd.from_pandas(df, npartitions=2).persist() ddf = ddf.map_partitions(lambda x: x) ddf["x"] = ddf["x"].astype("f8") ddf = ddf.map_partitions(lambda x: x) ddf["x"] = ddf["x"].astype("f8") result = await c.compute(ddf) assert result.equals(df.astype("f8")) def test_direct_to_workers(s, loop): with Client(s["address"], loop=loop, direct_to_workers=True) as client: future = client.scatter(1) future.result() resp = client.run_on_scheduler(lambda dask_scheduler: dask_scheduler.events) assert "gather" not in str(resp) @gen_cluster(client=True) async def test_instances(c, s, a, b): assert list(Client._instances) == [c] assert list(Scheduler._instances) == [s] assert set(Worker._instances) == {a, b} @gen_cluster(client=True) async def test_wait_for_workers(c, s, a, b): future = asyncio.ensure_future(c.wait_for_workers(n_workers=3)) await asyncio.sleep(0.22) # 2 chances assert not future.done() async with Worker(s.address): start = time() await future assert time() < start + 1 with pytest.raises(TimeoutError) as info: await c.wait_for_workers(n_workers=10, timeout="1 ms") assert "2/10" in str(info.value).replace(" ", "") assert "1 ms" in str(info.value) @pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows") @pytest.mark.parametrize("Worker", [Worker, Nanny]) @gen_test() async def test_file_descriptors_dont_leak(Worker): pytest.importorskip("pandas") df = dask.datasets.timeseries(freq="10s", dtypes={"x": int, "y": float}) proc = psutil.Process() before = proc.num_fds() async with Scheduler(dashboard_address=":0") as s: async with Worker(s.address), Worker(s.address), Client( s.address, asynchronous=True ): assert proc.num_fds() > before await df.sum().persist() start = time() while proc.num_fds() > before: await asyncio.sleep(0.01) assert time() < start + 10, (before, proc.num_fds()) @gen_test() async def test_dashboard_link_cluster(): class MyCluster(LocalCluster): @property def dashboard_link(self): return "http://foo.com" async with MyCluster( processes=False, asynchronous=True, dashboard_address=":0" ) as cluster: async with Client(cluster, asynchronous=True) as client: assert "http://foo.com" in client._repr_html_() @gen_test() async def test_shutdown(): async with Scheduler(dashboard_address=":0") as s: async with Worker(s.address) as w: async with Client(s.address, asynchronous=True) as c: await c.shutdown() assert s.status == Status.closed assert w.status in {Status.closed, Status.closing} @gen_test() async def test_shutdown_localcluster(): async with LocalCluster( n_workers=1, asynchronous=True, processes=False, dashboard_address=":0" ) as lc: async with Client(lc, asynchronous=True) as c: await c.shutdown() assert lc.scheduler.status == Status.closed @gen_test() async def test_config_inherited_by_subprocess(): with dask.config.set(foo=100): async with LocalCluster( n_workers=1, asynchronous=True, processes=True, dashboard_address=":0", ) as lc: async with Client(lc, asynchronous=True) as c: assert await c.submit(dask.config.get, "foo") == 100 @gen_cluster(client=True) async def test_futures_of_sorted(c, s, a, b): pytest.importorskip("dask.dataframe") df = await dask.datasets.timeseries(dtypes={"x": int}).persist() futures = futures_of(df) for k, f in zip(df.__dask_keys__(), futures): assert str(k) in str(f) @pytest.mark.flaky(reruns=10, reruns_delay=5) @gen_cluster( client=True, config={ "distributed.worker.profile.enabled": True, "distributed.worker.profile.cycle": "10ms", }, ) async def test_profile_server(c, s, a, b): for i in range(5): try: x = c.map(slowinc, range(10), delay=0.01, workers=a.address, pure=False) await wait(x) await asyncio.gather( c.run(slowinc, 1, delay=0.5), c.run_on_scheduler(slowdec, 1, delay=0.5) ) p = await c.profile(server=True) # All worker servers assert "slowinc" in str(p) p = await c.profile(scheduler=True) # Scheduler assert "slowdec" in str(p) except AssertionError: if i == 4: raise else: pass else: break @gen_cluster( client=True, config={ "distributed.worker.profile.enabled": False, "distributed.worker.profile.cycle": "10ms", }, ) async def test_profile_server_disabled(c, s, a, b): x = c.map(slowinc, range(10), delay=0.01, workers=a.address, pure=False) await wait(x) await asyncio.gather( c.run(slowinc, 1, delay=0.5), c.run_on_scheduler(slowdec, 1, delay=0.5) ) p = await c.profile(server=True) # All worker servers assert "slowinc" not in str(p) p = await c.profile(scheduler=True) # Scheduler assert "slowdec" not in str(p) @gen_cluster(client=True) async def test_await_future(c, s, a, b): future = c.submit(inc, 1) async def f(): # flake8: noqa result = await future assert result == 2 await f() future = c.submit(div, 1, 0) async def f(): with pytest.raises(ZeroDivisionError): await future await f() @gen_cluster(client=True) async def test_as_completed_async_for(c, s, a, b): futures = c.map(inc, range(10)) ac = as_completed(futures) results = [] async def f(): async for future in ac: result = await future results.append(result) await f() assert set(results) == set(range(1, 11)) @gen_cluster(client=True) async def test_as_completed_async_for_results(c, s, a, b): futures = c.map(inc, range(10)) ac = as_completed(futures, with_results=True) results = [] async def f(): async for future, result in ac: results.append(result) await f() assert set(results) == set(range(1, 11)) assert not s.counters["op"].components[0]["gather"] @gen_cluster(client=True) async def test_as_completed_async_for_cancel(c, s, a, b): x = c.submit(inc, 1) ev = Event() y = c.submit(lambda ev: ev.wait(), ev) ac = as_completed([x, y]) await x await y.cancel() futs = [future async for future in ac] assert futs == [x, y] await ev.set() # Allow for clean teardown @gen_test() async def test_async_with(): async with Client(processes=False, dashboard_address=":0", asynchronous=True) as c: assert await c.submit(lambda x: x + 1, 10) == 11 assert c.status == "closed" assert c.cluster.status == Status.closed def test_client_sync_with_async_def(loop): async def ff(): await asyncio.sleep(0.01) return 1 with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: assert sync(loop, ff) == 1 assert c.sync(ff) == 1 @pytest.mark.skip(reason="known intermittent failure") @gen_cluster(client=True) async def test_dont_hold_on_to_large_messages(c, s, a, b): np = pytest.importorskip("numpy") da = pytest.importorskip("dask.array") x = np.random.random(1000000) xr = weakref.ref(x) d = da.from_array(x, chunks=(100000,)) d = d.persist() del x start = time() while xr() is not None: if time() > start + 5: # Help diagnosing from types import FrameType x = xr() if x is not None: del x rc = sys.getrefcount(xr()) refs = gc.get_referrers(xr()) print("refs to x:", rc, refs, gc.isenabled()) frames = [r for r in refs if isinstance(r, FrameType)] for i, f in enumerate(frames): print( "frames #%d:" % i, f.f_code.co_name, f.f_code.co_filename, sorted(f.f_locals), ) pytest.fail("array should have been destroyed") await asyncio.sleep(0.200) @gen_cluster(client=True) async def test_run_on_scheduler_async_def(c, s, a, b): async def f(dask_scheduler): await asyncio.sleep(0.01) dask_scheduler.foo = "bar" await c.run_on_scheduler(f) assert s.foo == "bar" async def f(dask_worker): await asyncio.sleep(0.01) dask_worker.foo = "bar" await c.run(f) assert a.foo == "bar" assert b.foo == "bar" @gen_cluster(client=True) async def test_run_on_scheduler_async_def_wait(c, s, a, b): async def f(dask_scheduler): await asyncio.sleep(0.01) dask_scheduler.foo = "bar" await c.run_on_scheduler(f, wait=False) while not hasattr(s, "foo"): await asyncio.sleep(0.01) assert s.foo == "bar" async def f(dask_worker): await asyncio.sleep(0.01) dask_worker.foo = "bar" await c.run(f, wait=False) while not hasattr(a, "foo") or not hasattr(b, "foo"): await asyncio.sleep(0.01) assert a.foo == "bar" assert b.foo == "bar" @pytest.mark.skipif(WINDOWS, reason="frequently kills off the whole test suite") @gen_cluster(client=True, nthreads=[("127.0.0.1", 2)] * 2) async def test_performance_report(c, s, a, b): pytest.importorskip("bokeh") da = pytest.importorskip("dask.array") async def f(stacklevel, mode=None): """ We wrap this in a function so that the assertions aren't in the performanace report itself Also, we want this comment to appear """ x = da.random.random((1000, 1000), chunks=(100, 100)) with tmpfile(extension="html") as fn: async with performance_report( filename=fn, stacklevel=stacklevel, mode=mode ): await c.compute((x + x.T).sum()) with open(fn) as f: data = f.read() return data # Ensure default kwarg maintains backward compatibility data = await f(stacklevel=1) assert "Also, we want this comment to appear" in data assert "bokeh" in data assert "random" in data assert "Dask Performance Report" in data assert "x = da.random" in data assert "Threads: 4" in data assert "No logs to report" in data assert dask.__version__ in data # stacklevel=2 captures code two frames back -- which in this case # is the testing function data = await f(stacklevel=2) assert "async def test_performance_report(c, s, a, b):" in data assert "Dask Performance Report" in data # stacklevel=0 or lower is overridden to stacklevel=1 so we don't see # distributed internals data = await f(stacklevel=0) assert "Also, we want this comment to appear" in data assert "Dask Performance Report" in data data = await f(stacklevel=1, mode="inline") assert "cdn.bokeh.org" not in data data = await f(stacklevel=1, mode="cdn") assert "cdn.bokeh.org" in data @pytest.mark.skipif( sys.version_info >= (3, 10), reason="On Py3.10+ semaphore._loop is not bound until .acquire() blocks", ) @gen_cluster(nthreads=[]) async def test_client_gather_semaphore_loop(s): async with Client(s.address, asynchronous=True) as c: assert c._gather_semaphore._loop is c.loop.asyncio_loop @gen_cluster(client=True) async def test_as_completed_condition_loop(c, s, a, b): seq = c.map(inc, range(5)) ac = as_completed(seq) # consume the ac so that the ac.condition is bound to the loop on py3.10+ async for _ in ac: pass assert ac.condition._loop == c.loop.asyncio_loop @pytest.mark.skipif( sys.version_info >= (3, 10), reason="On Py3.10+ semaphore._loop is not bound until .acquire() blocks", ) def test_client_connectionpool_semaphore_loop(s, a, b, loop): with Client(s["address"], loop=loop) as c: assert c.rpc.semaphore._loop is loop.asyncio_loop @pytest.mark.slow @gen_cluster(nthreads=[], timeout=60) async def test_mixed_compression(s): pytest.importorskip("lz4") da = pytest.importorskip("dask.array") async with Nanny( s.address, nthreads=1, config={"distributed.comm.compression": None} ): async with Nanny( s.address, nthreads=1, config={"distributed.comm.compression": "lz4"} ): async with Client(s.address, asynchronous=True) as c: await c.get_versions() x = da.ones((10000, 10000)) y = x + x.T await c.compute(y.sum()) @gen_cluster(client=True) async def test_futures_in_subgraphs(c, s, a, b): """Regression test of <https://github.com/dask/distributed/issues/4145>""" dd = pytest.importorskip("dask.dataframe") import pandas as pd ddf = dd.from_pandas( pd.DataFrame( dict( uid=range(50), enter_time=pd.date_range( start="2020-01-01", end="2020-09-01", periods=50, tz="UTC" ), ) ), npartitions=5, ) ddf = ddf[ddf.uid.isin(range(29))].persist() ddf["local_time"] = ddf.enter_time.dt.tz_convert("US/Central") ddf["day"] = ddf.enter_time.dt.day_name() ddf = await c.submit(dd.categorical.categorize, ddf, columns=["day"], index=False) @gen_cluster(client=True) async def test_get_task_metadata(c, s, a, b): # Populate task metadata await c.register_worker_plugin(TaskStateMetadataPlugin()) async with get_task_metadata() as tasks: f = c.submit(slowinc, 1) await f metadata = tasks.metadata assert f.key in metadata assert metadata[f.key] == s.tasks.get(f.key).metadata state = tasks.state assert f.key in state assert state[f.key] == "memory" assert not any(isinstance(p, CollectTaskMetaDataPlugin) for p in s.plugins) @gen_cluster(client=True) async def test_get_task_metadata_multiple(c, s, a, b): # Populate task metadata await c.register_worker_plugin(TaskStateMetadataPlugin()) # Ensure that get_task_metadata only collects metadata for # tasks which are submitted and completed within its context async with get_task_metadata() as tasks1: f1 = c.submit(slowinc, 1) await f1 async with get_task_metadata() as tasks2: f2 = c.submit(slowinc, 2) await f2 metadata1 = tasks1.metadata metadata2 = tasks2.metadata assert len(metadata1) == 2 assert sorted(metadata1.keys()) == sorted([f1.key, f2.key]) assert metadata1[f1.key] == s.tasks.get(f1.key).metadata assert metadata1[f2.key] == s.tasks.get(f2.key).metadata assert len(metadata2) == 1 assert list(metadata2.keys()) == [f2.key] assert metadata2[f2.key] == s.tasks.get(f2.key).metadata @gen_cluster(client=True) async def test_register_worker_plugin_exception(c, s, a, b): class MyPlugin: def setup(self, worker=None): raise ValueError("Setup failed") with pytest.raises(ValueError, match="Setup failed"): await c.register_worker_plugin(MyPlugin()) @gen_cluster(client=True, nthreads=[("", 1)]) async def test_log_event(c, s, a): # Log an event from inside a task def foo(): get_worker().log_event("topic1", {"foo": "bar"}) assert not await c.get_events("topic1") await c.submit(foo) events = await c.get_events("topic1") assert len(events) == 1 assert events[0][1] == {"foo": "bar", "worker": a.address} # Log an event while on the scheduler def log_scheduler(dask_scheduler): dask_scheduler.log_event("topic2", {"woo": "hoo"}) await c.run_on_scheduler(log_scheduler) events = await c.get_events("topic2") assert len(events) == 1 assert events[0][1] == {"woo": "hoo"} # Log an event from the client process await c.log_event("topic2", ("alice", "bob")) events = await c.get_events("topic2") assert len(events) == 2 assert events[1][1] == ("alice", "bob") @gen_cluster(client=True) async def test_annotations_task_state(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(qux="bar", priority=100): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all( {"qux": "bar", "priority": 100} == ts.annotations for ts in s.tasks.values() ) @pytest.mark.parametrize("fn", ["compute", "persist"]) @gen_cluster(client=True) async def test_annotations_compute_time(c, s, a, b, fn): da = pytest.importorskip("dask.array") x = da.ones(10, chunks=(5,)) with dask.annotate(foo="bar"): # Turn off optimization to avoid rewriting layers and picking up annotations # that way. Instead, we want `compute`/`persist` to be able to pick them up. fut = getattr(c, fn)(x, optimize_graph=False) await wait(fut) assert s.tasks assert all(ts.annotations == {"foo": "bar"} for ts in s.tasks.values()) @pytest.mark.xfail(reason="https://github.com/dask/dask/issues/7036") @gen_cluster(client=True) async def test_annotations_survive_optimization(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(foo="bar"): x = da.ones(10, chunks=(5,)) ann = x.__dask_graph__().layers[x.name].annotations assert ann is not None assert ann.get("foo", None) == "bar" (xx,) = dask.optimize(x) ann = xx.__dask_graph__().layers[x.name].annotations assert ann is not None assert ann.get("foo", None) == "bar" @gen_cluster(client=True) async def test_annotations_priorities(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(priority=15): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all("15" in str(ts.priority) for ts in s.tasks.values()) assert all(ts.priority[0] == -15 for ts in s.tasks.values()) assert all({"priority": 15} == ts.annotations for ts in s.tasks.values()) @gen_cluster(client=True) async def test_annotations_workers(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(workers=[a.address]): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all({"workers": (a.address,)} == ts.annotations for ts in s.tasks.values()) assert all({a.address} == ts.worker_restrictions for ts in s.tasks.values()) assert a.data assert not b.data @gen_cluster(client=True) async def test_annotations_retries(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(retries=2): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all(ts.retries == 2 for ts in s.tasks.values()) assert all(ts.annotations == {"retries": 2} for ts in s.tasks.values()) @gen_cluster(client=True) async def test_annotations_blockwise_unpack(c, s, a, b): da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") from dask.array.utils import assert_eq # A flaky doubling function -- need extra args because it is called before # application to establish dtype/meta. scale = varying([ZeroDivisionError("one"), ZeroDivisionError("two"), 2, 2]) def flaky_double(x): return scale() * x # A reliable double function. def reliable_double(x): return 2 * x x = da.ones(10, chunks=(5,)) # The later annotations should not override the earlier annotations with dask.annotate(retries=2): y = x.map_blocks(flaky_double, meta=np.array((), dtype=float)) with dask.annotate(retries=0): z = y.map_blocks(reliable_double, meta=np.array((), dtype=float)) with dask.config.set(optimization__fuse__active=False): z = await c.compute(z) assert_eq(z, np.ones(10) * 4.0) @gen_cluster( client=True, nthreads=[ ("127.0.0.1", 1), ("127.0.0.1", 1, {"resources": {"GPU": 1}}), ], ) async def test_annotations_resources(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(resources={"GPU": 1}): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all([{"GPU": 1} == ts.resource_restrictions for ts in s.tasks.values()]) assert all([{"resources": {"GPU": 1}} == ts.annotations for ts in s.tasks.values()]) @gen_cluster( client=True, nthreads=[ ("127.0.0.1", 1), ("127.0.0.1", 1, {"resources": {"GPU": 1}}), ], ) async def test_annotations_resources_culled(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones((2, 2, 2), chunks=1) with dask.annotate(resources={"GPU": 1}): y = x.map_blocks(lambda x0: x0, meta=x._meta) z = y[0, 0, 0] (z,) = c.compute([z], optimize_graph=False) await z # it worked! @gen_cluster(client=True) async def test_annotations_loose_restrictions(c, s, a, b): da = pytest.importorskip("dask.array") # Eventually fails if allow_other_workers=False with dask.annotate(workers=["fake"], allow_other_workers=True): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all(not ts.worker_restrictions for ts in s.tasks.values()) assert all({"fake"} == ts.host_restrictions for ts in s.tasks.values()) assert all( [ {"workers": ("fake",), "allow_other_workers": True} == ts.annotations for ts in s.tasks.values() ] ) @gen_cluster(client=True) async def test_workers_collection_restriction(c, s, a, b): da = pytest.importorskip("dask.array") future = c.compute(da.arange(10), workers=a.address) await future assert a.data and not b.data @pytest.mark.filterwarnings("ignore:There is no current event loop:DeprecationWarning") @pytest.mark.filterwarnings("ignore:make_current is deprecated:DeprecationWarning") @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)]) async def test_get_client_functions_spawn_clusters(c, s, a): # see gh4565 scheduler_addr = c.scheduler.address def f(x): with LocalCluster( n_workers=1, processes=False, dashboard_address=":0", worker_dashboard_address=":0", loop=None, ) as cluster2: with Client(cluster2) as c1: c2 = get_client() c1_scheduler = c1.scheduler.address c2_scheduler = c2.scheduler.address assert c1_scheduler != c2_scheduler assert c2_scheduler == scheduler_addr await c.gather(c.map(f, range(2))) await a.close() c_default = default_client() assert c is c_default def test_computation_code_walk_frames(): test_function_code = inspect.getsource(test_computation_code_walk_frames) code = Client._get_computation_code() assert test_function_code == code def nested_call(): return Client._get_computation_code() assert nested_call() == inspect.getsource(nested_call) with pytest.raises(TypeError, match="Ignored modules must be a list"): with dask.config.set( {"distributed.diagnostics.computations.ignore-modules": "test_client"} ): code = Client._get_computation_code() with dask.config.set( {"distributed.diagnostics.computations.ignore-modules": ["test_client"]} ): import sys upper_frame_code = inspect.getsource(sys._getframe(1)) code = Client._get_computation_code() assert code == upper_frame_code assert nested_call() == upper_frame_code def test_computation_object_code_dask_compute(client): da = pytest.importorskip("dask.array") x = da.ones((10, 10), chunks=(3, 3)) future = x.sum().compute() y = future test_function_code = inspect.getsource(test_computation_object_code_dask_compute) def fetch_comp_code(dask_scheduler): computations = list(dask_scheduler.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 return comp.code[0] code = client.run_on_scheduler(fetch_comp_code) assert code == test_function_code def test_computation_object_code_not_available(client): np = pytest.importorskip("numpy") pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") df = pd.DataFrame({"a": range(10)}) ddf = dd.from_pandas(df, npartitions=3) result = np.where(ddf.a > 4) def fetch_comp_code(dask_scheduler): computations = list(dask_scheduler.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 return comp.code[0] code = client.run_on_scheduler(fetch_comp_code) assert code == "<Code not available>" @gen_cluster(client=True) async def test_computation_object_code_dask_persist(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones((10, 10), chunks=(3, 3)) future = x.sum().persist() await future test_function_code = inspect.getsource( test_computation_object_code_dask_persist.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True) async def test_computation_object_code_client_submit_simple(c, s, a, b): def func(x): return x fut = c.submit(func, 1) await fut test_function_code = inspect.getsource( test_computation_object_code_client_submit_simple.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True) async def test_computation_object_code_client_submit_list_comp(c, s, a, b): def func(x): return x futs = [c.submit(func, x) for x in range(10)] await c.gather(futs) test_function_code = inspect.getsource( test_computation_object_code_client_submit_list_comp.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] # Code is deduplicated assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True) async def test_computation_object_code_client_submit_dict_comp(c, s, a, b): def func(x): return x futs = {x: c.submit(func, x) for x in range(10)} await c.gather(futs) test_function_code = inspect.getsource( test_computation_object_code_client_submit_dict_comp.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] # Code is deduplicated assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True) async def test_computation_object_code_client_map(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones((10, 10), chunks=(3, 3)) future = c.compute(x.sum(), retries=2) y = await future test_function_code = inspect.getsource( test_computation_object_code_client_map.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True) async def test_computation_object_code_client_compute(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones((10, 10), chunks=(3, 3)) future = c.compute(x.sum(), retries=2) y = await future test_function_code = inspect.getsource( test_computation_object_code_client_compute.__wrapped__ ) computations = list(s.computations) assert len(computations) == 1 comp = computations[0] assert len(comp.code) == 1 assert comp.code[0] == test_function_code @gen_cluster(client=True, Worker=Nanny) async def test_upload_directory(c, s, a, b, tmp_path): from dask.distributed import UploadDirectory # Be sure to exclude code coverage reports files_start = {f for f in os.listdir() if not f.startswith(".coverage")} with open(tmp_path / "foo.py", "w") as f: f.write("x = 123") with open(tmp_path / "bar.py", "w") as f: f.write("from foo import x") plugin = UploadDirectory(tmp_path, restart=True, update_path=True) await c.register_worker_plugin(plugin) [name] = a.plugins assert os.path.split(tmp_path)[-1] in name def f(): import bar return bar.x results = await c.run(f) assert results[a.worker_address] == 123 assert results[b.worker_address] == 123 async with Nanny(s.address, local_directory=tmp_path / "foo", name="foo") as n: results = await c.run(f) assert results[n.worker_address] == 123 files_end = {f for f in os.listdir() if not f.startswith(".coverage")} assert files_start == files_end # no change @gen_cluster(client=True) async def test_exception_text(c, s, a, b): def bad(x): raise Exception(x) future = c.submit(bad, 123) await wait(future) ts = s.tasks[future.key] assert isinstance(ts.exception_text, str) assert "123" in ts.exception_text assert "Exception(x)" in ts.traceback_text assert "bad" in ts.traceback_text @gen_cluster(client=True) async def test_async_task(c, s, a, b): async def f(x): return x + 1 future = c.submit(f, 10) result = await future assert result == 11 @gen_cluster(client=True) async def test_async_task_with_partial(c, s, a, b): async def f(x, y): return x + y + 1 future = c.submit(functools.partial(f, 1), 10) result = await future assert result == 12 @gen_cluster(client=True, nthreads=[("", 1)]) async def test_events_subscribe_topic(c, s, a): log = [] def user_event_handler(event): log.append(event) c.subscribe_topic("test-topic", user_event_handler) while not s.event_subscriber["test-topic"]: await asyncio.sleep(0.01) a.log_event("test-topic", {"important": "event"}) while len(log) != 1: await asyncio.sleep(0.01) time_, msg = log[0] assert isinstance(time_, float) assert msg == {"important": "event", "worker": a.address} c.unsubscribe_topic("test-topic") while s.event_subscriber["test-topic"]: await asyncio.sleep(0.01) a.log_event("test-topic", {"forget": "me"}) while len(s.events["test-topic"]) == 1: await asyncio.sleep(0.01) assert len(log) == 1 async def async_user_event_handler(event): log.append(event) await asyncio.sleep(0) c.subscribe_topic("test-topic", async_user_event_handler) while not s.event_subscriber["test-topic"]: await asyncio.sleep(0.01) a.log_event("test-topic", {"async": "event"}) while len(log) == 1: await asyncio.sleep(0.01) assert len(log) == 2 time_, msg = log[1] assert isinstance(time_, float) assert msg == {"async": "event", "worker": a.address} # Even though the middle event was not subscribed to, the scheduler still # knows about all and we can retrieve them all_events = await c.get_events(topic="test-topic") assert len(all_events) == 3 @gen_cluster(client=True, nthreads=[("", 1)]) async def test_events_subscribe_topic_cancelled(c, s, a): event_handler_started = asyncio.Event() exc_info = None async def user_event_handler(event): nonlocal exc_info c.unsubscribe_topic("test-topic") event_handler_started.set() with pytest.raises(asyncio.CancelledError) as exc_info: await asyncio.sleep(0.5) c.subscribe_topic("test-topic", user_event_handler) while not s.event_subscriber["test-topic"]: await asyncio.sleep(0.01) a.log_event("test-topic", {}) await event_handler_started.wait() await c._close(fast=True) assert exc_info is not None @gen_cluster(client=True, nthreads=[("", 1)]) async def test_events_all_servers_use_same_channel(c, s, a): """Ensure that logs from all server types (scheduler, worker, nanny) and the clients themselves arrive""" log = [] def user_event_handler(event): log.append(event) c.subscribe_topic("test-topic", user_event_handler) while not s.event_subscriber["test-topic"]: await asyncio.sleep(0.01) async with Nanny(s.address) as n: a.log_event("test-topic", "worker") n.log_event("test-topic", "nanny") s.log_event("test-topic", "scheduler") await c.log_event("test-topic", "client") while not len(log) == 4 == len(set(log)): await asyncio.sleep(0.1) @gen_cluster(client=True, nthreads=[]) async def test_events_unsubscribe_raises_if_unknown(c, s): with pytest.raises(ValueError, match="No event handler known for topic unknown"): c.unsubscribe_topic("unknown") @gen_cluster(client=True) async def test_log_event_warn(c, s, a, b): def foo(): get_worker().log_event(["foo", "warn"], "Hello!") with pytest.warns(UserWarning, match="Hello!"): await c.submit(foo) def no_message(): # missing "message" key should log TypeError get_worker().log_event("warn", {}) with captured_logger(logging.getLogger("distributed.client")) as log: await c.submit(no_message) assert "TypeError" in log.getvalue() def no_category(): # missing "category" defaults to `UserWarning` get_worker().log_event("warn", {"message": pickle.dumps("asdf")}) with pytest.warns(UserWarning, match="asdf"): await c.submit(no_category) @gen_cluster(client=True) async def test_log_event_warn_dask_warns(c, s, a, b): from dask.distributed import warn def warn_simple(): warn("Hello!") with pytest.warns(UserWarning, match="Hello!"): await c.submit(warn_simple) def warn_deprecation_1(): # one way to do it... warn("You have been deprecated by AI", DeprecationWarning) with pytest.warns(DeprecationWarning, match="You have been deprecated by AI"): await c.submit(warn_deprecation_1) def warn_deprecation_2(): # another way to do it... warn(DeprecationWarning("Your profession has been deprecated")) with pytest.warns(DeprecationWarning, match="Your profession has been deprecated"): await c.submit(warn_deprecation_2) # user-defined warning subclass class MyPrescientWarning(UserWarning): pass def warn_cassandra(): warn(MyPrescientWarning("Cassandra says...")) with pytest.warns(MyPrescientWarning, match="Cassandra says..."): await c.submit(warn_cassandra) @gen_cluster(client=True, Worker=Nanny) async def test_print_remote(c, s, a, b, capsys): from dask.distributed import print def foo(): print("Hello!", 123) def bar(): print("Hello!", 123, sep=":") def baz(): print("Hello!", 123, sep=":", end="") def frotz(): # like builtin print(), None values for kwargs should be same as # defaults " ", "\n", sys.stdout, False, respectively. # (But note we don't really have a good way to test for flushes.) print("Hello!", 123, sep=None, end=None, file=None, flush=None) def plugh(): # no positional arguments print(sep=":", end=".") def print_stdout(): print("meow", file=sys.stdout) def print_stderr(): print("meow", file=sys.stderr) def print_badfile(): print("meow", file="my arbitrary file object") capsys.readouterr() # drop any output captured so far await c.submit(foo) out, err = capsys.readouterr() assert "Hello! 123\n" == out await c.submit(bar) out, err = capsys.readouterr() assert "Hello!:123\n" == out await c.submit(baz) out, err = capsys.readouterr() assert "Hello!:123" == out await c.submit(frotz) out, err = capsys.readouterr() assert "Hello! 123\n" == out await c.submit(plugh) out, err = capsys.readouterr() assert "." == out await c.submit(print_stdout) out, err = capsys.readouterr() assert "meow\n" == out and "" == err await c.submit(print_stderr) out, err = capsys.readouterr() assert "meow\n" == err and "" == out with pytest.raises(TypeError): await c.submit(print_badfile) @gen_cluster(client=True, Worker=Nanny) async def test_print_manual(c, s, a, b, capsys): def foo(): get_worker().log_event("print", "Hello!") capsys.readouterr() # drop any output captured so far await c.submit(foo) out, err = capsys.readouterr() assert "Hello!\n" == out def print_otherfile(): # this should log a TypeError in the client get_worker().log_event("print", {"args": ("hello",), "file": "bad value"}) with captured_logger(logging.getLogger("distributed.client")) as log: await c.submit(print_otherfile) assert "TypeError" in log.getvalue() @gen_cluster(client=True, Worker=Nanny) async def test_print_manual_bad_args(c, s, a, b, capsys): def foo(): get_worker().log_event("print", {"args": "not a tuple"}) with captured_logger(logging.getLogger("distributed.client")) as log: await c.submit(foo) assert "TypeError" in log.getvalue() @gen_cluster(client=True, Worker=Nanny) async def test_print_non_msgpack_serializable(c, s, a, b, capsys): from dask.distributed import print def foo(): print(object()) await c.submit(foo) out, err = capsys.readouterr() assert "<object object at" in out def test_print_local(capsys): from dask.distributed import print capsys.readouterr() # drop any output captured so far print("Hello!", 123, sep=":") out, err = capsys.readouterr() assert "Hello!:123\n" == out def _verify_cluster_dump( url: str | pathlib.PosixPath, format: str, addresses: set[str] ) -> dict: fsspec = pytest.importorskip("fsspec") # for load_cluster_dump url = str(url) + (".msgpack.gz" if format == "msgpack" else ".yaml") state = load_cluster_dump(url) assert isinstance(state, dict) assert "scheduler" in state assert "workers" in state assert "versions" in state assert state["workers"].keys() == addresses return state def test_dump_cluster_state_write_from_scheduler(c, s, a, b, tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) scheduler_dir = tmp_path / "scheduler" scheduler_dir.mkdir() c.run_on_scheduler(os.chdir, str(scheduler_dir)) c.dump_cluster_state("not-url") assert (tmp_path / "not-url.msgpack.gz").is_file() c.dump_cluster_state("file://is-url") assert (scheduler_dir / "is-url.msgpack.gz").is_file() c.dump_cluster_state("file://local-explicit", write_from_scheduler=False) assert (tmp_path / "local-explicit.msgpack.gz").is_file() c.dump_cluster_state("scheduler-explicit", write_from_scheduler=True) assert (scheduler_dir / "scheduler-explicit.msgpack.gz").is_file() @pytest.mark.parametrize("local", [True, False]) @pytest.mark.parametrize("_format", ["msgpack", "yaml"]) def test_dump_cluster_state_sync(c, s, a, b, tmp_path, _format, local): filename = tmp_path / "foo" if not local: pytest.importorskip("fsspec") # Make it look like an fsspec path filename = f"file://{filename}" c.dump_cluster_state(filename, format=_format) _verify_cluster_dump(filename, _format, {a["address"], b["address"]}) @pytest.mark.parametrize("local", [True, False]) @pytest.mark.parametrize("_format", ["msgpack", "yaml"]) @gen_cluster(client=True) async def test_dump_cluster_state_async(c, s, a, b, tmp_path, _format, local): filename = tmp_path / "foo" if not local: pytest.importorskip("fsspec") # Make it look like an fsspec path filename = f"file://{filename}" await c.dump_cluster_state(filename, format=_format) _verify_cluster_dump(filename, _format, {a.address, b.address}) @pytest.mark.parametrize("local", [True, False]) @gen_cluster(client=True) async def test_dump_cluster_state_json(c, s, a, b, tmp_path, local): filename = tmp_path / "foo" if not local: pytest.importorskip("fsspec") # Make it look like an fsspec path filename = f"file://{filename}" with pytest.raises(ValueError, match="Unsupported format"): await c.dump_cluster_state(filename, format="json") @gen_cluster(client=True) async def test_dump_cluster_state_exclude_default(c, s, a, b, tmp_path): futs = c.map(inc, range(10)) while len(s.tasks) != len(futs): await asyncio.sleep(0.01) excluded_by_default = [ "run_spec", ] filename = tmp_path / "foo" await c.dump_cluster_state( filename=filename, format="yaml", ) with open(f"{filename}.yaml") as fd: state = yaml.safe_load(fd) assert "workers" in state assert len(state["workers"]) == len(s.workers) for worker_dump in state["workers"].values(): for k, task_dump in worker_dump["tasks"].items(): assert not any(blocked in task_dump for blocked in excluded_by_default) assert k in s.tasks assert "scheduler" in state assert "tasks" in state["scheduler"] tasks = state["scheduler"]["tasks"] assert len(tasks) == len(futs) for k, task_dump in tasks.items(): assert not any(blocked in task_dump for blocked in excluded_by_default) assert k in s.tasks await c.dump_cluster_state( filename=filename, format="yaml", exclude=(), ) with open(f"{filename}.yaml") as fd: state = yaml.safe_load(fd) assert "workers" in state assert len(state["workers"]) == len(s.workers) for worker_dump in state["workers"].values(): for k, task_dump in worker_dump["tasks"].items(): assert all(blocked in task_dump for blocked in excluded_by_default) assert k in s.tasks assert "scheduler" in state assert "tasks" in state["scheduler"] tasks = state["scheduler"]["tasks"] assert len(tasks) == len(futs) for k, task_dump in tasks.items(): assert all(blocked in task_dump for blocked in excluded_by_default) assert k in s.tasks class TestClientSecurityLoader: @contextmanager def config_loader(self, monkeypatch, loader): module_name = "totally_fake_module_name_1" module = types.ModuleType(module_name) module.loader = loader with monkeypatch.context() as m: m.setitem(sys.modules, module_name, module) with dask.config.set( {"distributed.client.security-loader": f"{module_name}.loader"} ): yield @gen_test() async def test_security_loader(self, monkeypatch): security = tls_only_security() async with Scheduler( dashboard_address=":0", protocol="tls", security=security ) as scheduler: def loader(info): assert info == {"address": scheduler.address} return security with self.config_loader(monkeypatch, loader): async with Client(scheduler.address, asynchronous=True) as client: assert client.security is security @gen_test() async def test_security_loader_ignored_if_explicit_security_provided( self, monkeypatch ): security = tls_only_security() def loader(info): assert False async with Scheduler( dashboard_address=":0", protocol="tls", security=security ) as scheduler: with self.config_loader(monkeypatch, loader): async with Client( scheduler.address, security=security, asynchronous=True ) as client: assert client.security is security @gen_test() async def test_security_loader_ignored_if_returns_none(self, monkeypatch): """Test that if a security loader is configured, but it returns `None`, then the default security configuration is used""" ca_file = get_cert("tls-ca-cert.pem") keycert = get_cert("tls-key-cert.pem") config = { "distributed.comm.require-encryption": True, "distributed.comm.tls.ca-file": ca_file, "distributed.comm.tls.client.cert": keycert, "distributed.comm.tls.scheduler.cert": keycert, "distributed.comm.tls.worker.cert": keycert, } def loader(info): loader.called = True return None with dask.config.set(config): async with Scheduler(dashboard_address=":0", protocol="tls") as scheduler: # Smoketest to make sure config was picked up (so we're actually testing something) assert scheduler.security.tls_client_cert assert scheduler.security.tls_scheduler_cert with self.config_loader(monkeypatch, loader): async with Client(scheduler.address, asynchronous=True) as client: assert ( client.security.tls_client_cert == scheduler.security.tls_client_cert ) assert loader.called @gen_test() async def test_security_loader_import_failed(self): security = tls_only_security() with dask.config.set( {"distributed.client.security-loader": "totally_fake_module_name_2.loader"} ): with pytest.raises(ImportError, match="totally_fake_module_name_2.loader"): async with Client("tls://bad-address:8888", asynchronous=True): pass @pytest.mark.avoid_ci(reason="This is slow and probably not worth the cost") @pytest.mark.slow @gen_cluster(client=True) async def test_benchmark_hardware(c, s, a, b): result = await c.benchmark_hardware() assert set(result) == {"disk", "memory", "network"} assert all(isinstance(v, float) for d in result.values() for v in d.values()) @gen_cluster(client=True, nthreads=[]) async def test_benchmark_hardware_no_workers(c, s): assert await c.benchmark_hardware() == {"memory": {}, "disk": {}, "network": {}} @gen_cluster(client=True, nthreads=[]) async def test_wait_for_workers_updates_info(c, s): async with Worker(s.address): await c.wait_for_workers(1) assert c.scheduler_info()["workers"] client_script = """ from dask.distributed import Client if __name__ == "__main__": client = Client(processes=%s, n_workers=1, scheduler_port=0, dashboard_address=":0") """ @pytest.mark.slow # These lines sometimes appear: # Creating scratch directories is taking a surprisingly long time # Future exception was never retrieved # tornado.util.TimeoutError # Batched Comm Closed @pytest.mark.flaky(reruns=5, reruns_delay=5) @pytest.mark.parametrize("processes", [True, False]) def test_quiet_close_process(processes, tmp_path): with open(tmp_path / "script.py", mode="w") as f: f.write(client_script % processes) with popen([sys.executable, tmp_path / "script.py"], capture_output=True) as proc: out, _ = proc.communicate(timeout=60) lines = out.decode("utf-8").split("\n") lines = [stripped for line in lines if (stripped := line.strip())] assert not lines @gen_cluster(client=False, nthreads=[]) async def test_deprecated_loop_properties(s): class ExampleClient(Client): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.loop = self.io_loop = IOLoop.current() with pytest.warns(DeprecationWarning) as warninfo: async with ExampleClient(s.address, asynchronous=True, loop=IOLoop.current()): pass assert [(w.category, *w.message.args) for w in warninfo] == [ (DeprecationWarning, "setting the loop property is deprecated"), (DeprecationWarning, "The io_loop property is deprecated"), (DeprecationWarning, "setting the loop property is deprecated"), ] @gen_cluster(client=False, nthreads=[]) async def test_fast_close_on_aexit_failure(s): class MyException(Exception): pass c = Client(s.address, asynchronous=True) with mock.patch.object(c, "_close", wraps=c._close) as _close_proxy: with pytest.raises(MyException): async with c: start = time() raise MyException stop = time() assert _close_proxy.mock_calls == [mock.call(fast=True)] assert c.status == "closed" assert (stop - start) < 2 @gen_cluster(client=True, nthreads=[]) async def test_wait_for_workers_no_default(c, s): with pytest.warns( FutureWarning, match="specify the `n_workers` argument when using `Client.wait_for_workers`", ): await c.wait_for_workers() @pytest.mark.parametrize( "value, exception", [ (None, ValueError), (0, ValueError), (1.0, ValueError), (1, None), (2, None), ], ) @gen_cluster(client=True) async def test_wait_for_workers_n_workers_value_check(c, s, a, b, value, exception): if exception: ctx = pytest.raises(exception) else: ctx = nullcontext() with ctx: await c.wait_for_workers(value) @gen_cluster(client=True) async def test_unpacks_remotedata_namedtuple(c, s, a, b): class NamedTupleAnnotation(namedtuple("BaseAnnotation", field_names="value")): def unwrap(self): return self.value def identity(x): return x outer_future = c.submit(identity, NamedTupleAnnotation("some-data")) result = await outer_future assert result == NamedTupleAnnotation(value="some-data")
bsd-3-clause
ddd4dc1bbf45c8cbcce06e6ccfe02129
27.73827
99
0.603265
3.223205
false
true
false
false
scikit-optimize/scikit-optimize
skopt/utils.py
1
27455
from copy import deepcopy from functools import wraps from sklearn.utils import check_random_state import numpy as np from scipy.optimize import OptimizeResult from scipy.optimize import minimize as sp_minimize from sklearn.base import is_regressor from sklearn.ensemble import GradientBoostingRegressor from joblib import dump as dump_ from joblib import load as load_ from collections import OrderedDict from .learning import ExtraTreesRegressor from .learning import GaussianProcessRegressor from .learning import GradientBoostingQuantileRegressor from .learning import RandomForestRegressor from .learning.gaussian_process.kernels import ConstantKernel from .learning.gaussian_process.kernels import HammingKernel from .learning.gaussian_process.kernels import Matern from .sampler import Sobol, Lhs, Hammersly, Halton, Grid from .sampler import InitialPointGenerator from .space import Space, Categorical, Integer, Real, Dimension __all__ = ( "load", "dump", ) def create_result(Xi, yi, space=None, rng=None, specs=None, models=None): """ Initialize an `OptimizeResult` object. Parameters ---------- Xi : list of lists, shape (n_iters, n_features) Location of the minimum at every iteration. yi : array-like, shape (n_iters,) Minimum value obtained at every iteration. space : Space instance, optional Search space. rng : RandomState instance, optional State of the random state. specs : dict, optional Call specifications. models : list, optional List of fit surrogate models. Returns ------- res : `OptimizeResult`, scipy object OptimizeResult instance with the required information. """ res = OptimizeResult() yi = np.asarray(yi) if np.ndim(yi) == 2: res.log_time = np.ravel(yi[:, 1]) yi = np.ravel(yi[:, 0]) best = np.argmin(yi) res.x = Xi[best] res.fun = yi[best] res.func_vals = yi res.x_iters = Xi res.models = models res.space = space res.random_state = rng res.specs = specs return res def eval_callbacks(callbacks, result): """Evaluate list of callbacks on result. The return values of the `callbacks` are ORed together to give the overall decision on whether or not the optimization procedure should continue. Parameters ---------- callbacks : list of callables Callbacks to evaluate. result : `OptimizeResult`, scipy object Optimization result object to be stored. Returns ------- decision : bool Decision of the callbacks whether or not to keep optimizing """ stop = False if callbacks: for c in callbacks: decision = c(result) if decision is not None: stop = stop or decision return stop def dump(res, filename, store_objective=True, **kwargs): """ Store an skopt optimization result into a file. Parameters ---------- res : `OptimizeResult`, scipy object Optimization result object to be stored. filename : string or `pathlib.Path` The path of the file in which it is to be stored. The compression method corresponding to one of the supported filename extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used automatically. store_objective : boolean, default=True Whether the objective function should be stored. Set `store_objective` to `False` if your objective function (`.specs['args']['func']`) is unserializable (i.e. if an exception is raised when trying to serialize the optimization result). Notice that if `store_objective` is set to `False`, a deep copy of the optimization result is created, potentially leading to performance problems if `res` is very large. If the objective function is not critical, one can delete it before calling `skopt.dump()` and thus avoid deep copying of `res`. **kwargs : other keyword arguments All other keyword arguments will be passed to `joblib.dump`. """ if store_objective: dump_(res, filename, **kwargs) elif 'func' in res.specs['args']: # If the user does not want to store the objective and it is indeed # present in the provided object, then create a deep copy of it and # remove the objective function before dumping it with joblib.dump. res_without_func = deepcopy(res) del res_without_func.specs['args']['func'] dump_(res_without_func, filename, **kwargs) else: # If the user does not want to store the objective and it is already # missing in the provided object, dump it without copying. dump_(res, filename, **kwargs) def load(filename, **kwargs): """ Reconstruct a skopt optimization result from a file persisted with skopt.dump. .. note:: Notice that the loaded optimization result can be missing the objective function (`.specs['args']['func']`) if `skopt.dump` was called with `store_objective=False`. Parameters ---------- filename : string or `pathlib.Path` The path of the file from which to load the optimization result. **kwargs : other keyword arguments All other keyword arguments will be passed to `joblib.load`. Returns ------- res : `OptimizeResult`, scipy object Reconstructed OptimizeResult instance. """ return load_(filename, **kwargs) def is_listlike(x): return isinstance(x, (list, tuple)) def is_2Dlistlike(x): return np.all([is_listlike(xi) for xi in x]) def check_x_in_space(x, space): if is_2Dlistlike(x): if not np.all([p in space for p in x]): raise ValueError("Not all points are within the bounds of" " the space.") if any([len(p) != len(space.dimensions) for p in x]): raise ValueError("Not all points have the same dimensions as" " the space.") elif is_listlike(x): if x not in space: raise ValueError("Point (%s) is not within the bounds of" " the space (%s)." % (x, space.bounds)) if len(x) != len(space.dimensions): raise ValueError("Dimensions of point (%s) and space (%s) do not match" % (x, space.bounds)) def expected_minimum(res, n_random_starts=20, random_state=None): """Compute the minimum over the predictions of the last surrogate model. Uses `expected_minimum_random_sampling` with `n_random_starts` = 100000, when the space contains any categorical values. .. note:: The returned minimum may not necessarily be an accurate prediction of the minimum of the true objective function. Parameters ---------- res : `OptimizeResult`, scipy object The optimization result returned by a `skopt` minimizer. n_random_starts : int, default=20 The number of random starts for the minimization of the surrogate model. random_state : int, RandomState instance, or None (default) Set random state to something other than None for reproducible results. Returns ------- x : list location of the minimum. fun : float the surrogate function value at the minimum. """ if res.space.is_partly_categorical: return expected_minimum_random_sampling(res, n_random_starts=100000, random_state=random_state) def func(x): reg = res.models[-1] x = res.space.transform(x.reshape(1, -1)) return reg.predict(x.reshape(1, -1))[0] xs = [res.x] if n_random_starts > 0: xs.extend(res.space.rvs(n_random_starts, random_state=random_state)) best_x = None best_fun = np.inf for x0 in xs: r = sp_minimize(func, x0=x0, bounds=res.space.bounds) if r.fun < best_fun: best_x = r.x best_fun = r.fun return [v for v in best_x], best_fun def expected_minimum_random_sampling(res, n_random_starts=100000, random_state=None): """Minimum search by doing naive random sampling, Returns the parameters that gave the minimum function value. Can be used when the space contains any categorical values. .. note:: The returned minimum may not necessarily be an accurate prediction of the minimum of the true objective function. Parameters ---------- res : `OptimizeResult`, scipy object The optimization result returned by a `skopt` minimizer. n_random_starts : int, default=100000 The number of random starts for the minimization of the surrogate model. random_state : int, RandomState instance, or None (default) Set random state to something other than None for reproducible results. Returns ------- x : list location of the minimum. fun : float the surrogate function value at the minimum. """ # sample points from search space random_samples = res.space.rvs(n_random_starts, random_state=random_state) # make estimations with surrogate model = res.models[-1] y_random = model.predict(res.space.transform(random_samples)) index_best_objective = np.argmin(y_random) min_x = random_samples[index_best_objective] return min_x, y_random[index_best_objective] def has_gradients(estimator): """ Check if an estimator's ``predict`` method provides gradients. Parameters ---------- estimator : sklearn BaseEstimator instance. """ tree_estimators = ( ExtraTreesRegressor, RandomForestRegressor, GradientBoostingQuantileRegressor ) # cook_estimator() returns None for "dummy minimize" aka random values only if estimator is None: return False if isinstance(estimator, tree_estimators): return False categorical_gp = False if hasattr(estimator, "kernel"): params = estimator.get_params() categorical_gp = ( isinstance(estimator.kernel, HammingKernel) or any([isinstance(params[p], HammingKernel) for p in params]) ) return not categorical_gp def cook_estimator(base_estimator, space=None, **kwargs): """Cook a default estimator. For the special base_estimator called "DUMMY" the return value is None. This corresponds to sampling points at random, hence there is no need for an estimator. Parameters ---------- base_estimator : "GP", "RF", "ET", "GBRT", "DUMMY" or sklearn regressor Should inherit from `sklearn.base.RegressorMixin`. In addition the `predict` method should have an optional `return_std` argument, which returns `std(Y | x)`` along with `E[Y | x]`. If base_estimator is one of ["GP", "RF", "ET", "GBRT", "DUMMY"], a surrogate model corresponding to the relevant `X_minimize` function is created. space : Space instance Has to be provided if the base_estimator is a gaussian process. Ignored otherwise. kwargs : dict Extra parameters provided to the base_estimator at init time. """ if isinstance(base_estimator, str): base_estimator = base_estimator.upper() if base_estimator not in ["GP", "ET", "RF", "GBRT", "DUMMY"]: raise ValueError("Valid strings for the base_estimator parameter " " are: 'RF', 'ET', 'GP', 'GBRT' or 'DUMMY' not " "%s." % base_estimator) elif not is_regressor(base_estimator): raise ValueError("base_estimator has to be a regressor.") if base_estimator == "GP": if space is not None: space = Space(space) space = Space(normalize_dimensions(space.dimensions)) n_dims = space.transformed_n_dims is_cat = space.is_categorical else: raise ValueError("Expected a Space instance, not None.") cov_amplitude = ConstantKernel(1.0, (0.01, 1000.0)) # only special if *all* dimensions are categorical if is_cat: other_kernel = HammingKernel(length_scale=np.ones(n_dims)) else: other_kernel = Matern( length_scale=np.ones(n_dims), length_scale_bounds=[(0.01, 100)] * n_dims, nu=2.5) base_estimator = GaussianProcessRegressor( kernel=cov_amplitude * other_kernel, normalize_y=True, noise="gaussian", n_restarts_optimizer=2) elif base_estimator == "RF": base_estimator = RandomForestRegressor(n_estimators=100, min_samples_leaf=3) elif base_estimator == "ET": base_estimator = ExtraTreesRegressor(n_estimators=100, min_samples_leaf=3) elif base_estimator == "GBRT": gbrt = GradientBoostingRegressor(n_estimators=30, loss="quantile") base_estimator = GradientBoostingQuantileRegressor(base_estimator=gbrt) elif base_estimator == "DUMMY": return None if ('n_jobs' in kwargs.keys()) and not hasattr(base_estimator, 'n_jobs'): del kwargs['n_jobs'] base_estimator.set_params(**kwargs) return base_estimator def cook_initial_point_generator(generator, **kwargs): """Cook a default initial point generator. For the special generator called "random" the return value is None. Parameters ---------- generator : "lhs", "sobol", "halton", "hammersly", "grid", "random" \ or InitialPointGenerator instance" Should inherit from `skopt.sampler.InitialPointGenerator`. kwargs : dict Extra parameters provided to the generator at init time. """ if generator is None: generator = "random" elif isinstance(generator, str): generator = generator.lower() if generator not in ["sobol", "halton", "hammersly", "lhs", "random", "grid"]: raise ValueError("Valid strings for the generator parameter " " are: 'sobol', 'lhs', 'halton', 'hammersly'," "'random', or 'grid' not " "%s." % generator) elif not isinstance(generator, InitialPointGenerator): raise ValueError("generator has to be an InitialPointGenerator." "Got %s" % (str(type(generator)))) if isinstance(generator, str): if generator == "sobol": generator = Sobol() elif generator == "halton": generator = Halton() elif generator == "hammersly": generator = Hammersly() elif generator == "lhs": generator = Lhs() elif generator == "grid": generator = Grid() elif generator == "random": return None generator.set_params(**kwargs) return generator def dimensions_aslist(search_space): """Convert a dict representation of a search space into a list of dimensions, ordered by sorted(search_space.keys()). Parameters ---------- search_space : dict Represents search space. The keys are dimension names (strings) and values are instances of classes that inherit from the class :class:`skopt.space.Dimension` (Real, Integer or Categorical) Returns ------- params_space_list: list list of skopt.space.Dimension instances. Examples -------- >>> from skopt.space.space import Real, Integer >>> from skopt.utils import dimensions_aslist >>> search_space = {'name1': Real(0,1), ... 'name2': Integer(2,4), 'name3': Real(-1,1)} >>> dimensions_aslist(search_space)[0] Real(low=0, high=1, prior='uniform', transform='identity') >>> dimensions_aslist(search_space)[1] Integer(low=2, high=4, prior='uniform', transform='identity') >>> dimensions_aslist(search_space)[2] Real(low=-1, high=1, prior='uniform', transform='identity') """ params_space_list = [ search_space[k] for k in sorted(search_space.keys()) ] return params_space_list def point_asdict(search_space, point_as_list): """Convert the list representation of a point from a search space to the dictionary representation, where keys are dimension names and values are corresponding to the values of dimensions in the list. .. seealso:: :class:`skopt.utils.point_aslist` Parameters ---------- search_space : dict Represents search space. The keys are dimension names (strings) and values are instances of classes that inherit from the class :class:`skopt.space.Dimension` (Real, Integer or Categorical) point_as_list : list list with parameter values.The order of parameters in the list is given by sorted(params_space.keys()). Returns ------- params_dict : OrderedDict dictionary with parameter names as keys to which corresponding parameter values are assigned. Examples -------- >>> from skopt.space.space import Real, Integer >>> from skopt.utils import point_asdict >>> search_space = {'name1': Real(0,1), ... 'name2': Integer(2,4), 'name3': Real(-1,1)} >>> point_as_list = [0.66, 3, -0.15] >>> point_asdict(search_space, point_as_list) OrderedDict([('name1', 0.66), ('name2', 3), ('name3', -0.15)]) """ params_dict = OrderedDict() for k, v in zip(sorted(search_space.keys()), point_as_list): params_dict[k] = v return params_dict def point_aslist(search_space, point_as_dict): """Convert a dictionary representation of a point from a search space to the list representation. The list of values is created from the values of the dictionary, sorted by the names of dimensions used as keys. .. seealso:: :class:`skopt.utils.point_asdict` Parameters ---------- search_space : dict Represents search space. The keys are dimension names (strings) and values are instances of classes that inherit from the class :class:`skopt.space.Dimension` (Real, Integer or Categorical) point_as_dict : dict dict with parameter names as keys to which corresponding parameter values are assigned. Returns ------- point_as_list : list list with point values.The order of parameters in the list is given by sorted(params_space.keys()). Examples -------- >>> from skopt.space.space import Real, Integer >>> from skopt.utils import point_aslist >>> search_space = {'name1': Real(0,1), ... 'name2': Integer(2,4), 'name3': Real(-1,1)} >>> point_as_dict = {'name1': 0.66, 'name2': 3, 'name3': -0.15} >>> point_aslist(search_space, point_as_dict) [0.66, 3, -0.15] """ point_as_list = [ point_as_dict[k] for k in sorted(search_space.keys()) ] return point_as_list def normalize_dimensions(dimensions): """Create a ``Space`` where all dimensions are normalized to unit range. This is particularly useful for Gaussian process based regressors and is used internally by ``gp_minimize``. Parameters ---------- dimensions : list, shape (n_dims,) List of search space dimensions. Each search dimension can be defined either as - a `(lower_bound, upper_bound)` tuple (for `Real` or `Integer` dimensions), - a `(lower_bound, upper_bound, "prior")` tuple (for `Real` dimensions), - as a list of categories (for `Categorical` dimensions), or - an instance of a `Dimension` object (`Real`, `Integer` or `Categorical`). NOTE: The upper and lower bounds are inclusive for `Integer` dimensions. """ space = Space(dimensions) transformed_dimensions = [] for dimension in space.dimensions: # check if dimension is of a Dimension instance if isinstance(dimension, Dimension): # Change the transformer to normalize # and add it to the new transformed dimensions dimension.set_transformer("normalize") transformed_dimensions.append( dimension ) else: raise RuntimeError("Unknown dimension type " "(%s)" % type(dimension)) return Space(transformed_dimensions) def check_list_types(x, types): """ Check whether all elements of a list `x` are of the correct type(s) and raise a ValueError if they are not. Note that `types` can be either a single object-type or a tuple of object-types. Raises `ValueError`, If one or more element in the list `x` is not of the correct type(s). Parameters ---------- x : list List of objects. types : object or list(object) Either a single object-type or a tuple of object-types. """ # List of the elements in the list that are incorrectly typed. err = list(filter(lambda a: not isinstance(a, types), x)) # If the list is non-empty then raise an exception. if len(err) > 0: msg = "All elements in list must be instances of {}, but found: {}" msg = msg.format(types, err) raise ValueError(msg) def check_dimension_names(dimensions): """ Check whether all dimensions have names. Raises `ValueError`, if one or more dimensions are unnamed. Parameters ---------- dimensions : list(Dimension) List of Dimension-objects. """ # List of the dimensions that have no names. err_dims = list(filter(lambda dim: dim.name is None, dimensions)) # If the list is non-empty then raise an exception. if len(err_dims) > 0: msg = "All dimensions must have names, but found: {}" msg = msg.format(err_dims) raise ValueError(msg) def use_named_args(dimensions): """ Wrapper / decorator for an objective function that uses named arguments to make it compatible with optimizers that use a single list of parameters. Your objective function can be defined as being callable using named arguments: `func(foo=123, bar=3.0, baz='hello')` for a search-space with dimensions named `['foo', 'bar', 'baz']`. But the optimizer will only pass a single list `x` of unnamed arguments when calling the objective function: `func(x=[123, 3.0, 'hello'])`. This wrapper converts your objective function with named arguments into one that accepts a list as argument, while doing the conversion automatically. The advantage of this is that you don't have to unpack the list of arguments `x` yourself, which makes the code easier to read and also reduces the risk of bugs if you change the number of dimensions or their order in the search-space. Examples -------- >>> # Define the search-space dimensions. They must all have names! >>> from skopt.space import Real >>> from skopt import forest_minimize >>> from skopt.utils import use_named_args >>> dim1 = Real(name='foo', low=0.0, high=1.0) >>> dim2 = Real(name='bar', low=0.0, high=1.0) >>> dim3 = Real(name='baz', low=0.0, high=1.0) >>> >>> # Gather the search-space dimensions in a list. >>> dimensions = [dim1, dim2, dim3] >>> >>> # Define the objective function with named arguments >>> # and use this function-decorator to specify the >>> # search-space dimensions. >>> @use_named_args(dimensions=dimensions) ... def my_objective_function(foo, bar, baz): ... return foo ** 2 + bar ** 4 + baz ** 8 >>> >>> # Not the function is callable from the outside as >>> # `my_objective_function(x)` where `x` is a list of unnamed arguments, >>> # which then wraps your objective function that is callable as >>> # `my_objective_function(foo, bar, baz)`. >>> # The conversion from a list `x` to named parameters `foo`, >>> # `bar`, `baz` >>> # is done automatically. >>> >>> # Run the optimizer on the wrapped objective function which is called >>> # as `my_objective_function(x)` as expected by `forest_minimize()`. >>> result = forest_minimize(func=my_objective_function, ... dimensions=dimensions, ... n_calls=20, base_estimator="ET", ... random_state=4) >>> >>> # Print the best-found results in same format as the expected result. >>> print("Best fitness: " + str(result.fun)) Best fitness: 0.1948080835239698 >>> print("Best parameters: {}".format(result.x)) Best parameters: [0.44134853091052617, 0.06570954323368307, 0.17586123323419825] Parameters ---------- dimensions : list(Dimension) List of `Dimension`-objects for the search-space dimensions. Returns ------- wrapped_func : callable Wrapped objective function. """ def decorator(func): """ This uses more advanced Python features to wrap `func` using a function-decorator, which are not explained so well in the official Python documentation. A good video tutorial explaining how this works is found here: https://www.youtube.com/watch?v=KlBPCzcQNU8 Parameters ---------- func : callable Function to minimize. Should take *named arguments* and return the objective value. """ # Ensure all dimensions are correctly typed. check_list_types(dimensions, Dimension) # Ensure all dimensions have names. check_dimension_names(dimensions) @wraps(func) def wrapper(x): """ This is the code that will be executed every time the wrapped / decorated `func` is being called. It takes `x` as a single list of parameters and converts them to named arguments and calls `func` with them. Parameters ---------- x : list A single list of parameters e.g. `[123, 3.0, 'linear']` which will be converted to named arguments and passed to `func`. Returns ------- objective_value The objective value returned by `func`. """ # Ensure the number of dimensions match # the number of parameters in the list x. if len(x) != len(dimensions): msg = "Mismatch in number of search-space dimensions. " \ "len(dimensions)=={} and len(x)=={}" msg = msg.format(len(dimensions), len(x)) raise ValueError(msg) # Create a dict where the keys are the names of the dimensions # and the values are taken from the list of parameters x. arg_dict = {dim.name: value for dim, value in zip(dimensions, x)} # Call the wrapped objective function with the named arguments. objective_value = func(**arg_dict) return objective_value return wrapper return decorator
bsd-3-clause
5dae05df24efbdf58efb7b31a969f807
33.534591
84
0.619195
4.288504
false
false
false
false
scikit-optimize/scikit-optimize
examples/parallel-optimization.py
5
3174
""" ===================== Parallel optimization ===================== Iaroslav Shcherbatyi, May 2017. Reviewed by Manoj Kumar and Tim Head. Reformatted by Holger Nahrstaedt 2020 .. currentmodule:: skopt Introduction ============ For many practical black box optimization problems expensive objective can be evaluated in parallel at multiple points. This allows to get more objective evaluations per unit of time, which reduces the time necessary to reach good objective values when appropriate optimization algorithms are used, see for example results in [1]_ and the references therein. One such example task is a selection of number and activation function of a neural network which results in highest accuracy for some machine learning problem. For such task, multiple neural networks with different combinations of number of neurons and activation function type can be evaluated at the same time in parallel on different cpu cores / computational nodes. The “ask and tell” API of scikit-optimize exposes functionality that allows to obtain multiple points for evaluation in parallel. Intended usage of this interface is as follows: 1. Initialize instance of the `Optimizer` class from skopt 2. Obtain n points for evaluation in parallel by calling the `ask` method of an optimizer instance with the `n_points` argument set to n > 0 3. Evaluate points 4. Provide points and corresponding objectives using the `tell` method of an optimizer instance 5. Continue from step 2 until eg maximum number of evaluations reached """ print(__doc__) import numpy as np ############################################################################# # Example # ======= # # A minimalistic example that uses joblib to parallelize evaluation of the # objective function is given below. from skopt import Optimizer from skopt.space import Real from joblib import Parallel, delayed # example objective taken from skopt from skopt.benchmarks import branin optimizer = Optimizer( dimensions=[Real(-5.0, 10.0), Real(0.0, 15.0)], random_state=1, base_estimator='gp' ) for i in range(10): x = optimizer.ask(n_points=4) # x is a list of n_points points y = Parallel(n_jobs=4)(delayed(branin)(v) for v in x) # evaluate points in parallel optimizer.tell(x, y) # takes ~ 20 sec to get here print(min(optimizer.yi)) # print the best objective found ############################################################################# # Note that if `n_points` is set to some integer > 0 for the `ask` method, the # result will be a list of points, even for `n_points` = 1. If the argument is # set to `None` (default value) then a single point (but not a list of points) # will be returned. # # The default "minimum constant liar" [1]_ parallelization strategy is used in # the example, which allows to obtain multiple points for evaluation with a # single call to the `ask` method with any surrogate or acquisition function. # Parallelization strategy can be set using the "strategy" argument of `ask`. # For supported parallelization strategies see the documentation of # scikit-optimize. # # .. [1] `<https://hal.archives-ouvertes.fr/hal-00732512/document>`_
bsd-3-clause
84f743cd8f30f0f8ed6359514caeb9a9
37.670732
140
0.715142
4.048531
false
false
false
false
dask/distributed
distributed/_signals.py
1
1297
from __future__ import annotations import asyncio import logging import signal from typing import Any logger = logging.getLogger(__name__) async def wait_for_signals() -> None: """Wait for sigint or sigterm by setting global signal handlers""" signals = (signal.SIGINT, signal.SIGTERM) loop = asyncio.get_running_loop() event = asyncio.Event() old_handlers: dict[int, Any] = {} caught_signal: int | None = None def handle_signal(signum, frame): # *** Do not log or print anything in here # https://stackoverflow.com/questions/45680378/how-to-explain-the-reentrant-runtimeerror-caused-by-printing-in-signal-handlers nonlocal caught_signal caught_signal = signum # Restore old signal handler to allow for quicker exit # if the user sends the signal again. signal.signal(signum, old_handlers[signum]) loop.call_soon_threadsafe(event.set) for sig in signals: old_handlers[sig] = signal.signal(sig, handle_signal) try: await event.wait() assert caught_signal logger.info( "Received signal %s (%d)", signal.Signals(caught_signal).name, caught_signal ) finally: for sig in signals: signal.signal(sig, old_handlers[sig])
bsd-3-clause
49c5a7cdb847545656a9f1cfdd116610
30.634146
134
0.655359
3.930303
false
false
false
false
dask/distributed
distributed/protocol/torch.py
1
1993
from __future__ import annotations import torch from distributed.protocol.serialize import ( dask_deserialize, dask_serialize, deserialize, register_generic, serialize, ) @dask_serialize.register(torch.Tensor) def serialize_torch_Tensor(t): requires_grad_ = t.requires_grad if requires_grad_: sub_header, frames = serialize(t.detach().numpy()) else: sub_header, frames = serialize(t.numpy()) header = {"sub-header": sub_header} if t.grad is not None: grad_header, grad_frames = serialize(t.grad.numpy()) header["grad"] = {"header": grad_header, "start": len(frames)} frames += grad_frames header["requires_grad"] = requires_grad_ header["device"] = t.device.type return header, frames @dask_deserialize.register(torch.Tensor) def deserialize_torch_Tensor(header, frames): if header.get("grad", False): i = header["grad"]["start"] frames, grad_frames = frames[:i], frames[i:] grad = deserialize(header["grad"]["header"], grad_frames) else: grad = None x = deserialize(header["sub-header"], frames) if header["device"] == "cpu": t = torch.from_numpy(x) if header["requires_grad"]: t = t.requires_grad_(True) else: t = torch.tensor( data=x, device=header["device"], requires_grad=header["requires_grad"] ) if grad is not None: t.grad = torch.from_numpy(grad) return t @dask_serialize.register(torch.nn.Parameter) def serialize_torch_Parameters(p): sub_header, frames = serialize(p.detach()) header = {"sub-header": sub_header} header["requires_grad"] = p.requires_grad return header, frames @dask_deserialize.register(torch.nn.Parameter) def deserialize_torch_Parameters(header, frames): t = deserialize(header["sub-header"], frames) return torch.nn.Parameter(data=t, requires_grad=header["requires_grad"]) register_generic(torch.nn.Module)
bsd-3-clause
0ff07a8b33e26bd40c5e72f2dcb921f0
27.471429
82
0.644757
3.656881
false
false
false
false
dask/distributed
distributed/multi_lock.py
1
8042
from __future__ import annotations import asyncio import logging import uuid from collections import defaultdict from collections.abc import Hashable from dask.utils import parse_timedelta from distributed.client import Client from distributed.utils import TimeoutError, log_errors from distributed.worker import get_worker logger = logging.getLogger(__name__) class MultiLockExtension: """An extension for the scheduler to manage MultiLocks This adds the following routes to the scheduler * multi_lock_acquire * multi_lock_release The approach is to maintain `self.locks` that maps a lock (unique name given to `MultiLock(names=, ...)` at creation) to a list of users (instances of `MultiLock`) that "requests" the lock. Additionally, `self.requests` maps a user to its requested locks and `self.requests_left` maps a user to the number of locks still need. Every time a user `x` gets to the front in `self.locks[name] = [x, ...]` it means that `x` now holds the lock `name` and when it holds all the requested locks `acquire()` can return. Finally, `self.events` contains all the events users are waiting on to finish. """ def __init__(self, scheduler): self.scheduler = scheduler self.locks = defaultdict(list) # lock -> users self.requests = {} # user -> locks self.requests_left = {} # user -> locks still needed self.events = {} self.scheduler.handlers.update( {"multi_lock_acquire": self.acquire, "multi_lock_release": self.release} ) def _request_locks(self, locks: list[str], id: Hashable, num_locks: int) -> bool: """Request locks Parameters ---------- locks: List[str] Names of the locks to request. id: Hashable Identifier of the `MultiLock` instance requesting the locks. num_locks: int Number of locks in `locks` requesting Return ------ result: bool Whether `num_locks` requested locks are free immediately or not. """ assert id not in self.requests self.requests[id] = set(locks) assert len(locks) >= num_locks and num_locks > 0 self.requests_left[id] = num_locks locks = sorted(locks, key=lambda x: len(self.locks[x])) for i, lock in enumerate(locks): self.locks[lock].append(id) if len(self.locks[lock]) == 1: # The lock was free self.requests_left[id] -= 1 if self.requests_left[id] == 0: # Got all locks needed # Since we got all locks need, we can remove the rest of the requests self.requests[id] -= set(locks[i + 1 :]) return True return False def _refain_locks(self, locks, id): """Cancel/release previously requested/acquired locks Parameters ---------- locks: List[str] Names of the locks to refain. id: Hashable Identifier of the `MultiLock` instance refraining the locks. """ waiters_ready = set() for lock in locks: if self.locks[lock][0] == id: self.locks[lock].pop(0) if self.locks[lock]: new_first = self.locks[lock][0] self.requests_left[new_first] -= 1 if self.requests_left[new_first] <= 0: # Notice, `self.requests_left[new_first]` might go below zero # if more locks are freed than requested. self.requests_left[new_first] = 0 waiters_ready.add(new_first) else: self.locks[lock].remove(id) assert id not in self.locks[lock] del self.requests[id] del self.requests_left[id] for waiter in waiters_ready: self.scheduler.loop.add_callback(self.events[waiter].set) @log_errors async def acquire(self, locks=None, id=None, timeout=None, num_locks=None): if not self._request_locks(locks, id, num_locks): assert id not in self.events event = asyncio.Event() self.events[id] = event future = event.wait() if timeout is not None: future = asyncio.wait_for(future, timeout) try: await future except TimeoutError: self._refain_locks(locks, id) return False finally: del self.events[id] # At this point `id` acquired all `locks` assert self.requests_left[id] == 0 return True @log_errors def release(self, id=None): self._refain_locks(self.requests[id], id) class MultiLock: """Distributed Centralized Lock Parameters ---------- names Names of the locks to acquire. Choosing the same name allows two disconnected processes to coordinate a lock. client Client to use for communication with the scheduler. If not given, the default global client will be used. Examples -------- >>> lock = MultiLock(['x', 'y']) # doctest: +SKIP >>> lock.acquire(timeout=1) # doctest: +SKIP >>> # do things with protected resource 'x' and 'y' >>> lock.release() # doctest: +SKIP """ def __init__(self, names: list[str] | None = None, client: Client | None = None): try: self.client = client or Client.current() except ValueError: # Initialise new client self.client = get_worker().client self.names = names or [] self.id = uuid.uuid4().hex self._locked = False def acquire(self, blocking=True, timeout=None, num_locks=None): """Acquire the lock Parameters ---------- blocking : bool, optional If false, don't wait on the lock in the scheduler at all. timeout : string or number or timedelta, optional Seconds to wait on the lock in the scheduler. This does not include local coroutine time, network transfer time, etc.. It is forbidden to specify a timeout when blocking is false. Instead of number of seconds, it is also possible to specify a timedelta in string format, e.g. "200ms". num_locks : int, optional Number of locks needed. If None, all locks are needed Examples -------- >>> lock = MultiLock(['x', 'y']) # doctest: +SKIP >>> lock.acquire(timeout="1s") # doctest: +SKIP Returns ------- True or False whether or not it successfully acquired the lock """ timeout = parse_timedelta(timeout) if not blocking: if timeout is not None: raise ValueError("can't specify a timeout for a non-blocking call") timeout = 0 result = self.client.sync( self.client.scheduler.multi_lock_acquire, locks=self.names, id=self.id, timeout=timeout, num_locks=num_locks or len(self.names), ) self._locked = True return result def release(self): """Release the lock if already acquired""" if not self.locked(): raise ValueError("Lock is not yet acquired") ret = self.client.sync(self.client.scheduler.multi_lock_release, id=self.id) self._locked = False return ret def locked(self): return self._locked def __enter__(self): self.acquire() return self def __exit__(self, exc_type, exc_value, traceback): self.release() async def __aenter__(self): await self.acquire() return self async def __aexit__(self, exc_type, exc_value, traceback): await self.release() def __reduce__(self): return (type(self), (self.names,))
bsd-3-clause
f6a5c3ddd95d80b1158fe8b2433e4a75
32.932489
89
0.576225
4.307445
false
false
false
false
dask/distributed
distributed/comm/asyncio_tcp.py
1
34198
from __future__ import annotations import asyncio import collections import logging import os import socket import ssl import struct import sys import weakref from itertools import islice from typing import Any import dask from distributed.comm.addressing import parse_host_port, unparse_host_port from distributed.comm.core import Comm, CommClosedError, Connector, Listener from distributed.comm.registry import Backend from distributed.comm.utils import ( ensure_concrete_host, from_frames, host_array, to_frames, ) from distributed.utils import ensure_ip, ensure_memoryview, get_ip, get_ipv6 logger = logging.getLogger(__name__) _COMM_CLOSED = object() def coalesce_buffers( buffers: list[bytes], target_buffer_size: int = 64 * 1024, small_buffer_size: int = 2048, ) -> list[bytes]: """Given a list of buffers, coalesce them into a new list of buffers that minimizes both copying and tiny writes. Parameters ---------- buffers : list of bytes_like target_buffer_size : int, optional The target intermediate buffer size from concatenating small buffers together. Coalesced buffers will be no larger than approximately this size. small_buffer_size : int, optional Buffers <= this size are considered "small" and may be copied. """ # Nothing to do if len(buffers) == 1: return buffers out_buffers: list[bytes] = [] concat: list[bytes] = [] # A list of buffers to concatenate csize = 0 # The total size of the concatenated buffers def flush(): nonlocal csize if concat: if len(concat) == 1: out_buffers.append(concat[0]) else: out_buffers.append(b"".join(concat)) concat.clear() csize = 0 for b in buffers: size = len(b) if size <= small_buffer_size: concat.append(b) csize += size if csize >= target_buffer_size: flush() else: flush() out_buffers.append(b) flush() return out_buffers class DaskCommProtocol(asyncio.BufferedProtocol): """Manages a state machine for parsing the message framing used by dask. Parameters ---------- on_connection : callable, optional A callback to call on connection, used server side for handling incoming connections. min_read_size : int, optional The minimum buffer size to pass to ``socket.recv_into``. Larger sizes will result in fewer recv calls, at the cost of more copying. For request-response comms (where only one message may be in the queue at a time), a smaller value is likely more performant. """ def __init__(self, on_connection=None, min_read_size=128 * 1024): super().__init__() self.on_connection = on_connection self._loop = asyncio.get_running_loop() # A queue of received messages self._queue = asyncio.Queue() # The corresponding transport, set on `connection_made` self._transport = None # Is the protocol paused? self._paused = False # If the protocol is paused, this holds a future to wait on until it's # unpaused. self._drain_waiter: asyncio.Future | None = None # A future for waiting until the protocol is actually closed self._closed_waiter = self._loop.create_future() # In the interest of reducing the number of `recv` calls, we always # want to provide the opportunity to read `min_read_size` bytes from # the socket (since memcpy is much faster than recv). Each read event # may read into either a default buffer (of size `min_read_size`), or # directly into one of the message frames (if the frame size is > # `min_read_size`). # Per-message state self._using_default_buffer = True self._default_len = max(min_read_size, 16) # need at least 16 bytes of buffer self._default_buffer = host_array(self._default_len) # Index in default_buffer pointing to the first unparsed byte self._default_start = 0 # Index in default_buffer pointing to the last written byte self._default_end = 0 # Each message is composed of one or more frames, these attributes # are filled in as the message is parsed, and cleared once a message # is fully parsed. self._nframes: int | None = None self._frame_lengths: list[int] | None = None self._frames: list[memoryview] | None = None self._frame_index: int | None = None # current frame to parse self._frame_nbytes_needed: int = 0 # nbytes left for parsing current frame @property def local_addr(self): if self.is_closed: return "<closed>" sockname = self._transport.get_extra_info("sockname") if sockname is not None: return unparse_host_port(*sockname[:2]) return "<unknown>" @property def peer_addr(self): if self.is_closed: return "<closed>" peername = self._transport.get_extra_info("peername") if peername is not None: return unparse_host_port(*peername[:2]) return "<unknown>" @property def is_closed(self): return self._transport is None def _abort(self): if not self.is_closed: self._transport, transport = None, self._transport transport.abort() def _close_from_finalizer(self, comm_repr): if not self.is_closed: logger.warning(f"Closing dangling comm `{comm_repr}`") try: self._abort() except RuntimeError: # This happens if the event loop is already closed pass async def _close(self): if not self.is_closed: self._transport, transport = None, self._transport transport.close() await self._closed_waiter def connection_made(self, transport): # XXX: When using asyncio, the default builtin transport makes # excessive copies when buffering. For the case of TCP on asyncio (no # TLS) we patch around that with a wrapper class that handles the write # side with minimal copying. if type(transport) is asyncio.selector_events._SelectorSocketTransport: transport = _ZeroCopyWriter(self, transport) self._transport = transport # Set the buffer limits to something more optimal for large data transfer. self._transport.set_write_buffer_limits(high=512 * 1024) # 512 KiB if self.on_connection is not None: self.on_connection(self) def get_buffer(self, sizehint): """Get a buffer to read into for this read event""" # Read into the default buffer if there are no frames or the current # frame is small. Otherwise read directly into the current frame. if self._frames is None or self._frame_nbytes_needed < self._default_len: self._using_default_buffer = True return self._default_buffer[self._default_end :] else: self._using_default_buffer = False frame = self._frames[self._frame_index] return frame[-self._frame_nbytes_needed :] def buffer_updated(self, nbytes): if nbytes == 0: return if self._using_default_buffer: self._default_end += nbytes self._parse_default_buffer() else: self._frame_nbytes_needed -= nbytes if not self._frames_check_remaining(): self._message_completed() def _parse_default_buffer(self): """Parse all messages in the default buffer.""" while True: if self._nframes is None: if not self._parse_nframes(): break if len(self._frame_lengths) < self._nframes: if not self._parse_frame_lengths(): break if not self._parse_frames(): break self._reset_default_buffer() def _parse_nframes(self): """Fill in `_nframes` from the default buffer. Returns True if successful, False if more data is needed""" # TODO: we drop the message total size prefix (sent as part of the # tornado-based tcp implementation), as it's not needed. If we ever # drop that prefix entirely, we can adjust this code (change 16 -> 8 # and 8 -> 0). if self._default_end - self._default_start >= 16: self._nframes = struct.unpack_from( "<Q", self._default_buffer, offset=self._default_start + 8 )[0] self._default_start += 16 self._frame_lengths = [] return True return False def _parse_frame_lengths(self): """Fill in `_frame_lengths` from the default buffer. Returns True if successful, False if more data is needed""" needed = self._nframes - len(self._frame_lengths) available = (self._default_end - self._default_start) // 8 n_read = min(available, needed) self._frame_lengths.extend( struct.unpack_from( f"<{n_read}Q", self._default_buffer, offset=self._default_start ) ) self._default_start += 8 * n_read if n_read == needed: self._frames = [host_array(n) for n in self._frame_lengths] self._frame_index = 0 self._frame_nbytes_needed = ( self._frame_lengths[0] if self._frame_lengths else 0 ) return True return False def _frames_check_remaining(self): # Current frame not filled if self._frame_nbytes_needed: return True # Advance until next non-empty frame while True: self._frame_index += 1 if self._frame_index < self._nframes: self._frame_nbytes_needed = self._frame_lengths[self._frame_index] if self._frame_nbytes_needed: return True else: # No non-empty frames remain return False def _parse_frames(self): """Fill in `_frames` from the default buffer. Returns True if successful, False if more data is needed""" while True: available = self._default_end - self._default_start # Are we out of frames? if not self._frames_check_remaining(): self._message_completed() return bool(available) # Are we out of data? if not available: return False frame = self._frames[self._frame_index] n_read = min(self._frame_nbytes_needed, available) frame[ -self._frame_nbytes_needed : (n_read - self._frame_nbytes_needed) or None ] = self._default_buffer[self._default_start : self._default_start + n_read] self._default_start += n_read self._frame_nbytes_needed -= n_read def _reset_default_buffer(self): """Reset the default buffer for the next read event""" start = self._default_start end = self._default_end if start < end and start != 0: # Still some unparsed data, copy it to the front of the buffer self._default_buffer[: end - start] = self._default_buffer[start:end] self._default_start = 0 self._default_end = end - start elif start == end: # All data is parsed, just reset the indices self._default_start = 0 self._default_end = 0 def _message_completed(self): """Push a completed message to the queue and reset per-message state""" self._queue.put_nowait(self._frames) self._nframes = None self._frames = None self._frame_lengths = None self._frame_nbytes_remaining = 0 def connection_lost(self, exc=None): self._transport = None self._closed_waiter.set_result(None) # Unblock read, if any self._queue.put_nowait(_COMM_CLOSED) # Unblock write, if any if self._paused: waiter = self._drain_waiter if waiter is not None: self._drain_waiter = None if not waiter.done(): waiter.set_exception(CommClosedError("Connection closed")) def pause_writing(self): self._paused = True def resume_writing(self): self._paused = False waiter = self._drain_waiter if waiter is not None: self._drain_waiter = None if not waiter.done(): waiter.set_result(None) async def read(self) -> list[bytes]: """Read a single message from the comm.""" # Even if comm is closed, we still yield all received data before # erroring if self._queue is not None: out = await self._queue.get() if out is not _COMM_CLOSED: return out self._queue = None raise CommClosedError("Connection closed") async def write(self, frames: list[bytes]) -> int: """Write a message to the comm.""" if self.is_closed: raise CommClosedError("Connection closed") elif self._paused: # Wait until there's room in the write buffer drain_waiter = self._drain_waiter = self._loop.create_future() await drain_waiter # Ensure all memoryviews are in single-byte format frames = [ ensure_memoryview(f) if isinstance(f, memoryview) else f for f in frames ] nframes = len(frames) frames_nbytes = [len(f) for f in frames] # TODO: the old TCP comm included an extra `msg_nbytes` prefix that # isn't really needed. We include it here for backwards compatibility, # but this could be removed if we ever want to make another breaking # change to the comms. msg_nbytes = sum(frames_nbytes) + (nframes + 1) * 8 header = struct.pack(f"{nframes + 2}Q", msg_nbytes, nframes, *frames_nbytes) if msg_nbytes < 4 * 1024: # Always concatenate small messages buffers = [b"".join([header, *frames])] else: buffers = coalesce_buffers([header, *frames]) if len(buffers) > 1: self._transport.writelines(buffers) else: self._transport.write(buffers[0]) return msg_nbytes class TCP(Comm): max_shard_size = dask.utils.parse_bytes(dask.config.get("distributed.comm.shard")) def __init__( self, protocol: DaskCommProtocol, local_addr: str, peer_addr: str, deserialize: bool = True, ): self._protocol = protocol self._local_addr = local_addr self._peer_addr = peer_addr self._closed = False super().__init__(deserialize=deserialize) # setup a finalizer to close the protocol if the comm was never explicitly closed self._finalizer = weakref.finalize( self, self._protocol._close_from_finalizer, repr(self) ) self._finalizer.atexit = False # Fill in any extra info about this comm self._extra_info = self._get_extra_info() def _get_extra_info(self): return {} @property def local_address(self) -> str: return self._local_addr @property def peer_address(self) -> str: return self._peer_addr async def read(self, deserializers=None): frames = await self._protocol.read() try: return await from_frames( frames, deserialize=self.deserialize, deserializers=deserializers, allow_offload=self.allow_offload, ) except EOFError: # Frames possibly garbled or truncated by communication error self.abort() raise CommClosedError("aborted stream on truncated data") async def write(self, msg, serializers=None, on_error="message"): frames = await to_frames( msg, allow_offload=self.allow_offload, serializers=serializers, on_error=on_error, context={ "sender": self.local_info, "recipient": self.remote_info, **self.handshake_options, }, frame_split_size=self.max_shard_size, ) nbytes = await self._protocol.write(frames) return nbytes async def close(self): """Flush and close the comm""" await self._protocol._close() self._finalizer.detach() def abort(self): """Hard close the comm""" self._protocol._abort() self._finalizer.detach() def closed(self): return self._protocol.is_closed @property def extra_info(self): return self._extra_info class TLS(TCP): def _get_extra_info(self): get = self._protocol._transport.get_extra_info return {"peercert": get("peercert"), "cipher": get("cipher")} def _expect_tls_context(connection_args): ctx = connection_args.get("ssl_context") if not isinstance(ctx, ssl.SSLContext): raise TypeError( "TLS expects a `ssl_context` argument of type " "ssl.SSLContext (perhaps check your TLS configuration?)" f" Instead got {ctx!r}" ) return ctx def _error_if_require_encryption(address, **kwargs): if kwargs.get("require_encryption"): raise RuntimeError( "encryption required by Dask configuration, " "refusing communication from/to %r" % ("tcp://" + address,) ) class TCPConnector(Connector): prefix = "tcp://" comm_class = TCP async def connect(self, address, deserialize=True, **kwargs): loop = asyncio.get_running_loop() ip, port = parse_host_port(address) kwargs = self._get_extra_kwargs(address, **kwargs) transport, protocol = await loop.create_connection( DaskCommProtocol, ip, port, **kwargs ) local_addr = self.prefix + protocol.local_addr peer_addr = self.prefix + address return self.comm_class(protocol, local_addr, peer_addr, deserialize=deserialize) def _get_extra_kwargs(self, address, **kwargs): _error_if_require_encryption(address, **kwargs) return {} class TLSConnector(TCPConnector): prefix = "tls://" comm_class = TLS def _get_extra_kwargs(self, address, **kwargs): ctx = _expect_tls_context(kwargs) return {"ssl": ctx} class TCPListener(Listener): prefix = "tcp://" comm_class = TCP def __init__( self, address, comm_handler, deserialize=True, allow_offload=True, default_host=None, default_port=0, **kwargs, ): self.ip, self.port = parse_host_port(address, default_port) self.default_host = default_host self.comm_handler = comm_handler self.deserialize = deserialize self.allow_offload = allow_offload self._extra_kwargs = self._get_extra_kwargs(address, **kwargs) self.bound_address = None def _get_extra_kwargs(self, address, **kwargs): _error_if_require_encryption(address, **kwargs) return {} def _on_connection(self, protocol): comm = self.comm_class( protocol, local_addr=self.prefix + protocol.local_addr, peer_addr=self.prefix + protocol.peer_addr, deserialize=self.deserialize, ) comm.allow_offload = self.allow_offload asyncio.ensure_future(self._comm_handler(comm)) async def _comm_handler(self, comm): try: await self.on_connection(comm) except CommClosedError: logger.debug("Connection closed before handshake completed") return await self.comm_handler(comm) async def _start_all_interfaces_with_random_port(self): """Due to a design decision in asyncio, listening on `("", 0)` will result in two different random ports being used (one for IPV4, one for IPV6), rather than both interfaces sharing the same random port. We work around this here. See https://bugs.python.org/issue45693 for more info.""" loop = asyncio.get_running_loop() # Typically resolves to list with length == 2 (one IPV4, one IPV6). infos = await loop.getaddrinfo( None, 0, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM, flags=socket.AI_PASSIVE, proto=0, ) # Sort infos to always bind ipv4 before ipv6 infos = sorted(infos, key=lambda x: x[0].name) # This code is a simplified and modified version of that found in # cpython here: # https://github.com/python/cpython/blob/401272e6e660445d6556d5cd4db88ed4267a50b3/Lib/asyncio/base_events.py#L1439 servers = [] port = None try: for res in infos: af, socktype, proto, canonname, sa = res try: sock = socket.socket(af, socktype, proto) except OSError: # Assume it's a bad family/type/protocol combination. continue # Disable IPv4/IPv6 dual stack support (enabled by # default on Linux) which makes a single socket # listen on both address families. if af == getattr(socket, "AF_INET6", None) and hasattr( socket, "IPPROTO_IPV6" ): sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, True) # If random port is already chosen, reuse it if port is not None: sa = (sa[0], port, *sa[2:]) try: sock.bind(sa) except OSError as err: raise OSError( err.errno, "error while attempting " "to bind on address %r: %s" % (sa, err.strerror.lower()), ) from None # If random port hadn't already been chosen, cache this port to # reuse for other interfaces if port is None: port = sock.getsockname()[1] # Create a new server for the socket server = await loop.create_server( lambda: DaskCommProtocol(self._on_connection), sock=sock, **self._extra_kwargs, ) servers.append(server) sock = None except BaseException: # Close all opened servers for server in servers: server.close() # If a socket was already created but not converted to a server # yet, close that as well. if sock is not None: sock.close() raise return servers async def start(self): loop = asyncio.get_running_loop() if not self.ip and not self.port: servers = await self._start_all_interfaces_with_random_port() else: servers = [ await loop.create_server( lambda: DaskCommProtocol(self._on_connection), host=self.ip, port=self.port, **self._extra_kwargs, ) ] self._servers = servers def stop(self): # Stop listening for server in self._servers: server.close() def get_host_port(self): """ The listening address as a (host, port) tuple. """ if self.bound_address is None: def get_socket(server): for family in [socket.AF_INET, socket.AF_INET6]: for sock in server.sockets: if sock.family == family: return sock raise RuntimeError("No active INET socket found?") sock = get_socket(self._servers[0]) self.bound_address = sock.getsockname()[:2] return self.bound_address @property def listen_address(self): """ The listening address as a string. """ return self.prefix + unparse_host_port(*self.get_host_port()) @property def contact_address(self): """ The contact address as a string. """ host, port = self.get_host_port() host = ensure_concrete_host(host, default_host=self.default_host) return self.prefix + unparse_host_port(host, port) class TLSListener(TCPListener): prefix = "tls://" comm_class = TLS def _get_extra_kwargs(self, address, **kwargs): ctx = _expect_tls_context(kwargs) return {"ssl": ctx} class TCPBackend(Backend): _connector_class = TCPConnector _listener_class = TCPListener def get_connector(self): return self._connector_class() def get_listener(self, loc, handle_comm, deserialize, **connection_args): return self._listener_class(loc, handle_comm, deserialize, **connection_args) def get_address_host(self, loc): return parse_host_port(loc)[0] def get_address_host_port(self, loc): return parse_host_port(loc) def resolve_address(self, loc): host, port = parse_host_port(loc) return unparse_host_port(ensure_ip(host), port) def get_local_address_for(self, loc): host, port = parse_host_port(loc) host = ensure_ip(host) if ":" in host: local_host = get_ipv6(host) else: local_host = get_ip(host) return unparse_host_port(local_host, None) class TLSBackend(TCPBackend): _connector_class = TLSConnector _listener_class = TLSListener # This class is based on parts of `asyncio.selector_events._SelectorSocketTransport` # (https://github.com/python/cpython/blob/dc4a212bd305831cb4b187a2e0cc82666fcb15ca/Lib/asyncio/selector_events.py#L757). class _ZeroCopyWriter: """The builtin socket transport in asyncio makes a bunch of copies, which can make sending large amounts of data much slower. This hacks around that. Note that this workaround isn't used with the windows ProactorEventLoop or uvloop.""" # We use sendmsg for scatter IO if it's available. Since bookkeeping # scatter IO has a small cost, we want to minimize the amount of processing # we do for each send call. We assume the system send buffer is < 4 MiB # (which would be very large), and set a limit on the number of buffers to # pass to sendmsg. if hasattr(socket.socket, "sendmsg"): # Note: WINDOWS constant doesn't work with `mypy --platform win32` if sys.platform == "win32": SENDMSG_MAX_COUNT = 16 # No os.sysconf available else: try: SENDMSG_MAX_COUNT = os.sysconf("SC_IOV_MAX") except Exception: SENDMSG_MAX_COUNT = 16 # Should be supported on all systems else: SENDMSG_MAX_COUNT = 1 # sendmsg not supported, use send instead def __init__(self, protocol, transport): self.protocol = protocol self.transport = transport self._loop = asyncio.get_running_loop() # This class mucks with the builtin asyncio transport's internals. # Check that the bits we touch still exist. for attr in [ "_sock", "_sock_fd", "_fatal_error", "_eof", "_closing", "_conn_lost", "_call_connection_lost", ]: assert hasattr(transport, attr) # Likewise, this calls a few internal methods of `loop`, ensure they # still exist. for attr in ["_add_writer", "_remove_writer"]: assert hasattr(self._loop, attr) # A deque of buffers to send self._buffers: collections.deque[memoryview] = collections.deque() # The total size of all bytes left to send in _buffers self._size = 0 # Is the backing protocol paused? self._protocol_paused = False # Initialize the buffer limits self.set_write_buffer_limits() def set_write_buffer_limits( self, high: int | None = None, low: int | None = None, ) -> None: """Set the write buffer limits""" # Copied almost verbatim from asyncio.transports._FlowControlMixin if high is None: if low is None: high = 64 * 1024 # 64 KiB else: high = 4 * low if low is None: low = high // 4 self._high_water = high self._low_water = low self._maybe_pause_protocol() def _maybe_pause_protocol(self): """If the high water mark has been reached, pause the protocol""" if not self._protocol_paused and self._size > self._high_water: self._protocol_paused = True self.protocol.pause_writing() def _maybe_resume_protocol(self): """If the low water mark has been reached, unpause the protocol""" if self._protocol_paused and self._size <= self._low_water: self._protocol_paused = False self.protocol.resume_writing() def _buffer_clear(self): """Clear the send buffer""" self._buffers.clear() self._size = 0 def _buffer_append(self, data: bytes) -> None: """Append new data to the send buffer""" mv = ensure_memoryview(data) self._size += len(mv) self._buffers.append(mv) def _buffer_peek(self) -> list[memoryview]: """Get one or more buffers to write to the socket""" return list(islice(self._buffers, self.SENDMSG_MAX_COUNT)) def _buffer_advance(self, size: int) -> None: """Advance the buffer index forward by `size`""" self._size -= size buffers = self._buffers while size: b = buffers[0] b_len = len(b) if b_len <= size: buffers.popleft() size -= b_len else: buffers[0] = b[size:] break def write(self, data: bytes) -> None: # Copied almost verbatim from asyncio.selector_events._SelectorSocketTransport transport = self.transport if transport._eof: raise RuntimeError("Cannot call write() after write_eof()") if not data: return if transport._conn_lost: return if not self._buffers: try: n = transport._sock.send(data) except (BlockingIOError, InterruptedError): pass except (SystemExit, KeyboardInterrupt): raise except BaseException as exc: transport._fatal_error(exc, "Fatal write error on socket transport") return else: data = data[n:] if not data: return # Not all was written; register write handler. self._loop._add_writer(transport._sock_fd, self._on_write_ready) # Add it to the buffer. self._buffer_append(data) self._maybe_pause_protocol() def writelines(self, buffers: list[bytes]) -> None: # Based on modified version of `write` above waiting = bool(self._buffers) for b in buffers: self._buffer_append(b) if not waiting: try: self._do_bulk_write() except (BlockingIOError, InterruptedError): pass except (SystemExit, KeyboardInterrupt): raise except BaseException as exc: self.transport._fatal_error( exc, "Fatal write error on socket transport" ) return if not self._buffers: return # Not all was written; register write handler. self._loop._add_writer(self.transport._sock_fd, self._on_write_ready) self._maybe_pause_protocol() def close(self) -> None: self._buffer_clear() return self.transport.close() def abort(self) -> None: self._buffer_clear() return self.transport.abort() def get_extra_info(self, key: str) -> Any: return self.transport.get_extra_info(key) def _do_bulk_write(self) -> None: buffers = self._buffer_peek() if len(buffers) == 1: n = self.transport._sock.send(buffers[0]) else: n = self.transport._sock.sendmsg(buffers) self._buffer_advance(n) def _on_write_ready(self) -> None: # Copied almost verbatim from asyncio.selector_events._SelectorSocketTransport transport = self.transport if transport._conn_lost: return try: self._do_bulk_write() except (BlockingIOError, InterruptedError): pass except (SystemExit, KeyboardInterrupt): raise except BaseException as exc: self._loop._remove_writer(transport._sock_fd) self._buffers.clear() transport._fatal_error(exc, "Fatal write error on socket transport") else: self._maybe_resume_protocol() if not self._buffers: self._loop._remove_writer(transport._sock_fd) if transport._closing: transport._call_connection_lost(None) elif transport._eof: transport._sock.shutdown(socket.SHUT_WR)
bsd-3-clause
67e2e247e7cad8ef3e48f4400da2b26c
34.003071
122
0.575268
4.307053
false
false
false
false
scikit-optimize/scikit-optimize
skopt/sampler/grid.py
1
6250
""" Inspired by https://github.com/jonathf/chaospy/blob/master/chaospy/ distributions/sampler/sequences/grid.py """ import numpy as np from .base import InitialPointGenerator from ..space import Space from sklearn.utils import check_random_state def _quadrature_combine(args): args = [np.asarray(arg).reshape(len(arg), -1) for arg in args] shapes = [arg.shape for arg in args] size = np.prod(shapes, 0)[0] * np.sum(shapes, 0)[1] if size > 10 ** 9: raise MemoryError("Too large sets") out = args[0] for arg in args[1:]: out = np.hstack([ np.tile(out, len(arg)).reshape(-1, out.shape[1]), np.tile(arg.T, len(out)).reshape(arg.shape[1], -1).T, ]) return out def _create_uniform_grid_exclude_border(n_dim, order): assert order > 0 assert n_dim > 0 x_data = np.arange(1, order + 1) / (order + 1.) x_data = _quadrature_combine([x_data] * n_dim) return x_data def _create_uniform_grid_include_border(n_dim, order): assert order > 1 assert n_dim > 0 x_data = np.arange(0, order) / (order - 1.) x_data = _quadrature_combine([x_data] * n_dim) return x_data def _create_uniform_grid_only_border(n_dim, order): assert n_dim > 0 assert order > 1 x = [[0., 1.]] * (n_dim - 1) x.append(list(np.arange(0, order) / (order - 1.))) x_data = _quadrature_combine(x) return x_data class Grid(InitialPointGenerator): """Generate samples from a regular grid. Parameters ---------- border : str, default='exclude' defines how the samples are generated: - 'include' : Includes the border into the grid layout - 'exclude' : Excludes the border from the grid layout - 'only' : Selects only points at the border of the dimension use_full_layout : boolean, default=True When True, a full factorial design is generated and missing points are taken from the next larger full factorial design, depending on `append_border` When False, the next larger full factorial design is generated and points are randomly selected from it. append_border : str, default="only" When use_full_layout is True, this parameter defines how the missing points will be generated from the next larger grid layout: - 'include' : Includes the border into the grid layout - 'exclude' : Excludes the border from the grid layout - 'only' : Selects only points at the border of the dimension """ def __init__(self, border="exclude", use_full_layout=True, append_border="only"): self.border = border self.use_full_layout = use_full_layout self.append_border = append_border def generate(self, dimensions, n_samples, random_state=None): """Creates samples from a regular grid. Parameters ---------- dimensions : list, shape (n_dims,) List of search space dimensions. Each search dimension can be defined either as - a `(lower_bound, upper_bound)` tuple (for `Real` or `Integer` dimensions), - a `(lower_bound, upper_bound, "prior")` tuple (for `Real` dimensions), - as a list of categories (for `Categorical` dimensions), or - an instance of a `Dimension` object (`Real`, `Integer` or `Categorical`). n_samples : int The order of the Halton sequence. Defines the number of samples. random_state : int, RandomState instance, or None (default) Set random state to something other than None for reproducible results. Returns ------- np.array, shape=(n_dim, n_samples) grid set """ rng = check_random_state(random_state) space = Space(dimensions) n_dim = space.n_dims transformer = space.get_transformer() space.set_transformer("normalize") if self.border == "include": if self.use_full_layout: order = int(np.floor(np.sqrt(n_samples))) else: order = int(np.ceil(np.sqrt(n_samples))) if order < 2: order = 2 h = _create_uniform_grid_include_border(n_dim, order) elif self.border == "exclude": if self.use_full_layout: order = int(np.floor(np.sqrt(n_samples))) else: order = int(np.ceil(np.sqrt(n_samples))) if order < 1: order = 1 h = _create_uniform_grid_exclude_border(n_dim, order) elif self.border == "only": if self.use_full_layout: order = int(np.floor(n_samples / 2.)) else: order = int(np.ceil(n_samples / 2.)) if order < 2: order = 2 h = _create_uniform_grid_exclude_border(n_dim, order) else: raise ValueError("Wrong value for border") if np.size(h, 0) > n_samples: rng.shuffle(h) h = h[:n_samples, :] elif np.size(h, 0) < n_samples: if self.append_border == "only": order = int(np.ceil((n_samples - np.size(h, 0)) / 2.)) if order < 2: order = 2 h2 = _create_uniform_grid_only_border(n_dim, order) elif self.append_border == "include": order = int(np.ceil(np.sqrt(n_samples - np.size(h, 0)))) if order < 2: order = 2 h2 = _create_uniform_grid_include_border(n_dim, order) elif self.append_border == "exclude": order = int(np.ceil(np.sqrt(n_samples - np.size(h, 0)))) if order < 1: order = 1 h2 = _create_uniform_grid_exclude_border(n_dim, order) else: raise ValueError("Wrong value for append_border") h = np.vstack((h, h2[:(n_samples - np.size(h, 0))])) rng.shuffle(h) else: rng.shuffle(h) h = space.inverse_transform(h) space.set_transformer(transformer) return h
bsd-3-clause
9291273adf04e3c0f13097b60fbde9c7
35.764706
76
0.55952
3.832005
false
false
false
false
dask/distributed
distributed/protocol/utils.py
1
6102
from __future__ import annotations import ctypes import struct from collections.abc import Sequence import dask from distributed.utils import nbytes BIG_BYTES_SHARD_SIZE = dask.utils.parse_bytes(dask.config.get("distributed.comm.shard")) msgpack_opts = { ("max_%s_len" % x): 2**31 - 1 for x in ["str", "bin", "array", "map", "ext"] } msgpack_opts["strict_map_key"] = False msgpack_opts["raw"] = False def frame_split_size( frame: bytes | memoryview, n: int = BIG_BYTES_SHARD_SIZE ) -> list[memoryview]: """ Split a frame into a list of frames of maximum size This helps us to avoid passing around very large bytestrings. Examples -------- >>> frame_split_size([b'12345', b'678'], n=3) # doctest: +SKIP [b'123', b'45', b'678'] """ n = n or BIG_BYTES_SHARD_SIZE frame = memoryview(frame) if frame.nbytes <= n: return [frame] nitems = frame.nbytes // frame.itemsize items_per_shard = n // frame.itemsize return [frame[i : i + items_per_shard] for i in range(0, nitems, items_per_shard)] def pack_frames_prelude(frames): nframes = len(frames) nbytes_frames = map(nbytes, frames) return struct.pack(f"Q{nframes}Q", nframes, *nbytes_frames) def pack_frames(frames): """Pack frames into a byte-like object This prepends length information to the front of the bytes-like object See Also -------- unpack_frames """ return b"".join([pack_frames_prelude(frames), *frames]) def unpack_frames(b): """Unpack bytes into a sequence of frames This assumes that length information is at the front of the bytestring, as performed by pack_frames See Also -------- pack_frames """ b = memoryview(b) fmt = "Q" fmt_size = struct.calcsize(fmt) (n_frames,) = struct.unpack_from(fmt, b) lengths = struct.unpack_from(f"{n_frames}{fmt}", b, fmt_size) frames = [] start = fmt_size * (1 + n_frames) for length in lengths: end = start + length frames.append(b[start:end]) start = end return frames def merge_memoryviews(mvs: Sequence[memoryview]) -> memoryview: """ Zero-copy "concatenate" a sequence of contiguous memoryviews. Returns a new memoryview which slices into the underlying buffer to extract out the portion equivalent to all of ``mvs`` being concatenated. All the memoryviews must: * Share the same underlying buffer (``.obj``) * When merged, cover a continuous portion of that buffer with no gaps * Have the same strides * Be 1-dimensional * Have the same format * Be contiguous Raises ValueError if these conditions are not met. """ if not mvs: return memoryview(bytearray()) if len(mvs) == 1: return mvs[0] first = mvs[0] if not isinstance(first, memoryview): raise TypeError(f"Expected memoryview; got {type(first)}") obj = first.obj format = first.format first_start_addr = 0 nbytes = 0 for i, mv in enumerate(mvs): if not isinstance(mv, memoryview): raise TypeError(f"{i}: expected memoryview; got {type(mv)}") if mv.nbytes == 0: continue if mv.obj is not obj: raise ValueError( f"{i}: memoryview has different buffer: {mv.obj!r} vs {obj!r}" ) if not mv.contiguous: raise ValueError(f"{i}: memoryview non-contiguous") if mv.ndim != 1: raise ValueError(f"{i}: memoryview has {mv.ndim} dimensions, not 1") if mv.format != format: raise ValueError(f"{i}: inconsistent format: {mv.format} vs {format}") start_addr = address_of_memoryview(mv) if first_start_addr == 0: first_start_addr = start_addr else: expected_addr = first_start_addr + nbytes if start_addr != expected_addr: raise ValueError( f"memoryview {i} does not start where the previous ends. " f"Expected {expected_addr:x}, starts {start_addr - expected_addr} byte(s) away." ) nbytes += mv.nbytes if nbytes == 0: # all memoryviews were zero-length assert len(first) == 0 return first assert first_start_addr != 0, "Underlying buffer is null pointer?!" base_mv = memoryview(obj).cast("B") base_start_addr = address_of_memoryview(base_mv) start_index = first_start_addr - base_start_addr return base_mv[start_index : start_index + nbytes].cast(format) one_byte_carr = ctypes.c_byte * 1 # ^ length and type don't matter, just use it to get the address of the first byte def address_of_memoryview(mv: memoryview) -> int: """ Get the pointer to the first byte of a memoryview's data. If the memoryview is read-only, NumPy must be installed. """ # NOTE: this method relies on pointer arithmetic to figure out # where each memoryview starts within the underlying buffer. # There's no direct API to get the address of a memoryview, # so we use a trick through ctypes and the buffer protocol: # https://mattgwwalker.wordpress.com/2020/10/15/address-of-a-buffer-in-python/ try: carr = one_byte_carr.from_buffer(mv) except TypeError: # `mv` is read-only. `from_buffer` requires the buffer to be writeable. # See https://bugs.python.org/issue11427 for discussion. # This typically comes from `deserialize_bytes`, where `mv.obj` is an # immutable bytestring. pass else: return ctypes.addressof(carr) try: import numpy as np except ImportError: raise ValueError( f"Cannot get address of read-only memoryview {mv} since NumPy is not installed." ) # NumPy doesn't mind read-only buffers. We could just use this method # for all cases, but it's nice to use the pure-Python method for the common # case of writeable buffers (created by TCP comms, for example). return np.asarray(mv).__array_interface__["data"][0]
bsd-3-clause
13fcbd67b33d0159c0bf9006c54020cd
29.207921
100
0.628319
3.816135
false
false
false
false
dask/distributed
distributed/comm/tcp.py
1
24496
from __future__ import annotations import asyncio import ctypes import errno import functools import logging import socket import ssl import struct import sys import weakref from ssl import SSLCertVerificationError, SSLError from typing import Any, ClassVar from tlz import sliding_window from tornado import gen, netutil from tornado.iostream import IOStream, StreamClosedError from tornado.tcpclient import TCPClient from tornado.tcpserver import TCPServer import dask from dask.utils import parse_timedelta from distributed.comm.addressing import parse_host_port, unparse_host_port from distributed.comm.core import ( Comm, CommClosedError, Connector, FatalCommClosedError, Listener, ) from distributed.comm.registry import Backend from distributed.comm.utils import ( ensure_concrete_host, from_frames, get_tcp_server_address, host_array, to_frames, ) from distributed.protocol.utils import pack_frames_prelude, unpack_frames from distributed.system import MEMORY_LIMIT from distributed.utils import ensure_ip, ensure_memoryview, get_ip, get_ipv6, nbytes logger = logging.getLogger(__name__) # Workaround for OpenSSL 1.0.2. # Can drop with OpenSSL 1.1.1 used by Python 3.10+. # ref: https://bugs.python.org/issue42853 if sys.version_info < (3, 10): OPENSSL_MAX_CHUNKSIZE = 256 ** ctypes.sizeof(ctypes.c_int) // 2 - 1 else: OPENSSL_MAX_CHUNKSIZE = 256 ** ctypes.sizeof(ctypes.c_size_t) - 1 MAX_BUFFER_SIZE = MEMORY_LIMIT / 2 def set_tcp_timeout(comm): """ Set kernel-level TCP timeout on the stream. """ if comm.closed(): return timeout = dask.config.get("distributed.comm.timeouts.tcp") timeout = int(parse_timedelta(timeout, default="seconds")) sock = comm.socket # Default (unsettable) value on Windows # https://msdn.microsoft.com/en-us/library/windows/desktop/dd877220(v=vs.85).aspx nprobes = 10 assert timeout >= nprobes + 1, "Timeout too low" idle = max(2, timeout // 4) interval = max(1, (timeout - idle) // nprobes) idle = timeout - interval * nprobes assert idle > 0 try: if sys.platform.startswith("win"): logger.debug("Setting TCP keepalive: idle=%d, interval=%d", idle, interval) sock.ioctl(socket.SIO_KEEPALIVE_VALS, (1, idle * 1000, interval * 1000)) else: sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) try: TCP_KEEPIDLE = socket.TCP_KEEPIDLE TCP_KEEPINTVL = socket.TCP_KEEPINTVL TCP_KEEPCNT = socket.TCP_KEEPCNT except AttributeError: if sys.platform == "darwin": TCP_KEEPIDLE = 0x10 # (named "TCP_KEEPALIVE" in C) TCP_KEEPINTVL = 0x101 TCP_KEEPCNT = 0x102 else: TCP_KEEPIDLE = None if TCP_KEEPIDLE is not None: logger.debug( "Setting TCP keepalive: nprobes=%d, idle=%d, interval=%d", nprobes, idle, interval, ) sock.setsockopt(socket.SOL_TCP, TCP_KEEPCNT, nprobes) sock.setsockopt(socket.SOL_TCP, TCP_KEEPIDLE, idle) sock.setsockopt(socket.SOL_TCP, TCP_KEEPINTVL, interval) if sys.platform.startswith("linux"): logger.debug("Setting TCP user timeout: %d ms", timeout * 1000) TCP_USER_TIMEOUT = 18 # since Linux 2.6.37 sock.setsockopt(socket.SOL_TCP, TCP_USER_TIMEOUT, timeout * 1000) except OSError: logger.exception("Could not set timeout on TCP stream.") def get_stream_address(comm): """ Get a stream's local address. """ if comm.closed(): return "<closed>" try: return unparse_host_port(*comm.socket.getsockname()[:2]) except OSError: # Probably EBADF return "<closed>" def convert_stream_closed_error(obj, exc): """ Re-raise StreamClosedError as CommClosedError. """ if exc.real_error is not None: # The stream was closed because of an underlying OS error exc = exc.real_error if isinstance(exc, ssl.SSLError): if exc.reason and "UNKNOWN_CA" in exc.reason: raise FatalCommClosedError(f"in {obj}: {exc.__class__.__name__}: {exc}") raise CommClosedError(f"in {obj}: {exc.__class__.__name__}: {exc}") from exc else: raise CommClosedError(f"in {obj}: {exc}") from exc def _close_comm(ref): """Callback to close Dask Comm when Tornado Stream closes Parameters ---------- ref: weak reference to a Dask comm """ comm = ref() if comm: comm._closed = True class TCP(Comm): """ An established communication based on an underlying Tornado IOStream. """ max_shard_size: ClassVar[int] = dask.utils.parse_bytes( dask.config.get("distributed.comm.shard") ) stream: IOStream | None def __init__( self, stream: IOStream, local_addr: str, peer_addr: str, deserialize: bool = True, ): self._closed = False super().__init__(deserialize=deserialize) self._local_addr = local_addr self._peer_addr = peer_addr self.stream = stream self._finalizer = weakref.finalize(self, self._get_finalizer()) self._finalizer.atexit = False self._extra: dict = {} ref = weakref.ref(self) stream.set_close_callback(functools.partial(_close_comm, ref)) stream.set_nodelay(True) set_tcp_timeout(stream) self._read_extra() def _read_extra(self): pass def _get_finalizer(self): r = repr(self) def finalize(stream=self.stream, r=r): # stream is None if a StreamClosedError is raised during interpreter # shutdown if stream is not None and not stream.closed(): logger.warning(f"Closing dangling stream in {r}") stream.close() return finalize @property def local_address(self) -> str: return self._local_addr @property def peer_address(self) -> str: return self._peer_addr async def read(self, deserializers=None): stream = self.stream if stream is None: raise CommClosedError() fmt = "Q" fmt_size = struct.calcsize(fmt) try: frames_nbytes = await stream.read_bytes(fmt_size) (frames_nbytes,) = struct.unpack(fmt, frames_nbytes) frames = host_array(frames_nbytes) for i, j in sliding_window( 2, range(0, frames_nbytes + OPENSSL_MAX_CHUNKSIZE, OPENSSL_MAX_CHUNKSIZE), ): chunk = frames[i:j] chunk_nbytes = chunk.nbytes n = await stream.read_into(chunk) assert n == chunk_nbytes, (n, chunk_nbytes) except StreamClosedError as e: self.stream = None self._closed = True if not sys.is_finalizing(): convert_stream_closed_error(self, e) except BaseException: # Some OSError, CancelledError or a another "low-level" exception. # We do not really know what was already read from the underlying # socket, so it is not even safe to retry here using the same stream. # The only safe thing to do is to abort. # (See also GitHub #4133, #6548). self.abort() raise else: try: frames = unpack_frames(frames) msg = await from_frames( frames, deserialize=self.deserialize, deserializers=deserializers, allow_offload=self.allow_offload, ) except EOFError: # Frames possibly garbled or truncated by communication error self.abort() raise CommClosedError("aborted stream on truncated data") return msg async def write(self, msg, serializers=None, on_error="message"): stream = self.stream if stream is None: raise CommClosedError() frames = await to_frames( msg, allow_offload=self.allow_offload, serializers=serializers, on_error=on_error, context={ "sender": self.local_info, "recipient": self.remote_info, **self.handshake_options, }, frame_split_size=self.max_shard_size, ) frames_nbytes = [nbytes(f) for f in frames] frames_nbytes_total = sum(frames_nbytes) header = pack_frames_prelude(frames) header = struct.pack("Q", nbytes(header) + frames_nbytes_total) + header frames = [header, *frames] frames_nbytes = [nbytes(header), *frames_nbytes] frames_nbytes_total += frames_nbytes[0] if frames_nbytes_total < 2**17: # 128kiB # small enough, send in one go frames = [b"".join(frames)] frames_nbytes = [frames_nbytes_total] try: # trick to enque all frames for writing beforehand for each_frame_nbytes, each_frame in zip(frames_nbytes, frames): if each_frame_nbytes: # Make sure that `len(data) == data.nbytes` # See <https://github.com/tornadoweb/tornado/pull/2996> each_frame = ensure_memoryview(each_frame) for i, j in sliding_window( 2, range( 0, each_frame_nbytes + OPENSSL_MAX_CHUNKSIZE, OPENSSL_MAX_CHUNKSIZE, ), ): chunk = each_frame[i:j] chunk_nbytes = chunk.nbytes if stream._write_buffer is None: raise StreamClosedError() stream._write_buffer.append(chunk) stream._total_write_index += chunk_nbytes # start writing frames stream.write(b"") except StreamClosedError as e: self.stream = None self._closed = True if not sys.is_finalizing(): convert_stream_closed_error(self, e) except BaseException: # Some OSError or a another "low-level" exception. We do not really know # what was already written to the underlying socket, so it is not even safe # to retry here using the same stream. The only safe thing to do is to # abort. (See also GitHub #4133). # In case of, for instance, KeyboardInterrupts or other # BaseExceptions that could be handled further upstream, we equally # want to discard this comm self.abort() raise return frames_nbytes_total @gen.coroutine def close(self): # We use gen.coroutine here rather than async def to avoid errors like # Task was destroyed but it is pending! # Triggered by distributed.deploy.tests.test_local::test_silent_startup stream, self.stream = self.stream, None self._closed = True if stream is not None and not stream.closed(): try: # Flush the stream's write buffer by waiting for a last write. if stream.writing(): yield stream.write(b"") stream.socket.shutdown(socket.SHUT_RDWR) except OSError: pass finally: self._finalizer.detach() stream.close() def abort(self) -> None: stream, self.stream = self.stream, None self._closed = True if stream is not None and not stream.closed(): self._finalizer.detach() stream.close() def closed(self) -> bool: return self._closed @property def extra_info(self): return self._extra class TLS(TCP): """ A TLS-specific version of TCP. """ max_shard_size = min(OPENSSL_MAX_CHUNKSIZE, TCP.max_shard_size) def _read_extra(self): TCP._read_extra(self) sock = self.stream.socket if sock is not None: self._extra.update(peercert=sock.getpeercert(), cipher=sock.cipher()) cipher, proto, bits = self._extra["cipher"] logger.debug( "TLS connection with %r: protocol=%s, cipher=%s, bits=%d", self._peer_addr, proto, cipher, bits, ) def _expect_tls_context(connection_args): ctx = connection_args.get("ssl_context") if not isinstance(ctx, ssl.SSLContext): raise TypeError( "TLS expects a `ssl_context` argument of type " "ssl.SSLContext (perhaps check your TLS configuration?)" f" Instead got {ctx!r}" ) return ctx class RequireEncryptionMixin: def _check_encryption(self, address, connection_args): if not self.encrypted and connection_args.get("require_encryption"): # XXX Should we have a dedicated SecurityError class? raise RuntimeError( "encryption required by Dask configuration, " "refusing communication from/to %r" % (self.prefix + address,) ) _NUMERIC_ONLY = socket.AI_NUMERICHOST | socket.AI_NUMERICSERV async def _getaddrinfo(host, port, *, family, type=socket.SOCK_STREAM): # On Python3.8 we are observing problems, particularly on slow systems # For additional info, see # https://github.com/dask/distributed/pull/6847#issuecomment-1208179864 # https://github.com/dask/distributed/pull/6847 # https://github.com/dask/distributed/issues/6896 # https://github.com/dask/distributed/issues/6846 if sys.version_info >= (3, 9): # If host and port are numeric, then getaddrinfo doesn't block and we # can skip get_running_loop().getaddrinfo which is implemented by # running in a ThreadPoolExecutor. So we try first with the # _NUMERIC_ONLY flags set, and then only use the threadpool if that # fails with EAI_NONAME: try: return socket.getaddrinfo( host, port, family=family, type=type, flags=_NUMERIC_ONLY, ) except socket.gaierror as e: if e.errno != socket.EAI_NONAME: raise # That failed; it's a real hostname. We better use a thread. return await asyncio.get_running_loop().getaddrinfo( host, port, family=family, type=socket.SOCK_STREAM ) class _DefaultLoopResolver(netutil.Resolver): """ Resolver implementation using `asyncio.loop.getaddrinfo`. backport from Tornado 6.2+ https://github.com/tornadoweb/tornado/blob/3de78b7a15ba7134917a18b0755ea24d7f8fde94/tornado/netutil.py#L416-L432 With an additional optimization based on https://github.com/python-trio/trio/blob/4edfd41bd5519a2e626e87f6c6ca9fb32b90a6f4/trio/_socket.py#L125-L192 (Copyright Contributors to the Trio project.) And proposed to cpython in https://github.com/python/cpython/pull/31497/ """ async def resolve( self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC ) -> list[tuple[int, Any]]: # On Solaris, getaddrinfo fails if the given port is not found # in /etc/services and no socket type is given, so we must pass # one here. The socket type used here doesn't seem to actually # matter (we discard the one we get back in the results), # so the addresses we return should still be usable with SOCK_DGRAM. return [ (fam, address) for fam, _, _, _, address in await _getaddrinfo( host, port, family=family, type=socket.SOCK_STREAM ) ] class BaseTCPConnector(Connector, RequireEncryptionMixin): client: ClassVar[TCPClient] = TCPClient(resolver=_DefaultLoopResolver()) async def connect(self, address, deserialize=True, **connection_args): self._check_encryption(address, connection_args) ip, port = parse_host_port(address) kwargs = self._get_connect_args(**connection_args) try: # server_hostname option (for SNI) only works with tornado.iostream.IOStream if "server_hostname" in kwargs: stream = await self.client.connect( ip, port, max_buffer_size=MAX_BUFFER_SIZE ) stream = await stream.start_tls(False, **kwargs) else: stream = await self.client.connect( ip, port, max_buffer_size=MAX_BUFFER_SIZE, **kwargs ) # Under certain circumstances tornado will have a closed connection with an # error and not raise a StreamClosedError. # # This occurs with tornado 5.x and openssl 1.1+ if stream.closed() and stream.error: raise StreamClosedError(stream.error) except StreamClosedError as e: # The socket connect() call failed convert_stream_closed_error(self, e) except SSLCertVerificationError as err: raise FatalCommClosedError( "TLS certificate does not match. Check your security settings. " "More info at https://distributed.dask.org/en/latest/tls.html" ) from err except SSLError as err: raise FatalCommClosedError() from err local_address = self.prefix + get_stream_address(stream) comm = self.comm_class( stream, local_address, self.prefix + address, deserialize ) return comm class TCPConnector(BaseTCPConnector): prefix = "tcp://" comm_class = TCP encrypted = False def _get_connect_args(self, **connection_args): return {} class TLSConnector(BaseTCPConnector): prefix = "tls://" comm_class = TLS encrypted = True def _get_connect_args(self, **connection_args): tls_args = {"ssl_options": _expect_tls_context(connection_args)} if connection_args.get("server_hostname"): tls_args["server_hostname"] = connection_args["server_hostname"] return tls_args class BaseTCPListener(Listener, RequireEncryptionMixin): def __init__( self, address, comm_handler, deserialize=True, allow_offload=True, default_host=None, default_port=0, **connection_args, ): self._check_encryption(address, connection_args) self.ip, self.port = parse_host_port(address, default_port) self.default_host = default_host self.comm_handler = comm_handler self.deserialize = deserialize self.allow_offload = allow_offload self.server_args = self._get_server_args(**connection_args) self.tcp_server = None self.bound_address = None async def start(self): self.tcp_server = TCPServer(max_buffer_size=MAX_BUFFER_SIZE, **self.server_args) self.tcp_server.handle_stream = self._handle_stream backlog = int(dask.config.get("distributed.comm.socket-backlog")) for _ in range(5): try: # When shuffling data between workers, there can # really be O(cluster size) connection requests # on a single worker socket, make sure the backlog # is large enough not to lose any. sockets = netutil.bind_sockets( self.port, address=self.ip, backlog=backlog ) except OSError as e: # EADDRINUSE can happen sporadically when trying to bind # to an ephemeral port if self.port != 0 or e.errno != errno.EADDRINUSE: raise exc = e else: self.tcp_server.add_sockets(sockets) break else: raise exc self.get_host_port() # trigger assignment to self.bound_address def stop(self): tcp_server, self.tcp_server = self.tcp_server, None if tcp_server is not None: tcp_server.stop() def _check_started(self): if self.tcp_server is None: raise ValueError("invalid operation on non-started TCPListener") async def _handle_stream(self, stream, address): address = self.prefix + unparse_host_port(*address[:2]) stream = await self._prepare_stream(stream, address) if stream is None: # Preparation failed return logger.debug("Incoming connection from %r to %r", address, self.contact_address) local_address = self.prefix + get_stream_address(stream) comm = self.comm_class(stream, local_address, address, self.deserialize) comm.allow_offload = self.allow_offload try: await self.on_connection(comm) except CommClosedError: logger.info("Connection from %s closed before handshake completed", address) return await self.comm_handler(comm) def get_host_port(self): """ The listening address as a (host, port) tuple. """ self._check_started() if self.bound_address is None: self.bound_address = get_tcp_server_address(self.tcp_server) # IPv6 getsockname() can return more a 4-len tuple return self.bound_address[:2] @property def listen_address(self): """ The listening address as a string. """ return self.prefix + unparse_host_port(*self.get_host_port()) @property def contact_address(self): """ The contact address as a string. """ host, port = self.get_host_port() host = ensure_concrete_host(host, default_host=self.default_host) return self.prefix + unparse_host_port(host, port) class TCPListener(BaseTCPListener): prefix = "tcp://" comm_class = TCP encrypted = False def _get_server_args(self, **connection_args): return {} async def _prepare_stream(self, stream, address): return stream class TLSListener(BaseTCPListener): prefix = "tls://" comm_class = TLS encrypted = True def _get_server_args(self, **connection_args): ctx = _expect_tls_context(connection_args) return {"ssl_options": ctx} async def _prepare_stream(self, stream, address): try: await stream.wait_for_handshake() except OSError as e: # The handshake went wrong, log and ignore logger.warning( "Listener on %r: TLS handshake failed with remote %r: %s", self.listen_address, address, getattr(e, "real_error", None) or e, ) else: return stream class BaseTCPBackend(Backend): # I/O def get_connector(self): return self._connector_class() def get_listener(self, loc, handle_comm, deserialize, **connection_args): return self._listener_class(loc, handle_comm, deserialize, **connection_args) # Address handling def get_address_host(self, loc): return parse_host_port(loc)[0] def get_address_host_port(self, loc): return parse_host_port(loc) def resolve_address(self, loc): host, port = parse_host_port(loc) return unparse_host_port(ensure_ip(host), port) def get_local_address_for(self, loc): host, port = parse_host_port(loc) host = ensure_ip(host) if ":" in host: local_host = get_ipv6(host) else: local_host = get_ip(host) return unparse_host_port(local_host, None) class TCPBackend(BaseTCPBackend): _connector_class = TCPConnector _listener_class = TCPListener class TLSBackend(BaseTCPBackend): _connector_class = TLSConnector _listener_class = TLSListener
bsd-3-clause
6b9ab267e92e8281bb2cf6e21af01e70
32.694635
116
0.588504
4.117667
false
false
false
false
dask/distributed
distributed/deploy/tests/test_old_ssh.py
1
2182
from __future__ import annotations from time import sleep import pytest pytest.importorskip("paramiko") from distributed import Client from distributed.deploy.old_ssh import SSHCluster from distributed.metrics import time @pytest.mark.avoid_ci def test_cluster(loop): with SSHCluster( scheduler_addr="127.0.0.1", scheduler_port=7437, worker_addrs=["127.0.0.1", "127.0.0.1"], ) as c: with Client(c, loop=loop) as e: start = time() while len(e.ncores()) != 2: sleep(0.01) assert time() < start + 5 c.add_worker("127.0.0.1") start = time() while len(e.ncores()) != 3: sleep(0.01) assert time() < start + 5 def test_old_ssh_nprocs_renamed_to_n_workers(): with pytest.warns(FutureWarning, match="renamed to n_workers"): with SSHCluster( scheduler_addr="127.0.0.1", scheduler_port=8687, worker_addrs=["127.0.0.1", "127.0.0.1"], nprocs=2, ) as c: assert c.n_workers == 2 def test_nprocs_attribute_is_deprecated(): with SSHCluster( scheduler_addr="127.0.0.1", scheduler_port=8687, worker_addrs=["127.0.0.1", "127.0.0.1"], ) as c: assert c.n_workers == 1 with pytest.warns(FutureWarning, match="renamed to n_workers"): assert c.nprocs == 1 with pytest.warns(FutureWarning, match="renamed to n_workers"): c.nprocs = 3 assert c.n_workers == 3 def test_old_ssh_n_workers_with_nprocs_is_an_error(): with pytest.raises(ValueError, match="Both nprocs and n_workers"): SSHCluster( scheduler_addr="127.0.0.1", scheduler_port=8687, worker_addrs=(), nprocs=2, n_workers=2, ) def test_extra_kwargs_is_an_error(): with pytest.raises(TypeError, match="unexpected keyword argument"): SSHCluster( scheduler_addr="127.0.0.1", scheduler_port=8687, worker_addrs=["127.0.0.1", "127.0.0.1"], unknown_kwarg=None, )
bsd-3-clause
d31fe00f38c42f6b61531e839d8ced74
26.620253
71
0.55637
3.480064
false
true
false
false
dask/distributed
distributed/deploy/adaptive.py
1
6702
from __future__ import annotations import logging from inspect import isawaitable from tornado.ioloop import IOLoop import dask.config from dask.utils import parse_timedelta from distributed.deploy.adaptive_core import AdaptiveCore from distributed.protocol import pickle from distributed.utils import log_errors logger = logging.getLogger(__name__) class Adaptive(AdaptiveCore): ''' Adaptively allocate workers based on scheduler load. A superclass. Contains logic to dynamically resize a Dask cluster based on current use. This class needs to be paired with a system that can create and destroy Dask workers using a cluster resource manager. Typically it is built into already existing solutions, rather than used directly by users. It is most commonly used from the ``.adapt(...)`` method of various Dask cluster classes. Parameters ---------- cluster: object Must have scale and scale_down methods/coroutines interval : timedelta or str, default "1000 ms" Milliseconds between checks wait_count: int, default 3 Number of consecutive times that a worker should be suggested for removal before we remove it. target_duration: timedelta or str, default "5s" Amount of time we want a computation to take. This affects how aggressively we scale up. worker_key: Callable[WorkerState] Function to group workers together when scaling down See Scheduler.workers_to_close for more information minimum: int Minimum number of workers to keep around maximum: int Maximum number of workers to keep around **kwargs: Extra parameters to pass to Scheduler.workers_to_close Examples -------- This is commonly used from existing Dask classes, like KubeCluster >>> from dask_kubernetes import KubeCluster >>> cluster = KubeCluster() >>> cluster.adapt(minimum=10, maximum=100) Alternatively you can use it from your own Cluster class by subclassing from Dask's Cluster superclass >>> from distributed.deploy import Cluster >>> class MyCluster(Cluster): ... def scale_up(self, n): ... """ Bring worker count up to n """ ... def scale_down(self, workers): ... """ Remove worker addresses from cluster """ >>> cluster = MyCluster() >>> cluster.adapt(minimum=10, maximum=100) Notes ----- Subclasses can override :meth:`Adaptive.target` and :meth:`Adaptive.workers_to_close` to control when the cluster should be resized. The default implementation checks if there are too many tasks per worker or too little memory available (see :meth:`distributed.Scheduler.adaptive_target`). The values for interval, min, max, wait_count and target_duration can be specified in the dask config under the distributed.adaptive key. ''' def __init__( self, cluster=None, interval=None, minimum=None, maximum=None, wait_count=None, target_duration=None, worker_key=None, **kwargs, ): self.cluster = cluster self.worker_key = worker_key self._workers_to_close_kwargs = kwargs if interval is None: interval = dask.config.get("distributed.adaptive.interval") if minimum is None: minimum = dask.config.get("distributed.adaptive.minimum") if maximum is None: maximum = dask.config.get("distributed.adaptive.maximum") if wait_count is None: wait_count = dask.config.get("distributed.adaptive.wait-count") if target_duration is None: target_duration = dask.config.get("distributed.adaptive.target-duration") self.target_duration = parse_timedelta(target_duration) logger.info("Adaptive scaling started: minimum=%s maximum=%s", minimum, maximum) super().__init__( minimum=minimum, maximum=maximum, wait_count=wait_count, interval=interval ) @property def scheduler(self): return self.cluster.scheduler_comm @property def plan(self): return self.cluster.plan @property def requested(self): return self.cluster.requested @property def observed(self): return self.cluster.observed async def target(self): """ Determine target number of workers that should exist. Notes ----- ``Adaptive.target`` dispatches to Scheduler.adaptive_target(), but may be overridden in subclasses. Returns ------- Target number of workers See Also -------- Scheduler.adaptive_target """ return await self.scheduler.adaptive_target( target_duration=self.target_duration ) async def recommendations(self, target: int) -> dict: if len(self.plan) != len(self.requested): # Ensure that the number of planned and requested workers # are in sync before making recommendations. await self.cluster return await super().recommendations(target) async def workers_to_close(self, target: int) -> list[str]: """ Determine which, if any, workers should potentially be removed from the cluster. Notes ----- ``Adaptive.workers_to_close`` dispatches to Scheduler.workers_to_close(), but may be overridden in subclasses. Returns ------- List of worker names to close, if any See Also -------- Scheduler.workers_to_close """ return await self.scheduler.workers_to_close( target=target, key=pickle.dumps(self.worker_key) if self.worker_key else None, attribute="name", **self._workers_to_close_kwargs, ) @log_errors async def scale_down(self, workers): if not workers: return logger.info("Retiring workers %s", workers) # Ask scheduler to cleanly retire workers await self.scheduler.retire_workers( names=workers, remove=True, close_workers=True, ) # close workers more forcefully f = self.cluster.scale_down(workers) if isawaitable(f): await f async def scale_up(self, n): f = self.cluster.scale(n) if isawaitable(f): await f @property def loop(self) -> IOLoop: """Override Adaptive.loop""" if self.cluster: return self.cluster.loop else: return IOLoop.current()
bsd-3-clause
db322c6022c44c4d67081266d2f68bd8
29.884793
88
0.630707
4.54065
false
false
false
false
dask/distributed
distributed/protocol/tests/test_serialize.py
1
16735
from __future__ import annotations import copy import pickle from array import array import msgpack import pytest from tlz import identity try: import numpy as np except ImportError: np = None # type: ignore import dask from distributed import Nanny, wait from distributed.comm.utils import from_frames, to_frames from distributed.protocol import ( Serialize, Serialized, dask_serialize, deserialize, deserialize_bytes, dumps, loads, nested_deserialize, register_serialization, register_serialization_family, serialize, serialize_bytelist, serialize_bytes, to_serialize, ) from distributed.protocol.serialize import check_dask_serializable from distributed.utils import ensure_memoryview, nbytes from distributed.utils_test import NO_AMM, gen_test, inc class MyObj: def __init__(self, data): self.data = data def __getstate__(self): raise Exception("Not picklable") def serialize_myobj(x): return {}, [pickle.dumps(x.data)] def deserialize_myobj(header, frames): return MyObj(pickle.loads(frames[0])) register_serialization(MyObj, serialize_myobj, deserialize_myobj) def test_dumps_serialize(): for x in [123, [1, 2, 3, 4, 5, 6]]: header, frames = serialize(x) assert header["serializer"] == "pickle" assert len(frames) == 1 result = deserialize(header, frames) assert result == x x = MyObj(123) header, frames = serialize(x) assert header["type"] assert len(frames) == 1 result = deserialize(header, frames) assert result.data == x.data def test_serialize_bytestrings(): for b in (b"123", bytearray(b"4567")): header, frames = serialize(b) assert frames[0] is b bb = deserialize(header, frames) assert type(bb) == type(b) assert bb == b bb = deserialize(header, list(map(memoryview, frames))) assert type(bb) == type(b) assert bb == b bb = deserialize(header, [b"", *frames]) assert type(bb) == type(b) assert bb == b def test_serialize_empty_array(): a = array("I") # serialize array header, frames = serialize(a) assert frames[0] == memoryview(a) # drop empty frame del frames[:] # deserialize with no frames a2 = deserialize(header, frames) assert type(a2) == type(a) assert a2.typecode == a.typecode assert a2 == a @pytest.mark.parametrize( "typecode", ["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q", "f", "d"] ) def test_serialize_arrays(typecode): a = array(typecode, range(5)) # handle normal round trip through serialization header, frames = serialize(a) assert frames[0] == memoryview(a) a2 = deserialize(header, frames) assert type(a2) == type(a) assert a2.typecode == a.typecode assert a2 == a # split up frames to test joining them back together header, frames = serialize(a) (f,) = frames f = ensure_memoryview(f) frames = [f[:1], f[1:2], f[2:-1], f[-1:]] a3 = deserialize(header, frames) assert type(a3) == type(a) assert a3.typecode == a.typecode assert a3 == a def test_Serialize(): s = Serialize(123) assert "123" in str(s) assert s.data == 123 t = Serialize((1, 2)) assert str(t) u = Serialize(123) assert s == u assert not (s != u) assert s != t assert not (s == t) assert hash(s) == hash(u) assert hash(s) != hash(t) # most probably def test_Serialized(): s = Serialized(*serialize(123)) t = Serialized(*serialize((1, 2))) u = Serialized(*serialize(123)) assert s == u assert not (s != u) assert s != t assert not (s == t) def test_nested_deserialize(): x = { "op": "update", "x": [to_serialize(123), to_serialize(456), 789], "y": {"a": ["abc", Serialized(*serialize("def"))], "b": b"ghi"}, } x_orig = copy.deepcopy(x) assert nested_deserialize(x) == { "op": "update", "x": [123, 456, 789], "y": {"a": ["abc", "def"], "b": b"ghi"}, } assert x == x_orig # x wasn't mutated def test_serialize_iterate_collection(): # Use iterate_collection to ensure elements of # a collection will be serialized separately arr = "special-data" sarr = Serialized(*serialize(arr)) sdarr = to_serialize(arr) task1 = (0, sarr, "('fake-key', 3)", None) task2 = (0, sdarr, "('fake-key', 3)", None) expect = (0, arr, "('fake-key', 3)", None) # Check serialize/deserialize directly assert deserialize(*serialize(task1, iterate_collection=True)) == expect assert deserialize(*serialize(task2, iterate_collection=True)) == expect from dask import delayed from distributed.utils_test import gen_cluster @gen_cluster(client=True) async def test_object_in_graph(c, s, a, b): o = MyObj(123) v = delayed(o) v2 = delayed(identity)(v) future = c.compute(v2) result = await future assert isinstance(result, MyObj) assert result.data == 123 @gen_cluster(client=True, config=NO_AMM) async def test_scatter(c, s, a, b): o = MyObj(123) [future] = await c._scatter([o]) await c._replicate(o) o2 = await c._gather(future) assert isinstance(o2, MyObj) assert o2.data == 123 @gen_cluster(client=True) async def test_inter_worker_comms(c, s, a, b): o = MyObj(123) [future] = await c._scatter([o], workers=a.address) future2 = c.submit(identity, future, workers=b.address) o2 = await c._gather(future2) assert isinstance(o2, MyObj) assert o2.data == 123 class Empty: def __getstate__(self): raise Exception("Not picklable") def serialize_empty(x): return {}, [] def deserialize_empty(header, frames): return Empty() register_serialization(Empty, serialize_empty, deserialize_empty) def test_empty(): e = Empty() e2 = deserialize(*serialize(e)) assert isinstance(e2, Empty) def test_empty_loads(): e = Empty() e2 = loads(dumps([to_serialize(e)])) assert isinstance(e2[0], Empty) def test_empty_loads_deep(): e = Empty() e2 = loads(dumps([[[to_serialize(e)]]])) assert isinstance(e2[0][0][0], Empty) @pytest.mark.skipif(np is None, reason="Test needs numpy") @pytest.mark.parametrize("kwargs", [{}, {"serializers": ["pickle"]}]) def test_serialize_bytes(kwargs): for x in [ 1, "abc", np.arange(5), b"ab" * int(40e6), int(2**26) * b"ab", (int(2**25) * b"ab", int(2**25) * b"ab"), ]: b = serialize_bytes(x, **kwargs) assert isinstance(b, bytes) y = deserialize_bytes(b) assert str(x) == str(y) @pytest.mark.skipif(np is None, reason="Test needs numpy") def test_serialize_list_compress(): pytest.importorskip("lz4") x = np.ones(1000000) L = serialize_bytelist(x) assert sum(map(nbytes, L)) < x.nbytes / 2 b = b"".join(L) y = deserialize_bytes(b) assert (x == y).all() def test_malicious_exception(): class BadException(Exception): def __setstate__(self): return Exception("Sneaky deserialization code") class MyClass: def __getstate__(self): raise BadException() obj = MyClass() header, frames = serialize(obj, serializers=[]) with pytest.raises(Exception) as info: deserialize(header, frames) assert "Sneaky" not in str(info.value) assert "MyClass" in str(info.value) header, frames = serialize(obj, serializers=["pickle"]) with pytest.raises(Exception) as info: deserialize(header, frames) assert "Sneaky" not in str(info.value) assert "BadException" in str(info.value) def test_errors(): msg = {"data": {"foo": to_serialize(inc)}, "a": 1, "b": 2, "c": 3, "d": 4, "e": 5} header, frames = serialize(msg, serializers=["msgpack", "pickle"]) assert header["serializer"] == "pickle" header, frames = serialize(msg, serializers=["msgpack"]) assert header["serializer"] == "error" with pytest.raises(TypeError): serialize(msg, serializers=["msgpack"], on_error="raise") @gen_test() async def test_err_on_bad_deserializer(): frames = await to_frames({"x": to_serialize(1234)}, serializers=["pickle"]) result = await from_frames(frames, deserializers=["pickle", "foo"]) assert result == {"x": 1234} with pytest.raises(TypeError): await from_frames(frames, deserializers=["msgpack"]) class MyObject: def __init__(self, **kwargs): self.__dict__.update(kwargs) def my_dumps(obj, context=None): if type(obj).__name__ == "MyObject": header = {"serializer": "my-ser"} frames = [ msgpack.dumps(obj.__dict__, use_bin_type=True), msgpack.dumps(context, use_bin_type=True), ] return header, frames else: raise NotImplementedError() def my_loads(header, frames): obj = MyObject(**msgpack.loads(frames[0], raw=False)) # to provide something to test against, lets just attach the context to # the object itself obj.context = msgpack.loads(frames[1], raw=False) return obj @gen_cluster( client=True, client_kwargs={"serializers": ["my-ser", "pickle"]}, worker_kwargs={"serializers": ["my-ser", "pickle"]}, ) async def test_context_specific_serialization(c, s, a, b): register_serialization_family("my-ser", my_dumps, my_loads) try: # Create the object on A, force communication to B x = c.submit(MyObject, x=1, y=2, workers=a.address) y = c.submit(lambda x: x, x, workers=b.address) await wait(y) key = y.key def check(dask_worker): # Get the context from the object stored on B my_obj = dask_worker.data[key] return my_obj.context result = await c.run(check, workers=[b.address]) expected = {"sender": a.address, "recipient": b.address} assert result[b.address]["sender"]["address"] == a.address # see origin worker z = await y # bring object to local process assert z.x == 1 and z.y == 2 assert z.context["sender"]["address"] == b.address finally: from distributed.protocol.serialize import families del families["my-ser"] @gen_cluster(client=True) async def test_context_specific_serialization_class(c, s, a, b): register_serialization(MyObject, my_dumps, my_loads) # Create the object on A, force communication to B x = c.submit(MyObject, x=1, y=2, workers=a.address) y = c.submit(lambda x: x, x, workers=b.address) await wait(y) key = y.key def check(dask_worker): # Get the context from the object stored on B my_obj = dask_worker.data[key] return my_obj.context result = await c.run(check, workers=[b.address]) assert result[b.address]["sender"]["address"] == a.address # see origin worker z = await y # bring object to local process assert z.x == 1 and z.y == 2 assert z.context["sender"]["address"] == b.address def test_serialize_raises(): class Foo: pass @dask_serialize.register(Foo) def dumps(f): raise Exception("Hello-123") with pytest.raises(Exception) as info: deserialize(*serialize(Foo())) assert "Hello-123" in str(info.value) @gen_test() async def test_profile_nested_sizeof(): # https://github.com/dask/distributed/issues/1674 n = 500 original = outer = {} inner = {} for _ in range(n): outer["children"] = inner outer, inner = inner, {} msg = {"data": original} frames = await to_frames(msg) def test_different_compression_families(): """Test serialization of a collection of items that use different compression This scenario happens for instance when serializing collections of cupy and numpy arrays. """ class MyObjWithCompression: pass class MyObjWithNoCompression: pass def my_dumps_compression(obj, context=None): if not isinstance(obj, MyObjWithCompression): raise NotImplementedError() header = {"compression": [True]} return header, [bytes(2**20)] def my_dumps_no_compression(obj, context=None): if not isinstance(obj, MyObjWithNoCompression): raise NotImplementedError() header = {"compression": [False]} return header, [bytes(2**20)] def my_loads(header, frames): return pickle.loads(frames[0]) register_serialization_family("with-compression", my_dumps_compression, my_loads) register_serialization_family("no-compression", my_dumps_no_compression, my_loads) header, _ = serialize( [MyObjWithCompression(), MyObjWithNoCompression()], serializers=("with-compression", "no-compression"), on_error="raise", iterate_collection=True, ) assert header["compression"] == [True, False] @gen_test() async def test_frame_split(): data = b"1234abcd" * (2**20) # 8 MiB assert dask.sizeof.sizeof(data) == dask.utils.parse_bytes("8MiB") size = dask.utils.parse_bytes("3MiB") split_frames = await to_frames({"x": to_serialize(data)}, frame_split_size=size) print(split_frames) assert len(split_frames) == 3 + 2 # Three splits and two headers size = dask.utils.parse_bytes("5MiB") split_frames = await to_frames({"x": to_serialize(data)}, frame_split_size=size) assert len(split_frames) == 2 + 2 # Two splits and two headers @pytest.mark.parametrize( "data,is_serializable", [ ([], False), ({}, False), ({i: i for i in range(10)}, False), (set(range(10)), False), (tuple(range(100)), False), ({"x": MyObj(5)}, True), ({"x": {"y": MyObj(5)}}, True), pytest.param( [1, MyObj(5)], True, marks=pytest.mark.xfail(reason="Only checks 0th element for now."), ), ([MyObj([0, 1, 2]), 1], True), (tuple([MyObj(None)]), True), ({("x", i): MyObj(5) for i in range(100)}, True), (memoryview(b"hello"), True), pytest.param( memoryview( np.random.random((3, 4)) # type: ignore if np is not None else b"skip np.random" ), True, marks=pytest.mark.skipif(np is None, reason="Test needs numpy"), ), ], ) def test_check_dask_serializable(data, is_serializable): result = check_dask_serializable(data) expected = is_serializable assert result == expected @pytest.mark.parametrize( "serializers", [["msgpack"], ["pickle"], ["msgpack", "pickle"], ["pickle", "msgpack"]], ) def test_serialize_lists(serializers): data_in = ["a", 2, "c", None, "e", 6] header, frames = serialize(data_in, serializers=serializers) data_out = deserialize(header, frames) assert data_in == data_out @pytest.mark.parametrize( "data_in", [ memoryview(b"hello"), pytest.param( memoryview( np.random.random((3, 4)) # type: ignore if np is not None else b"skip np.random" ), marks=pytest.mark.skipif(np is None, reason="Test needs numpy"), ), ], ) def test_deser_memoryview(data_in): header, frames = serialize(data_in) assert header["type"] == "memoryview" assert frames[0] is data_in data_out = deserialize(header, frames) assert data_in == data_out @pytest.mark.skipif(np is None, reason="Test needs numpy") def test_ser_memoryview_object(): data_in = memoryview(np.array(["hello"], dtype=object)) with pytest.raises(TypeError): serialize(data_in, on_error="raise") def test_ser_empty_1d_memoryview(): mv = memoryview(b"") # serialize empty `memoryview` header, frames = serialize(mv) assert frames[0] == mv # deserialize empty `memoryview` mv2 = deserialize(header, frames) assert type(mv2) == type(mv) assert mv2.format == mv.format assert mv2 == mv def test_ser_empty_nd_memoryview(): mv = memoryview(b"12").cast("B", (1, 2))[:0] # serialize empty `memoryview` with pytest.raises(TypeError): serialize(mv, on_error="raise") @gen_cluster(client=True, Worker=Nanny) async def test_large_pickled_object(c, s, a, b): np = pytest.importorskip("numpy") class Data: def __init__(self, n): self.data = np.empty(n, dtype="u1") x = Data(100_000_000) y = await c.scatter(x, workers=[a.worker_address]) z = c.submit(lambda x: x, y, workers=[b.worker_address]) await z
bsd-3-clause
8ffc779310b08f0b9025b019ee4c306d
25.69059
87
0.609083
3.518713
false
true
false
false
dask/distributed
distributed/deploy/tests/test_ssh.py
1
9457
from __future__ import annotations import pytest pytest.importorskip("asyncssh") import sys import dask from distributed import Client from distributed.compatibility import MACOS, WINDOWS from distributed.deploy.ssh import SSHCluster from distributed.utils_test import gen_test pytestmark = [ pytest.mark.xfail(MACOS, reason="very high flakiness; see distributed/issues/4543"), pytest.mark.skipif(WINDOWS, reason="no CI support; see distributed/issues/4509"), ] def test_ssh_hosts_None(): with pytest.raises(ValueError): SSHCluster(hosts=None) def test_ssh_hosts_empty_list(): with pytest.raises(ValueError): SSHCluster(hosts=[]) @gen_test() async def test_ssh_cluster_raises_if_asyncssh_not_installed(monkeypatch): monkeypatch.setitem(sys.modules, "asyncssh", None) with pytest.raises( (RuntimeError, ImportError), match="SSHCluster requires the `asyncssh` package" ): async with SSHCluster( ["127.0.0.1"] * 3, connect_options=[dict(known_hosts=None)] * 3, asynchronous=True, scheduler_options={"idle_timeout": "5s"}, worker_options={"death_timeout": "5s"}, ) as cluster: assert not cluster @gen_test() async def test_basic(): async with SSHCluster( ["127.0.0.1"] * 3, connect_options=dict(known_hosts=None), asynchronous=True, scheduler_options={"idle_timeout": "5s"}, worker_options={"death_timeout": "5s"}, ) as cluster: assert len(cluster.workers) == 2 async with Client(cluster, asynchronous=True) as client: result = await client.submit(lambda x: x + 1, 10) assert result == 11 assert not cluster._supports_scaling assert "SSH" in repr(cluster) @gen_test() async def test_n_workers(): async with SSHCluster( ["127.0.0.1"] * 3, connect_options=dict(known_hosts=None), asynchronous=True, scheduler_options={"idle_timeout": "5s"}, worker_options={"death_timeout": "5s", "n_workers": 2}, ) as cluster: assert len(cluster.workers) == 2 async with Client(cluster, asynchronous=True) as client: await client.wait_for_workers(4) result = await client.submit(lambda x: x + 1, 10) assert result == 11 assert not cluster._supports_scaling assert "SSH" in repr(cluster) @gen_test() async def test_nprocs_attribute_is_deprecated(): async with SSHCluster( ["127.0.0.1"] * 2, connect_options=dict(known_hosts=None), asynchronous=True, scheduler_options={"idle_timeout": "5s"}, worker_options={"death_timeout": "5s"}, ) as cluster: assert len(cluster.workers) == 1 worker = cluster.workers[0] assert worker.n_workers == 1 with pytest.warns(FutureWarning, match="renamed to n_workers"): assert worker.nprocs == 1 with pytest.warns(FutureWarning, match="renamed to n_workers"): worker.nprocs = 3 assert worker.n_workers == 3 @gen_test() async def test_ssh_nprocs_renamed_to_n_workers(): with pytest.warns(FutureWarning, match="renamed to n_workers"): async with SSHCluster( ["127.0.0.1"] * 3, connect_options=dict(known_hosts=None), asynchronous=True, scheduler_options={"idle_timeout": "5s"}, worker_options={"death_timeout": "5s", "nprocs": 2}, ) as cluster: assert len(cluster.workers) == 2 async with Client(cluster, asynchronous=True) as client: await client.wait_for_workers(4) @gen_test() async def test_ssh_n_workers_with_nprocs_is_an_error(): cluster = SSHCluster( ["127.0.0.1"] * 3, connect_options=dict(known_hosts=None), asynchronous=True, scheduler_options={}, worker_options={"n_workers": 2, "nprocs": 2}, ) try: with pytest.raises(ValueError, match="Both nprocs and n_workers"): async with cluster: pass finally: # FIXME: SSHCluster leaks if SSHCluster.__aenter__ raises await cluster.close() @gen_test() async def test_keywords(): async with SSHCluster( ["127.0.0.1"] * 3, connect_options=dict(known_hosts=None), asynchronous=True, worker_options={ "nthreads": 2, "memory_limit": "2 GiB", "death_timeout": "5s", }, scheduler_options={"idle_timeout": "10s"}, ) as cluster: async with Client(cluster, asynchronous=True) as client: assert ( await client.run_on_scheduler( lambda dask_scheduler: dask_scheduler.idle_timeout ) ) == 10 d = client.scheduler_info()["workers"] assert all(v["nthreads"] == 2 for v in d.values()) @pytest.mark.avoid_ci def test_defer_to_old(loop): with pytest.warns( UserWarning, match=r"Note that the SSHCluster API has been replaced\. " r"We're routing you to the older implementation\. " r"This will be removed in the future", ): c = SSHCluster( scheduler_addr="127.0.0.1", scheduler_port=7437, worker_addrs=["127.0.0.1", "127.0.0.1"], ) with c: from distributed.deploy.old_ssh import SSHCluster as OldSSHCluster assert isinstance(c, OldSSHCluster) @pytest.mark.avoid_ci def test_old_ssh_with_local_dir(loop): from distributed.deploy.old_ssh import SSHCluster as OldSSHCluster with OldSSHCluster( scheduler_addr="127.0.0.1", scheduler_port=7437, worker_addrs=["127.0.0.1", "127.0.0.1"], local_directory="/tmp", ) as c: assert len(c.workers) == 2 with Client(c) as client: result = client.submit(lambda x: x + 1, 10) result = result.result() assert result == 11 @gen_test() async def test_config_inherited_by_subprocess(loop): def f(x): return dask.config.get("foo") + 1 with dask.config.set(foo=100): async with SSHCluster( ["127.0.0.1"] * 2, connect_options=dict(known_hosts=None), asynchronous=True, scheduler_options={"idle_timeout": "5s"}, worker_options={"death_timeout": "5s"}, ) as cluster: async with Client(cluster, asynchronous=True) as client: result = await client.submit(f, 1) assert result == 101 @gen_test() async def test_unimplemented_options(): with pytest.raises(Exception): async with SSHCluster( ["127.0.0.1"] * 3, connect_kwargs=dict(known_hosts=None), asynchronous=True, worker_kwargs={ "nthreads": 2, "memory_limit": "2 GiB", "death_timeout": "5s", "unimplemented_option": 2, }, scheduler_kwargs={"idle_timeout": "5s"}, ) as cluster: assert cluster @gen_test() async def test_list_of_connect_options(): async with SSHCluster( ["127.0.0.1"] * 3, connect_options=[dict(known_hosts=None)] * 3, asynchronous=True, scheduler_options={"idle_timeout": "5s"}, worker_options={"death_timeout": "5s"}, ) as cluster: assert len(cluster.workers) == 2 async with Client(cluster, asynchronous=True) as client: result = await client.submit(lambda x: x + 1, 10) assert result == 11 assert not cluster._supports_scaling assert "SSH" in repr(cluster) @gen_test() async def test_list_of_connect_options_raises(): with pytest.raises(RuntimeError): async with SSHCluster( ["127.0.0.1"] * 3, connect_options=[dict(known_hosts=None)] * 4, # Mismatch in length 4 != 3 asynchronous=True, scheduler_options={"idle_timeout": "5s"}, worker_options={"death_timeout": "5s"}, ) as _: pass @gen_test() async def test_remote_python(): async with SSHCluster( ["127.0.0.1"] * 3, connect_options=[dict(known_hosts=None)] * 3, asynchronous=True, scheduler_options={"idle_timeout": "5s"}, worker_options={"death_timeout": "5s"}, remote_python=sys.executable, ) as cluster: assert cluster.workers[0].remote_python == sys.executable @gen_test() async def test_remote_python_as_dict(): async with SSHCluster( ["127.0.0.1"] * 3, connect_options=[dict(known_hosts=None)] * 3, asynchronous=True, scheduler_options={"idle_timeout": "5s"}, worker_options={"death_timeout": "5s"}, remote_python=[sys.executable] * 3, ) as cluster: assert cluster.workers[0].remote_python == sys.executable @gen_test() async def test_list_of_remote_python_raises(): with pytest.raises(RuntimeError): async with SSHCluster( ["127.0.0.1"] * 3, connect_options=[dict(known_hosts=None)] * 3, asynchronous=True, scheduler_options={"idle_timeout": "5s"}, worker_options={"death_timeout": "5s"}, remote_python=[sys.executable] * 4, # Mismatch in length 4 != 3 ) as _: pass
bsd-3-clause
f26cd31c2b5786ab1f4bab9bc1575ea9
30.418605
88
0.583483
3.787345
false
true
false
false
dask/distributed
distributed/http/proxy.py
1
4377
from __future__ import annotations import logging from tornado import web logger = logging.getLogger(__name__) try: from jupyter_server_proxy.handlers import ProxyHandler class GlobalProxyHandler(ProxyHandler): """ A tornado request handler that proxies HTTP and websockets from a port to any valid endpoint'. """ def initialize(self, dask_server=None, extra=None): self.scheduler = dask_server self.extra = extra or {} async def http_get(self, port, host, proxied_path): # route here first # incoming URI /proxy/{port}/{host}/{proxied_path} self.host = host # rewrite uri for jupyter-server-proxy handling uri = f"/proxy/{port}/{proxied_path}" self.request.uri = uri # slash is removed during regex in handler proxied_path = "/%s" % proxied_path worker = f"{self.host}:{port}" if not check_worker_dashboard_exits(self.scheduler, worker): msg = "Worker <%s> does not exist" % worker self.set_status(400) self.finish(msg) return return await self.proxy(port, proxied_path) async def open(self, port, host, proxied_path): # finally, proxy to other address/port return await self.proxy_open(host, port, proxied_path) def post(self, port, proxied_path): return self.proxy(port, proxied_path) def put(self, port, proxied_path): return self.proxy(port, proxied_path) def delete(self, port, proxied_path): return self.proxy(port, proxied_path) def head(self, port, proxied_path): return self.proxy(port, proxied_path) def patch(self, port, proxied_path): return self.proxy(port, proxied_path) def options(self, port, proxied_path): return self.proxy(port, proxied_path) def proxy(self, port, proxied_path): # router here second # returns ProxyHandler coroutine return super().proxy(self.host, port, proxied_path) except ImportError: logger.info( "To route to workers diagnostics web server " "please install jupyter-server-proxy: " "python -m pip install jupyter-server-proxy" ) class GlobalProxyHandler(web.RequestHandler): # type: ignore """Minimal Proxy handler when jupyter-server-proxy is not installed""" def initialize(self, dask_server=None, extra=None): self.server = dask_server self.extra = extra or {} def get(self, port, host, proxied_path): worker_url = f"{host}:{port}/{proxied_path}" msg = """ <p> Try navigating to <a href=http://{}>{}</a> for your worker dashboard </p> <p> Dask tried to proxy you to that page through your Scheduler's dashboard connection, but you don't have jupyter-server-proxy installed. You may want to install it with either conda or pip, and then restart your scheduler. </p> <p><pre> conda install jupyter-server-proxy -c conda-forge </pre></p> <p><pre> python -m pip install jupyter-server-proxy</pre></p> <p> The link above should work though if your workers are on a sufficiently open network. This is common on single machines, but less common in production clusters. Your IT administrators will know more </p> """.format( worker_url, worker_url, ) self.write(msg) def check_worker_dashboard_exits(scheduler, worker): """Check addr:port exists as a worker in scheduler list Parameters ---------- worker : str addr:port Returns ------- bool """ addr, port = worker.split(":") workers = list(scheduler.workers.values()) for w in workers: bokeh_port = w.services.get("dashboard", "") if addr == w.host and port == str(bokeh_port): return True return False routes: list[tuple] = [(r"proxy/(\d+)/(.*?)/(.*)", GlobalProxyHandler, {})]
bsd-3-clause
57afc58bfbf386c409ac7a060125bd29
31.909774
93
0.56934
4.196548
false
false
false
false
dask/distributed
distributed/shuffle/_shuffle.py
1
4851
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from dask.base import tokenize from dask.highlevelgraph import HighLevelGraph from dask.layers import SimpleShuffleLayer from distributed.shuffle._shuffle_extension import ShuffleId, ShuffleWorkerExtension logger = logging.getLogger("distributed.shuffle") if TYPE_CHECKING: import pandas as pd from dask.dataframe import DataFrame def _get_worker_extension() -> ShuffleWorkerExtension: from distributed import get_worker try: worker = get_worker() except ValueError as e: raise RuntimeError( "`shuffle='p2p'` requires Dask's distributed scheduler. This task is not running on a Worker; " "please confirm that you've created a distributed Client and are submitting this computation through it." ) from e extension: ShuffleWorkerExtension | None = worker.extensions.get("shuffle") if extension is None: raise RuntimeError( f"The worker {worker.address} does not have a ShuffleExtension. " "Is pandas installed on the worker?" ) return extension def shuffle_transfer( input: pd.DataFrame, id: ShuffleId, npartitions: int, column: str, ) -> None: _get_worker_extension().add_partition( input, id, npartitions=npartitions, column=column ) def shuffle_unpack( id: ShuffleId, output_partition: int, barrier: object ) -> pd.DataFrame: return _get_worker_extension().get_output_partition(id, output_partition) def shuffle_barrier(id: ShuffleId, transfers: list[None]) -> None: return _get_worker_extension().barrier(id) def rearrange_by_column_p2p( df: DataFrame, column: str, npartitions: int | None = None, ) -> DataFrame: from dask.dataframe import DataFrame npartitions = npartitions or df.npartitions token = tokenize(df, column, npartitions) empty = df._meta.copy() for c, dt in empty.dtypes.items(): if dt == object: empty[c] = empty[c].astype( "string" ) # TODO: we fail at non-string object dtypes empty[column] = empty[column].astype("int64") # TODO: this shouldn't be necesssary name = f"shuffle-p2p-{token}" layer = P2PShuffleLayer( name, column, npartitions, npartitions_input=df.npartitions, ignore_index=True, name_input=df._name, meta_input=empty, ) return DataFrame( HighLevelGraph.from_collections(name, layer, [df]), name, empty, [None] * (npartitions + 1), ) class P2PShuffleLayer(SimpleShuffleLayer): def __init__( self, name: str, column: str, npartitions: int, npartitions_input: int, ignore_index: bool, name_input: str, meta_input: pd.DataFrame, parts_out: list | None = None, annotations: dict | None = None, ): annotations = annotations or {} annotations.update({"shuffle": lambda key: key[1]}) super().__init__( name, column, npartitions, npartitions_input, ignore_index, name_input, meta_input, parts_out, annotations=annotations, ) def get_split_keys(self) -> list: # TODO: This is doing some funky stuff to set priorities but we don't need this return [] def __repr__(self) -> str: return ( f"{type(self).__name__}<name='{self.name}', npartitions={self.npartitions}>" ) def _cull(self, parts_out: list) -> P2PShuffleLayer: return P2PShuffleLayer( self.name, self.column, self.npartitions, self.npartitions_input, self.ignore_index, self.name_input, self.meta_input, parts_out=parts_out, ) def _construct_graph(self, deserializing: Any = None) -> dict[tuple | str, tuple]: token = tokenize(self.name_input, self.column, self.npartitions, self.parts_out) dsk: dict[tuple | str, tuple] = {} barrier_key = "shuffle-barrier-" + token name = "shuffle-transfer-" + token transfer_keys = list() for i in range(self.npartitions_input): transfer_keys.append((name, i)) dsk[(name, i)] = ( shuffle_transfer, (self.name_input, i), token, self.npartitions, self.column, ) dsk[barrier_key] = (shuffle_barrier, token, transfer_keys) name = self.name for part_out in self.parts_out: dsk[(name, part_out)] = (shuffle_unpack, token, part_out, barrier_key) return dsk
bsd-3-clause
37f26b9a5a777bd57074b276d7cbaac0
28.579268
117
0.59699
3.95677
false
false
false
false
jschneier/django-storages
storages/backends/azure_storage.py
1
14292
import mimetypes from datetime import datetime from datetime import timedelta from tempfile import SpooledTemporaryFile from azure.core.exceptions import ResourceNotFoundError from azure.storage.blob import BlobClient from azure.storage.blob import BlobSasPermissions from azure.storage.blob import BlobServiceClient from azure.storage.blob import ContentSettings from azure.storage.blob import generate_blob_sas from django.core.exceptions import SuspiciousOperation from django.core.files.base import File from django.utils import timezone from django.utils.deconstruct import deconstructible from storages.base import BaseStorage from storages.utils import clean_name from storages.utils import get_available_overwrite_name from storages.utils import safe_join from storages.utils import setting from storages.utils import to_bytes @deconstructible class AzureStorageFile(File): def __init__(self, name, mode, storage): self.name = name self._mode = mode self._storage = storage self._is_dirty = False self._file = None self._path = storage._get_valid_path(name) def _get_file(self): if self._file is not None: return self._file file = SpooledTemporaryFile( max_size=self._storage.max_memory_size, suffix=".AzureStorageFile", dir=setting("FILE_UPLOAD_TEMP_DIR", None)) if 'r' in self._mode or 'a' in self._mode: download_stream = self._storage.client.download_blob( self._path, timeout=self._storage.timeout) download_stream.readinto(file) if 'r' in self._mode: file.seek(0) self._file = file return self._file def _set_file(self, value): self._file = value file = property(_get_file, _set_file) def read(self, *args, **kwargs): if 'r' not in self._mode and 'a' not in self._mode: raise AttributeError("File was not opened in read mode.") return super().read(*args, **kwargs) def write(self, content): if ('w' not in self._mode and '+' not in self._mode and 'a' not in self._mode): raise AttributeError("File was not opened in write mode.") self._is_dirty = True return super().write(to_bytes(content)) def close(self): if self._file is None: return if self._is_dirty: self._file.seek(0) self._storage._save(self.name, self._file) self._is_dirty = False self._file.close() self._file = None def _content_type(content): try: return content.file.content_type except AttributeError: pass try: return content.content_type except AttributeError: pass return None def _get_valid_path(s): # A blob name: # * must not end with dot or slash # * can contain any character # * must escape URL reserved characters # (not needed here since the azure client will do that) s = s.strip('./') if len(s) > _AZURE_NAME_MAX_LEN: raise ValueError( "File name max len is %d" % _AZURE_NAME_MAX_LEN) if not len(s): raise ValueError( "File name must contain one or more " "printable characters") if s.count('/') > 256: raise ValueError( "File name must not contain " "more than 256 slashes") return s # Max len according to azure's docs _AZURE_NAME_MAX_LEN = 1024 @deconstructible class AzureStorage(BaseStorage): def __init__(self, **settings): super().__init__(**settings) self._service_client = None self._custom_service_client = None self._client = None self._custom_client = None self._user_delegation_key = None self._user_delegation_key_expiry = datetime.utcnow() def get_default_settings(self): return { "account_name": setting("AZURE_ACCOUNT_NAME"), "account_key": setting("AZURE_ACCOUNT_KEY"), "object_parameters": setting("AZURE_OBJECT_PARAMETERS", {}), "azure_container": setting("AZURE_CONTAINER"), "azure_ssl": setting("AZURE_SSL", True), "upload_max_conn": setting("AZURE_UPLOAD_MAX_CONN", 2), "timeout": setting('AZURE_CONNECTION_TIMEOUT_SECS', 20), "max_memory_size": setting('AZURE_BLOB_MAX_MEMORY_SIZE', 2*1024*1024), "expiration_secs": setting('AZURE_URL_EXPIRATION_SECS'), "overwrite_files": setting('AZURE_OVERWRITE_FILES', False), "location": setting('AZURE_LOCATION', ''), "default_content_type": 'application/octet-stream', "cache_control": setting("AZURE_CACHE_CONTROL"), "sas_token": setting('AZURE_SAS_TOKEN'), "endpoint_suffix": setting('AZURE_ENDPOINT_SUFFIX', 'core.windows.net'), "custom_domain": setting('AZURE_CUSTOM_DOMAIN'), "connection_string": setting('AZURE_CONNECTION_STRING'), "token_credential": setting('AZURE_TOKEN_CREDENTIAL'), "api_version": setting('AZURE_API_VERSION', None), } def _get_service_client(self, use_custom_domain): if self.connection_string is not None: return BlobServiceClient.from_connection_string(self.connection_string) account_domain = self.custom_domain if self.custom_domain and use_custom_domain else "{}.blob.{}".format( self.account_name, self.endpoint_suffix, ) account_url = "{}://{}".format(self.azure_protocol, account_domain) credential = None if self.account_key: credential = { "account_name": self.account_name, "account_key": self.account_key, } elif self.sas_token: credential = self.sas_token elif self.token_credential: credential = self.token_credential options = {} if self.api_version: options["api_version"] = self.api_version return BlobServiceClient(account_url, credential=credential, **options) @property def service_client(self): if self._service_client is None: self._service_client = self._get_service_client(use_custom_domain=False) return self._service_client @property def custom_service_client(self): if self._custom_service_client is None: self._custom_service_client = self._get_service_client(use_custom_domain=True) return self._custom_service_client @property def client(self): if self._client is None: self._client = self.service_client.get_container_client( self.azure_container ) return self._client @property def custom_client(self): if self._custom_client is None: self._custom_client = self.custom_service_client.get_container_client( self.azure_container ) return self._custom_client def get_user_delegation_key(self, expiry): # We'll only be able to get a user delegation key if we've authenticated with a # token credential. if self.token_credential is None: return None # Get a new key if we don't already have one, or if the one we have expires too # soon. if ( self._user_delegation_key is None or expiry > self._user_delegation_key_expiry ): now = datetime.utcnow() key_expiry_time = now + timedelta(days=7) self._user_delegation_key = self.custom_service_client.get_user_delegation_key( key_start_time=now, key_expiry_time=key_expiry_time ) self._user_delegation_key_expiry = key_expiry_time return self._user_delegation_key @property def azure_protocol(self): if self.azure_ssl: return 'https' else: return 'http' def _normalize_name(self, name): try: return safe_join(self.location, name) except ValueError: raise SuspiciousOperation("Attempted access to '%s' denied." % name) def _get_valid_path(self, name): # Must be idempotent return _get_valid_path( self._normalize_name( clean_name(name))) def _open(self, name, mode="rb"): return AzureStorageFile(name, mode, self) def get_available_name(self, name, max_length=_AZURE_NAME_MAX_LEN): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ name = clean_name(name) if self.overwrite_files: return get_available_overwrite_name(name, max_length) return super().get_available_name(name, max_length) def exists(self, name): blob_client = self.client.get_blob_client(self._get_valid_path(name)) return blob_client.exists() def delete(self, name): try: self.client.delete_blob( self._get_valid_path(name), timeout=self.timeout) except ResourceNotFoundError: pass def size(self, name): blob_client = self.client.get_blob_client(self._get_valid_path(name)) properties = blob_client.get_blob_properties(timeout=self.timeout) return properties.size def _save(self, name, content): cleaned_name = clean_name(name) name = self._get_valid_path(name) params = self._get_content_settings_parameters(name, content) # Unwrap django file (wrapped by parent's save call) if isinstance(content, File): content = content.file content.seek(0) self.client.upload_blob( name, content, content_settings=ContentSettings(**params), max_concurrency=self.upload_max_conn, timeout=self.timeout, overwrite=self.overwrite_files) return cleaned_name def _expire_at(self, expire): # azure expects time in UTC return datetime.utcnow() + timedelta(seconds=expire) def url(self, name, expire=None, parameters=None): name = self._get_valid_path(name) params = parameters or {} if expire is None: expire = self.expiration_secs credential = None if expire: expiry = self._expire_at(expire) user_delegation_key = self.get_user_delegation_key(expiry) sas_token = generate_blob_sas( self.account_name, self.azure_container, name, account_key=self.account_key, user_delegation_key=user_delegation_key, permission=BlobSasPermissions(read=True), expiry=expiry, **params ) credential = sas_token container_blob_url = self.custom_client.get_blob_client(name).url return BlobClient.from_blob_url(container_blob_url, credential=credential).url def _get_content_settings_parameters(self, name, content=None): params = {} guessed_type, content_encoding = mimetypes.guess_type(name) content_type = ( _content_type(content) or guessed_type or self.default_content_type) params['cache_control'] = self.cache_control params['content_type'] = content_type params['content_encoding'] = content_encoding params.update(self.get_object_parameters(name)) return params def get_object_parameters(self, name): """ Returns a dictionary that is passed to content settings. Override this method to adjust this on a per-object basis to set e.g ContentDisposition. By default, returns the value of AZURE_OBJECT_PARAMETERS. """ return self.object_parameters.copy() def get_modified_time(self, name): """ Returns an (aware) datetime object containing the last modified time if USE_TZ is True, otherwise returns a naive datetime in the local timezone. """ blob_client = self.client.get_blob_client(self._get_valid_path(name)) properties = blob_client.get_blob_properties(timeout=self.timeout) if not setting('USE_TZ', False): return timezone.make_naive(properties.last_modified) tz = timezone.get_current_timezone() if timezone.is_naive(properties.last_modified): return timezone.make_aware(properties.last_modified, tz) # `last_modified` is in UTC time_zone, we # must convert it to settings time_zone return properties.last_modified.astimezone(tz) def modified_time(self, name): """Returns a naive datetime object containing the last modified time.""" mtime = self.get_modified_time(name) if timezone.is_naive(mtime): return mtime return timezone.make_naive(mtime) def list_all(self, path=''): """Return all files for a given path""" if path: path = self._get_valid_path(path) if path and not path.endswith('/'): path += '/' # XXX make generator, add start, end return [ blob.name for blob in self.client.list_blobs( name_starts_with=path, timeout=self.timeout)] def listdir(self, path=''): """ Return directories and files for a given path. Leave the path empty to list the root. Order of dirs and files is undefined. """ files = [] dirs = set() for name in self.list_all(path): n = name[len(path):] if '/' in n: dirs.add(n.split('/', 1)[0]) else: files.append(n) return list(dirs), files def get_name_max_len(self): max_len = _AZURE_NAME_MAX_LEN - len(self._get_valid_path('foo')) - len('foo') if not self.overwrite_files: max_len -= len('_1234567') return max_len
bsd-3-clause
652eb4f7714dbfb0c4dc093983a7fe0a
33.858537
113
0.599566
4.142609
false
false
false
false
cherrypy/cherrypy
cherrypy/_cpcompat.py
10
1992
"""Compatibility code for using CherryPy with various versions of Python. To retain compatibility with older Python versions, this module provides a useful abstraction over the differences between Python versions, sometimes by preferring a newer idiom, sometimes an older one, and sometimes a custom one. In particular, Python 2 uses str and '' for byte strings, while Python 3 uses str and '' for unicode strings. We will call each of these the 'native string' type for each version. Because of this major difference, this module provides two functions: 'ntob', which translates native strings (of type 'str') into byte strings regardless of Python version, and 'ntou', which translates native strings to unicode strings. Try not to use the compatibility functions 'ntob', 'ntou', 'tonative'. They were created with Python 2.3-2.5 compatibility in mind. Instead, use unicode literals (from __future__) and bytes literals and their .encode/.decode methods as needed. """ import http.client def ntob(n, encoding='ISO-8859-1'): """Return the given native string as a byte string in the given encoding. """ assert_native(n) # In Python 3, the native string type is unicode return n.encode(encoding) def ntou(n, encoding='ISO-8859-1'): """Return the given native string as a unicode string with the given encoding. """ assert_native(n) # In Python 3, the native string type is unicode return n def tonative(n, encoding='ISO-8859-1'): """Return the given string as a native string in the given encoding.""" # In Python 3, the native string type is unicode if isinstance(n, bytes): return n.decode(encoding) return n def assert_native(n): if not isinstance(n, str): raise TypeError('n must be a native str (got %s)' % type(n).__name__) # Some platforms don't expose HTTPSConnection, so handle it separately HTTPSConnection = getattr(http.client, 'HTTPSConnection', None) text_or_bytes = str, bytes
bsd-3-clause
88fa05e896ebb4035050b0a7ab7d7b3d
32.762712
78
0.725904
4.008048
false
false
false
false
cherrypy/cherrypy
cherrypy/test/modfcgid.py
1
4192
"""Wrapper for mod_fcgid, for use as a CherryPy HTTP server when testing. To autostart fcgid, the "apache" executable or script must be on your system path, or you must override the global APACHE_PATH. On some platforms, "apache" may be called "apachectl", "apache2ctl", or "httpd"--create a symlink to them if needed. You'll also need the WSGIServer from flup.servers. See http://projects.amor.org/misc/wiki/ModPythonGateway KNOWN BUGS ========== 1. Apache processes Range headers automatically; CherryPy's truncated output is then truncated again by Apache. See test_core.testRanges. This was worked around in http://www.cherrypy.dev/changeset/1319. 2. Apache does not allow custom HTTP methods like CONNECT as per the spec. See test_core.testHTTPMethods. 3. Max request header and body settings do not work with Apache. 4. Apache replaces status "reason phrases" automatically. For example, CherryPy may set "304 Not modified" but Apache will write out "304 Not Modified" (capital "M"). 5. Apache does not allow custom error codes as per the spec. 6. Apache (or perhaps modpython, or modpython_gateway) unquotes %xx in the Request-URI too early. 7. mod_python will not read request bodies which use the "chunked" transfer-coding (it passes REQUEST_CHUNKED_ERROR to ap_setup_client_block instead of REQUEST_CHUNKED_DECHUNK, see Apache2's http_protocol.c and mod_python's requestobject.c). 8. Apache will output a "Content-Length: 0" response header even if there's no response entity body. This isn't really a bug; it just differs from the CherryPy default. """ import os import re import cherrypy from cherrypy._cpcompat import ntob from cherrypy.process import servers from cherrypy.test import helper curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) def read_process(cmd, args=''): pipein, pipeout = os.popen4('%s %s' % (cmd, args)) try: firstline = pipeout.readline() if (re.search(r'(not recognized|No such file|not found)', firstline, re.IGNORECASE)): raise IOError('%s must be on your system path.' % cmd) output = firstline + pipeout.read() finally: pipeout.close() return output APACHE_PATH = 'httpd' CONF_PATH = 'fcgi.conf' conf_fcgid = """ # Apache2 server conf file for testing CherryPy with mod_fcgid. DocumentRoot "%(root)s" ServerName 127.0.0.1 Listen %(port)s LoadModule fastcgi_module modules/mod_fastcgi.dll LoadModule rewrite_module modules/mod_rewrite.so Options ExecCGI SetHandler fastcgi-script RewriteEngine On RewriteRule ^(.*)$ /fastcgi.pyc [L] FastCgiExternalServer "%(server)s" -host 127.0.0.1:4000 """ class ModFCGISupervisor(helper.LocalSupervisor): using_apache = True using_wsgi = True template = conf_fcgid def __str__(self): return 'FCGI Server on %s:%s' % (self.host, self.port) def start(self, modulename): cherrypy.server.httpserver = servers.FlupFCGIServer( application=cherrypy.tree, bindAddress=('127.0.0.1', 4000)) cherrypy.server.httpserver.bind_addr = ('127.0.0.1', 4000) # For FCGI, we both start apache... self.start_apache() # ...and our local server helper.LocalServer.start(self, modulename) def start_apache(self): fcgiconf = CONF_PATH if not os.path.isabs(fcgiconf): fcgiconf = os.path.join(curdir, fcgiconf) # Write the Apache conf file. with open(fcgiconf, 'wb') as f: server = repr(os.path.join(curdir, 'fastcgi.pyc'))[1:-1] output = self.template % {'port': self.port, 'root': curdir, 'server': server} output = ntob(output.replace('\r\n', '\n')) f.write(output) result = read_process(APACHE_PATH, '-k start -f %s' % fcgiconf) if result: print(result) def stop(self): """Gracefully shutdown a server that is serving forever.""" read_process(APACHE_PATH, '-k stop') helper.LocalServer.stop(self) def sync_apps(self): cherrypy.server.httpserver.fcgiserver.application = self.get_app()
bsd-3-clause
370a490a84f3dcba987db95f449f42f7
33.644628
77
0.674857
3.601375
false
true
false
false
cherrypy/cherrypy
cherrypy/lib/static.py
6
16592
"""Module with helpers for serving static files.""" import os import platform import re import stat import mimetypes import urllib.parse import unicodedata from email.generator import _make_boundary as make_boundary from io import UnsupportedOperation import cherrypy from cherrypy._cpcompat import ntob from cherrypy.lib import cptools, httputil, file_generator_limited def _setup_mimetypes(): """Pre-initialize global mimetype map.""" if not mimetypes.inited: mimetypes.init() mimetypes.types_map['.dwg'] = 'image/x-dwg' mimetypes.types_map['.ico'] = 'image/x-icon' mimetypes.types_map['.bz2'] = 'application/x-bzip2' mimetypes.types_map['.gz'] = 'application/x-gzip' _setup_mimetypes() def _make_content_disposition(disposition, file_name): """Create HTTP header for downloading a file with a UTF-8 filename. This function implements the recommendations of :rfc:`6266#appendix-D`. See this and related answers: https://stackoverflow.com/a/8996249/2173868. """ # As normalization algorithm for `unicodedata` is used composed form (NFC # and NFKC) with compatibility equivalence criteria (NFK), so "NFKC" is the # one. It first applies the compatibility decomposition, followed by the # canonical composition. Should be displayed in the same manner, should be # treated in the same way by applications such as alphabetizing names or # searching, and may be substituted for each other. # See: https://en.wikipedia.org/wiki/Unicode_equivalence. ascii_name = ( unicodedata.normalize('NFKC', file_name). encode('ascii', errors='ignore').decode() ) header = '{}; filename="{}"'.format(disposition, ascii_name) if ascii_name != file_name: quoted_name = urllib.parse.quote(file_name) header += '; filename*=UTF-8\'\'{}'.format(quoted_name) return header def serve_file(path, content_type=None, disposition=None, name=None, debug=False): """Set status, headers, and body in order to serve the given path. The Content-Type header will be set to the content_type arg, if provided. If not provided, the Content-Type will be guessed by the file extension of the 'path' argument. If disposition is not None, the Content-Disposition header will be set to "<disposition>; filename=<name>; filename*=utf-8''<name>" as described in :rfc:`6266#appendix-D`. If name is None, it will be set to the basename of path. If disposition is None, no Content-Disposition header will be written. """ response = cherrypy.serving.response # If path is relative, users should fix it by making path absolute. # That is, CherryPy should not guess where the application root is. # It certainly should *not* use cwd (since CP may be invoked from a # variety of paths). If using tools.staticdir, you can make your relative # paths become absolute by supplying a value for "tools.staticdir.root". if not os.path.isabs(path): msg = "'%s' is not an absolute path." % path if debug: cherrypy.log(msg, 'TOOLS.STATICFILE') raise ValueError(msg) try: st = os.stat(path) except (OSError, TypeError, ValueError): # OSError when file fails to stat # TypeError on Python 2 when there's a null byte # ValueError on Python 3 when there's a null byte if debug: cherrypy.log('os.stat(%r) failed' % path, 'TOOLS.STATIC') raise cherrypy.NotFound() # Check if path is a directory. if stat.S_ISDIR(st.st_mode): # Let the caller deal with it as they like. if debug: cherrypy.log('%r is a directory' % path, 'TOOLS.STATIC') raise cherrypy.NotFound() # Set the Last-Modified response header, so that # modified-since validation code can work. response.headers['Last-Modified'] = httputil.HTTPDate(st.st_mtime) cptools.validate_since() if content_type is None: # Set content-type based on filename extension ext = '' i = path.rfind('.') if i != -1: ext = path[i:].lower() content_type = mimetypes.types_map.get(ext, None) if content_type is not None: response.headers['Content-Type'] = content_type if debug: cherrypy.log('Content-Type: %r' % content_type, 'TOOLS.STATIC') cd = None if disposition is not None: if name is None: name = os.path.basename(path) cd = _make_content_disposition(disposition, name) response.headers['Content-Disposition'] = cd if debug: cherrypy.log('Content-Disposition: %r' % cd, 'TOOLS.STATIC') # Set Content-Length and use an iterable (file object) # this way CP won't load the whole file in memory content_length = st.st_size fileobj = open(path, 'rb') return _serve_fileobj(fileobj, content_type, content_length, debug=debug) def serve_fileobj(fileobj, content_type=None, disposition=None, name=None, debug=False): """Set status, headers, and body in order to serve the given file object. The Content-Type header will be set to the content_type arg, if provided. If disposition is not None, the Content-Disposition header will be set to "<disposition>; filename=<name>; filename*=utf-8''<name>" as described in :rfc:`6266#appendix-D`. If name is None, 'filename' will not be set. If disposition is None, no Content-Disposition header will be written. CAUTION: If the request contains a 'Range' header, one or more seek()s will be performed on the file object. This may cause undesired behavior if the file object is not seekable. It could also produce undesired results if the caller set the read position of the file object prior to calling serve_fileobj(), expecting that the data would be served starting from that position. """ response = cherrypy.serving.response try: st = os.fstat(fileobj.fileno()) except AttributeError: if debug: cherrypy.log('os has no fstat attribute', 'TOOLS.STATIC') content_length = None except UnsupportedOperation: content_length = None else: # Set the Last-Modified response header, so that # modified-since validation code can work. response.headers['Last-Modified'] = httputil.HTTPDate(st.st_mtime) cptools.validate_since() content_length = st.st_size if content_type is not None: response.headers['Content-Type'] = content_type if debug: cherrypy.log('Content-Type: %r' % content_type, 'TOOLS.STATIC') cd = None if disposition is not None: if name is None: cd = disposition else: cd = _make_content_disposition(disposition, name) response.headers['Content-Disposition'] = cd if debug: cherrypy.log('Content-Disposition: %r' % cd, 'TOOLS.STATIC') return _serve_fileobj(fileobj, content_type, content_length, debug=debug) def _serve_fileobj(fileobj, content_type, content_length, debug=False): """Internal. Set response.body to the given file object, perhaps ranged.""" response = cherrypy.serving.response # HTTP/1.0 didn't have Range/Accept-Ranges headers, or the 206 code request = cherrypy.serving.request if request.protocol >= (1, 1): response.headers['Accept-Ranges'] = 'bytes' r = httputil.get_ranges(request.headers.get('Range'), content_length) if r == []: response.headers['Content-Range'] = 'bytes */%s' % content_length message = ('Invalid Range (first-byte-pos greater than ' 'Content-Length)') if debug: cherrypy.log(message, 'TOOLS.STATIC') raise cherrypy.HTTPError(416, message) if r: if len(r) == 1: # Return a single-part response. start, stop = r[0] if stop > content_length: stop = content_length r_len = stop - start if debug: cherrypy.log( 'Single part; start: %r, stop: %r' % (start, stop), 'TOOLS.STATIC') response.status = '206 Partial Content' response.headers['Content-Range'] = ( 'bytes %s-%s/%s' % (start, stop - 1, content_length)) response.headers['Content-Length'] = r_len fileobj.seek(start) response.body = file_generator_limited(fileobj, r_len) else: # Return a multipart/byteranges response. response.status = '206 Partial Content' boundary = make_boundary() ct = 'multipart/byteranges; boundary=%s' % boundary response.headers['Content-Type'] = ct if 'Content-Length' in response.headers: # Delete Content-Length header so finalize() recalcs it. del response.headers['Content-Length'] def file_ranges(): # Apache compatibility: yield b'\r\n' for start, stop in r: if debug: cherrypy.log( 'Multipart; start: %r, stop: %r' % ( start, stop), 'TOOLS.STATIC') yield ntob('--' + boundary, 'ascii') yield ntob('\r\nContent-type: %s' % content_type, 'ascii') yield ntob( '\r\nContent-range: bytes %s-%s/%s\r\n\r\n' % ( start, stop - 1, content_length), 'ascii') fileobj.seek(start) gen = file_generator_limited(fileobj, stop - start) for chunk in gen: yield chunk yield b'\r\n' # Final boundary yield ntob('--' + boundary + '--', 'ascii') # Apache compatibility: yield b'\r\n' response.body = file_ranges() return response.body else: if debug: cherrypy.log('No byteranges requested', 'TOOLS.STATIC') # Set Content-Length and use an iterable (file object) # this way CP won't load the whole file in memory response.headers['Content-Length'] = content_length response.body = fileobj return response.body def serve_download(path, name=None): """Serve 'path' as an application/x-download attachment.""" # This is such a common idiom I felt it deserved its own wrapper. return serve_file(path, 'application/x-download', 'attachment', name) def _attempt(filename, content_types, debug=False): if debug: cherrypy.log('Attempting %r (content_types %r)' % (filename, content_types), 'TOOLS.STATICDIR') try: # you can set the content types for a # complete directory per extension content_type = None if content_types: r, ext = os.path.splitext(filename) content_type = content_types.get(ext[1:], None) serve_file(filename, content_type=content_type, debug=debug) return True except cherrypy.NotFound: # If we didn't find the static file, continue handling the # request. We might find a dynamic handler instead. if debug: cherrypy.log('NotFound', 'TOOLS.STATICFILE') return False def staticdir(section, dir, root='', match='', content_types=None, index='', debug=False): """Serve a static resource from the given (root +) dir. match If given, request.path_info will be searched for the given regular expression before attempting to serve static content. content_types If given, it should be a Python dictionary of {file-extension: content-type} pairs, where 'file-extension' is a string (e.g. "gif") and 'content-type' is the value to write out in the Content-Type response header (e.g. "image/gif"). index If provided, it should be the (relative) name of a file to serve for directory requests. For example, if the dir argument is '/home/me', the Request-URI is 'myapp', and the index arg is 'index.html', the file '/home/me/myapp/index.html' will be sought. """ request = cherrypy.serving.request if request.method not in ('GET', 'HEAD'): if debug: cherrypy.log('request.method not GET or HEAD', 'TOOLS.STATICDIR') return False if match and not re.search(match, request.path_info): if debug: cherrypy.log('request.path_info %r does not match pattern %r' % (request.path_info, match), 'TOOLS.STATICDIR') return False # Allow the use of '~' to refer to a user's home directory. dir = os.path.expanduser(dir) # If dir is relative, make absolute using "root". if not os.path.isabs(dir): if not root: msg = 'Static dir requires an absolute dir (or root).' if debug: cherrypy.log(msg, 'TOOLS.STATICDIR') raise ValueError(msg) dir = os.path.join(root, dir) # Determine where we are in the object tree relative to 'section' # (where the static tool was defined). if section == 'global': section = '/' section = section.rstrip(r'\/') branch = request.path_info[len(section) + 1:] branch = urllib.parse.unquote(branch.lstrip(r'\/')) # Requesting a file in sub-dir of the staticdir results # in mixing of delimiter styles, e.g. C:\static\js/script.js. # Windows accepts this form except not when the path is # supplied in extended-path notation, e.g. \\?\C:\static\js/script.js. # http://bit.ly/1vdioCX if platform.system() == 'Windows': branch = branch.replace('/', '\\') # If branch is "", filename will end in a slash filename = os.path.join(dir, branch) if debug: cherrypy.log('Checking file %r to fulfill %r' % (filename, request.path_info), 'TOOLS.STATICDIR') # There's a chance that the branch pulled from the URL might # have ".." or similar uplevel attacks in it. Check that the final # filename is a child of dir. if not os.path.normpath(filename).startswith(os.path.normpath(dir)): raise cherrypy.HTTPError(403) # Forbidden handled = _attempt(filename, content_types) if not handled: # Check for an index file if a folder was requested. if index: handled = _attempt(os.path.join(filename, index), content_types) if handled: request.is_index = filename[-1] in (r'\/') return handled def staticfile(filename, root=None, match='', content_types=None, debug=False): """Serve a static resource from the given (root +) filename. match If given, request.path_info will be searched for the given regular expression before attempting to serve static content. content_types If given, it should be a Python dictionary of {file-extension: content-type} pairs, where 'file-extension' is a string (e.g. "gif") and 'content-type' is the value to write out in the Content-Type response header (e.g. "image/gif"). """ request = cherrypy.serving.request if request.method not in ('GET', 'HEAD'): if debug: cherrypy.log('request.method not GET or HEAD', 'TOOLS.STATICFILE') return False if match and not re.search(match, request.path_info): if debug: cherrypy.log('request.path_info %r does not match pattern %r' % (request.path_info, match), 'TOOLS.STATICFILE') return False # If filename is relative, make absolute using "root". if not os.path.isabs(filename): if not root: msg = "Static tool requires an absolute filename (got '%s')." % ( filename,) if debug: cherrypy.log(msg, 'TOOLS.STATICFILE') raise ValueError(msg) filename = os.path.join(root, filename) return _attempt(filename, content_types, debug=debug)
bsd-3-clause
1cc8acc84b0ddd13f6ec936fbec950bf
38.884615
79
0.606377
4.156313
false
false
false
false
cherrypy/cherrypy
cherrypy/_cpdispatch.py
1
25216
"""CherryPy dispatchers. A 'dispatcher' is the object which looks up the 'page handler' callable and collects config for the current request based on the path_info, other request attributes, and the application architecture. The core calls the dispatcher as early as possible, passing it a 'path_info' argument. The default dispatcher discovers the page handler by matching path_info to a hierarchical arrangement of objects, starting at request.app.root. """ import string import sys import types try: classtype = (type, types.ClassType) except AttributeError: classtype = type import cherrypy class PageHandler(object): """Callable which sets response.body.""" def __init__(self, callable, *args, **kwargs): self.callable = callable self.args = args self.kwargs = kwargs @property def args(self): """The ordered args should be accessible from post dispatch hooks.""" return cherrypy.serving.request.args @args.setter def args(self, args): cherrypy.serving.request.args = args return cherrypy.serving.request.args @property def kwargs(self): """The named kwargs should be accessible from post dispatch hooks.""" return cherrypy.serving.request.kwargs @kwargs.setter def kwargs(self, kwargs): cherrypy.serving.request.kwargs = kwargs return cherrypy.serving.request.kwargs def __call__(self): try: return self.callable(*self.args, **self.kwargs) except TypeError: x = sys.exc_info()[1] try: test_callable_spec(self.callable, self.args, self.kwargs) except cherrypy.HTTPError: raise sys.exc_info()[1] except Exception: raise x raise def test_callable_spec(callable, callable_args, callable_kwargs): """ Inspect callable and test to see if the given args are suitable for it. When an error occurs during the handler's invoking stage there are 2 erroneous cases: 1. Too many parameters passed to a function which doesn't define one of *args or **kwargs. 2. Too little parameters are passed to the function. There are 3 sources of parameters to a cherrypy handler. 1. query string parameters are passed as keyword parameters to the handler. 2. body parameters are also passed as keyword parameters. 3. when partial matching occurs, the final path atoms are passed as positional args. Both the query string and path atoms are part of the URI. If they are incorrect, then a 404 Not Found should be raised. Conversely the body parameters are part of the request; if they are invalid a 400 Bad Request. """ show_mismatched_params = getattr( cherrypy.serving.request, 'show_mismatched_params', False) try: (args, varargs, varkw, defaults) = getargspec(callable) except TypeError: if isinstance(callable, object) and hasattr(callable, '__call__'): (args, varargs, varkw, defaults) = getargspec(callable.__call__) else: # If it wasn't one of our own types, re-raise # the original error raise if args and ( # For callable objects, which have a __call__(self) method hasattr(callable, '__call__') or # For normal methods inspect.ismethod(callable) ): # Strip 'self' args = args[1:] arg_usage = dict([(arg, 0,) for arg in args]) vararg_usage = 0 varkw_usage = 0 extra_kwargs = set() for i, value in enumerate(callable_args): try: arg_usage[args[i]] += 1 except IndexError: vararg_usage += 1 for key in callable_kwargs.keys(): try: arg_usage[key] += 1 except KeyError: varkw_usage += 1 extra_kwargs.add(key) # figure out which args have defaults. args_with_defaults = args[-len(defaults or []):] for i, val in enumerate(defaults or []): # Defaults take effect only when the arg hasn't been used yet. if arg_usage[args_with_defaults[i]] == 0: arg_usage[args_with_defaults[i]] += 1 missing_args = [] multiple_args = [] for key, usage in arg_usage.items(): if usage == 0: missing_args.append(key) elif usage > 1: multiple_args.append(key) if missing_args: # In the case where the method allows body arguments # there are 3 potential errors: # 1. not enough query string parameters -> 404 # 2. not enough body parameters -> 400 # 3. not enough path parts (partial matches) -> 404 # # We can't actually tell which case it is, # so I'm raising a 404 because that covers 2/3 of the # possibilities # # In the case where the method does not allow body # arguments it's definitely a 404. message = None if show_mismatched_params: message = 'Missing parameters: %s' % ','.join(missing_args) raise cherrypy.HTTPError(404, message=message) # the extra positional arguments come from the path - 404 Not Found if not varargs and vararg_usage > 0: raise cherrypy.HTTPError(404) body_params = cherrypy.serving.request.body.params or {} body_params = set(body_params.keys()) qs_params = set(callable_kwargs.keys()) - body_params if multiple_args: if qs_params.intersection(set(multiple_args)): # If any of the multiple parameters came from the query string then # it's a 404 Not Found error = 404 else: # Otherwise it's a 400 Bad Request error = 400 message = None if show_mismatched_params: message = 'Multiple values for parameters: '\ '%s' % ','.join(multiple_args) raise cherrypy.HTTPError(error, message=message) if not varkw and varkw_usage > 0: # If there were extra query string parameters, it's a 404 Not Found extra_qs_params = set(qs_params).intersection(extra_kwargs) if extra_qs_params: message = None if show_mismatched_params: message = 'Unexpected query string '\ 'parameters: %s' % ', '.join(extra_qs_params) raise cherrypy.HTTPError(404, message=message) # If there were any extra body parameters, it's a 400 Not Found extra_body_params = set(body_params).intersection(extra_kwargs) if extra_body_params: message = None if show_mismatched_params: message = 'Unexpected body parameters: '\ '%s' % ', '.join(extra_body_params) raise cherrypy.HTTPError(400, message=message) try: import inspect except ImportError: def test_callable_spec(callable, args, kwargs): # noqa: F811 return None else: def getargspec(callable): return inspect.getfullargspec(callable)[:4] class LateParamPageHandler(PageHandler): """When passing cherrypy.request.params to the page handler, we do not want to capture that dict too early; we want to give tools like the decoding tool a chance to modify the params dict in-between the lookup of the handler and the actual calling of the handler. This subclass takes that into account, and allows request.params to be 'bound late' (it's more complicated than that, but that's the effect). """ @property def kwargs(self): """Page handler kwargs (with cherrypy.request.params copied in).""" kwargs = cherrypy.serving.request.params.copy() if self._kwargs: kwargs.update(self._kwargs) return kwargs @kwargs.setter def kwargs(self, kwargs): cherrypy.serving.request.kwargs = kwargs self._kwargs = kwargs if sys.version_info < (3, 0): punctuation_to_underscores = string.maketrans( string.punctuation, '_' * len(string.punctuation)) def validate_translator(t): if not isinstance(t, str) or len(t) != 256: raise ValueError( 'The translate argument must be a str of len 256.') else: punctuation_to_underscores = str.maketrans( string.punctuation, '_' * len(string.punctuation)) def validate_translator(t): if not isinstance(t, dict): raise ValueError('The translate argument must be a dict.') class Dispatcher(object): """CherryPy Dispatcher which walks a tree of objects to find a handler. The tree is rooted at cherrypy.request.app.root, and each hierarchical component in the path_info argument is matched to a corresponding nested attribute of the root object. Matching handlers must have an 'exposed' attribute which evaluates to True. The special method name "index" matches a URI which ends in a slash ("/"). The special method name "default" may match a portion of the path_info (but only when no longer substring of the path_info matches some other object). This is the default, built-in dispatcher for CherryPy. """ dispatch_method_name = '_cp_dispatch' """ The name of the dispatch method that nodes may optionally implement to provide their own dynamic dispatch algorithm. """ def __init__(self, dispatch_method_name=None, translate=punctuation_to_underscores): validate_translator(translate) self.translate = translate if dispatch_method_name: self.dispatch_method_name = dispatch_method_name def __call__(self, path_info): """Set handler and config for the current request.""" request = cherrypy.serving.request func, vpath = self.find_handler(path_info) if func: # Decode any leftover %2F in the virtual_path atoms. vpath = [x.replace('%2F', '/') for x in vpath] request.handler = LateParamPageHandler(func, *vpath) else: request.handler = cherrypy.NotFound() def find_handler(self, path): """Return the appropriate page handler, plus any virtual path. This will return two objects. The first will be a callable, which can be used to generate page output. Any parameters from the query string or request body will be sent to that callable as keyword arguments. The callable is found by traversing the application's tree, starting from cherrypy.request.app.root, and matching path components to successive objects in the tree. For example, the URL "/path/to/handler" might return root.path.to.handler. The second object returned will be a list of names which are 'virtual path' components: parts of the URL which are dynamic, and were not used when looking up the handler. These virtual path components are passed to the handler as positional arguments. """ request = cherrypy.serving.request app = request.app root = app.root dispatch_name = self.dispatch_method_name # Get config for the root object/path. fullpath = [x for x in path.strip('/').split('/') if x] + ['index'] fullpath_len = len(fullpath) segleft = fullpath_len nodeconf = {} if hasattr(root, '_cp_config'): nodeconf.update(root._cp_config) if '/' in app.config: nodeconf.update(app.config['/']) object_trail = [['root', root, nodeconf, segleft]] node = root iternames = fullpath[:] while iternames: name = iternames[0] # map to legal Python identifiers (e.g. replace '.' with '_') objname = name.translate(self.translate) nodeconf = {} subnode = getattr(node, objname, None) pre_len = len(iternames) if subnode is None: dispatch = getattr(node, dispatch_name, None) if dispatch and hasattr(dispatch, '__call__') and not \ getattr(dispatch, 'exposed', False) and \ pre_len > 1: # Don't expose the hidden 'index' token to _cp_dispatch # We skip this if pre_len == 1 since it makes no sense # to call a dispatcher when we have no tokens left. index_name = iternames.pop() subnode = dispatch(vpath=iternames) iternames.append(index_name) else: # We didn't find a path, but keep processing in case there # is a default() handler. iternames.pop(0) else: # We found the path, remove the vpath entry iternames.pop(0) segleft = len(iternames) if segleft > pre_len: # No path segment was removed. Raise an error. raise cherrypy.CherryPyException( 'A vpath segment was added. Custom dispatchers may only ' 'remove elements. While trying to process ' '{0} in {1}'.format(name, fullpath) ) elif segleft == pre_len: # Assume that the handler used the current path segment, but # did not pop it. This allows things like # return getattr(self, vpath[0], None) iternames.pop(0) segleft -= 1 node = subnode if node is not None: # Get _cp_config attached to this node. if hasattr(node, '_cp_config'): nodeconf.update(node._cp_config) # Mix in values from app.config for this path. existing_len = fullpath_len - pre_len if existing_len != 0: curpath = '/' + '/'.join(fullpath[0:existing_len]) else: curpath = '' new_segs = fullpath[fullpath_len - pre_len:fullpath_len - segleft] for seg in new_segs: curpath += '/' + seg if curpath in app.config: nodeconf.update(app.config[curpath]) object_trail.append([name, node, nodeconf, segleft]) def set_conf(): """Collapse all object_trail config into cherrypy.request.config. """ base = cherrypy.config.copy() # Note that we merge the config from each node # even if that node was None. for name, obj, conf, segleft in object_trail: base.update(conf) if 'tools.staticdir.dir' in conf: base['tools.staticdir.section'] = '/' + \ '/'.join(fullpath[0:fullpath_len - segleft]) return base # Try successive objects (reverse order) num_candidates = len(object_trail) - 1 for i in range(num_candidates, -1, -1): name, candidate, nodeconf, segleft = object_trail[i] if candidate is None: continue # Try a "default" method on the current leaf. if hasattr(candidate, 'default'): defhandler = candidate.default if getattr(defhandler, 'exposed', False): # Insert any extra _cp_config from the default handler. conf = getattr(defhandler, '_cp_config', {}) object_trail.insert( i + 1, ['default', defhandler, conf, segleft]) request.config = set_conf() # See https://github.com/cherrypy/cherrypy/issues/613 request.is_index = path.endswith('/') return defhandler, fullpath[fullpath_len - segleft:-1] # Uncomment the next line to restrict positional params to # "default". # if i < num_candidates - 2: continue # Try the current leaf. if getattr(candidate, 'exposed', False): request.config = set_conf() if i == num_candidates: # We found the extra ".index". Mark request so tools # can redirect if path_info has no trailing slash. request.is_index = True else: # We're not at an 'index' handler. Mark request so tools # can redirect if path_info has NO trailing slash. # Note that this also includes handlers which take # positional parameters (virtual paths). request.is_index = False return candidate, fullpath[fullpath_len - segleft:-1] # We didn't find anything request.config = set_conf() return None, [] class MethodDispatcher(Dispatcher): """Additional dispatch based on cherrypy.request.method.upper(). Methods named GET, POST, etc will be called on an exposed class. The method names must be all caps; the appropriate Allow header will be output showing all capitalized method names as allowable HTTP verbs. Note that the containing class must be exposed, not the methods. """ def __call__(self, path_info): """Set handler and config for the current request.""" request = cherrypy.serving.request resource, vpath = self.find_handler(path_info) if resource: # Set Allow header avail = [m for m in dir(resource) if m.isupper()] if 'GET' in avail and 'HEAD' not in avail: avail.append('HEAD') avail.sort() cherrypy.serving.response.headers['Allow'] = ', '.join(avail) # Find the subhandler meth = request.method.upper() func = getattr(resource, meth, None) if func is None and meth == 'HEAD': func = getattr(resource, 'GET', None) if func: # Grab any _cp_config on the subhandler. if hasattr(func, '_cp_config'): request.config.update(func._cp_config) # Decode any leftover %2F in the virtual_path atoms. vpath = [x.replace('%2F', '/') for x in vpath] request.handler = LateParamPageHandler(func, *vpath) else: request.handler = cherrypy.HTTPError(405) else: request.handler = cherrypy.NotFound() class RoutesDispatcher(object): """A Routes based dispatcher for CherryPy.""" def __init__(self, full_result=False, **mapper_options): """ Routes dispatcher Set full_result to True if you wish the controller and the action to be passed on to the page handler parameters. By default they won't be. """ import routes self.full_result = full_result self.controllers = {} self.mapper = routes.Mapper(**mapper_options) self.mapper.controller_scan = self.controllers.keys def connect(self, name, route, controller, **kwargs): self.controllers[name] = controller self.mapper.connect(name, route, controller=name, **kwargs) def redirect(self, url): raise cherrypy.HTTPRedirect(url) def __call__(self, path_info): """Set handler and config for the current request.""" func = self.find_handler(path_info) if func: cherrypy.serving.request.handler = LateParamPageHandler(func) else: cherrypy.serving.request.handler = cherrypy.NotFound() def find_handler(self, path_info): """Find the right page handler, and set request.config.""" import routes request = cherrypy.serving.request config = routes.request_config() config.mapper = self.mapper if hasattr(request, 'wsgi_environ'): config.environ = request.wsgi_environ config.host = request.headers.get('Host', None) config.protocol = request.scheme config.redirect = self.redirect result = self.mapper.match(path_info) config.mapper_dict = result params = {} if result: params = result.copy() if not self.full_result: params.pop('controller', None) params.pop('action', None) request.params.update(params) # Get config for the root object/path. request.config = base = cherrypy.config.copy() curpath = '' def merge(nodeconf): if 'tools.staticdir.dir' in nodeconf: nodeconf['tools.staticdir.section'] = curpath or '/' base.update(nodeconf) app = request.app root = app.root if hasattr(root, '_cp_config'): merge(root._cp_config) if '/' in app.config: merge(app.config['/']) # Mix in values from app.config. atoms = [x for x in path_info.split('/') if x] if atoms: last = atoms.pop() else: last = None for atom in atoms: curpath = '/'.join((curpath, atom)) if curpath in app.config: merge(app.config[curpath]) handler = None if result: controller = result.get('controller') controller = self.controllers.get(controller, controller) if controller: if isinstance(controller, classtype): controller = controller() # Get config from the controller. if hasattr(controller, '_cp_config'): merge(controller._cp_config) action = result.get('action') if action is not None: handler = getattr(controller, action, None) # Get config from the handler if hasattr(handler, '_cp_config'): merge(handler._cp_config) else: handler = controller # Do the last path atom here so it can # override the controller's _cp_config. if last: curpath = '/'.join((curpath, last)) if curpath in app.config: merge(app.config[curpath]) return handler def XMLRPCDispatcher(next_dispatcher=Dispatcher()): from cherrypy.lib import xmlrpcutil def xmlrpc_dispatch(path_info): path_info = xmlrpcutil.patched_path(path_info) return next_dispatcher(path_info) return xmlrpc_dispatch def VirtualHost(next_dispatcher=Dispatcher(), use_x_forwarded_host=True, **domains): """ Select a different handler based on the Host header. This can be useful when running multiple sites within one CP server. It allows several domains to point to different parts of a single website structure. For example:: http://www.domain.example -> root http://www.domain2.example -> root/domain2/ http://www.domain2.example:443 -> root/secure can be accomplished via the following config:: [/] request.dispatch = cherrypy.dispatch.VirtualHost( **{'www.domain2.example': '/domain2', 'www.domain2.example:443': '/secure', }) next_dispatcher The next dispatcher object in the dispatch chain. The VirtualHost dispatcher adds a prefix to the URL and calls another dispatcher. Defaults to cherrypy.dispatch.Dispatcher(). use_x_forwarded_host If True (the default), any "X-Forwarded-Host" request header will be used instead of the "Host" header. This is commonly added by HTTP servers (such as Apache) when proxying. ``**domains`` A dict of {host header value: virtual prefix} pairs. The incoming "Host" request header is looked up in this dict, and, if a match is found, the corresponding "virtual prefix" value will be prepended to the URL path before calling the next dispatcher. Note that you often need separate entries for "example.com" and "www.example.com". In addition, "Host" headers may contain the port number. """ from cherrypy.lib import httputil def vhost_dispatch(path_info): request = cherrypy.serving.request header = request.headers.get domain = header('Host', '') if use_x_forwarded_host: domain = header('X-Forwarded-Host', domain) prefix = domains.get(domain, '') if prefix: path_info = httputil.urljoin(prefix, path_info) result = next_dispatcher(path_info) # Touch up staticdir config. See # https://github.com/cherrypy/cherrypy/issues/614. section = request.config.get('tools.staticdir.section') if section: section = section[len(prefix):] request.config['tools.staticdir.section'] = section return result return vhost_dispatch
bsd-3-clause
5bdae5491bb0095204a756a5ce47e6c6
35.973607
79
0.591172
4.495632
false
true
false
false
cherrypy/cherrypy
cherrypy/_cpserver.py
10
8320
"""Manage HTTP servers with CherryPy.""" import cherrypy from cherrypy.lib.reprconf import attributes from cherrypy._cpcompat import text_or_bytes from cherrypy.process.servers import ServerAdapter __all__ = ('Server', ) class Server(ServerAdapter): """An adapter for an HTTP server. You can set attributes (like socket_host and socket_port) on *this* object (which is probably cherrypy.server), and call quickstart. For example:: cherrypy.server.socket_port = 80 cherrypy.quickstart() """ socket_port = 8080 """The TCP port on which to listen for connections.""" _socket_host = '127.0.0.1' @property def socket_host(self): # noqa: D401; irrelevant for properties """The hostname or IP address on which to listen for connections. Host values may be any IPv4 or IPv6 address, or any valid hostname. The string 'localhost' is a synonym for '127.0.0.1' (or '::1', if your hosts file prefers IPv6). The string '0.0.0.0' is a special IPv4 entry meaning "any active interface" (INADDR_ANY), and '::' is the similar IN6ADDR_ANY for IPv6. The empty string or None are not allowed. """ return self._socket_host @socket_host.setter def socket_host(self, value): if value == '': raise ValueError("The empty string ('') is not an allowed value. " "Use '0.0.0.0' instead to listen on all active " 'interfaces (INADDR_ANY).') self._socket_host = value socket_file = None """If given, the name of the UNIX socket to use instead of TCP/IP. When this option is not None, the `socket_host` and `socket_port` options are ignored.""" socket_queue_size = 5 """The 'backlog' argument to socket.listen(); specifies the maximum number of queued connections (default 5).""" socket_timeout = 10 """The timeout in seconds for accepted connections (default 10).""" accepted_queue_size = -1 """The maximum number of requests which will be queued up before the server refuses to accept it (default -1, meaning no limit).""" accepted_queue_timeout = 10 """The timeout in seconds for attempting to add a request to the queue when the queue is full (default 10).""" shutdown_timeout = 5 """The time to wait for HTTP worker threads to clean up.""" protocol_version = 'HTTP/1.1' """The version string to write in the Status-Line of all HTTP responses, for example, "HTTP/1.1" (the default). Depending on the HTTP server used, this should also limit the supported features used in the response.""" thread_pool = 10 """The number of worker threads to start up in the pool.""" thread_pool_max = -1 """The maximum size of the worker-thread pool. Use -1 to indicate no limit. """ max_request_header_size = 500 * 1024 """The maximum number of bytes allowable in the request headers. If exceeded, the HTTP server should return "413 Request Entity Too Large". """ max_request_body_size = 100 * 1024 * 1024 """The maximum number of bytes allowable in the request body. If exceeded, the HTTP server should return "413 Request Entity Too Large".""" instance = None """If not None, this should be an HTTP server instance (such as cheroot.wsgi.Server) which cherrypy.server will control. Use this when you need more control over object instantiation than is available in the various configuration options.""" ssl_context = None """When using PyOpenSSL, an instance of SSL.Context.""" ssl_certificate = None """The filename of the SSL certificate to use.""" ssl_certificate_chain = None """When using PyOpenSSL, the certificate chain to pass to Context.load_verify_locations.""" ssl_private_key = None """The filename of the private key to use with SSL.""" ssl_ciphers = None """The ciphers list of SSL.""" ssl_module = 'builtin' """The name of a registered SSL adaptation module to use with the builtin WSGI server. Builtin options are: 'builtin' (to use the SSL library built into recent versions of Python). You may also register your own classes in the cheroot.server.ssl_adapters dict.""" statistics = False """Turns statistics-gathering on or off for aware HTTP servers.""" nodelay = True """If True (the default since 3.1), sets the TCP_NODELAY socket option.""" wsgi_version = (1, 0) """The WSGI version tuple to use with the builtin WSGI server. The provided options are (1, 0) [which includes support for PEP 3333, which declares it covers WSGI version 1.0.1 but still mandates the wsgi.version (1, 0)] and ('u', 0), an experimental unicode version. You may create and register your own experimental versions of the WSGI protocol by adding custom classes to the cheroot.server.wsgi_gateways dict. """ peercreds = False """If True, peer cred lookup for UNIX domain socket will put to WSGI env. This information will then be available through WSGI env vars: * X_REMOTE_PID * X_REMOTE_UID * X_REMOTE_GID """ peercreds_resolve = False """If True, username/group will be looked up in the OS from peercreds. This information will then be available through WSGI env vars: * REMOTE_USER * X_REMOTE_USER * X_REMOTE_GROUP """ def __init__(self): """Initialize Server instance.""" self.bus = cherrypy.engine self.httpserver = None self.interrupt = None self.running = False def httpserver_from_self(self, httpserver=None): """Return a (httpserver, bind_addr) pair based on self attributes.""" if httpserver is None: httpserver = self.instance if httpserver is None: from cherrypy import _cpwsgi_server httpserver = _cpwsgi_server.CPWSGIServer(self) if isinstance(httpserver, text_or_bytes): # Is anyone using this? Can I add an arg? httpserver = attributes(httpserver)(self) return httpserver, self.bind_addr def start(self): """Start the HTTP server.""" if not self.httpserver: self.httpserver, self.bind_addr = self.httpserver_from_self() super(Server, self).start() start.priority = 75 @property def bind_addr(self): """Return bind address. A (host, port) tuple for TCP sockets or a str for Unix domain sockts. """ if self.socket_file: return self.socket_file if self.socket_host is None and self.socket_port is None: return None return (self.socket_host, self.socket_port) @bind_addr.setter def bind_addr(self, value): if value is None: self.socket_file = None self.socket_host = None self.socket_port = None elif isinstance(value, text_or_bytes): self.socket_file = value self.socket_host = None self.socket_port = None else: try: self.socket_host, self.socket_port = value self.socket_file = None except ValueError: raise ValueError('bind_addr must be a (host, port) tuple ' '(for TCP sockets) or a string (for Unix ' 'domain sockets), not %r' % value) def base(self): """Return the base for this server. e.i. scheme://host[:port] or sock file """ if self.socket_file: return self.socket_file host = self.socket_host if host in ('0.0.0.0', '::'): # 0.0.0.0 is INADDR_ANY and :: is IN6ADDR_ANY. # Look up the host name, which should be the # safest thing to spit out in a URL. import socket host = socket.gethostname() port = self.socket_port if self.ssl_certificate: scheme = 'https' if port != 443: host += ':%s' % port else: scheme = 'http' if port != 80: host += ':%s' % port return '%s://%s' % (scheme, host)
bsd-3-clause
06f089dd83f15678474cf151ff5338d0
33.522822
79
0.619111
4.221208
false
false
false
false
mozilla/mozilla-ignite
vendor-local/src/django-voting/voting/templatetags/voting_tags.py
32
8050
from django import template from django.utils.html import escape from voting.models import Vote register = template.Library() # Tags class ScoreForObjectNode(template.Node): def __init__(self, object, context_var): self.object = object self.context_var = context_var def render(self, context): try: object = template.resolve_variable(self.object, context) except template.VariableDoesNotExist: return '' context[self.context_var] = Vote.objects.get_score(object) return '' class ScoresForObjectsNode(template.Node): def __init__(self, objects, context_var): self.objects = objects self.context_var = context_var def render(self, context): try: objects = template.resolve_variable(self.objects, context) except template.VariableDoesNotExist: return '' context[self.context_var] = Vote.objects.get_scores_in_bulk(objects) return '' class VoteByUserNode(template.Node): def __init__(self, user, object, context_var): self.user = user self.object = object self.context_var = context_var def render(self, context): try: user = template.resolve_variable(self.user, context) object = template.resolve_variable(self.object, context) except template.VariableDoesNotExist: return '' context[self.context_var] = Vote.objects.get_for_user(object, user) return '' class VotesByUserNode(template.Node): def __init__(self, user, objects, context_var): self.user = user self.objects = objects self.context_var = context_var def render(self, context): try: user = template.resolve_variable(self.user, context) objects = template.resolve_variable(self.objects, context) except template.VariableDoesNotExist: return '' context[self.context_var] = Vote.objects.get_for_user_in_bulk(objects, user) return '' class DictEntryForItemNode(template.Node): def __init__(self, item, dictionary, context_var): self.item = item self.dictionary = dictionary self.context_var = context_var def render(self, context): try: dictionary = template.resolve_variable(self.dictionary, context) item = template.resolve_variable(self.item, context) except template.VariableDoesNotExist: return '' context[self.context_var] = dictionary.get(item.id, None) return '' def do_score_for_object(parser, token): """ Retrieves the total score for an object and the number of votes it's received and stores them in a context variable which has ``score`` and ``num_votes`` properties. Example usage:: {% score_for_object widget as score %} {{ score.score }}point{{ score.score|pluralize }} after {{ score.num_votes }} vote{{ score.num_votes|pluralize }} """ bits = token.contents.split() if len(bits) != 4: raise template.TemplateSyntaxError("'%s' tag takes exactly three arguments" % bits[0]) if bits[2] != 'as': raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0]) return ScoreForObjectNode(bits[1], bits[3]) def do_scores_for_objects(parser, token): """ Retrieves the total scores for a list of objects and the number of votes they have received and stores them in a context variable. Example usage:: {% scores_for_objects widget_list as score_dict %} """ bits = token.contents.split() if len(bits) != 4: raise template.TemplateSyntaxError("'%s' tag takes exactly three arguments" % bits[0]) if bits[2] != 'as': raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0]) return ScoresForObjectsNode(bits[1], bits[3]) def do_vote_by_user(parser, token): """ Retrieves the ``Vote`` cast by a user on a particular object and stores it in a context variable. If the user has not voted, the context variable will be ``None``. Example usage:: {% vote_by_user user on widget as vote %} """ bits = token.contents.split() if len(bits) != 6: raise template.TemplateSyntaxError("'%s' tag takes exactly five arguments" % bits[0]) if bits[2] != 'on': raise template.TemplateSyntaxError("second argument to '%s' tag must be 'on'" % bits[0]) if bits[4] != 'as': raise template.TemplateSyntaxError("fourth argument to '%s' tag must be 'as'" % bits[0]) return VoteByUserNode(bits[1], bits[3], bits[5]) def do_votes_by_user(parser, token): """ Retrieves the votes cast by a user on a list of objects as a dictionary keyed with object ids and stores it in a context variable. Example usage:: {% votes_by_user user on widget_list as vote_dict %} """ bits = token.contents.split() if len(bits) != 6: raise template.TemplateSyntaxError("'%s' tag takes exactly four arguments" % bits[0]) if bits[2] != 'on': raise template.TemplateSyntaxError("second argument to '%s' tag must be 'on'" % bits[0]) if bits[4] != 'as': raise template.TemplateSyntaxError("fourth argument to '%s' tag must be 'as'" % bits[0]) return VotesByUserNode(bits[1], bits[3], bits[5]) def do_dict_entry_for_item(parser, token): """ Given an object and a dictionary keyed with object ids - as returned by the ``votes_by_user`` and ``scores_for_objects`` template tags - retrieves the value for the given object and stores it in a context variable, storing ``None`` if no value exists for the given object. Example usage:: {% dict_entry_for_item widget from vote_dict as vote %} """ bits = token.contents.split() if len(bits) != 6: raise template.TemplateSyntaxError("'%s' tag takes exactly five arguments" % bits[0]) if bits[2] != 'from': raise template.TemplateSyntaxError("second argument to '%s' tag must be 'from'" % bits[0]) if bits[4] != 'as': raise template.TemplateSyntaxError("fourth argument to '%s' tag must be 'as'" % bits[0]) return DictEntryForItemNode(bits[1], bits[3], bits[5]) register.tag('score_for_object', do_score_for_object) register.tag('scores_for_objects', do_scores_for_objects) register.tag('vote_by_user', do_vote_by_user) register.tag('votes_by_user', do_votes_by_user) register.tag('dict_entry_for_item', do_dict_entry_for_item) # Simple Tags def confirm_vote_message(object_description, vote_direction): """ Creates an appropriate message asking the user to confirm the given vote for the given object description. Example usage:: {% confirm_vote_message widget.title direction %} """ if vote_direction == 'clear': message = 'Confirm clearing your vote for <strong>%s</strong>.' else: message = 'Confirm <strong>%s</strong> vote for <strong>%%s</strong>.' % vote_direction return message % (escape(object_description),) register.simple_tag(confirm_vote_message) # Filters def vote_display(vote, arg=None): """ Given a string mapping values for up and down votes, returns one of the strings according to the given ``Vote``: ========= ===================== ============= Vote type Argument Outputs ========= ===================== ============= ``+1`` ``"Bodacious,Bogus"`` ``Bodacious`` ``-1`` ``"Bodacious,Bogus"`` ``Bogus`` ========= ===================== ============= If no string mapping is given, "Up" and "Down" will be used. Example usage:: {{ vote|vote_display:"Bodacious,Bogus" }} """ if arg is None: arg = 'Up,Down' bits = arg.split(',') if len(bits) != 2: return vote.vote # Invalid arg up, down = bits if vote.vote == 1: return up return down register.filter(vote_display)
bsd-3-clause
be0f15ad0479801990048a706c88a06a
33.852814
98
0.626335
3.870192
false
false
false
false
mozilla/mozilla-ignite
apps/projects/migrations/0005_auto__add_link__del_field_project_github__del_field_project_blog.py
2
10765
# encoding: utf-8 from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Link' db.create_table('projects_link', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=100)), ('url', self.gf('django.db.models.fields.URLField')(max_length=200)), ('subscribe', self.gf('django.db.models.fields.BooleanField')(default=False)), ('blog', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal('projects', ['Link']) # Adding M2M table for field links on 'Project' db.create_table('projects_project_links', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('project', models.ForeignKey(orm['projects.project'], null=False)), ('link', models.ForeignKey(orm['projects.link'], null=False)) )) db.create_unique('projects_project_links', ['project_id', 'link_id']) if not db.dry_run: result = db.execute('SELECT id, blog, github FROM projects_project') for row in result: id, blog, github = row project = orm.Project.objects.get(id=id) if github: github_link = orm.Link(name=u'Source Code', url=github) github_link.save() project.links.add(github_link) if blog: blog_link = orm.Link(name=u'Blog', url=blog, blog=True) blog_link.save() project.links.add(blog_link) project.save() # Deleting field 'Project.github' db.delete_column('projects_project', 'github') # Deleting field 'Project.blog' db.delete_column('projects_project', 'blog') def backwards(self, orm): # Deleting model 'Link' db.delete_table('projects_link') # Adding field 'Project.github' db.add_column('projects_project', 'github', self.gf('django.db.models.fields.URLField')(max_length=200, null=True, blank=True), keep_default=False) # Adding field 'Project.blog' db.add_column('projects_project', 'blog', self.gf('django.db.models.fields.URLField')(max_length=200, null=True, blank=True), keep_default=False) # Removing M2M table for field links on 'Project' db.delete_table('projects_project_links') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'projects.link': { 'Meta': {'object_name': 'Link'}, 'blog': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'subscribe': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}) }, 'projects.project': { 'Meta': {'object_name': 'Project'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'featured_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'links': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['projects.Link']", 'symmetrical': 'False'}), 'long_description': ('django.db.models.fields.TextField', [], {}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}), 'team_members': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['users.Profile']", 'symmetrical': 'False'}), 'topics': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['topics.Topic']", 'symmetrical': 'False'}) }, 'taggit.tag': { 'Meta': {'object_name': 'Tag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}) }, 'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"}) }, 'topics.topic': { 'Meta': {'object_name': 'Topic'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'long_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}) }, 'users.link': { 'Meta': {'object_name': 'Link'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'service': ('django.db.models.fields.CharField', [], {'default': "u'other'", 'max_length': '50'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '255'}) }, 'users.profile': { 'Meta': {'object_name': 'Profile'}, 'avatar': ('django.db.models.fields.files.ImageField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'bio': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'featured_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'links': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['users.Link']", 'symmetrical': 'False', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}) } } complete_apps = ['projects']
bsd-3-clause
c4d9dda8c1891fd922f521909aca98a5
63.077381
182
0.550302
3.726203
false
false
false
false
mozilla/mozilla-ignite
vendor-local/lib/python/django_extensions/mongodb/models.py
40
2596
""" Django Extensions abstract base mongoengine Document classes. """ import datetime from mongoengine.document import Document from mongoengine.fields import StringField, IntField, DateTimeField from mongoengine.queryset import QuerySetManager from django.utils.translation import ugettext_lazy as _ from django_extensions.mongodb.fields import (ModificationDateTimeField, CreationDateTimeField, AutoSlugField) class TimeStampedModel(Document): """ TimeStampedModel An abstract base class model that provides self-managed "created" and "modified" fields. """ created = CreationDateTimeField(_('created')) modified = ModificationDateTimeField(_('modified')) class Meta: abstract = True class TitleSlugDescriptionModel(Document): """ TitleSlugDescriptionModel An abstract base class model that provides title and description fields and a self-managed "slug" field that populates from the title. """ title = StringField(_('title'), max_length=255) slug = AutoSlugField(_('slug'), populate_from='title') description = StringField(_('description'), blank=True, null=True) class Meta: abstract = True class ActivatorModelManager(QuerySetManager): """ ActivatorModelManager Manager to return instances of ActivatorModel: SomeModel.objects.active() / .inactive() """ def active(self): """ Returns active instances of ActivatorModel: SomeModel.objects.active() """ return super(ActivatorModelManager, self).get_query_set().filter(status=1) def inactive(self): """ Returns inactive instances of ActivatorModel: SomeModel.objects.inactive() """ return super(ActivatorModelManager, self).get_query_set().filter(status=0) class ActivatorModel(Document): """ ActivatorModel An abstract base class model that provides activate and deactivate fields. """ STATUS_CHOICES = ( (0, _('Inactive')), (1, _('Active')), ) status = IntField(_('status'), choices=STATUS_CHOICES, default=1) activate_date = DateTimeField(blank=True, null=True, help_text=_('keep empty for an immediate activation')) deactivate_date = DateTimeField(blank=True, null=True, help_text=_('keep empty for indefinite activation')) objects = ActivatorModelManager() class Meta: abstract = True def save(self, *args, **kwargs): if not self.activate_date: self.activate_date = datetime.datetime.now() super(ActivatorModel, self).save(*args, **kwargs)
bsd-3-clause
7457094da01268046f9cf1c9928d5947
36.623188
91
0.691448
4.468158
false
false
false
false
mozilla/mozilla-ignite
vendor-local/lib/python/requests/packages/urllib3/connectionpool.py
33
18424
# urllib3/connectionpool.py # Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import logging import socket from socket import error as SocketError, timeout as SocketTimeout try: # Python 3 from http.client import HTTPConnection, HTTPException from http.client import HTTP_PORT, HTTPS_PORT except ImportError: from httplib import HTTPConnection, HTTPException from httplib import HTTP_PORT, HTTPS_PORT try: # Python 3 from queue import LifoQueue, Empty, Full except ImportError: from Queue import LifoQueue, Empty, Full try: # Compiled with SSL? HTTPSConnection = object BaseSSLError = None ssl = None try: # Python 3 from http.client import HTTPSConnection except ImportError: from httplib import HTTPSConnection import ssl BaseSSLError = ssl.SSLError except (ImportError, AttributeError): pass from .request import RequestMethods from .response import HTTPResponse from .util import get_host, is_connection_dropped from .exceptions import ( EmptyPoolError, HostChangedError, MaxRetryError, SSLError, TimeoutError, ) from .packages.ssl_match_hostname import match_hostname, CertificateError from .packages import six xrange = six.moves.xrange log = logging.getLogger(__name__) _Default = object() port_by_scheme = { 'http': HTTP_PORT, 'https': HTTPS_PORT, } ## Connection objects (extension of httplib) class VerifiedHTTPSConnection(HTTPSConnection): """ Based on httplib.HTTPSConnection but wraps the socket with SSL certification. """ cert_reqs = None ca_certs = None def set_cert(self, key_file=None, cert_file=None, cert_reqs='CERT_NONE', ca_certs=None): ssl_req_scheme = { 'CERT_NONE': ssl.CERT_NONE, 'CERT_OPTIONAL': ssl.CERT_OPTIONAL, 'CERT_REQUIRED': ssl.CERT_REQUIRED } self.key_file = key_file self.cert_file = cert_file self.cert_reqs = ssl_req_scheme.get(cert_reqs) or ssl.CERT_NONE self.ca_certs = ca_certs def connect(self): # Add certificate verification sock = socket.create_connection((self.host, self.port), self.timeout) # Wrap socket using verification with the root certs in # trusted_root_certs self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs) if self.ca_certs: match_hostname(self.sock.getpeercert(), self.host) ## Pool objects class ConnectionPool(object): """ Base class for all connection pools, such as :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`. """ scheme = None QueueCls = LifoQueue def __init__(self, host, port=None): self.host = host self.port = port def __str__(self): return '%s(host=%r, port=%r)' % (type(self).__name__, self.host, self.port) class HTTPConnectionPool(ConnectionPool, RequestMethods): """ Thread-safe connection pool for one host. :param host: Host used for this HTTP Connection (e.g. "localhost"), passed into :class:`httplib.HTTPConnection`. :param port: Port used for this HTTP Connection (None is equivalent to 80), passed into :class:`httplib.HTTPConnection`. :param strict: Causes BadStatusLine to be raised if the status line can't be parsed as a valid HTTP/1.0 or 1.1 status line, passed into :class:`httplib.HTTPConnection`. :param timeout: Socket timeout for each individual connection, can be a float. None disables timeout. :param maxsize: Number of connections to save that can be reused. More than 1 is useful in multithreaded situations. If ``block`` is set to false, more connections will be created but they will not be saved once they've been used. :param block: If set to True, no more than ``maxsize`` connections will be used at a time. When no free connections are available, the call will block until a connection has been released. This is a useful side effect for particular multithreaded situations where one does not want to use more than maxsize connections per host to prevent flooding. :param headers: Headers to include with all requests, unless other headers are given explicitly. """ scheme = 'http' def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1, block=False, headers=None): super(HTTPConnectionPool, self).__init__(host, port) self.strict = strict self.timeout = timeout self.pool = self.QueueCls(maxsize) self.block = block self.headers = headers or {} # Fill the queue up so that doing get() on it will block properly for _ in xrange(maxsize): self.pool.put(None) # These are mostly for testing and debugging purposes. self.num_connections = 0 self.num_requests = 0 def _new_conn(self): """ Return a fresh :class:`httplib.HTTPConnection`. """ self.num_connections += 1 log.info("Starting new HTTP connection (%d): %s" % (self.num_connections, self.host)) return HTTPConnection(host=self.host, port=self.port) def _get_conn(self, timeout=None): """ Get a connection. Will return a pooled connection if one is available. If no connections are available and :prop:`.block` is ``False``, then a fresh connection is returned. :param timeout: Seconds to wait before giving up and raising :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and :prop:`.block` is ``True``. """ conn = None try: conn = self.pool.get(block=self.block, timeout=timeout) # If this is a persistent connection, check if it got disconnected if conn and is_connection_dropped(conn): log.info("Resetting dropped connection: %s" % self.host) conn.close() except Empty: if self.block: raise EmptyPoolError(self, "Pool reached maximum size and no more " "connections are allowed.") pass # Oh well, we'll create a new connection then return conn or self._new_conn() def _put_conn(self, conn): """ Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is discarded because we exceeded maxsize. If connections are discarded frequently, then maxsize should be increased. """ try: self.pool.put(conn, block=False) except Full: # This should never happen if self.block == True log.warning("HttpConnectionPool is full, discarding connection: %s" % self.host) def _make_request(self, conn, method, url, timeout=_Default, **httplib_request_kw): """ Perform a request on a given httplib connection object taken from our pool. """ self.num_requests += 1 if timeout is _Default: timeout = self.timeout conn.timeout = timeout # This only does anything in Py26+ conn.request(method, url, **httplib_request_kw) # Set timeout sock = getattr(conn, 'sock', False) # AppEngine doesn't have sock attr. if sock: sock.settimeout(timeout) httplib_response = conn.getresponse() # AppEngine doesn't have a version attr. http_version = getattr(conn, '_http_vsn_str', 'HTTP/?'), log.debug("\"%s %s %s\" %s %s" % (method, url, http_version, httplib_response.status, httplib_response.length)) return httplib_response def is_same_host(self, url): """ Check if the given ``url`` is a member of the same host as this connection pool. """ # TODO: Add optional support for socket.gethostbyname checking. scheme, host, port = get_host(url) if self.port and not port: # Use explicit default port for comparison when none is given. port = port_by_scheme.get(scheme) return (url.startswith('/') or (scheme, host, port) == (self.scheme, self.host, self.port)) def urlopen(self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, **response_kw): """ Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param body: Data to send in the request body (useful for creating POST requests, see HTTPConnectionPool.post_url for more convenience). :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Number of retries to allow before raising a MaxRetryError exception. :param redirect: Automatically handle redirects (status codes 301, 302, 303, 307), each redirect counts as a retry. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When False, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param \**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib` """ if headers is None: headers = self.headers if retries < 0: raise MaxRetryError(self, url) if timeout is _Default: timeout = self.timeout if release_conn is None: release_conn = response_kw.get('preload_content', True) # Check host if assert_same_host and not self.is_same_host(url): host = "%s://%s" % (self.scheme, self.host) if self.port: host = "%s:%d" % (host, self.port) raise HostChangedError(self, url, retries - 1) conn = None try: # Request a connection from the queue # (Could raise SocketError: Bad file descriptor) conn = self._get_conn(timeout=pool_timeout) # Make the request on the httplib connection object httplib_response = self._make_request(conn, method, url, timeout=timeout, body=body, headers=headers) # If we're going to release the connection in ``finally:``, then # the request doesn't need to know about the connection. Otherwise # it will also try to release it and we'll have a double-release # mess. response_conn = not release_conn and conn # Import httplib's response into our own wrapper object response = HTTPResponse.from_httplib(httplib_response, pool=self, connection=response_conn, **response_kw) # else: # The connection will be put back into the pool when # ``response.release_conn()`` is called (implicitly by # ``response.read()``) except Empty as e: # Timed out by queue raise TimeoutError(self, "Request timed out. (pool_timeout=%s)" % pool_timeout) except SocketTimeout as e: # Timed out by socket raise TimeoutError(self, "Request timed out. (timeout=%s)" % timeout) except BaseSSLError as e: # SSL certificate error raise SSLError(e) except CertificateError as e: # Name mismatch raise SSLError(e) except (HTTPException, SocketError) as e: # Connection broken, discard. It will be replaced next _get_conn(). conn = None # This is necessary so we can access e below err = e finally: if conn and release_conn: # Put the connection back to be reused self._put_conn(conn) if not conn: log.warn("Retrying (%d attempts remain) after connection " "broken by '%r': %s" % (retries, err, url)) return self.urlopen(method, url, body, headers, retries - 1, redirect, assert_same_host) # Try again # Handle redirect? redirect_location = redirect and response.get_redirect_location() if redirect_location: log.info("Redirecting %s -> %s" % (url, redirect_location)) return self.urlopen(method, redirect_location, body, headers, retries - 1, redirect, assert_same_host) return response class HTTPSConnectionPool(HTTPConnectionPool): """ Same as :class:`.HTTPConnectionPool`, but HTTPS. When Python is compiled with the :mod:`ssl` module, then :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates, instead of :class:httplib.HTTPSConnection`. The ``key_file``, ``cert_file``, ``cert_reqs``, and ``ca_certs`` parameters are only used if :mod:`ssl` is available and are fed into :meth:`ssl.wrap_socket` to upgrade the connection socket into an SSL socket. """ scheme = 'https' def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1, block=False, headers=None, key_file=None, cert_file=None, cert_reqs='CERT_NONE', ca_certs=None): super(HTTPSConnectionPool, self).__init__(host, port, strict, timeout, maxsize, block, headers) self.key_file = key_file self.cert_file = cert_file self.cert_reqs = cert_reqs self.ca_certs = ca_certs def _new_conn(self): """ Return a fresh :class:`httplib.HTTPSConnection`. """ self.num_connections += 1 log.info("Starting new HTTPS connection (%d): %s" % (self.num_connections, self.host)) if not ssl: # Platform-specific: Python compiled without +ssl if not HTTPSConnection or HTTPSConnection is object: raise SSLError("Can't connect to HTTPS URL because the SSL " "module is not available.") return HTTPSConnection(host=self.host, port=self.port) connection = VerifiedHTTPSConnection(host=self.host, port=self.port) connection.set_cert(key_file=self.key_file, cert_file=self.cert_file, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs) return connection def connection_from_url(url, **kw): """ Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :param \**kw: Passes additional parameters to the constructor of the appropriate :class:`.ConnectionPool`. Useful for specifying things like timeout, maxsize, headers, etc. Example: :: >>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/') """ scheme, host, port = get_host(url) if scheme == 'https': return HTTPSConnectionPool(host, port=port, **kw) else: return HTTPConnectionPool(host, port=port, **kw)
bsd-3-clause
3de6152b345b53612d41a8e63b98370a
34.295019
80
0.592054
4.561525
false
false
false
false
mozilla/mozilla-ignite
vendor-local/lib/python/requests/cookies.py
4
8923
""" Compatibility code to be able to use `cookielib.CookieJar` with requests. requests.utils imports from here, so be careful with imports. """ import collections from .compat import cookielib, urlparse, Morsel try: import threading # grr, pyflakes: this fixes "redefinition of unused 'threading'" threading except ImportError: import dummy_threading as threading class MockRequest(object): """Wraps a `requests.Request` to mimic a `urllib2.Request`. The code in `cookielib.CookieJar` expects this interface in order to correctly manage cookie policies, i.e., determine whether a cookie can be set, given the domains of the request and the cookie. The original request object is read-only. The client is responsible for collecting the new headers via `get_new_headers()` and interpreting them appropriately. You probably want `get_cookie_header`, defined below. """ def __init__(self, request): self._r = request self._new_headers = {} def get_type(self): return urlparse(self._r.full_url).scheme def get_host(self): return urlparse(self._r.full_url).netloc def get_origin_req_host(self): if self._r.response.history: r = self._r.response.history[0] return urlparse(r).netloc else: return self.get_host() def get_full_url(self): return self._r.full_url def is_unverifiable(self): # unverifiable == redirected return bool(self._r.response.history) def has_header(self, name): return name in self._r.headers or name in self._new_headers def get_header(self, name, default=None): return self._r.headers.get(name, self._new_headers.get(name, default)) def add_header(self, key, val): """cookielib has no legitimate use for this method; add it back if you find one.""" raise NotImplementedError("Cookie headers should be added with add_unredirected_header()") def add_unredirected_header(self, name, value): self._new_headers[name] = value def get_new_headers(self): return self._new_headers class MockResponse(object): """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`. ...what? Basically, expose the parsed HTTP headers from the server response the way `cookielib` expects to see them. """ def __init__(self, headers): """Make a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers """ self._headers = headers def info(self): return self._headers def getheaders(self, name): self._headers.getheaders(name) def extract_cookies_to_jar(jar, request, response): """Extract the cookies from the response into a CookieJar. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar) :param request: our own requests.Request object :param response: urllib3.HTTPResponse object """ # the _original_response field is the wrapped httplib.HTTPResponse object, # and in safe mode, it may be None if the request didn't actually complete. # in that case, just skip the cookie extraction. if response._original_response is not None: req = MockRequest(request) # pull out the HTTPMessage with the headers and put it in the mock: res = MockResponse(response._original_response.msg) jar.extract_cookies(res, req) def get_cookie_header(jar, request): """Produce an appropriate Cookie header string to be sent with `request`, or None.""" r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie') def remove_cookie_by_name(cookiejar, name, domain=None, path=None): """Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). """ clearables = [] for cookie in cookiejar: if cookie.name == name: if domain is None or domain == cookie.domain: if path is None or path == cookie.path: clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name) class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping): """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface. This is the CookieJar we create by default for requests and sessions that don't specify one, since some clients may expect response.cookies and session.cookies to support dict operations. Don't use the dict interface internally; it's just for compatibility with with external client code. All `requests` code should work out of the box with externally provided instances of CookieJar, e.g., LWPCookieJar and FileCookieJar. Caution: dictionary operations that are normally O(1) may be O(n). Unlike a regular CookieJar, this class is pickleable. """ def get(self, name, domain=None, path=None, default=None): try: return self._find(name, domain, path) except KeyError: return default def set(self, name, value, **kwargs): # support client code that unsets cookies by assignment of a None value: if value is None: remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path')) return if isinstance(value, Morsel): c = morsel_to_cookie(value) else: c = create_cookie(name, value, **kwargs) self.set_cookie(c) return c def __getitem__(self, name): return self._find(name) def __setitem__(self, name, value): self.set(name, value) def __delitem__(self, name): remove_cookie_by_name(self, name) def _find(self, name, domain=None, path=None): for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: return cookie.value raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) def __getstate__(self): state = self.__dict__.copy() # remove the unpickleable RLock object state.pop('_cookies_lock') return state def __setstate__(self, state): self.__dict__.update(state) if '_cookies_lock' not in self.__dict__: self._cookies_lock = threading.RLock() def copy(self): """We're probably better off forbidding this.""" raise NotImplementedError def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). """ result = dict( version=0, name=name, value=value, port=None, domain='', path='/', secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False, ) badargs = set(kwargs) - set(result) if badargs: err = 'create_cookie() got unexpected keyword arguments: %s' raise TypeError(err % list(badargs)) result.update(kwargs) result['port_specified'] = bool(result['port']) result['domain_specified'] = bool(result['domain']) result['domain_initial_dot'] = result['domain'].startswith('.') result['path_specified'] = bool(result['path']) return cookielib.Cookie(**result) def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" c = create_cookie( name=morsel.key, value=morsel.value, version=morsel['version'] or 0, port=None, port_specified=False, domain=morsel['domain'], domain_specified=bool(morsel['domain']), domain_initial_dot=morsel['domain'].startswith('.'), path=morsel['path'], path_specified=bool(morsel['path']), secure=bool(morsel['secure']), expires=morsel['max-age'] or morsel['expires'], discard=False, comment=morsel['comment'], comment_url=bool(morsel['comment']), rest={'HttpOnly': morsel['httponly']}, rfc2109=False, ) return c def cookiejar_from_dict(cookie_dict, cookiejar=None): """Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. """ if cookiejar is None: cookiejar = RequestsCookieJar() if cookie_dict is not None: for name in cookie_dict: cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) return cookiejar
bsd-3-clause
80fc1ca261ff17fbfac32d0a4d173a31
32.799242
99
0.639247
4.083753
false
false
false
false
mozilla/mozilla-ignite
vendor-local/lib/python/rsa/util.py
5
2778
# -*- coding: utf-8 -*- # # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''Utility functions.''' import sys from optparse import OptionParser import rsa.key def private_to_public(): '''Reads a private key and outputs the corresponding public key.''' # Parse the CLI options parser = OptionParser(usage='usage: %prog [options]', description='Reads a private key and outputs the ' 'corresponding public key. Both private and public keys use ' 'the format described in PKCS#1 v1.5') parser.add_option('-i', '--input', dest='infilename', type='string', help='Input filename. Reads from stdin if not specified') parser.add_option('-o', '--output', dest='outfilename', type='string', help='Output filename. Writes to stdout of not specified') parser.add_option('--inform', dest='inform', help='key format of input - default PEM', choices=('PEM', 'DER'), default='PEM') parser.add_option('--outform', dest='outform', help='key format of output - default PEM', choices=('PEM', 'DER'), default='PEM') (cli, cli_args) = parser.parse_args(sys.argv) # Read the input data if cli.infilename: print >>sys.stderr, 'Reading private key from %s in %s format' % \ (cli.infilename, cli.inform) with open(cli.infilename) as infile: in_data = infile.read() else: print >>sys.stderr, 'Reading private key from stdin in %s format' % \ cli.inform in_data = sys.stdin.read() # Take the public fields and create a public key priv_key = rsa.key.PrivateKey.load_pkcs1(in_data, cli.inform) pub_key = rsa.key.PublicKey(priv_key.n, priv_key.e) # Save to the output file out_data = pub_key.save_pkcs1(cli.outform) if cli.outfilename: print >>sys.stderr, 'Writing public key to %s in %s format' % \ (cli.outfilename, cli.outform) with open(cli.outfilename, 'w') as outfile: outfile.write(out_data) else: print >>sys.stderr, 'Writing public key to stdout in %s format' % \ cli.outform sys.stdout.write(out_data)
bsd-3-clause
38287aff1cf7abaa767f3413161e7f16
35.064935
77
0.638459
3.783379
false
false
false
false
mozilla/mozilla-ignite
apps/challenges/migrations/0022_wipe_judge_assignment.py
1
14798
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'JudgeAssignment' db.delete_table('challenges_judgeassignment') def backwards(self, orm): # Adding model 'JudgeAssignment' db.create_table('challenges_judgeassignment', ( ('judge', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['users.Profile'])), ('created_on', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.utcnow)), ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('submission', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['challenges.Submission'], unique=True)), )) db.send_create_signal('challenges', ['JudgeAssignment']) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'challenges.category': { 'Meta': {'object_name': 'Category'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '60', 'db_index': 'True'}) }, 'challenges.challenge': { 'Meta': {'object_name': 'Challenge'}, 'allow_voting': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.TextField', [], {}), 'end_date': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'moderate': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']"}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '60', 'db_index': 'True'}), 'start_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.utcnow'}), 'summary': ('django.db.models.fields.TextField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}) }, 'challenges.externallink': { 'Meta': {'object_name': 'ExternalLink'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Submission']", 'null': 'True', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '255'}) }, 'challenges.judgement': { 'Meta': {'unique_together': "(('submission', 'judge'),)", 'object_name': 'Judgement'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'judge': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Profile']"}), 'notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Submission']"}) }, 'challenges.judginganswer': { 'Meta': {'unique_together': "(('judgement', 'criterion'),)", 'object_name': 'JudgingAnswer'}, 'criterion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.JudgingCriterion']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'judgement': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'answers'", 'to': "orm['challenges.Judgement']"}), 'rating': ('django.db.models.fields.IntegerField', [], {}) }, 'challenges.judgingcriterion': { 'Meta': {'ordering': "('id',)", 'object_name': 'JudgingCriterion'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'max_value': ('django.db.models.fields.IntegerField', [], {'default': '10'}), 'min_value': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'phases': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'judgement_criteria'", 'blank': 'True', 'to': "orm['challenges.Phase']"}), 'question': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '250'}) }, 'challenges.phase': { 'Meta': {'ordering': "('order',)", 'unique_together': "(('challenge', 'name'),)", 'object_name': 'Phase'}, 'challenge': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'phases'", 'to': "orm['challenges.Challenge']"}), 'end_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 7, 31, 17, 24, 4, 909738)'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'order': ('django.db.models.fields.IntegerField', [], {}), 'start_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.utcnow'}) }, 'challenges.submission': { 'Meta': {'ordering': "['-id']", 'object_name': 'Submission'}, 'brief_description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Category']"}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Profile']"}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.utcnow'}), 'description': ('django.db.models.fields.TextField', [], {}), 'flagged_offensive': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'flagged_offensive_reason': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_live': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_winner': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'phase': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Phase']"}), 'sketh_note': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'projects.project': { 'Meta': {'object_name': 'Project'}, 'allow_participation': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'allow_sub_projects': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'featured_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'followers': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'projects_following'", 'symmetrical': 'False', 'to': "orm['users.Profile']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'long_description': ('django.db.models.fields.TextField', [], {}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'parent_project_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}), 'sub_project_label': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'team_members': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['users.Profile']", 'symmetrical': 'False'}), 'topics': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['topics.Topic']", 'symmetrical': 'False'}) }, 'taggit.tag': { 'Meta': {'object_name': 'Tag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}) }, 'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"}) }, 'topics.topic': { 'Meta': {'object_name': 'Topic'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'draft': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'long_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}) }, 'users.profile': { 'Meta': {'object_name': 'Profile'}, 'avatar': ('django.db.models.fields.files.ImageField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'bio': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'featured_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}) } } complete_apps = ['challenges']
bsd-3-clause
6f4a2777288e25aef6b1be5ca814034d
76.072917
194
0.553656
3.698575
false
false
false
false
mozilla/mozilla-ignite
vendor-local/lib/python/requests/utils.py
1
13350
# -*- coding: utf-8 -*- """ requests.utils ~~~~~~~~~~~~~~ This module provides utility functions that are used within Requests that are also useful for external consumption. """ import cgi import codecs import os import random import re import zlib from netrc import netrc, NetrcParseError from .compat import parse_http_list as _parse_list_header from .compat import quote, is_py2, urlparse from .compat import basestring, bytes, str from .cookies import RequestsCookieJar, cookiejar_from_dict _hush_pyflakes = (RequestsCookieJar,) CERTIFI_BUNDLE_PATH = None try: # see if requests's own CA certificate bundle is installed import certifi CERTIFI_BUNDLE_PATH = certifi.where() except ImportError: pass NETRC_FILES = ('.netrc', '_netrc') # common paths for the OS's CA certificate bundle POSSIBLE_CA_BUNDLE_PATHS = [ # Red Hat, CentOS, Fedora and friends (provided by the ca-certificates package): '/etc/pki/tls/certs/ca-bundle.crt', # Ubuntu, Debian, and friends (provided by the ca-certificates package): '/etc/ssl/certs/ca-certificates.crt', # FreeBSD (provided by the ca_root_nss package): '/usr/local/share/certs/ca-root-nss.crt', ] def get_os_ca_bundle_path(): """Try to pick an available CA certificate bundle provided by the OS.""" for path in POSSIBLE_CA_BUNDLE_PATHS: if os.path.exists(path): return path return None # if certifi is installed, use its CA bundle; # otherwise, try and use the OS bundle DEFAULT_CA_BUNDLE_PATH = CERTIFI_BUNDLE_PATH or get_os_ca_bundle_path() def dict_to_sequence(d): """Returns an internal sequence dictionary update.""" if hasattr(d, 'items'): d = d.items() return d def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: locations = (os.path.expanduser('~/{0}'.format(f)) for f in NETRC_FILES) netrc_path = None for loc in locations: if os.path.exists(loc) and not netrc_path: netrc_path = loc # Abort early if there isn't one. if netrc_path is None: return netrc_path ri = urlparse(url) # Strip port numbers from netloc host = ri.netloc.split(':')[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth pass # AppEngine hackiness. except AttributeError: pass def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) if name and name[0] != '<' and name[-1] != '>': return name # From mitsuhiko/werkzeug (used with permission). def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` """ result = [] for item in _parse_list_header(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result # From mitsuhiko/werkzeug (used with permission). def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` """ result = {} for item in _parse_list_header(value): if '=' not in item: result[item] = None continue name, value = item.split('=', 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result # From mitsuhiko/werkzeug (used with permission). def unquote_header_value(value, is_filename=False): r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. """ if value and value[0] == value[-1] == '"': # this is not the real unquoting, but fixing this so that the # RFC is met will result in bugs with internet explorer and # probably some other browsers as well. IE for example is # uploading files with "C:\foo\bar.txt" as filename value = value[1:-1] # if this is a filename and the starting characters look like # a UNC path, then just return the value without quotes. Using the # replace sequence below on a UNC path has the effect of turning # the leading double slash into a single slash and then # _fix_ie_filename() doesn't work correctly. See #458. if not is_filename or value[:2] != '\\\\': return value.replace('\\\\', '\\').replace('\\"', '"') return value def header_expand(headers): """Returns an HTTP Header value string from a dictionary. Example expansion:: {'text/x-dvi': {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}, 'text/x-c': {}} # Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c (('text/x-dvi', {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}), ('text/x-c', {})) # Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c """ collector = [] if isinstance(headers, dict): headers = list(headers.items()) elif isinstance(headers, basestring): return headers elif isinstance(headers, str): # As discussed in https://github.com/kennethreitz/requests/issues/400 # latin-1 is the most conservative encoding used on the web. Anyone # who needs more can encode to a byte-string before calling return headers.encode("latin-1") elif headers is None: return headers for i, (value, params) in enumerate(headers): _params = [] for (p_k, p_v) in list(params.items()): _params.append('%s=%s' % (p_k, p_v)) collector.append(value) collector.append('; ') if len(params): collector.append('; '.join(_params)) if not len(headers) == i + 1: collector.append(', ') # Remove trailing separators. if collector[-1] in (', ', '; '): del collector[-1] return ''.join(collector) def randombytes(n): """Return n random bytes.""" if is_py2: L = [chr(random.randrange(0, 256)) for i in range(n)] else: L = [chr(random.randrange(0, 256)).encode('utf-8') for i in range(n)] return b"".join(L) def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. """ cookie_dict = {} for _, cookies in list(cj._cookies.items()): for _, cookies in list(cookies.items()): for cookie in list(cookies.values()): # print cookie cookie_dict[cookie.name] = cookie.value return cookie_dict def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. """ cj2 = cookiejar_from_dict(cookie_dict) for cookie in cj2: cj.set_cookie(cookie) return cj def get_encodings_from_content(content): """Returns encodings from given content string. :param content: bytestring to extract encodings from. """ charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) return charset_re.findall(content) def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. """ content_type = headers.get('content-type') if not content_type: return None content_type, params = cgi.parse_header(content_type) if 'charset' in params: return params['charset'].strip("'\"") if 'text' in content_type: return 'ISO-8859-1' def stream_decode_response_unicode(iterator, r): """Stream decodes a iterator.""" if r.encoding is None: for item in iterator: yield item return decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace') for chunk in iterator: rv = decoder.decode(chunk) if rv: yield rv rv = decoder.decode('', final=True) if rv: yield rv def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. every encodings from ``<meta ... charset=XXX>`` 3. fall back and replace all unicode characters """ tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors='replace') except TypeError: return r.content def stream_decompress(iterator, mode='gzip'): """ Stream decodes an iterator over compressed data :param iterator: An iterator over compressed data :param mode: 'gzip' or 'deflate' :return: An iterator over decompressed data """ if mode not in ['gzip', 'deflate']: raise ValueError('stream_decompress mode must be gzip or deflate') zlib_mode = 16 + zlib.MAX_WBITS if mode == 'gzip' else -zlib.MAX_WBITS dec = zlib.decompressobj(zlib_mode) try: for chunk in iterator: rv = dec.decompress(chunk) if rv: yield rv except zlib.error: # If there was an error decompressing, just return the raw chunk yield chunk # Continue to return the rest of the raw data for chunk in iterator: yield chunk else: # Make sure everything has been returned from the decompression object buf = dec.decompress(bytes()) rv = buf + dec.flush() if rv: yield rv def stream_untransfer(gen, resp): if 'gzip' in resp.headers.get('content-encoding', ''): gen = stream_decompress(gen, mode='gzip') elif 'deflate' in resp.headers.get('content-encoding', ''): gen = stream_decompress(gen, mode='deflate') return gen # The unreserved URI characters (RFC 3986) UNRESERVED_SET = frozenset( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~") def unquote_unreserved(uri): """Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. """ parts = uri.split('%') for i in range(1, len(parts)): h = parts[i][0:2] if len(h) == 2: c = chr(int(h, 16)) if c in UNRESERVED_SET: parts[i] = c + parts[i][2:] else: parts[i] = '%' + parts[i] else: parts[i] = '%' + parts[i] return ''.join(parts) def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. """ # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, unreserved, # or '%') return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~") def get_environ_proxies(): """Return a dict of environment proxies.""" proxy_keys = [ 'all', 'http', 'https', 'ftp', 'socks', 'no' ] get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys] return dict([(key, val) for (key, val) in proxies if val])
bsd-3-clause
0147703293240dedb128eb912ef85ed7
27.771552
88
0.611386
3.836207
false
false
false
false
mozilla/mozilla-ignite
apps/timeslot/baseconv.py
1
1571
""" Convert numbers from base 10 integers to base X strings and back again. Original: http://www.djangosnippets.org/snippets/1431/ Sample usage: >>> base20 = BaseConverter('0123456789abcdefghij') >>> base20.from_decimal(1234) '31e' >>> base20.to_decimal('31e') 1234 """ class BaseConverter(object): decimal_digits = "0123456789" def __init__(self, digits): self.digits = digits def from_decimal(self, i): return self.convert(i, self.decimal_digits, self.digits) def to_decimal(self, s): return int(self.convert(s, self.digits, self.decimal_digits)) def convert(number, fromdigits, todigits): # Based on http://code.activestate.com/recipes/111286/ if str(number)[0] == '-': number = str(number)[1:] neg = 1 else: neg = 0 # make an integer out of the number x = 0 for digit in str(number): x = x * len(fromdigits) + fromdigits.index(digit) # create the result in base 'len(todigits)' if x == 0: res = todigits[0] else: res = "" while x > 0: digit = x % len(todigits) res = todigits[digit] + res x = int(x / len(todigits)) if neg: res = '-' + res return res convert = staticmethod(convert) bin = BaseConverter('01') hexconv = BaseConverter('0123456789ABCDEF') base62 = BaseConverter( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz' )
bsd-3-clause
8f703c2a9c917d96f02dce333dcb200b
25.627119
71
0.57352
3.9275
false
false
false
false
mozilla/mozilla-ignite
vendor-local/lib/python/markdown/extensions/meta.py
9
2759
#!usr/bin/python """ Meta Data Extension for Python-Markdown ======================================= This extension adds Meta Data handling to markdown. Basic Usage: >>> import markdown >>> text = '''Title: A Test Doc. ... Author: Waylan Limberg ... John Doe ... Blank_Data: ... ... The body. This is paragraph one. ... ''' >>> md = markdown.Markdown(['meta']) >>> print md.convert(text) <p>The body. This is paragraph one.</p> >>> print md.Meta {u'blank_data': [u''], u'author': [u'Waylan Limberg', u'John Doe'], u'title': [u'A Test Doc.']} Make sure text without Meta Data still works (markdown < 1.6b returns a <p>). >>> text = ' Some Code - not extra lines of meta data.' >>> md = markdown.Markdown(['meta']) >>> print md.convert(text) <pre><code>Some Code - not extra lines of meta data. </code></pre> >>> md.Meta {} Copyright 2007-2008 [Waylan Limberg](http://achinghead.com). Project website: <http://www.freewisdom.org/project/python-markdown/Meta-Data> Contact: markdown@freewisdom.org License: BSD (see ../docs/LICENSE for details) """ import re import markdown # Global Vars META_RE = re.compile(r'^[ ]{0,3}(?P<key>[A-Za-z0-9_-]+):\s*(?P<value>.*)') META_MORE_RE = re.compile(r'^[ ]{4,}(?P<value>.*)') class MetaExtension (markdown.Extension): """ Meta-Data extension for Python-Markdown. """ def extendMarkdown(self, md, md_globals): """ Add MetaPreprocessor to Markdown instance. """ md.preprocessors.add("meta", MetaPreprocessor(md), "_begin") class MetaPreprocessor(markdown.preprocessors.Preprocessor): """ Get Meta-Data. """ def run(self, lines): """ Parse Meta-Data and store in Markdown.Meta. """ meta = {} key = None while 1: line = lines.pop(0) if line.strip() == '': break # blank line - done m1 = META_RE.match(line) if m1: key = m1.group('key').lower().strip() value = m1.group('value').strip() try: meta[key].append(value) except KeyError: meta[key] = [value] else: m2 = META_MORE_RE.match(line) if m2 and key: # Add another line to existing key meta[key].append(m2.group('value').strip()) else: lines.insert(0, line) break # no meta data - done self.markdown.Meta = meta return lines def makeExtension(configs={}): return MetaExtension(configs=configs) if __name__ == "__main__": import doctest doctest.testmod()
bsd-3-clause
d4e73b16845cd2368965c75679f2ee39
27.739583
99
0.542588
3.753741
false
true
false
false
mozilla/mozilla-ignite
apps/resources/migrations/0001_initial.py
1
2929
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Resource' db.create_table('resources_resource', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=255)), ('slug', self.gf('django_extensions.db.fields.AutoSlugField')(allow_duplicates=False, max_length=50, separator=u'-', blank=True, populate_from='title', overwrite=False, db_index=True)), ('resource_type', self.gf('django.db.models.fields.IntegerField')()), ('body', self.gf('django.db.models.fields.TextField')()), ('url', self.gf('django.db.models.fields.URLField')(max_length=500, blank=True)), ('email', self.gf('django.db.models.fields.EmailField')(max_length=150, blank=True)), ('is_featured', self.gf('django.db.models.fields.BooleanField')(default=False)), ('status', self.gf('django.db.models.fields.IntegerField')(default=1)), ('created', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, blank=True)), ('updated', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, blank=True)), )) db.send_create_signal('resources', ['Resource']) def backwards(self, orm): # Deleting model 'Resource' db.delete_table('resources_resource') models = { 'resources.resource': { 'Meta': {'object_name': 'Resource'}, 'body': ('django.db.models.fields.TextField', [], {}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '150', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'resource_type': ('django.db.models.fields.IntegerField', [], {}), 'slug': ('django_extensions.db.fields.AutoSlugField', [], {'allow_duplicates': 'False', 'max_length': '50', 'separator': "u'-'", 'blank': 'True', 'populate_from': "'title'", 'overwrite': 'False', 'db_index': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '500', 'blank': 'True'}) } } complete_apps = ['resources']
bsd-3-clause
54d2ac57f6a582d6cfa170aba23baae9
56.431373
229
0.598156
3.798962
false
false
false
false
mozilla/mozilla-ignite
vendor-local/src/django-voting/setup.py
17
1354
from distutils.core import setup from distutils.command.install import INSTALL_SCHEMES # Tell distutils to put the data_files in platform-specific installation # locations. See here for an explanation: # http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb for scheme in INSTALL_SCHEMES.values(): scheme['data'] = scheme['purelib'] # Dynamically calculate the version based on tagging.VERSION. version_tuple = __import__('voting').VERSION if version_tuple[2] is not None: version = "%d.%d_%s" % version_tuple else: version = "%d.%d" % version_tuple[:2] setup( name = 'django-voting', version = version, description = 'Generic voting application for Django', author = 'Jonathan Buchanan', author_email = 'jonathan.buchanan@gmail.com', url = 'http://code.google.com/p/django-voting/', packages = ['voting', 'voting.templatetags', 'voting.tests'], classifiers = ['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], )
bsd-3-clause
55101721dd9d83e5ec5fee61efe5c592
40.060606
104
0.641802
3.890805
false
false
false
false
mozilla/mozilla-ignite
vendor-local/lib/python/pyasn1/type/univ.py
20
39555
# ASN.1 "universal" data types import operator, sys from pyasn1.type import base, tag, constraint, namedtype, namedval, tagmap from pyasn1.codec.ber import eoo from pyasn1.compat import octets from pyasn1 import error # "Simple" ASN.1 types (yet incomplete) class Integer(base.AbstractSimpleAsn1Item): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x02) ) namedValues = namedval.NamedValues() def __init__(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if namedValues is None: self.__namedValues = self.namedValues else: self.__namedValues = namedValues base.AbstractSimpleAsn1Item.__init__( self, value, tagSet, subtypeSpec ) def __and__(self, value): return self.clone(self._value & value) def __rand__(self, value): return self.clone(value & self._value) def __or__(self, value): return self.clone(self._value | value) def __ror__(self, value): return self.clone(value | self._value) def __xor__(self, value): return self.clone(self._value ^ value) def __rxor__(self, value): return self.clone(value ^ self._value) def __lshift__(self, value): return self.clone(self._value << value) def __rshift__(self, value): return self.clone(self._value >> value) def __add__(self, value): return self.clone(self._value + value) def __radd__(self, value): return self.clone(value + self._value) def __sub__(self, value): return self.clone(self._value - value) def __rsub__(self, value): return self.clone(value - self._value) def __mul__(self, value): return self.clone(self._value * value) def __rmul__(self, value): return self.clone(value * self._value) def __mod__(self, value): return self.clone(self._value % value) def __rmod__(self, value): return self.clone(value % self._value) def __pow__(self, value, modulo=None): return self.clone(pow(self._value, value, modulo)) def __rpow__(self, value): return self.clone(pow(value, self._value)) if sys.version_info[0] <= 2: def __div__(self, value): return self.clone(self._value // value) def __rdiv__(self, value): return self.clone(value // self._value) else: def __truediv__(self, value): return self.clone(self._value / value) def __rtruediv__(self, value): return self.clone(value / self._value) def __divmod__(self, value): return self.clone(self._value // value) def __rdivmod__(self, value): return self.clone(value // self._value) __hash__ = base.AbstractSimpleAsn1Item.__hash__ def __int__(self): return int(self._value) if sys.version_info[0] <= 2: def __long__(self): return long(self._value) def __float__(self): return float(self._value) def __abs__(self): return abs(self._value) def __index__(self): return int(self._value) def __lt__(self, value): return self._value < value def __le__(self, value): return self._value <= value def __eq__(self, value): return self._value == value def __ne__(self, value): return self._value != value def __gt__(self, value): return self._value > value def __ge__(self, value): return self._value >= value def prettyIn(self, value): if not isinstance(value, str): return int(value) r = self.__namedValues.getValue(value) if r is not None: return r try: return int(value) except ValueError: raise error.PyAsn1Error( 'Can\'t coerce %s into integer: %s' % (value, sys.exc_info()[1]) ) def prettyOut(self, value): r = self.__namedValues.getName(value) return r is None and str(value) or repr(r) def getNamedValues(self): return self.__namedValues def clone(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if value is None and tagSet is None and subtypeSpec is None \ and namedValues is None: return self if value is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if namedValues is None: namedValues = self.__namedValues return self.__class__(value, tagSet, subtypeSpec, namedValues) def subtype(self, value=None, implicitTag=None, explicitTag=None, subtypeSpec=None, namedValues=None): if value is None: value = self._value if implicitTag is not None: tagSet = self._tagSet.tagImplicitly(implicitTag) elif explicitTag is not None: tagSet = self._tagSet.tagExplicitly(explicitTag) else: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec else: subtypeSpec = subtypeSpec + self._subtypeSpec if namedValues is None: namedValues = self.__namedValues else: namedValues = namedValues + self.__namedValues return self.__class__(value, tagSet, subtypeSpec, namedValues) class Boolean(Integer): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x01), ) subtypeSpec = Integer.subtypeSpec+constraint.SingleValueConstraint(0,1) namedValues = Integer.namedValues.clone(('False', 0), ('True', 1)) class BitString(base.AbstractSimpleAsn1Item): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x03) ) namedValues = namedval.NamedValues() def __init__(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if namedValues is None: self.__namedValues = self.namedValues else: self.__namedValues = namedValues base.AbstractSimpleAsn1Item.__init__( self, value, tagSet, subtypeSpec ) def clone(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if value is None and tagSet is None and subtypeSpec is None \ and namedValues is None: return self if value is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if namedValues is None: namedValues = self.__namedValues return self.__class__(value, tagSet, subtypeSpec, namedValues) def subtype(self, value=None, implicitTag=None, explicitTag=None, subtypeSpec=None, namedValues=None): if value is None: value = self._value if implicitTag is not None: tagSet = self._tagSet.tagImplicitly(implicitTag) elif explicitTag is not None: tagSet = self._tagSet.tagExplicitly(explicitTag) else: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec else: subtypeSpec = subtypeSpec + self._subtypeSpec if namedValues is None: namedValues = self.__namedValues else: namedValues = namedValues + self.__namedValues return self.__class__(value, tagSet, subtypeSpec, namedValues) def __str__(self): return str(tuple(self)) # Immutable sequence object protocol def __len__(self): if self._len is None: self._len = len(self._value) return self._len def __getitem__(self, i): if isinstance(i, slice): return self.clone(operator.getitem(self._value, i)) else: return self._value[i] def __add__(self, value): return self.clone(self._value + value) def __radd__(self, value): return self.clone(value + self._value) def __mul__(self, value): return self.clone(self._value * value) def __rmul__(self, value): return self * value def prettyIn(self, value): r = [] if not value: return () elif isinstance(value, str): if value[0] == '\'': if value[-2:] == '\'B': for v in value[1:-2]: if v == '0': r.append(0) elif v == '1': r.append(1) else: raise error.PyAsn1Error( 'Non-binary BIT STRING initializer %s' % (v,) ) return tuple(r) elif value[-2:] == '\'H': for v in value[1:-2]: i = 4 v = int(v, 16) while i: i = i - 1 r.append((v>>i)&0x01) return tuple(r) else: raise error.PyAsn1Error( 'Bad BIT STRING value notation %s' % value ) else: for i in value.split(','): j = self.__namedValues.getValue(i) if j is None: raise error.PyAsn1Error( 'Unknown bit identifier \'%s\'' % i ) if j >= len(r): r.extend([0]*(j-len(r)+1)) r[j] = 1 return tuple(r) elif isinstance(value, (tuple, list)): r = tuple(value) for b in r: if b and b != 1: raise error.PyAsn1Error( 'Non-binary BitString initializer \'%s\'' % (r,) ) return r elif isinstance(value, BitString): return tuple(value) else: raise error.PyAsn1Error( 'Bad BitString initializer type \'%s\'' % (value,) ) def prettyOut(self, value): return '\"\'%s\'B\"' % ''.join([str(x) for x in value]) class OctetString(base.AbstractSimpleAsn1Item): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x04) ) defaultBinValue = defaultHexValue = base.noValue encoding = 'us-ascii' def __init__(self, value=None, tagSet=None, subtypeSpec=None, encoding=None, binValue=None, hexValue=None): if encoding is None: self._encoding = self.encoding else: self._encoding = encoding if binValue is not None: value = self.fromBinaryString(binValue) if hexValue is not None: value = self.fromHexString(hexValue) if value is None or value is base.noValue: value = self.defaultHexValue if value is None or value is base.noValue: value = self.defaultBinValue self.__intValue = None base.AbstractSimpleAsn1Item.__init__(self, value, tagSet, subtypeSpec) def clone(self, value=None, tagSet=None, subtypeSpec=None, encoding=None, binValue=None, hexValue=None): if value is None and tagSet is None and subtypeSpec is None and \ encoding is None and binValue is None and hexValue is None: return self if value is None and binValue is None and hexValue is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if encoding is None: encoding = self._encoding return self.__class__( value, tagSet, subtypeSpec, encoding, binValue, hexValue ) if sys.version_info[0] <= 2: def prettyIn(self, value): if isinstance(value, str): return value elif isinstance(value, (tuple, list)): try: return ''.join([ chr(x) for x in value ]) except ValueError: raise error.PyAsn1Error( 'Bad OctetString initializer \'%s\'' % (value,) ) else: return str(value) else: def prettyIn(self, value): if isinstance(value, bytes): return value elif isinstance(value, OctetString): return value.asOctets() elif isinstance(value, (tuple, list, map)): try: return bytes(value) except ValueError: raise error.PyAsn1Error( 'Bad OctetString initializer \'%s\'' % (value,) ) else: try: return str(value).encode(self._encoding) except UnicodeEncodeError: raise error.PyAsn1Error( 'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding) ) def fromBinaryString(self, value): bitNo = 8; byte = 0; r = () for v in value: if bitNo: bitNo = bitNo - 1 else: bitNo = 7 r = r + (byte,) byte = 0 if v == '0': v = 0 elif v == '1': v = 1 else: raise error.PyAsn1Error( 'Non-binary OCTET STRING initializer %s' % (v,) ) byte = byte | (v << bitNo) return octets.ints2octs(r + (byte,)) def fromHexString(self, value): r = p = () for v in value: if p: r = r + (int(p+v, 16),) p = () else: p = v if p: r = r + (int(p+'0', 16),) return octets.ints2octs(r) def prettyOut(self, value): if sys.version_info[0] <= 2: numbers = tuple([ ord(x) for x in value ]) else: numbers = tuple(value) if [ x for x in numbers if x < 32 or x > 126 ]: return '0x' + ''.join([ '%.2x' % x for x in numbers ]) else: return str(value) def __repr__(self): if self._value is base.noValue: return self.__class__.__name__ + '()' if [ x for x in self.asNumbers() if x < 32 or x > 126 ]: return self.__class__.__name__ + '(hexValue=\'' + ''.join([ '%.2x' % x for x in self.asNumbers() ])+'\')' else: return self.__class__.__name__ + '(\'' + self.prettyOut(self._value) + '\')' if sys.version_info[0] <= 2: def __str__(self): return str(self._value) def __unicode__(self): return self._value.decode(self._encoding, 'ignore') def asOctets(self): return self._value def asNumbers(self): if self.__intValue is None: self.__intValue = tuple([ ord(x) for x in self._value ]) return self.__intValue else: def __str__(self): return self._value.decode(self._encoding, 'ignore') def __bytes__(self): return self._value def asOctets(self): return self._value def asNumbers(self): if self.__intValue is None: self.__intValue = tuple(self._value) return self.__intValue # Immutable sequence object protocol def __len__(self): if self._len is None: self._len = len(self._value) return self._len def __getitem__(self, i): if isinstance(i, slice): return self.clone(operator.getitem(self._value, i)) else: return self._value[i] def __add__(self, value): return self.clone(self._value + self.prettyIn(value)) def __radd__(self, value): return self.clone(self.prettyIn(value) + self._value) def __mul__(self, value): return self.clone(self._value * value) def __rmul__(self, value): return self * value class Null(OctetString): defaultValue = ''.encode() # This is tightly constrained tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x05) ) subtypeSpec = OctetString.subtypeSpec+constraint.SingleValueConstraint(''.encode()) if sys.version_info[0] <= 2: intTypes = (int, long) else: intTypes = int class ObjectIdentifier(base.AbstractSimpleAsn1Item): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x06) ) def __add__(self, other): return self.clone(self._value + other) def __radd__(self, other): return self.clone(other + self._value) def asTuple(self): return self._value # Sequence object protocol def __len__(self): if self._len is None: self._len = len(self._value) return self._len def __getitem__(self, i): if isinstance(i, slice): return self.clone( operator.getitem(self._value, i) ) else: return self._value[i] def __str__(self): return self.prettyPrint() def index(self, suboid): return self._value.index(suboid) def isPrefixOf(self, value): """Returns true if argument OID resides deeper in the OID tree""" l = len(self) if l <= len(value): if self._value[:l] == value[:l]: return 1 return 0 def prettyIn(self, value): """Dotted -> tuple of numerics OID converter""" if isinstance(value, tuple): pass elif isinstance(value, ObjectIdentifier): return tuple(value) elif isinstance(value, str): r = [] for element in [ x for x in value.split('.') if x != '' ]: try: r.append(int(element, 0)) except ValueError: raise error.PyAsn1Error( 'Malformed Object ID %s at %s: %s' % (str(value), self.__class__.__name__, sys.exc_info()[1]) ) value = tuple(r) else: try: value = tuple(value) except TypeError: raise error.PyAsn1Error( 'Malformed Object ID %s at %s: %s' % (str(value), self.__class__.__name__,sys.exc_info()[1]) ) for x in value: if not isinstance(x, intTypes) or x < 0: raise error.PyAsn1Error( 'Invalid sub-ID in %s at %s' % (value, self.__class__.__name__) ) return value def prettyOut(self, value): return '.'.join([ str(x) for x in value ]) class Real(base.AbstractSimpleAsn1Item): try: _plusInf = float('inf') _minusInf = float('-inf') _inf = (_plusInf, _minusInf) except ValueError: # Infinity support is platform and Python dependent _plusInf = _minusInf = None _inf = () tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x09) ) def __normalizeBase10(self, value): m, b, e = value while m and m % 10 == 0: m = m / 10 e = e + 1 return m, b, e def prettyIn(self, value): if isinstance(value, tuple) and len(value) == 3: for d in value: if not isinstance(d, intTypes): raise error.PyAsn1Error( 'Lame Real value syntax: %s' % (value,) ) if value[1] not in (2, 10): raise error.PyAsn1Error( 'Prohibited base for Real value: %s' % value[1] ) if value[1] == 10: value = self.__normalizeBase10(value) return value elif isinstance(value, intTypes): return self.__normalizeBase10((value, 10, 0)) elif isinstance(value, float): if self._inf and value in self._inf: return value else: e = 0 while int(value) != value: value = value * 10 e = e - 1 return self.__normalizeBase10((int(value), 10, e)) elif isinstance(value, Real): return tuple(value) elif isinstance(value, str): # handle infinite literal try: return float(value) except ValueError: pass raise error.PyAsn1Error( 'Bad real value syntax: %s' % (value,) ) def prettyOut(self, value): if value in self._inf: return '\'%s\'' % value else: return str(value) def isPlusInfinity(self): return self._value == self._plusInf def isMinusInfinity(self): return self._value == self._minusInf def isInfinity(self): return self._value in self._inf def __str__(self): return str(float(self)) def __add__(self, value): return self.clone(float(self) + value) def __radd__(self, value): return self + value def __mul__(self, value): return self.clone(float(self) * value) def __rmul__(self, value): return self * value def __sub__(self, value): return self.clone(float(self) - value) def __rsub__(self, value): return self.clone(value - float(self)) def __mod__(self, value): return self.clone(float(self) % value) def __rmod__(self, value): return self.clone(value % float(self)) def __pow__(self, value, modulo=None): return self.clone(pow(float(self), value, modulo)) def __rpow__(self, value): return self.clone(pow(value, float(self))) if sys.version_info[0] <= 2: def __div__(self, value): return self.clone(float(self) / value) def __rdiv__(self, value): return self.clone(value / float(self)) else: def __truediv__(self, value): return self.clone(float(self) / value) def __rtruediv__(self, value): return self.clone(value / float(self)) def __divmod__(self, value): return self.clone(float(self) // value) def __rdivmod__(self, value): return self.clone(value // float(self)) def __int__(self): return int(float(self)) if sys.version_info[0] <= 2: def __long__(self): return long(float(self)) def __float__(self): if self._value in self._inf: return self._value else: return float( self._value[0] * pow(self._value[1], self._value[2]) ) def __abs__(self): return abs(float(self)) def __lt__(self, value): return float(self) < value def __le__(self, value): return float(self) <= value def __eq__(self, value): return float(self) == value def __ne__(self, value): return float(self) != value def __gt__(self, value): return float(self) > value def __ge__(self, value): return float(self) >= value if sys.version_info[0] <= 2: def __nonzero__(self): return bool(float(self)) else: def __bool__(self): return bool(float(self)) __hash__ = base.AbstractSimpleAsn1Item.__hash__ def __getitem__(self, idx): if self._value in self._inf: raise error.PyAsn1Error('Invalid infinite value operation') else: return self._value[idx] class Enumerated(Integer): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x0A) ) # "Structured" ASN.1 types class SetOf(base.AbstractConstructedAsn1Item): componentType = None tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11) ) typeId = 1 def _cloneComponentValues(self, myClone, cloneValueFlag): idx = 0; l = len(self._componentValues) while idx < l: c = self._componentValues[idx] if c is not None: if isinstance(c, base.AbstractConstructedAsn1Item): myClone.setComponentByPosition( idx, c.clone(cloneValueFlag=cloneValueFlag) ) else: myClone.setComponentByPosition(idx, c.clone()) idx = idx + 1 def _verifyComponent(self, idx, value): if self._componentType is not None and \ not self._componentType.isSuperTypeOf(value): raise error.PyAsn1Error('Component type error %s' % value) def getComponentByPosition(self, idx): return self._componentValues[idx] def setComponentByPosition(self, idx, value=None, verifyConstraints=True): l = len(self._componentValues) if idx >= l: self._componentValues = self._componentValues + (idx-l+1)*[None] if value is None: if self._componentValues[idx] is None: if self._componentType is None: raise error.PyAsn1Error('Component type not defined') self._componentValues[idx] = self._componentType.clone() self._componentValuesSet = self._componentValuesSet + 1 return self elif not isinstance(value, base.Asn1Item): if self._componentType is None: raise error.PyAsn1Error('Component type not defined') if isinstance(self._componentType, base.AbstractSimpleAsn1Item): value = self._componentType.clone(value=value) else: raise error.PyAsn1Error('Instance value required') if verifyConstraints: if self._componentType is not None: self._verifyComponent(idx, value) self._verifySubtypeSpec(value, idx) if self._componentValues[idx] is None: self._componentValuesSet = self._componentValuesSet + 1 self._componentValues[idx] = value return self def getComponentTagMap(self): if self._componentType is not None: return self._componentType.getTagMap() def prettyPrint(self, scope=0): scope = scope + 1 r = self.__class__.__name__ + ':\n' for idx in range(len(self._componentValues)): r = r + ' '*scope if self._componentValues[idx] is None: r = r + '<empty>' else: r = r + self._componentValues[idx].prettyPrint(scope) return r class SequenceOf(SetOf): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10) ) typeId = 2 class SequenceAndSetBase(base.AbstractConstructedAsn1Item): componentType = namedtype.NamedTypes() def __init__(self, componentType=None, tagSet=None, subtypeSpec=None, sizeSpec=None): base.AbstractConstructedAsn1Item.__init__( self, componentType, tagSet, subtypeSpec, sizeSpec ) if self._componentType is None: self._componentTypeLen = 0 else: self._componentTypeLen = len(self._componentType) def __getitem__(self, idx): if isinstance(idx, str): return self.getComponentByName(idx) else: return base.AbstractConstructedAsn1Item.__getitem__(self, idx) def __setitem__(self, idx, value): if isinstance(idx, str): self.setComponentByName(idx, value) else: base.AbstractConstructedAsn1Item.__setitem__(self, idx, value) def _cloneComponentValues(self, myClone, cloneValueFlag): idx = 0; l = len(self._componentValues) while idx < l: c = self._componentValues[idx] if c is not None: if isinstance(c, base.AbstractConstructedAsn1Item): myClone.setComponentByPosition( idx, c.clone(cloneValueFlag=cloneValueFlag) ) else: myClone.setComponentByPosition(idx, c.clone()) idx = idx + 1 def _verifyComponent(self, idx, value): if idx >= self._componentTypeLen: raise error.PyAsn1Error( 'Component type error out of range' ) t = self._componentType[idx].getType() if not t.isSuperTypeOf(value): raise error.PyAsn1Error('Component type error %r vs %r' % (t, value)) def getComponentByName(self, name): return self.getComponentByPosition( self._componentType.getPositionByName(name) ) def setComponentByName(self, name, value=None, verifyConstraints=True): return self.setComponentByPosition( self._componentType.getPositionByName(name), value, verifyConstraints ) def getComponentByPosition(self, idx): try: return self._componentValues[idx] except IndexError: if idx < self._componentTypeLen: return raise def setComponentByPosition(self, idx, value=None, verifyConstraints=True): l = len(self._componentValues) if idx >= l: self._componentValues = self._componentValues + (idx-l+1)*[None] if value is None: if self._componentValues[idx] is None: self._componentValues[idx] = self._componentType.getTypeByPosition(idx).clone() self._componentValuesSet = self._componentValuesSet + 1 return self elif not isinstance(value, base.Asn1Item): t = self._componentType.getTypeByPosition(idx) if isinstance(t, base.AbstractSimpleAsn1Item): value = t.clone(value=value) else: raise error.PyAsn1Error('Instance value required') if verifyConstraints: if self._componentTypeLen: self._verifyComponent(idx, value) self._verifySubtypeSpec(value, idx) if self._componentValues[idx] is None: self._componentValuesSet = self._componentValuesSet + 1 self._componentValues[idx] = value return self def getNameByPosition(self, idx): if self._componentTypeLen: return self._componentType.getNameByPosition(idx) def getDefaultComponentByPosition(self, idx): if self._componentTypeLen and self._componentType[idx].isDefaulted: return self._componentType[idx].getType() def getComponentType(self): if self._componentTypeLen: return self._componentType def setDefaultComponents(self): if self._componentTypeLen == self._componentValuesSet: return idx = self._componentTypeLen while idx: idx = idx - 1 if self._componentType[idx].isDefaulted: if self.getComponentByPosition(idx) is None: self.setComponentByPosition(idx) elif not self._componentType[idx].isOptional: if self.getComponentByPosition(idx) is None: raise error.PyAsn1Error( 'Uninitialized component #%s at %r' % (idx, self) ) def prettyPrint(self, scope=0): scope = scope + 1 r = self.__class__.__name__ + ':\n' for idx in range(len(self._componentValues)): if self._componentValues[idx] is not None: r = r + ' '*scope componentType = self.getComponentType() if componentType is None: r = r + '<no-name>' else: r = r + componentType.getNameByPosition(idx) r = '%s=%s\n' % ( r, self._componentValues[idx].prettyPrint(scope) ) return r class Sequence(SequenceAndSetBase): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10) ) typeId = 3 def getComponentTagMapNearPosition(self, idx): if self._componentType: return self._componentType.getTagMapNearPosition(idx) def getComponentPositionNearType(self, tagSet, idx): if self._componentType: return self._componentType.getPositionNearType(tagSet, idx) else: return idx class Set(SequenceAndSetBase): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11) ) typeId = 4 def getComponent(self, innerFlag=0): return self def getComponentByType(self, tagSet, innerFlag=0): c = self.getComponentByPosition( self._componentType.getPositionByType(tagSet) ) if innerFlag and isinstance(c, Set): # get inner component by inner tagSet return c.getComponent(1) else: # get outer component by inner tagSet return c def setComponentByType(self, tagSet, value=None, innerFlag=0, verifyConstraints=True): idx = self._componentType.getPositionByType(tagSet) t = self._componentType.getTypeByPosition(idx) if innerFlag: # set inner component by inner tagSet if t.getTagSet(): return self.setComponentByPosition( idx, value, verifyConstraints ) else: t = self.setComponentByPosition(idx).getComponentByPosition(idx) return t.setComponentByType( tagSet, value, innerFlag, verifyConstraints ) else: # set outer component by inner tagSet return self.setComponentByPosition( idx, value, verifyConstraints ) def getComponentTagMap(self): if self._componentType: return self._componentType.getTagMap(True) def getComponentPositionByType(self, tagSet): if self._componentType: return self._componentType.getPositionByType(tagSet) class Choice(Set): tagSet = baseTagSet = tag.TagSet() # untagged sizeSpec = constraint.ConstraintsIntersection( constraint.ValueSizeConstraint(1, 1) ) typeId = 5 _currentIdx = None def __eq__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] == other return NotImplemented def __ne__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] != other return NotImplemented def __lt__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] < other return NotImplemented def __le__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] <= other return NotImplemented def __gt__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] > other return NotImplemented def __ge__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] >= other return NotImplemented if sys.version_info[0] <= 2: def __nonzero__(self, other): return bool(self._componentValues) else: def __bool__(self, other): return bool(self._componentValues) def __len__(self): return self._currentIdx is not None and 1 or 0 def verifySizeSpec(self): if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: self._sizeSpec(' ') def _cloneComponentValues(self, myClone, cloneValueFlag): try: c = self.getComponent() except error.PyAsn1Error: pass else: if isinstance(c, Choice): tagSet = c.getEffectiveTagSet() else: tagSet = c.getTagSet() if isinstance(c, base.AbstractConstructedAsn1Item): myClone.setComponentByType( tagSet, c.clone(cloneValueFlag=cloneValueFlag) ) else: myClone.setComponentByType(tagSet, c.clone()) def setComponentByPosition(self, idx, value=None, verifyConstraints=True): l = len(self._componentValues) if idx >= l: self._componentValues = self._componentValues + (idx-l+1)*[None] if self._currentIdx is not None: self._componentValues[self._currentIdx] = None if value is None: if self._componentValues[idx] is None: self._componentValues[idx] = self._componentType.getTypeByPosition(idx).clone() self._componentValuesSet = 1 self._currentIdx = idx return self elif not isinstance(value, base.Asn1Item): value = self._componentType.getTypeByPosition(idx).clone( value=value ) if verifyConstraints: if self._componentTypeLen: self._verifyComponent(idx, value) self._verifySubtypeSpec(value, idx) self._componentValues[idx] = value self._currentIdx = idx self._componentValuesSet = 1 return self def getMinTagSet(self): if self._tagSet: return self._tagSet else: return self._componentType.genMinTagSet() def getEffectiveTagSet(self): if self._tagSet: return self._tagSet else: c = self.getComponent() if isinstance(c, Choice): return c.getEffectiveTagSet() else: return c.getTagSet() def getTagMap(self): if self._tagSet: return Set.getTagMap(self) else: return Set.getComponentTagMap(self) def getComponent(self, innerFlag=0): if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: c = self._componentValues[self._currentIdx] if innerFlag and isinstance(c, Choice): return c.getComponent(innerFlag) else: return c def getName(self, innerFlag=0): if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: if innerFlag: c = self._componentValues[self._currentIdx] if isinstance(c, Choice): return c.getName(innerFlag) return self._componentType.getNameByPosition(self._currentIdx) def setDefaultComponents(self): pass class Any(OctetString): tagSet = baseTagSet = tag.TagSet() # untagged typeId = 6 def getTagMap(self): return tagmap.TagMap( { self.getTagSet(): self }, { eoo.endOfOctets.getTagSet(): eoo.endOfOctets }, self ) # XXX # coercion rules?
bsd-3-clause
aded309ab4ad5f6cea34f69ffd6280db
37.143684
117
0.551182
4.210218
false
false
false
false
mozilla/mozilla-ignite
apps/challenges/migrations/0031_auto__add_field_submission_life_improvements__add_field_submission_tak.py
1
17108
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): depends_on = ( ('challenges', '0030_remove_min_criterion_value'), ) def forwards(self, orm): # Adding field 'Submission.life_improvements' db.add_column('challenges_submission', 'life_improvements', self.gf('django.db.models.fields.TextField')(default=''), keep_default=False) # Adding field 'Submission.take_advantage' db.add_column('challenges_submission', 'take_advantage', self.gf('django.db.models.fields.TextField')(null=True, blank=True), keep_default=False) # Adding field 'Submission.interest_making' db.add_column('challenges_submission', 'interest_making', self.gf('django.db.models.fields.TextField')(null=True, blank=True), keep_default=False) # Adding field 'Submission.team_members' db.add_column('challenges_submission', 'team_members', self.gf('django.db.models.fields.TextField')(null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'Submission.life_improvements' db.delete_column('challenges_submission', 'life_improvements') # Deleting field 'Submission.take_advantage' db.delete_column('challenges_submission', 'take_advantage') # Deleting field 'Submission.interest_making' db.delete_column('challenges_submission', 'interest_making') # Deleting field 'Submission.team_members' db.delete_column('challenges_submission', 'team_members') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'challenges.category': { 'Meta': {'object_name': 'Category'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '60', 'db_index': 'True'}) }, 'challenges.challenge': { 'Meta': {'object_name': 'Challenge'}, 'allow_voting': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.TextField', [], {}), 'end_date': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'moderate': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']"}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '60', 'db_index': 'True'}), 'start_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.utcnow'}), 'summary': ('django.db.models.fields.TextField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}) }, 'challenges.exclusionflag': { 'Meta': {'object_name': 'ExclusionFlag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Submission']"}) }, 'challenges.externallink': { 'Meta': {'object_name': 'ExternalLink'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Submission']", 'null': 'True', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '255'}) }, 'challenges.judgeassignment': { 'Meta': {'unique_together': "(('submission', 'judge'),)", 'object_name': 'JudgeAssignment'}, 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.utcnow'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'judge': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Profile']"}), 'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Submission']"}) }, 'challenges.judgement': { 'Meta': {'unique_together': "(('submission', 'judge'),)", 'object_name': 'Judgement'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'judge': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Profile']"}), 'notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Submission']"}) }, 'challenges.judginganswer': { 'Meta': {'unique_together': "(('judgement', 'criterion'),)", 'object_name': 'JudgingAnswer'}, 'criterion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.JudgingCriterion']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'judgement': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'answers'", 'to': "orm['challenges.Judgement']"}), 'rating': ('django.db.models.fields.IntegerField', [], {}) }, 'challenges.judgingcriterion': { 'Meta': {'ordering': "('id',)", 'object_name': 'JudgingCriterion'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'max_value': ('django.db.models.fields.IntegerField', [], {'default': '10'}), 'phases': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'judgement_criteria'", 'blank': 'True', 'through': "orm['challenges.PhaseCriterion']", 'to': "orm['challenges.Phase']"}), 'question': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '250'}) }, 'challenges.phase': { 'Meta': {'ordering': "('order',)", 'unique_together': "(('challenge', 'name'),)", 'object_name': 'Phase'}, 'challenge': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'phases'", 'to': "orm['challenges.Challenge']"}), 'end_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 9, 28, 10, 51, 17, 415245)'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'order': ('django.db.models.fields.IntegerField', [], {}), 'start_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.utcnow'}) }, 'challenges.phasecriterion': { 'Meta': {'unique_together': "(('phase', 'criterion'),)", 'object_name': 'PhaseCriterion'}, 'criterion': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.JudgingCriterion']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'phase': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Phase']"}), 'weight': ('django.db.models.fields.DecimalField', [], {'default': '10', 'max_digits': '4', 'decimal_places': '2'}) }, 'challenges.submission': { 'Meta': {'ordering': "['-id']", 'object_name': 'Submission'}, 'brief_description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Category']"}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Profile']"}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.utcnow'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'interest_making': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_winner': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'life_improvements': ('django.db.models.fields.TextField', [], {'default': "''"}), 'phase': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Phase']"}), 'sketh_note': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'take_advantage': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'team_members': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'projects.project': { 'Meta': {'object_name': 'Project'}, 'allow_participation': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'allow_sub_projects': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'featured_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'followers': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'projects_following'", 'symmetrical': 'False', 'to': "orm['users.Profile']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'long_description': ('django.db.models.fields.TextField', [], {}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'parent_project_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}), 'sub_project_label': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'team_members': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['users.Profile']", 'symmetrical': 'False'}), 'topics': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['topics.Topic']", 'symmetrical': 'False'}) }, 'taggit.tag': { 'Meta': {'object_name': 'Tag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}) }, 'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"}) }, 'topics.topic': { 'Meta': {'object_name': 'Topic'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'draft': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'long_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}) }, 'users.profile': { 'Meta': {'object_name': 'Profile'}, 'avatar': ('django.db.models.fields.files.ImageField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'bio': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'featured_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}) } } complete_apps = ['challenges']
bsd-3-clause
b8f44a053c670e90786c897c2b802573
74.035088
241
0.561141
3.699027
false
false
false
false
mozilla/mozilla-ignite
vendor-local/lib/python/requests/packages/urllib3/request.py
107
5427
# urllib3/request.py # Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php try: from urllib.parse import urlencode except ImportError: from urllib import urlencode from .filepost import encode_multipart_formdata __all__ = ['RequestMethods'] class RequestMethods(object): """ Convenience mixin for classes who implement a :meth:`urlopen` method, such as :class:`~urllib3.connectionpool.HTTPConnectionPool` and :class:`~urllib3.poolmanager.PoolManager`. Provides behavior for making common types of HTTP request methods and decides which type of request field encoding to use. Specifically, :meth:`.request_encode_url` is for sending requests whose fields are encoded in the URL (such as GET, HEAD, DELETE). :meth:`.request_encode_body` is for sending requests whose fields are encoded in the *body* of the request using multipart or www-orm-urlencoded (such as for POST, PUT, PATCH). :meth:`.request` is for making any kind of request, it will look up the appropriate encoding format and use one of the above two methods to make the request. """ _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS']) _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE']) def urlopen(self, method, url, body=None, headers=None, encode_multipart=True, multipart_boundary=None, **kw): # Abstract raise NotImplemented("Classes extending RequestMethods must implement " "their own ``urlopen`` method.") def request(self, method, url, fields=None, headers=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the appropriate encoding of ``fields`` based on the ``method`` used. This is a convenience method that requires the least amount of manual effort. It can be used in most situations, while still having the option to drop down to more specific methods when necessary, such as :meth:`request_encode_url`, :meth:`request_encode_body`, or even the lowest level :meth:`urlopen`. """ method = method.upper() if method in self._encode_url_methods: return self.request_encode_url(method, url, fields=fields, headers=headers, **urlopen_kw) else: return self.request_encode_body(method, url, fields=fields, headers=headers, **urlopen_kw) def request_encode_url(self, method, url, fields=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. """ if fields: url += '?' + urlencode(fields) return self.urlopen(method, url, **urlopen_kw) def request_encode_body(self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :meth:`urllib.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data) tuple. For example: :: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'nonamefile': ('contents of nonamefile field'), } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimick behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter. """ if encode_multipart: body, content_type = encode_multipart_formdata(fields or {}, boundary=multipart_boundary) else: body, content_type = (urlencode(fields or {}), 'application/x-www-form-urlencoded') headers = headers or {} headers.update({'Content-Type': content_type}) return self.urlopen(method, url, body=body, headers=headers, **urlopen_kw)
bsd-3-clause
87aa22cf0791422b2a2ce44f71d97c4d
41.398438
81
0.616178
4.583615
false
false
false
false
mozilla/mozilla-ignite
apps/users/models.py
1
4554
# -*- coding: utf-8 -*- import base64 import hashlib from django.conf import settings from django.contrib.auth.models import User from django.db import models from innovate.models import BaseModel from innovate.utils import get_partition_id, safe_filename, ImageStorage from tower import ugettext_lazy as _ def determine_upload_path(instance, filename): chunk_size = 1000 # max files per directory path = getattr(settings, 'USER_AVATAR_PATH', 'images/profiles/') path = path.lstrip('/').rstrip('/') return "%(path)s/%(filename)s" % { 'path': path, 'filename': safe_filename(filename) } class Link(BaseModel): name = models.CharField(max_length=50, verbose_name=_(u'Link Name')) url = models.URLField(verbose_name=_(u'URL'), max_length=255) profile = models.ForeignKey('users.Profile', blank=True, null=True) def __unicode__(self): return u'%s -> %s' % (self.name, self.url) def get_profile(cls): """Create an empty profile for users if none exists.""" profile, created = Profile.objects.get_or_create(user=cls) return profile User.get_profile = get_profile class Profile(BaseModel): user = models.OneToOneField(User, primary_key=True, verbose_name=_(u'User')) name = models.CharField(max_length=255, blank=True, verbose_name=_(u'Display name')) title = models.CharField(max_length=255, blank=True, null=True, verbose_name=(u'Job title')) avatar = models.ImageField(upload_to=determine_upload_path, null=True, blank=True, verbose_name=_(u'Avatar'), max_length=settings.MAX_FILEPATH_LENGTH, storage=ImageStorage()) website = models.URLField(verbose_name=_(u'Website'), max_length=255, blank=True) bio = models.TextField(verbose_name=_(u'Bio'), blank=True) featured = models.BooleanField(default=False) featured_image = models.ImageField(verbose_name=_(u'Featured Image'), blank=True, null=True, upload_to=settings.USER_AVATAR_PATH) @models.permalink def get_absolute_url(self): return ('users_profile', [self.user.username]) def get_gravatar_url(self, size=140): base_url = getattr(settings, 'GRAVATAR_URL', None) if not base_url: return None return '%s%s?s=%d' % (base_url, self.email_hash, size) @property def email_hash(self): """MD5 hash of users email address.""" return hashlib.md5(self.user.email).hexdigest() def avatar_url(self, size=140): """Return user provided avatar, or gravatar if none exists.""" media_url = getattr(settings, 'MEDIA_URL', None) path = lambda f: f and "%s%s" % (media_url, f) return path(self.avatar) or self.get_gravatar_url(size) @property def featured_image_or_default(self): """Return featured image for splash page.""" return self.featured_image or 'img/featured-default.gif' def __unicode__(self): """Return a string representation of the user.""" return self.display_name @property def username_hash(self): """ Return a hash of the users email. Used as a URL component when no username is set (as is the case with users signed up via BrowserID). """ return base64.urlsafe_b64encode( hashlib.sha1(self.user.email).digest()).rstrip('=') @property def has_chosen_identifier(self): """Determine if user has a generated or chosen public identifier..""" return self.name or (not self.user.username == self.username_hash) @property def masked_email(self): """ If a user does not have a display name or a username, their email may be displayed on their profile. This returns a masked copy so we don't leak that data. """ user, domain = self.user.email.split('@') mask_part = lambda s, n: s[:n] + u'…' + s[-1:] return '@'.join( (mask_part(user, len(user) / 3), mask_part(domain, 1))) @property def display_name(self): """Choose and return the best public display identifier for a user.""" if self.name: return self.name if self.has_chosen_identifier: return self.user.username return self.masked_email
bsd-3-clause
dd9431b340699a98469ac09a6452d833
35.416
78
0.605009
3.941126
false
false
false
false
mozilla/mozilla-ignite
vendor-local/lib/python/rsa/key.py
5
17161
# -*- coding: utf-8 -*- # # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''RSA key generation code. Create new keys with the newkeys() function. It will give you a PublicKey and a PrivateKey object. Loading and saving keys requires the pyasn1 module. This module is imported as late as possible, such that other functionality will remain working in absence of pyasn1. ''' import logging import rsa.prime import rsa.pem import rsa.common log = logging.getLogger(__name__) class AbstractKey(object): '''Abstract superclass for private and public keys.''' @classmethod def load_pkcs1(cls, keyfile, format='PEM'): r'''Loads a key in PKCS#1 DER or PEM format. :param keyfile: contents of a DER- or PEM-encoded file that contains the public key. :param format: the format of the file to load; 'PEM' or 'DER' :return: a PublicKey object ''' methods = { 'PEM': cls._load_pkcs1_pem, 'DER': cls._load_pkcs1_der, } if format not in methods: formats = ', '.join(sorted(methods.keys())) raise ValueError('Unsupported format: %r, try one of %s' % (format, formats)) method = methods[format] return method(keyfile) def save_pkcs1(self, format='PEM'): '''Saves the public key in PKCS#1 DER or PEM format. :param format: the format to save; 'PEM' or 'DER' :returns: the DER- or PEM-encoded public key. ''' methods = { 'PEM': self._save_pkcs1_pem, 'DER': self._save_pkcs1_der, } if format not in methods: formats = ', '.join(sorted(methods.keys())) raise ValueError('Unsupported format: %r, try one of %s' % (format, formats)) method = methods[format] return method() class PublicKey(AbstractKey): '''Represents a public RSA key. This key is also known as the 'encryption key'. It contains the 'n' and 'e' values. Supports attributes as well as dictionary-like access. Attribute accesss is faster, though. >>> PublicKey(5, 3) PublicKey(5, 3) >>> key = PublicKey(5, 3) >>> key.n 5 >>> key['n'] 5 >>> key.e 3 >>> key['e'] 3 ''' __slots__ = ('n', 'e') def __init__(self, n, e): self.n = n self.e = e def __getitem__(self, key): return getattr(self, key) def __repr__(self): return u'PublicKey(%i, %i)' % (self.n, self.e) def __eq__(self, other): if other is None: return False if not isinstance(other, PublicKey): return False return self.n == other.n and self.e == other.e def __ne__(self, other): return not (self == other) @classmethod def _load_pkcs1_der(cls, keyfile): r'''Loads a key in PKCS#1 DER format. @param keyfile: contents of a DER-encoded file that contains the public key. @return: a PublicKey object First let's construct a DER encoded key: >>> import base64 >>> b64der = 'MAwCBQCNGmYtAgMBAAE=' >>> der = base64.decodestring(b64der) This loads the file: >>> PublicKey._load_pkcs1_der(der) PublicKey(2367317549, 65537) ''' from pyasn1.codec.der import decoder (priv, _) = decoder.decode(keyfile) # ASN.1 contents of DER encoded public key: # # RSAPublicKey ::= SEQUENCE { # modulus INTEGER, -- n # publicExponent INTEGER, -- e as_ints = tuple(int(x) for x in priv) return cls(*as_ints) def _save_pkcs1_der(self): '''Saves the public key in PKCS#1 DER format. @returns: the DER-encoded public key. ''' from pyasn1.type import univ, namedtype from pyasn1.codec.der import encoder class AsnPubKey(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('modulus', univ.Integer()), namedtype.NamedType('publicExponent', univ.Integer()), ) # Create the ASN object asn_key = AsnPubKey() asn_key.setComponentByName('modulus', self.n) asn_key.setComponentByName('publicExponent', self.e) return encoder.encode(asn_key) @classmethod def _load_pkcs1_pem(cls, keyfile): '''Loads a PKCS#1 PEM-encoded public key file. The contents of the file before the "-----BEGIN RSA PUBLIC KEY-----" and after the "-----END RSA PUBLIC KEY-----" lines is ignored. @param keyfile: contents of a PEM-encoded file that contains the public key. @return: a PublicKey object ''' der = rsa.pem.load_pem(keyfile, 'RSA PUBLIC KEY') return cls._load_pkcs1_der(der) def _save_pkcs1_pem(self): '''Saves a PKCS#1 PEM-encoded public key file. @return: contents of a PEM-encoded file that contains the public key. ''' der = self._save_pkcs1_der() return rsa.pem.save_pem(der, 'RSA PUBLIC KEY') class PrivateKey(AbstractKey): '''Represents a private RSA key. This key is also known as the 'decryption key'. It contains the 'n', 'e', 'd', 'p', 'q' and other values. Supports attributes as well as dictionary-like access. Attribute accesss is faster, though. >>> PrivateKey(3247, 65537, 833, 191, 17) PrivateKey(3247, 65537, 833, 191, 17) exp1, exp2 and coef don't have to be given, they will be calculated: >>> pk = PrivateKey(3727264081, 65537, 3349121513, 65063, 57287) >>> pk.exp1 55063 >>> pk.exp2 10095 >>> pk.coef 50797 If you give exp1, exp2 or coef, they will be used as-is: >>> pk = PrivateKey(1, 2, 3, 4, 5, 6, 7, 8) >>> pk.exp1 6 >>> pk.exp2 7 >>> pk.coef 8 ''' __slots__ = ('n', 'e', 'd', 'p', 'q', 'exp1', 'exp2', 'coef') def __init__(self, n, e, d, p, q, exp1=None, exp2=None, coef=None): self.n = n self.e = e self.d = d self.p = p self.q = q # Calculate the other values if they aren't supplied if exp1 is None: self.exp1 = int(d % (p - 1)) else: self.exp1 = exp1 if exp1 is None: self.exp2 = int(d % (q - 1)) else: self.exp2 = exp2 if coef is None: (_, self.coef, _) = extended_gcd(q, p) else: self.coef = coef def __getitem__(self, key): return getattr(self, key) def __repr__(self): return u'PrivateKey(%(n)i, %(e)i, %(d)i, %(p)i, %(q)i)' % self def __eq__(self, other): if other is None: return False if not isinstance(other, PrivateKey): return False return (self.n == other.n and self.e == other.e and self.d == other.d and self.p == other.p and self.q == other.q and self.exp1 == other.exp1 and self.exp2 == other.exp2 and self.coef == other.coef) def __ne__(self, other): return not (self == other) @classmethod def _load_pkcs1_der(cls, keyfile): r'''Loads a key in PKCS#1 DER format. @param keyfile: contents of a DER-encoded file that contains the private key. @return: a PrivateKey object First let's construct a DER encoded key: >>> import base64 >>> b64der = 'MC4CAQACBQDeKYlRAgMBAAECBQDHn4npAgMA/icCAwDfxwIDANcXAgInbwIDAMZt' >>> der = base64.decodestring(b64der) This loads the file: >>> PrivateKey._load_pkcs1_der(der) PrivateKey(3727264081, 65537, 3349121513, 65063, 57287) ''' from pyasn1.codec.der import decoder (priv, _) = decoder.decode(keyfile) # ASN.1 contents of DER encoded private key: # # RSAPrivateKey ::= SEQUENCE { # version Version, # modulus INTEGER, -- n # publicExponent INTEGER, -- e # privateExponent INTEGER, -- d # prime1 INTEGER, -- p # prime2 INTEGER, -- q # exponent1 INTEGER, -- d mod (p-1) # exponent2 INTEGER, -- d mod (q-1) # coefficient INTEGER, -- (inverse of q) mod p # otherPrimeInfos OtherPrimeInfos OPTIONAL # } if priv[0] != 0: raise ValueError('Unable to read this file, version %s != 0' % priv[0]) as_ints = tuple(int(x) for x in priv[1:9]) return cls(*as_ints) def _save_pkcs1_der(self): '''Saves the private key in PKCS#1 DER format. @returns: the DER-encoded private key. ''' from pyasn1.type import univ, namedtype from pyasn1.codec.der import encoder class AsnPrivKey(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('version', univ.Integer()), namedtype.NamedType('modulus', univ.Integer()), namedtype.NamedType('publicExponent', univ.Integer()), namedtype.NamedType('privateExponent', univ.Integer()), namedtype.NamedType('prime1', univ.Integer()), namedtype.NamedType('prime2', univ.Integer()), namedtype.NamedType('exponent1', univ.Integer()), namedtype.NamedType('exponent2', univ.Integer()), namedtype.NamedType('coefficient', univ.Integer()), ) # Create the ASN object asn_key = AsnPrivKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', self.n) asn_key.setComponentByName('publicExponent', self.e) asn_key.setComponentByName('privateExponent', self.d) asn_key.setComponentByName('prime1', self.p) asn_key.setComponentByName('prime2', self.q) asn_key.setComponentByName('exponent1', self.exp1) asn_key.setComponentByName('exponent2', self.exp2) asn_key.setComponentByName('coefficient', self.coef) return encoder.encode(asn_key) @classmethod def _load_pkcs1_pem(cls, keyfile): '''Loads a PKCS#1 PEM-encoded private key file. The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and after the "-----END RSA PRIVATE KEY-----" lines is ignored. @param keyfile: contents of a PEM-encoded file that contains the private key. @return: a PrivateKey object ''' der = rsa.pem.load_pem(keyfile, 'RSA PRIVATE KEY') return cls._load_pkcs1_der(der) def _save_pkcs1_pem(self): '''Saves a PKCS#1 PEM-encoded private key file. @return: contents of a PEM-encoded file that contains the private key. ''' der = self._save_pkcs1_der() return rsa.pem.save_pem(der, 'RSA PRIVATE KEY') def extended_gcd(a, b): """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb """ # r = gcd(a,b) i = multiplicitive inverse of a mod b # or j = multiplicitive inverse of b mod a # Neg return values for i or j are made positive mod b or a respectively # Iterateive Version is faster and uses much less stack space x = 0 y = 1 lx = 1 ly = 0 oa = a #Remember original a/b to remove ob = b #negative values from return results while b != 0: q = a // b (a, b) = (b, a % b) (x, lx) = ((lx - (q * x)),x) (y, ly) = ((ly - (q * y)),y) if (lx < 0): lx += ob #If neg wrap modulo orignal b if (ly < 0): ly += oa #If neg wrap modulo orignal a return (a, lx, ly) #Return only positive values def find_p_q(nbits, accurate=True): ''''Returns a tuple of two different primes of nbits bits each. The resulting p * q has exacty 2 * nbits bits, and the returned p and q will not be equal. @param nbits: the number of bits in each of p and q. @param accurate: whether to enable accurate mode or not. @returns (p, q), where p > q >>> (p, q) = find_p_q(128) >>> from rsa import common >>> common.bit_size(p * q) 256 When not in accurate mode, the number of bits can be slightly less >>> (p, q) = find_p_q(128, accurate=False) >>> from rsa import common >>> common.bit_size(p * q) <= 256 True >>> common.bit_size(p * q) > 240 True ''' total_bits = nbits * 2 # Make sure that p and q aren't too close or the factoring programs can # factor n. shift = nbits // 16 pbits = nbits + shift qbits = nbits - shift # Choose the two initial primes log.debug('find_p_q(%i): Finding p', nbits) p = rsa.prime.getprime(pbits) log.debug('find_p_q(%i): Finding q', nbits) q = rsa.prime.getprime(qbits) def is_acceptable(p, q): '''Returns True iff p and q are acceptable: - p and q differ - (p * q) has the right nr of bits (when accurate=True) ''' if p == q: return False if not accurate: return True # Make sure we have just the right amount of bits found_size = rsa.common.bit_size(p * q) return total_bits == found_size # Keep choosing other primes until they match our requirements. change_p = False tries = 0 while not is_acceptable(p, q): tries += 1 # Change p on one iteration and q on the other if change_p: log.debug(' find another p') p = rsa.prime.getprime(pbits) else: log.debug(' find another q') q = rsa.prime.getprime(qbits) change_p = not change_p # We want p > q as described on # http://www.di-mgt.com.au/rsa_alg.html#crt return (max(p, q), min(p, q)) def calculate_keys(p, q, nbits): """Calculates an encryption and a decryption key given p and q, and returns them as a tuple (e, d) """ phi_n = (p - 1) * (q - 1) # A very common choice for e is 65537 e = 65537 (divider, d, _) = extended_gcd(e, phi_n) if divider != 1: raise ValueError("e (%d) and phi_n (%d) are not relatively prime" % (e, phi_n)) if (d < 0): raise ValueError("extended_gcd shouldn't return negative values, " "please file a bug") if (e * d) % phi_n != 1: raise ValueError("e (%d) and d (%d) are not mult. inv. modulo " "phi_n (%d)" % (e, d, phi_n)) return (e, d) def gen_keys(nbits, accurate=True): """Generate RSA keys of nbits bits. Returns (p, q, e, d). Note: this can take a long time, depending on the key size. @param nbits: the total number of bits in ``p`` and ``q``. Both ``p`` and ``q`` will use ``nbits/2`` bits. """ (p, q) = find_p_q(nbits // 2, accurate) (e, d) = calculate_keys(p, q, nbits // 2) return (p, q, e, d) def newkeys(nbits, accurate=True): """Generates public and private keys, and returns them as (pub, priv). The public key is also known as the 'encryption key', and is a :py:class:`PublicKey` object. The private key is also known as the 'decryption key' and is a :py:class:`PrivateKey` object. :param nbits: the number of bits required to store ``n = p*q``. :param accurate: when True, ``n`` will have exactly the number of bits you asked for. However, this makes key generation much slower. When False, `n`` may have slightly less bits. :returns: a tuple (:py:class:`rsa.PublicKey`, :py:class:`rsa.PrivateKey`) """ if nbits < 16: raise ValueError('Key too small') (p, q, e, d) = gen_keys(nbits) n = p * q return ( PublicKey(n, e), PrivateKey(n, e, d, p, q) ) __all__ = ['PublicKey', 'PrivateKey', 'newkeys'] if __name__ == '__main__': import doctest try: for count in range(100): (failures, tests) = doctest.testmod() if failures: break if (count and count % 10 == 0) or count == 1: print '%i times' % count except KeyboardInterrupt: print 'Aborted' else: print 'Doctests done'
bsd-3-clause
478102e7657183434a2dde06f026d27b
28.433962
87
0.562296
3.658849
false
false
false
false
mozilla/mozilla-ignite
apps/users/migrations/0003_auto__add_link__add_field_profile_bio.py
2
6019
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Link' db.create_table('users_link', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('service', self.gf('django.db.models.fields.CharField')(max_length=50)), ('name', self.gf('django.db.models.fields.CharField')(max_length=50)), ('url', self.gf('django.db.models.fields.URLField')(max_length=255)), )) db.send_create_signal('users', ['Link']) # Adding field 'Profile.bio' db.add_column('users_profile', 'bio', self.gf('django.db.models.fields.TextField')(default='', blank=True), keep_default=False) # Adding M2M table for field links on 'Profile' db.create_table('users_profile_links', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('profile', models.ForeignKey(orm['users.profile'], null=False)), ('link', models.ForeignKey(orm['users.link'], null=False)) )) db.create_unique('users_profile_links', ['profile_id', 'link_id']) def backwards(self, orm): # Deleting model 'Link' db.delete_table('users_link') # Deleting field 'Profile.bio' db.delete_column('users_profile', 'bio') # Removing M2M table for field links on 'Profile' db.delete_table('users_profile_links') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'users.link': { 'Meta': {'object_name': 'Link'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'service': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '255'}) }, 'users.profile': { 'Meta': {'object_name': 'Profile'}, 'avatar': ('django.db.models.fields.files.ImageField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'bio': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'confirmation_token': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'links': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['users.Link']", 'symmetrical': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}) } } complete_apps = ['users']
bsd-3-clause
e663ad42e41ed388f0d0845555ddb8f5
59.19
182
0.556571
3.720025
false
false
false
false
mozilla/mozilla-ignite
apps/challenges/migrations/0015_auto.py
1
12702
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding M2M table for field category on 'Submission' db.create_table('challenges_submission_category', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('submission', models.ForeignKey(orm['challenges.submission'], null=False)), ('category', models.ForeignKey(orm['challenges.category'], null=False)) )) db.create_unique('challenges_submission_category', ['submission_id', 'category_id']) def backwards(self, orm): # Removing M2M table for field category on 'Submission' db.delete_table('challenges_submission_category') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'challenges.category': { 'Meta': {'object_name': 'Category'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '60', 'db_index': 'True'}) }, 'challenges.challenge': { 'Meta': {'object_name': 'Challenge'}, 'allow_voting': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.TextField', [], {}), 'end_date': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'moderate': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']"}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '60', 'db_index': 'True'}), 'start_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'summary': ('django.db.models.fields.TextField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}) }, 'challenges.externallink': { 'Meta': {'object_name': 'ExternalLink'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Submission']", 'null': 'True', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '255'}) }, 'challenges.phase': { 'Meta': {'ordering': "('order',)", 'unique_together': "(('challenge', 'name'),)", 'object_name': 'Phase'}, 'challenge': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'phases'", 'to': "orm['challenges.Challenge']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'order': ('django.db.models.fields.IntegerField', [], {}) }, 'challenges.submission': { 'Meta': {'ordering': "['-id']", 'object_name': 'Submission'}, 'brief_description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'category': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['challenges.Category']", 'symmetrical': 'False'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Profile']"}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 12, 6, 14, 15, 52, 383201)'}), 'description': ('django.db.models.fields.TextField', [], {}), 'flagged_offensive': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'flagged_offensive_reason': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_live': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_winner': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'phase': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['challenges.Phase']"}), 'sketh_note': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '60'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'projects.project': { 'Meta': {'object_name': 'Project'}, 'allow_participation': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'allow_sub_projects': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'featured_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'followers': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'projects_following'", 'symmetrical': 'False', 'to': "orm['users.Profile']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'long_description': ('django.db.models.fields.TextField', [], {}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'parent_project_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}), 'sub_project_label': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'team_members': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['users.Profile']", 'symmetrical': 'False'}), 'topics': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['topics.Topic']", 'symmetrical': 'False'}) }, 'taggit.tag': { 'Meta': {'object_name': 'Tag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}) }, 'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"}) }, 'topics.topic': { 'Meta': {'object_name': 'Topic'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'draft': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'long_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}) }, 'users.profile': { 'Meta': {'object_name': 'Profile'}, 'avatar': ('django.db.models.fields.files.ImageField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'bio': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'featured_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}) } } complete_apps = ['challenges']
bsd-3-clause
6ed8fc8753cbda11e40b5b9e4b84156d
75.05988
182
0.552118
3.705368
false
false
false
false
mitsuhiko/zine
zine/services.py
1
1400
# -*- coding: utf-8 -*- """ zine.services ~~~~~~~~~~~~~ The builtin (JSON) services. :copyright: (c) 2010 by the Zine Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from werkzeug import abort from zine.models import Comment, Tag from zine.privileges import MODERATE_COMMENTS from zine.utils.dates import to_timestamp def do_get_comment(req): comment_id = req.values.get('comment_id') if comment_id is None: abort(404) comment = Comment.query.get(comment_id) if comment is None: abort(404) if comment.blocked and not req.user.has_privilege(MODERATE_COMMENTS): abort(403) if comment.parent is not None: parent_id = comment.parent.id else: parent_id = None email = None if req.user.is_manager: email = comment.email return { 'id': comment.id, 'parent': parent_id, 'body': unicode(comment.body), 'author': comment.author, 'email': email, 'pub_date': to_timestamp(comment.pub_date), } def do_get_taglist(req): return { 'tags': sorted([t.name for t in Tag.query.all()], key=lambda x: x.lower()) } all_services = { 'get_comment': do_get_comment, 'get_taglist': do_get_taglist }
bsd-3-clause
ad2861248ea411b94cb34ea16c40f985
24.925926
73
0.569286
3.589744
false
false
false
false
mitsuhiko/zine
zine/utils/crypto.py
1
5077
""" zine.utils.crypto ~~~~~~~~~~~~~~~~~ This module implements various cryptographic functions. :copyright: (c) 2010 by the Zine Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import string from random import choice, randrange try: from hashlib import sha1, md5 except ImportError: from sha import new as sha1 from md5 import new as md5 KEY_CHARS = string.ascii_letters + string.digits IDENTIFIER_START = string.ascii_letters + '_' IDENTIFIER_CHAR = IDENTIFIER_START + string.digits SALT_CHARS = string.ascii_lowercase + string.digits SECRET_KEY_CHARS = string.ascii_letters + string.digits + string.punctuation def gen_salt(length=6): """Generate a random string of SALT_CHARS with specified ``length``.""" if length <= 0: raise ValueError('requested salt of length <= 0') return ''.join(choice(SALT_CHARS) for _ in xrange(length)) def new_iid(): """Called by the websetup to get a unique uuid for the application iid.""" try: import uuid except ImportError: # if there is no uuid support, we create a pseudo-unique id based # on the current time. This should be good enough to keep local # installations apart. import time return '%x%x' % tuple(map(int, str(time.time()).split('.'))) return uuid.uuid4().hex def gen_activation_key(length=8): """Generate a ``length`` long string of KEY_CHARS, suitable as password or activation key. """ if length <= 0: raise ValueError('requested key of length <= 0') return ''.join(choice(KEY_CHARS) for _ in xrange(length)) def gen_random_identifier(length=8): """Generate a random identifier.""" if length <= 0: raise ValueError('requested key of length <= 0') return choice(IDENTIFIER_START) + \ ''.join(choice(IDENTIFIER_CHAR) for _ in xrange(length - 1)) def gen_secret_key(): """Generate a new secret key.""" return ''.join(choice(SECRET_KEY_CHARS) for _ in xrange(64)) def gen_password(length=8, add_numbers=True, mix_case=True, add_special_char=True): """Generate a pronounceable password.""" if length <= 0: raise ValueError('requested password of length <= 0') consonants = 'bcdfghjklmnprstvwz' vowels = 'aeiou' if mix_case: consonants = consonants * 2 + consonants.upper() vowels = vowels * 2 + vowels.upper() pw = ''.join([choice(consonants) + choice(vowels) + choice(consonants + vowels) for _ in xrange(length // 3 + 1)])[:length] if add_numbers: n = length // 3 if n > 0: pw = pw[:-n] for _ in xrange(n): pw += choice('0123456789') if add_special_char: tmp = randrange(0, len(pw)) l1 = pw[:tmp] l2 = pw[tmp:] if max(len(l1), len(l2)) == len(l1): l1 = l1[:-1] else: l2 = l2[:-1] return l1 + choice('#$&%?!') + l2 return pw def gen_pwhash(password): """Return a the password encrypted in sha format with a random salt.""" if isinstance(password, unicode): password = password.encode('utf-8') salt = gen_salt(6) h = sha1() h.update(salt) h.update(password) return 'sha$%s$%s' % (salt, h.hexdigest()) def check_pwhash(pwhash, password): """Check a password against a given hash value. Since many forums save md5 passwords with no salt and it's technically impossible to convert this to an sha hash with a salt we use this to be able to check for plain passwords:: plain$$default md5 passwords without salt:: md5$$c21f969b5f03d33d43e04f8f136e7682 md5 passwords with salt:: md5$123456$7faa731e3365037d264ae6c2e3c7697e sha passwords:: sha$123456$118083bd04c79ab51944a9ef863efcd9c048dd9a Note that the integral passwd column in the table is only 60 chars long. If you have a very large salt or the plaintext password is too long it will be truncated. >>> check_pwhash('plain$$default', 'default') True >>> check_pwhash('sha$$5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', 'password') True >>> check_pwhash('sha$$5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', 'wrong') False >>> check_pwhash('md5$xyz$bcc27016b4fdceb2bd1b369d5dc46c3f', u'example') True >>> check_pwhash('sha$5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', 'password') False >>> check_pwhash('md42$xyz$bcc27016b4fdceb2bd1b369d5dc46c3f', 'example') False """ if isinstance(password, unicode): password = password.encode('utf-8') if pwhash.count('$') < 2: return False method, salt, hashval = pwhash.split('$', 2) if method == 'plain': return hashval == password elif method == 'md5': h = md5() elif method == 'sha': h = sha1() else: return False h.update(salt) h.update(password) return h.hexdigest() == hashval
bsd-3-clause
93013a602699b39ffde1fd9dda411f59
29.769697
81
0.623006
3.437373
false
false
false
false
mitsuhiko/zine
zine/database.py
1
14745
# -*- coding: utf-8 -*- """ zine.database ~~~~~~~~~~~~~ This module is a rather complex layer on top of SQLAlchemy. Basically you will never use the `zine.database` module except if you are a core developer, but always the high level :mod:`~zine.database.db` module which you can import from the :mod:`zine.api` module. :copyright: (c) 2010 by the Zine Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import re import os import sys import time from os import path from types import ModuleType from copy import deepcopy import sqlalchemy from sqlalchemy import orm from sqlalchemy.interfaces import ConnectionProxy from sqlalchemy.orm.interfaces import AttributeExtension from sqlalchemy.exc import ArgumentError from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine.url import make_url, URL from sqlalchemy.types import TypeDecorator from sqlalchemy.ext.associationproxy import association_proxy from werkzeug import url_decode from werkzeug.exceptions import NotFound from zine.utils import local_manager if sys.platform == 'win32': _timer = time.clock else: _timer = time.time _sqlite_re = re.compile(r'sqlite:(?:(?://(.*?))|memory)(?:\?(.*))?$') def get_engine(): """Return the active database engine (the database engine of the active application). If no application is enabled this has an undefined behavior. If you are not sure if the application is bound to the active thread, use :func:`~zine.application.get_application` and check it for `None`. The database engine is stored on the application object as `database_engine`. """ from zine.application import get_application return get_application().database_engine def create_engine(uri, relative_to=None, debug=False): """Create a new engine. This works a bit like SQLAlchemy's `create_engine` with the difference that it automaticaly set's MySQL engines to 'utf-8', and paths for SQLite are relative to the path provided as `relative_to`. Furthermore the engine is created with `convert_unicode` by default. """ # special case sqlite. We want nicer urls for that one. if uri.startswith('sqlite:'): match = _sqlite_re.match(uri) if match is None: raise ArgumentError('Could not parse rfc1738 URL') database, query = match.groups() if database is None: database = ':memory:' elif relative_to is not None: database = path.join(relative_to, database) if query: query = url_decode(query).to_dict() else: query = {} info = URL('sqlite', database=database, query=query) else: info = make_url(uri) # if mysql is the database engine and no connection encoding is # provided we set it to utf-8 if info.drivername == 'mysql': info.query.setdefault('charset', 'utf8') options = {'convert_unicode': True} # alternative pool sizes / recycle settings and more. These are # interpreter wide and not from the config for the following reasons: # # - system administrators can set it independently from the webserver # configuration via SetEnv and friends. # - this setting is deployment dependent should not affect a development # server for the same instance or a development shell for key in 'pool_size', 'pool_recycle', 'pool_timeout': value = os.environ.get('ZINE_DATABASE_' + key.upper()) if value is not None: options[key] = int(value) # if debugging is enabled, hook the ConnectionDebugProxy in if debug: options['proxy'] = ConnectionDebugProxy() return sqlalchemy.create_engine(info, **options) def secure_database_uri(uri): """Returns the database uri with confidental information stripped.""" obj = make_url(uri) if obj.password: obj.password = '***' return unicode(obj).replace(u':%2A%2A%2A@', u':***@', 1) def attribute_loaded(model, attribute): """Returns true if the attribute of the model was already loaded.""" # XXX: this works but it relys on a specific implementation in # SQLAlchemy. Figure out if SA provides a way to query that information. return attribute in model.__dict__ class ConnectionDebugProxy(ConnectionProxy): """Helps debugging the database.""" def cursor_execute(self, execute, cursor, statement, parameters, context, executemany): start = _timer() try: return execute(cursor, statement, parameters, context) finally: from zine.application import get_request from zine.utils.debug import find_calling_context request = get_request() if request is not None: request.queries.append((statement, parameters, start, _timer(), find_calling_context())) class ZEMLParserData(TypeDecorator): """Holds parser data. The implementation is rather ugly because it does not really compare the trees for performance reasons but only the dirty flags. This might change in future versions if there is some sort of support for this kind of hackery in SQLAlchemy or if we find a fast way to compare the trees. """ impl = sqlalchemy.LargeBinary def process_bind_param(self, value, dialect): if value is None: return from zine.utils.zeml import dump_parser_data return dump_parser_data(value) def process_result_value(self, value, dialect): from zine.utils.zeml import load_parser_data try: return load_parser_data(value) except ValueError: # Parser data invalid. Database corruption? from zine.i18n import _ from zine.utils import log log.exception(_(u'Error when loading parsed data from database. ' u'Maybe the database was manually edited and got ' u'corrupted? The system returned an empty value.')) return {} def copy_value(self, value): return deepcopy(value) def compare_values(self, x, y): return x is y def is_mutable(self): return False class Query(orm.Query): """Default query class.""" def lightweight(self, deferred=None, lazy=None): """Send a lightweight query which deferes some more expensive things such as comment queries or even text and parser data. """ args = map(db.lazyload, lazy or ()) + map(db.defer, deferred or ()) return self.options(*args) def first(self, raise_if_missing=False): """Return the first result of this `Query` or None if the result doesn't contain any rows. If `raise_if_missing` is set to `True` a `NotFound` exception is raised if no row is found. """ rv = orm.Query.first(self) if rv is None and raise_if_missing: raise NotFound() return rv session = orm.scoped_session(lambda: orm.create_session(get_engine(), autoflush=True, autocommit=False), local_manager.get_ident) def mapper(cls, *args, **kwargs): """Attaches a query and auto registers.""" if not hasattr(cls, 'query'): cls.query = session.query_property(Query) old_init = getattr(cls, '__init__', None) def register_init(self, *args, **kwargs): if old_init is not None: old_init(self, *args, **kwargs) session.add(self) cls.__init__ = register_init return orm.mapper(cls, *args, **kwargs) # configure a declarative base. This is unused in the code but makes it easier # for plugins to work with the database. class ModelBase(object): """Internal baseclass for `Model`.""" Model = declarative_base(name='Model', cls=ModelBase, mapper=mapper) ModelBase.query = session.query_property(Query) #: create a new module for all the database related functions and objects sys.modules['zine.database.db'] = db = ModuleType('db') key = value = mod = None for mod in sqlalchemy, orm: for key, value in mod.__dict__.iteritems(): if key in mod.__all__: setattr(db, key, value) del key, mod, value #: forward some session methods to the module as well for name in 'delete', 'flush', 'execute', 'begin', 'commit', 'rollback', \ 'refresh', 'expire', 'query_property': setattr(db, name, getattr(session, name)) # Some things changed names with SQLAlchemy 0.6.0 db.save = session.add db.clear = session.expunge_all #: and finally hook our own implementations of various objects in db.Model = Model db.Query = Query db.get_engine = get_engine db.create_engine = create_engine db.session = session db.ZEMLParserData = ZEMLParserData db.mapper = mapper db.basic_mapper = orm.mapper db.association_proxy = association_proxy db.attribute_loaded = attribute_loaded db.AttributeExtension = AttributeExtension #: called at the end of a request cleanup_session = session.remove #: metadata for the core tables and the core table definitions metadata = db.MetaData() schema_versions = db.Table('schema_versions', metadata, db.Column('repository_id', db.String(255), primary_key=True), db.Column('repository_path', db.Text), db.Column('version', db.Integer) ) users = db.Table('users', metadata, db.Column('user_id', db.Integer, primary_key=True), db.Column('username', db.String(30)), db.Column('real_name', db.String(180)), db.Column('display_name', db.String(180)), db.Column('description', db.Text), db.Column('extra', db.PickleType), db.Column('pw_hash', db.String(70)), db.Column('email', db.String(250)), db.Column('www', db.String(200)), db.Column('is_author', db.Boolean) ) groups = db.Table('groups', metadata, db.Column('group_id', db.Integer, primary_key=True), db.Column('name', db.String(30)) ) group_users = db.Table('group_users', metadata, db.Column('group_id', db.Integer, db.ForeignKey('groups.group_id')), db.Column('user_id', db.Integer, db.ForeignKey('users.user_id')) ) privileges = db.Table('privileges', metadata, db.Column('privilege_id', db.Integer, primary_key=True), db.Column('name', db.String(50), unique=True) ) user_privileges = db.Table('user_privileges', metadata, db.Column('user_id', db.Integer, db.ForeignKey('users.user_id')), db.Column('privilege_id', db.Integer, db.ForeignKey('privileges.privilege_id')) ) group_privileges = db.Table('group_privileges', metadata, db.Column('group_id', db.Integer, db.ForeignKey('groups.group_id')), db.Column('privilege_id', db.Integer, db.ForeignKey('privileges.privilege_id')) ) categories = db.Table('categories', metadata, db.Column('category_id', db.Integer, primary_key=True), db.Column('slug', db.String(50)), db.Column('name', db.String(50)), db.Column('description', db.Text) ) texts = db.Table('texts', metadata, db.Column('text_id', db.Integer, primary_key=True), db.Column('text', db.Text), db.Column('parser_data', db.ZEMLParserData), db.Column('extra', db.PickleType) ) posts = db.Table('posts', metadata, db.Column('post_id', db.Integer, primary_key=True), db.Column('pub_date', db.DateTime), db.Column('last_update', db.DateTime), db.Column('slug', db.String(200), index=True, nullable=False), db.Column('uid', db.String(250)), db.Column('title', db.String(150)), db.Column('text_id', db.Integer, db.ForeignKey('texts.text_id')), db.Column('author_id', db.Integer, db.ForeignKey('users.user_id')), db.Column('comments_enabled', db.Boolean), db.Column('comment_count', db.Integer, nullable=False, default=0), db.Column('pings_enabled', db.Boolean), db.Column('content_type', db.String(40), index=True), db.Column('status', db.Integer), ) post_links = db.Table('post_links', metadata, db.Column('link_id', db.Integer, primary_key=True), db.Column('post_id', db.Integer, db.ForeignKey('posts.post_id')), db.Column('href', db.String(250), nullable=False), db.Column('rel', db.String(250)), db.Column('type', db.String(100)), db.Column('hreflang', db.String(30)), db.Column('title', db.String(200)), db.Column('length', db.Integer) ) tags = db.Table('tags', metadata, db.Column('tag_id', db.Integer, primary_key=True), db.Column('slug', db.String(150), unique=True, nullable=False), db.Column('name', db.String(100), unique=True, nullable=False) ) post_categories = db.Table('post_categories', metadata, db.Column('post_id', db.Integer, db.ForeignKey('posts.post_id')), db.Column('category_id', db.Integer, db.ForeignKey('categories.category_id')) ) post_tags = db.Table('post_tags', metadata, db.Column('post_id', db.Integer, db.ForeignKey('posts.post_id')), db.Column('tag_id', db.Integer, db.ForeignKey('tags.tag_id')) ) comments = db.Table('comments', metadata, db.Column('comment_id', db.Integer, primary_key=True), db.Column('post_id', db.Integer, db.ForeignKey('posts.post_id')), db.Column('user_id', db.Integer, db.ForeignKey('users.user_id')), db.Column('author', db.String(160)), db.Column('email', db.String(250)), db.Column('www', db.String(200)), db.Column('text_id', db.Integer, db.ForeignKey('texts.text_id')), db.Column('is_pingback', db.Boolean, nullable=False), db.Column('parent_id', db.Integer, db.ForeignKey('comments.comment_id')), db.Column('pub_date', db.DateTime), db.Column('blocked_msg', db.String(250)), db.Column('submitter_ip', db.String(100)), db.Column('status', db.Integer, nullable=False) ) redirects = db.Table('redirects', metadata, db.Column('redirect_id', db.Integer, primary_key=True), db.Column('original', db.String(200), unique=True), db.Column('new', db.String(200)) ) notification_subscriptions = db.Table('notification_subscriptions', metadata, db.Column('subscription_id', db.Integer, primary_key=True), db.Column('user_id', db.Integer, db.ForeignKey('users.user_id')), db.Column('notification_system', db.String(50)), db.Column('notification_id', db.String(100)), db.UniqueConstraint('user_id', 'notification_system', 'notification_id') ) def init_database(engine): """This is called from the websetup which explains why it takes an engine and not a zine application. """ # XXX: consider using something like this for mysql: # cx = engine.connect() # cx.execute('set storage_engine=innodb') # metadata.create_all(cx) metadata.create_all(engine)
bsd-3-clause
3a39e4cc3d99af3b4c5713f38e0de227
35.139706
81
0.66158
3.724425
false
false
false
false
globocom/database-as-a-service
dbaas/logical/models.py
1
51081
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import simple_audit import logging import datetime import urllib from datetime import date, timedelta from django.db import models, transaction, Error from django.db.models.signals import pre_save, post_save, pre_delete from django.contrib.auth.models import User from django.dispatch import receiver from django.core.exceptions import ValidationError, ObjectDoesNotExist from django.utils.functional import cached_property from django.utils.html import format_html from django.utils.translation import ugettext_lazy as _ from django_extensions.db.fields.encrypted import EncryptedCharField from util import slugify, make_db_random_password from util.models import BaseModel from physical.models import DatabaseInfra, Environment from drivers import factory_for from system.models import Configuration from account.models import Team from drivers.base import DatabaseStatus from drivers.errors import ConnectionError from logical.validators import database_name_evironment_constraint from workflow.steps.util.zabbix import DisableAlarms, EnableAlarms from workflow.steps.util.db_monitor import DisableMonitoring, EnableMonitoring from notification.models import TaskHistory from util import get_credentials_for from util import get_or_none_credentials_for from dbaas_credentials.models import CredentialType from system.models import Configuration LOG = logging.getLogger(__name__) KB_FACTOR = 1.0 / 1024.0 MB_FACTOR = 1.0 / 1024.0 / 1024.0 GB_FACTOR = 1.0 / 1024.0 / 1024.0 / 1024.0 class Project(BaseModel): name = models.CharField( verbose_name=_("Project name"), max_length=100, unique=True) description = models.TextField( verbose_name=_("Description"), null=True, blank=True) is_active = models.BooleanField( verbose_name=_("Is project active"), default=True) slug = models.SlugField() def __unicode__(self): return "%s" % self.name class Meta: permissions = ( ("view_project", "Can view projects"), ) ordering = ['name'] class DatabaseAliveManager(models.Manager): def get_query_set(self): return Database.objects.filter(is_in_quarantine=False) class DatabaseHistory(models.Model): database_id = models.IntegerField(db_index=True) environment = models.CharField( verbose_name=_("environment"), max_length=20 ) engine = models.CharField( verbose_name=_("engine"), max_length=100 ) name = models.CharField( verbose_name=_("name"), max_length=200 ) project = models.CharField( verbose_name=_("project"), max_length=100 ) team = models.CharField( verbose_name=_("team"), max_length=100 ) databaseinfra_name = models.CharField( verbose_name=_("databaseinfra_name"), max_length=100 ) plan = models.CharField( verbose_name=_("plan"), max_length=100 ) disk_size_kb = models.PositiveIntegerField(verbose_name=_("Size KB")) has_persistence = models.BooleanField( verbose_name="Disk persistence", default=True ) created_at = models.DateTimeField( verbose_name=_("created_at")) deleted_at = models.DateTimeField( verbose_name=_("deleted_at"), auto_now_add=True) description = models.TextField( verbose_name=_("Description"), null=True, blank=True ) class Database(BaseModel): DEAD = 0 ALIVE = 1 INITIALIZING = 2 ALERT = 3 DB_STATUS = ( (DEAD, 'Dead'), (ALIVE, 'Alive'), (INITIALIZING, 'Initializing'), (ALERT, 'Alert') ) name = models.CharField( verbose_name=_("Database name"), max_length=100, db_index=True ) databaseinfra = models.ForeignKey( DatabaseInfra, related_name="databases", on_delete=models.PROTECT ) project = models.ForeignKey( Project, related_name="databases", on_delete=models.PROTECT, null=True, blank=True ) team = models.ForeignKey( Team, related_name="databases", null=True, blank=True, help_text=_("Team that is accountable for the database") ) is_in_quarantine = models.BooleanField( verbose_name=_("Is database in quarantine?"), default=False ) is_monitoring = models.BooleanField( verbose_name=_("Is database being monitored?"), default=True ) quarantine_dt = models.DateField( verbose_name=_("Quarantine date"), null=True, blank=True, editable=False ) description = models.TextField( verbose_name=_("Description"), null=True, blank=True ) status = models.IntegerField(choices=DB_STATUS, default=2) used_size_in_bytes = models.FloatField(default=0.0) environment = models.ForeignKey( Environment, related_name="databases", on_delete=models.PROTECT, db_index=True ) backup_path = models.CharField( verbose_name=_("Backup path"), max_length=300, null=True, blank=True, help_text=_("Full path to backup file") ) subscribe_to_email_events = models.BooleanField( verbose_name=_("Subscribe to email events"), default=True, help_text=_( "Check this box if you'd like to receive information " "regarding this database by email." ) ) disk_auto_resize = models.BooleanField( verbose_name=_("Disk auto resize"), default=True, help_text=_("When marked, the disk will be resized automatically.") ) is_protected = models.BooleanField( verbose_name=_("Protected"), default=False, help_text=_("When marked, the database can not be deleted.") ) quarantine_user = models.ForeignKey( User, related_name='databases_quarantine', null=True, blank=True, editable=False ) apps_bind_name = models.TextField( verbose_name=_("apps_bind_name"), null=True, blank=True ) def validate_unique(self, *args, **kwargs): ''' Validate if database name is unique in environemnt stage''' super(Database, self).validate_unique(*args, **kwargs) if not any([ hasattr(self, "environment"), hasattr(self, "name")]) or self.id: return environment = Environment.objects.filter(pk=self.environment_id) if not environment.exists(): return environment = environment[0] db_check = Database.objects.filter( name=self.name, environment__stage=environment.stage ) if db_check.exists(): raise ValidationError({ "name": [ "Name %s is alredy been used in the %s environment" % ( self.name, Environment.get_stage_by_id(self.environment.stage) ) ] }) def team_contact(self): if self.team: return self.team.emergency_contacts team_contact.short_description = 'Emergency contacts' objects = models.Manager() alive = DatabaseAliveManager() quarantine_time = Configuration.get_by_name_as_int( 'quarantine_retention_days' ) def __unicode__(self): return u"{}".format(self.name) class Meta: permissions = ( ("can_manage_quarantine_databases", "Can manage databases in quarantine"), ("view_database", "Can view databases"), ("upgrade_mongo24_to_30", "Can upgrade mongoDB version from 2.4 to 3.0"), ("upgrade_database", "Can upgrade databases"), ("configure_ssl", "Can configure SSL"), ) unique_together = ( ('name', 'environment'), ) ordering = ('name', ) @property def is_in_memory(self): return self.engine.engine_type.is_in_memory @property def has_persistence(self): return self.plan.has_persistence @property def has_persistense_equivalent_plan(self): if self.plan.persistense_equivalent_plan: return True return False @property def persistence_change_text(self): if self.has_persistence: return 'Change to Memory Only' return 'Change to Persisted' @property def infra(self): return self.databaseinfra @property def engine_type(self): return self.infra.engine_name @property def engine(self): return self.infra.engine @property def plan(self): return self.databaseinfra and self.databaseinfra.plan @property def has_cost_credential(self): return get_or_none_credentials_for( self.infra.environment, CredentialType.GCP_COST ) @property def gcp_log_credential(self): return get_or_none_credentials_for( self.environment, CredentialType.GCP_LOG ) def pin_task(self, task): try: with transaction.atomic(): DatabaseLock(database=self, task=task).save() except Error: return False else: return True @staticmethod def __clean_task(task_name): if task_name.endswith('_rollback'): return task_name.rsplit('_rollback', 1)[0] if task_name.endswith('_retry'): return task_name.rsplit('_retry', 1)[0] return task_name def update_task(self, task): lock = self.lock.first() if not lock: return self.pin_task(task) with transaction.atomic(): lock = DatabaseLock.objects.select_for_update().filter( database=self ).first() task_name = self.__clean_task(task.task_name) if '.' in task_name: task_name = task_name.split('.')[-1] lock_task_name = self.__clean_task(lock.task.task_name) if '.' in lock_task_name: lock_task_name = lock_task_name.split('.')[-1] if lock_task_name != task_name or not lock.task.is_status_error: return False lock.task = task lock.save() return True def finish_task(self): for instance in self.infra.instances.all(): try: instance.update_status() except Exception as e: LOG.error( "Could not refresh status for {} - {}".format(instance, e) ) continue try: self.update_status() except Exception as e: LOG.error("Could not refresh status for {} - {}".format(self, e)) self.unpin_task() def update_status(self): self.status = Database.DEAD if self.database_status and self.database_status.is_alive: self.status = Database.ALIVE instances_status = self.databaseinfra.check_instances_status() if instances_status == self.databaseinfra.ALERT: self.status = Database.ALERT self.save(update_fields=['status']) def unpin_task(self): DatabaseLock.objects.filter(database=self).delete() @property def current_locked_task(self): lock = self.lock.first() if lock: return lock.task @property def is_locked(self): lock = self.lock.first() if lock: return True return False def delete(self, *args, **kwargs): if self.is_in_quarantine: LOG.warning( "Database {} is in quarantine and will be removed".format( self.name ) ) for credential in self.credentials.all(): instance = factory_for(self.databaseinfra) instance.try_remove_user(credential) engine = self.databaseinfra.engine databaseinfra = self.databaseinfra try: DatabaseHistory.objects.create( database_id=self.id, name=self.name, description=self.description, engine='{} {}'.format( engine.engine_type.name, engine.version ), project=self.project.name if self.project else '', team=self.team.name if self.team else '', databaseinfra_name=databaseinfra.name, plan=databaseinfra.plan.name, disk_size_kb=databaseinfra.disk_offering.size_kb, has_persistence=databaseinfra.plan.has_persistence, environment=self.environment.name, created_at=self.created_at ) except Exception as err: LOG.error( ('Error on creating database history for ' '"database {}: {}'.format(self.id, err))) super(Database, self).delete(*args, **kwargs) else: LOG.warning("Putting database {} in quarantine".format(self.name)) self.is_in_quarantine = True self.is_protected = False self.save() if self.credentials.exists(): for credential in self.credentials.all(): new_password = make_db_random_password() new_credential = Credential.objects.get(pk=credential.id) new_credential.password = new_password new_credential.save() instance = factory_for(self.databaseinfra) instance.try_update_user(new_credential) def clean(self): if not self.pk: self.name = slugify(self.name) if self.name in self.__get_database_reserved_names(): raise ValidationError( _("{} is a reserved database name".format( self.name )) ) def automatic_create_first_credential(self): LOG.info("creating new credential for database {}".format(self.name)) user = Credential.USER_PATTERN % self.name credential = Credential.create_new_credential(user, self) return credential @classmethod def provision(cls, name, databaseinfra): if not isinstance(databaseinfra, DatabaseInfra): raise ValidationError( 'Invalid databaseinfra type {} - {}'.format( type(databaseinfra), databaseinfra ) ) database = Database() database.databaseinfra = databaseinfra database.environment = databaseinfra.environment database.name = name database.full_clean() database.save() database = Database.objects.get(pk=database.pk) return database def __get_database_reserved_names(self): return getattr(self.driver, 'RESERVED_DATABASES_NAME', []) @property def driver(self): if self.databaseinfra_id is not None: return self.databaseinfra.get_driver() def get_endpoint(self): return self.driver.get_connection(database=self) def get_endpoint_dns(self): return self.driver.get_connection_dns(database=self) def get_endpoint_dns_simple(self): return self.driver.get_connection_dns_simple(database=self) def __kibana_url(self): if self.databaseinfra.plan.is_pre_provisioned: return "" credential = get_credentials_for( environment=self.environment, credential_type=CredentialType.KIBANA_LOG ) search_field = credential.get_parameter_by_name('search_field') if not search_field: return "" time_query = "_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:now-6h,to:now))" filter_query = "_a=(columns:!(_source),filters:!(),interval:auto,query:(language:lucene,query:'{}:{}'))".format( search_field, self.name ) return "{}/app/kibana#/discover?{}&{}".format( credential.endpoint, time_query, filter_query ) def __gcp_log_url(self): from workflow.steps.util.base import HostProviderClient host_prov_client = HostProviderClient(self.environment) credential = self.gcp_log_credential vm_ids = host_prov_client.get_vm_ids(self.infra) search_filter = " OR ".join( ['resource.labels.instance_id="%s"' % x for x in vm_ids]) new_filter = '(resource.type="gce_instance") AND ({})'.format(search_filter) query = "query;query=%(search_filter)s;" % { "search_filter": urllib.quote(new_filter) } project = "?project={}".format(credential.get_parameter_by_name("project")) url = "{endpoint}/logs/{query}{project}".format( endpoint=credential.endpoint, query=query, project=project ) print('URL:', url) return url def get_log_url(self): if self.gcp_log_credential: return self.__gcp_log_url() else: return self.__kibana_url() def __activate_monitoring(self, instances): for instance in instances: EnableAlarms(instance).do() EnableMonitoring(instance).do() return def __deactivate_monitoring(self,instances): for instance in instances: DisableAlarms(instance).do() DisableMonitoring(instance).do() return def toggle_monitoring(self): instances = self.infra.get_driver().get_database_instances() if not self.is_monitoring: self.__activate_monitoring(instances) else: self.__deactivate_monitoring(instances) def get_chg_register_url(self): endpoint = Configuration.get_by_name('chg_register_url') url = "{endpoint}/chg_register/{database_name}".format( endpoint=endpoint, database_name=self.name ) print('URL:', url) return url def get_dex_url(self): if Configuration.get_by_name_as_int('dex_analyze') != 1: return "" if self.databaseinfra.plan.is_pre_provisioned: return "" if self.engine_type != 'mongodb': return "" return 1 def get_is_preprovisioned(self): return self.databaseinfra.plan.is_pre_provisioned endpoint = property(get_endpoint) endpoint_dns = property(get_endpoint_dns) @cached_property def database_status(self): try: info = self.databaseinfra.get_info() if info is None: return None database_status = info.get_database_status(self.name) if database_status is None: # try get without cache info = self.databaseinfra.get_info(force_refresh=True) database_status = info.get_database_status(self.name) except ConnectionError as e: msg = ("ConnectionError calling database_status for database {}:" "{}").format(self, e) LOG.error(msg) database_status = DatabaseStatus(self) return database_status def get_offering_name(self): LOG.info("Get offering") try: offer_name = self.infra.offering.name except Exception as e: LOG.info("Oops...{}".format(e)) offer_name = None return offer_name offering = property(get_offering_name) @property def total_size(self): return self.driver.masters_total_size_in_bytes @property def total_size_in_kb(self): return round(self.driver.masters_total_size_in_bytes * KB_FACTOR, 2) @property def total_size_in_mb(self): return round(self.driver.masters_total_size_in_bytes * MB_FACTOR, 2) @property def total_size_in_gb(self): return round(self.driver.masters_total_size_in_bytes * GB_FACTOR, 2) @property def used_size_in_kb(self): return self.driver.masters_used_size_in_bytes * KB_FACTOR @property def used_size_in_mb(self): return self.driver.masters_used_size_in_bytes * MB_FACTOR @property def used_size_in_gb(self): return self.driver.masters_used_size_in_bytes * GB_FACTOR @property def capacity(self): if self.status: return round( ((1.0 * self.used_size_in_bytes / self.total_size) if self.total_size else 0, 2)) @classmethod def purge_quarantine(self): quarantine_time = Configuration.get_by_name_as_int( 'quarantine_retention_days') quarantine_time_dt = date.today() - timedelta(days=quarantine_time) databases = Database.objects.filter( is_in_quarantine=True, quarantine_dt__lte=quarantine_time_dt ) for database in databases: database.delete() LOG.info( ("The database %s was deleted, because it was set to " "quarentine %d days ago") % (database.name, quarantine_time) ) @classmethod def clone(cls, database, clone_name, plan, environment, user): from notification.tasks import TaskRegister TaskRegister.database_clone( origin_database=database, clone_name=clone_name, plan=plan, environment=environment, user=user ) @classmethod def restore(cls, database, snapshot, user): from notification.tasks import TaskRegister LOG.info( ("Changing database volume with params: " "database {} snapshot: {}, user: {}").format( database, snapshot, user ) ) TaskRegister.restore_snapshot( database=database, snapshot=snapshot, user=user ) @classmethod def upgrade_disk_type(cls, database, disk_offering_type, user): from notification.tasks import TaskRegister LOG.info( ("Changing database volume with params: " "database {}, new_disk_type: {}, user: {}").format( database, disk_offering_type, user ) ) TaskRegister.upgrade_disk_type( database=database, new_disk_type_upgrade=disk_offering_type, user=user ) @classmethod def resize(cls, database, offering, user): from notification.tasks import TaskRegister TaskRegister.database_resize( database=database, user=user, offering=offering ) # @classmethod # def recover_snapshot(cls, database, snapshot, user, task_history): # from backup.tasks import restore_snapshot # # restore_snapshot.delay( # database=database, snapshot=snapshot, user=user, # task_history=task_history # ) def get_metrics_url(self): return "/admin/logical/database/{}/metrics/".format(self.id) def get_resize_retry_url(self): return "/admin/logical/database/{}/resize_retry/".format(self.id) def get_resize_rollback_url(self): return "/admin/logical/database/{}/resize_rollback/".format(self.id) def get_disk_resize_url(self): return "/admin/logical/database/{}/disk_resize/".format(self.id) def get_add_instances_database_retry_url(self): return "/admin/logical/database/{}/add_instances_database_retry/".format(self.id) def get_add_instances_database_rollback_url(self): return "/admin/logical/database/{}/add_instances_database_rollback/".format(self.id) def get_remove_instance_database_retry_url(self): return "/admin/logical/database/{}/remove_instance_database_retry/".format(self.id) def get_mongodb_engine_version_upgrade_url(self): return ("/admin/logical/database/{}/" "mongodb_engine_version_upgrade/").format(self.id) def get_upgrade_url(self): return "/admin/logical/database/{}/upgrade/".format(self.id) def get_upgrade_retry_url(self): return "/admin/logical/database/{}/upgrade_retry/".format(self.id) def get_migrate_engine_retry_url(self): return "/admin/logical/database/{}/migrate_engine_retry/".format(self.id) def get_upgrade_patch_url(self): return "/admin/logical/database/{}/upgrade_patch/".format(self.id) def get_upgrade_patch_retry_url(self): return "/admin/logical/database/{}/upgrade_patch_retry/".format( self.id ) def get_change_parameters_retry_url(self): return "/admin/logical/database/{}/change_parameters_retry/".format( self.id ) def get_reinstallvm_retry_url(self): return "/admin/logical/database/{}/reinstallvm_retry/".format(self.id) def get_recreateslave_retry_url(self): return "/admin/logical/database/{}/recreateslave_retry/".format( self.id ) def get_configure_ssl_url(self): return "/admin/logical/database/{}/configure_ssl/".format(self.id) def get_configure_ssl_retry_url(self): return "/admin/logical/database/{}/configure_ssl_retry/".format( self.id ) def get_set_ssl_required_url(self): return "/admin/logical/database/{}/set_ssl_required/".format(self.id) def get_set_ssl_required_retry_url(self): return "/admin/logical/database/{}/set_ssl_required_retry/".format( self.id ) def get_set_ssl_not_required_url(self): return "/admin/logical/database/{}/set_ssl_not_required/".format( self.id) def get_set_ssl_not_required_retry_url(self): return "/admin/logical/database/{}/set_ssl_not_required_retry/".format( self.id ) def get_change_persistence_url(self): return "/admin/logical/database/{}/change_persistence/".format(self.id) def get_change_persistence_retry_url(self): return "/admin/logical/database/{}/change_persistence_retry/".format( self.id ) def is_mongodb_24(self): engine = self.engine if engine.name == 'mongodb' and engine.version.startswith('2.4'): return True return False def get_offering_id(self): LOG.info("Get offering") try: offer_id = self.infra.plan.stronger_offering.id except Exception as e: LOG.info("Oops...{}".format(e)) offer_id = None return offer_id offering_id = property(get_offering_id) def is_being_used_elsewhere(self, skip_tasks=None): tasks = TaskHistory.objects.filter( task_status=TaskHistory.STATUS_WAITING, object_id=self.id, object_class=self._meta.db_table) if tasks: return True if not self.current_locked_task: return False skip_tasks = skip_tasks or [] if self.current_locked_task.task_name in skip_tasks: if self.current_locked_task.is_status_error: return False return True def restore_allowed(self): if Configuration.get_by_name_as_int('restore_allowed') == 1: return True return False def has_offerings(self): offerings = self.environment.offerings.exclude(id=self.offering_id) return bool(offerings) def has_disk_offerings(self): from physical.models import DiskOffering offerings = DiskOffering.objects.exclude( id=self.databaseinfra.disk_offering.id ) return bool(offerings) @property def can_modify_parameters(self): if self.plan.replication_topology.parameter.all(): return True else: return False @property def is_host_migrate_available(self): from util.providers import get_host_migrate_steps class_path = self.plan.replication_topology.class_path try: get_host_migrate_steps(class_path) except NotImplementedError: return False else: return True @property def is_dead(self): if self.status != Database.ALIVE: return True if self.database_status and not self.database_status.is_alive: return True return False @classmethod def disk_resize(cls, database, new_disk_offering, user): from physical.models import DiskOffering from notification.tasks import TaskRegister disk_offering = DiskOffering.objects.get(id=new_disk_offering) TaskRegister.database_disk_resize( database=database, user=user, disk_offering=disk_offering ) def update_host_disk_used_size(self, host_address, used_size_kb, total_size_kb=None): instance = self.databaseinfra.instances.filter( address=host_address ).first() if not instance: raise ObjectDoesNotExist() volume = instance.hostname.volumes.last() if not volume: return None if total_size_kb: volume.total_size_kb = total_size_kb volume.used_size_kb = used_size_kb volume.save(update_fields=['total_size_kb','used_size_kb']) return volume def can_be_cloned(self, database_view_button=False): if not self.plan.has_persistence: return False, "Database does not have persistence cannot be cloned" if self.is_being_used_elsewhere(): return False, "Database is being used by another task" if self.is_in_quarantine: return False, "Database in quarantine cannot be cloned" if database_view_button: if self.status != self.ALIVE: return False, "Database is not alive and cannot be cloned" else: if self.is_dead: return False, "Database is not alive and cannot be cloned" return True, None def can_be_restored(self): if not self.restore_allowed(): return False, ('Restore is not allowed. Please, contact DBaaS ' 'team for more information') if self.is_in_quarantine: return False, "Database in quarantine cannot be restored" if self.status != self.ALIVE or self.is_dead: return False, "Database is not alive and cannot be restored" if self.is_being_used_elsewhere(): return False, ("Database is being used by another task, please " "check your tasks") return True, None def can_be_disk_type_upgraded(self): if self.is_in_quarantine: return False, "Database in quarantine cannot be upgraded" if self.status != self.ALIVE or self.is_dead: return False, "Database is not alive and cannot be upgraded" if self.is_being_used_elsewhere(): return False, ("Database is being used by another task, please " "check your tasks") return True, None def can_be_deleted(self): error = None if self.is_protected and not self.is_in_quarantine: error = "Database {} is protected and cannot be deleted" # elif self.is_dead: # error = "Database {} is not alive and cannot be deleted" # elif self.is_being_used_elsewhere(): # error = "Database {} cannot be deleted because" \ # " it is in use by another task." if error: return False, error.format(self.name) return True, None def can_do_upgrade_retry(self): error = None if self.is_mongodb_24(): error = "MongoDB 2.4 cannot be upgraded by this task." elif self.is_in_quarantine: error = "Database in quarantine and cannot be upgraded." elif self.is_being_used_elsewhere([('notification.tasks' '.upgrade_database')]): error = "Database cannot be upgraded because " \ "it is in use by another task." elif not self.infra.plan.engine_equivalent_plan: error = "Source plan do not has equivalent plan to upgrade." if error: return False, error return True, None def can_do_upgrade(self): can_do_upgrade, error = self.can_do_upgrade_retry() if can_do_upgrade: if self.is_dead: error = "Database is dead and cannot be upgraded." elif self.is_being_used_elsewhere(): error = "Database cannot be upgraded because " \ "it is in use by another task." if error: return False, error return True, None def can_do_engine_migration(self, retry=False): error = None if self.is_in_quarantine: error = "Database in quarantine and cannot be upgraded." elif self.is_being_used_elsewhere([('notification.tasks' '.migrate_engine')]): error = "Database engine cannot be migrated because " \ "it is in use by another task." elif not retry and self.is_dead: error = "Database is dead and cannot be upgraded." elif not retry and self.is_being_used_elsewhere(): error = "Database engine cannot be migrated because " \ "it is in use by another task." if error: return False, error return True, None def can_do_upgrade_patch_retry(self): error = None if self.is_in_quarantine: error = "Database in quarantine and cannot be upgraded." elif self.is_being_used_elsewhere( ['notification.tasks.upgrade_database_patch'] ): error = "Database cannot be upgraded because " \ "it is in use by another task." if error: return False, error return True, None def can_do_upgrade_patch(self): can_do_upgrade, error = self.can_do_upgrade_patch_retry() if can_do_upgrade: if self.is_dead: error = "Database is dead and cannot be upgraded." elif self.is_being_used_elsewhere(): error = "Database cannot be upgraded because " \ "it is in use by another task." if error: return False, error return True, None def can_do_resize_retry(self): error = None if self.is_in_quarantine: error = "Database in quarantine and cannot be resized." elif not self.has_offerings: error = "There is no offerings for this database." elif self.is_being_used_elsewhere(['notification.tasks.resize_database', 'notification.tasks.resize_database_rollback']): error = "Database cannot be resized because" \ " it is in use by another task." if error: return False, error return True, None def can_do_resize(self): error = None if self.is_in_quarantine: error = "Database in quarantine and cannot be resized." elif not self.has_offerings: error = "There is no offerings for this database." elif self.is_dead: error = "Database is dead and cannot be resized." elif self.is_being_used_elsewhere(): error = "Database cannot be resized because" \ " it is in use by another task." if error: return False, error return True, None def can_do_change_parameters_retry(self): error = None if self.is_in_quarantine: error = ("Database in quarantine and cannot have the parameters " "changed.") elif self.is_being_used_elsewhere([('notification.tasks' '.change_parameters_database')]): error = "Database cannot have the parameters changed because" \ " it is in use by another task." if error: return False, error return True, None def can_do_change_parameters(self): error = None if self.is_in_quarantine: error = ("Database in quarantine and cannot have the parameters " "changed.") elif self.is_dead: error = "Database is dead and cannot have the parameters changed." elif self.is_being_used_elsewhere(): error = "Database cannot have the parameters changed because" \ " it is in use by another task." if error: return False, error return True, None def can_migrate_host(self): error = None if self.is_in_quarantine: error = "Database in quarantine and cannot have host migrate." elif self.is_dead: error = "Database is dead and cannot migrate host" elif self.is_being_used_elsewhere(): error = ("Database cannot migrate host it is in use " "by another task.") if error: return False, error return True, None def can_do_change_persistence_retry(self): error = None if self.is_in_quarantine: error = ("Database in quarantine and cannot have the persistence " "changed.") elif self.is_being_used_elsewhere([('notification.tasks' '.change_database_persistence')]): error = "Database cannot have the persistence changed because" \ " it is in use by another task." elif not self.has_persistense_equivalent_plan: error = "Database cannot have the persistence changed because" \ " it has not any persistense equivalent plan " if error: return False, error return True, None def can_do_change_persistence(self): error = None if self.is_in_quarantine: error = ("Database in quarantine and cannot have the persistence " "changed.") elif self.is_dead: error = "Database is dead and cannot have the persistence changed." elif self.is_being_used_elsewhere(): error = "Database cannot have the persistence changed because" \ " it is in use by another task." elif not self.has_persistense_equivalent_plan: error = "Database cannot have the persistence changed because" \ " it has not any persistense equivalent plan " if error: return False, error return True, None def can_do_disk_resize(self): error = None if self.is_in_quarantine: error = "Database in quarantine and cannot be resized." elif self.is_being_used_elsewhere(): error = "Database cannot be resized because" \ " it is in use by another task." elif not self.has_disk_offerings: error = "There is no other disk offering for this database." if error: return False, error return True, None def can_do_configure_ssl_retry(self): error = None if self.is_in_quarantine: error = "Database in quarantine and cannot have SSL cofigured." elif self.is_being_used_elsewhere([('notification.tasks' '.configure_ssl_database')]): error = "Database cannot have SSL cofigured because " \ "it is in use by another task." if error: return False, error return True, None def can_do_configure_ssl(self): can_do_configure_ssl, error = self.can_do_configure_ssl_retry() if can_do_configure_ssl: if self.is_dead: error = "Database is dead and cannot have SSL cofigured." elif self.is_being_used_elsewhere(): error = "Database cannot have SSL cofigured because " \ "it is in use by another task." if error: return False, error return True, None def can_do_set_ssl_required_retry(self): error = None if self.is_in_quarantine: error = "Database in quarantine and cannot have set SSL " \ "required." elif self.is_being_used_elsewhere([('notification.tasks' '.database_set_ssl_required')]): error = "Database cannot have set SSL required " \ "because it is in use by another task." if error: return False, error return True, None def can_do_set_ssl_required(self): can_do_set_ssl_required, error = self.can_do_set_ssl_required_retry() if can_do_set_ssl_required: if self.is_dead: error = "Database is dead and cannot have set SSL required." elif self.is_being_used_elsewhere(): error = "Database cannot have set SSL required " \ "because it is in use by another task." if error: return False, error return True, None def can_do_set_ssl_not_required_retry(self): error = None if self.is_in_quarantine: error = "Database in quarantine and cannot have set SSL not " \ "required." elif self.is_being_used_elsewhere( [('notification.tasks.database_set_ssl_not_required')]): error = "Database cannot have set SSL not required " \ "because it is in use by another task." if error: return False, error return True, None def can_do_set_ssl_not_required(self): can_do_ssl, error = self.can_do_set_ssl_not_required_retry() if can_do_ssl: if self.is_dead: error = "Database is dead and cannot have set SSL not " \ "required." elif self.is_being_used_elsewhere(): error = "Database cannot have set SSL not required " \ "because it is in use by another task." if error: return False, error return True, None def destroy(self, user): if not self.is_in_quarantine: self.delete() return if self.plan.provider != self.plan.CLOUDSTACK: self.delete() return LOG.debug( "call destroy_database - name={}, team={}, project={}, " "user={}".format(self.name, self.team, self.project, user) ) from notification.tasks import TaskRegister TaskRegister.database_destroy(database=self, user=user) return @property def last_successful_upgrade(self): from maintenance.models import DatabaseUpgrade return self.upgrades.filter(status=DatabaseUpgrade.SUCCESS).last() @property def status_html(self): html_default = '<span class="label label-{}">{}</span>' if self.status == Database.ALIVE: status = html_default.format("success", "Alive") elif self.status == Database.DEAD: status = html_default.format("important", "Dead") elif self.status == Database.ALERT: status = html_default.format("warning", "Alert") else: status = html_default.format("info", "Initializing") return format_html(status) @property def migrating_html(self): html_default = '&nbsp;<span class="label label-{}">{}</span>' if self.infra.migration_in_progress: status = html_default.format("info", "Migrating ({} of {})".format( self.infra.migration_stage, self.infra.total_stages_migration)) return format_html(status) return "" @property def organization(self): return self.team.organization class DatabaseLock(BaseModel): database = models.ForeignKey( Database, related_name="lock", unique=True ) task = models.ForeignKey( TaskHistory, related_name="lock" ) class Credential(BaseModel): USER_PATTERN = "u_%s" USER_MAXIMUM_LENGTH_NAME = 16 user = models.CharField(verbose_name=_("User name"), max_length=100) password = EncryptedCharField( verbose_name=_("User password"), max_length=255) database = models.ForeignKey(Database, related_name="credentials") force_ssl = models.BooleanField(default=False) OWNER = 'Owner' READ_WRITE = 'Read-Write' READ_ONLY = 'Read-Only' PRIVILEGES_CHOICES = { (OWNER, 'Owner'), (READ_WRITE, 'Read-Write'), (READ_ONLY, 'Read-Only'), } privileges = models.CharField(max_length=10, choices=PRIVILEGES_CHOICES, default=OWNER) def __unicode__(self): return u"%s" % self.user class Meta: permissions = ( ("view_credential", "Can view credentials"), ) unique_together = ( ('user', 'database'), ) ordering = ('database', 'user',) def clean(self): if len(self.user) > self.USER_MAXIMUM_LENGTH_NAME: raise ValidationError(_("%s is too long" % self.user)) @cached_property def driver(self): return self.database.databaseinfra.get_driver() def reset_password(self): """ Reset credential password to a new random password """ self.password = make_db_random_password() self.driver.update_user(self) self.save() @property def ssl_swap_label(self): if self.force_ssl: return "Disable SSL" else: return "Enable SSL" def swap_force_ssl(self): if self.force_ssl: self.force_ssl = False self.driver.set_user_not_require_ssl(self) self.save() else: self.force_ssl = True self.driver.set_user_require_ssl(self) self.save() @classmethod def create_new_credential(cls, user, database, privileges="Owner"): credential = Credential() credential.database = database credential.user = user[:cls.USER_MAXIMUM_LENGTH_NAME] credential.user = slugify(credential.user) credential.password = make_db_random_password() credential.privileges = privileges credential.full_clean() credential.driver.create_user(credential) credential.save() return credential def delete(self, *args, **kwargs): self.driver.remove_user(self) LOG.info('User removed from driver') super(Credential, self).delete(*args, **kwargs) # # SIGNALS # @receiver(pre_delete, sender=Database) def database_pre_delete(sender, **kwargs): """ database pre delete signal. Removes database from the engine """ database = kwargs.get("instance") LOG.debug("database pre-delete triggered") engine = factory_for(database.databaseinfra) engine.try_remove_database(database) @receiver(post_save, sender=Database, dispatch_uid="database_drive_credentials") def database_post_save(sender, **kwargs): """ Database post save signal. Creates the database in the driver and creates a new credential. """ database = kwargs.get("instance") is_new = kwargs.get("created") LOG.debug("database post-save triggered") if is_new and database.engine_type != 'redis': LOG.info( ("a new database (%s) were created... " "provision it in the engine" % ( database.name)) ) engine = factory_for(database.databaseinfra) engine.create_database(database) database.automatic_create_first_credential() @receiver(pre_save, sender=Database) def database_pre_save(sender, **kwargs): from notification.tasks import TaskRegister database = kwargs.get('instance') if database.is_in_quarantine: if database.quarantine_dt is None: database.quarantine_dt = datetime.datetime.now().date() if not database.quarantine_user: from dbaas.middleware import UserMiddleware database.quarantine_user = UserMiddleware.current_user() else: database.quarantine_dt = None database.quarantine_user = None if database.id: saved_object = Database.objects.get(id=database.id) if database.name != saved_object.name: raise AttributeError(_("Attribute name cannot be edited")) if database.team and saved_object.team: if database.team.organization != saved_object.team.organization: TaskRegister.update_organization_name_monitoring( database=database, organization_name=database.team.organization.name) if saved_object.team.external: TaskRegister.update_database_monitoring( database=database, hostgroup=(saved_object.team.organization .grafana_hostgroup), action='remove') if database.team.external: TaskRegister.update_database_monitoring( database=database, hostgroup=database.team.organization.grafana_hostgroup, action='add') else: # new database if database_name_evironment_constraint( database.name, database.environment.name): raise AttributeError( _('%s already exists in production!') % database.name ) LOG.debug("slugfying database's name for %s" % database.name) database.name = slugify(database.name) @receiver(pre_save, sender=Credential) def credential_pre_save(sender, **kwargs): credential = kwargs.get('instance') if credential.id: saved_object = Credential.objects.get(id=credential.id) if credential.user != saved_object.user: raise AttributeError(_("Attribute user cannot be edited")) if credential.database != saved_object.database: raise AttributeError(_("Attribute database cannot be edited")) @receiver(pre_save, sender=Project) def project_pre_save(sender, **kwargs): instance = kwargs.get('instance') instance.slug = slugify(instance.name) class NoDatabaseInfraCapacity(Exception): """ There isn't databaseinfra capable to support a new database with this plan """ pass simple_audit.register(Project, Database, Credential)
bsd-3-clause
55527fe57ab2d2fc5d87735de3592982
32.561761
129
0.590963
4.235923
false
false
false
false
globocom/database-as-a-service
dbaas/physical/migrations/0097_auto__add_field_script_configure_log.py
1
27134
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Script.configure_log' db.add_column(u'physical_script', 'configure_log', self.gf('django.db.models.fields.CharField')(max_length=300, null=True, blank=True), keep_default=False) db.execute( "update physical_script set configure_log = 'rsyslog_config.sh';COMMIT;") def backwards(self, orm): # Deleting field 'Script.configure_log' db.delete_column(u'physical_script', 'configure_log') models = { u'physical.cloud': { 'Meta': {'object_name': 'Cloud'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.databaseinfra': { 'Meta': {'object_name': 'DatabaseInfra'}, 'backup_hour': ('django.db.models.fields.IntegerField', [], {}), 'capacity': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'endpoint': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'endpoint_dns': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Engine']"}), 'engine_patch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EnginePatch']"}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_vm_created': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'maintenance_day': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'maintenance_window': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'name_prefix': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'name_stamp': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'blank': 'True'}), 'per_database_size_mbytes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Plan']"}), 'ssl_configured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'ssl_mode': ('django.db.models.fields.IntegerField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, u'physical.databaseinfraparameter': { 'Meta': {'unique_together': "((u'databaseinfra', u'parameter'),)", 'object_name': 'DatabaseInfraParameter'}, 'applied_on_database': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_value': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.DatabaseInfra']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'parameter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Parameter']"}), 'reset_default_value': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'physical.diskoffering': { 'Meta': {'object_name': 'DiskOffering'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'size_kb': ('django.db.models.fields.PositiveIntegerField', [], {}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.engine': { 'Meta': {'ordering': "(u'engine_type__name', u'version')", 'unique_together': "((u'version', u'engine_type'),)", 'object_name': 'Engine'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'engines'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), 'engine_upgrade_option': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_engine'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Engine']"}), 'has_users': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'major_version': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'minor_version': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'read_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}), 'template_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user_data_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'write_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}) }, u'physical.enginepatch': { 'Meta': {'object_name': 'EnginePatch'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'patchs'", 'to': u"orm['physical.Engine']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_initial_patch': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'patch_path': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '200', 'null': 'True', 'blank': 'True'}), 'patch_version': ('django.db.models.fields.PositiveIntegerField', [], {}), 'required_disk_size_gb': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.enginetype': { 'Meta': {'ordering': "(u'name',)", 'object_name': 'EngineType'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_memory': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.environment': { 'Meta': {'object_name': 'Environment'}, 'cloud': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'environment_cloud'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Cloud']"}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'migrate_environment': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Environment']"}), 'min_of_zones': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.environmentgroup': { 'Meta': {'object_name': 'EnvironmentGroup'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'groups'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.host': { 'Meta': {'object_name': 'Host'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'future_host': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Host']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255'}), 'monitor_url': ('django.db.models.fields.URLField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'offering': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Offering']", 'null': 'True'}), 'os_description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'null': 'True', 'blank': 'True'}), 'root_size_gb': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'ssl_expire_at': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }, u'physical.instance': { 'Meta': {'unique_together': "((u'address', u'port'),)", 'object_name': 'Instance'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.DatabaseInfra']"}), 'dns': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'future_instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Instance']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.Host']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance_type': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'port': ('django.db.models.fields.IntegerField', [], {}), 'read_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'shard': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'total_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, u'physical.offering': { 'Meta': {'object_name': 'Offering'}, 'cpus': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'offerings'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'memory_size_mb': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.parameter': { 'Meta': {'ordering': "(u'engine_type__name', u'name')", 'unique_together': "((u'name', u'engine_type'),)", 'object_name': 'Parameter'}, 'allowed_values': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '200', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'custom_method': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'dynamic': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'enginetype'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter_type': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.plan': { 'Meta': {'object_name': 'Plan'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'plans'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'plans'", 'to': u"orm['physical.Engine']"}), 'engine_equivalent_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_plan'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'plans'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), 'has_persistence': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_ha': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'max_db_size': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'migrate_engine_equivalent_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_engine_plan'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'migrate_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Plan']"}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'persistense_equivalent_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_persisted_plan'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'provider': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'replication_topology': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'replication_topology'", 'null': 'True', 'to': u"orm['physical.ReplicationTopology']"}), 'stronger_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'main_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'weaker_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'weaker_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}) }, u'physical.planattribute': { 'Meta': {'object_name': 'PlanAttribute'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'plan_attributes'", 'to': u"orm['physical.Plan']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'physical.replicationtopology': { 'Meta': {'object_name': 'ReplicationTopology'}, 'can_change_parameters': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_clone_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_recreate_slave': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_reinstall_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_resize_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_setup_ssl': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_switch_master': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_upgrade_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'class_path': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'details': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'replication_topologies'", 'symmetrical': 'False', 'to': u"orm['physical.Engine']"}), 'has_horizontal_scalability': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'replication_topologies'", 'blank': 'True', 'to': u"orm['physical.Parameter']"}), 'script': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'replication_topologies'", 'null': 'True', 'to': u"orm['physical.Script']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.script': { 'Meta': {'object_name': 'Script'}, 'configuration': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'configure_log': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'initialization': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'metric_collector': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'start_database': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'start_replication': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.topologyparametercustomvalue': { 'Meta': {'unique_together': "((u'topology', u'parameter'),)", 'object_name': 'TopologyParameterCustomValue'}, 'attr_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'parameter': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'topology_custom_values'", 'to': u"orm['physical.Parameter']"}), 'topology': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'param_custom_values'", 'to': u"orm['physical.ReplicationTopology']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.vip': { 'Meta': {'object_name': 'Vip'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'infra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'vips'", 'to': u"orm['physical.DatabaseInfra']"}), 'original_vip': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Vip']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.volume': { 'Meta': {'object_name': 'Volume'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'host': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'volumes'", 'to': u"orm['physical.Host']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'total_size_kb': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_kb': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) } } complete_apps = ['physical']
bsd-3-clause
ed8c66f307f3eaf3dad285a286ffc085
92.568966
239
0.563831
3.565103
false
false
false
false
globocom/database-as-a-service
dbaas/tsuru/views/getServiceStatus.py
1
1640
from rest_framework.views import APIView from rest_framework.renderers import JSONRenderer, JSONPRenderer from rest_framework.response import Response from rest_framework import status from logical.models import Database from notification.models import TaskHistory from ..utils import get_url_env, get_database, LOG from django.db.models import Q class GetServiceStatus(APIView): renderer_classes = (JSONRenderer, JSONPRenderer) model = Database def get(self, request, database_name, format=None): env = get_url_env(request) LOG.info("Database name {}. Environment {}".format( database_name, env) ) try: database = get_database(database_name, env) database_status = database.status except IndexError as e: database_status = 0 LOG.warn( "There is not a database with this {} name on {}. {}".format( database_name, env, e ) ) LOG.info("Status = {}".format(database_status)) task = TaskHistory.objects.filter( Q(arguments__contains=database_name) & Q(arguments__contains=env), task_status="RUNNING" ).order_by("created_at") LOG.info("Task {}".format(task)) if database_status == Database.ALIVE: database_status = status.HTTP_204_NO_CONTENT elif database_status == Database.DEAD and not task: database_status = status.HTTP_500_INTERNAL_SERVER_ERROR else: database_status = status.HTTP_202_ACCEPTED return Response(status=database_status)
bsd-3-clause
d7d96f90253000a6bc5f9ab75b44446e
34.673913
77
0.630488
4.350133
false
false
false
false
globocom/database-as-a-service
dbaas/logical/migrations/0009_auto__del_field_database_group__add_field_database_team.py
1
12359
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Database.group' db.delete_column(u'logical_database', 'group_id') # Adding field 'Database.team' db.add_column(u'logical_database', 'team', self.gf('django.db.models.fields.related.ForeignKey')( blank=True, related_name=u'databases', null=True, to=orm['account.Team']), keep_default=False) def backwards(self, orm): # Adding field 'Database.group' db.add_column(u'logical_database', 'group', self.gf('django.db.models.fields.related.ForeignKey')( related_name=u'databases', null=True, to=orm['auth.Group'], blank=True), keep_default=False) # Deleting field 'Database.team' db.delete_column(u'logical_database', 'team_id') models = { u'account.team': { 'Meta': {'object_name': 'Team'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'role': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.Group']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.User']", 'symmetrical': 'False'}) }, u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'logical.credential': { 'Meta': {'ordering': "(u'database', u'user')", 'unique_together': "((u'user', u'database'),)", 'object_name': 'Credential'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'credentials'", 'to': u"orm['logical.Database']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'logical.database': { 'Meta': {'ordering': "(u'databaseinfra', u'name')", 'unique_together': "((u'name', u'databaseinfra'),)", 'object_name': 'Database'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DatabaseInfra']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_quarantine': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['logical.Project']"}), 'quarantine_dt': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'team': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases'", 'null': 'True', 'to': u"orm['account.Team']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'logical.project': { 'Meta': {'object_name': 'Project'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.databaseinfra': { 'Meta': {'object_name': 'DatabaseInfra'}, 'capacity': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Engine']"}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'blank': 'True'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Plan']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, u'physical.engine': { 'Meta': {'unique_together': "((u'version', u'engine_type'),)", 'object_name': 'Engine'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'engines'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'template_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user_data_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'physical.enginetype': { 'Meta': {'object_name': 'EngineType'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.environment': { 'Meta': {'object_name': 'Environment'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.plan': { 'Meta': {'object_name': 'Plan'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'plans'", 'to': u"orm['physical.EngineType']"}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['physical.Environment']", 'symmetrical': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_default': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) } } complete_apps = ['logical']
bsd-3-clause
e1bd0e4b8f90d41afeb94102dbec1ab4
77.221519
205
0.553281
3.612686
false
false
false
false
globocom/database-as-a-service
dbaas/maintenance/admin/remove_instance_database.py
1
1160
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.utils.html import format_html from .database_maintenance_task import DatabaseMaintenanceTaskAdmin class RemoveInstanceDatabaseAdmin(DatabaseMaintenanceTaskAdmin): list_filter = [ "database__team", "current_step", "instance", "status", ] list_display = ( "database", "database_team", "instance", "current_step", "friendly_status", "maintenance_action", "link_task", "started_at", "finished_at" ) readonly_fields = ( "current_step_class", "database", "instance", "link_task", "started_at", "finished_at", "current_step", "status", "maintenance_action", "task_schedule" ) def maintenance_action(self, maintenance_task): if (not maintenance_task.is_status_error or not maintenance_task.can_do_retry): return 'N/A' url = maintenance_task.database.get_remove_instance_database_retry_url() html = ("<a title='Retry' class='btn btn-info' " "href='{}'>Retry</a>").format(url) return format_html(html)
bsd-3-clause
28636fc56fa3da5570f1534da68b0fd3
33.117647
80
0.623276
3.828383
false
false
false
false
globocom/database-as-a-service
dbaas/physical/migrations/0041_auto__del_field_plan_flipperfox_equivalent_plan.py
1
13264
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Plan.flipperfox_equivalent_plan' db.delete_column(u'physical_plan', 'flipperfox_equivalent_plan_id') def backwards(self, orm): # Adding field 'Plan.flipperfox_equivalent_plan' db.add_column(u'physical_plan', 'flipperfox_equivalent_plan', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'flipperfox_migration_plan', null=True, to=orm['physical.Plan'], on_delete=models.SET_NULL, blank=True), keep_default=False) models = { u'physical.databaseinfra': { 'Meta': {'object_name': 'DatabaseInfra'}, 'capacity': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'endpoint': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'endpoint_dns': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Engine']"}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_vm_created': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'name_prefix': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'name_stamp': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'blank': 'True'}), 'per_database_size_mbytes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Plan']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, u'physical.diskoffering': { 'Meta': {'object_name': 'DiskOffering'}, 'available_size_kb': ('django.db.models.fields.PositiveIntegerField', [], {}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'size_kb': ('django.db.models.fields.PositiveIntegerField', [], {}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.engine': { 'Meta': {'ordering': "(u'engine_type__name', u'version')", 'unique_together': "((u'version', u'engine_type'),)", 'object_name': 'Engine'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'engines'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), 'engine_upgrade_option': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_engine'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Engine']"}), 'has_users': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'read_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}), 'template_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user_data_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'write_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}) }, u'physical.enginetype': { 'Meta': {'ordering': "(u'name',)", 'object_name': 'EngineType'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_memory': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.environment': { 'Meta': {'object_name': 'Environment'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'min_of_zones': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.host': { 'Meta': {'object_name': 'Host'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'future_host': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Host']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'monitor_url': ('django.db.models.fields.URLField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'os_description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.instance': { 'Meta': {'unique_together': "((u'address', u'port'),)", 'object_name': 'Instance'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.DatabaseInfra']"}), 'dns': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'future_instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Instance']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.Host']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance_type': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'port': ('django.db.models.fields.IntegerField', [], {}), 'read_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.plan': { 'Meta': {'object_name': 'Plan'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'plans'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'plans'", 'to': u"orm['physical.Engine']"}), 'engine_equivalent_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_plan'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'plans'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), 'has_persistence': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_ha': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'max_db_size': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'provider': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'replication_topology': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'replication_topology'", 'null': 'True', 'to': u"orm['physical.ReplicationTopology']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.planattribute': { 'Meta': {'object_name': 'PlanAttribute'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'plan_attributes'", 'to': u"orm['physical.Plan']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'physical.replicationtopology': { 'Meta': {'object_name': 'ReplicationTopology'}, 'class_path': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'details': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'replication_topologies'", 'symmetrical': 'False', 'to': u"orm['physical.Engine']"}), 'has_horizontal_scalability': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) } } complete_apps = ['physical']
bsd-3-clause
5ad779c4037da2d00b2b19eead203a99
86.847682
227
0.565365
3.556032
false
false
false
false