gt
stringclasses 1
value | context
stringlengths 2.49k
119k
|
---|---|
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
"""PTransform and descendants.
A PTransform is an object describing (not executing) a computation. The actual
execution semantics for a transform is captured by a runner object. A transform
object always belongs to a pipeline object.
A PTransform derived class needs to define the expand() method that describes
how one or more PValues are created by the transform.
The module defines a few standard transforms: FlatMap (parallel do),
GroupByKey (group by key), etc. Note that the expand() methods for these
classes contain code that will add nodes to the processing graph associated
with a pipeline.
As support for the FlatMap transform, the module also defines a DoFn
class and wrapper class that allows lambda functions to be used as
FlatMap processing functions.
"""
from __future__ import absolute_import
import copy
import inspect
import operator
import os
import sys
from functools import reduce
from google.protobuf import wrappers_pb2
from apache_beam import error
from apache_beam import pvalue
from apache_beam.internal import pickler
from apache_beam.internal import util
from apache_beam.transforms.display import DisplayDataItem
from apache_beam.transforms.display import HasDisplayData
from apache_beam.typehints import typehints
from apache_beam.typehints.decorators import TypeCheckError
from apache_beam.typehints.decorators import WithTypeHints
from apache_beam.typehints.decorators import getcallargs_forhints
from apache_beam.typehints.trivial_inference import instance_to_type
from apache_beam.typehints.typehints import validate_composite_type_param
from apache_beam.utils import proto_utils
from apache_beam.utils import urns
__all__ = [
'PTransform',
'ptransform_fn',
'label_from_callable',
]
class _PValueishTransform(object):
"""Visitor for PValueish objects.
A PValueish is a PValue, or list, tuple, dict of PValuesish objects.
This visits a PValueish, contstructing a (possibly mutated) copy.
"""
def visit_nested(self, node, *args):
if isinstance(node, (tuple, list)):
args = [self.visit(x, *args) for x in node]
if isinstance(node, tuple) and hasattr(node.__class__, '_make'):
# namedtuples require unpacked arguments in their constructor
return node.__class__(*args)
else:
return node.__class__(args)
elif isinstance(node, dict):
return node.__class__(
{key: self.visit(value, *args) for (key, value) in node.items()})
else:
return node
class _SetInputPValues(_PValueishTransform):
def visit(self, node, replacements):
if id(node) in replacements:
return replacements[id(node)]
else:
return self.visit_nested(node, replacements)
class _MaterializedDoOutputsTuple(pvalue.DoOutputsTuple):
def __init__(self, deferred, pvalue_cache):
super(_MaterializedDoOutputsTuple, self).__init__(
None, None, deferred._tags, deferred._main_tag)
self._deferred = deferred
self._pvalue_cache = pvalue_cache
def __getitem__(self, tag):
# Simply accessing the value should not use it up.
return self._pvalue_cache.get_unwindowed_pvalue(
self._deferred[tag], decref=False)
class _MaterializePValues(_PValueishTransform):
def __init__(self, pvalue_cache):
self._pvalue_cache = pvalue_cache
def visit(self, node):
if isinstance(node, pvalue.PValue):
# Simply accessing the value should not use it up.
return self._pvalue_cache.get_unwindowed_pvalue(node, decref=False)
elif isinstance(node, pvalue.DoOutputsTuple):
return _MaterializedDoOutputsTuple(node, self._pvalue_cache)
else:
return self.visit_nested(node)
class _GetPValues(_PValueishTransform):
def visit(self, node, pvalues):
if isinstance(node, (pvalue.PValue, pvalue.DoOutputsTuple)):
pvalues.append(node)
else:
self.visit_nested(node, pvalues)
def get_nested_pvalues(pvalueish):
pvalues = []
_GetPValues().visit(pvalueish, pvalues)
return pvalues
class _ZipPValues(object):
"""Pairs each PValue in a pvalueish with a value in a parallel out sibling.
Sibling should have the same nested structure as pvalueish. Leaves in
sibling are expanded across nested pvalueish lists, tuples, and dicts.
For example
ZipPValues().visit({'a': pc1, 'b': (pc2, pc3)},
{'a': 'A', 'b', 'B'})
will return
[('a', pc1, 'A'), ('b', pc2, 'B'), ('b', pc3, 'B')]
"""
def visit(self, pvalueish, sibling, pairs=None, context=None):
if pairs is None:
pairs = []
self.visit(pvalueish, sibling, pairs, context)
return pairs
elif isinstance(pvalueish, (pvalue.PValue, pvalue.DoOutputsTuple)):
pairs.append((context, pvalueish, sibling))
elif isinstance(pvalueish, (list, tuple)):
self.visit_sequence(pvalueish, sibling, pairs, context)
elif isinstance(pvalueish, dict):
self.visit_dict(pvalueish, sibling, pairs, context)
def visit_sequence(self, pvalueish, sibling, pairs, context):
if isinstance(sibling, (list, tuple)):
for ix, (p, s) in enumerate(zip(
pvalueish, list(sibling) + [None] * len(pvalueish))):
self.visit(p, s, pairs, 'position %s' % ix)
else:
for p in pvalueish:
self.visit(p, sibling, pairs, context)
def visit_dict(self, pvalueish, sibling, pairs, context):
if isinstance(sibling, dict):
for key, p in pvalueish.items():
self.visit(p, sibling.get(key), pairs, key)
else:
for p in pvalueish.values():
self.visit(p, sibling, pairs, context)
class PTransform(WithTypeHints, HasDisplayData):
"""A transform object used to modify one or more PCollections.
Subclasses must define an expand() method that will be used when the transform
is applied to some arguments. Typical usage pattern will be:
input | CustomTransform(...)
The expand() method of the CustomTransform object passed in will be called
with input as an argument.
"""
# By default, transforms don't have any side inputs.
side_inputs = ()
# Used for nullary transforms.
pipeline = None
# Default is unset.
_user_label = None
def __init__(self, label=None):
super(PTransform, self).__init__()
self.label = label
@property
def label(self):
return self._user_label or self.default_label()
@label.setter
def label(self, value):
self._user_label = value
def default_label(self):
return self.__class__.__name__
def with_input_types(self, input_type_hint):
"""Annotates the input type of a :class:`PTransform` with a type-hint.
Args:
input_type_hint (type): An instance of an allowed built-in type, a custom
class, or an instance of a
:class:`~apache_beam.typehints.typehints.TypeConstraint`.
Raises:
~exceptions.TypeError: If **input_type_hint** is not a valid type-hint.
See
:obj:`apache_beam.typehints.typehints.validate_composite_type_param()`
for further details.
Returns:
PTransform: A reference to the instance of this particular
:class:`PTransform` object. This allows chaining type-hinting related
methods.
"""
validate_composite_type_param(input_type_hint,
'Type hints for a PTransform')
return super(PTransform, self).with_input_types(input_type_hint)
def with_output_types(self, type_hint):
"""Annotates the output type of a :class:`PTransform` with a type-hint.
Args:
type_hint (type): An instance of an allowed built-in type, a custom class,
or a :class:`~apache_beam.typehints.typehints.TypeConstraint`.
Raises:
~exceptions.TypeError: If **type_hint** is not a valid type-hint. See
:obj:`~apache_beam.typehints.typehints.validate_composite_type_param()`
for further details.
Returns:
PTransform: A reference to the instance of this particular
:class:`PTransform` object. This allows chaining type-hinting related
methods.
"""
validate_composite_type_param(type_hint, 'Type hints for a PTransform')
return super(PTransform, self).with_output_types(type_hint)
def type_check_inputs(self, pvalueish):
self.type_check_inputs_or_outputs(pvalueish, 'input')
def infer_output_type(self, unused_input_type):
return self.get_type_hints().simple_output_type(self.label) or typehints.Any
def type_check_outputs(self, pvalueish):
self.type_check_inputs_or_outputs(pvalueish, 'output')
def type_check_inputs_or_outputs(self, pvalueish, input_or_output):
hints = getattr(self.get_type_hints(), input_or_output + '_types')
if not hints:
return
arg_hints, kwarg_hints = hints
if arg_hints and kwarg_hints:
raise TypeCheckError(
'PTransform cannot have both positional and keyword type hints '
'without overriding %s._type_check_%s()' % (
self.__class__, input_or_output))
root_hint = (
arg_hints[0] if len(arg_hints) == 1 else arg_hints or kwarg_hints)
for context, pvalue_, hint in _ZipPValues().visit(pvalueish, root_hint):
if pvalue_.element_type is None:
# TODO(robertwb): It's a bug that we ever get here. (typecheck)
continue
if hint and not typehints.is_consistent_with(pvalue_.element_type, hint):
at_context = ' %s %s' % (input_or_output, context) if context else ''
raise TypeCheckError(
'%s type hint violation at %s%s: expected %s, got %s' % (
input_or_output.title(), self.label, at_context, hint,
pvalue_.element_type))
def _infer_output_coder(self, input_type=None, input_coder=None):
"""Returns the output coder to use for output of this transform.
Note: this API is experimental and is subject to change; please do not rely
on behavior induced by this method.
The Coder returned here should not be wrapped in a WindowedValueCoder
wrapper.
Args:
input_type: An instance of an allowed built-in type, a custom class, or a
typehints.TypeConstraint for the input type, or None if not available.
input_coder: Coder object for encoding input to this PTransform, or None
if not available.
Returns:
Coder object for encoding output of this PTransform or None if unknown.
"""
# TODO(ccy): further refine this API.
return None
def _clone(self, new_label):
"""Clones the current transform instance under a new label."""
transform = copy.copy(self)
transform.label = new_label
return transform
def expand(self, input_or_inputs):
raise NotImplementedError
def __str__(self):
return '<%s>' % self._str_internal()
def __repr__(self):
return '<%s at %s>' % (self._str_internal(), hex(id(self)))
def _str_internal(self):
return '%s(PTransform)%s%s%s' % (
self.__class__.__name__,
' label=[%s]' % self.label if (hasattr(self, 'label') and
self.label) else '',
' inputs=%s' % str(self.inputs) if (hasattr(self, 'inputs') and
self.inputs) else '',
' side_inputs=%s' % str(self.side_inputs) if self.side_inputs else '')
def _check_pcollection(self, pcoll):
if not isinstance(pcoll, pvalue.PCollection):
raise error.TransformError('Expecting a PCollection argument.')
if not pcoll.pipeline:
raise error.TransformError('PCollection not part of a pipeline.')
def get_windowing(self, inputs):
"""Returns the window function to be associated with transform's output.
By default most transforms just return the windowing function associated
with the input PCollection (or the first input if several).
"""
# TODO(robertwb): Assert all input WindowFns compatible.
return inputs[0].windowing
def __rrshift__(self, label):
return _NamedPTransform(self, label)
def __or__(self, right):
"""Used to compose PTransforms, e.g., ptransform1 | ptransform2."""
if isinstance(right, PTransform):
return _ChainedPTransform(self, right)
return NotImplemented
def __ror__(self, left, label=None):
"""Used to apply this PTransform to non-PValues, e.g., a tuple."""
pvalueish, pvalues = self._extract_input_pvalues(left)
pipelines = [v.pipeline for v in pvalues if isinstance(v, pvalue.PValue)]
if pvalues and not pipelines:
deferred = False
# pylint: disable=wrong-import-order, wrong-import-position
from apache_beam import pipeline
from apache_beam.options.pipeline_options import PipelineOptions
# pylint: enable=wrong-import-order, wrong-import-position
p = pipeline.Pipeline(
'DirectRunner', PipelineOptions(sys.argv))
else:
if not pipelines:
if self.pipeline is not None:
p = self.pipeline
else:
raise ValueError('"%s" requires a pipeline to be specified '
'as there are no deferred inputs.'% self.label)
else:
p = self.pipeline or pipelines[0]
for pp in pipelines:
if p != pp:
raise ValueError(
'Mixing value from different pipelines not allowed.')
deferred = not getattr(p.runner, 'is_eager', False)
# pylint: disable=wrong-import-order, wrong-import-position
from apache_beam.transforms.core import Create
# pylint: enable=wrong-import-order, wrong-import-position
replacements = {id(v): p | 'CreatePInput%s' % ix >> Create(v)
for ix, v in enumerate(pvalues)
if not isinstance(v, pvalue.PValue) and v is not None}
pvalueish = _SetInputPValues().visit(pvalueish, replacements)
self.pipeline = p
result = p.apply(self, pvalueish, label)
if deferred:
return result
# Get a reference to the runners internal cache, otherwise runner may
# clean it after run.
cache = p.runner.cache
p.run().wait_until_finish()
return _MaterializePValues(cache).visit(result)
def _extract_input_pvalues(self, pvalueish):
"""Extract all the pvalues contained in the input pvalueish.
Returns pvalueish as well as the flat inputs list as the input may have to
be copied as inspection may be destructive.
By default, recursively extracts tuple components and dict values.
Generally only needs to be overriden for multi-input PTransforms.
"""
# pylint: disable=wrong-import-order
from apache_beam import pipeline
# pylint: enable=wrong-import-order
if isinstance(pvalueish, pipeline.Pipeline):
pvalueish = pvalue.PBegin(pvalueish)
def _dict_tuple_leaves(pvalueish):
if isinstance(pvalueish, tuple):
for a in pvalueish:
for p in _dict_tuple_leaves(a):
yield p
elif isinstance(pvalueish, dict):
for a in pvalueish.values():
for p in _dict_tuple_leaves(a):
yield p
else:
yield pvalueish
return pvalueish, tuple(_dict_tuple_leaves(pvalueish))
_known_urns = {}
@classmethod
def register_urn(cls, urn, parameter_type, constructor=None):
def register(constructor):
cls._known_urns[urn] = parameter_type, constructor
return staticmethod(constructor)
if constructor:
# Used as a statement.
register(constructor)
else:
# Used as a decorator.
return register
def to_runner_api(self, context):
from apache_beam.portability.api import beam_runner_api_pb2
urn, typed_param = self.to_runner_api_parameter(context)
return beam_runner_api_pb2.FunctionSpec(
urn=urn,
payload=typed_param.SerializeToString()
if typed_param is not None else None)
@classmethod
def from_runner_api(cls, proto, context):
if proto is None or not proto.urn:
return None
parameter_type, constructor = cls._known_urns[proto.urn]
return constructor(
proto_utils.parse_Bytes(proto.payload, parameter_type),
context)
def to_runner_api_parameter(self, context):
return (urns.PICKLED_TRANSFORM,
wrappers_pb2.BytesValue(value=pickler.dumps(self)))
@staticmethod
def from_runner_api_parameter(spec_parameter, unused_context):
return pickler.loads(spec_parameter.value)
PTransform.register_urn(
urns.PICKLED_TRANSFORM,
wrappers_pb2.BytesValue,
PTransform.from_runner_api_parameter)
class _ChainedPTransform(PTransform):
def __init__(self, *parts):
super(_ChainedPTransform, self).__init__(label=self._chain_label(parts))
self._parts = parts
def _chain_label(self, parts):
return '|'.join(p.label for p in parts)
def __or__(self, right):
if isinstance(right, PTransform):
# Create a flat list rather than a nested tree of composite
# transforms for better monitoring, etc.
return _ChainedPTransform(*(self._parts + (right,)))
return NotImplemented
def expand(self, pval):
return reduce(operator.or_, self._parts, pval)
class PTransformWithSideInputs(PTransform):
"""A superclass for any :class:`PTransform` (e.g.
:func:`~apache_beam.transforms.core.FlatMap` or
:class:`~apache_beam.transforms.core.CombineFn`)
invoking user code.
:class:`PTransform` s like :func:`~apache_beam.transforms.core.FlatMap`
invoke user-supplied code in some kind of package (e.g. a
:class:`~apache_beam.transforms.core.DoFn`) and optionally provide arguments
and side inputs to that code. This internal-use-only class contains common
functionality for :class:`PTransform` s that fit this model.
"""
def __init__(self, fn, *args, **kwargs):
if isinstance(fn, type) and issubclass(fn, WithTypeHints):
# Don't treat Fn class objects as callables.
raise ValueError('Use %s() not %s.' % (fn.__name__, fn.__name__))
self.fn = self.make_fn(fn)
# Now that we figure out the label, initialize the super-class.
super(PTransformWithSideInputs, self).__init__()
if (any([isinstance(v, pvalue.PCollection) for v in args]) or
any([isinstance(v, pvalue.PCollection) for v in kwargs.itervalues()])):
raise error.SideInputError(
'PCollection used directly as side input argument. Specify '
'AsIter(pcollection) or AsSingleton(pcollection) to indicate how the '
'PCollection is to be used.')
self.args, self.kwargs, self.side_inputs = util.remove_objects_from_args(
args, kwargs, pvalue.AsSideInput)
self.raw_side_inputs = args, kwargs
# Prevent name collisions with fns of the form '<function <lambda> at ...>'
self._cached_fn = self.fn
# Ensure fn and side inputs are picklable for remote execution.
self.fn = pickler.loads(pickler.dumps(self.fn))
self.args = pickler.loads(pickler.dumps(self.args))
self.kwargs = pickler.loads(pickler.dumps(self.kwargs))
# For type hints, because loads(dumps(class)) != class.
self.fn = self._cached_fn
def with_input_types(
self, input_type_hint, *side_inputs_arg_hints, **side_input_kwarg_hints):
"""Annotates the types of main inputs and side inputs for the PTransform.
Args:
input_type_hint: An instance of an allowed built-in type, a custom class,
or an instance of a typehints.TypeConstraint.
*side_inputs_arg_hints: A variable length argument composed of
of an allowed built-in type, a custom class, or a
typehints.TypeConstraint.
**side_input_kwarg_hints: A dictionary argument composed of
of an allowed built-in type, a custom class, or a
typehints.TypeConstraint.
Example of annotating the types of side-inputs::
FlatMap().with_input_types(int, int, bool)
Raises:
:class:`~exceptions.TypeError`: If **type_hint** is not a valid type-hint.
See
:func:`~apache_beam.typehints.typehints.validate_composite_type_param`
for further details.
Returns:
:class:`PTransform`: A reference to the instance of this particular
:class:`PTransform` object. This allows chaining type-hinting related
methods.
"""
super(PTransformWithSideInputs, self).with_input_types(input_type_hint)
for si in side_inputs_arg_hints:
validate_composite_type_param(si, 'Type hints for a PTransform')
for si in side_input_kwarg_hints.values():
validate_composite_type_param(si, 'Type hints for a PTransform')
self.side_inputs_types = side_inputs_arg_hints
return WithTypeHints.with_input_types(
self, input_type_hint, *side_inputs_arg_hints, **side_input_kwarg_hints)
def type_check_inputs(self, pvalueish):
type_hints = self.get_type_hints().input_types
if type_hints:
args, kwargs = self.raw_side_inputs
def element_type(side_input):
if isinstance(side_input, pvalue.AsSideInput):
return side_input.element_type
return instance_to_type(side_input)
arg_types = [pvalueish.element_type] + [element_type(v) for v in args]
kwargs_types = {k: element_type(v) for (k, v) in kwargs.items()}
argspec_fn = self._process_argspec_fn()
bindings = getcallargs_forhints(argspec_fn, *arg_types, **kwargs_types)
hints = getcallargs_forhints(argspec_fn, *type_hints[0], **type_hints[1])
for arg, hint in hints.items():
if arg.startswith('%unknown%'):
continue
if hint is None:
continue
if not typehints.is_consistent_with(
bindings.get(arg, typehints.Any), hint):
raise TypeCheckError(
'Type hint violation for \'%s\': requires %s but got %s for %s'
% (self.label, hint, bindings[arg], arg))
def _process_argspec_fn(self):
"""Returns an argspec of the function actually consuming the data.
"""
raise NotImplementedError
def make_fn(self, fn):
# TODO(silviuc): Add comment describing that this is meant to be overriden
# by methods detecting callables and wrapping them in DoFns.
return fn
def default_label(self):
return '%s(%s)' % (self.__class__.__name__, self.fn.default_label())
class _PTransformFnPTransform(PTransform):
"""A class wrapper for a function-based transform."""
def __init__(self, fn, *args, **kwargs):
super(_PTransformFnPTransform, self).__init__()
self._fn = fn
self._args = args
self._kwargs = kwargs
def display_data(self):
res = {'fn': (self._fn.__name__
if hasattr(self._fn, '__name__')
else self._fn.__class__),
'args': DisplayDataItem(str(self._args)).drop_if_default('()'),
'kwargs': DisplayDataItem(str(self._kwargs)).drop_if_default('{}')}
return res
def expand(self, pcoll):
# Since the PTransform will be implemented entirely as a function
# (once called), we need to pass through any type-hinting information that
# may have been annotated via the .with_input_types() and
# .with_output_types() methods.
kwargs = dict(self._kwargs)
args = tuple(self._args)
try:
if 'type_hints' in inspect.getargspec(self._fn).args:
args = (self.get_type_hints(),) + args
except TypeError:
# Might not be a function.
pass
return self._fn(pcoll, *args, **kwargs)
def default_label(self):
if self._args:
return '%s(%s)' % (
label_from_callable(self._fn), label_from_callable(self._args[0]))
return label_from_callable(self._fn)
def ptransform_fn(fn):
"""A decorator for a function-based PTransform.
Experimental; no backwards-compatibility guarantees.
Args:
fn: A function implementing a custom PTransform.
Returns:
A CallablePTransform instance wrapping the function-based PTransform.
This wrapper provides an alternative, simpler way to define a PTransform.
The standard method is to subclass from PTransform and override the expand()
method. An equivalent effect can be obtained by defining a function that
an input PCollection and additional optional arguments and returns a
resulting PCollection. For example::
@ptransform_fn
def CustomMapper(pcoll, mapfn):
return pcoll | ParDo(mapfn)
The equivalent approach using PTransform subclassing::
class CustomMapper(PTransform):
def __init__(self, mapfn):
super(CustomMapper, self).__init__()
self.mapfn = mapfn
def expand(self, pcoll):
return pcoll | ParDo(self.mapfn)
With either method the custom PTransform can be used in pipelines as if
it were one of the "native" PTransforms::
result_pcoll = input_pcoll | 'Label' >> CustomMapper(somefn)
Note that for both solutions the underlying implementation of the pipe
operator (i.e., `|`) will inject the pcoll argument in its proper place
(first argument if no label was specified and second argument otherwise).
"""
# TODO(robertwb): Consider removing staticmethod to allow for self parameter.
def callable_ptransform_factory(*args, **kwargs):
return _PTransformFnPTransform(fn, *args, **kwargs)
return callable_ptransform_factory
def label_from_callable(fn):
if hasattr(fn, 'default_label'):
return fn.default_label()
elif hasattr(fn, '__name__'):
if fn.__name__ == '<lambda>':
return '<lambda at %s:%s>' % (
os.path.basename(fn.__code__.co_filename),
fn.__code__.co_firstlineno)
return fn.__name__
return str(fn)
class _NamedPTransform(PTransform):
def __init__(self, transform, label):
super(_NamedPTransform, self).__init__(label)
self.transform = transform
def __ror__(self, pvalueish, _unused=None):
return self.transform.__ror__(pvalueish, self.label)
def expand(self, pvalue):
raise RuntimeError("Should never be expanded directly.")
|
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import with_statement
import copy
import threading
try:
import simplejson as json
except ImportError:
import json
from types import GeneratorType
from .exceptions import BulkOperationException
__author__ = 'alberto'
class DotDict(dict):
def __getattr__(self, attr):
if attr.startswith('__'):
raise AttributeError
return self.get(attr, None)
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def __deepcopy__(self, memo):
return DotDict([(copy.deepcopy(k, memo), copy.deepcopy(v, memo)) for k, v in self.items()])
class ElasticSearchModel(DotDict):
def __init__(self, *args, **kwargs):
from pyes import ES
self._meta = DotDict()
self.__initialised = True
if len(args) == 2 and isinstance(args[0], ES):
item = args[1]
self.update(item.pop("_source", DotDict()))
self.update(item.pop("fields", {}))
self._meta = DotDict([(k.lstrip("_"), v) for k, v in item.items()])
self._meta.parent = self.pop("_parent", None)
self._meta.connection = args[0]
else:
self.update(dict(*args, **kwargs))
def __setattr__(self, key, value):
if not self.__dict__.has_key(
'_ElasticSearchModel__initialised'): # this test allows attributes to be set in the __init__ method
return dict.__setattr__(self, key, value)
elif self.__dict__.has_key(key): # any normal attributes are handled normally
dict.__setattr__(self, key, value)
else:
self.__setitem__(key, value)
def get_meta(self):
return self._meta
def delete(self, bulk=False):
"""
Delete the object
"""
meta = self._meta
conn = meta['connection']
conn.delete(meta.index, meta.type, meta.id, bulk=bulk)
def save(self, bulk=False, id=None, parent=None, force=False):
"""
Save the object and returns id
"""
meta = self._meta
conn = meta['connection']
id = id or meta.get("id", None)
parent = parent or meta.get('parent', None)
version = meta.get('version', None)
if force:
version = None
res = conn.index(self,
meta.index, meta.type, id, parent=parent, bulk=bulk, version=version, force_insert=force)
if not bulk:
self._meta.id = res._id
self._meta.version = res._version
return res._id
return id
def reload(self):
meta = self._meta
conn = meta['connection']
res = conn.get(meta.index, meta.type, meta["id"])
self.update(res)
def get_id(self):
""" Force the object saveing to get an id"""
_id = self._meta.get("id", None)
if _id is None:
_id = self.save()
return _id
def get_bulk(self, create=False):
"""Return bulk code"""
result = []
op_type = "index"
if create:
op_type = "create"
meta = self._meta
cmd = {op_type: {"_index": meta.index, "_type": meta.type}}
if meta.parent:
cmd[op_type]['_parent'] = meta.parent
if meta.version:
cmd[op_type]['_version'] = meta.version
if meta.id:
cmd[op_type]['_id'] = meta.id
result.append(json.dumps(cmd, cls=self._meta.connection.encoder))
result.append("\n")
result.append(json.dumps(self, cls=self._meta.connection.encoder))
result.append("\n")
return ''.join(result)
#--------
# Bulkers
#--------
class BaseBulker(object):
"""
Base class to implement a bulker strategy
"""
def __init__(self, conn, bulk_size=400, raise_on_bulk_item_failure=False):
self.conn = conn
self._bulk_size = bulk_size
# protects bulk_data
self.bulk_lock = threading.RLock()
with self.bulk_lock:
self.bulk_data = []
self.raise_on_bulk_item_failure = raise_on_bulk_item_failure
def get_bulk_size(self):
"""
Get the current bulk_size
:return a int: the size of the bulk holder
"""
return self._bulk_size
def set_bulk_size(self, bulk_size):
"""
Set the bulk size
:param bulk_size the bulker size
"""
self._bulk_size = bulk_size
self.flush_bulk()
bulk_size = property(get_bulk_size, set_bulk_size)
def add(self, content):
raise NotImplementedError
def flush_bulk(self, forced=False):
raise NotImplementedError
class ListBulker(BaseBulker):
"""
A bulker that store data in a list
"""
def __init__(self, conn, bulk_size=400, raise_on_bulk_item_failure=False):
super(ListBulker, self).__init__(conn=conn, bulk_size=bulk_size,
raise_on_bulk_item_failure=raise_on_bulk_item_failure)
with self.bulk_lock:
self.bulk_data = []
def add(self, content):
with self.bulk_lock:
self.bulk_data.append(content)
def flush_bulk(self, forced=False):
with self.bulk_lock:
if forced or len(self.bulk_data) >= self.bulk_size:
batch = self.bulk_data
self.bulk_data = []
else:
return None
if len(batch) > 0:
bulk_result = self.conn._send_request("POST",
"/_bulk",
"\n".join(batch) + "\n")
if self.raise_on_bulk_item_failure:
_raise_exception_if_bulk_item_failed(bulk_result)
return bulk_result
def _is_bulk_item_ok(item):
if "index" in item:
return "ok" in item["index"]
elif "delete" in item:
return "ok" in item["delete"]
else:
# unknown response type; be conservative
return False
def _raise_exception_if_bulk_item_failed(bulk_result):
errors = [item for item in bulk_result["items"] if not _is_bulk_item_ok(item)]
if len(errors) > 0:
raise BulkOperationException(errors, bulk_result)
return None
class SortedDict(dict):
"""
A dictionary that keeps its keys in the order in which they're inserted.
Taken from django
"""
def __new__(cls, *args, **kwargs):
instance = super(SortedDict, cls).__new__(cls, *args, **kwargs)
instance.keyOrder = []
return instance
def __init__(self, data=None):
if data is None:
data = {}
elif isinstance(data, GeneratorType):
# Unfortunately we need to be able to read a generator twice. Once
# to get the data into self with our super().__init__ call and a
# second time to setup keyOrder correctly
data = list(data)
super(SortedDict, self).__init__(data)
if isinstance(data, dict):
self.keyOrder = data.keys()
else:
self.keyOrder = []
seen = set()
for key, value in data:
if key not in seen:
self.keyOrder.append(key)
seen.add(key)
def __deepcopy__(self, memo):
return self.__class__([(key, copy.deepcopy(value, memo))
for key, value in self.iteritems()])
def __setitem__(self, key, value):
if key not in self:
self.keyOrder.append(key)
super(SortedDict, self).__setitem__(key, value)
def __delitem__(self, key):
super(SortedDict, self).__delitem__(key)
self.keyOrder.remove(key)
def __iter__(self):
return iter(self.keyOrder)
def pop(self, k, *args):
result = super(SortedDict, self).pop(k, *args)
try:
self.keyOrder.remove(k)
except ValueError:
# Key wasn't in the dictionary in the first place. No problem.
pass
return result
def popitem(self):
result = super(SortedDict, self).popitem()
self.keyOrder.remove(result[0])
return result
def items(self):
return zip(self.keyOrder, self.values())
def iteritems(self):
for key in self.keyOrder:
yield key, self[key]
def keys(self):
return self.keyOrder[:]
def iterkeys(self):
return iter(self.keyOrder)
def values(self):
return map(self.__getitem__, self.keyOrder)
def itervalues(self):
for key in self.keyOrder:
yield self[key]
def update(self, dict_):
for k, v in dict_.iteritems():
self[k] = v
def setdefault(self, key, default):
if key not in self:
self.keyOrder.append(key)
return super(SortedDict, self).setdefault(key, default)
def value_for_index(self, index):
"""Returns the value of the item at the given zero-based index."""
return self[self.keyOrder[index]]
def insert(self, index, key, value):
"""Inserts the key, value pair before the item with the given index."""
if key in self.keyOrder:
n = self.keyOrder.index(key)
del self.keyOrder[n]
if n < index:
index -= 1
self.keyOrder.insert(index, key)
super(SortedDict, self).__setitem__(key, value)
def copy(self):
"""Returns a copy of this object."""
# This way of initializing the copy means it works for subclasses, too.
obj = self.__class__(self)
obj.keyOrder = self.keyOrder[:]
return obj
def __repr__(self):
"""
Replaces the normal dict.__repr__ with a version that returns the keys
in their sorted order.
"""
return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in self.items()])
def clear(self):
super(SortedDict, self).clear()
self.keyOrder = []
|
|
import numpy as NP
import h5py
import ast
import warnings
def recursive_find_notNone_in_dict(inpdict):
"""
----------------------------------------------------------------------------
Recursively walk through a dictionary and reduce it to only non-None values.
Inputs:
inpdict [dictionary] Input dictionary to reduced to non-None values
Outputs:
outdict is an output dictionary which only contains keys and values
corresponding to non-None values
----------------------------------------------------------------------------
"""
if not isinstance(inpdict, dict):
raise TypeError('inpdict must be a dictionary')
outdict = {}
for k, v in inpdict.iteritems():
if v is not None:
if not isinstance(v, dict):
outdict[k] = v
else:
temp = recursive_find_notNone_in_dict(v)
if temp:
outdict[k] = temp
return outdict
################################################################################
def is_dict1_subset_of_dict2(dict1, dict2, ignoreNone=True):
"""
----------------------------------------------------------------------------
Check if keys and values of the first dictionary are a subset of the second.
Inputs:
dict1 [dictionary] First dictionary. It will be checked if both its
keys and values are a subset of the second dictionary.
dict2 [dictionary] Second dictionary. The values and keys of the first
dictionary will be checked against this dictionary to check if
the first is a subset of the second.
ignoreNone [boolean] If set to True (default), the subset checking happens
using the non-None values in both dictionaries. This is a
loose check. If set to False, a strict subset checking happens
not ignoring the None values, if any.
Output:
Boolean value True if dict1 is found to be a subset of dict2, False
otherwise
----------------------------------------------------------------------------
"""
if not isinstance(dict1, dict):
raise TypeError('Input dict1 must be a dictionary')
if not isinstance(dict2, dict):
raise TypeError('Input dict2 must be a dictionary')
if ignoreNone:
dict1 = recursive_find_notNone_in_dict(dict1)
dict2 = recursive_find_notNone_in_dict(dict2)
if cmp(dict1, dict2) == 0:
return True
else:
dict2sub = {}
for k, v in dict1.iteritems():
if k in dict2:
dict2sub[k] = dict2[k]
else:
return False
if cmp(dict1, dict2sub) == 0:
return True
else:
return False
################################################################################
def find_list_in_list(reference_array, inp):
"""
---------------------------------------------------------------------------
Find occurrences of input list in a reference list and return indices
into the reference list
Inputs:
reference_array [list or numpy array] One-dimensional reference list or
numpy array in which occurrences of elements in the input
list or array will be found
inp [list or numpy array] One-dimensional input list whose
elements will be searched in the reference array and
the indices into the reference array will be returned
Output:
ind [numpy masked array] Indices of occurrences of elements
of input array in the reference array. It will be of same
size as input array. For example,
inp = reference_array[ind]. Indices for elements which are
not found in the reference array will be masked.
---------------------------------------------------------------------------
"""
try:
reference_array, inp
except NameError:
raise NameError('Inputs reference_array, inp must be specified')
if not isinstance(reference_array, (list, NP.ndarray)):
raise TypeError('Input reference_array must be a list or numpy array')
reference_array = NP.asarray(reference_array).ravel()
if not isinstance(inp, (list, NP.ndarray)):
raise TypeError('Input inp must be a list or numpy array')
inp = NP.asarray(inp).ravel()
if (inp.size == 0) or (reference_array.size == 0):
raise ValueError('One or both inputs contain no elements')
sortind_ref = NP.argsort(reference_array)
sorted_ref = reference_array[sortind_ref]
ind_in_sorted_ref = NP.searchsorted(sorted_ref, inp)
ii = NP.take(sortind_ref, ind_in_sorted_ref, mode='clip')
mask = reference_array[ii] != inp
ind = NP.ma.array(ii, mask=mask)
return ind
################################################################################
def find_all_occurrences_list1_in_list2(list1, list2):
"""
---------------------------------------------------------------------------
Find all occurrences of input list1 (a reference list) in input list2
Inputs:
list1 [list or numpy array] List of elements which need to be searched
for in list2. Must be a flattened list or numpy array
list2 [list or numpy array] List of elements in which elements in list1
are searched for. Must be a flattened list or numpy array
Output:
ind [list of lists] Indices of occurrences of elements
of input list1 indexed into list2. For each element in list1,
there is an output list which contains all the indices of this
element occurring in list2. Hence, the output is a list of lists
where the top level list contains equal number of items as list1.
Each i-th item in this list is another list containing indices of
the element list1[i] in list2
---------------------------------------------------------------------------
"""
if not isinstance(list1, (list, NP.ndarray)):
raise TypeError('Input list1 must be a list or numpy array')
if not isinstance(list2, (list, NP.ndarray)):
raise TypeError('Input list2 must be a list or numpy array')
list_of_list_of_inds = [[i for i, x in enumerate(list2) if x == e] for e in list1]
return list_of_list_of_inds
################################################################################
def save_dict_to_hdf5(dic, filename, compressinfo=None):
"""
---------------------------------------------------------------------------
Save a dictionary as a HDF5 structure under the given filename preserving
its structure
Inputs:
dic [dictionary] Input dictionary which is to be stored in HDF5
format
filename [string] string containing full path to the HDF5 file including
the file name
compressinfo
[dictionary] Dictionary containing compression options or
set as None (default) when no compression is to be applied.
When compression is to be applied, it contains keys of those
data that are to be compressed. Under each key is another
dictionary with the following keys and values:
'compress_fmt' [string] Compression format. Accepted values
are 'gzip' and 'lzf'
'compress_opts' [int] Integer denoting level of compression.
Only applies if compress_fmt is set to 'gzip'.
It must be an integer between 0 and 9
'chunkshape' [tuple] Shape of the chunks to be used in
compression. It must be broadcastable to the
data shape inside input dic
If at any point, any error is encountered, it will switch to
no compression
---------------------------------------------------------------------------
"""
with h5py.File(filename, 'w') as h5file:
recursively_save_dict_contents_to_group(h5file, '/', dic, compressinfo=compressinfo)
################################################################################
def recursively_save_dict_contents_to_group(h5file, path, dic, compressinfo=None):
"""
---------------------------------------------------------------------------
Recursively store contents of a dictionary in HDF5 groups
Inputs:
h5file [Python File Object] An open file object under which the HDF5
groups will be created
path [string] String containing the root group under the python file
object h5file
dic [dictionary] dictionary whose keys and items will be stored
under the root group specified by path under the python file
object h5file
compressinfo
[dictionary] Dictionary containing compression options or
set as None (default) when no compression is to be applied.
When compression is to be applied, it contains keys of those
data that are to be compressed. Under each key is another
dictionary with the following keys and values:
'compress_fmt' [string] Compression format. Accepted values
are 'gzip' and 'lzf'
'compress_opts' [int] Integer denoting level of compression.
Only applies if compress_fmt is set to 'gzip'.
It must be an integer between 0 and 9
'chunkshape' [tuple] Shape of the chunks to be used in
compression. It must be broadcastable to the
data shape inside input dic
If at any point, any error is encountered, it will switch to
no compression
---------------------------------------------------------------------------
"""
for key, item in dic.iteritems():
if not isinstance(key, str):
warnings.warn('Key found not to be a string. Converting the key to string and proceeding...')
key = str(key)
if isinstance(item, (NP.ndarray, NP.int, NP.int32, NP.int64, NP.float, NP.float32, NP.float64, NP.complex, NP.complex64, NP.complex128, str, bytes)):
if isinstance(item, NP.ndarray):
if compressinfo is not None:
if isinstance(compressinfo, dict):
try:
compress_fmt = compressinfo[key]['compress_fmt'].lower()
compress_opts = NP.clip(compressinfo[key]['compress_opts'], 0, 9)
chunkshape = compressinfo[key]['chunkshape']
except:
h5file[path + key] = item
else:
dset = h5file.create_dataset(path+key, data=item, chunks=chunkshape, compression=compress_fmt, compression_opts=compress_opts)
# if not isinstance(compressinfo[key]['compress_fmt'], str):
# raise TypeError('Input parameter compress_fmt must be a string')
# compress_fmt = compressinfo[key]['compress_fmt'].lower()
# if compress_fmt not in ['gzip', 'lzf']:
# raise ValueError('Input parameter compress_fmt invalid')
# if compress_fmt == 'gzip':
# if not isinstance(compressinfo[key]['compress_opts'], int):
# raise TypeError('Input parameter compress_opts must be an integer')
# compress_opts = NP.clip(compressinfo[key]['compress_opts'], 0, 9)
# if 'chunkshape' not in compressinfo[key]:
# raise KeyError('Key chunkshape not provided in cmagompressinfo parameter')
# elif not isinstance(compressinfo[key]['chunkshape'], tuple):
# raise TypeError('Value under chunkshape key in compressinfo parameter must be a tuple')
# else:
# dset = h5file.create_dataset(path+key, data=item, chunks=chunkshape, compression=compress_fmt, compression_opts=compress_opts)
else:
warnings.warn('Compression options not specified properly. Proceeding with no compression')
h5file[path + key] = item
else:
h5file[path + key] = item
else:
h5file[path + key] = item
elif item is None:
h5file[path + key] = 'None'
elif isinstance(item, dict):
recursively_save_dict_contents_to_group(h5file, path + key + '/', item, compressinfo=compressinfo)
else:
raise ValueError('Cannot save %s type'%type(item))
################################################################################
def load_dict_from_hdf5(filename):
"""
---------------------------------------------------------------------------
Load HDF5 contents into a python dictionary preserving the structure
Input:
filename [string] Full path to the HDF5 file
Output:
Python dictionary containing the contents of the HDF5 file
---------------------------------------------------------------------------
"""
with h5py.File(filename, 'r') as h5file:
return recursively_load_dict_contents_from_group(h5file, '/')
################################################################################
def recursively_load_dict_contents_from_group(h5file, path):
"""
---------------------------------------------------------------------------
Recursively load HDF5 group contents into python dictionary structure
Inputs:
h5file [Python File Object] An open file object under which the HDF5
groups will be created
path [string] String containing the root group under the python file
object h5file
Output:
Python structure that is copied from the HDF5 content at the level
specified by the path in the python object h5file
---------------------------------------------------------------------------
"""
ans = {}
for key, item in h5file[path].items():
if isinstance(item, h5py._hl.dataset.Dataset):
if isinstance(item.value, str):
try:
if ast.literal_eval(item.value) is None:
ans[key] = None
except:
ans[key] = item.value
else:
ans[key] = item.value
elif isinstance(item, h5py._hl.group.Group):
ans[key] = recursively_load_dict_contents_from_group(h5file, path + key + '/')
return ans
################################################################################
|
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from datetime import datetime
from vilya.libs.store import mc, cache
from vilya.libs.store import store
MC_KEY_TAG_TYPE_IDS_BY_TAG_ID = "code:tags:type_ids:by:tag_id:%s"
MC_KEY_TAG_IDS_BY_TARGET_ID_AND_TYPE = "code:tag_ids:by:target_id:%s:type:%s"
ONE_DAY = 60 * 60 * 24
# TODO: table `tagname` should be renamed `tags`
# TODO: TagName should be renamed Tag
class TagName(object):
def __init__(self, id, name, author_id, created_at, target_type,
target_id, hex_color):
self.id = id
self.name = name
self.author_id = author_id
self.created_at = created_at
self.target_type = target_type
self.target_id = target_id
self.hex_color = hex_color
self._group_uid = None
@property
def group_uid(self):
if self._group_uid is None:
uid = 'used'
name = self.name
if ':' in name:
if self.name.startswith('type:'):
uid = 'type'
elif self.name.startswith('stage:'):
uid = 'stage'
elif self.name.startswith('priority:'):
uid = 'priority'
self._group_uid = uid
return self._group_uid
@classmethod
def add(cls, name, author_id, target_type, target_id, color='cccccc'):
# TODO: check tag name
time = datetime.now()
tagname_id = store.execute(
"insert into tag_names(name, author_id, created_at, target_type, "
"target_id, hex_color) values ( % s, % s, NULL, % s, % s, % s) ",
(name, author_id, target_type, target_id, color))
store.commit()
return cls(
tagname_id, name, author_id, time, target_type, target_id, color)
@classmethod
def gets(cls):
tags = []
rs = store.execute(
"select id, name, author_id, created_at, target_type, target_id, "
"hex_color from tag_names")
for r in rs:
tags.append(cls(*r))
return tags
@classmethod
def get_by_name_and_target_id(cls, name, target_type, target_id):
rs = store.execute(
"select id, name, author_id, created_at, target_type, target_id, "
"hex_color from tag_names "
"where name=%s and target_type=%s and target_id=%s",
(name, target_type, target_id))
if rs and rs[0]:
return cls(*rs[0])
@classmethod
def get_by_id(cls, id):
rs = store.execute(
"select id, name, author_id, created_at, target_type, target_id, "
"hex_color from tag_names "
"where id=%s", (id,))
if rs and rs[0]:
return cls(*rs[0])
def _check_tag_is_in_use(self):
rs = store.execute(
"select id from tags"
"where tag_id=%s", (self.id,))
if rs and rs[0]:
return True
return False
def delete(self):
n = store.execute(
"delete from tag_names "
"where id=%s", (self.id,))
if n:
store.commit()
return True
@property
def project_issue_ids(self):
if self.target_type == TAG_TYPE_PROJECT_ISSUE:
tags = Tag.gets_by_tag_id(self.id)
return [t.type_id for t in tags]
return []
@classmethod
def get_project_issue_tag(cls, name, project):
tag_name = cls.get_by_name_and_target_id(
name, TAG_TYPE_PROJECT_ISSUE, project.id)
return tag_name
@classmethod
def get_target_tags(cls, target_type, target_id):
rs = store.execute(
"select id, name, author_id, created_at, target_type, target_id, "
"hex_color from tag_names where target_type=%s and target_id=%s",
(target_type, target_id))
return [cls(*_) for _ in rs] if rs else []
def update_name(self, name):
store.execute("update tag_names set name=%s where id=%s",
(name, self.id))
store.commit()
self.name = name
def update_color(self, color):
store.execute("update tag_names set hex_color=%s where id=%s",
(color, self.id))
store.commit()
self.hex_color = color
# TODO: table `tags` should be renamed `target_tags` or `type_tags`
# TODO: Tag should be TargetTag or TypeTag or KindTag
class Tag(object):
def __init__(self, id, tag_id, type, type_id, author_id, created_at,
target_id):
self.id = id
self.tag_id = tag_id
self.type = type
self.type_id = type_id
self.author_id = author_id
self.created_at = created_at
self.target_id = target_id
@property
def name(self):
tag = TagName.get_by_id(self.tag_id)
return tag.name
# TagName
@property
def tagname(self):
return TagName.get_by_id(self.tag_id)
@classmethod
def add(cls, tag_id, type, type_id, author_id, target_id):
time = datetime.now()
issue_tag_id = store.execute(
"insert into tags "
"(tag_id, type_id, type, author_id, created_at, target_id) "
"values (%s, %s, %s, %s, NULL, %s)",
(tag_id, type_id, type, author_id, target_id))
store.commit()
tag = cls(issue_tag_id, tag_id, type,
type_id, author_id, time, target_id)
if tag:
tag._clean_cache()
return tag
@classmethod
def get_type_tags(cls, type, type_id=None, author_id=None):
tags = []
sql = ("select id, tag_id, type, type_id, author_id, created_at, "
"target_id from tags where type=%s ")
params = [type]
if type_id:
sql = sql + "and type_id=%s "
params.append(type_id)
if author_id:
sql = sql + "and author=%s "
params.append(author_id)
rs = store.execute(sql, tuple(params))
for r in rs:
tags.append(cls(*r))
return tags
def _clean_cache(self):
mc.delete(MC_KEY_TAG_TYPE_IDS_BY_TAG_ID % self.tag_id)
mc.delete(MC_KEY_TAG_IDS_BY_TARGET_ID_AND_TYPE %
(self.target_id, self.type))
@classmethod
def gets_by_issue_id(cls, issue_id, type):
return cls.get_type_tags(type, issue_id)
@classmethod
def gets_by_tag_id(cls, tag_id):
rs = store.execute(
"select id, tag_id, type, type_id, author_id, created_at, "
"target_id from tags where tag_id=%s ", tag_id)
return [cls(*r) for r in rs]
@classmethod
@cache(MC_KEY_TAG_IDS_BY_TARGET_ID_AND_TYPE % (
'{target_id}', '{type}'), expire=ONE_DAY)
def _gets_by_target_id(cls, target_id, type):
sql = ("select id, tag_id, type, type_id, author_id, created_at, "
"target_id from tags where type=%s and target_id=%s")
rs = store.execute(sql, (type, target_id))
return rs
@classmethod
def gets_by_target_id(cls, type, target_id):
rs = cls._gets_by_target_id(target_id, type)
return [cls(*r) for r in rs]
@classmethod
@cache(MC_KEY_TAG_TYPE_IDS_BY_TAG_ID % '{tag_id}', expire=60 * 60 * 24)
def get_type_ids_by_tag_id(cls, tag_id):
sql = ("select id, tag_id, type, type_id, author_id, created_at, "
"target_id from tags where tag_id=%s")
rs = store.execute(sql, tag_id)
tags = [cls(*r) for r in rs]
return [t.type_id for t in tags if t]
@classmethod
def get_by_type_id_and_tag_id(cls, type, type_id, tag_id):
rs = store.execute(
"select id, tag_id, type, type_id, author_id, created_at, "
"target_id from tags where type=%s and type_id=%s and tag_id=%s ",
(type, type_id, tag_id))
if rs and rs[0]:
return cls(*rs[0])
@classmethod
def add_to_issue(cls, tag_id, type, issue_id, author_id, target_id):
return cls.add(tag_id, type, issue_id, author_id, target_id)
@classmethod
def add_to_gist(cls, tag_id, gist_id, author_id, target_id):
return cls.add(tag_id, TAG_TYPE_GIST, gist_id, author_id, target_id)
def delete(self):
n = store.execute(
"delete from tags "
"where id=%s", self.id)
self._clean_cache()
if n:
store.commit()
return True
@classmethod
def gets(cls):
sql = ("select id, tag_id, type, type_id, author_id, created_at, "
"target_id from tags")
rs = store.execute(sql)
return [cls(*r) for r in rs]
@classmethod
def get_type_ids_by_name_and_target_id(cls, type, name, target_id):
tag_name = TagName.get_by_name_and_target_id(name, type, target_id)
return cls.get_type_ids_by_tag_id(tag_name.id) if tag_name else []
@classmethod
def get_type_ids_by_names_and_target_id(cls, type, names, target_id):
issue_ids = []
for name in names:
issue_ids.append(
cls.get_type_ids_by_name_and_target_id(type, name, target_id))
return reduce(lambda x, y: set(x) & set(y), issue_ids)
# tag target type list
TAG_TYPE_PROJECT_ISSUE = 1
TAG_TYPE_TEAM_ISSUE = 2
TAG_TYPE_GIST = 3
TAG_TYPE_FAIR_ISSUE = 4
class TagMixin(object):
@property
def tag_type(self):
raise NotImplementedError('Subclasses should implement this!')
@property
def tags(self):
return self.get_tags()
def get_tags(self):
all_tags = TagName.get_target_tags(self.tag_type, self.id)
return all_tags
def get_group_tags(self, selected_names):
group_tags = {}
all_tags = TagName.get_target_tags(self.tag_type, self.id)
for tag in all_tags:
if tag.group_uid not in group_tags:
group_tags[tag.group_uid] = []
if tag.name in selected_names:
group_tags[tag.group_uid].append((tag, 0, 'selected'))
else:
group_tags[tag.group_uid].append((tag, 0, 'unselected'))
return group_tags
|
|
# Copyright (c) 2012 Rackspace Hosting
# All Rights Reserved.
#
# 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.
"""
Tests For Cells RPCAPI
"""
from oslo.config import cfg
import six
from nova.cells import rpcapi as cells_rpcapi
from nova import exception
from nova import objects
from nova import test
from nova.tests.unit import fake_instance
CONF = cfg.CONF
CONF.import_opt('topic', 'nova.cells.opts', group='cells')
class CellsAPITestCase(test.NoDBTestCase):
"""Test case for cells.api interfaces."""
def setUp(self):
super(CellsAPITestCase, self).setUp()
self.fake_topic = 'fake_topic'
self.fake_context = 'fake_context'
self.flags(topic=self.fake_topic, enable=True, group='cells')
self.cells_rpcapi = cells_rpcapi.CellsAPI()
def _stub_rpc_method(self, rpc_method, result):
call_info = {}
orig_prepare = self.cells_rpcapi.client.prepare
def fake_rpc_prepare(**kwargs):
if 'version' in kwargs:
call_info['version'] = kwargs.pop('version')
return self.cells_rpcapi.client
def fake_csv(version):
return orig_prepare(version).can_send_version()
def fake_rpc_method(ctxt, method, **kwargs):
call_info['context'] = ctxt
call_info['method'] = method
call_info['args'] = kwargs
return result
self.stubs.Set(self.cells_rpcapi.client, 'prepare', fake_rpc_prepare)
self.stubs.Set(self.cells_rpcapi.client, 'can_send_version', fake_csv)
self.stubs.Set(self.cells_rpcapi.client, rpc_method, fake_rpc_method)
return call_info
def _check_result(self, call_info, method, args, version=None):
self.assertEqual(self.cells_rpcapi.client.target.topic,
self.fake_topic)
self.assertEqual(self.fake_context, call_info['context'])
self.assertEqual(method, call_info['method'])
self.assertEqual(args, call_info['args'])
if version is not None:
self.assertIn('version', call_info)
self.assertIsInstance(call_info['version'], six.string_types,
msg="Message version %s is not a string" %
call_info['version'])
self.assertEqual(version, call_info['version'])
else:
self.assertNotIn('version', call_info)
def test_cast_compute_api_method(self):
fake_cell_name = 'fake_cell_name'
fake_method = 'fake_method'
fake_method_args = (1, 2)
fake_method_kwargs = {'kwarg1': 10, 'kwarg2': 20}
expected_method_info = {'method': fake_method,
'method_args': fake_method_args,
'method_kwargs': fake_method_kwargs}
expected_args = {'method_info': expected_method_info,
'cell_name': fake_cell_name,
'call': False}
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.cast_compute_api_method(self.fake_context,
fake_cell_name, fake_method,
*fake_method_args, **fake_method_kwargs)
self._check_result(call_info, 'run_compute_api_method',
expected_args)
def test_call_compute_api_method(self):
fake_cell_name = 'fake_cell_name'
fake_method = 'fake_method'
fake_method_args = (1, 2)
fake_method_kwargs = {'kwarg1': 10, 'kwarg2': 20}
fake_response = 'fake_response'
expected_method_info = {'method': fake_method,
'method_args': fake_method_args,
'method_kwargs': fake_method_kwargs}
expected_args = {'method_info': expected_method_info,
'cell_name': fake_cell_name,
'call': True}
call_info = self._stub_rpc_method('call', fake_response)
result = self.cells_rpcapi.call_compute_api_method(self.fake_context,
fake_cell_name, fake_method,
*fake_method_args, **fake_method_kwargs)
self._check_result(call_info, 'run_compute_api_method',
expected_args)
self.assertEqual(fake_response, result)
def test_build_instances(self):
call_info = self._stub_rpc_method('cast', None)
instances = [objects.Instance(id=1),
objects.Instance(id=2)]
self.cells_rpcapi.build_instances(
self.fake_context, instances=instances,
image={'fake': 'image'}, arg1=1, arg2=2, arg3=3)
expected_args = {'build_inst_kwargs': {'instances': instances,
'image': {'fake': 'image'},
'arg1': 1,
'arg2': 2,
'arg3': 3}}
self._check_result(call_info, 'build_instances',
expected_args, version='1.32')
def test_get_capacities(self):
capacity_info = {"capacity": "info"}
call_info = self._stub_rpc_method('call',
result=capacity_info)
result = self.cells_rpcapi.get_capacities(self.fake_context,
cell_name="name")
self._check_result(call_info, 'get_capacities',
{'cell_name': 'name'}, version='1.9')
self.assertEqual(capacity_info, result)
def test_instance_update_at_top(self):
fake_info_cache = {'id': 1,
'instance': 'fake_instance',
'other': 'moo'}
fake_sys_metadata = [{'id': 1,
'key': 'key1',
'value': 'value1'},
{'id': 2,
'key': 'key2',
'value': 'value2'}]
fake_instance = {'id': 2,
'security_groups': 'fake',
'instance_type': 'fake',
'volumes': 'fake',
'cell_name': 'fake',
'name': 'fake',
'metadata': 'fake',
'info_cache': fake_info_cache,
'system_metadata': fake_sys_metadata,
'other': 'meow'}
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.instance_update_at_top(
self.fake_context, fake_instance)
expected_args = {'instance': fake_instance}
self._check_result(call_info, 'instance_update_at_top',
expected_args)
def test_instance_destroy_at_top(self):
fake_instance = {'uuid': 'fake-uuid'}
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.instance_destroy_at_top(
self.fake_context, fake_instance)
expected_args = {'instance': fake_instance}
self._check_result(call_info, 'instance_destroy_at_top',
expected_args)
def test_instance_delete_everywhere(self):
instance = fake_instance.fake_instance_obj(self.fake_context)
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.instance_delete_everywhere(
self.fake_context, instance,
'fake-type')
expected_args = {'instance': instance,
'delete_type': 'fake-type'}
self._check_result(call_info, 'instance_delete_everywhere',
expected_args, version='1.27')
def test_instance_fault_create_at_top(self):
fake_instance_fault = {'id': 2,
'other': 'meow'}
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.instance_fault_create_at_top(
self.fake_context, fake_instance_fault)
expected_args = {'instance_fault': fake_instance_fault}
self._check_result(call_info, 'instance_fault_create_at_top',
expected_args)
def test_bw_usage_update_at_top(self):
update_args = ('fake_uuid', 'fake_mac', 'fake_start_period',
'fake_bw_in', 'fake_bw_out', 'fake_ctr_in',
'fake_ctr_out')
update_kwargs = {'last_refreshed': 'fake_refreshed'}
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.bw_usage_update_at_top(
self.fake_context, *update_args, **update_kwargs)
bw_update_info = {'uuid': 'fake_uuid',
'mac': 'fake_mac',
'start_period': 'fake_start_period',
'bw_in': 'fake_bw_in',
'bw_out': 'fake_bw_out',
'last_ctr_in': 'fake_ctr_in',
'last_ctr_out': 'fake_ctr_out',
'last_refreshed': 'fake_refreshed'}
expected_args = {'bw_update_info': bw_update_info}
self._check_result(call_info, 'bw_usage_update_at_top',
expected_args)
def test_get_cell_info_for_neighbors(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.get_cell_info_for_neighbors(
self.fake_context)
self._check_result(call_info, 'get_cell_info_for_neighbors', {},
version='1.1')
self.assertEqual(result, 'fake_response')
def test_sync_instances(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.sync_instances(self.fake_context,
project_id='fake_project', updated_since='fake_time',
deleted=True)
expected_args = {'project_id': 'fake_project',
'updated_since': 'fake_time',
'deleted': True}
self._check_result(call_info, 'sync_instances', expected_args,
version='1.1')
def test_service_get_all(self):
call_info = self._stub_rpc_method('call', 'fake_response')
fake_filters = {'key1': 'val1', 'key2': 'val2'}
result = self.cells_rpcapi.service_get_all(self.fake_context,
filters=fake_filters)
expected_args = {'filters': fake_filters}
self._check_result(call_info, 'service_get_all', expected_args,
version='1.2')
self.assertEqual(result, 'fake_response')
def test_service_get_by_compute_host(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.service_get_by_compute_host(
self.fake_context, host_name='fake-host-name')
expected_args = {'host_name': 'fake-host-name'}
self._check_result(call_info, 'service_get_by_compute_host',
expected_args,
version='1.2')
self.assertEqual(result, 'fake_response')
def test_get_host_uptime(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.get_host_uptime(
self.fake_context, host_name='fake-host-name')
expected_args = {'host_name': 'fake-host-name'}
self._check_result(call_info, 'get_host_uptime',
expected_args,
version='1.17')
self.assertEqual(result, 'fake_response')
def test_service_update(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.service_update(
self.fake_context, host_name='fake-host-name',
binary='nova-api', params_to_update={'disabled': True})
expected_args = {
'host_name': 'fake-host-name',
'binary': 'nova-api',
'params_to_update': {'disabled': True}}
self._check_result(call_info, 'service_update',
expected_args,
version='1.7')
self.assertEqual(result, 'fake_response')
def test_service_delete(self):
call_info = self._stub_rpc_method('call', None)
cell_service_id = 'cell@id'
result = self.cells_rpcapi.service_delete(
self.fake_context, cell_service_id=cell_service_id)
expected_args = {'cell_service_id': cell_service_id}
self._check_result(call_info, 'service_delete',
expected_args, version='1.26')
self.assertIsNone(result)
def test_proxy_rpc_to_manager(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.proxy_rpc_to_manager(
self.fake_context, rpc_message='fake-msg',
topic='fake-topic', call=True, timeout=-1)
expected_args = {'rpc_message': 'fake-msg',
'topic': 'fake-topic',
'call': True,
'timeout': -1}
self._check_result(call_info, 'proxy_rpc_to_manager',
expected_args,
version='1.2')
self.assertEqual(result, 'fake_response')
def test_task_log_get_all(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.task_log_get_all(self.fake_context,
task_name='fake_name',
period_beginning='fake_begin',
period_ending='fake_end',
host='fake_host',
state='fake_state')
expected_args = {'task_name': 'fake_name',
'period_beginning': 'fake_begin',
'period_ending': 'fake_end',
'host': 'fake_host',
'state': 'fake_state'}
self._check_result(call_info, 'task_log_get_all', expected_args,
version='1.3')
self.assertEqual(result, 'fake_response')
def test_compute_node_get_all(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.compute_node_get_all(self.fake_context,
hypervisor_match='fake-match')
expected_args = {'hypervisor_match': 'fake-match'}
self._check_result(call_info, 'compute_node_get_all', expected_args,
version='1.4')
self.assertEqual(result, 'fake_response')
def test_compute_node_stats(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.compute_node_stats(self.fake_context)
expected_args = {}
self._check_result(call_info, 'compute_node_stats',
expected_args, version='1.4')
self.assertEqual(result, 'fake_response')
def test_compute_node_get(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.compute_node_get(self.fake_context,
'fake_compute_id')
expected_args = {'compute_id': 'fake_compute_id'}
self._check_result(call_info, 'compute_node_get',
expected_args, version='1.4')
self.assertEqual(result, 'fake_response')
def test_actions_get(self):
fake_instance = {'uuid': 'fake-uuid', 'cell_name': 'region!child'}
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.actions_get(self.fake_context,
fake_instance)
expected_args = {'cell_name': 'region!child',
'instance_uuid': fake_instance['uuid']}
self._check_result(call_info, 'actions_get', expected_args,
version='1.5')
self.assertEqual(result, 'fake_response')
def test_actions_get_no_cell(self):
fake_instance = {'uuid': 'fake-uuid', 'cell_name': None}
self.assertRaises(exception.InstanceUnknownCell,
self.cells_rpcapi.actions_get, self.fake_context,
fake_instance)
def test_action_get_by_request_id(self):
fake_instance = {'uuid': 'fake-uuid', 'cell_name': 'region!child'}
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.action_get_by_request_id(self.fake_context,
fake_instance,
'req-fake')
expected_args = {'cell_name': 'region!child',
'instance_uuid': fake_instance['uuid'],
'request_id': 'req-fake'}
self._check_result(call_info, 'action_get_by_request_id',
expected_args, version='1.5')
self.assertEqual(result, 'fake_response')
def test_action_get_by_request_id_no_cell(self):
fake_instance = {'uuid': 'fake-uuid', 'cell_name': None}
self.assertRaises(exception.InstanceUnknownCell,
self.cells_rpcapi.action_get_by_request_id,
self.fake_context, fake_instance, 'req-fake')
def test_action_events_get(self):
fake_instance = {'uuid': 'fake-uuid', 'cell_name': 'region!child'}
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.action_events_get(self.fake_context,
fake_instance,
'fake-action')
expected_args = {'cell_name': 'region!child',
'action_id': 'fake-action'}
self._check_result(call_info, 'action_events_get', expected_args,
version='1.5')
self.assertEqual(result, 'fake_response')
def test_action_events_get_no_cell(self):
fake_instance = {'uuid': 'fake-uuid', 'cell_name': None}
self.assertRaises(exception.InstanceUnknownCell,
self.cells_rpcapi.action_events_get,
self.fake_context, fake_instance, 'fake-action')
def test_consoleauth_delete_tokens(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.consoleauth_delete_tokens(self.fake_context,
'fake-uuid')
expected_args = {'instance_uuid': 'fake-uuid'}
self._check_result(call_info, 'consoleauth_delete_tokens',
expected_args, version='1.6')
def test_validate_console_port(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.validate_console_port(self.fake_context,
'fake-uuid', 'fake-port', 'fake-type')
expected_args = {'instance_uuid': 'fake-uuid',
'console_port': 'fake-port',
'console_type': 'fake-type'}
self._check_result(call_info, 'validate_console_port',
expected_args, version='1.6')
self.assertEqual(result, 'fake_response')
def test_bdm_update_or_create_at_top(self):
fake_bdm = {'id': 2, 'other': 'meow'}
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.bdm_update_or_create_at_top(
self.fake_context, fake_bdm, create='fake-create')
expected_args = {'bdm': fake_bdm, 'create': 'fake-create'}
self._check_result(call_info, 'bdm_update_or_create_at_top',
expected_args, version='1.28')
def test_bdm_destroy_at_top(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.bdm_destroy_at_top(self.fake_context,
'fake-uuid',
device_name='fake-device',
volume_id='fake-vol')
expected_args = {'instance_uuid': 'fake-uuid',
'device_name': 'fake-device',
'volume_id': 'fake-vol'}
self._check_result(call_info, 'bdm_destroy_at_top',
expected_args, version='1.10')
def test_get_migrations(self):
call_info = self._stub_rpc_method('call', None)
filters = {'cell_name': 'ChildCell', 'status': 'confirmed'}
self.cells_rpcapi.get_migrations(self.fake_context, filters)
expected_args = {'filters': filters}
self._check_result(call_info, 'get_migrations', expected_args,
version="1.11")
def test_instance_update_from_api(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.instance_update_from_api(
self.fake_context, 'fake-instance',
expected_vm_state='exp_vm',
expected_task_state='exp_task',
admin_state_reset='admin_reset')
expected_args = {'instance': 'fake-instance',
'expected_vm_state': 'exp_vm',
'expected_task_state': 'exp_task',
'admin_state_reset': 'admin_reset'}
self._check_result(call_info, 'instance_update_from_api',
expected_args, version='1.16')
def test_start_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.start_instance(
self.fake_context, 'fake-instance')
expected_args = {'instance': 'fake-instance'}
self._check_result(call_info, 'start_instance',
expected_args, version='1.12')
def test_stop_instance_cast(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.stop_instance(
self.fake_context, 'fake-instance', do_cast=True,
clean_shutdown=True)
expected_args = {'instance': 'fake-instance',
'do_cast': True,
'clean_shutdown': True}
self._check_result(call_info, 'stop_instance',
expected_args, version='1.31')
def test_stop_instance_call(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.stop_instance(
self.fake_context, 'fake-instance', do_cast=False,
clean_shutdown=True)
expected_args = {'instance': 'fake-instance',
'do_cast': False,
'clean_shutdown': True}
self._check_result(call_info, 'stop_instance',
expected_args, version='1.31')
self.assertEqual(result, 'fake_response')
def test_cell_create(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.cell_create(self.fake_context, 'values')
expected_args = {'values': 'values'}
self._check_result(call_info, 'cell_create',
expected_args, version='1.13')
self.assertEqual(result, 'fake_response')
def test_cell_update(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.cell_update(self.fake_context,
'cell_name', 'values')
expected_args = {'cell_name': 'cell_name',
'values': 'values'}
self._check_result(call_info, 'cell_update',
expected_args, version='1.13')
self.assertEqual(result, 'fake_response')
def test_cell_delete(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.cell_delete(self.fake_context,
'cell_name')
expected_args = {'cell_name': 'cell_name'}
self._check_result(call_info, 'cell_delete',
expected_args, version='1.13')
self.assertEqual(result, 'fake_response')
def test_cell_get(self):
call_info = self._stub_rpc_method('call', 'fake_response')
result = self.cells_rpcapi.cell_get(self.fake_context,
'cell_name')
expected_args = {'cell_name': 'cell_name'}
self._check_result(call_info, 'cell_get',
expected_args, version='1.13')
self.assertEqual(result, 'fake_response')
def test_reboot_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.reboot_instance(
self.fake_context, 'fake-instance',
block_device_info='ignored', reboot_type='HARD')
expected_args = {'instance': 'fake-instance',
'reboot_type': 'HARD'}
self._check_result(call_info, 'reboot_instance',
expected_args, version='1.14')
def test_pause_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.pause_instance(
self.fake_context, 'fake-instance')
expected_args = {'instance': 'fake-instance'}
self._check_result(call_info, 'pause_instance',
expected_args, version='1.19')
def test_unpause_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.unpause_instance(
self.fake_context, 'fake-instance')
expected_args = {'instance': 'fake-instance'}
self._check_result(call_info, 'unpause_instance',
expected_args, version='1.19')
def test_suspend_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.suspend_instance(
self.fake_context, 'fake-instance')
expected_args = {'instance': 'fake-instance'}
self._check_result(call_info, 'suspend_instance',
expected_args, version='1.15')
def test_resume_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.resume_instance(
self.fake_context, 'fake-instance')
expected_args = {'instance': 'fake-instance'}
self._check_result(call_info, 'resume_instance',
expected_args, version='1.15')
def test_terminate_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.terminate_instance(self.fake_context,
'fake-instance', [])
expected_args = {'instance': 'fake-instance'}
self._check_result(call_info, 'terminate_instance',
expected_args, version='1.18')
def test_soft_delete_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.soft_delete_instance(self.fake_context,
'fake-instance')
expected_args = {'instance': 'fake-instance'}
self._check_result(call_info, 'soft_delete_instance',
expected_args, version='1.18')
def test_resize_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.resize_instance(self.fake_context,
'fake-instance',
dict(cow='moo'),
'fake-hint',
'fake-flavor',
'fake-reservations',
clean_shutdown=True)
expected_args = {'instance': 'fake-instance',
'flavor': 'fake-flavor',
'extra_instance_updates': dict(cow='moo'),
'clean_shutdown': True}
self._check_result(call_info, 'resize_instance',
expected_args, version='1.33')
def test_live_migrate_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.live_migrate_instance(self.fake_context,
'fake-instance',
'fake-host',
'fake-block',
'fake-commit')
expected_args = {'instance': 'fake-instance',
'block_migration': 'fake-block',
'disk_over_commit': 'fake-commit',
'host_name': 'fake-host'}
self._check_result(call_info, 'live_migrate_instance',
expected_args, version='1.20')
def test_revert_resize(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.revert_resize(self.fake_context,
'fake-instance',
'fake-migration',
'fake-dest',
'resvs')
expected_args = {'instance': 'fake-instance'}
self._check_result(call_info, 'revert_resize',
expected_args, version='1.21')
def test_confirm_resize(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.confirm_resize(self.fake_context,
'fake-instance',
'fake-migration',
'fake-source',
'resvs')
expected_args = {'instance': 'fake-instance'}
self._check_result(call_info, 'confirm_resize',
expected_args, version='1.21')
def test_reset_network(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.reset_network(self.fake_context,
'fake-instance')
expected_args = {'instance': 'fake-instance'}
self._check_result(call_info, 'reset_network',
expected_args, version='1.22')
def test_inject_network_info(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.inject_network_info(self.fake_context,
'fake-instance')
expected_args = {'instance': 'fake-instance'}
self._check_result(call_info, 'inject_network_info',
expected_args, version='1.23')
def test_snapshot_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.snapshot_instance(self.fake_context,
'fake-instance',
'image-id')
expected_args = {'instance': 'fake-instance',
'image_id': 'image-id'}
self._check_result(call_info, 'snapshot_instance',
expected_args, version='1.24')
def test_backup_instance(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.backup_instance(self.fake_context,
'fake-instance',
'image-id',
'backup-type',
'rotation')
expected_args = {'instance': 'fake-instance',
'image_id': 'image-id',
'backup_type': 'backup-type',
'rotation': 'rotation'}
self._check_result(call_info, 'backup_instance',
expected_args, version='1.24')
def test_set_admin_password(self):
call_info = self._stub_rpc_method('cast', None)
self.cells_rpcapi.set_admin_password(self.fake_context,
'fake-instance', 'fake-password')
expected_args = {'instance': 'fake-instance',
'new_pass': 'fake-password'}
self._check_result(call_info, 'set_admin_password',
expected_args, version='1.29')
|
|
'''
Created on 11 mrt. 2013
@author: sander
'''
from ipaddress import ip_address
from pylisp.application.lispd.address_tree.authoritative_container_node import AuthContainerNode
from pylisp.application.lispd.address_tree.base import AbstractNode
from pylisp.application.lispd.address_tree.map_server_node import MapServerNode
from pylisp.application.lispd.send_message import send_message
from pylisp.application.lispd.utils.prefix import determine_instance_id_and_afi, resolve_path
from pylisp.packet.lisp.control.locator_record import LocatorRecord
from pylisp.packet.lisp.control.map_referral import MapReferralMessage
from pylisp.packet.lisp.control.map_referral_record import MapReferralRecord
import logging
# Get the logger
logger = logging.getLogger(__name__)
class DDTReferralNode(AbstractNode):
def __init__(self, prefix, ddt_nodes=None):
super(DDTReferralNode, self).__init__(prefix)
self.ddt_nodes = set()
if ddt_nodes:
self.update(ddt_nodes)
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.prefix, self.ddt_nodes)
def __iter__(self):
return iter(self.ddt_nodes)
def __len__(self):
return len(self.ddt_nodes)
def add(self, ddt_node):
ddt_node = ip_address(ddt_node)
# Add the new node
self.ddt_nodes.add(ddt_node)
def clear(self):
self.ddt_nodes = set()
def __contains__(self, ddt_node):
return ddt_node in self.ddt_nodes
def copy(self):
return self.__class__(self.prefix, self.ddt_nodes)
def discard(self, ddt_node):
self.ddt_nodes.discard(ddt_node)
def remove(self, ddt_node):
self.ddt_nodes.remove(ddt_node)
def update(self, ddt_nodes):
for ddt_node in ddt_nodes:
self.add(ddt_node)
def get_referral(self):
locators = []
for ddt_node in self.ddt_nodes:
locator = LocatorRecord(priority=0, weight=0,
m_priority=0, m_weight=0,
reachable=True, locator=ddt_node)
locators.append(locator)
referral = MapReferralRecord(ttl=1440,
action=MapReferralRecord.ACT_NODE_REFERRAL,
authoritative=True,
eid_prefix=self.prefix,
locator_records=locators)
return referral
def send_answer(received_message, referral):
map_request = received_message.inner_message
# Put it in a reply packet
reply = MapReferralMessage(nonce=map_request.nonce,
records=[referral])
# Send the reply over UDP
send_message(message=reply,
my_sockets=[received_message.socket],
destinations=[received_message.source[0]],
port=received_message.source[1])
def send_referral(received_message, tree_node):
logger.debug("Sending NODE_REFERRAL response for message %d", received_message.message_nr)
map_request = received_message.inner_message
locators = []
for ddt_node in tree_node:
locator = LocatorRecord(priority=0, weight=0,
m_priority=0, m_weight=0,
reachable=True, locator=ddt_node)
locators.append(locator)
referral = MapReferralRecord(ttl=1440,
action=MapReferralRecord.ACT_NODE_REFERRAL,
authoritative=True,
eid_prefix=map_request.eid_prefixes[0],
locator_records=locators)
send_answer(received_message, referral)
def send_delegation_hole(received_message):
logger.debug("Sending DELEGATION_HOLE response for message %d", received_message.message_nr)
map_request = received_message.inner_message
# We are authoritative and no matching targets, we seem to have a hole
referral = MapReferralRecord(ttl=15,
authoritative=True,
action=MapReferralRecord.ACT_DELEGATION_HOLE,
eid_prefix=map_request.eid_prefixes[0])
send_answer(received_message, referral)
def send_not_authoritative(received_message):
logger.debug("Sending NOT_AUTHORITATIVE response for message %d", received_message.message_nr)
map_request = received_message.inner_message
# No matching prefixes, we don't seem to be authoritative
referral = MapReferralRecord(ttl=0,
action=MapReferralRecord.ACT_NOT_AUTHORITATIVE,
incomplete=True,
eid_prefix=map_request.eid_prefixes[0])
send_answer(received_message, referral)
def send_ms_ack(received_message, ms_prefix, other_map_servers=None):
logger.debug("Sending MS_ACK response for message %d", received_message.message_nr)
other_map_servers = other_map_servers or []
locators = []
for ddt_node in other_map_servers:
locator = LocatorRecord(priority=0, weight=0,
m_priority=0, m_weight=0,
reachable=True, locator=ddt_node)
locators.append(locator)
# MapServer forwarded the request
referral = MapReferralRecord(ttl=1440,
action=MapReferralRecord.ACT_MS_NOT_REGISTERED,
incomplete=(len(locators) == 0),
eid_prefix=ms_prefix,
locator_records=locators)
send_answer(received_message, referral)
def send_ms_not_registered(received_message, ms_prefix, other_map_servers=None):
logger.debug("Sending MS_NOT_REGISTERED response for message %d", received_message.message_nr)
other_map_servers = other_map_servers or []
locators = []
for ddt_node in other_map_servers:
locator = LocatorRecord(priority=0, weight=0,
m_priority=0, m_weight=0,
reachable=True, locator=ddt_node)
locators.append(locator)
# No data in the MapServer
referral = MapReferralRecord(ttl=1,
action=MapReferralRecord.ACT_MS_NOT_REGISTERED,
incomplete=(len(locators) == 0),
eid_prefix=ms_prefix,
locator_records=locators)
send_answer(received_message, referral)
def handle_ddt_map_request(received_message, control_plane_sockets, data_plane_sockets):
ecm = received_message.message
# TODO: Implement security [LISP-Security]
if ecm.security:
logger.error("We can't handle LISP-Security yet")
return
# Look up the address in the tree
map_request = received_message.inner_message
instance_id, afi, req_prefix = determine_instance_id_and_afi(map_request.eid_prefixes[0])
tree_nodes = resolve_path(instance_id, afi, req_prefix)
# Find the handling node and its children
auth_node = None
handling_node = None
more_specific_nodes = []
for tree_node in tree_nodes[::-1]:
# Mark that we are authoritative for this request
if isinstance(tree_node, (AuthContainerNode, MapServerNode)):
auth_node = tree_node
# Do we already have a handler?
if handling_node is not None:
# We have a handler, collect the more specific nodes
more_specific_nodes.append(tree_node)
else:
if isinstance(tree_node, DDTReferralNode):
# DDTReferralNodes are an answer by themselves
handling_node = tree_node
break
elif isinstance(tree_node, MapServerNode):
# MapServerNodes handle themselves
handling_node = tree_node
break
else:
# We don't really care about other node types
pass
# Didn't find any handling node
if not handling_node:
# We are not authoritative
send_not_authoritative(received_message)
return
# We have all the information: handle it
if isinstance(handling_node, DDTReferralNode):
# Handle this as a DDT referral
referral = handling_node.get_referral()
send_answer(received_message, referral)
return
elif isinstance(tree_node, MapServerNode):
# Handle this as a DDT Map-Server
# Let he MapServerNode send the Map-Request to the ETR or answer as a proxy
handled = handling_node.handle_map_request(received_message, control_plane_sockets, data_plane_sockets)
# Send DDT response
if handled:
send_ms_ack(received_message=received_message,
ms_prefix=handling_node.prefix,
other_map_servers=(auth_node and auth_node.ddt_nodes or []))
else:
send_ms_not_registered(received_message=received_message,
ms_prefix=handling_node.prefix,
other_map_servers=(auth_node and auth_node.ddt_nodes or []))
elif auth_node:
# We are authoritative and no matching targets, we seem to have a hole
send_delegation_hole(received_message)
else:
# We are not authoritative
send_not_authoritative(received_message)
|
|
import shutil
from unittest import TestCase
import numpy as np
import scipy.linalg as sl
import scipy.optimize as so
from PTMCMCSampler import PTMCMCSampler
class GaussianLikelihood(object):
def __init__(self, ndim=2, pmin=-10, pmax=10):
self.a = np.ones(ndim) * pmin
self.b = np.ones(ndim) * pmax
def lnlikefn(self, x):
return -0.5 * np.sum(x ** 2) - len(x) * 0.5 * np.log(2 * np.pi)
def lnlikefn_grad(self, x):
ll = -0.5 * np.sum(x ** 2) - len(x) * 0.5 * np.log(2 * np.pi)
ll_grad = -x
return ll, ll_grad
def lnpriorfn(self, x):
if np.all(self.a <= x) and np.all(self.b >= x):
return 0.0
else:
return -np.inf
return 0.0
def lnpriorfn_grad(self, x):
return self.lnpriorfn(x), np.zeros_like(x)
def lnpost_grad(self, x):
ll, ll_grad = self.lnlikefn_grad(x)
lp, lp_grad = self.lnpriorfn_grad(x)
return ll + lp, ll_grad + lp_grad
def lnpost(self, x):
return self.lnpost_grad(x)[0]
def hessian(self, x):
return -np.eye(len(x))
class intervalTransform(object):
"""
Wrapper class of the likelihood for Hamiltonian samplers. This implements a
coordinate transformation for all parameters from an interval to all real numbers.
"""
def __init__(self, likob, pmin=None, pmax=None):
"""Initialize the intervalLikelihood with a ptaLikelihood object"""
self.likob = likob
if pmin is None:
self.a = likob.a
else:
self.a = pmin * np.ones_like(likob.a)
if pmax is None:
self.b = likob.b
else:
self.b = pmax * np.ones_like(likob.b)
def forward(self, x):
"""Forward transform the real coordinates (on the interval) to the
transformed coordinates (on all real numbers)
"""
p = np.atleast_2d(x.copy())
posinf, neginf = (self.a == x), (self.b == x)
m = ~(posinf | neginf)
p[:, m] = np.log((p[:, m] - self.a[m]) / (self.b[m] - p[:, m]))
p[:, posinf] = np.inf
p[:, neginf] = -np.inf
return p.reshape(x.shape)
def backward(self, p):
"""Backward transform the transformed coordinates (on all real numbers)
to the real coordinates (on the interval)
"""
x = np.atleast_2d(p.copy())
x[:, :] = (self.b[:] - self.a[:]) * np.exp(x[:, :]) / (1 + np.exp(x[:, :])) + self.a[:]
return x.reshape(p.shape)
def logjacobian_grad(self, p):
"""Return the log of the Jacobian at point p"""
lj = np.sum(np.log(self.b[:] - self.a[:]) + p[:] - 2 * np.log(1.0 + np.exp(p[:])))
lj_grad = np.zeros_like(p)
lj_grad[:] = (1 - np.exp(p[:])) / (1 + np.exp(p[:]))
return lj, lj_grad
def dxdp(self, p):
"""Derivative of x wrt p (jacobian for chain-rule) - diagonal"""
pp = np.atleast_2d(p)
d = np.ones_like(pp)
d[:, :] = (self.b[:] - self.a[:]) * np.exp(pp[:, :]) / (1 + np.exp(pp[:, :])) ** 2
return d.reshape(p.shape)
def d2xd2p(self, p):
"""Derivative of x wrt p (jacobian for chain-rule) - diagonal"""
pp = np.atleast_2d(p)
d = np.zeros_like(pp)
d[:, :] = (self.b[:] - self.a[:]) * (np.exp(2 * pp[:, :]) - np.exp(pp[:, :])) / (1 + np.exp(pp[:, :])) ** 3
return d.reshape(p.shape)
def logjac_hessian(self, p):
"""The Hessian of the log-jacobian"""
# p should not be more than one-dimensional
assert len(p.shape) == 1
return np.diag(-2 * np.exp(p) / (1 + np.exp(p)) ** 2)
def lnlikefn_grad(self, p, **kwargs):
"""The log-likelihood in the new coordinates"""
x = self.backward(p)
ll, ll_grad = self.likob.lnlikefn_grad(x, **kwargs)
lj, lj_grad = self.logjacobian_grad(p)
return ll + lj, ll_grad * self.dxdp(p) + lj_grad
def lnlikefn(self, p, **kwargs):
return self.lnlikefn_grad(p)[0]
def lnpriorfn_grad(self, p, **kwargs):
"""The log-prior in the new coordinates. Do not include the Jacobian"""
x = self.backward(p)
lp, lp_grad = self.likob.lnpriorfn_grad(x)
return lp, lp_grad * self.dxdp(p)
def lnpriorfn(self, p, **kwargs):
return self.lnpriorfn_grad(p)[0]
def logpostfn_grad(self, p, **kwargs):
"""The log-posterior in the new coordinates"""
x = self.backward(p)
lp, lp_grad = self.likob.lnpost_grad(x)
lj, lj_grad = self.logjacobian_grad(p)
return lp + lj, lp_grad * self.dxdp(p) + lj_grad
def hessian(self, p):
"""The Hessian matrix in the new coordinates"""
# p should not be more than one-dimensional
assert len(p.shape) == 1
# Get quantities from un-transformed distribution
x = self.backward(p)
orig_hessian = self.likob.hessian(x)
_, orig_lp_grad = self.likob.lnpost_grad(x)
# Transformation properties
hessian = self.logjac_hessian(p)
dxdpf = np.diag(self.dxdp(p))
hessian += np.dot(dxdpf.T, np.dot(orig_hessian, dxdpf))
hessian -= np.diag(self.d2xd2p(p) * orig_lp_grad)
return hessian
class TestNuts(TestCase):
@classmethod
def tearDownClass(cls):
shutil.rmtree("chains")
def test_nuts(self):
ndim = 40
glo = GaussianLikelihood(ndim=ndim, pmin=0.0, pmax=10.0)
glt = intervalTransform(glo, pmin=0.0, pmax=10)
gl = glt
p0 = np.ones(ndim) * 0.01
# Maximize using scipy
result = so.minimize(
lambda x: -gl.lnlikefn(x),
p0,
jac=lambda x: -gl.lnlikefn_grad(x)[1],
method="Newton-CG",
hess=lambda x: -gl.hessian(x),
options={"disp": True},
)
# Set the start position and the covariance
p0 = result["x"]
h0 = gl.hessian(p0)
cov = sl.cho_solve(sl.cho_factor(-h0), np.eye(len(h0)))
sampler = PTMCMCSampler.PTSampler(
ndim,
gl.lnlikefn,
gl.lnpriorfn,
np.copy(cov),
logl_grad=gl.lnlikefn_grad,
logp_grad=gl.lnpriorfn_grad,
outDir="./chains",
)
sampler.sample(
p0,
1000,
burn=500,
thin=1,
covUpdate=500,
SCAMweight=10,
AMweight=10,
DEweight=10,
NUTSweight=10,
HMCweight=10,
MALAweight=0,
HMCsteps=100,
HMCstepsize=0.4,
)
|
|
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
"""
PySpark supports custom serializers for transferring data; this can improve
performance.
By default, PySpark uses L{PickleSerializer} to serialize objects using Python's
C{cPickle} serializer, which can serialize nearly any Python object.
Other serializers, like L{MarshalSerializer}, support fewer datatypes but can be
faster.
The serializer is chosen when creating L{SparkContext}:
>>> from pyspark.context import SparkContext
>>> from pyspark.serializers import MarshalSerializer
>>> sc = SparkContext('local', 'test', serializer=MarshalSerializer())
>>> sc.parallelize(list(range(1000))).map(lambda x: 2 * x).take(10)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> sc.stop()
PySpark serializes objects in batches; by default, the batch size is chosen based
on the size of objects and is also configurable by SparkContext's C{batchSize}
parameter:
>>> sc = SparkContext('local', 'test', batchSize=2)
>>> rdd = sc.parallelize(range(16), 4).map(lambda x: x)
Behind the scenes, this creates a JavaRDD with four partitions, each of
which contains two batches of two objects:
>>> rdd.glom().collect()
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
>>> int(rdd._jrdd.count())
8
>>> sc.stop()
"""
import sys
from itertools import chain, product
import marshal
import struct
import types
import collections
import zlib
import itertools
if sys.version < '3':
import cPickle as pickle
protocol = 2
from itertools import izip as zip, imap as map
else:
import pickle
protocol = 3
xrange = range
from pyspark import cloudpickle
from pyspark.util import _exception_message
__all__ = ["PickleSerializer", "MarshalSerializer", "UTF8Deserializer"]
class SpecialLengths(object):
END_OF_DATA_SECTION = -1
PYTHON_EXCEPTION_THROWN = -2
TIMING_DATA = -3
END_OF_STREAM = -4
NULL = -5
START_ARROW_STREAM = -6
class Serializer(object):
def dump_stream(self, iterator, stream):
"""
Serialize an iterator of objects to the output stream.
"""
raise NotImplementedError
def load_stream(self, stream):
"""
Return an iterator of deserialized objects from the input stream.
"""
raise NotImplementedError
def _load_stream_without_unbatching(self, stream):
"""
Return an iterator of deserialized batches (iterable) of objects from the input stream.
If the serializer does not operate on batches the default implementation returns an
iterator of single element lists.
"""
return map(lambda x: [x], self.load_stream(stream))
# Note: our notion of "equality" is that output generated by
# equal serializers can be deserialized using the same serializer.
# This default implementation handles the simple cases;
# subclasses should override __eq__ as appropriate.
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return "%s()" % self.__class__.__name__
def __hash__(self):
return hash(str(self))
class FramedSerializer(Serializer):
"""
Serializer that writes objects as a stream of (length, data) pairs,
where C{length} is a 32-bit integer and data is C{length} bytes.
"""
def __init__(self):
# On Python 2.6, we can't write bytearrays to streams, so we need to convert them
# to strings first. Check if the version number is that old.
self._only_write_strings = sys.version_info[0:2] <= (2, 6)
def dump_stream(self, iterator, stream):
for obj in iterator:
self._write_with_length(obj, stream)
def load_stream(self, stream):
while True:
try:
yield self._read_with_length(stream)
except EOFError:
return
def _write_with_length(self, obj, stream):
serialized = self.dumps(obj)
if serialized is None:
raise ValueError("serialized value should not be None")
if len(serialized) > (1 << 31):
raise ValueError("can not serialize object larger than 2G")
write_int(len(serialized), stream)
if self._only_write_strings:
stream.write(str(serialized))
else:
stream.write(serialized)
def _read_with_length(self, stream):
length = read_int(stream)
if length == SpecialLengths.END_OF_DATA_SECTION:
raise EOFError
elif length == SpecialLengths.NULL:
return None
obj = stream.read(length)
if len(obj) < length:
raise EOFError
return self.loads(obj)
def dumps(self, obj):
"""
Serialize an object into a byte array.
When batching is used, this will be called with an array of objects.
"""
raise NotImplementedError
def loads(self, obj):
"""
Deserialize an object from a byte array.
"""
raise NotImplementedError
class ArrowStreamSerializer(Serializer):
"""
Serializes Arrow record batches as a stream.
"""
def dump_stream(self, iterator, stream):
import pyarrow as pa
writer = None
try:
for batch in iterator:
if writer is None:
writer = pa.RecordBatchStreamWriter(stream, batch.schema)
writer.write_batch(batch)
finally:
if writer is not None:
writer.close()
def load_stream(self, stream):
import pyarrow as pa
reader = pa.open_stream(stream)
for batch in reader:
yield batch
def __repr__(self):
return "ArrowStreamSerializer"
def _create_batch(series, timezone):
"""
Create an Arrow record batch from the given pandas.Series or list of Series, with optional type.
:param series: A single pandas.Series, list of Series, or list of (series, arrow_type)
:param timezone: A timezone to respect when handling timestamp values
:return: Arrow RecordBatch
"""
import decimal
from distutils.version import LooseVersion
import pyarrow as pa
from pyspark.sql.types import _check_series_convert_timestamps_internal
# Make input conform to [(series1, type1), (series2, type2), ...]
if not isinstance(series, (list, tuple)) or \
(len(series) == 2 and isinstance(series[1], pa.DataType)):
series = [series]
series = ((s, None) if not isinstance(s, (list, tuple)) else s for s in series)
def create_array(s, t):
mask = s.isnull()
# Ensure timestamp series are in expected form for Spark internal representation
# TODO: maybe don't need None check anymore as of Arrow 0.9.1
if t is not None and pa.types.is_timestamp(t):
s = _check_series_convert_timestamps_internal(s.fillna(0), timezone)
# TODO: need cast after Arrow conversion, ns values cause error with pandas 0.19.2
return pa.Array.from_pandas(s, mask=mask).cast(t, safe=False)
elif t is not None and pa.types.is_string(t) and sys.version < '3':
# TODO: need decode before converting to Arrow in Python 2
# TODO: don't need as of Arrow 0.9.1
return pa.Array.from_pandas(s.apply(
lambda v: v.decode("utf-8") if isinstance(v, str) else v), mask=mask, type=t)
elif t is not None and pa.types.is_decimal(t) and \
LooseVersion("0.9.0") <= LooseVersion(pa.__version__) < LooseVersion("0.10.0"):
# TODO: see ARROW-2432. Remove when the minimum PyArrow version becomes 0.10.0.
return pa.Array.from_pandas(s.apply(
lambda v: decimal.Decimal('NaN') if v is None else v), mask=mask, type=t)
return pa.Array.from_pandas(s, mask=mask, type=t)
arrs = [create_array(s, t) for s, t in series]
return pa.RecordBatch.from_arrays(arrs, ["_%d" % i for i in xrange(len(arrs))])
class ArrowStreamPandasSerializer(Serializer):
"""
Serializes Pandas.Series as Arrow data with Arrow streaming format.
"""
def __init__(self, timezone):
super(ArrowStreamPandasSerializer, self).__init__()
self._timezone = timezone
def arrow_to_pandas(self, arrow_column):
from pyspark.sql.types import from_arrow_type, \
_check_series_convert_date, _check_series_localize_timestamps
s = arrow_column.to_pandas()
s = _check_series_convert_date(s, from_arrow_type(arrow_column.type))
s = _check_series_localize_timestamps(s, self._timezone)
return s
def dump_stream(self, iterator, stream):
"""
Make ArrowRecordBatches from Pandas Series and serialize. Input is a single series or
a list of series accompanied by an optional pyarrow type to coerce the data to.
"""
import pyarrow as pa
writer = None
try:
for series in iterator:
batch = _create_batch(series, self._timezone)
if writer is None:
write_int(SpecialLengths.START_ARROW_STREAM, stream)
writer = pa.RecordBatchStreamWriter(stream, batch.schema)
writer.write_batch(batch)
finally:
if writer is not None:
writer.close()
def load_stream(self, stream):
"""
Deserialize ArrowRecordBatches to an Arrow table and return as a list of pandas.Series.
"""
import pyarrow as pa
reader = pa.open_stream(stream)
for batch in reader:
yield [self.arrow_to_pandas(c) for c in pa.Table.from_batches([batch]).itercolumns()]
def __repr__(self):
return "ArrowStreamPandasSerializer"
class BatchedSerializer(Serializer):
"""
Serializes a stream of objects in batches by calling its wrapped
Serializer with streams of objects.
"""
UNLIMITED_BATCH_SIZE = -1
UNKNOWN_BATCH_SIZE = 0
def __init__(self, serializer, batchSize=UNLIMITED_BATCH_SIZE):
self.serializer = serializer
self.batchSize = batchSize
def _batched(self, iterator):
if self.batchSize == self.UNLIMITED_BATCH_SIZE:
yield list(iterator)
elif hasattr(iterator, "__len__") and hasattr(iterator, "__getslice__"):
n = len(iterator)
for i in xrange(0, n, self.batchSize):
yield iterator[i: i + self.batchSize]
else:
items = []
count = 0
for item in iterator:
items.append(item)
count += 1
if count == self.batchSize:
yield items
items = []
count = 0
if items:
yield items
def dump_stream(self, iterator, stream):
self.serializer.dump_stream(self._batched(iterator), stream)
def load_stream(self, stream):
return chain.from_iterable(self._load_stream_without_unbatching(stream))
def _load_stream_without_unbatching(self, stream):
return self.serializer.load_stream(stream)
def __repr__(self):
return "BatchedSerializer(%s, %d)" % (str(self.serializer), self.batchSize)
class FlattenedValuesSerializer(BatchedSerializer):
"""
Serializes a stream of list of pairs, split the list of values
which contain more than a certain number of objects to make them
have similar sizes.
"""
def __init__(self, serializer, batchSize=10):
BatchedSerializer.__init__(self, serializer, batchSize)
def _batched(self, iterator):
n = self.batchSize
for key, values in iterator:
for i in range(0, len(values), n):
yield key, values[i:i + n]
def load_stream(self, stream):
return self.serializer.load_stream(stream)
def __repr__(self):
return "FlattenedValuesSerializer(%s, %d)" % (self.serializer, self.batchSize)
class AutoBatchedSerializer(BatchedSerializer):
"""
Choose the size of batch automatically based on the size of object
"""
def __init__(self, serializer, bestSize=1 << 16):
BatchedSerializer.__init__(self, serializer, self.UNKNOWN_BATCH_SIZE)
self.bestSize = bestSize
def dump_stream(self, iterator, stream):
batch, best = 1, self.bestSize
iterator = iter(iterator)
while True:
vs = list(itertools.islice(iterator, batch))
if not vs:
break
bytes = self.serializer.dumps(vs)
write_int(len(bytes), stream)
stream.write(bytes)
size = len(bytes)
if size < best:
batch *= 2
elif size > best * 10 and batch > 1:
batch //= 2
def __repr__(self):
return "AutoBatchedSerializer(%s)" % self.serializer
class CartesianDeserializer(Serializer):
"""
Deserializes the JavaRDD cartesian() of two PythonRDDs.
Due to pyspark batching we cannot simply use the result of the Java RDD cartesian,
we additionally need to do the cartesian within each pair of batches.
"""
def __init__(self, key_ser, val_ser):
self.key_ser = key_ser
self.val_ser = val_ser
def _load_stream_without_unbatching(self, stream):
key_batch_stream = self.key_ser._load_stream_without_unbatching(stream)
val_batch_stream = self.val_ser._load_stream_without_unbatching(stream)
for (key_batch, val_batch) in zip(key_batch_stream, val_batch_stream):
# for correctness with repeated cartesian/zip this must be returned as one batch
yield product(key_batch, val_batch)
def load_stream(self, stream):
return chain.from_iterable(self._load_stream_without_unbatching(stream))
def __repr__(self):
return "CartesianDeserializer(%s, %s)" % \
(str(self.key_ser), str(self.val_ser))
class PairDeserializer(Serializer):
"""
Deserializes the JavaRDD zip() of two PythonRDDs.
Due to pyspark batching we cannot simply use the result of the Java RDD zip,
we additionally need to do the zip within each pair of batches.
"""
def __init__(self, key_ser, val_ser):
self.key_ser = key_ser
self.val_ser = val_ser
def _load_stream_without_unbatching(self, stream):
key_batch_stream = self.key_ser._load_stream_without_unbatching(stream)
val_batch_stream = self.val_ser._load_stream_without_unbatching(stream)
for (key_batch, val_batch) in zip(key_batch_stream, val_batch_stream):
# For double-zipped RDDs, the batches can be iterators from other PairDeserializer,
# instead of lists. We need to convert them to lists if needed.
key_batch = key_batch if hasattr(key_batch, '__len__') else list(key_batch)
val_batch = val_batch if hasattr(val_batch, '__len__') else list(val_batch)
if len(key_batch) != len(val_batch):
raise ValueError("Can not deserialize PairRDD with different number of items"
" in batches: (%d, %d)" % (len(key_batch), len(val_batch)))
# for correctness with repeated cartesian/zip this must be returned as one batch
yield zip(key_batch, val_batch)
def load_stream(self, stream):
return chain.from_iterable(self._load_stream_without_unbatching(stream))
def __repr__(self):
return "PairDeserializer(%s, %s)" % (str(self.key_ser), str(self.val_ser))
class NoOpSerializer(FramedSerializer):
def loads(self, obj):
return obj
def dumps(self, obj):
return obj
# Hack namedtuple, make it picklable
__cls = {}
def _restore(name, fields, value):
""" Restore an object of namedtuple"""
k = (name, fields)
cls = __cls.get(k)
if cls is None:
cls = collections.namedtuple(name, fields)
__cls[k] = cls
return cls(*value)
def _hack_namedtuple(cls):
""" Make class generated by namedtuple picklable """
name = cls.__name__
fields = cls._fields
def __reduce__(self):
return (_restore, (name, fields, tuple(self)))
cls.__reduce__ = __reduce__
cls._is_namedtuple_ = True
return cls
def _hijack_namedtuple():
""" Hack namedtuple() to make it picklable """
# hijack only one time
if hasattr(collections.namedtuple, "__hijack"):
return
global _old_namedtuple # or it will put in closure
global _old_namedtuple_kwdefaults # or it will put in closure too
def _copy_func(f):
return types.FunctionType(f.__code__, f.__globals__, f.__name__,
f.__defaults__, f.__closure__)
def _kwdefaults(f):
# __kwdefaults__ contains the default values of keyword-only arguments which are
# introduced from Python 3. The possible cases for __kwdefaults__ in namedtuple
# are as below:
#
# - Does not exist in Python 2.
# - Returns None in <= Python 3.5.x.
# - Returns a dictionary containing the default values to the keys from Python 3.6.x
# (See https://bugs.python.org/issue25628).
kargs = getattr(f, "__kwdefaults__", None)
if kargs is None:
return {}
else:
return kargs
_old_namedtuple = _copy_func(collections.namedtuple)
_old_namedtuple_kwdefaults = _kwdefaults(collections.namedtuple)
def namedtuple(*args, **kwargs):
for k, v in _old_namedtuple_kwdefaults.items():
kwargs[k] = kwargs.get(k, v)
cls = _old_namedtuple(*args, **kwargs)
return _hack_namedtuple(cls)
# replace namedtuple with the new one
collections.namedtuple.__globals__["_old_namedtuple_kwdefaults"] = _old_namedtuple_kwdefaults
collections.namedtuple.__globals__["_old_namedtuple"] = _old_namedtuple
collections.namedtuple.__globals__["_hack_namedtuple"] = _hack_namedtuple
collections.namedtuple.__code__ = namedtuple.__code__
collections.namedtuple.__hijack = 1
# hack the cls already generated by namedtuple.
# Those created in other modules can be pickled as normal,
# so only hack those in __main__ module
for n, o in sys.modules["__main__"].__dict__.items():
if (type(o) is type and o.__base__ is tuple
and hasattr(o, "_fields")
and "__reduce__" not in o.__dict__):
_hack_namedtuple(o) # hack inplace
_hijack_namedtuple()
class PickleSerializer(FramedSerializer):
"""
Serializes objects using Python's pickle serializer:
http://docs.python.org/2/library/pickle.html
This serializer supports nearly any Python object, but may
not be as fast as more specialized serializers.
"""
def dumps(self, obj):
return pickle.dumps(obj, protocol)
if sys.version >= '3':
def loads(self, obj, encoding="bytes"):
return pickle.loads(obj, encoding=encoding)
else:
def loads(self, obj, encoding=None):
return pickle.loads(obj)
class CloudPickleSerializer(PickleSerializer):
def dumps(self, obj):
try:
return cloudpickle.dumps(obj, 2)
except pickle.PickleError:
raise
except Exception as e:
emsg = _exception_message(e)
if "'i' format requires" in emsg:
msg = "Object too large to serialize: %s" % emsg
else:
msg = "Could not serialize object: %s: %s" % (e.__class__.__name__, emsg)
cloudpickle.print_exec(sys.stderr)
raise pickle.PicklingError(msg)
class MarshalSerializer(FramedSerializer):
"""
Serializes objects using Python's Marshal serializer:
http://docs.python.org/2/library/marshal.html
This serializer is faster than PickleSerializer but supports fewer datatypes.
"""
def dumps(self, obj):
return marshal.dumps(obj)
def loads(self, obj):
return marshal.loads(obj)
class AutoSerializer(FramedSerializer):
"""
Choose marshal or pickle as serialization protocol automatically
"""
def __init__(self):
FramedSerializer.__init__(self)
self._type = None
def dumps(self, obj):
if self._type is not None:
return b'P' + pickle.dumps(obj, -1)
try:
return b'M' + marshal.dumps(obj)
except Exception:
self._type = b'P'
return b'P' + pickle.dumps(obj, -1)
def loads(self, obj):
_type = obj[0]
if _type == b'M':
return marshal.loads(obj[1:])
elif _type == b'P':
return pickle.loads(obj[1:])
else:
raise ValueError("invalid serialization type: %s" % _type)
class CompressedSerializer(FramedSerializer):
"""
Compress the serialized data
"""
def __init__(self, serializer):
FramedSerializer.__init__(self)
assert isinstance(serializer, FramedSerializer), "serializer must be a FramedSerializer"
self.serializer = serializer
def dumps(self, obj):
return zlib.compress(self.serializer.dumps(obj), 1)
def loads(self, obj):
return self.serializer.loads(zlib.decompress(obj))
def __repr__(self):
return "CompressedSerializer(%s)" % self.serializer
class UTF8Deserializer(Serializer):
"""
Deserializes streams written by String.getBytes.
"""
def __init__(self, use_unicode=True):
self.use_unicode = use_unicode
def loads(self, stream):
length = read_int(stream)
if length == SpecialLengths.END_OF_DATA_SECTION:
raise EOFError
elif length == SpecialLengths.NULL:
return None
s = stream.read(length)
return s.decode("utf-8") if self.use_unicode else s
def load_stream(self, stream):
try:
while True:
yield self.loads(stream)
except struct.error:
return
except EOFError:
return
def __repr__(self):
return "UTF8Deserializer(%s)" % self.use_unicode
def read_long(stream):
length = stream.read(8)
if not length:
raise EOFError
return struct.unpack("!q", length)[0]
def write_long(value, stream):
stream.write(struct.pack("!q", value))
def pack_long(value):
return struct.pack("!q", value)
def read_int(stream):
length = stream.read(4)
if not length:
raise EOFError
return struct.unpack("!i", length)[0]
def write_int(value, stream):
stream.write(struct.pack("!i", value))
def read_bool(stream):
length = stream.read(1)
if not length:
raise EOFError
return struct.unpack("!?", length)[0]
def write_with_length(obj, stream):
write_int(len(obj), stream)
stream.write(obj)
if __name__ == '__main__':
import doctest
(failure_count, test_count) = doctest.testmod()
if failure_count:
sys.exit(-1)
|
|
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Test MirroredVariable in MirroredStrategy and MultiWorkerMirroredStrategy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.distribute import collective_all_reduce_strategy
from tensorflow.python.distribute import combinations
from tensorflow.python.distribute import distribution_strategy_context as ds_context
from tensorflow.python.distribute import strategy_combinations
from tensorflow.python.distribute import values
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.eager import test
from tensorflow.python.framework import config
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import ops
from tensorflow.python.layers import core
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import rnn
from tensorflow.python.ops import rnn_cell_impl
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
def _replica_id():
replica_id = ds_context.get_replica_context().replica_id_in_sync_group
if not isinstance(replica_id, ops.Tensor):
replica_id = constant_op.constant(replica_id)
return replica_id
def _mimic_two_cpus():
cpus = config.list_physical_devices("CPU")
config.set_logical_device_configuration(cpus[0], [
context.LogicalDeviceConfiguration(),
context.LogicalDeviceConfiguration(),
])
@combinations.generate(
combinations.combine(
distribution=[
strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
combinations.NamedDistribution(
"Collective2CPUs",
# pylint: disable=g-long-lambda
lambda: collective_all_reduce_strategy.
CollectiveAllReduceStrategy._from_local_devices((
"/device:CPU:0", "/device:CPU:1")),
required_gpus=0)
],
mode=["graph", "eager"]))
class MirroredVariableCreationTest(test.TestCase):
"""Base class that tests mirrored variable creator.
Currently it assumes all strategy objects have two replicas.
"""
@classmethod
def setUpClass(cls):
_mimic_two_cpus()
# TODO(priyag): Modify more tests to use this helper and check more
# properties.
def _test_mv_properties(self, var, name, strategy):
self.assertIsInstance(var, values.MirroredVariable)
self.assertEqual(name, var.name)
self.assertIs(strategy, var.distribute_strategy)
for d in var.devices:
self.assertEqual(d, var.get(d).device)
self.assertIs(strategy, var.get(d)._distribute_strategy) # pylint: disable=protected-access
def testVariableInFuncGraph(self, distribution):
def model_fn():
v = variable_scope.variable(2.0, name="bar")
ds_context.get_replica_context().merge_call(lambda _: _)
return v
with func_graph.FuncGraph("fg").as_default(), distribution.scope():
v1 = variable_scope.variable(1.0, name="foo")
v2 = distribution.extended.call_for_each_replica(model_fn)
self._test_mv_properties(v1, "foo:0", distribution)
self._test_mv_properties(v2, "bar:0", distribution)
def testVariableWithTensorInitialValueInFunction(self, distribution):
if not context.executing_eagerly():
self.skipTest("`tf.function` is an eager-only feature")
v = [None]
def model_fn():
if v[0] is None:
init_val = array_ops.zeros([])
v[0] = variables.Variable(init_val)
ds_context.get_replica_context().merge_call(lambda _: _)
return v[0]
@def_function.function(autograph=False)
def make_v1():
return distribution.experimental_local_results(
distribution.extended.call_for_each_replica(model_fn))
self.assertAllEqual([0, 0], make_v1())
def testSingleVariable(self, distribution):
def model_fn():
# This variable should be created only once across the threads because of
# special variable_creator functions used by
# `distribution.extended.call_for_each_replica`.
v = variable_scope.variable(1.0, name="foo")
ds_context.get_replica_context().merge_call(lambda _: _)
return v
with distribution.scope():
result = distribution.extended.call_for_each_replica(model_fn)
self._test_mv_properties(result, "foo:0", distribution)
def testUnnamedVariable(self, distribution):
def model_fn():
v = variable_scope.variable(1.0)
ds_context.get_replica_context().merge_call(lambda _: _)
return v
with distribution.scope():
result = distribution.extended.call_for_each_replica(model_fn)
self._test_mv_properties(result, "Variable:0", distribution)
def testMultipleVariables(self, distribution):
def model_fn():
vs = []
for i in range(5):
vs.append(variable_scope.variable(1.0, name="foo" + str(i)))
ds_context.get_replica_context().merge_call(lambda _: _)
return vs
with distribution.scope():
result = distribution.extended.call_for_each_replica(model_fn)
for i, v in enumerate(result):
self._test_mv_properties(v, "foo" + str(i) + ":0", distribution)
def testMultipleVariablesWithSameCanonicalName(self, distribution):
def model_fn():
vs = []
vs.append(variable_scope.variable(1.0, name="foo/bar"))
vs.append(variable_scope.variable(1.0, name="foo_1/bar"))
vs.append(variable_scope.variable(1.0, name="foo_1/bar_1"))
vs.append(variable_scope.variable(1.0, name="foo/bar_1"))
ds_context.get_replica_context().merge_call(lambda _: _)
return vs
with distribution.scope():
result = distribution.extended.call_for_each_replica(model_fn)
for v in result:
self.assertIsInstance(v, values.MirroredVariable)
self.assertEqual(4, len(result))
self.assertEqual("foo/bar:0", result[0].name)
self.assertEqual("foo_1/bar:0", result[1].name)
self.assertEqual("foo_1/bar_1:0", result[2].name)
self.assertEqual("foo/bar_1:0", result[3].name)
def testVariableWithSameCanonicalNameAcrossThreads(self, distribution):
def model_fn():
replica_id = self.evaluate(_replica_id())
v = variable_scope.variable(1.0, name="foo_" + str(replica_id))
ds_context.get_replica_context().merge_call(lambda _: _)
return v
with distribution.scope():
result = distribution.extended.call_for_each_replica(model_fn)
self.assertIsInstance(result, values.MirroredVariable)
# The resulting mirrored variable will use the name from the first device.
self.assertEqual("foo_0:0", result.name)
def testWithLayers(self, distribution):
def model_fn(features):
with variable_scope.variable_scope("common"):
layer1 = core.Dense(1)
layer1(features)
layer2 = core.Dense(1)
layer2(features)
# This will pause the current thread, and execute the other thread.
ds_context.get_replica_context().merge_call(lambda _: _)
layer3 = core.Dense(1)
layer3(features)
return [(layer1.kernel, layer1.bias), (layer2.kernel, layer2.bias),
(layer3.kernel, layer3.bias)]
iterator = distribution.make_input_fn_iterator(
lambda _: dataset_ops.Dataset.from_tensors([[1.]]).repeat(10))
self.evaluate(iterator.initialize())
features = iterator.get_next()
with distribution.scope():
result = distribution.extended.call_for_each_replica(
model_fn, args=(features,))
suffixes = ["", "_1", "_2"]
for (kernel, bias), suffix in zip(result, suffixes):
self.assertIsInstance(kernel, values.MirroredVariable)
self.assertEqual("common/dense" + suffix + "/kernel:0", kernel.name)
self.assertIsInstance(bias, values.MirroredVariable)
self.assertEqual("common/dense" + suffix + "/bias:0", bias.name)
def testWithVariableAndVariableScope(self, distribution):
def model_fn():
v0 = variable_scope.variable(1.0, name="var0", aggregation=None)
with variable_scope.variable_scope("common"):
v1 = variable_scope.variable(1.0, name="var1")
# This will pause the current thread, and execute the other thread.
ds_context.get_replica_context().merge_call(lambda _: _)
v2 = variable_scope.variable(
1.0,
name="var2",
synchronization=variable_scope.VariableSynchronization.ON_READ,
aggregation=variable_scope.VariableAggregation.SUM)
v3 = variable_scope.variable(
1.0,
name="var3",
synchronization=variable_scope.VariableSynchronization.ON_WRITE,
aggregation=variable_scope.VariableAggregation.MEAN)
return v0, v1, v2, v3
with distribution.scope():
v = variable_scope.variable(1.0, name="var-main0")
self.assertEqual("var-main0:0", v.name)
result = distribution.extended.call_for_each_replica(model_fn)
self.assertEqual(4, len(result))
v0, v1, v2, v3 = result
self.assertIsInstance(v0, values.MirroredVariable)
self.assertEqual("var0:0", v0.name)
self.assertIsInstance(v1, values.MirroredVariable)
self.assertEqual("common/var1:0", v1.name)
self.assertIsInstance(v2, values.SyncOnReadVariable)
self.assertEqual("common/var2:0", v2.name)
self.assertEqual(variable_scope.VariableAggregation.SUM, v2.aggregation)
self.assertIsInstance(v3, values.MirroredVariable)
self.assertEqual("common/var3:0", v3.name)
self.assertEqual(variable_scope.VariableAggregation.MEAN, v3.aggregation)
def testWithGetVariableAndVariableScope(self, distribution):
def model_fn():
v0 = variable_scope.get_variable("var0", [1])
with variable_scope.variable_scope("common"):
v1 = variable_scope.get_variable("var1", [1])
# This will pause the current thread, and execute the other thread.
ds_context.get_replica_context().merge_call(lambda _: _)
v2 = variable_scope.get_variable(
"var2", [1],
synchronization=variable_scope.VariableSynchronization.ON_READ,
aggregation=variable_scope.VariableAggregation.SUM)
v3 = variable_scope.get_variable(
"var3", [1],
synchronization=variable_scope.VariableSynchronization.ON_WRITE,
aggregation=variable_scope.VariableAggregation.MEAN)
return v0, v1, v2, v3
with distribution.scope():
with variable_scope.variable_scope("main"):
v = variable_scope.get_variable("var-main0", [1])
self.assertEqual("main/var-main0:0", v.name)
result = distribution.extended.call_for_each_replica(model_fn)
self.assertEqual(4, len(result))
v0, v1, v2, v3 = result
self.assertIsInstance(v0, values.MirroredVariable)
self.assertEqual("main/var0:0", v0.name)
self.assertIsInstance(v1, values.MirroredVariable)
self.assertEqual("main/common/var1:0", v1.name)
self.assertIsInstance(v2, values.SyncOnReadVariable)
self.assertEqual("main/common/var2:0", v2.name)
self.assertEqual(variable_scope.VariableAggregation.SUM, v2.aggregation)
self.assertIsInstance(v3, values.MirroredVariable)
self.assertEqual("main/common/var3:0", v3.name)
self.assertEqual(variable_scope.VariableAggregation.MEAN,
v3.aggregation)
def testOnlyFirstReplicaUpdatesVariables(self, distribution):
def create_fn():
aggregation = variable_scope.VariableAggregation.ONLY_FIRST_REPLICA
v0 = variable_scope.variable(
2.0,
name="on_read",
synchronization=variable_scope.VariableSynchronization.ON_READ,
aggregation=aggregation)
v1 = variable_scope.variable(
3.0,
name="on_write",
synchronization=variable_scope.VariableSynchronization.ON_WRITE,
aggregation=aggregation)
return v0, v1
devices = distribution.extended.worker_devices
with distribution.scope():
v0, v1 = distribution.extended.call_for_each_replica(create_fn)
self.evaluate(v0.initializer)
self.assertEqual(2.0, self.evaluate(v0.get(devices[0])))
self.assertEqual(2.0, self.evaluate(v0.get(devices[1])))
self.assertEqual(2.0, self.evaluate(distribution.extended.read_var(v0)))
self.evaluate(v1.initializer)
self.assertEqual(3.0, self.evaluate(v1.get(devices[0])))
self.assertEqual(3.0, self.evaluate(v1.get(devices[1])))
self.assertEqual(3.0, self.evaluate(distribution.extended.read_var(v1)))
def replica_id_plus_one():
return math_ops.cast(_replica_id() + 1, dtype=dtypes.float32)
# Update using the assign_add member function.
def update_member_fn():
update0 = v0.assign_add(5.0 * replica_id_plus_one())
update1 = v1.assign_add(7.0 * replica_id_plus_one())
return update0, update1
update0a, update1a = distribution.extended.call_for_each_replica(
update_member_fn)
# Update "sync on read" variable.
self.evaluate(distribution.group(update0a))
self.assertEqual(2.0 + 5.0, self.evaluate(v0.get(devices[0])))
# Writes are not synchronized for "sync on read" variables,
# so device[1] can end up with a different value.
self.assertEqual(2.0 + 2 * 5.0, self.evaluate(v0.get(devices[1])))
# Always reads from device 0.
self.assertEqual(2.0 + 5.0,
self.evaluate(distribution.extended.read_var(v0)))
# Update "sync on write" variable.
self.evaluate(distribution.group(update1a))
self.assertEqual(3.0 + 7.0, self.evaluate(v1.get(devices[0])))
# Writes are synchronized for v1, only the argument to assign_add on
# device[0] is used.
self.assertEqual(3.0 + 7.0, self.evaluate(v1.get(devices[1])))
self.assertEqual(3.0 + 7.0,
self.evaluate(distribution.extended.read_var(v1)))
# Update using state_ops.assign_add global function.
def update_state_ops_fn():
update0 = state_ops.assign_add(v0, 11.0 * replica_id_plus_one())
update1 = state_ops.assign_add(v1, 13.0 * replica_id_plus_one())
return update0, update1
update0b, update1b = distribution.extended.call_for_each_replica(
update_state_ops_fn)
self.evaluate(distribution.group(update0b))
# Update "sync on read" variable.
self.assertEqual(2.0 + 5.0 + 11.0, self.evaluate(v0.get(devices[0])))
self.assertEqual(2.0 + 2 * 5.0 + 2 * 11.0,
self.evaluate(v0.get(devices[1])))
self.assertEqual(2.0 + 5.0 + 11.0,
self.evaluate(distribution.extended.read_var(v0)))
# Update "sync on write" variable.
self.evaluate(distribution.group(update1b))
self.assertEqual(3.0 + 7.0 + 13.0, self.evaluate(v1.get(devices[0])))
self.assertEqual(3.0 + 7.0 + 13.0, self.evaluate(v1.get(devices[1])))
self.assertEqual(3.0 + 7.0 + 13.0,
self.evaluate(distribution.extended.read_var(v1)))
def testNoneSynchronizationWithGetVariable(self, distribution):
with distribution.scope():
with self.assertRaisesRegexp(
ValueError, "`NONE` variable synchronization mode is not "
"supported with `Mirrored` distribution strategy. Please change "
"the `synchronization` for variable: v"):
variable_scope.get_variable(
"v", [1],
synchronization=variable_scope.VariableSynchronization.NONE)
def testNoneSynchronizationWithVariable(self, distribution):
with distribution.scope():
with self.assertRaisesRegexp(
ValueError, "`NONE` variable synchronization mode is not "
"supported with `Mirrored` distribution strategy. Please change "
"the `synchronization` for variable: v"):
variable_scope.variable(
1.0,
name="v",
synchronization=variable_scope.VariableSynchronization.NONE)
def testInvalidSynchronizationWithVariable(self, distribution):
with distribution.scope():
with self.assertRaisesRegexp(
ValueError, "Invalid variable synchronization mode: Invalid for "
"variable: v"):
variable_scope.variable(1.0, name="v", synchronization="Invalid")
def testInvalidAggregationWithGetVariable(self, distribution):
with distribution.scope():
with self.assertRaisesRegexp(
ValueError, "Invalid variable aggregation mode: invalid for "
"variable: v"):
variable_scope.get_variable(
"v", [1],
synchronization=variable_scope.VariableSynchronization.ON_WRITE,
aggregation="invalid")
def testInvalidAggregationWithVariable(self, distribution):
with distribution.scope():
with self.assertRaisesRegexp(
ValueError, "Invalid variable aggregation mode: invalid for "
"variable: v"):
variable_scope.variable(
1.0,
name="v",
synchronization=variable_scope.VariableSynchronization.ON_WRITE,
aggregation="invalid")
def testNonMatchingVariableCreation(self, distribution):
self.skipTest("b/123075960")
def model_fn(name):
v = variable_scope.variable(1.0, name=name)
ds_context.get_replica_context().merge_call(lambda _: _)
return v
with distribution.scope():
device_map = values.ReplicaDeviceMap(distribution.extended.worker_devices)
names = values.DistributedValues(device_map, ("foo", "bar"))
with self.assertRaises(RuntimeError):
_ = distribution.extended.call_for_each_replica(model_fn, args=(names,))
def testSyncOnReadVariable(self, distribution):
if context.executing_eagerly():
self.skipTest("Skip the test due to b/137400477.")
all_v_sum = {}
all_v_mean = {}
components_sum = {}
components_mean = {}
def model_fn():
replica_id = self.evaluate(_replica_id())
v_sum = variable_scope.variable(
1.0,
synchronization=variable_scope.VariableSynchronization.ON_READ,
aggregation=variable_scope.VariableAggregation.SUM)
v_mean = variable_scope.variable(
4.0,
synchronization=variable_scope.VariableSynchronization.ON_READ,
aggregation=variable_scope.VariableAggregation.MEAN)
self.assertIsInstance(v_sum, values.SyncOnReadVariable)
self.assertIsInstance(v_mean, values.SyncOnReadVariable)
updates = [
v_sum.assign_add(2.0 + replica_id),
v_mean.assign(6.0 * replica_id)
]
all_v_sum[replica_id] = v_sum
all_v_mean[replica_id] = v_mean
c_sum = v_sum.get()
c_mean = v_mean.get()
components_sum[replica_id] = c_sum
components_mean[replica_id] = c_mean
self.assertIsNot(v_sum, c_sum)
self.assertIsNot(v_mean, c_mean)
return updates, v_sum, v_mean, c_sum, c_mean
with distribution.scope():
# Create "sum" and "mean" versions of SyncOnReadVariables.
ret_ops, ret_v_sum, ret_v_mean, regrouped_sum, regrouped_mean = (
distribution.extended.call_for_each_replica(model_fn))
# Should see the same wrapping instance in all replicas.
self.assertIs(all_v_sum[0], ret_v_sum)
self.assertIs(all_v_mean[0], ret_v_mean)
self.assertIs(all_v_sum[0], all_v_sum[1])
self.assertIs(all_v_mean[0], all_v_mean[1])
# Regroup should recover the same wrapper.
self.assertIs(ret_v_sum, regrouped_sum)
self.assertIs(ret_v_mean, regrouped_mean)
self.assertIsNot(components_sum[0], components_sum[1])
self.assertIsNot(components_mean[0], components_mean[1])
# Apply updates
self.evaluate(variables.global_variables_initializer())
self.evaluate([
y for x in ret_ops # pylint: disable=g-complex-comprehension
for y in distribution.experimental_local_results(x)
])
expected_sum = 0.0
expected_mean = 0.0
for i, d in enumerate(distribution.extended.worker_devices):
# Should see different values on different devices.
v_sum_value = self.evaluate(ret_v_sum.get(d).read_value())
v_mean_value = self.evaluate(ret_v_mean.get(d).read_value())
expected = i + 3.0
self.assertEqual(expected, v_sum_value)
expected_sum += expected
expected = i * 6.0
self.assertEqual(expected, v_mean_value)
expected_mean += expected
expected_mean /= len(distribution.extended.worker_devices)
# Without get(device), should return the value you get by
# applying the reduction across all replicas (whether you use
# read_var(), get(), or nothing).
self.assertEqual(expected_sum, self.evaluate(
distribution.extended.read_var(ret_v_sum)))
self.assertEqual(expected_mean, self.evaluate(
distribution.extended.read_var(ret_v_mean)))
self.assertEqual(expected_sum, self.evaluate(ret_v_sum.get()))
self.assertEqual(expected_mean, self.evaluate(ret_v_mean.get()))
self.assertEqual(expected_sum, self.evaluate(ret_v_sum))
self.assertEqual(expected_mean, self.evaluate(ret_v_mean))
# TODO(priyag): Update this test to work in eager mode as well.
def testDynamicRnnVariables(self, distribution):
def model_fn():
inputs = constant_op.constant(2 * [2 * [[0.0, 1.0, 2.0, 3.0, 4.0]]])
cell_fw = rnn_cell_impl.LSTMCell(300)
cell_bw = rnn_cell_impl.LSTMCell(300)
(outputs, _) = rnn.bidirectional_dynamic_rnn(
cell_fw, cell_bw, inputs, dtype=dtypes.float32)
return outputs
with context.graph_mode(), distribution.scope():
result = distribution.extended.call_for_each_replica(model_fn)
# Two variables are created by the RNN layer.
self.assertEqual(2, len(result))
for v in result:
self.assertIsInstance(v, values.DistributedValues)
_, v1 = distribution.experimental_local_results(v)
self.assertStartsWith(v1._op.name, "replica_1/")
def testSyncOnReadVariableUpdate(self, distribution):
if context.executing_eagerly():
self.skipTest("Skip the test due to b/137400477.")
def model_fn():
v_sum = variable_scope.variable(
1.0,
synchronization=variable_scope.VariableSynchronization.ON_READ,
aggregation=variable_scope.VariableAggregation.SUM)
self.assertIsInstance(v_sum, values.SyncOnReadVariable)
return v_sum
def update(var, value):
return var.assign(value)
with distribution.scope():
ret_v_sum = distribution.extended.call_for_each_replica(model_fn)
# Initialize variables.
self.evaluate(variables.global_variables_initializer())
# Assert that the aggregated value of the sync on read var is the sum
# of the individual values before running the update ops.
self.assertEqual(
1.0,
self.evaluate(
ret_v_sum.get(
distribution.extended.worker_devices[0]).read_value()))
self.assertEqual(2.0, self.evaluate(ret_v_sum))
# Apply updates.
update_ops = distribution.extended.update(
ret_v_sum, update, args=(5.0,), group=False)
self.evaluate(update_ops)
# Assert that the aggregated value of the sync on read vars is the sum
# of the individual values after running the update ops.
self.assertEqual(
5.0,
self.evaluate(
ret_v_sum.get(
distribution.extended.worker_devices[0]).read_value()))
self.assertEqual(10.0, self.evaluate(ret_v_sum))
def testVarDistributeStrategy(self, distribution):
with distribution.scope():
mirrored = variable_scope.variable(1.0)
sync_on_read = variable_scope.variable(
1.0, synchronization=variable_scope.VariableSynchronization.ON_READ)
self.assertIs(distribution, mirrored.distribute_strategy)
self.assertIs(distribution, sync_on_read.distribute_strategy)
if __name__ == "__main__":
test.main()
|
|
# Copyright 2014 NEC Corporation. All rights reserved.
#
# 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.
from heatclient import exc
from oslo_service import loopingcall
from magnum.common import exception
from magnum.conductor.handlers import bay_conductor
from magnum import objects
from magnum.objects.bay import Status as bay_status
from magnum.tests import base
from magnum.tests.unit.db import base as db_base
from magnum.tests.unit.db import utils
import mock
from mock import patch
from oslo_config import cfg
class TestBayConductorWithK8s(base.TestCase):
def setUp(self):
super(TestBayConductorWithK8s, self).setUp()
self.baymodel_dict = {
'image_id': 'image_id',
'flavor_id': 'flavor_id',
'master_flavor_id': 'master_flavor_id',
'keypair_id': 'keypair_id',
'dns_nameserver': 'dns_nameserver',
'external_network_id': 'external_network_id',
'fixed_network': '10.20.30.0/24',
'docker_volume_size': 20,
'cluster_distro': 'fedora-atomic',
'ssh_authorized_key': 'ssh_authorized_key',
'coe': 'kubernetes',
'token': None,
}
self.bay_dict = {
'baymodel_id': 'xx-xx-xx-xx',
'name': 'bay1',
'stack_id': 'xx-xx-xx-xx',
'api_address': '172.17.2.3',
'node_addresses': ['172.17.2.4'],
'node_count': 1,
'discovery_url': 'https://discovery.etcd.io/test',
}
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition(
self,
mock_objects_baymodel_get_by_uuid):
self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid)
def _test_extract_template_definition(
self,
mock_objects_baymodel_get_by_uuid,
missing_attr=None):
if missing_attr in self.baymodel_dict:
self.baymodel_dict[missing_attr] = None
elif missing_attr in self.bay_dict:
self.bay_dict[missing_attr] = None
baymodel = objects.BayModel(self.context, **self.baymodel_dict)
mock_objects_baymodel_get_by_uuid.return_value = baymodel
bay = objects.Bay(self.context, **self.bay_dict)
(template_path,
definition) = bay_conductor._extract_template_definition(self.context,
bay)
mapping = {
'dns_nameserver': 'dns_nameserver',
'image_id': 'server_image',
'flavor_id': 'minion_flavor',
'docker_volume_size': 'docker_volume_size',
'fixed_network': 'fixed_network_cidr',
'master_flavor_id': 'master_flavor',
'apiserver_port': '',
'node_count': 'number_of_minions',
'discovery_url': 'discovery_url',
}
expected = {
'ssh_key_name': 'keypair_id',
'external_network': 'external_network_id',
'dns_nameserver': 'dns_nameserver',
'server_image': 'image_id',
'minion_flavor': 'flavor_id',
'master_flavor': 'master_flavor_id',
'number_of_minions': '1',
'fixed_network_cidr': '10.20.30.0/24',
'docker_volume_size': 20,
'discovery_url': 'https://discovery.etcd.io/test',
}
if missing_attr is not None:
expected.pop(mapping[missing_attr], None)
self.assertEqual(expected, definition)
@patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_coreos_with_disovery(
self,
mock_objects_baymodel_get_by_uuid,
reqget):
baymodel_dict = self.baymodel_dict
baymodel_dict['cluster_distro'] = 'coreos'
cfg.CONF.set_override('coreos_discovery_token_url',
'http://tokentest',
group='bay')
mock_req = mock.MagicMock(text='/h1/h2/h3')
reqget.return_value = mock_req
baymodel = objects.BayModel(self.context, **self.baymodel_dict)
mock_objects_baymodel_get_by_uuid.return_value = baymodel
bay = objects.Bay(self.context, **self.bay_dict)
(template_path,
definition) = bay_conductor._extract_template_definition(self.context,
bay)
expected = {
'ssh_key_name': 'keypair_id',
'external_network': 'external_network_id',
'dns_nameserver': 'dns_nameserver',
'server_image': 'image_id',
'minion_flavor': 'flavor_id',
'master_flavor': 'master_flavor_id',
'number_of_minions': '1',
'fixed_network_cidr': '10.20.30.0/24',
'docker_volume_size': 20,
'ssh_authorized_key': 'ssh_authorized_key',
'token': 'h3',
'discovery_url': 'https://discovery.etcd.io/test',
}
self.assertEqual(expected, definition)
@patch('uuid.uuid4')
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_coreos_no_discoveryurl(
self,
mock_objects_baymodel_get_by_uuid,
mock_uuid):
baymodel_dict = self.baymodel_dict
baymodel_dict['cluster_distro'] = 'coreos'
cfg.CONF.set_override('coreos_discovery_token_url',
None,
group='bay')
mock_uuid.return_value = mock.MagicMock(
hex='ba3d1866282848ddbedc76112110c208')
baymodel = objects.BayModel(self.context, **self.baymodel_dict)
mock_objects_baymodel_get_by_uuid.return_value = baymodel
bay = objects.Bay(self.context, **self.bay_dict)
(template_path,
definition) = bay_conductor._extract_template_definition(self.context,
bay)
expected = {
'ssh_key_name': 'keypair_id',
'external_network': 'external_network_id',
'dns_nameserver': 'dns_nameserver',
'server_image': 'image_id',
'minion_flavor': 'flavor_id',
'master_flavor': 'master_flavor_id',
'number_of_minions': '1',
'fixed_network_cidr': '10.20.30.0/24',
'docker_volume_size': 20,
'ssh_authorized_key': 'ssh_authorized_key',
'token': 'ba3d1866282848ddbedc76112110c208',
'discovery_url': 'https://discovery.etcd.io/test',
}
self.assertEqual(expected, definition)
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_without_dns(
self,
mock_objects_baymodel_get_by_uuid):
self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid,
missing_attr='dns_nameserver')
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_without_server_image(
self,
mock_objects_baymodel_get_by_uuid):
self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid,
missing_attr='image_id')
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_without_minion_flavor(
self,
mock_objects_baymodel_get_by_uuid):
self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid,
missing_attr='flavor_id')
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_without_docker_volume_size(
self,
mock_objects_baymodel_get_by_uuid):
self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid,
missing_attr='docker_volume_size')
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_without_fixed_network(
self,
mock_objects_baymodel_get_by_uuid):
self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid,
missing_attr='fixed_network')
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_without_master_flavor(
self,
mock_objects_baymodel_get_by_uuid):
self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid,
missing_attr='master_flavor_id')
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_without_ssh_authorized_key(
self,
mock_objects_baymodel_get_by_uuid):
baymodel_dict = self.baymodel_dict
baymodel_dict['cluster_distro'] = 'coreos'
baymodel_dict['ssh_authorized_key'] = None
baymodel = objects.BayModel(self.context, **baymodel_dict)
mock_objects_baymodel_get_by_uuid.return_value = baymodel
bay = objects.Bay(self.context, **self.bay_dict)
(template_path,
definition) = bay_conductor._extract_template_definition(self.context,
bay)
expected = {
'ssh_key_name': 'keypair_id',
'external_network': 'external_network_id',
'dns_nameserver': 'dns_nameserver',
'server_image': 'image_id',
'master_flavor': 'master_flavor_id',
'minion_flavor': 'flavor_id',
'number_of_minions': '1',
'fixed_network_cidr': '10.20.30.0/24',
'docker_volume_size': 20,
'discovery_url': 'https://discovery.etcd.io/test',
}
self.assertIn('token', definition)
del definition['token']
self.assertEqual(expected, definition)
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_without_apiserver_port(
self,
mock_objects_baymodel_get_by_uuid):
self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid,
missing_attr='apiserver_port')
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_without_node_count(
self,
mock_objects_baymodel_get_by_uuid):
self._test_extract_template_definition(
mock_objects_baymodel_get_by_uuid,
missing_attr='node_count')
@patch('requests.get')
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_without_discovery_url(
self,
mock_objects_baymodel_get_by_uuid,
reqget):
baymodel = objects.BayModel(self.context, **self.baymodel_dict)
mock_objects_baymodel_get_by_uuid.return_value = baymodel
bay_dict = self.bay_dict
bay_dict['discovery_url'] = None
bay = objects.Bay(self.context, **bay_dict)
cfg.CONF.set_override('etcd_discovery_service_endpoint_format',
'http://etcd/test?size=%(size)d',
group='bay')
mock_req = mock.MagicMock(text='https://address/token')
reqget.return_value = mock_req
(template_path,
definition) = bay_conductor._extract_template_definition(self.context,
bay)
expected = {
'ssh_key_name': 'keypair_id',
'external_network': 'external_network_id',
'dns_nameserver': 'dns_nameserver',
'server_image': 'image_id',
'master_flavor': 'master_flavor_id',
'minion_flavor': 'flavor_id',
'number_of_minions': '1',
'fixed_network_cidr': '10.20.30.0/24',
'docker_volume_size': 20,
'discovery_url': 'https://address/token',
}
self.assertEqual(expected, definition)
reqget.assert_called_once_with('http://etcd/test?size=1')
@patch('magnum.objects.BayModel.get_by_uuid')
def test_update_stack_outputs(self, mock_objects_baymodel_get_by_uuid):
baymodel_dict = self.baymodel_dict
baymodel_dict['cluster_distro'] = 'coreos'
baymodel = objects.BayModel(self.context, **baymodel_dict)
mock_objects_baymodel_get_by_uuid.return_value = baymodel
expected_api_address = 'api_address'
expected_node_addresses = ['ex_minion', 'address']
outputs = [
{"output_value": expected_node_addresses,
"description": "No description given",
"output_key": "kube_minions_external"},
{"output_value": expected_api_address,
"description": "No description given",
"output_key": "api_address"},
{"output_value": ['any', 'output'],
"description": "No description given",
"output_key": "kube_minions"}
]
mock_stack = mock.MagicMock()
mock_stack.outputs = outputs
mock_bay = mock.MagicMock()
bay_conductor._update_stack_outputs(self.context, mock_stack, mock_bay)
self.assertEqual(mock_bay.api_address, expected_api_address)
self.assertEqual(mock_bay.node_addresses, expected_node_addresses)
@patch('magnum.common.short_id.generate_id')
@patch('heatclient.common.template_utils.get_template_contents')
@patch('magnum.conductor.handlers.bay_conductor'
'._extract_template_definition')
def test_create_stack(self,
mock_extract_template_definition,
mock_get_template_contents,
mock_generate_id):
mock_generate_id.return_value = 'xx-xx-xx-xx'
expected_stack_name = 'expected_stack_name-xx-xx-xx-xx'
expected_template_contents = 'template_contents'
exptected_files = []
dummy_bay_name = 'expected_stack_name'
expected_timeout = 15
mock_tpl_files = mock.MagicMock()
mock_tpl_files.items.return_value = exptected_files
mock_get_template_contents.return_value = [
mock_tpl_files, expected_template_contents]
mock_extract_template_definition.return_value = ('template/path',
{})
mock_heat_client = mock.MagicMock()
mock_osc = mock.MagicMock()
mock_osc.heat.return_value = mock_heat_client
mock_bay = mock.MagicMock()
mock_bay.name = dummy_bay_name
bay_conductor._create_stack(self.context, mock_osc,
mock_bay, expected_timeout)
expected_args = {
'stack_name': expected_stack_name,
'parameters': {},
'template': expected_template_contents,
'files': dict(exptected_files),
'timeout_mins': expected_timeout
}
mock_heat_client.stacks.create.assert_called_once_with(**expected_args)
@patch('magnum.common.short_id.generate_id')
@patch('heatclient.common.template_utils.get_template_contents')
@patch('magnum.conductor.handlers.bay_conductor'
'._extract_template_definition')
def test_create_stack_no_timeout_specified(
self,
mock_extract_template_definition,
mock_get_template_contents,
mock_generate_id):
mock_generate_id.return_value = 'xx-xx-xx-xx'
expected_stack_name = 'expected_stack_name-xx-xx-xx-xx'
expected_template_contents = 'template_contents'
exptected_files = []
dummy_bay_name = 'expected_stack_name'
expected_timeout = cfg.CONF.bay_heat.bay_create_timeout
mock_tpl_files = mock.MagicMock()
mock_tpl_files.items.return_value = exptected_files
mock_get_template_contents.return_value = [
mock_tpl_files, expected_template_contents]
mock_extract_template_definition.return_value = ('template/path',
{})
mock_heat_client = mock.MagicMock()
mock_osc = mock.MagicMock()
mock_osc.heat.return_value = mock_heat_client
mock_bay = mock.MagicMock()
mock_bay.name = dummy_bay_name
bay_conductor._create_stack(self.context, mock_osc,
mock_bay, None)
expected_args = {
'stack_name': expected_stack_name,
'parameters': {},
'template': expected_template_contents,
'files': dict(exptected_files),
'timeout_mins': expected_timeout
}
mock_heat_client.stacks.create.assert_called_once_with(**expected_args)
@patch('magnum.common.short_id.generate_id')
@patch('heatclient.common.template_utils.get_template_contents')
@patch('magnum.conductor.handlers.bay_conductor'
'._extract_template_definition')
def test_create_stack_timeout_is_zero(
self,
mock_extract_template_definition,
mock_get_template_contents,
mock_generate_id):
mock_generate_id.return_value = 'xx-xx-xx-xx'
expected_stack_name = 'expected_stack_name-xx-xx-xx-xx'
expected_template_contents = 'template_contents'
exptected_files = []
dummy_bay_name = 'expected_stack_name'
bay_timeout = 0
expected_timeout = None
mock_tpl_files = mock.MagicMock()
mock_tpl_files.items.return_value = exptected_files
mock_get_template_contents.return_value = [
mock_tpl_files, expected_template_contents]
mock_extract_template_definition.return_value = ('template/path',
{})
mock_heat_client = mock.MagicMock()
mock_osc = mock.MagicMock()
mock_osc.heat.return_value = mock_heat_client
mock_bay = mock.MagicMock()
mock_bay.name = dummy_bay_name
bay_conductor._create_stack(self.context, mock_osc,
mock_bay, bay_timeout)
expected_args = {
'stack_name': expected_stack_name,
'parameters': {},
'template': expected_template_contents,
'files': dict(exptected_files),
'timeout_mins': expected_timeout
}
mock_heat_client.stacks.create.assert_called_once_with(**expected_args)
@patch('heatclient.common.template_utils.get_template_contents')
@patch('magnum.conductor.handlers.bay_conductor'
'._extract_template_definition')
def test_update_stack(self,
mock_extract_template_definition,
mock_get_template_contents):
mock_stack_id = 'xx-xx-xx-xx'
expected_template_contents = 'template_contents'
exptected_files = []
mock_tpl_files = mock.MagicMock()
mock_tpl_files.items.return_value = exptected_files
mock_get_template_contents.return_value = [
mock_tpl_files, expected_template_contents]
mock_extract_template_definition.return_value = ('template/path',
{})
mock_heat_client = mock.MagicMock()
mock_osc = mock.MagicMock()
mock_osc.heat.return_value = mock_heat_client
mock_bay = mock.MagicMock()
mock_bay.stack_id = mock_stack_id
bay_conductor._update_stack({}, mock_osc, mock_bay)
expected_args = {
'parameters': {},
'template': expected_template_contents,
'files': dict(exptected_files)
}
mock_heat_client.stacks.update.assert_called_once_with(mock_stack_id,
**expected_args)
@patch('oslo_config.cfg')
@patch('magnum.common.clients.OpenStackClients')
def setup_poll_test(self, mock_openstack_client, cfg):
cfg.CONF.bay_heat.max_attempts = 10
bay = mock.MagicMock()
mock_heat_stack = mock.MagicMock()
mock_heat_client = mock.MagicMock()
mock_heat_client.stacks.get.return_value = mock_heat_stack
mock_openstack_client.heat.return_value = mock_heat_client
poller = bay_conductor.HeatPoller(mock_openstack_client, bay)
return (mock_heat_stack, bay, poller)
def test_poll_no_save(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
bay.status = bay_status.CREATE_IN_PROGRESS
mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS
poller.poll_and_check()
self.assertEqual(bay.save.call_count, 0)
self.assertEqual(poller.attempts, 1)
def test_poll_save(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
bay.status = bay_status.CREATE_IN_PROGRESS
mock_heat_stack.stack_status = bay_status.CREATE_FAILED
mock_heat_stack.stack_status_reason = 'Create failed'
self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check)
self.assertEqual(bay.save.call_count, 1)
self.assertEqual(bay.status, bay_status.CREATE_FAILED)
self.assertEqual(bay.status_reason, 'Create failed')
self.assertEqual(poller.attempts, 1)
def test_poll_done(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
mock_heat_stack.stack_status = bay_status.DELETE_COMPLETE
self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check)
mock_heat_stack.stack_status = bay_status.CREATE_FAILED
self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check)
self.assertEqual(poller.attempts, 2)
def test_poll_done_by_update_failed(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
mock_heat_stack.stack_status = bay_status.UPDATE_FAILED
self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check)
def test_poll_destroy(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
mock_heat_stack.stack_status = bay_status.DELETE_FAILED
self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check)
# Destroy method is not called when stack delete failed
self.assertEqual(bay.destroy.call_count, 0)
mock_heat_stack.stack_status = bay_status.DELETE_IN_PROGRESS
poller.poll_and_check()
self.assertEqual(bay.destroy.call_count, 0)
self.assertEqual(bay.status, bay_status.DELETE_IN_PROGRESS)
mock_heat_stack.stack_status = bay_status.DELETE_COMPLETE
self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check)
# The bay status should still be DELETE_IN_PROGRESS, because
# the destroy() method may be failed. If success, this bay record
# will delete directly, change status is meaningless.
self.assertEqual(bay.status, bay_status.DELETE_IN_PROGRESS)
self.assertEqual(bay.destroy.call_count, 1)
def test_poll_delete_in_progress_timeout_set(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
mock_heat_stack.stack_status = bay_status.DELETE_IN_PROGRESS
mock_heat_stack.timeout_mins = 60
# timeout only affects stack creation so expecting this
# to process normally
poller.poll_and_check()
def test_poll_delete_in_progress_max_attempts_reached(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
mock_heat_stack.stack_status = bay_status.DELETE_IN_PROGRESS
poller.attempts = cfg.CONF.bay_heat.max_attempts
self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check)
def test_poll_create_in_prog_max_att_reached_no_timeout(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS
poller.attempts = cfg.CONF.bay_heat.max_attempts
mock_heat_stack.timeout_mins = None
self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check)
def test_poll_create_in_prog_max_att_reached_timeout_set(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS
poller.attempts = cfg.CONF.bay_heat.max_attempts
mock_heat_stack.timeout_mins = 60
# since the timeout is set the max attempts gets ignored since
# the timeout will eventually stop the poller either when
# the stack gets created or the timeout gets reached
poller.poll_and_check()
def test_poll_create_in_prog_max_att_reached_timed_out(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
mock_heat_stack.stack_status = bay_status.CREATE_FAILED
poller.attempts = cfg.CONF.bay_heat.max_attempts
mock_heat_stack.timeout_mins = 60
self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check)
def test_poll_create_in_prog_max_att_not_reached_no_timeout(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS
mock_heat_stack.timeout.mins = None
poller.poll_and_check()
def test_poll_create_in_prog_max_att_not_reached_timeout_set(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
mock_heat_stack.stack_status = bay_status.CREATE_IN_PROGRESS
mock_heat_stack.timeout_mins = 60
poller.poll_and_check()
def test_poll_create_in_prog_max_att_not_reached_timed_out(self):
mock_heat_stack, bay, poller = self.setup_poll_test()
mock_heat_stack.stack_status = bay_status.CREATE_FAILED
mock_heat_stack.timeout_mins = 60
self.assertRaises(loopingcall.LoopingCallDone, poller.poll_and_check)
class TestHandler(db_base.DbTestCase):
def setUp(self):
super(TestHandler, self).setUp()
self.handler = bay_conductor.Handler()
baymodel_dict = utils.get_test_baymodel()
self.baymodel = objects.BayModel(self.context, **baymodel_dict)
self.baymodel.create()
bay_dict = utils.get_test_bay(node_count=1)
self.bay = objects.Bay(self.context, **bay_dict)
self.bay.create()
@patch('magnum.conductor.scale_manager.ScaleManager')
@patch('magnum.conductor.handlers.bay_conductor.Handler._poll_and_check')
@patch('magnum.conductor.handlers.bay_conductor._update_stack')
@patch('magnum.common.clients.OpenStackClients')
def test_update_node_count_success(
self, mock_openstack_client_class,
mock_update_stack, mock_poll_and_check,
mock_scale_manager):
mock_heat_stack = mock.MagicMock()
mock_heat_stack.stack_status = bay_status.CREATE_COMPLETE
mock_heat_client = mock.MagicMock()
mock_heat_client.stacks.get.return_value = mock_heat_stack
mock_openstack_client = mock_openstack_client_class.return_value
mock_openstack_client.heat.return_value = mock_heat_client
self.bay.node_count = 2
self.handler.bay_update(self.context, self.bay)
mock_update_stack.assert_called_once_with(
self.context, mock_openstack_client, self.bay,
mock_scale_manager.return_value)
bay = objects.Bay.get(self.context, self.bay.uuid)
self.assertEqual(bay.node_count, 2)
@patch('magnum.conductor.handlers.bay_conductor.Handler._poll_and_check')
@patch('magnum.conductor.handlers.bay_conductor._update_stack')
@patch('magnum.common.clients.OpenStackClients')
def test_update_node_count_failure(
self, mock_openstack_client_class,
mock_update_stack, mock_poll_and_check):
mock_heat_stack = mock.MagicMock()
mock_heat_stack.stack_status = bay_status.CREATE_FAILED
mock_heat_client = mock.MagicMock()
mock_heat_client.stacks.get.return_value = mock_heat_stack
mock_openstack_client = mock_openstack_client_class.return_value
mock_openstack_client.heat.return_value = mock_heat_client
self.bay.node_count = 2
self.assertRaises(exception.NotSupported, self.handler.bay_update,
self.context, self.bay)
bay = objects.Bay.get(self.context, self.bay.uuid)
self.assertEqual(bay.node_count, 1)
@patch('magnum.conductor.handlers.bay_conductor._create_stack')
@patch('magnum.common.clients.OpenStackClients')
def test_create(self, mock_openstack_client_class, mock_create_stack):
mock_create_stack.side_effect = exc.HTTPBadRequest
timeout = 15
self.assertRaises(exception.InvalidParameterValue,
self.handler.bay_create, self.context,
self.bay, timeout)
@patch('magnum.common.clients.OpenStackClients')
def test_bay_delete(self, mock_openstack_client_class):
osc = mock.MagicMock()
mock_openstack_client_class.return_value = osc
osc.heat.side_effect = exc.HTTPNotFound
self.handler.bay_delete(self.context, self.bay.uuid)
# The bay has been destroyed
self.assertRaises(exception.BayNotFound,
objects.Bay.get, self.context, self.bay.uuid)
class TestBayConductorWithSwarm(base.TestCase):
def setUp(self):
super(TestBayConductorWithSwarm, self).setUp()
self.baymodel_dict = {
'image_id': 'image_id',
'flavor_id': 'flavor_id',
'keypair_id': 'keypair_id',
'dns_nameserver': 'dns_nameserver',
'external_network_id': 'external_network_id',
'fixed_network': '10.2.0.0/22',
'cluster_distro': 'fedora-atomic',
'coe': 'swarm'
}
self.bay_dict = {
'id': 1,
'uuid': 'some_uuid',
'baymodel_id': 'xx-xx-xx-xx',
'name': 'bay1',
'stack_id': 'xx-xx-xx-xx',
'api_address': '172.17.2.3',
'node_addresses': ['172.17.2.4'],
'node_count': 1,
'discovery_url': 'token://39987da72f8386e0d0225ae8929e7cb4',
}
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_all_values(
self,
mock_objects_baymodel_get_by_uuid):
baymodel = objects.BayModel(self.context, **self.baymodel_dict)
mock_objects_baymodel_get_by_uuid.return_value = baymodel
bay = objects.Bay(self.context, **self.bay_dict)
(template_path,
definition) = bay_conductor._extract_template_definition(self.context,
bay)
expected = {
'ssh_key_name': 'keypair_id',
'external_network': 'external_network_id',
'dns_nameserver': 'dns_nameserver',
'server_image': 'image_id',
'server_flavor': 'flavor_id',
'number_of_nodes': '1',
'fixed_network_cidr': '10.2.0.0/22',
'discovery_url': 'token://39987da72f8386e0d0225ae8929e7cb4'
}
self.assertEqual(expected, definition)
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_only_required(
self,
mock_objects_baymodel_get_by_uuid):
cfg.CONF.set_override('public_swarm_discovery', False, group='bay')
cfg.CONF.set_override('swarm_discovery_url_format',
'test_discovery', group='bay')
not_required = ['image_id', 'flavor_id', 'dns_nameserver',
'fixed_network']
for key in not_required:
self.baymodel_dict[key] = None
self.bay_dict['discovery_url'] = None
baymodel = objects.BayModel(self.context, **self.baymodel_dict)
mock_objects_baymodel_get_by_uuid.return_value = baymodel
bay = objects.Bay(self.context, **self.bay_dict)
(template_path,
definition) = bay_conductor._extract_template_definition(self.context,
bay)
expected = {
'ssh_key_name': 'keypair_id',
'external_network': 'external_network_id',
'number_of_nodes': '1',
'discovery_url': 'test_discovery'
}
self.assertEqual(expected, definition)
class TestBayConductorWithMesos(base.TestCase):
def setUp(self):
super(TestBayConductorWithMesos, self).setUp()
self.baymodel_dict = {
'image_id': 'image_id',
'flavor_id': 'flavor_id',
'master_flavor_id': 'master_flavor_id',
'keypair_id': 'keypair_id',
'dns_nameserver': 'dns_nameserver',
'external_network_id': 'external_network_id',
'fixed_network': '10.2.0.0/22',
'cluster_distro': 'ubuntu',
'coe': 'mesos'
}
self.bay_dict = {
'id': 1,
'uuid': 'some_uuid',
'baymodel_id': 'xx-xx-xx-xx',
'name': 'bay1',
'stack_id': 'xx-xx-xx-xx',
'api_address': '172.17.2.3',
'node_addresses': ['172.17.2.4'],
'node_count': 1,
}
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_all_values(
self,
mock_objects_baymodel_get_by_uuid):
baymodel = objects.BayModel(self.context, **self.baymodel_dict)
mock_objects_baymodel_get_by_uuid.return_value = baymodel
bay = objects.Bay(self.context, **self.bay_dict)
(template_path,
definition) = bay_conductor._extract_template_definition(self.context,
bay)
expected = {
'ssh_key_name': 'keypair_id',
'external_network': 'external_network_id',
'dns_nameserver': 'dns_nameserver',
'server_image': 'image_id',
'master_flavor': 'master_flavor_id',
'slave_flavor': 'flavor_id',
'number_of_slaves': '1',
'fixed_network_cidr': '10.2.0.0/22'
}
self.assertEqual(expected, definition)
@patch('magnum.objects.BayModel.get_by_uuid')
def test_extract_template_definition_only_required(
self,
mock_objects_baymodel_get_by_uuid):
not_required = ['image_id', 'master_flavor_id', 'flavor_id',
'dns_nameserver', 'fixed_network']
for key in not_required:
self.baymodel_dict[key] = None
baymodel = objects.BayModel(self.context, **self.baymodel_dict)
mock_objects_baymodel_get_by_uuid.return_value = baymodel
bay = objects.Bay(self.context, **self.bay_dict)
(template_path,
definition) = bay_conductor._extract_template_definition(self.context,
bay)
expected = {
'ssh_key_name': 'keypair_id',
'external_network': 'external_network_id',
'number_of_slaves': '1',
}
self.assertEqual(expected, definition)
|
|
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from collections import deque
import os
import cPickle as pickle
from zope.interface import implements, Interface
def ReadFile(path):
f = open(path, 'rb')
try:
return f.read()
finally:
f.close()
def WriteFile(path, buf):
f = open(path, 'wb')
try:
f.write(buf)
finally:
f.close()
class IQueue(Interface):
"""Abstraction of a queue."""
def pushItem(item):
"""Adds an individual item to the end of the queue.
Returns an item if it was overflowed."""
def insertBackChunk(items):
"""Adds a list of items as the oldest entries.
Normally called in case of failure to process the data, queue the data
back so it can be retrieved at a later time.
Returns a list of items if it was overflowed."""
def popChunk(nbItems=None):
"""Pop many items at once. Defaults to self.maxItems()."""
def save():
"""Save the queue to storage if implemented."""
def items():
"""Returns items in the queue.
Warning: Can be extremely slow for queue on disk."""
def nbItems():
"""Returns the number of items in the queue."""
def maxItems():
"""Returns the maximum number of items this queue can hold."""
class MemoryQueue(object):
"""Simple length bounded queue using deque.
list.pop(0) operation is O(n) so for a 10000 items list, it can start to
be real slow. On the contrary, deque.popleft() is O(1) most of the time.
See http://docs.python.org/library/collections.html for more
information.
"""
implements(IQueue)
def __init__(self, maxItems=None):
self._maxItems = maxItems
if self._maxItems is None:
self._maxItems = 10000
self._items = deque()
def pushItem(self, item):
ret = None
if len(self._items) == self._maxItems:
ret = self._items.popleft()
self._items.append(item)
return ret
def insertBackChunk(self, chunk):
ret = None
excess = len(self._items) + len(chunk) - self._maxItems
if excess > 0:
ret = chunk[0:excess]
chunk = chunk[excess:]
self._items.extendleft(reversed(chunk))
return ret
def popChunk(self, nbItems=None):
if nbItems is None:
nbItems = self._maxItems
if nbItems > len(self._items):
items = list(self._items)
self._items = deque()
else:
items = []
for i in range(nbItems):
items.append(self._items.popleft())
return items
def save(self):
pass
def items(self):
return list(self._items)
def nbItems(self):
return len(self._items)
def maxItems(self):
return self._maxItems
class DiskQueue(object):
"""Keeps a list of abstract items and serializes it to the disk.
Use pickle for serialization."""
implements(IQueue)
def __init__(self, path, maxItems=None, pickleFn=pickle.dumps,
unpickleFn=pickle.loads):
"""
@path: directory to save the items.
@maxItems: maximum number of items to keep on disk, flush the
older ones.
@pickleFn: function used to pack the items to disk.
@unpickleFn: function used to unpack items from disk.
"""
self.path = path
self._maxItems = maxItems
if self._maxItems is None:
self._maxItems = 100000
if not os.path.isdir(self.path):
os.mkdir(self.path)
self.pickleFn = pickleFn
self.unpickleFn = unpickleFn
# Total number of items.
self._nbItems = 0
# The actual items id start at one.
self.firstItemId = 0
self.lastItemId = 0
self._loadFromDisk()
def pushItem(self, item):
ret = None
if self._nbItems == self._maxItems:
id = self._findNext(self.firstItemId)
path = os.path.join(self.path, str(id))
ret = self.unpickleFn(ReadFile(path))
os.remove(path)
self.firstItemId = id + 1
else:
self._nbItems += 1
self.lastItemId += 1
path = os.path.join(self.path, str(self.lastItemId))
if os.path.exists(path):
raise IOError('%s already exists.' % path)
WriteFile(path, self.pickleFn(item))
return ret
def insertBackChunk(self, chunk):
ret = None
excess = self._nbItems + len(chunk) - self._maxItems
if excess > 0:
ret = chunk[0:excess]
chunk = chunk[excess:]
for i in reversed(chunk):
self.firstItemId -= 1
path = os.path.join(self.path, str(self.firstItemId))
if os.path.exists(path):
raise IOError('%s already exists.' % path)
WriteFile(path, self.pickleFn(i))
self._nbItems += 1
return ret
def popChunk(self, nbItems=None):
if nbItems is None:
nbItems = self._maxItems
ret = []
for i in range(nbItems):
if self._nbItems == 0:
break
id = self._findNext(self.firstItemId)
path = os.path.join(self.path, str(id))
ret.append(self.unpickleFn(ReadFile(path)))
os.remove(path)
self._nbItems -= 1
self.firstItemId = id + 1
return ret
def save(self):
pass
def items(self):
"""Warning, very slow."""
ret = []
for id in range(self.firstItemId, self.lastItemId + 1):
path = os.path.join(self.path, str(id))
if os.path.exists(path):
ret.append(self.unpickleFn(ReadFile(path)))
return ret
def nbItems(self):
return self._nbItems
def maxItems(self):
return self._maxItems
#### Protected functions
def _findNext(self, id):
while True:
path = os.path.join(self.path, str(id))
if os.path.isfile(path):
return id
id += 1
return None
def _loadFromDisk(self):
"""Loads the queue from disk upto self.maxMemoryItems items into
self.items.
"""
def SafeInt(item):
try:
return int(item)
except ValueError:
return None
files = filter(None, [SafeInt(x) for x in os.listdir(self.path)])
files.sort()
self._nbItems = len(files)
if self._nbItems:
self.firstItemId = files[0]
self.lastItemId = files[-1]
class PersistentQueue(object):
"""Keeps a list of abstract items and serializes it to the disk.
It has 2 layers of queue, normally an in-memory queue and an on-disk queue.
When the number of items in the primary queue gets too large, the new items
are automatically saved to the secondary queue. The older items are kept in
the primary queue.
"""
implements(IQueue)
def __init__(self, primaryQueue=None, secondaryQueue=None, path=None):
"""
@primaryQueue: memory queue to use before buffering to disk.
@secondaryQueue: disk queue to use as permanent buffer.
@path: path is a shortcut when using default DiskQueue settings.
"""
self.primaryQueue = primaryQueue
if self.primaryQueue is None:
self.primaryQueue = MemoryQueue()
self.secondaryQueue = secondaryQueue
if self.secondaryQueue is None:
self.secondaryQueue = DiskQueue(path)
# Preload data from the secondary queue only if we know we won't start
# using the secondary queue right away.
if self.secondaryQueue.nbItems() < self.primaryQueue.maxItems():
self.primaryQueue.insertBackChunk(
self.secondaryQueue.popChunk(self.primaryQueue.maxItems()))
def pushItem(self, item):
# If there is already items in secondaryQueue, we'd need to pop them
# all to start inserting them into primaryQueue so don't bother and
# just push it in secondaryQueue.
if (self.secondaryQueue.nbItems() or
self.primaryQueue.nbItems() == self.primaryQueue.maxItems()):
item = self.secondaryQueue.pushItem(item)
if item is None:
return item
# If item is not None, secondaryQueue overflowed. We need to push it
# back to primaryQueue so the oldest item is dumped.
# Or everything fit in the primaryQueue.
return self.primaryQueue.pushItem(item)
def insertBackChunk(self, chunk):
ret = None
# Overall excess
excess = self.nbItems() + len(chunk) - self.maxItems()
if excess > 0:
ret = chunk[0:excess]
chunk = chunk[excess:]
# Memory excess
excess = (self.primaryQueue.nbItems() + len(chunk) -
self.primaryQueue.maxItems())
if excess > 0:
chunk2 = []
for i in range(excess):
chunk2.append(self.primaryQueue.items().pop())
chunk2.reverse()
x = self.primaryQueue.insertBackChunk(chunk)
assert x is None, "primaryQueue.insertBackChunk did not return None"
if excess > 0:
x = self.secondaryQueue.insertBackChunk(chunk2)
assert x is None, ("secondaryQueue.insertBackChunk did not return "
" None")
return ret
def popChunk(self, nbItems=None):
if nbItems is None:
nbItems = self.primaryQueue.maxItems()
ret = self.primaryQueue.popChunk(nbItems)
nbItems -= len(ret)
if nbItems and self.secondaryQueue.nbItems():
ret.extend(self.secondaryQueue.popChunk(nbItems))
return ret
def save(self):
self.secondaryQueue.insertBackChunk(self.primaryQueue.popChunk())
def items(self):
return self.primaryQueue.items() + self.secondaryQueue.items()
def nbItems(self):
return self.primaryQueue.nbItems() + self.secondaryQueue.nbItems()
def maxItems(self):
return self.primaryQueue.maxItems() + self.secondaryQueue.maxItems()
class IndexedQueue(object):
"""Adds functionality to a IQueue object to track its usage.
Adds a new member function getIndex() and modify popChunk() and
insertBackChunk() to keep a virtual pointer to the queue's first entry
index."""
implements(IQueue)
def __init__(self, queue):
# Copy all the member functions from the other object that this class
# doesn't already define.
assert IQueue.providedBy(queue)
def Filter(m):
return (m[0] != '_' and callable(getattr(queue, m))
and not hasattr(self, m))
for member in filter(Filter, dir(queue)):
setattr(self, member, getattr(queue, member))
self.queue = queue
self._index = 0
def getIndex(self):
return self._index
def popChunk(self, *args, **kwargs):
items = self.queue.popChunk(*args, **kwargs)
if items:
self._index += len(items)
return items
def insertBackChunk(self, items):
self._index -= len(items)
ret = self.queue.insertBackChunk(items)
if ret:
self._index += len(ret)
return ret
def ToIndexedQueue(queue):
"""If the IQueue wasn't already a IndexedQueue, makes it an IndexedQueue."""
if not IQueue.providedBy(queue):
raise TypeError("queue doesn't implement IQueue", queue)
if isinstance(queue, IndexedQueue):
return queue
return IndexedQueue(queue)
# vim: set ts=4 sts=4 sw=4 et:
|
|
#!/usr/bin/python
# Copyright (C) 2015, WSID
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import unittest
from gi.repository import GObject
from gi.repository import CrankBase
class TestDigraph(unittest.TestCase):
def setUp (self):
self.graph = CrankBase.Digraph ()
self.nodes = [self.graph.add (i) for i in range (9)]
self.edges = []
# 0
# 1->2, 1->3, 2->3
self.edges.append (self.graph.connect (self.nodes[1], self.nodes[2], 17.3))
self.edges.append (self.graph.connect (self.nodes[1], self.nodes[3], 32.1))
self.edges.append (self.graph.connect (self.nodes[2], self.nodes[3], 18.3))
# 4->5, 4->6, 4->7, 5->8, 7->6
self.edges.append (self.graph.connect (self.nodes[4], self.nodes[5], 21.3))
self.edges.append (self.graph.connect (self.nodes[4], self.nodes[6], 10.5))
self.edges.append (self.graph.connect (self.nodes[4], self.nodes[7], 17.5))
self.edges.append (self.graph.connect (self.nodes[5], self.nodes[8], 9.4))
self.edges.append (self.graph.connect (self.nodes[7], self.nodes[6], 19.6))
def test_get_nodes (self):
self.assertEqual (self.graph.get_nodes (), self.nodes)
def test_get_edges (self):
self.assertEqual (self.graph.get_edges (), self.edges)
def test_disconnect (self):
assert (self.graph.disconnect (self.nodes[2], self.nodes[3]))
assert (self.graph.disconnect (self.nodes[4], self.nodes[6]))
assert (not self.graph.disconnect (self.nodes[0], self.nodes[1]))
assert (not self.graph.disconnect (self.nodes[6], self.nodes[7]))
assert (not self.graph.disconnect (self.nodes[4], self.nodes[8]))
assert (not self.graph.disconnect (self.nodes[4], self.nodes[6]))
edge_list = self.graph.get_edges ();
assert (not (self.edges[2] in edge_list))
assert (not (self.edges[4] in edge_list))
def test_disconnect_edge (self):
self.graph.disconnect_edge (self.edges[2])
self.graph.disconnect_edge (self.edges[4])
edge_list = self.graph.get_edges ();
assert (not (self.edges[2] in edge_list))
assert (not (self.edges[4] in edge_list))
def test_node_get_data (self):
node_v = GObject.Value (value_type=int)
for i in range (9):
self.assertEqual (self.nodes[i].get_data (), i)
def test_node_get_in_edges (self):
self.assertEqual (
self.nodes[3].get_in_edges (),
[self.edges[1], self.edges[2]]
)
def test_node_get_out_edges (self):
self.assertEqual (
self.nodes[4].get_out_edges (),
[self.edges[3], self.edges[4], self.edges[5]]
)
def test_node_get_in_nodes (self):
self.assertEqual (
self.nodes[3].get_in_nodes (),
[self.nodes[1], self.nodes[2]]
)
def test_node_get_indegree (self):
self.assertEqual (self.nodes[2].get_indegree (), 1)
self.assertEqual (self.nodes[5].get_indegree (), 1)
self.assertEqual (self.nodes[6].get_indegree (), 2)
def test_node_get_outdegree (self):
self.assertEqual (self.nodes[2].get_outdegree (), 1)
self.assertEqual (self.nodes[5].get_outdegree (), 1)
self.assertEqual (self.nodes[6].get_outdegree (), 0)
def test_node_is_adjacent (self):
assert (self.nodes[2].is_adjacent (self.nodes[3]))
assert (self.nodes[4].is_adjacent (self.nodes[6]))
assert (self.nodes[6].is_adjacent (self.nodes[7]))
assert (not self.nodes[0].is_adjacent (self.nodes[2]))
assert (not self.nodes[4].is_adjacent (self.nodes[8]))
def test_node_is_adjacent_from (self):
assert (self.nodes[3].is_adjacent_from (self.nodes[2]))
assert (self.nodes[6].is_adjacent_from (self.nodes[4]))
assert (not self.nodes[7].is_adjacent_from (self.nodes[6]))
assert (not self.nodes[2].is_adjacent_from (self.nodes[3]))
assert (not self.nodes[8].is_adjacent_from (self.nodes[8]))
def test_node_is_adjacent_to (self):
assert (self.nodes[2].is_adjacent_to (self.nodes[3]))
assert (self.nodes[4].is_adjacent_to (self.nodes[6]))
assert (not self.nodes[6].is_adjacent_to (self.nodes[7]))
assert (not self.nodes[0].is_adjacent_to (self.nodes[2]))
assert (not self.nodes[4].is_adjacent_to (self.nodes[8]))
def test_node_foreach_depth (self):
iter_nodes = []
def accum (n):
iter_nodes.append (n)
return True
self.nodes[0].foreach_depth (accum)
self.assertEqual (iter_nodes, [self.nodes[0]]);
iter_nodes = []
self.nodes[1].foreach_depth (accum)
self.assertEqual (iter_nodes,
[self.nodes[1],
self.nodes[3],
self.nodes[2]] )
iter_nodes = []
self.nodes[4].foreach_depth (accum)
self.assertEqual (iter_nodes,
[self.nodes[4],
self.nodes[7],
self.nodes[6],
self.nodes[5],
self.nodes[8]] )
def test_node_foreach_breadth (self):
iter_nodes = []
def accum (n):
iter_nodes.append (n)
return True
self.nodes[0].foreach_breadth (accum)
self.assertEqual (iter_nodes, [self.nodes[0]]);
iter_nodes = []
self.nodes[1].foreach_breadth (accum)
self.assertEqual (iter_nodes,
[self.nodes[1],
self.nodes[2],
self.nodes[3]] )
iter_nodes = []
self.nodes[4].foreach_breadth (accum)
self.assertEqual (iter_nodes,
[self.nodes[4],
self.nodes[5],
self.nodes[6],
self.nodes[7],
self.nodes[8]] )
def test_edge_get_data (self):
self.assertEqual (self.edges[5].get_data (), 17.5)
def test_edge_get_tail (self):
self.assertEqual (self.edges[3].get_tail (), self.nodes[4])
self.assertEqual (self.edges[5].get_tail (), self.nodes[4])
self.assertEqual (self.edges[7].get_tail (), self.nodes[7])
def test_edge_get_head (self):
self.assertEqual (self.edges[1].get_head (), self.nodes[3])
self.assertEqual (self.edges[2].get_head (), self.nodes[3])
self.assertEqual (self.edges[4].get_head (), self.nodes[6])
if __name__ == '__main__':
unittest.main ()
|
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import unittest
import faiss
import tempfile
import os
import io
import sys
import pickle
from multiprocessing.dummy import Pool as ThreadPool
class TestIOVariants(unittest.TestCase):
def test_io_error(self):
d, n = 32, 1000
x = np.random.uniform(size=(n, d)).astype('float32')
index = faiss.IndexFlatL2(d)
index.add(x)
fd, fname = tempfile.mkstemp()
os.close(fd)
try:
faiss.write_index(index, fname)
# should be fine
faiss.read_index(fname)
with open(fname, 'rb') as f:
data = f.read()
# now damage file
with open(fname, 'wb') as f:
f.write(data[:int(len(data) / 2)])
# should make a nice readable exception that mentions the filename
try:
faiss.read_index(fname)
except RuntimeError as e:
if fname not in str(e):
raise
else:
raise
finally:
if os.path.exists(fname):
os.unlink(fname)
class TestCallbacks(unittest.TestCase):
def do_write_callback(self, bsz):
d, n = 32, 1000
x = np.random.uniform(size=(n, d)).astype('float32')
index = faiss.IndexFlatL2(d)
index.add(x)
f = io.BytesIO()
# test with small block size
writer = faiss.PyCallbackIOWriter(f.write, 1234)
if bsz > 0:
writer = faiss.BufferedIOWriter(writer, bsz)
faiss.write_index(index, writer)
del writer # make sure all writes committed
if sys.version_info[0] < 3:
buf = f.getvalue()
else:
buf = f.getbuffer()
index2 = faiss.deserialize_index(np.frombuffer(buf, dtype='uint8'))
self.assertEqual(index.d, index2.d)
np.testing.assert_array_equal(
faiss.vector_to_array(index.codes),
faiss.vector_to_array(index2.codes)
)
# This is not a callable function: shoudl raise an exception
writer = faiss.PyCallbackIOWriter("blabla")
self.assertRaises(
Exception,
faiss.write_index, index, writer
)
def test_buf_read(self):
x = np.random.uniform(size=20)
fd, fname = tempfile.mkstemp()
os.close(fd)
try:
x.tofile(fname)
with open(fname, 'rb') as f:
reader = faiss.PyCallbackIOReader(f.read, 1234)
bsz = 123
reader = faiss.BufferedIOReader(reader, bsz)
y = np.zeros_like(x)
print('nbytes=', y.nbytes)
reader(faiss.swig_ptr(y), y.nbytes, 1)
np.testing.assert_array_equal(x, y)
finally:
if os.path.exists(fname):
os.unlink(fname)
def do_read_callback(self, bsz):
d, n = 32, 1000
x = np.random.uniform(size=(n, d)).astype('float32')
index = faiss.IndexFlatL2(d)
index.add(x)
fd, fname = tempfile.mkstemp()
os.close(fd)
try:
faiss.write_index(index, fname)
with open(fname, 'rb') as f:
reader = faiss.PyCallbackIOReader(f.read, 1234)
if bsz > 0:
reader = faiss.BufferedIOReader(reader, bsz)
index2 = faiss.read_index(reader)
self.assertEqual(index.d, index2.d)
np.testing.assert_array_equal(
faiss.vector_to_array(index.codes),
faiss.vector_to_array(index2.codes)
)
# This is not a callable function: should raise an exception
reader = faiss.PyCallbackIOReader("blabla")
self.assertRaises(
Exception,
faiss.read_index, reader
)
finally:
if os.path.exists(fname):
os.unlink(fname)
def test_write_callback(self):
self.do_write_callback(0)
def test_write_buffer(self):
self.do_write_callback(123)
self.do_write_callback(2345)
def test_read_callback(self):
self.do_read_callback(0)
def test_read_callback_buffered(self):
self.do_read_callback(123)
self.do_read_callback(12345)
def test_read_buffer(self):
d, n = 32, 1000
x = np.random.uniform(size=(n, d)).astype('float32')
index = faiss.IndexFlatL2(d)
index.add(x)
fd, fname = tempfile.mkstemp()
os.close(fd)
try:
faiss.write_index(index, fname)
reader = faiss.BufferedIOReader(
faiss.FileIOReader(fname), 1234)
index2 = faiss.read_index(reader)
self.assertEqual(index.d, index2.d)
np.testing.assert_array_equal(
faiss.vector_to_array(index.codes),
faiss.vector_to_array(index2.codes)
)
finally:
del reader
if os.path.exists(fname):
os.unlink(fname)
def test_transfer_pipe(self):
""" transfer an index through a Unix pipe """
d, n = 32, 1000
x = np.random.uniform(size=(n, d)).astype('float32')
index = faiss.IndexFlatL2(d)
index.add(x)
Dref, Iref = index.search(x, 10)
rf, wf = os.pipe()
# start thread that will decompress the index
def index_from_pipe():
reader = faiss.PyCallbackIOReader(lambda size: os.read(rf, size))
return faiss.read_index(reader)
with ThreadPool(1) as pool:
fut = pool.apply_async(index_from_pipe, ())
# write to pipe
writer = faiss.PyCallbackIOWriter(lambda b: os.write(wf, b))
faiss.write_index(index, writer)
index2 = fut.get()
# closing is not really useful but it does not hurt
os.close(wf)
os.close(rf)
Dnew, Inew = index2.search(x, 10)
np.testing.assert_array_equal(Iref, Inew)
np.testing.assert_array_equal(Dref, Dnew)
class PyOndiskInvertedLists:
""" wraps an OnDisk object for use from C++ """
def __init__(self, oil):
self.oil = oil
def list_size(self, list_no):
return self.oil.list_size(list_no)
def get_codes(self, list_no):
oil = self.oil
assert 0 <= list_no < oil.lists.size()
l = oil.lists.at(list_no)
with open(oil.filename, 'rb') as f:
f.seek(l.offset)
return f.read(l.size * oil.code_size)
def get_ids(self, list_no):
oil = self.oil
assert 0 <= list_no < oil.lists.size()
l = oil.lists.at(list_no)
with open(oil.filename, 'rb') as f:
f.seek(l.offset + l.capacity * oil.code_size)
return f.read(l.size * 8)
class TestPickle(unittest.TestCase):
def dump_load_factory(self, fs):
xq = faiss.randn((25, 10), 123)
xb = faiss.randn((25, 10), 124)
index = faiss.index_factory(10, fs)
index.train(xb)
index.add(xb)
Dref, Iref = index.search(xq, 4)
buf = io.BytesIO()
pickle.dump(index, buf)
buf.seek(0)
index2 = pickle.load(buf)
Dnew, Inew = index2.search(xq, 4)
np.testing.assert_array_equal(Iref, Inew)
np.testing.assert_array_equal(Dref, Dnew)
def test_flat(self):
self.dump_load_factory("Flat")
def test_hnsw(self):
self.dump_load_factory("HNSW32")
def test_ivf(self):
self.dump_load_factory("IVF5,Flat")
|
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# coding: utf-8
# pylint: disable=unnecessary-pass
"""Data iterators for common data formats."""
from collections import namedtuple
import sys
import ctypes
import logging
import threading
import numpy as np
from ..base import _LIB
from ..base import c_str_array, mx_uint, py_str
from ..base import DataIterHandle, NDArrayHandle
from ..base import mx_real_t
from ..base import check_call, build_param_doc as _build_param_doc
from ..ndarray import NDArray
from ..ndarray.sparse import CSRNDArray
from ..util import is_np_array
from ..ndarray import array
from ..ndarray import concat, tile
from .utils import _init_data, _has_instance, _getdata_by_idx
class DataDesc(namedtuple('DataDesc', ['name', 'shape'])):
"""DataDesc is used to store name, shape, type and layout
information of the data or the label.
The `layout` describes how the axes in `shape` should be interpreted,
for example for image data setting `layout=NCHW` indicates
that the first axis is number of examples in the batch(N),
C is number of channels, H is the height and W is the width of the image.
For sequential data, by default `layout` is set to ``NTC``, where
N is number of examples in the batch, T the temporal axis representing time
and C is the number of channels.
Parameters
----------
cls : DataDesc
The class.
name : str
Data name.
shape : tuple of int
Data shape.
dtype : np.dtype, optional
Data type.
layout : str, optional
Data layout.
"""
def __new__(cls, name, shape, dtype=mx_real_t, layout='NCHW'): # pylint: disable=super-on-old-class
ret = super(cls, DataDesc).__new__(cls, name, shape)
ret.dtype = dtype
ret.layout = layout
return ret
def __repr__(self):
return "DataDesc[%s,%s,%s,%s]" % (self.name, self.shape, self.dtype,
self.layout)
@staticmethod
def get_batch_axis(layout):
"""Get the dimension that corresponds to the batch size.
When data parallelism is used, the data will be automatically split and
concatenated along the batch-size dimension. Axis can be -1, which means
the whole array will be copied for each data-parallelism device.
Parameters
----------
layout : str
layout string. For example, "NCHW".
Returns
-------
int
An axis indicating the batch_size dimension.
"""
if layout is None:
return 0
return layout.find('N')
@staticmethod
def get_list(shapes, types):
"""Get DataDesc list from attribute lists.
Parameters
----------
shapes : a tuple of (name, shape)
types : a tuple of (name, np.dtype)
"""
if types is not None:
type_dict = dict(types)
return [DataDesc(x[0], x[1], type_dict[x[0]]) for x in shapes]
else:
return [DataDesc(x[0], x[1]) for x in shapes]
class DataBatch(object):
"""A data batch.
MXNet's data iterator returns a batch of data for each `next` call.
This data contains `batch_size` number of examples.
If the input data consists of images, then shape of these images depend on
the `layout` attribute of `DataDesc` object in `provide_data` parameter.
If `layout` is set to 'NCHW' then, images should be stored in a 4-D matrix
of shape ``(batch_size, num_channel, height, width)``.
If `layout` is set to 'NHWC' then, images should be stored in a 4-D matrix
of shape ``(batch_size, height, width, num_channel)``.
The channels are often in RGB order.
Parameters
----------
data : list of `NDArray`, each array containing `batch_size` examples.
A list of input data.
label : list of `NDArray`, each array often containing a 1-dimensional array. optional
A list of input labels.
pad : int, optional
The number of examples padded at the end of a batch. It is used when the
total number of examples read is not divisible by the `batch_size`.
These extra padded examples are ignored in prediction.
index : numpy.array, optional
The example indices in this batch.
bucket_key : int, optional
The bucket key, used for bucketing module.
provide_data : list of `DataDesc`, optional
A list of `DataDesc` objects. `DataDesc` is used to store
name, shape, type and layout information of the data.
The *i*-th element describes the name and shape of ``data[i]``.
provide_label : list of `DataDesc`, optional
A list of `DataDesc` objects. `DataDesc` is used to store
name, shape, type and layout information of the label.
The *i*-th element describes the name and shape of ``label[i]``.
"""
def __init__(self, data, label=None, pad=None, index=None,
bucket_key=None, provide_data=None, provide_label=None):
if data is not None:
assert isinstance(data, (list, tuple)), "Data must be list of NDArrays"
if label is not None:
assert isinstance(label, (list, tuple)), "Label must be list of NDArrays"
self.data = data
self.label = label
self.pad = pad
self.index = index
self.bucket_key = bucket_key
self.provide_data = provide_data
self.provide_label = provide_label
def __str__(self):
data_shapes = [d.shape for d in self.data]
if self.label:
label_shapes = [l.shape for l in self.label]
else:
label_shapes = None
return "{}: data shapes: {} label shapes: {}".format(
self.__class__.__name__,
data_shapes,
label_shapes)
class DataIter(object):
"""The base class for an MXNet data iterator.
All I/O in MXNet is handled by specializations of this class. Data iterators
in MXNet are similar to standard-iterators in Python. On each call to `next`
they return a `DataBatch` which represents the next batch of data. When
there is no more data to return, it raises a `StopIteration` exception.
Parameters
----------
batch_size : int, optional
The batch size, namely the number of items in the batch.
See Also
--------
NDArrayIter : Data-iterator for MXNet NDArray or numpy-ndarray objects.
CSVIter : Data-iterator for csv data.
LibSVMIter : Data-iterator for libsvm data.
ImageIter : Data-iterator for images.
"""
def __init__(self, batch_size=0):
self.batch_size = batch_size
def __iter__(self):
return self
def reset(self):
"""Reset the iterator to the begin of the data."""
pass
def next(self):
"""Get next data batch from iterator.
Returns
-------
DataBatch
The data of next batch.
Raises
------
StopIteration
If the end of the data is reached.
"""
if self.iter_next():
return DataBatch(data=self.getdata(), label=self.getlabel(), \
pad=self.getpad(), index=self.getindex())
else:
raise StopIteration
def __next__(self):
return self.next()
def iter_next(self):
"""Move to the next batch.
Returns
-------
boolean
Whether the move is successful.
"""
pass
def getdata(self):
"""Get data of current batch.
Returns
-------
list of NDArray
The data of the current batch.
"""
pass
def getlabel(self):
"""Get label of the current batch.
Returns
-------
list of NDArray
The label of the current batch.
"""
pass
def getindex(self):
"""Get index of the current batch.
Returns
-------
index : numpy.array
The indices of examples in the current batch.
"""
return None
def getpad(self):
"""Get the number of padding examples in the current batch.
Returns
-------
int
Number of padding examples in the current batch.
"""
pass
class ResizeIter(DataIter):
"""Resize a data iterator to a given number of batches.
Parameters
----------
data_iter : DataIter
The data iterator to be resized.
size : int
The number of batches per epoch to resize to.
reset_internal : bool
Whether to reset internal iterator on ResizeIter.reset.
Examples
--------
>>> nd_iter = mx.io.NDArrayIter(mx.nd.ones((100,10)), batch_size=25)
>>> resize_iter = mx.io.ResizeIter(nd_iter, 2)
>>> for batch in resize_iter:
... print(batch.data)
[<NDArray 25x10 @cpu(0)>]
[<NDArray 25x10 @cpu(0)>]
"""
def __init__(self, data_iter, size, reset_internal=True):
super(ResizeIter, self).__init__()
self.data_iter = data_iter
self.size = size
self.reset_internal = reset_internal
self.cur = 0
self.current_batch = None
self.provide_data = data_iter.provide_data
self.provide_label = data_iter.provide_label
self.batch_size = data_iter.batch_size
if hasattr(data_iter, 'default_bucket_key'):
self.default_bucket_key = data_iter.default_bucket_key
def reset(self):
self.cur = 0
if self.reset_internal:
self.data_iter.reset()
def iter_next(self):
if self.cur == self.size:
return False
try:
self.current_batch = self.data_iter.next()
except StopIteration:
self.data_iter.reset()
self.current_batch = self.data_iter.next()
self.cur += 1
return True
def getdata(self):
return self.current_batch.data
def getlabel(self):
return self.current_batch.label
def getindex(self):
return self.current_batch.index
def getpad(self):
return self.current_batch.pad
class PrefetchingIter(DataIter):
"""Performs pre-fetch for other data iterators.
This iterator will create another thread to perform ``iter_next`` and then
store the data in memory. It potentially accelerates the data read, at the
cost of more memory usage.
Parameters
----------
iters : DataIter or list of DataIter
The data iterators to be pre-fetched.
rename_data : None or list of dict
The *i*-th element is a renaming map for the *i*-th iter, in the form of
{'original_name' : 'new_name'}. Should have one entry for each entry
in iter[i].provide_data.
rename_label : None or list of dict
Similar to ``rename_data``.
Examples
--------
>>> iter1 = mx.io.NDArrayIter({'data':mx.nd.ones((100,10))}, batch_size=25)
>>> iter2 = mx.io.NDArrayIter({'data':mx.nd.ones((100,10))}, batch_size=25)
>>> piter = mx.io.PrefetchingIter([iter1, iter2],
... rename_data=[{'data': 'data_1'}, {'data': 'data_2'}])
>>> print(piter.provide_data)
[DataDesc[data_1,(25, 10L),<type 'numpy.float32'>,NCHW],
DataDesc[data_2,(25, 10L),<type 'numpy.float32'>,NCHW]]
"""
def __init__(self, iters, rename_data=None, rename_label=None):
super(PrefetchingIter, self).__init__()
if not isinstance(iters, list):
iters = [iters]
self.n_iter = len(iters)
assert self.n_iter > 0
self.iters = iters
self.rename_data = rename_data
self.rename_label = rename_label
self.batch_size = self.provide_data[0][1][0]
self.data_ready = [threading.Event() for i in range(self.n_iter)]
self.data_taken = [threading.Event() for i in range(self.n_iter)]
for i in self.data_taken:
i.set()
self.started = True
self.current_batch = [None for i in range(self.n_iter)]
self.next_batch = [None for i in range(self.n_iter)]
def prefetch_func(self, i):
"""Thread entry"""
while True:
self.data_taken[i].wait()
if not self.started:
break
try:
self.next_batch[i] = self.iters[i].next()
except StopIteration:
self.next_batch[i] = None
self.data_taken[i].clear()
self.data_ready[i].set()
self.prefetch_threads = [threading.Thread(target=prefetch_func, args=[self, i]) \
for i in range(self.n_iter)]
for thread in self.prefetch_threads:
thread.setDaemon(True)
thread.start()
def __del__(self):
self.started = False
for i in self.data_taken:
i.set()
for thread in self.prefetch_threads:
thread.join()
@property
def provide_data(self):
if self.rename_data is None:
return sum([i.provide_data for i in self.iters], [])
else:
return sum([[
DataDesc(r[x.name], x.shape, x.dtype)
if isinstance(x, DataDesc) else DataDesc(*x)
for x in i.provide_data
] for r, i in zip(self.rename_data, self.iters)], [])
@property
def provide_label(self):
if self.rename_label is None:
return sum([i.provide_label for i in self.iters], [])
else:
return sum([[
DataDesc(r[x.name], x.shape, x.dtype)
if isinstance(x, DataDesc) else DataDesc(*x)
for x in i.provide_label
] for r, i in zip(self.rename_label, self.iters)], [])
def reset(self):
for i in self.data_ready:
i.wait()
for i in self.iters:
i.reset()
for i in self.data_ready:
i.clear()
for i in self.data_taken:
i.set()
def iter_next(self):
for i in self.data_ready:
i.wait()
if self.next_batch[0] is None:
for i in self.next_batch:
assert i is None, "Number of entry mismatches between iterators"
return False
else:
for batch in self.next_batch:
assert batch.pad == self.next_batch[0].pad, \
"Number of entry mismatches between iterators"
self.current_batch = DataBatch(sum([batch.data for batch in self.next_batch], []),
sum([batch.label for batch in self.next_batch], []),
self.next_batch[0].pad,
self.next_batch[0].index,
provide_data=self.provide_data,
provide_label=self.provide_label)
for i in self.data_ready:
i.clear()
for i in self.data_taken:
i.set()
return True
def next(self):
if self.iter_next():
return self.current_batch
else:
raise StopIteration
def getdata(self):
return self.current_batch.data
def getlabel(self):
return self.current_batch.label
def getindex(self):
return self.current_batch.index
def getpad(self):
return self.current_batch.pad
class NDArrayIter(DataIter):
"""Returns an iterator for ``mx.nd.NDArray``, ``numpy.ndarray``, ``h5py.Dataset``
``mx.nd.sparse.CSRNDArray`` or ``scipy.sparse.csr_matrix``.
Examples
--------
>>> data = np.arange(40).reshape((10,2,2))
>>> labels = np.ones([10, 1])
>>> dataiter = mx.io.NDArrayIter(data, labels, 3, True, last_batch_handle='discard')
>>> for batch in dataiter:
... print batch.data[0].asnumpy()
... batch.data[0].shape
...
[[[ 36. 37.]
[ 38. 39.]]
[[ 16. 17.]
[ 18. 19.]]
[[ 12. 13.]
[ 14. 15.]]]
(3L, 2L, 2L)
[[[ 32. 33.]
[ 34. 35.]]
[[ 4. 5.]
[ 6. 7.]]
[[ 24. 25.]
[ 26. 27.]]]
(3L, 2L, 2L)
[[[ 8. 9.]
[ 10. 11.]]
[[ 20. 21.]
[ 22. 23.]]
[[ 28. 29.]
[ 30. 31.]]]
(3L, 2L, 2L)
>>> dataiter.provide_data # Returns a list of `DataDesc`
[DataDesc[data,(3, 2L, 2L),<type 'numpy.float32'>,NCHW]]
>>> dataiter.provide_label # Returns a list of `DataDesc`
[DataDesc[softmax_label,(3, 1L),<type 'numpy.float32'>,NCHW]]
In the above example, data is shuffled as `shuffle` parameter is set to `True`
and remaining examples are discarded as `last_batch_handle` parameter is set to `discard`.
Usage of `last_batch_handle` parameter:
>>> dataiter = mx.io.NDArrayIter(data, labels, 3, True, last_batch_handle='pad')
>>> batchidx = 0
>>> for batch in dataiter:
... batchidx += 1
...
>>> batchidx # Padding added after the examples read are over. So, 10/3+1 batches are created.
4
>>> dataiter = mx.io.NDArrayIter(data, labels, 3, True, last_batch_handle='discard')
>>> batchidx = 0
>>> for batch in dataiter:
... batchidx += 1
...
>>> batchidx # Remaining examples are discarded. So, 10/3 batches are created.
3
>>> dataiter = mx.io.NDArrayIter(data, labels, 3, False, last_batch_handle='roll_over')
>>> batchidx = 0
>>> for batch in dataiter:
... batchidx += 1
...
>>> batchidx # Remaining examples are rolled over to the next iteration.
3
>>> dataiter.reset()
>>> dataiter.next().data[0].asnumpy()
[[[ 36. 37.]
[ 38. 39.]]
[[ 0. 1.]
[ 2. 3.]]
[[ 4. 5.]
[ 6. 7.]]]
(3L, 2L, 2L)
`NDArrayIter` also supports multiple input and labels.
>>> data = {'data1':np.zeros(shape=(10,2,2)), 'data2':np.zeros(shape=(20,2,2))}
>>> label = {'label1':np.zeros(shape=(10,1)), 'label2':np.zeros(shape=(20,1))}
>>> dataiter = mx.io.NDArrayIter(data, label, 3, True, last_batch_handle='discard')
`NDArrayIter` also supports ``mx.nd.sparse.CSRNDArray``
with `last_batch_handle` set to `discard`.
>>> csr_data = mx.nd.array(np.arange(40).reshape((10,4))).tostype('csr')
>>> labels = np.ones([10, 1])
>>> dataiter = mx.io.NDArrayIter(csr_data, labels, 3, last_batch_handle='discard')
>>> [batch.data[0] for batch in dataiter]
[
<CSRNDArray 3x4 @cpu(0)>,
<CSRNDArray 3x4 @cpu(0)>,
<CSRNDArray 3x4 @cpu(0)>]
Parameters
----------
data: array or list of array or dict of string to array
The input data.
label: array or list of array or dict of string to array, optional
The input label.
batch_size: int
Batch size of data.
shuffle: bool, optional
Whether to shuffle the data.
Only supported if no h5py.Dataset inputs are used.
last_batch_handle : str, optional
How to handle the last batch. This parameter can be 'pad', 'discard' or
'roll_over'.
If 'pad', the last batch will be padded with data starting from the begining
If 'discard', the last batch will be discarded
If 'roll_over', the remaining elements will be rolled over to the next iteration and
note that it is intended for training and can cause problems if used for prediction.
data_name : str, optional
The data name.
label_name : str, optional
The label name.
"""
def __init__(self, data, label=None, batch_size=1, shuffle=False,
last_batch_handle='pad', data_name='data',
label_name='softmax_label'):
super(NDArrayIter, self).__init__(batch_size)
self.data = _init_data(data, allow_empty=False, default_name=data_name)
self.label = _init_data(label, allow_empty=True, default_name=label_name)
if ((_has_instance(self.data, CSRNDArray) or
_has_instance(self.label, CSRNDArray)) and
(last_batch_handle != 'discard')):
raise NotImplementedError("`NDArrayIter` only supports ``CSRNDArray``" \
" with `last_batch_handle` set to `discard`.")
self.idx = np.arange(self.data[0][1].shape[0])
self.shuffle = shuffle
self.last_batch_handle = last_batch_handle
self.batch_size = batch_size
self.cursor = -self.batch_size
self.num_data = self.idx.shape[0]
# shuffle
self.reset()
self.data_list = [x[1] for x in self.data] + [x[1] for x in self.label]
self.num_source = len(self.data_list)
# used for 'roll_over'
self._cache_data = None
self._cache_label = None
@property
def provide_data(self):
"""The name and shape of data provided by this iterator."""
return [
DataDesc(k, tuple([self.batch_size] + list(v.shape[1:])), v.dtype)
for k, v in self.data
]
@property
def provide_label(self):
"""The name and shape of label provided by this iterator."""
return [
DataDesc(k, tuple([self.batch_size] + list(v.shape[1:])), v.dtype)
for k, v in self.label
]
def hard_reset(self):
"""Ignore roll over data and set to start."""
if self.shuffle:
self._shuffle_data()
self.cursor = -self.batch_size
self._cache_data = None
self._cache_label = None
def reset(self):
"""Resets the iterator to the beginning of the data."""
if self.shuffle:
self._shuffle_data()
# the range below indicate the last batch
if self.last_batch_handle == 'roll_over' and \
self.num_data - self.batch_size < self.cursor < self.num_data:
# (self.cursor - self.num_data) represents the data we have for the last batch
self.cursor = self.cursor - self.num_data - self.batch_size
else:
self.cursor = -self.batch_size
def iter_next(self):
"""Increments the coursor by batch_size for next batch
and check current cursor if it exceed the number of data points."""
self.cursor += self.batch_size
return self.cursor < self.num_data
def next(self):
"""Returns the next batch of data."""
if not self.iter_next():
raise StopIteration
data = self.getdata()
label = self.getlabel()
# iter should stop when last batch is not complete
if data[0].shape[0] != self.batch_size:
# in this case, cache it for next epoch
self._cache_data = data
self._cache_label = label
raise StopIteration
return DataBatch(data=data, label=label, \
pad=self.getpad(), index=None)
def _getdata(self, data_source, start=None, end=None):
"""Load data from underlying arrays."""
assert start is not None or end is not None, 'should at least specify start or end'
start = start if start is not None else 0
if end is None:
end = data_source[0][1].shape[0] if data_source else 0
s = slice(start, end)
return [
x[1][s]
if isinstance(x[1], (np.ndarray, NDArray)) else
# h5py (only supports indices in increasing order)
array(x[1][sorted(self.idx[s])][[
list(self.idx[s]).index(i)
for i in sorted(self.idx[s])
]]) for x in data_source
]
def _concat(self, first_data, second_data):
"""Helper function to concat two NDArrays."""
if (not first_data) or (not second_data):
return first_data if first_data else second_data
assert len(first_data) == len(
second_data), 'data source should contain the same size'
return [
concat(
first_data[i],
second_data[i],
dim=0
) for i in range(len(first_data))
]
def _tile(self, data, repeats):
if not data:
return []
res = []
for datum in data:
reps = [1] * len(datum.shape)
reps[0] = repeats
res.append(tile(datum, reps))
return res
def _batchify(self, data_source):
"""Load data from underlying arrays, internal use only."""
assert self.cursor < self.num_data, 'DataIter needs reset.'
# first batch of next epoch with 'roll_over'
if self.last_batch_handle == 'roll_over' and \
-self.batch_size < self.cursor < 0:
assert self._cache_data is not None or self._cache_label is not None, \
'next epoch should have cached data'
cache_data = self._cache_data if self._cache_data is not None else self._cache_label
second_data = self._getdata(
data_source, end=self.cursor + self.batch_size)
if self._cache_data is not None:
self._cache_data = None
else:
self._cache_label = None
return self._concat(cache_data, second_data)
# last batch with 'pad'
elif self.last_batch_handle == 'pad' and \
self.cursor + self.batch_size > self.num_data:
pad = self.batch_size - self.num_data + self.cursor
first_data = self._getdata(data_source, start=self.cursor)
if pad > self.num_data:
repeats = pad // self.num_data
second_data = self._tile(self._getdata(data_source, end=self.num_data), repeats)
if pad % self.num_data != 0:
second_data = self._concat(second_data, self._getdata(data_source, end=pad % self.num_data))
else:
second_data = self._getdata(data_source, end=pad)
return self._concat(first_data, second_data)
# normal case
else:
if self.cursor + self.batch_size < self.num_data:
end_idx = self.cursor + self.batch_size
# get incomplete last batch
else:
end_idx = self.num_data
return self._getdata(data_source, self.cursor, end_idx)
def getdata(self):
"""Get data."""
return self._batchify(self.data)
def getlabel(self):
"""Get label."""
return self._batchify(self.label)
def getpad(self):
"""Get pad value of DataBatch."""
if self.last_batch_handle == 'pad' and \
self.cursor + self.batch_size > self.num_data:
return self.cursor + self.batch_size - self.num_data
# check the first batch
elif self.last_batch_handle == 'roll_over' and \
-self.batch_size < self.cursor < 0:
return -self.cursor
else:
return 0
def _shuffle_data(self):
"""Shuffle the data."""
# shuffle index
np.random.shuffle(self.idx)
# get the data by corresponding index
self.data = _getdata_by_idx(self.data, self.idx)
self.label = _getdata_by_idx(self.label, self.idx)
class MXDataIter(DataIter):
"""A python wrapper a C++ data iterator.
This iterator is the Python wrapper to all native C++ data iterators, such
as `CSVIter`, `ImageRecordIter`, `MNISTIter`, etc. When initializing
`CSVIter` for example, you will get an `MXDataIter` instance to use in your
Python code. Calls to `next`, `reset`, etc will be delegated to the
underlying C++ data iterators.
Usually you don't need to interact with `MXDataIter` directly unless you are
implementing your own data iterators in C++. To do that, please refer to
examples under the `src/io` folder.
Parameters
----------
handle : DataIterHandle, required
The handle to the underlying C++ Data Iterator.
data_name : str, optional
Data name. Default to "data".
label_name : str, optional
Label name. Default to "softmax_label".
See Also
--------
src/io : The underlying C++ data iterator implementation, e.g., `CSVIter`.
"""
def __init__(self, handle, data_name='data', label_name='softmax_label', **kwargs):
super(MXDataIter, self).__init__()
from ..ndarray import _ndarray_cls
from ..numpy.multiarray import _np_ndarray_cls
self._create_ndarray_fn = _np_ndarray_cls if is_np_array() else _ndarray_cls
self.handle = handle
self._kwargs = kwargs
# debug option, used to test the speed with io effect eliminated
self._debug_skip_load = False
# load the first batch to get shape information
self.first_batch = None
self.first_batch = self.next()
data = self.first_batch.data[0]
label = self.first_batch.label[0]
# properties
self.provide_data = [DataDesc(data_name, data.shape, data.dtype)]
self.provide_label = [DataDesc(label_name, label.shape, label.dtype)]
self.batch_size = data.shape[0]
def __del__(self):
check_call(_LIB.MXDataIterFree(self.handle))
def debug_skip_load(self):
# Set the iterator to simply return always first batch. This can be used
# to test the speed of network without taking the loading delay into
# account.
self._debug_skip_load = True
logging.info('Set debug_skip_load to be true, will simply return first batch')
def reset(self):
self._debug_at_begin = True
self.first_batch = None
check_call(_LIB.MXDataIterBeforeFirst(self.handle))
def next(self):
if self._debug_skip_load and not self._debug_at_begin:
return DataBatch(data=[self.getdata()], label=[self.getlabel()], pad=self.getpad(),
index=self.getindex())
if self.first_batch is not None:
batch = self.first_batch
self.first_batch = None
return batch
self._debug_at_begin = False
next_res = ctypes.c_int(0)
check_call(_LIB.MXDataIterNext(self.handle, ctypes.byref(next_res)))
if next_res.value:
return DataBatch(data=[self.getdata()], label=[self.getlabel()], pad=self.getpad(),
index=self.getindex())
else:
raise StopIteration
def iter_next(self):
if self.first_batch is not None:
return True
next_res = ctypes.c_int(0)
check_call(_LIB.MXDataIterNext(self.handle, ctypes.byref(next_res)))
return next_res.value
def getdata(self):
hdl = NDArrayHandle()
check_call(_LIB.MXDataIterGetData(self.handle, ctypes.byref(hdl)))
return self._create_ndarray_fn(hdl, False)
def getlabel(self):
hdl = NDArrayHandle()
check_call(_LIB.MXDataIterGetLabel(self.handle, ctypes.byref(hdl)))
return self._create_ndarray_fn(hdl, False)
def getindex(self):
index_size = ctypes.c_uint64(0)
index_data = ctypes.POINTER(ctypes.c_uint64)()
check_call(_LIB.MXDataIterGetIndex(self.handle,
ctypes.byref(index_data),
ctypes.byref(index_size)))
if index_size.value:
address = ctypes.addressof(index_data.contents)
dbuffer = (ctypes.c_uint64* index_size.value).from_address(address)
np_index = np.frombuffer(dbuffer, dtype=np.uint64)
return np_index.copy()
else:
return None
def getpad(self):
pad = ctypes.c_int(0)
check_call(_LIB.MXDataIterGetPadNum(self.handle, ctypes.byref(pad)))
return pad.value
def getitems(self):
output_vars = ctypes.POINTER(NDArrayHandle)()
num_output = ctypes.c_int(0)
check_call(_LIB.MXDataIterGetItems(self.handle,
ctypes.byref(num_output),
ctypes.byref(output_vars)))
out = [self._create_ndarray_fn(ctypes.cast(output_vars[i], NDArrayHandle),
False) for i in range(num_output.value)]
return tuple(out)
def __len__(self):
length = ctypes.c_int64(-1)
check_call(_LIB.MXDataIterGetLenHint(self.handle, ctypes.byref(length)))
if length.value < 0:
return 0
return length.value
def _make_io_iterator(handle):
"""Create an io iterator by handle."""
name = ctypes.c_char_p()
desc = ctypes.c_char_p()
num_args = mx_uint()
arg_names = ctypes.POINTER(ctypes.c_char_p)()
arg_types = ctypes.POINTER(ctypes.c_char_p)()
arg_descs = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.MXDataIterGetIterInfo( \
handle, ctypes.byref(name), ctypes.byref(desc), \
ctypes.byref(num_args), \
ctypes.byref(arg_names), \
ctypes.byref(arg_types), \
ctypes.byref(arg_descs)))
iter_name = py_str(name.value)
narg = int(num_args.value)
param_str = _build_param_doc(
[py_str(arg_names[i]) for i in range(narg)],
[py_str(arg_types[i]) for i in range(narg)],
[py_str(arg_descs[i]) for i in range(narg)])
doc_str = ('%s\n\n' +
'%s\n' +
'Returns\n' +
'-------\n' +
'MXDataIter\n'+
' The result iterator.')
doc_str = doc_str % (desc.value, param_str)
def creator(*args, **kwargs):
"""Create an iterator.
The parameters listed below can be passed in as keyword arguments.
Parameters
----------
name : string, required.
Name of the resulting data iterator.
Returns
-------
dataiter: Dataiter
The resulting data iterator.
"""
param_keys = []
param_vals = []
for k, val in kwargs.items():
if iter_name == 'ThreadedDataLoader':
# convert ndarray to handle
if hasattr(val, 'handle'):
val = val.handle.value
elif isinstance(val, (tuple, list)):
val = [vv.handle.value if hasattr(vv, 'handle') else vv for vv in val]
elif isinstance(getattr(val, '_iter', None), MXDataIter):
val = val._iter.handle.value
param_keys.append(k)
param_vals.append(str(val))
# create atomic symbol
param_keys = c_str_array(param_keys)
param_vals = c_str_array(param_vals)
iter_handle = DataIterHandle()
check_call(_LIB.MXDataIterCreateIter(
handle,
mx_uint(len(param_keys)),
param_keys, param_vals,
ctypes.byref(iter_handle)))
if len(args):
raise TypeError('%s can only accept keyword arguments' % iter_name)
return MXDataIter(iter_handle, **kwargs)
creator.__name__ = iter_name
creator.__doc__ = doc_str
return creator
def _init_io_module():
"""List and add all the data iterators to current module."""
plist = ctypes.POINTER(ctypes.c_void_p)()
size = ctypes.c_uint()
check_call(_LIB.MXListDataIters(ctypes.byref(size), ctypes.byref(plist)))
module_obj = sys.modules[__name__]
for i in range(size.value):
hdl = ctypes.c_void_p(plist[i])
dataiter = _make_io_iterator(hdl)
setattr(module_obj, dataiter.__name__, dataiter)
_init_io_module()
|
|
# Copyright 2011 OpenStack Foundation
# Copyright 2012 Justin Santa Barbara
# All Rights Reserved.
#
# 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.
"""The security groups extension."""
from oslo_log import log as logging
from oslo_serialization import jsonutils
from webob import exc
from nova.api.openstack.api_version_request \
import MAX_PROXY_API_SUPPORT_VERSION
from nova.api.openstack import common
from nova.api.openstack.compute.schemas import security_groups as \
schema_security_groups
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova import compute
from nova import exception
from nova.i18n import _
from nova.network.security_group import openstack_driver
from nova.policies import security_groups as sg_policies
from nova.virt import netutils
LOG = logging.getLogger(__name__)
ALIAS = 'os-security-groups'
ATTRIBUTE_NAME = 'security_groups'
def _authorize_context(req):
context = req.environ['nova.context']
context.can(sg_policies.BASE_POLICY_NAME)
return context
class SecurityGroupControllerBase(object):
"""Base class for Security Group controllers."""
def __init__(self):
self.security_group_api = (
openstack_driver.get_openstack_security_group_driver())
self.compute_api = compute.API(
security_group_api=self.security_group_api)
def _format_security_group_rule(self, context, rule, group_rule_data=None):
"""Return a security group rule in desired API response format.
If group_rule_data is passed in that is used rather than querying
for it.
"""
sg_rule = {}
sg_rule['id'] = rule['id']
sg_rule['parent_group_id'] = rule['parent_group_id']
sg_rule['ip_protocol'] = rule['protocol']
sg_rule['from_port'] = rule['from_port']
sg_rule['to_port'] = rule['to_port']
sg_rule['group'] = {}
sg_rule['ip_range'] = {}
if rule['group_id']:
try:
source_group = self.security_group_api.get(
context, id=rule['group_id'])
except exception.SecurityGroupNotFound:
# NOTE(arosen): There is a possible race condition that can
# occur here if two api calls occur concurrently: one that
# lists the security groups and another one that deletes a
# security group rule that has a group_id before the
# group_id is fetched. To handle this if
# SecurityGroupNotFound is raised we return None instead
# of the rule and the caller should ignore the rule.
LOG.debug("Security Group ID %s does not exist",
rule['group_id'])
return
sg_rule['group'] = {'name': source_group.get('name'),
'tenant_id': source_group.get('project_id')}
elif group_rule_data:
sg_rule['group'] = group_rule_data
else:
sg_rule['ip_range'] = {'cidr': rule['cidr']}
return sg_rule
def _format_security_group(self, context, group):
security_group = {}
security_group['id'] = group['id']
security_group['description'] = group['description']
security_group['name'] = group['name']
security_group['tenant_id'] = group['project_id']
security_group['rules'] = []
for rule in group['rules']:
formatted_rule = self._format_security_group_rule(context, rule)
if formatted_rule:
security_group['rules'] += [formatted_rule]
return security_group
def _from_body(self, body, key):
if not body:
raise exc.HTTPBadRequest(
explanation=_("The request body can't be empty"))
value = body.get(key, None)
if value is None:
raise exc.HTTPBadRequest(
explanation=_("Missing parameter %s") % key)
return value
class SecurityGroupController(SecurityGroupControllerBase, wsgi.Controller):
"""The Security group API controller for the OpenStack API."""
@wsgi.Controller.api_version("2.1", MAX_PROXY_API_SUPPORT_VERSION)
@extensions.expected_errors((400, 404))
def show(self, req, id):
"""Return data about the given security group."""
context = _authorize_context(req)
try:
id = self.security_group_api.validate_id(id)
security_group = self.security_group_api.get(context, None, id,
map_exception=True)
except exception.SecurityGroupNotFound as exp:
raise exc.HTTPNotFound(explanation=exp.format_message())
except exception.Invalid as exp:
raise exc.HTTPBadRequest(explanation=exp.format_message())
return {'security_group': self._format_security_group(context,
security_group)}
@wsgi.Controller.api_version("2.1", MAX_PROXY_API_SUPPORT_VERSION)
@extensions.expected_errors((400, 404))
@wsgi.response(202)
def delete(self, req, id):
"""Delete a security group."""
context = _authorize_context(req)
try:
id = self.security_group_api.validate_id(id)
security_group = self.security_group_api.get(context, None, id,
map_exception=True)
self.security_group_api.destroy(context, security_group)
except exception.SecurityGroupNotFound as exp:
raise exc.HTTPNotFound(explanation=exp.format_message())
except exception.Invalid as exp:
raise exc.HTTPBadRequest(explanation=exp.format_message())
@wsgi.Controller.api_version("2.1", MAX_PROXY_API_SUPPORT_VERSION)
@extensions.expected_errors(404)
def index(self, req):
"""Returns a list of security groups."""
context = _authorize_context(req)
search_opts = {}
search_opts.update(req.GET)
project_id = context.project_id
raw_groups = self.security_group_api.list(context,
project=project_id,
search_opts=search_opts)
limited_list = common.limited(raw_groups, req)
result = [self._format_security_group(context, group)
for group in limited_list]
return {'security_groups':
list(sorted(result,
key=lambda k: (k['tenant_id'], k['name'])))}
@wsgi.Controller.api_version("2.1", MAX_PROXY_API_SUPPORT_VERSION)
@extensions.expected_errors((400, 403))
def create(self, req, body):
"""Creates a new security group."""
context = _authorize_context(req)
security_group = self._from_body(body, 'security_group')
group_name = security_group.get('name', None)
group_description = security_group.get('description', None)
try:
self.security_group_api.validate_property(group_name, 'name', None)
self.security_group_api.validate_property(group_description,
'description', None)
group_ref = self.security_group_api.create_security_group(
context, group_name, group_description)
except exception.Invalid as exp:
raise exc.HTTPBadRequest(explanation=exp.format_message())
except exception.SecurityGroupLimitExceeded as exp:
raise exc.HTTPForbidden(explanation=exp.format_message())
return {'security_group': self._format_security_group(context,
group_ref)}
@wsgi.Controller.api_version("2.1", MAX_PROXY_API_SUPPORT_VERSION)
@extensions.expected_errors((400, 404))
def update(self, req, id, body):
"""Update a security group."""
context = _authorize_context(req)
try:
id = self.security_group_api.validate_id(id)
security_group = self.security_group_api.get(context, None, id,
map_exception=True)
except exception.SecurityGroupNotFound as exp:
raise exc.HTTPNotFound(explanation=exp.format_message())
except exception.Invalid as exp:
raise exc.HTTPBadRequest(explanation=exp.format_message())
security_group_data = self._from_body(body, 'security_group')
group_name = security_group_data.get('name', None)
group_description = security_group_data.get('description', None)
try:
self.security_group_api.validate_property(group_name, 'name', None)
self.security_group_api.validate_property(group_description,
'description', None)
group_ref = self.security_group_api.update_security_group(
context, security_group, group_name, group_description)
except exception.SecurityGroupNotFound as exp:
raise exc.HTTPNotFound(explanation=exp.format_message())
except exception.Invalid as exp:
raise exc.HTTPBadRequest(explanation=exp.format_message())
return {'security_group': self._format_security_group(context,
group_ref)}
class SecurityGroupRulesController(SecurityGroupControllerBase,
wsgi.Controller):
@wsgi.Controller.api_version("2.1", MAX_PROXY_API_SUPPORT_VERSION)
@extensions.expected_errors((400, 403, 404))
def create(self, req, body):
context = _authorize_context(req)
sg_rule = self._from_body(body, 'security_group_rule')
try:
parent_group_id = self.security_group_api.validate_id(
sg_rule.get('parent_group_id'))
security_group = self.security_group_api.get(context, None,
parent_group_id,
map_exception=True)
new_rule = self._rule_args_to_dict(context,
to_port=sg_rule.get('to_port'),
from_port=sg_rule.get('from_port'),
ip_protocol=sg_rule.get('ip_protocol'),
cidr=sg_rule.get('cidr'),
group_id=sg_rule.get('group_id'))
except (exception.Invalid, exception.InvalidCidr) as exp:
raise exc.HTTPBadRequest(explanation=exp.format_message())
except exception.SecurityGroupNotFound as exp:
raise exc.HTTPNotFound(explanation=exp.format_message())
if new_rule is None:
msg = _("Not enough parameters to build a valid rule.")
raise exc.HTTPBadRequest(explanation=msg)
new_rule['parent_group_id'] = security_group['id']
if 'cidr' in new_rule:
net, prefixlen = netutils.get_net_and_prefixlen(new_rule['cidr'])
if net not in ('0.0.0.0', '::') and prefixlen == '0':
msg = _("Bad prefix for network in cidr %s") % new_rule['cidr']
raise exc.HTTPBadRequest(explanation=msg)
group_rule_data = None
try:
if sg_rule.get('group_id'):
source_group = self.security_group_api.get(
context, id=sg_rule['group_id'])
group_rule_data = {'name': source_group.get('name'),
'tenant_id': source_group.get('project_id')}
security_group_rule = (
self.security_group_api.create_security_group_rule(
context, security_group, new_rule))
except exception.Invalid as exp:
raise exc.HTTPBadRequest(explanation=exp.format_message())
except exception.SecurityGroupNotFound as exp:
raise exc.HTTPNotFound(explanation=exp.format_message())
except exception.SecurityGroupLimitExceeded as exp:
raise exc.HTTPForbidden(explanation=exp.format_message())
formatted_rule = self._format_security_group_rule(context,
security_group_rule,
group_rule_data)
return {"security_group_rule": formatted_rule}
def _rule_args_to_dict(self, context, to_port=None, from_port=None,
ip_protocol=None, cidr=None, group_id=None):
if group_id is not None:
group_id = self.security_group_api.validate_id(group_id)
# check if groupId exists
self.security_group_api.get(context, id=group_id)
return self.security_group_api.new_group_ingress_rule(
group_id, ip_protocol, from_port, to_port)
else:
cidr = self.security_group_api.parse_cidr(cidr)
return self.security_group_api.new_cidr_ingress_rule(
cidr, ip_protocol, from_port, to_port)
@wsgi.Controller.api_version("2.1", MAX_PROXY_API_SUPPORT_VERSION)
@extensions.expected_errors((400, 404, 409))
@wsgi.response(202)
def delete(self, req, id):
context = _authorize_context(req)
try:
id = self.security_group_api.validate_id(id)
rule = self.security_group_api.get_rule(context, id)
group_id = rule['parent_group_id']
security_group = self.security_group_api.get(context, None,
group_id,
map_exception=True)
self.security_group_api.remove_rules(context, security_group,
[rule['id']])
except exception.SecurityGroupNotFound as exp:
raise exc.HTTPNotFound(explanation=exp.format_message())
except exception.NoUniqueMatch as exp:
raise exc.HTTPConflict(explanation=exp.format_message())
except exception.Invalid as exp:
raise exc.HTTPBadRequest(explanation=exp.format_message())
class ServerSecurityGroupController(SecurityGroupControllerBase):
@extensions.expected_errors(404)
def index(self, req, server_id):
"""Returns a list of security groups for the given instance."""
context = _authorize_context(req)
self.security_group_api.ensure_default(context)
try:
instance = common.get_instance(self.compute_api, context,
server_id)
groups = self.security_group_api.get_instance_security_groups(
context, instance, True)
except (exception.SecurityGroupNotFound,
exception.InstanceNotFound) as exp:
msg = exp.format_message()
raise exc.HTTPNotFound(explanation=msg)
result = [self._format_security_group(context, group)
for group in groups]
return {'security_groups':
list(sorted(result,
key=lambda k: (k['tenant_id'], k['name'])))}
class SecurityGroupActionController(wsgi.Controller):
def __init__(self, *args, **kwargs):
super(SecurityGroupActionController, self).__init__(*args, **kwargs)
self.security_group_api = (
openstack_driver.get_openstack_security_group_driver())
self.compute_api = compute.API(
security_group_api=self.security_group_api)
def _parse(self, body, action):
try:
body = body[action]
group_name = body['name']
except TypeError:
msg = _("Missing parameter dict")
raise exc.HTTPBadRequest(explanation=msg)
except KeyError:
msg = _("Security group not specified")
raise exc.HTTPBadRequest(explanation=msg)
if not group_name or group_name.strip() == '':
msg = _("Security group name cannot be empty")
raise exc.HTTPBadRequest(explanation=msg)
return group_name
def _invoke(self, method, context, id, group_name):
instance = common.get_instance(self.compute_api, context, id)
method(context, instance, group_name)
@extensions.expected_errors((400, 404, 409))
@wsgi.response(202)
@wsgi.action('addSecurityGroup')
def _addSecurityGroup(self, req, id, body):
context = req.environ['nova.context']
context.can(sg_policies.BASE_POLICY_NAME)
group_name = self._parse(body, 'addSecurityGroup')
try:
return self._invoke(self.security_group_api.add_to_instance,
context, id, group_name)
except (exception.SecurityGroupNotFound,
exception.InstanceNotFound) as exp:
raise exc.HTTPNotFound(explanation=exp.format_message())
except exception.NoUniqueMatch as exp:
raise exc.HTTPConflict(explanation=exp.format_message())
except (exception.SecurityGroupCannotBeApplied,
exception.SecurityGroupExistsForInstance) as exp:
raise exc.HTTPBadRequest(explanation=exp.format_message())
@extensions.expected_errors((400, 404, 409))
@wsgi.response(202)
@wsgi.action('removeSecurityGroup')
def _removeSecurityGroup(self, req, id, body):
context = req.environ['nova.context']
context.can(sg_policies.BASE_POLICY_NAME)
group_name = self._parse(body, 'removeSecurityGroup')
try:
return self._invoke(self.security_group_api.remove_from_instance,
context, id, group_name)
except (exception.SecurityGroupNotFound,
exception.InstanceNotFound) as exp:
raise exc.HTTPNotFound(explanation=exp.format_message())
except exception.NoUniqueMatch as exp:
raise exc.HTTPConflict(explanation=exp.format_message())
except exception.SecurityGroupNotExistsForInstance as exp:
raise exc.HTTPBadRequest(explanation=exp.format_message())
class SecurityGroupsOutputController(wsgi.Controller):
def __init__(self, *args, **kwargs):
super(SecurityGroupsOutputController, self).__init__(*args, **kwargs)
self.compute_api = compute.API()
self.security_group_api = (
openstack_driver.get_openstack_security_group_driver())
def _extend_servers(self, req, servers):
# TODO(arosen) this function should be refactored to reduce duplicate
# code and use get_instance_security_groups instead of get_db_instance.
if not len(servers):
return
key = "security_groups"
context = req.environ['nova.context']
if not context.can(sg_policies.BASE_POLICY_NAME, fatal=False):
return
if not openstack_driver.is_neutron_security_groups():
for server in servers:
instance = req.get_db_instance(server['id'])
groups = instance.get(key)
if groups:
server[ATTRIBUTE_NAME] = [{"name": group.name}
for group in groups]
else:
# If method is a POST we get the security groups intended for an
# instance from the request. The reason for this is if using
# neutron security groups the requested security groups for the
# instance are not in the db and have not been sent to neutron yet.
if req.method != 'POST':
sg_instance_bindings = (
self.security_group_api
.get_instances_security_groups_bindings(context,
servers))
for server in servers:
groups = sg_instance_bindings.get(server['id'])
if groups:
server[ATTRIBUTE_NAME] = groups
# In this section of code len(servers) == 1 as you can only POST
# one server in an API request.
else:
# try converting to json
req_obj = jsonutils.loads(req.body)
# Add security group to server, if no security group was in
# request add default since that is the group it is part of
servers[0][ATTRIBUTE_NAME] = req_obj['server'].get(
ATTRIBUTE_NAME, [{'name': 'default'}])
def _show(self, req, resp_obj):
if 'server' in resp_obj.obj:
self._extend_servers(req, [resp_obj.obj['server']])
@wsgi.extends
def show(self, req, resp_obj, id):
return self._show(req, resp_obj)
@wsgi.extends
def create(self, req, resp_obj, body):
return self._show(req, resp_obj)
@wsgi.extends
def detail(self, req, resp_obj):
self._extend_servers(req, list(resp_obj.obj['servers']))
class SecurityGroups(extensions.V21APIExtensionBase):
"""Security group support."""
name = "SecurityGroups"
alias = ALIAS
version = 1
def get_controller_extensions(self):
secgrp_output_ext = extensions.ControllerExtension(
self, 'servers', SecurityGroupsOutputController())
secgrp_act_ext = extensions.ControllerExtension(
self, 'servers', SecurityGroupActionController())
return [secgrp_output_ext, secgrp_act_ext]
def get_resources(self):
secgrp_ext = extensions.ResourceExtension(ALIAS,
SecurityGroupController())
server_secgrp_ext = extensions.ResourceExtension(
ALIAS,
controller=ServerSecurityGroupController(),
parent=dict(member_name='server', collection_name='servers'))
secgrp_rules_ext = extensions.ResourceExtension(
'os-security-group-rules',
controller=SecurityGroupRulesController())
return [secgrp_ext, server_secgrp_ext, secgrp_rules_ext]
# NOTE(gmann): This function is not supposed to use 'body_deprecated_param'
# parameter as this is placed to handle scheduler_hint extension for V2.1.
def server_create(self, server_dict, create_kwargs, body_deprecated_param):
security_groups = server_dict.get(ATTRIBUTE_NAME)
if security_groups is not None:
create_kwargs['security_group'] = [
sg['name'] for sg in security_groups if sg.get('name')]
create_kwargs['security_group'] = list(
set(create_kwargs['security_group']))
def get_server_create_schema(self, version):
if version == '2.0':
return schema_security_groups.server_create_v20
return schema_security_groups.server_create
|
|
import re
from tests.base import IntegrationTest
from tasklib import local_zone
from datetime import datetime
def current_year():
return local_zone.localize(datetime.now()).year
def current_month():
current_month_number = local_zone.localize(datetime.now()).month
months = ["January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"]
return months[current_month_number - 1]
class TestBurndownDailySimple(IntegrationTest):
def execute(self):
self.command("TaskWikiBurndownDaily")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer burndown.daily")
assert "Daily Burndown" in self.read_buffer()[0]
class TestBurndownMonthlySimple(IntegrationTest):
def execute(self):
self.command("TaskWikiBurndownMonthly")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer burndown.monthly")
assert "Monthly Burndown" in self.read_buffer()[0]
class TestBurndownWeeklySimple(IntegrationTest):
def execute(self):
self.command("TaskWikiBurndownWeekly")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer burndown.weekly")
assert "Weekly Burndown" in self.read_buffer()[0]
class TestCalendarSimple(IntegrationTest):
def execute(self):
self.command("TaskWikiCalendar")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer calendar")
# Assert each day is displayed at least once.
output = self.read_buffer()
for day in map(str, range(1, 29)):
assert any(day in line for line in output)
class TestGhistoryAnnualSimple(IntegrationTest):
tasks = [
dict(description="test task"),
dict(description="completed task 1", status="completed", end="now"),
dict(description="completed task 2", status="completed", end="now"),
dict(description="deleted task", status="deleted"),
]
def execute(self):
self.command("TaskWikiGhistoryAnnual")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer ghistory.annual")
output = self.read_buffer()
header_words = ("Year", "Number", "Added", "Completed", "Deleted")
for word in header_words:
assert word in output[0]
legend_words = ("Legend", "Added", "Completed", "Deleted")
for word in legend_words:
assert re.search(word, output[-1], re.IGNORECASE)
assert str(current_year()) in '\n'.join(output)
class TestGhistoryMonthlySimple(IntegrationTest):
tasks = [
dict(description="test task"),
dict(description="completed task 1", status="completed", end="now"),
dict(description="completed task 2", status="completed", end="now"),
dict(description="deleted task", status="deleted"),
]
def execute(self):
self.command("TaskWikiGhistoryMonthly")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer ghistory.monthly")
output = self.read_buffer()
header_words = ("Year", "Month", "Number", "Added", "Completed", "Deleted")
for word in header_words:
assert word in output[0]
legend_words = ("Legend", "Added", "Completed", "Deleted")
for word in legend_words:
assert re.search(word, output[-1], re.IGNORECASE)
assert str(current_year()) in '\n'.join(output)
assert current_month() in '\n'.join(output)
class TestHistoryAnnualSimple(IntegrationTest):
tasks = [
dict(description="test task"),
dict(description="completed task 1", status="completed", end="now"),
dict(description="completed task 2", status="completed", end="now"),
dict(description="deleted task", status="deleted"),
]
def execute(self):
self.command("TaskWikiHistoryAnnual")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer history.annual")
output = '\n'.join(self.read_buffer())
header = r'\s*'.join(['Year', 'Added', 'Completed', 'Deleted', 'Net'])
year = r'\s*'.join(map(str, [current_year(), 4, 2, 1, 1]))
assert re.search(header, output, re.MULTILINE)
assert re.search(year, output, re.MULTILINE)
class TestHistoryMonthlySimple(IntegrationTest):
tasks = [
dict(description="test task"),
dict(description="completed task 1", status="completed", end="now"),
dict(description="completed task 2", status="completed", end="now"),
dict(description="deleted task", status="deleted"),
]
def execute(self):
self.command("TaskWikiHistoryMonthly")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer history.monthly")
output = '\n'.join(self.read_buffer())
header = r'\s*'.join(['Year', 'Month', 'Added', 'Completed', 'Deleted', 'Net'])
year = r'\s*'.join(map(str, [current_year(), current_month(), 4, 2, 1, 1]))
assert re.search(header, output, re.MULTILINE)
assert re.search(year, output, re.MULTILINE)
class TestProjectsSimple(IntegrationTest):
tasks = [
dict(description="home task", project="Home"),
dict(description="home chore task 1", project="Home.Chores"),
dict(description="home chore task 2", project="Home.Chores"),
dict(description="work task 1", project="Work"),
dict(description="work task 2", project="Work"),
]
def execute(self):
self.command("TaskWikiProjects")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer projects")
output = '\n'.join(self.read_buffer())
header = r'\s*'.join(['Project', 'Tasks'])
home = r'\s*'.join(['Home', '3' if self.tw.version >= '2.4.2' else '1'])
chores = r'\s*'.join(['Chores', '2'])
work = r'\s*'.join(['Work', '2'])
assert re.search(header, output, re.MULTILINE)
assert re.search(home, output, re.MULTILINE)
assert re.search(chores, output, re.MULTILINE)
assert re.search(work, output, re.MULTILINE)
class TestSummarySimple(IntegrationTest):
tasks = [
dict(description="home task", project="Home"),
dict(description="home chore task 1", project="Home.Chores"),
dict(description="home chore task 2", project="Home.Chores"),
dict(description="work task 1", project="Work"),
dict(description="work task 2", project="Work"),
]
def execute(self):
self.command("TaskWikiProjectsSummary")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer summary")
output = '\n'.join(self.read_buffer())
header = r'\s*'.join(['Project', 'Remaining', 'Avg age', 'Complete'])
home = r'\s*'.join(['Home', '3' if self.tw.version >= '2.4.2' else '1'])
chores = r'\s*'.join(['Chores', '2'])
work = r'\s*'.join(['Work', '2'])
assert re.search(header, output, re.MULTILINE)
assert re.search(home, output, re.MULTILINE)
assert re.search(chores, output, re.MULTILINE)
assert re.search(work, output, re.MULTILINE)
class TestStatsSimple(IntegrationTest):
tasks = [
dict(description="home task"),
dict(description="home chore task 1", tags=['chore']),
dict(description="home chore task 2", tags=['chore']),
dict(description="work task 1", tags=['work']),
dict(description="work task 2", tags=['work']),
]
def execute(self):
self.command("TaskWikiStats")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer stats")
output = '\n'.join(self.read_buffer())
header = r'\s*'.join(['Category', 'Data'])
data = r'\s*'.join(['Pending', '5'])
assert re.search(header, output, re.MULTILINE)
assert re.search(data, output, re.MULTILINE)
class TestTagsSimple(IntegrationTest):
tasks = [
dict(description="home task"),
dict(description="home chore task 1", tags=['chore']),
dict(description="home chore task 2", tags=['chore']),
dict(description="work task 1", tags=['work']),
dict(description="work task 2", tags=['work']),
]
def execute(self):
self.command("TaskWikiTags")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer tags")
output = '\n'.join(self.read_buffer())
header = r'\s*'.join(['Tag', 'Count'])
chores = r'\s*'.join(['chore', '2'])
work = r'\s*'.join(['work', '2'])
assert re.search(header, output, re.MULTILINE)
assert re.search(chores, output, re.MULTILINE)
assert re.search(work, output, re.MULTILINE)
class TestTagsSimpleFiltered(IntegrationTest):
tasks = [
dict(description="home task"),
dict(description="home chore task 1", tags=['chore']),
dict(description="home chore task 2", tags=['chore']),
dict(description="work task 1", tags=['work']),
dict(description="work task 2", tags=['work']),
]
def execute(self):
self.command("TaskWikiTags +chore")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer tags")
output = '\n'.join(self.read_buffer())
header = r'\s*'.join(['Tag', 'Count'])
chores = r'\s*'.join(['chore', '2'])
work = r'\s*'.join(['work', '2'])
assert re.search(header, output, re.MULTILINE)
assert re.search(chores, output, re.MULTILINE)
assert not re.search(work, output, re.MULTILINE)
class TestSplitReplacement(IntegrationTest):
def execute(self):
self.command("TaskWikiBurndownDaily")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer burndown.daily")
assert "Daily Burndown" in self.read_buffer()[0]
self.command("TaskWikiBurndownDaily")
assert self.command(":py print vim.current.buffer", silent=False).startswith("<buffer burndown.daily")
assert "Daily Burndown" in self.read_buffer()[0]
# Assert that there are only two buffers in the window
self.command(":py print len(vim.buffers)", regex='2$', lines=1)
|
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Mortar Data
#
# 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.
#
from __future__ import print_function
import os
import sys
import tempfile
from target_test import FileSystemTargetTestMixin
from helpers import with_config, unittest, skipOnTravis
from boto.exception import S3ResponseError
from boto.s3 import key
from moto import mock_s3
from moto import mock_sts
from luigi import configuration
from luigi.contrib.s3 import FileNotFoundException, InvalidDeleteException, S3Client, S3Target
from luigi.target import MissingParentDirectory
if (3, 4, 0) <= sys.version_info[:3] < (3, 4, 3):
# spulec/moto#308
raise unittest.SkipTest('moto mock doesn\'t work with python3.4')
AWS_ACCESS_KEY = "XXXXXXXXXXXXXXXXXXXX"
AWS_SECRET_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
class TestS3Target(unittest.TestCase, FileSystemTargetTestMixin):
def setUp(self):
f = tempfile.NamedTemporaryFile(mode='wb', delete=False)
self.tempFileContents = (
b"I'm a temporary file for testing\nAnd this is the second line\n"
b"This is the third.")
self.tempFilePath = f.name
f.write(self.tempFileContents)
f.close()
self.addCleanup(os.remove, self.tempFilePath)
self.mock_s3 = mock_s3()
self.mock_s3.start()
self.addCleanup(self.mock_s3.stop)
def create_target(self, format=None, **kwargs):
client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
client.s3.create_bucket('mybucket')
return S3Target('s3://mybucket/test_file', client=client, format=format, **kwargs)
def test_read(self):
client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
client.s3.create_bucket('mybucket')
client.put(self.tempFilePath, 's3://mybucket/tempfile')
t = S3Target('s3://mybucket/tempfile', client=client)
read_file = t.open()
file_str = read_file.read()
self.assertEqual(self.tempFileContents, file_str.encode('utf-8'))
def test_read_no_file(self):
t = self.create_target()
self.assertRaises(FileNotFoundException, t.open)
def test_read_no_file_sse(self):
t = self.create_target(encrypt_key=True)
self.assertRaises(FileNotFoundException, t.open)
def test_read_iterator_long(self):
# write a file that is 5X the boto buffersize
# to test line buffering
old_buffer = key.Key.BufferSize
key.Key.BufferSize = 2
try:
tempf = tempfile.NamedTemporaryFile(mode='wb', delete=False)
temppath = tempf.name
firstline = ''.zfill(key.Key.BufferSize * 5) + os.linesep
contents = firstline + 'line two' + os.linesep + 'line three'
tempf.write(contents.encode('utf-8'))
tempf.close()
client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
client.s3.create_bucket('mybucket')
client.put(temppath, 's3://mybucket/largetempfile')
t = S3Target('s3://mybucket/largetempfile', client=client)
with t.open() as read_file:
lines = [line for line in read_file]
finally:
key.Key.BufferSize = old_buffer
self.assertEqual(3, len(lines))
self.assertEqual(firstline, lines[0])
self.assertEqual("line two" + os.linesep, lines[1])
self.assertEqual("line three", lines[2])
def test_get_path(self):
t = self.create_target()
path = t.path
self.assertEqual('s3://mybucket/test_file', path)
def test_get_path_sse(self):
t = self.create_target(encrypt_key=True)
path = t.path
self.assertEqual('s3://mybucket/test_file', path)
class TestS3Client(unittest.TestCase):
def setUp(self):
f = tempfile.NamedTemporaryFile(mode='wb', delete=False)
self.tempFilePath = f.name
self.tempFileContents = b"I'm a temporary file for testing\n"
f.write(self.tempFileContents)
f.close()
self.addCleanup(os.remove, self.tempFilePath)
self.mock_s3 = mock_s3()
self.mock_s3.start()
self.mock_sts = mock_sts()
self.mock_sts.start()
self.addCleanup(self.mock_s3.stop)
self.addCleanup(self.mock_sts.stop)
def test_init_with_environment_variables(self):
os.environ['AWS_ACCESS_KEY_ID'] = 'foo'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'bar'
# Don't read any exsisting config
old_config_paths = configuration.LuigiConfigParser._config_paths
configuration.LuigiConfigParser._config_paths = [tempfile.mktemp()]
s3_client = S3Client()
configuration.LuigiConfigParser._config_paths = old_config_paths
self.assertEqual(s3_client.s3.gs_access_key_id, 'foo')
self.assertEqual(s3_client.s3.gs_secret_access_key, 'bar')
@with_config({'s3': {'aws_access_key_id': 'foo', 'aws_secret_access_key': 'bar'}})
def test_init_with_config(self):
s3_client = S3Client()
self.assertEqual(s3_client.s3.access_key, 'foo')
self.assertEqual(s3_client.s3.secret_key, 'bar')
@with_config({'s3': {'aws_role_arn': 'role', 'aws_role_session_name': 'name'}})
def test_init_with_config_and_roles(self):
s3_client = S3Client()
self.assertEqual(s3_client.s3.access_key, 'AKIAIOSFODNN7EXAMPLE')
self.assertEqual(s3_client.s3.secret_key, 'aJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY')
def test_put(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put(self.tempFilePath, 's3://mybucket/putMe')
self.assertTrue(s3_client.exists('s3://mybucket/putMe'))
def test_put_sse(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put(self.tempFilePath, 's3://mybucket/putMe', encrypt_key=True)
self.assertTrue(s3_client.exists('s3://mybucket/putMe'))
def test_put_string(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put_string("SOMESTRING", 's3://mybucket/putString')
self.assertTrue(s3_client.exists('s3://mybucket/putString'))
def test_put_string_sse(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put_string("SOMESTRING", 's3://mybucket/putString', encrypt_key=True)
self.assertTrue(s3_client.exists('s3://mybucket/putString'))
def test_put_multipart_multiple_parts_non_exact_fit(self):
"""
Test a multipart put with two parts, where the parts are not exactly the split size.
"""
# 5MB is minimum part size
part_size = (1024 ** 2) * 5
file_size = (part_size * 2) - 5000
self._run_multipart_test(part_size, file_size)
def test_put_multipart_multiple_parts_non_exact_fit_with_sse(self):
"""
Test a multipart put with two parts, where the parts are not exactly the split size.
"""
# 5MB is minimum part size
part_size = (1024 ** 2) * 5
file_size = (part_size * 2) - 5000
self._run_multipart_test(part_size, file_size, encrypt_key=True)
def test_put_multipart_multiple_parts_exact_fit(self):
"""
Test a multipart put with multiple parts, where the parts are exactly the split size.
"""
# 5MB is minimum part size
part_size = (1024 ** 2) * 5
file_size = part_size * 2
self._run_multipart_test(part_size, file_size)
def test_put_multipart_multiple_parts_exact_fit_wit_sse(self):
"""
Test a multipart put with multiple parts, where the parts are exactly the split size.
"""
# 5MB is minimum part size
part_size = (1024 ** 2) * 5
file_size = part_size * 2
self._run_multipart_test(part_size, file_size, encrypt_key=True)
def test_put_multipart_less_than_split_size(self):
"""
Test a multipart put with a file smaller than split size; should revert to regular put.
"""
# 5MB is minimum part size
part_size = (1024 ** 2) * 5
file_size = 5000
self._run_multipart_test(part_size, file_size)
def test_put_multipart_less_than_split_size_with_sse(self):
"""
Test a multipart put with a file smaller than split size; should revert to regular put.
"""
# 5MB is minimum part size
part_size = (1024 ** 2) * 5
file_size = 5000
self._run_multipart_test(part_size, file_size, encrypt_key=True)
def test_put_multipart_empty_file(self):
"""
Test a multipart put with an empty file.
"""
# 5MB is minimum part size
part_size = (1024 ** 2) * 5
file_size = 0
self._run_multipart_test(part_size, file_size)
def test_put_multipart_empty_file_with_sse(self):
"""
Test a multipart put with an empty file.
"""
# 5MB is minimum part size
part_size = (1024 ** 2) * 5
file_size = 0
self._run_multipart_test(part_size, file_size, encrypt_key=True)
def test_exists(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
self.assertTrue(s3_client.exists('s3://mybucket/'))
self.assertTrue(s3_client.exists('s3://mybucket'))
self.assertFalse(s3_client.exists('s3://mybucket/nope'))
self.assertFalse(s3_client.exists('s3://mybucket/nope/'))
s3_client.put(self.tempFilePath, 's3://mybucket/tempfile')
self.assertTrue(s3_client.exists('s3://mybucket/tempfile'))
self.assertFalse(s3_client.exists('s3://mybucket/temp'))
s3_client.put(self.tempFilePath, 's3://mybucket/tempdir0_$folder$')
self.assertTrue(s3_client.exists('s3://mybucket/tempdir0'))
s3_client.put(self.tempFilePath, 's3://mybucket/tempdir1/')
self.assertTrue(s3_client.exists('s3://mybucket/tempdir1'))
s3_client.put(self.tempFilePath, 's3://mybucket/tempdir2/subdir')
self.assertTrue(s3_client.exists('s3://mybucket/tempdir2'))
self.assertFalse(s3_client.exists('s3://mybucket/tempdir'))
def test_get(self):
# put a file on s3 first
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put(self.tempFilePath, 's3://mybucket/putMe')
tmp_file = tempfile.NamedTemporaryFile(delete=True)
tmp_file_path = tmp_file.name
s3_client.get('s3://mybucket/putMe', tmp_file_path)
self.assertEqual(tmp_file.read(), self.tempFileContents)
tmp_file.close()
def test_get_as_string(self):
# put a file on s3 first
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put(self.tempFilePath, 's3://mybucket/putMe')
contents = s3_client.get_as_string('s3://mybucket/putMe')
self.assertEqual(contents, self.tempFileContents)
def test_get_key(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put(self.tempFilePath, 's3://mybucket/key_to_find')
self.assertTrue(s3_client.get_key('s3://mybucket/key_to_find'))
self.assertFalse(s3_client.get_key('s3://mybucket/does_not_exist'))
def test_isdir(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
self.assertTrue(s3_client.isdir('s3://mybucket'))
s3_client.put(self.tempFilePath, 's3://mybucket/tempdir0_$folder$')
self.assertTrue(s3_client.isdir('s3://mybucket/tempdir0'))
s3_client.put(self.tempFilePath, 's3://mybucket/tempdir1/')
self.assertTrue(s3_client.isdir('s3://mybucket/tempdir1'))
s3_client.put(self.tempFilePath, 's3://mybucket/key')
self.assertFalse(s3_client.isdir('s3://mybucket/key'))
def test_mkdir(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
self.assertTrue(s3_client.isdir('s3://mybucket'))
s3_client.mkdir('s3://mybucket')
s3_client.mkdir('s3://mybucket/dir')
self.assertTrue(s3_client.isdir('s3://mybucket/dir'))
self.assertRaises(MissingParentDirectory,
s3_client.mkdir, 's3://mybucket/dir/foo/bar', parents=False)
self.assertFalse(s3_client.isdir('s3://mybucket/dir/foo/bar'))
def test_listdir(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put_string("", 's3://mybucket/hello/frank')
s3_client.put_string("", 's3://mybucket/hello/world')
self.assertEqual(['s3://mybucket/hello/frank', 's3://mybucket/hello/world'],
list(s3_client.listdir('s3://mybucket/hello')))
def test_list(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put_string("", 's3://mybucket/hello/frank')
s3_client.put_string("", 's3://mybucket/hello/world')
self.assertEqual(['frank', 'world'],
list(s3_client.list('s3://mybucket/hello')))
def test_listdir_key(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put_string("", 's3://mybucket/hello/frank')
s3_client.put_string("", 's3://mybucket/hello/world')
self.assertEqual([True, True],
[x.exists() for x in s3_client.listdir('s3://mybucket/hello', return_key=True)])
def test_list_key(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put_string("", 's3://mybucket/hello/frank')
s3_client.put_string("", 's3://mybucket/hello/world')
self.assertEqual([True, True],
[x.exists() for x in s3_client.list('s3://mybucket/hello', return_key=True)])
def test_remove(self):
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
self.assertRaises(
S3ResponseError,
lambda: s3_client.remove('s3://bucketdoesnotexist/file')
)
self.assertFalse(s3_client.remove('s3://mybucket/doesNotExist'))
s3_client.put(self.tempFilePath, 's3://mybucket/existingFile0')
self.assertTrue(s3_client.remove('s3://mybucket/existingFile0'))
self.assertFalse(s3_client.exists('s3://mybucket/existingFile0'))
self.assertRaises(
InvalidDeleteException,
lambda: s3_client.remove('s3://mybucket/')
)
self.assertRaises(
InvalidDeleteException,
lambda: s3_client.remove('s3://mybucket')
)
s3_client.put(self.tempFilePath, 's3://mybucket/removemedir/file')
self.assertRaises(
InvalidDeleteException,
lambda: s3_client.remove('s3://mybucket/removemedir', recursive=False)
)
# test that the marker file created by Hadoop S3 Native FileSystem is removed
s3_client.put(self.tempFilePath, 's3://mybucket/removemedir/file')
s3_client.put_string("", 's3://mybucket/removemedir_$folder$')
self.assertTrue(s3_client.remove('s3://mybucket/removemedir'))
self.assertFalse(s3_client.exists('s3://mybucket/removemedir_$folder$'))
def test_copy_multiple_parts_non_exact_fit(self):
"""
Test a multipart put with two parts, where the parts are not exactly the split size.
"""
# First, put a file into S3
self._run_copy_test(self.test_put_multipart_multiple_parts_non_exact_fit)
def test_copy_multiple_parts_exact_fit(self):
"""
Test a copy multiple parts, where the parts are exactly the split size.
"""
self._run_copy_test(self.test_put_multipart_multiple_parts_exact_fit)
def test_copy_less_than_split_size(self):
"""
Test a copy with a file smaller than split size; should revert to regular put.
"""
self._run_copy_test(self.test_put_multipart_less_than_split_size)
def test_copy_empty_file(self):
"""
Test a copy with an empty file.
"""
self._run_copy_test(self.test_put_multipart_empty_file)
def test_copy_multipart_multiple_parts_non_exact_fit(self):
"""
Test a multipart copy with two parts, where the parts are not exactly the split size.
"""
# First, put a file into S3
self._run_multipart_copy_test(self.test_put_multipart_multiple_parts_non_exact_fit)
def test_copy_multipart_multiple_parts_exact_fit(self):
"""
Test a multipart copy with multiple parts, where the parts are exactly the split size.
"""
self._run_multipart_copy_test(self.test_put_multipart_multiple_parts_exact_fit)
def test_copy_multipart_less_than_split_size(self):
"""
Test a multipart copy with a file smaller than split size; should revert to regular put.
"""
self._run_multipart_copy_test(self.test_put_multipart_less_than_split_size)
def test_copy_multipart_empty_file(self):
"""
Test a multipart copy with an empty file.
"""
self._run_multipart_copy_test(self.test_put_multipart_empty_file)
@skipOnTravis('https://travis-ci.org/spotify/luigi/jobs/145895385')
def test_copy_dir(self):
"""
Test copying 20 files from one folder to another
"""
n = 20
copy_part_size = (1024 ** 2) * 5
# Note we can't test the multipart copy due to moto issue #526
# so here I have to keep the file size smaller than the copy_part_size
file_size = 5000
s3_dir = 's3://mybucket/copydir/'
file_contents = b"a" * file_size
tmp_file = tempfile.NamedTemporaryFile(mode='wb', delete=True)
tmp_file_path = tmp_file.name
tmp_file.write(file_contents)
tmp_file.flush()
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
for i in range(n):
file_path = s3_dir + str(i)
s3_client.put_multipart(tmp_file_path, file_path)
self.assertTrue(s3_client.exists(file_path))
s3_dest = 's3://mybucket/copydir_new/'
s3_client.copy(s3_dir, s3_dest, threads=10, part_size=copy_part_size)
for i in range(n):
original_size = s3_client.get_key(s3_dir + str(i)).size
copy_size = s3_client.get_key(s3_dest + str(i)).size
self.assertEqual(original_size, copy_size)
def _run_multipart_copy_test(self, put_method):
# Run the method to put the file into s3 into the first place
put_method()
# As all the multipart put methods use `self._run_multipart_test`
# we can just use this key
original = 's3://mybucket/putMe'
copy = 's3://mybucket/putMe_copy'
# 5MB is minimum part size, use it here so we don't have to generate huge files to test
# the multipart upload in moto
part_size = (1024 ** 2) * 5
# Copy the file from old location to new
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.copy(original, copy, part_size=part_size, threads=4)
# We can't use etags to compare between multipart and normal keys,
# so we fall back to using the size instead
original_size = s3_client.get_key(original).size
copy_size = s3_client.get_key(copy).size
self.assertEqual(original_size, copy_size)
def _run_copy_test(self, put_method):
# Run the method to put the file into s3 into the first place
put_method()
# As all the multipart put methods use `self._run_multipart_test`
# we can just use this key
original = 's3://mybucket/putMe'
copy = 's3://mybucket/putMe_copy'
# Copy the file from old location to new
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.copy(original, copy, threads=4)
# We can't use etags to compare between multipart and normal keys,
# so we fall back to using the file size
original_size = s3_client.get_key(original).size
copy_size = s3_client.get_key(copy).size
self.assertEqual(original_size, copy_size)
def _run_multipart_test(self, part_size, file_size, **kwargs):
file_contents = b"a" * file_size
s3_path = 's3://mybucket/putMe'
tmp_file = tempfile.NamedTemporaryFile(mode='wb', delete=True)
tmp_file_path = tmp_file.name
tmp_file.write(file_contents)
tmp_file.flush()
s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
s3_client.s3.create_bucket('mybucket')
s3_client.put_multipart(tmp_file_path, s3_path, part_size=part_size, **kwargs)
self.assertTrue(s3_client.exists(s3_path))
file_size = os.path.getsize(tmp_file.name)
key_size = s3_client.get_key(s3_path).size
self.assertEqual(file_size, key_size)
tmp_file.close()
|
|
import time
import testify as T
from pushmanager.core.settings import Settings
from pushmanager.testing.testservlet import TemplateTestCase
class PushTemplateTest(TemplateTestCase):
authenticated = True
push_page = 'push.html'
push_status_page = 'push-status.html'
push_info_page = 'push-info.html'
push_button_bar_page = 'push-button-bar.html'
push_dialogs_page = 'push-dialogs.html'
accepting_push_sections = ['blessed', 'verified', 'staged', 'added', 'pickme', 'requested']
now = time.time()
basic_push = {
'id': 0,
'user': 'pushmaster',
'title': 'fake_push',
'branch': 'deploy-fake-branch',
'state': 'accepting',
'pushtype': 'Regular',
'created': now,
'modified': now,
'extra_pings': None,
'stageenv': None,
}
basic_kwargs = {
'page_title': 'fake_push_title',
'push_contents': {},
'available_requests': [],
'fullrepo': 'not/a/repo',
'override': False,
'push_survey_url': None
}
basic_request = {
'id': 0,
'repo': 'non-existent',
'branch': 'non-existent',
'user': 'testuser',
'reviewid': 0,
'title': 'some title',
'tags': None,
'revision': '0' * 40,
'state': 'requested',
'created': now,
'modified': now,
'description': 'nondescript',
'comments': 'nocomment',
'watchers': None,
}
basic_request = {
'id': 0,
'repo': 'non-existent',
'branch': 'non-existent',
'user': 'testuser',
'reviewid': 0,
'title': 'some title',
'tags': None,
'revision': '0' * 40,
'state': 'requested',
'created': now,
'modified': now,
'description': 'nondescript',
'comments': 'nocomment',
'watchers': None,
}
basic_push_info_items = {
'Pushmaster': basic_push['user'],
'Branch': basic_push['branch'],
'Buildbot Runs': 'https://%s/branch/%s' % (Settings['buildbot']['servername'], basic_push['branch']),
'State': basic_push['state'],
'Push Type': basic_push['pushtype'],
'Created': time.strftime("%x %X", time.localtime(basic_push['created']))
}
def test_include_push_info(self):
tree = self.render_etree(
self.push_page,
push_info=self.basic_push,
**self.basic_kwargs)
found_ul = []
for ul in tree.iter('ul'):
if 'id' in ul.attrib and ul.attrib['id'] == 'push-info':
found_ul.append(ul)
T.assert_equal(1, len(found_ul))
def test_include_push_button_bar(self):
tree = self.render_etree(
self.push_page,
push_info=self.basic_push,
**self.basic_kwargs)
found_ul = []
for ul in tree.iter('ul'):
if 'id' in ul.attrib and ul.attrib['id'] == 'action-buttons':
found_ul.append(ul)
T.assert_equal(1, len(found_ul))
def test_include_push_status_when_accepting(self):
tree = self.render_etree(
self.push_page,
push_info=self.basic_push,
**self.basic_kwargs)
found_h3 = []
for h3 in tree.iter('h3'):
T.assert_equal('status-header', h3.attrib['class'])
T.assert_in(h3.attrib['section'], self.accepting_push_sections)
found_h3.append(h3)
T.assert_equal(len(self.accepting_push_sections), len(found_h3))
def test_include_push_status_when_done(self):
push = dict(self.basic_push)
push['state'] = 'live'
tree = self.render_etree(
self.push_page,
push_info=push,
**self.basic_kwargs)
found_h3 = []
for h3 in tree.iter('h3'):
T.assert_equal('status-header', h3.attrib['class'])
found_h3.append(h3)
T.assert_equal(1, len(found_h3))
def generate_push_contents(self, requests):
push_contents = dict.fromkeys(self.accepting_push_sections, [])
for section in self.accepting_push_sections:
push_contents[section] = requests
return push_contents
def test_no_mine_on_requests_as_random_user(self):
kwargs = dict(self.basic_kwargs)
kwargs['push_contents'] = self.generate_push_contents([self.basic_request])
kwargs['current_user'] = 'random_user'
with self.no_ui_modules():
tree = self.render_etree(
self.push_status_page,
push_info=self.basic_push,
**kwargs)
found_mockreq = []
for mockreq in tree.iter('mock'):
T.assert_not_in('class', mockreq.getparent().attrib.keys())
found_mockreq.append(mockreq)
T.assert_equal(5, len(found_mockreq))
def test_mine_on_requests_as_request_user(self):
request = dict(self.basic_request)
request['user'] = 'notme'
push_contents = {}
section_id = []
for section in self.accepting_push_sections:
push_contents[section] = [self.basic_request, request]
section_id.append('%s-items' % section)
kwargs = dict(self.basic_kwargs)
kwargs['push_contents'] = push_contents
kwargs['current_user'] = 'testuser'
with self.no_ui_modules():
tree = self.render_etree(
self.push_status_page,
push_info=self.basic_push,
**kwargs)
found_li = []
found_mockreq = []
for mockreq in tree.iter('mock'):
if 'class' in mockreq.getparent().attrib:
T.assert_equal('mine', mockreq.getparent().attrib['class'])
found_li.append(mockreq)
found_mockreq.append(mockreq)
T.assert_equal(5, len(found_li))
T.assert_equal(10, len(found_mockreq))
def test_mine_on_requests_as_watcher(self):
request = dict(self.basic_request)
request['watchers'] = 'watcher1'
push_contents = {}
section_id = []
for section in self.accepting_push_sections:
push_contents[section] = [request, self.basic_request]
section_id.append('%s-items' % section)
kwargs = dict(self.basic_kwargs)
kwargs['push_contents'] = push_contents
kwargs['current_user'] = 'watcher1'
with self.no_ui_modules():
tree = self.render_etree(
self.push_status_page,
push_info=self.basic_push,
**kwargs)
found_li = []
found_mockreq = []
for mockreq in tree.iter('mock'):
if 'class' in mockreq.getparent().attrib:
T.assert_equal('mine', mockreq.getparent().attrib['class'])
found_li.append(mockreq)
found_mockreq.append(mockreq)
T.assert_equal(5, len(found_li))
T.assert_equal(10, len(found_mockreq))
def test_mine_on_requests_as_pushmaster(self):
push_contents = {}
section_id = []
for section in self.accepting_push_sections:
push_contents[section] = [self.basic_request]
section_id.append('%s-items' % section)
kwargs = dict(self.basic_kwargs)
kwargs['push_contents'] = push_contents
with self.no_ui_modules():
tree = self.render_etree(
self.push_status_page,
push_info=self.basic_push,
**kwargs)
found_mockreq = []
for mockreq in tree.iter('mock'):
T.assert_not_in('class', mockreq.getparent().attrib.keys())
found_mockreq.append(mockreq)
T.assert_equal(5, len(found_mockreq))
def test_include_push_survey_exists(self):
push = dict(self.basic_push)
push['state'] = 'live'
kwargs = dict(**self.basic_kwargs)
kwargs['push_survey_url'] = 'http://sometestsurvey'
tree = self.render_etree(
self.push_page,
push_info=push,
**kwargs)
for script in tree.iter('script'):
if script.text and kwargs['push_survey_url'] in script.text:
break
else:
assert False, 'push_survey_url not found'
def test_include_new_request_form(self):
with self.no_ui_modules():
tree = self.render_etree(
self.push_page,
push_info=self.basic_push,
**self.basic_kwargs)
T.assert_exactly_one(
*[mock.attrib['name'] for mock in tree.iter('mock')],
truthy_fxn=lambda name: name == 'mock.NewRequestDialog()')
def test_include_edit_push(self):
tree = self.render_etree(
self.push_page,
push_info=self.basic_push,
**self.basic_kwargs)
found_form = []
for form in tree.iter('form'):
if form.attrib['id'] == 'push-info-form':
found_form.append(form)
T.assert_equal(len(found_form), 1)
def test_include_dialogs(self):
tree = self.render_etree(
self.push_page,
push_info=self.basic_push,
**self.basic_kwargs)
found_divs = []
for div in tree.iter('div'):
if 'id' in div.attrib and div.attrib['id'] == 'dialog-prototypes':
found_divs.append(div)
T.assert_equal(len(found_divs), 1)
push_info_items = [
'Pushmaster', 'Branch', 'Buildbot Runs',
'State', 'Push Type', 'Created', 'Modified'
]
push_info_attributes = {
'branch': basic_push['branch'],
'class': 'push-info standalone',
'id': 'push-info',
'pushmaster': basic_push['user'],
'push': '%d' % basic_push['id'],
'stageenv': '',
'title': basic_push['title'],
}
def assert_push_info_attributes(self, ul_attributes, expected):
T.assert_dicts_equal(ul_attributes, expected)
def assert_push_info_listitems(self, list_items, push_info_items):
for li in list_items:
T.assert_in(li[0].text, push_info_items.keys())
if li[0].text == 'Buildbot Runs':
T.assert_equal(li[1][0].text, 'url')
T.assert_equal(li[1][0].attrib['href'], push_info_items['Buildbot Runs'])
elif li[0].text == 'State':
T.assert_equal(li[1][0].attrib['class'], 'tags') # Inner ul
T.assert_equal(li[1][0][0].attrib['class'], 'tag-%s' % push_info_items['State']) # Inner li
T.assert_equal(li[1][0][0].text, push_info_items['State'])
elif li[0].text == 'Push Type':
T.assert_equal(li[1][0].attrib['class'], 'tags') # Inner ul
T.assert_equal(li[1][0][0].attrib['class'], 'tag-%s' % push_info_items['Push Type']) # Inner li
T.assert_equal(li[1][0][0].text, push_info_items['Push Type'])
else:
T.assert_equal(li[1].text, push_info_items[li[0].text])
T.assert_equal(len(list_items), len(push_info_items))
def test_push_info_list_items(self):
tree = self.render_etree(
self.push_info_page,
push_info=self.basic_push,
**self.basic_kwargs)
self.assert_push_info_listitems(list(tree.iter('ul'))[0], self.basic_push_info_items)
self.assert_push_info_attributes(list(tree.iter('ul'))[0].attrib, self.push_info_attributes)
def test_push_info_list_items_modified(self):
push = dict(self.basic_push)
push['modified'] = time.time()
tree = self.render_etree(
self.push_info_page,
push_info=push,
**self.basic_kwargs)
push_info_items = dict(self.basic_push_info_items)
push_info_items['Modified'] = time.strftime("%x %X", time.localtime(push['modified']))
self.assert_push_info_listitems(list(tree.iter('ul'))[0], push_info_items)
self.assert_push_info_attributes(list(tree.iter('ul'))[0].attrib, self.push_info_attributes)
def test_push_info_list_items_notaccepting(self):
push = dict(self.basic_push)
push['state'] = 'live'
tree = self.render_etree(
self.push_info_page,
push_info=push,
**self.basic_kwargs)
push_info_items = dict(self.basic_push_info_items)
push_info_items['State'] = 'live'
del push_info_items['Buildbot Runs']
self.assert_push_info_listitems(list(tree.iter('ul'))[0], push_info_items)
self.assert_push_info_attributes(list(tree.iter('ul'))[0].attrib, self.push_info_attributes)
def test_push_info_list_items_stageenv(self):
push = dict(self.basic_push)
push['stageenv'] = 'stageenv'
tree = self.render_etree(
self.push_info_page,
push_info=push,
**self.basic_kwargs)
push_info_items = dict(self.basic_push_info_items)
push_info_items['Stage'] = 'stageenv'
attributes = dict(self.push_info_attributes)
attributes['stageenv'] = 'stageenv'
self.assert_push_info_listitems(list(tree.iter('ul'))[0], push_info_items)
self.assert_push_info_attributes(list(tree.iter('ul'))[0].attrib, attributes)
push_button_ids_base = ['expand-all-requests', 'collapse-all-requests', 'ping-me', 'edit-push']
push_button_ids_pushmaster = [
'discard-push', 'add-selected-requests',
'remove-selected-requests', 'rebuild-deploy-branch',
'deploy-to-stage-step0', 'deploy-to-prod', 'merge-to-master',
'message-all', 'show-checklist']
def test_push_buttons_random_user(self):
with self.no_ui_modules():
tree = self.render_etree(
self.push_button_bar_page,
push_info=self.basic_push,
**self.basic_kwargs)
found_buttons = []
for button in tree.iter('button'):
T.assert_in(button.attrib['id'], self.push_button_ids_base)
found_buttons.append(button)
T.assert_equal(len(found_buttons), len(self.push_button_ids_base))
def test_push_buttons_pushmaster(self):
kwargs = dict(self.basic_kwargs)
kwargs['current_user'] = self.basic_push['user']
with self.no_ui_modules():
tree = self.render_etree(
self.push_button_bar_page,
push_info=self.basic_push,
**kwargs)
found_buttons = []
for button in tree.iter('button'):
T.assert_in(
button.attrib['id'],
self.push_button_ids_base + self.push_button_ids_pushmaster)
found_buttons.append(button)
T.assert_equal(
len(found_buttons),
len(self.push_button_ids_base + self.push_button_ids_pushmaster))
dialog_ids = [
'dialog-prototypes',
'run-a-command', 'comment-on-request', 'merge-requests',
'merge-branches-command', 'push-checklist', 'send-message-prompt',
'push-survey', 'set-stageenv-prompt',
]
def test_dialogs_divs(self):
tree = self.render_etree(
self.push_dialogs_page,
push_info=self.basic_push,
**self.basic_kwargs)
found_divs = []
for div in tree.iter('div'):
T.assert_in(div.attrib['id'], self.dialog_ids)
found_divs.append(div)
T.assert_equal(len(found_divs),len(self.dialog_ids))
if __name__ == '__main__':
T.run()
|
|
#!/usr/bin/env python
# The MIT License (MIT)
# Copyright (c) 2014 xaedes
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import rospy
import numpy as np
# import numdifftools as nd # sudo pip install numdifftools
from time import time
from std_msgs.msg import Int32
from std_msgs.msg import Float32
from geometry_msgs.msg import Vector3Stamped
from sensor_msgs.msg import Imu
import functools
import sys
import signal
import threading
from Kalman import Kalman
from ExtendedKalman import ExtendedKalman
from DTFilter import DTFilter
class ImuSensorsFilter(Kalman):
"""docstring for ImuSensorsFilter"""
def __init__(self):
super(ImuSensorsFilter, self).__init__(n_states = 9, n_sensors = 9)
#states:
# accel: x,y,z 0:3
# gyro: x,y,z 3:6
# mag: x,y,z 6:9
#sensors:
# accel: x,y,z 0:3
# gyro: x,y,z 3:6
# mag: x,y,z 6:9
self.states = self.sensors = {'accel.x': 0, 'accel.y': 1, 'accel.z': 2,
'gyro.x': 3, 'gyro.y': 4, 'gyro.z': 5,
'mag.x': 6, 'mag.y': 7, 'mag.z': 8}
# H: Messmatrix
self.H = np.matrix( '1 0 0 0 0 0 0 0 0;' #accel.x
'0 1 0 0 0 0 0 0 0;' #accel.y
'0 0 1 0 0 0 0 0 0;' #accel.z
'0 0 0 1 0 0 0 0 0;' #gyro.x
'0 0 0 0 1 0 0 0 0;' #gyro.y
'0 0 0 0 0 1 0 0 0;' #gyro.z
'0 0 0 0 0 0 1 0 0;' #mag.x
'0 0 0 0 0 0 0 1 0;' #mag.y
'0 0 0 0 0 0 0 0 1 ' #mag.z
)
# F: Dynamik
self.F = np.matrix([[1,0,0,0,0,0,0,0,0], #accel.x = accel.x
[0,1,0,0,0,0,0,0,0], #accel.y = accel.y
[0,0,1,0,0,0,0,0,0], #accel.z = accel.z
[0,0,0,1,0,0,0,0,0], #gyro.x = gyro.x
[0,0,0,0,1,0,0,0,0], #gyro.y = gyro.y
[0,0,0,0,0,1,0,0,0], #gyro.z = gyro.z
[0,0,0,0,0,0,1,0,0], #mag.x = mag.x
[0,0,0,0,0,0,0,1,0], #mag.y = mag.y
[0,0,0,0,0,0,0,0,1] #mag.z = mag.z
])
# Q: Unsicherheit der Dynamik
self.Q = np.matrix(np.identity(self.n_states)) * 0.1
# P: Unsicherheit ueber Systemzustand
self.P *= 0.1
# R: Messunsicherheit
self.R *= 1
def measure(self,imu,mag,biases=None):
Z = np.matrix([imu.linear_acceleration.x,imu.linear_acceleration.y,imu.linear_acceleration.z,
imu.angular_velocity.x,imu.angular_velocity.y,imu.angular_velocity.z,
mag.vector.x,mag.vector.y,mag.vector.z]).getT()
self.predict()
if biases==None:
self.update(Z)
else:
self.update(Z-biases)
class ImuSensorsBiasFilter(ImuSensorsFilter):
"""docstring for ImuSensorsBiasFilter"""
def __init__(self):
super(ImuSensorsBiasFilter, self).__init__()
# Aenderungen gegenueber ImuSensorsFilter:
# Q: Unsicherheit der Dynamik
self.Q *= 1
# P: Unsicherheit ueber Systemzustand
self.P *= 1
# R: Messunsicherheit
self.R *= 1
class MotionModelCV(ExtendedKalman):
"""Constant Velocity linear motion model"""
#http://www.isif.org/fusion/proceedings/fusion08CD/papers/1569107835.pdf
def __init__(self, dt):
super(MotionModelCV, self).__init__(n_states = 4, n_sensors = 2)
#states:
# acceleration 0
# velocity 1
# velocity_bias 2
# distance 3
#sensors:
# acceleration 0
# velocity_bias 1
self.states = {'acceleration': 0, 'velocity': 1, 'velocity_bias': 2, 'distance': 3}
self.sensors = {'acceleration': 0,'velocity_bias': 1}
# self.x[1,0] = 10
self.dt = dt
# F: Dynamik
self.f = lambda x,u: np.array([
[0], # acceleration = 0
[x[1,0] + self.dt*x[0,0]], # velocity = velocity + dt * acceleration
[x[2,0]], # velocity_bias = velocity_bias
[self.dt*self.dt*x[0,0] + self.dt*x[1,0] - self.dt*x[2,0] + x[3,0]] # distance = distance + dt * (velocity-velocity_bias) + dt * dt * acceleration
])
self.J_f_fun = lambda x: np.matrix([
[0,0,0,0],
[self.dt,1,0,0],
[0,0,1,0],
[self.dt*self.dt,self.dt,-self.dt,1]
])
# h: Messfunktion
# function h can be used to compute the predicted measurement from the predicted state
self.h = lambda x: np.array([
[0], # expect to see zero
[0] # expect to see zero
])
self.J_h_fun = lambda x: np.matrix([
[0,0,0,0],
[0,0,0,0]
])
def update_dt(self,dt):
self.dt = dt
def measure(self,acceleration,zero_velocity):
# print acceleration
# Z = np.matrix([[acceleration]])
if(zero_velocity==True):
Z = np.matrix([acceleration,self.x[self.states['velocity'],0]]).getT()
else:
Z = np.matrix([acceleration,0]).getT()
self.predict()
self.x[0,0] = acceleration
self.update(Z)
class OrientationFilter(ExtendedKalman):
"""OrientationFilter"""
#
def __init__(self, dt):
super(OrientationFilter, self).__init__(n_states = 2, n_sensors = 1)
#states:
# gyro 0
# angle 1
#sensors:
# gyro 0
self.states = {'gyro': 0, 'angle': 1}
self.sensors = {'gyro': 0}
self.dt = dt
# F: Dynamik
self.f = lambda x,u: np.array([
[0], # gyro = 0
[self.dt*x[0,0] + x[1,0]] # angle = angle + dt * gyro
])
self.J_f_fun = lambda x: np.matrix([
[0,0],
[1.,0]
])
# h: Messfunktion
# function h can be used to compute the predicted measurement from the predicted state
self.h = lambda x: np.array([
[0] # expect to see zero
])
self.J_h_fun = lambda x: np.matrix([
[0,0]
])
def update_dt(self,dt):
self.dt = dt
def measure(self,gyro):
Z = np.matrix([gyro]).getT()
self.predict()
self.x[0,0] = gyro # hack
self.update(Z)
class MeasureSampleRate(object):
"""docstring for MeasureSampleRate"""
def __init__(self, update_interval = 10, gain = 0.5):
super(MeasureSampleRate, self).__init__()
self.sample_rate = 1
self.gain = gain
self.update_interval = update_interval #in number of samples
self.first_samplerate = False
self.n_samples = 0
self.last_time = rospy.Time.now().to_sec()
def add_sample(self):
self.n_samples = (self.n_samples + 1) % self.update_interval
if self.n_samples == 0:
self.update_sample_rate(self.update_interval)
def update_sample_rate(self, n_new_samples = 1):
dtime = rospy.Time.now().to_sec() - self.last_time
self.last_time = rospy.Time.now().to_sec()
current_sample_rate = n_new_samples / dtime
if self.first_samplerate:
self.first_samplerate = False
self.sample_rate = current_sample_rate
self.sample_rate = self.sample_rate * (1-self.gain) + current_sample_rate * self.gain
return self.sample_rate
def __complex__(self):
return complex(self.sample_rate)
def __int__(self):
return int(self.sample_rate)
def __long__(self):
return long(self.sample_rate)
def __float__(self):
return float(self.sample_rate)
class Subscriber(object):
"""docstring for Subscriber"""
def __init__(self):
super(Subscriber, self).__init__()
rospy.init_node('kalman', anonymous=True)
self.run = True
self.pause = False
self.rate = 40.
signal.signal(signal.SIGINT, self.keyboard_interupt)
self.dt = 1./min(self.rate,40.) # topic rate ~ 40hz
self.measure_sample_rate = MeasureSampleRate()
self.sensors = ImuSensorsFilter()
self.sensor_biases = ImuSensorsBiasFilter()
self.orientation = OrientationFilter(dt=self.dt)
self.motion_cv = MotionModelCV(dt=self.dt)
# Publishers
self.pub_imu = rospy.Publisher('/imu/data_filtered', Imu)
self.pub_imu_bias = rospy.Publisher('/imu/data_biases', Imu)
self.pub_mag = rospy.Publisher('/imu/mag_filtered', Vector3Stamped)
self.pub_rps = rospy.Publisher('/rps', Float32)
self.pub_dt = rospy.Publisher('/kalman_dt', Float32)
self.pub_cv_vel = rospy.Publisher('/motion/cv/velocity', Float32)
self.pub_cv_acc = rospy.Publisher('/motion/cv/acceleration', Float32)
self.pub_cv_dis = rospy.Publisher('/motion/cv/distance', Float32)
self.pub_orientation = rospy.Publisher('/orientation', Float32)
# Subscribers
rospy.Subscriber('/imu/data_raw', Imu, self.callback_imu)
rospy.Subscriber('/imu/mag', Vector3Stamped, self.callback_mag)
rospy.Subscriber('/sensor_motor_revolutions', Int32, self.callback_revolutions)
rospy.Subscriber('/sensor_motor_rps', Float32, self.callback_rps)
self.rps_gain = 0.25
self.dt_gain = 0.125 / 2
self.dtfilter = DTFilter(dt_estimate = 1.0 / self.rate)
self.imu = self.mag = self.revolutions = None
self.rps = 0
self.last_revolutions = self.last_rps_time = self.last_time = None
self.counter = 0
self.spin()
def reset(self):
self.dtfilter = DTFilter(dt_estimate = 1.0 / self.rate)
self.dt = self.dtfilter.update()
self.sensors.reset()
self.sensor_biases.reset()
self.motion_cv.reset()
self.orientation.reset()
self.imu = self.mag = self.revolutions = None
self.rps = 0
self.last_revolutions = self.last_rps_time = self.last_time = None
print "reset"
def callback_rps(self, msg):
self.rps = msg.data
def callback_revolutions(self, msg):
self.revolutions = msg.data
def callback_imu(self, msg):
self.imu = msg
def callback_mag(self, msg):
self.mag = msg
def spin(self):
# print "Setting up rate ", self.rate, "hz"
r = rospy.Rate(self.rate)
while(self.run):
self.measure()
# self.pub_mag.publish(Vector3Stamped())
r.sleep()
def measure(self):
# only proceed if we have all msgs
if((self.mag==None)or(self.imu==None)or(self.rps==None)):
return
# update sample rate and dt
self.measure_sample_rate.add_sample()
# self.dt = 1/float(self.measure_sample_rate)
# filter dt
self.dt = self.dtfilter.update()
# self.pub_dt.publish(self.dt)
self.counter += 1
if(self.counter==10):
print float(self.measure_sample_rate)
self.counter=0
# update bias if car stands still (rps < 1)
if(self.rps < 1):
self.sensor_biases.measure(self.imu,self.mag)
# update sensors
self.sensors.measure(self.imu,self.mag,self.sensor_biases.x)
# update orientation filter
self.orientation.dt = self.dt
self.orientation.measure(self.sensors.x[self.sensors.states['gyro.z'],0])
# grab header to propagate to published msgs
header = self.mag.header
# update motion model
# self.motion_cv.update_dt(self.dt)
# self.motion_cv.measure(self.sensors.x[self.sensors.states['accel.x'],0],)
######### publish filtered data
self.pub_orientation.publish(self.orientation.x[self.orientation.states['angle'],0])
# if(False):
# # publish imu bias
# imu = Imu()
# imu.header = header
# imu.linear_acceleration.x = self.sensor_biases.x[0]
# imu.linear_acceleration.y = self.sensor_biases.x[1]
# imu.linear_acceleration.z = self.sensor_biases.x[2]
# imu.angular_velocity.x = self.sensor_biases.x[3]
# imu.angular_velocity.y = self.sensor_biases.x[4]
# imu.angular_velocity.z = self.sensor_biases.x[5]
# self.pub_imu_bias.publish(imu)
# # publish filtered mag
# mag = Vector3Stamped()
# mag.header = header
# mag.vector.x = self.sensors.x[6]
# mag.vector.y = self.sensors.x[7]
# mag.vector.z = self.sensors.x[8]
# self.pub_mag.publish(mag)
# # publish rps
# self.pub_rps.publish(self.rps)
# # publish filtered imu
# imu = Imu()
# imu.header = header
# imu.linear_acceleration.x = self.sensors.x[0,0]
# imu.linear_acceleration.y = self.sensors.x[1,0]
# imu.linear_acceleration.z = self.sensors.x[2,0]
# imu.angular_velocity.x = self.sensors.x[3,0]
# imu.angular_velocity.y = self.sensors.x[4,0]
# imu.angular_velocity.z = self.sensors.x[5,0]
# self.pub_imu.publish(imu)
# # publish data from motion model
# self.pub_cv_vel.publish(self.motion_cv.x[self.motion_cv.states['velocity'],0]-self.motion_cv.x[self.motion_cv.states['velocity_bias'],0])
# self.pub_cv_acc.publish(self.motion_cv.x[self.motion_cv.states['acceleration'],0])
# self.pub_cv_dis.publish(self.motion_cv.x[self.motion_cv.states['distance'],0])
# remove old msgs
self.imu = self.mag = self.rps = None
def keyboard_interupt(self, signum, frame):
self.run = False
print " closing...\n"
if __name__ == '__main__':
subscriber = Subscriber()
|
|
import theano
import theano.tensor as T
import lasagne as nn
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
_srng = RandomStreams()
class TiedDropoutLayer(nn.layers.Layer):
"""
Dropout layer that broadcasts the mask across all axes beyond the first two.
"""
def __init__(self, input_layer, p=0.5, rescale=True, **kwargs):
super(TiedDropoutLayer, self).__init__(input_layer, **kwargs)
self.p = p
self.rescale = rescale
def get_output_for(self, input, deterministic=False, *args, **kwargs):
if deterministic or self.p == 0:
return input
else:
retain_prob = 1 - self.p
if self.rescale:
input /= retain_prob
mask = _srng.binomial(input.shape[:2], p=retain_prob,
dtype=theano.config.floatX)
axes = [0, 1] + (['x'] * (input.ndim - 2))
mask = mask.dimshuffle(*axes)
return input * mask
class BatchNormLayer(nn.layers.Layer):
"""
lasagne.layers.BatchNormLayer(incoming, axes='auto', epsilon=1e-4,
alpha=0.5, nonlinearity=None, mode='low_mem',
beta=lasagne.init.Constant(0), gamma=lasagne.init.Constant(1),
mean=lasagne.init.Constant(0), var=lasagne.init.Constant(1), **kwargs)
Batch Normalization
This layer implements batch normalization of its inputs, following [1]_:
.. math::
y = \\frac{x - \\mu}{\\sqrt{\\sigma^2 + \\epsilon}} \\gamma + \\beta
That is, the input is normalized to zero mean and unit variance, and then
linearly transformed.
During training, :math:`\\mu` and :math:`\\sigma^2` are defined to be the
mean and variance of the current input mini-batch :math:`x`, and during
testing, they are replaced with average statistics over the training
data. Consequently, this layer has four stored parameters: :math:`\\beta`,
:math:`\\gamma`, and the averages :math:`\\mu` and :math:`\\sigma^2`.
By default, this layer learns the average statistics as exponential moving
averages computed during training, so it can be plugged into an existing
network without any changes of the training procedure (see Notes).
Parameters
----------
incoming : a :class:`Layer` instance or a tuple
The layer feeding into this layer, or the expected input shape
axes : 'auto', int or tuple of int
The axis or axes to normalize over. If ``'auto'`` (the default),
normalize over all axes except for the second: this will normalize over
the minibatch dimension for dense layers, and additionally over all
spatial dimensions for convolutional layers.
epsilon : scalar
Small constant :math:`\\epsilon` added to the variance before taking
the square root and dividing by it, to avoid numeric problems
alpha : scalar
Coefficient for the exponential moving average of batch-wise means and
standard deviations computed during training; the closer to one, the
more it will depend on the last batches seen
nonlinearity : callable or None
The nonlinearity that is applied to the layer activations. If ``None``
is provided, the layer will be linear (this is the default).
mode : {'low_mem', 'high_mem'}
Specify which batch normalization implementation to use: ``'low_mem'``
avoids storing intermediate representations and thus requires less
memory, while ``'high_mem'`` can reuse representations for the backward
pass and is thus 5-10% faster.
beta : Theano shared variable, expression, numpy array, or callable
Initial value, expression or initializer for :math:`\\beta`. Must match
the incoming shape, skipping all axes in `axes`.
See :func:`lasagne.utils.create_param` for more information.
gamma : Theano shared variable, expression, numpy array, or callable
Initial value, expression or initializer for :math:`\\gamma`. Must
match the incoming shape, skipping all axes in `axes`.
See :func:`lasagne.utils.create_param` for more information.
mean : Theano shared variable, expression, numpy array, or callable
Initial value, expression or initializer for :math:`\\mu`. Must match
the incoming shape, skipping all axes in `axes`.
See :func:`lasagne.utils.create_param` for more information.
var : Theano shared variable, expression, numpy array, or callable
Initial value, expression or initializer for :math:`\\sigma^2`. Must
match the incoming shape, skipping all axes in `axes`.
See :func:`lasagne.utils.create_param` for more information.
**kwargs
Any additional keyword arguments are passed to the :class:`Layer`
superclass.
Notes
-----
This layer should be inserted between a linear transformation (such as a
:class:`DenseLayer`, or :class:`Conv2DLayer`) and its nonlinearity. The
convenience function :func:`batch_norm` modifies an existing layer to
insert batch normalization in front of its nonlinearity.
The behavior can be controlled by passing keyword arguments to
:func:`lasagne.layers.get_output()` when building the output expression
of any network containing this layer.
During training, [1]_ normalize each input mini-batch by its statistics
and update an exponential moving average of the statistics to be used for
validation. This can be achieved by passing ``deterministic=False``.
For validation, [1]_ normalize each input mini-batch by the stored
statistics. This can be achieved by passing ``deterministic=True``.
For more fine-grained control, ``batch_norm_update_averages`` can be passed
to update the exponential moving averages (``True``) or not (``False``),
and ``batch_norm_use_averages`` can be passed to use the exponential moving
averages for normalization (``True``) or normalize each mini-batch by its
own statistics (``False``). These settings override ``deterministic``.
Note that for testing a model after training, [1]_ replace the stored
exponential moving average statistics by fixing all network weights and
re-computing average statistics over the training data in a layerwise
fashion. This is not part of the layer implementation.
See also
--------
batch_norm : Convenience function to apply batch normalization to a layer
References
----------
.. [1]: Ioffe, Sergey and Szegedy, Christian (2015):
Batch Normalization: Accelerating Deep Network Training by Reducing
Internal Covariate Shift. http://arxiv.org/abs/1502.03167.
"""
def __init__(self, incoming, axes='auto', epsilon=1e-4, alpha=0.1,
nonlinearity=None, mode='low_mem',
beta=nn.init.Constant(0), gamma=nn.init.Constant(1),
mean=nn.init.Constant(0), var=nn.init.Constant(1), **kwargs):
super(BatchNormLayer, self).__init__(incoming, **kwargs)
if axes == 'auto':
# default: normalize over all but the second axis
axes = (0,) + tuple(range(2, len(self.input_shape)))
elif isinstance(axes, int):
axes = (axes,)
self.axes = axes
self.epsilon = epsilon
self.alpha = alpha
if nonlinearity is None:
nonlinearity = nn.nonlinearities.identity
self.nonlinearity = nonlinearity
self.mode = mode
# create parameters, ignoring all dimensions in axes
shape = [size for axis, size in enumerate(self.input_shape)
if axis not in self.axes]
if any(size is None for size in shape):
raise ValueError("BatchNormLayer needs specified input sizes for "
"all axes not normalized over.")
self.beta = self.add_param(beta, shape, 'beta',
trainable=True, regularizable=False)
self.gamma = self.add_param(gamma, shape, 'gamma',
trainable=True, regularizable=True)
self.mean = self.add_param(mean, shape, 'mean',
trainable=False, regularizable=False)
self.var = self.add_param(var, shape, 'var',
trainable=False, regularizable=False)
def get_output_for(self, input, deterministic=False, **kwargs):
input_mean = input.mean(self.axes)
input_var = input.var(self.axes)
# Decide whether to use the stored averages or mini-batch statistics
use_averages = kwargs.get('batch_norm_use_averages',
deterministic)
if use_averages:
mean = self.mean
var = self.var
else:
mean = input_mean
var = input_var
# Decide whether to update the stored averages
update_averages = kwargs.get('batch_norm_update_averages',
not deterministic)
if update_averages:
# Trick: To update the stored statistics, we create memory-aliased
# clones of the stored statistics:
running_mean = theano.clone(self.mean, share_inputs=False)
running_var = theano.clone(self.var, share_inputs=False)
# set a default update for them:
running_mean.default_update = ((1 - self.alpha) * running_mean +
self.alpha * input_mean)
running_var.default_update = ((1 - self.alpha) * running_var +
self.alpha * input_var)
# and make sure they end up in the graph without participating in
# the computation (this way their default_update will be collected
# and applied, but the computation will be optimized away):
mean += 0 * running_mean
var += 0 * running_var
# prepare dimshuffle pattern inserting broadcastable axes as needed
param_axes = iter(range(self.beta.ndim))
pattern = ['x' if input_axis in self.axes
else next(param_axes)
for input_axis in range(input.ndim)]
# apply dimshuffle pattern to all parameters
beta = self.beta.dimshuffle(pattern)
gamma = self.gamma.dimshuffle(pattern)
mean = mean.dimshuffle(pattern)
std = T.sqrt(var + self.epsilon)
std = std.dimshuffle(pattern)
# normalize
# normalized = (input - mean) * (gamma / std) + beta
normalized = T.nnet.batch_normalization(input, gamma=gamma, beta=beta,
mean=mean, std=std,
mode=self.mode)
return self.nonlinearity(normalized)
def batch_norm(layer, **kwargs):
"""
Apply batch normalization to an existing layer. This is a convenience
function modifying an existing layer to include batch normalization: It
will steal the layer's nonlinearity if there is one (effectively
introducing the normalization right before the nonlinearity), remove
the layer's bias if there is one (because it would be redundant), and add
a :class:`BatchNormLayer` on top.
Parameters
----------
layer : A :class:`Layer` instance
The layer to apply the normalization to; note that it will be
irreversibly modified as specified above
**kwargs
Any additional keyword arguments are passed on to the
:class:`BatchNormLayer` constructor. Especially note the `mode`
argument, which controls a memory usage to performance tradeoff.
Returns
-------
:class:`BatchNormLayer` instance
A batch normalization layer stacked on the given modified `layer`.
"""
nonlinearity = getattr(layer, 'nonlinearity', None)
if nonlinearity is not None:
layer.nonlinearity = nn.nonlinearities.identity
if hasattr(layer, 'b'):
del layer.params[layer.b]
layer.b = None
return BatchNormLayer(layer, nonlinearity=nonlinearity, **kwargs)
def batch_norm2(layer, **kwargs):
nonlinearity = getattr(layer, 'nonlinearity', None)
if nonlinearity is not None:
layer.nonlinearity = nn.nonlinearities.identity
if hasattr(layer, 'b') and layer.b is not None:
del layer.params[layer.b]
layer.b = None
layer = BatchNormLayer(layer, **kwargs)
if nonlinearity is not None:
from lasagne.layers.special import NonlinearityLayer
layer = NonlinearityLayer(layer, nonlinearity, name='%s_nl' % layer.name)
return layer
|
|
#!/usr/bin/env python
# vim: et :
#
# This is run by Travis-CI after an upgrade to verify that the data loaded by
# upgrade-before.py has been correctly updated in the upgrade process. For
# example, new columns might have been added and the value of those columns
# should be automatically updated. This test should be used to verify such
# things.
#
import logging
import unittest
import sys
sys.path.append('../nipap/')
from nipap.backend import Nipap
from nipap.authlib import SqliteAuth
from nipap.nipapconfig import NipapConfig
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
log_format = "%(levelname)-8s %(message)s"
import xmlrpclib
server_url = "http://unittest:[email protected]:1337/XMLRPC"
s = xmlrpclib.Server(server_url, allow_none=1);
ad = { 'authoritative_source': 'nipap' }
class TestCheckdata(unittest.TestCase):
""" Tests the NIPAP XML-RPC daemon
"""
maxDiff = None
def _mangle_pool_result(self, res):
""" Mangle pool result for easier testing
We can never predict the values of things like the ID (okay, that
one is actually kind of doable) or the added and last_modified
timestamp. This function will make sure the values are present but
then strip them to make it easier to test against an expected
result.
"""
if isinstance(res, list):
# res from list_prefix
for p in res:
self.assertIn('id', p)
del(p['id'])
elif isinstance(res, dict) and 'result' in res:
# res from smart search
for p in res['result']:
self.assertIn('id', p)
del(p['id'])
elif isinstance(res, dict):
# just one single prefix
self.assertIn('id', res)
del(res['id'])
return res
def _mangle_prefix_result(self, res):
""" Mangle prefix result for easier testing
We can never predict the values of things like the ID (okay, that
one is actually kind of doable) or the added and last_modified
timestamp. This function will make sure the values are present but
then strip them to make it easier to test against an expected
result.
"""
if isinstance(res, list):
# res from list_prefix
for p in res:
self.assertIn('added', p)
self.assertIn('last_modified', p)
self.assertIn('id', p)
self.assertIn('pool_id', p)
del(p['added'])
del(p['last_modified'])
del(p['id'])
del(p['pool_id'])
elif isinstance(res, dict) and 'result' in res:
# res from smart search
for p in res['result']:
self.assertIn('added', p)
self.assertIn('last_modified', p)
self.assertIn('id', p)
self.assertIn('pool_id', p)
del(p['added'])
del(p['last_modified'])
del(p['id'])
del(p['pool_id'])
elif isinstance(res, dict):
# just one single prefix
self.assertIn('added', res)
self.assertIn('last_modified', res)
self.assertIn('id', res)
self.assertIn('pool_id', res)
del(res['added'])
del(res['last_modified'])
del(res['id'])
del(res['pool_id'])
return res
def _mangle_vrf_result(self, res):
""" Mangle vrf result for easier testing
We can never predict the values of things like the ID (okay, that
one is actually kind of doable) or the added and last_modified
timestamp. This function will make sure the values are present but
then strip them to make it easier to test against an expected
result.
"""
if isinstance(res, list):
# res from list_prefix
for p in res:
self.assertIn('id', p)
del(p['id'])
elif isinstance(res, dict) and 'result' in res:
# res from smart search
for p in res['result']:
self.assertIn('id', p)
del(p['id'])
elif isinstance(res, dict):
# just one single prefix
self.assertIn('id', res)
del(res['id'])
return res
def test_verify_prefix(self):
""" Verify data after upgrade
"""
expected_base = {
'alarm_priority': None,
'authoritative_source': 'nipap',
'avps': {},
'comment': None,
'country': None,
'description': 'test',
'expires': None,
'external_key': None,
'family': 4,
'indent': 0,
'inherited_tags': [],
'monitor': None,
'node': None,
'order_id': None,
'customer_id': None,
'pool_name': None,
'tags': [],
'type': 'reservation',
'vrf_rt': None,
'vrf_id': 0,
'vrf_name': 'default',
'vlan': None,
'status': 'assigned'
}
expected_prefixes = [
{ 'prefix': '192.168.0.0/16', 'indent': 0, 'total_addresses':
'65536', 'used_addresses': '8192', 'free_addresses': '57344' },
{ 'prefix': '192.168.0.0/20', 'indent': 1, 'total_addresses':
'4096', 'used_addresses': '768', 'free_addresses': '3328',
'pool_name': 'upgrade-test' },
{ 'prefix': '192.168.0.0/24', 'indent': 2, 'total_addresses':
'256', 'used_addresses': '0', 'free_addresses': '256' },
{ 'prefix': '192.168.1.0/24', 'indent': 2, 'total_addresses':
'256', 'used_addresses': '0', 'free_addresses': '256' },
{ 'prefix': '192.168.2.0/24', 'indent': 2, 'total_addresses':
'256', 'used_addresses': '0', 'free_addresses': '256' },
{ 'prefix': '192.168.32.0/20', 'indent': 1, 'total_addresses':
'4096', 'used_addresses': '256', 'free_addresses': '3840' },
{ 'prefix': '192.168.32.0/24', 'indent': 2, 'total_addresses':
'256', 'used_addresses': '1', 'free_addresses': '255' },
{ 'prefix': '192.168.32.1/32', 'display_prefix': '192.168.32.1',
'indent': 3, 'total_addresses': '1', 'used_addresses': '1',
'free_addresses': '0' },
{ 'prefix': '2001:db8:1::/48', 'indent': 0, 'family': 6,
'pool_name': 'upgrade-test',
'total_addresses': '1208925819614629174706176',
'used_addresses': '18446744073709551616',
'free_addresses': '1208907372870555465154560' },
{ 'prefix': '2001:db8:1::/64', 'indent': 1, 'family': 6,
'total_addresses': '18446744073709551616', 'used_addresses': '0',
'free_addresses': '18446744073709551616' },
{ 'prefix': '2001:db8:2::/48', 'indent': 0, 'family': 6,
'total_addresses': '1208925819614629174706176',
'used_addresses': '0',
'free_addresses': '1208925819614629174706176' },
]
expected = []
for p in expected_prefixes:
pexp = expected_base.copy()
for key in p:
pexp[key] = p[key]
if 'display_prefix' not in pexp:
pexp['display_prefix'] = p['prefix']
expected.append(pexp)
self.assertEqual(expected, self._mangle_prefix_result(s.list_prefix({ 'auth': ad, })))
def test_pool1(self):
""" Verify data after upgrade
"""
expected = [{
'used_prefixes_v4': '3',
'used_prefixes_v6': '1',
'free_prefixes_v4': '1664',
'free_prefixes_v6': '18446462598732840960',
'total_prefixes_v4': '1667',
'total_prefixes_v6': '18446462598732840961',
'default_type': None,
'description': None,
'free_addresses_v4': '3328',
'free_addresses_v6': '1208907372870555465154560',
'ipv4_default_prefix_length': 31,
'ipv6_default_prefix_length': 112,
'member_prefixes_v4': '1',
'member_prefixes_v6': '1',
'name': 'upgrade-test',
'prefixes': [ '192.168.0.0/20', '2001:db8:1::/48' ],
'total_addresses_v4': '4096',
'total_addresses_v6': '1208925819614629174706176',
'used_addresses_v4': '768',
'used_addresses_v6': '18446744073709551616',
'vrf_id': 0,
'vrf_name': 'default',
'vrf_rt': None,
'tags': [],
'avps': {}
}]
self.assertEqual(expected, self._mangle_pool_result(s.list_pool({ 'auth': ad, 'pool': { 'name': 'upgrade-test' } })))
def test_pool2(self):
""" Verify data after upgrade
"""
expected = [{
'used_prefixes_v4': '0',
'used_prefixes_v6': '0',
'free_prefixes_v4': None,
'free_prefixes_v6': None,
'total_prefixes_v4': None,
'total_prefixes_v6': None,
'default_type': None,
'description': None,
'free_addresses_v4': '0',
'free_addresses_v6': '0',
'ipv4_default_prefix_length': None,
'ipv6_default_prefix_length': None,
'member_prefixes_v4': '0',
'member_prefixes_v6': '0',
'name': 'upgrade-test2',
'prefixes': [ ],
'total_addresses_v4': '0',
'total_addresses_v6': '0',
'used_addresses_v4': '0',
'used_addresses_v6': '0',
'vrf_id': None,
'vrf_name': None,
'vrf_rt': None,
'tags': [],
'avps': {}
}]
self.assertEqual(expected, self._mangle_pool_result(s.list_pool({ 'auth': ad, 'pool': { 'name': 'upgrade-test2' } })))
def test_vrf1(self):
""" Verify empty VRF looks good
"""
expected = [
{'description': None,
'free_addresses_v4': '0',
'free_addresses_v6': '0',
'name': 'foo',
'num_prefixes_v4': '0',
'num_prefixes_v6': '0',
'rt': '123:123',
'total_addresses_v4': '0',
'total_addresses_v6': '0',
'used_addresses_v4': '0',
'used_addresses_v6': '0',
'tags': [],
'avps': {}
}]
self.assertEqual(expected, self._mangle_vrf_result(s.list_vrf({ 'auth':
ad, 'vrf': { 'name': 'foo' } })))
def test_vrf2(self):
""" Verify default VRF looks good with prefixes
"""
expected = [
{
'description': 'The default VRF, typically the Internet.',
'free_addresses_v4': '57344',
'free_addresses_v6': '2417833192485184639860736',
'name': 'default',
'num_prefixes_v4': '8',
'num_prefixes_v6': '3',
'rt': None,
'total_addresses_v4': '65536',
'total_addresses_v6': '2417851639229258349412352',
'used_addresses_v4': '8192',
'used_addresses_v6': '18446744073709551616',
'tags': [],
'avps': {}
}]
self.assertEqual(expected, self._mangle_vrf_result(s.list_vrf({ 'auth':
ad, 'vrf': { 'name': 'default' } })))
if __name__ == '__main__':
# set up logging
log = logging.getLogger()
logging.basicConfig()
log.setLevel(logging.INFO)
if sys.version_info >= (2,7):
unittest.main(verbosity=2)
else:
unittest.main()
|
|
import ConfigParser
import logging
import subprocess
import sys
import uuid
from twisted.internet import defer
from twisted.names import srvconnect
from twisted.python import log as txlog
from twisted.trial import unittest
from twisted.words.protocols.jabber import client
from twisted.words.protocols.jabber import error
from twisted.words.protocols.jabber import jid
from twisted.words.protocols.jabber import xmlstream
from twisted.words.xish import domish
class Response(object):
def __init__(self):
self.id = None
self.code = None
self.type = None
self.output = None
self.error = None
class Execute(object):
def __init__(self, command, stdin=''):
self.code = '-1'
self.error = ''
self.output = ''
reference = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
close_fds=True
)
self.stdout, self.stderr = reference.communicate(input=stdin)
self.return_code = str(reference.returncode)
self.parse()
def parse(self):
self.code = self.parse_code(self.stdout, self.code)
self.code = self.parse_code(self.stderr, self.code)
self.output = self.parse_text(self.stdout)
self.error = self.parse_text(self.error)
def parse_code(self, text, default):
if int(default) < 0 and ' (' in text and '):' in text:
return text.split(' (', 1)[1].split('):', 1)[0]
else:
return default
def parse_text(self, text, default=''):
if '):' in text:
return text.split('): ', 1)[1]
else:
return default
class log(object):
@staticmethod
def debug(text):
txlog.msg(text, logLevel=logging.DEBUG)
@staticmethod
def info(text):
txlog.msg(text, logLevel=logging.INFO)
@staticmethod
def warning(text):
txlog.msg(text, logLevel=logging.WARNING)
@staticmethod
def error(text):
txlog.msg(text, logLevel=logging.ERROR)
@staticmethod
def critical(text):
log.msg(text, logLevel=logging.CRITICAL)
class Base(object):
def setup_basic(self):
self.timeout = 60
self.config = ConfigParser.RawConfigParser()
self.config.read('helper.conf')
if self.config.getboolean('general', 'logging'):
txlog.startLogging(sys.stdout)
class BaseXMPP(Base):
def setUp(self):
defer_connected = defer.Deferred()
self.defer_disconnected = defer.Deferred()
self.client_connection = self.setup_client(
defer_connected,
self.defer_disconnected,
)
return defer.gatherResults([
defer_connected,
])
def tearDown(self):
self.client_connection.disconnect()
return defer.gatherResults([
self.defer_disconnected,
])
def setup_client(self, d1, d2):
from twisted.internet import reactor
factory = client.XMPPClientFactory(
self.jid,
self.password,
)
factory.addBootstrap(
xmlstream.STREAM_AUTHD_EVENT,
self.client_authenticated,
)
factory.addBootstrap(
xmlstream.INIT_FAILED_EVENT,
self.client_init_failed,
)
self.defer_authenticated = d1
self.defer_closed = d2
factory.clientConnectionLost = self.client_closed
self.factory = factory
return reactor.connectTCP('127.0.0.1', 5222, factory)
def raw_data_in(self, buf):
log.debug('CLIENT RECV: %s' % unicode(buf, 'utf-8').encode('ascii', 'replace'))
def raw_data_out(self, buf):
log.debug('CLIENT SEND: %s' % unicode(buf, 'utf-8').encode('ascii', 'replace'))
def client_authenticated(self, xs):
self.xmlStream = xs
self.xmlStream.rawDataInFn = self.raw_data_in
self.xmlStream.rawDataOutFn = self.raw_data_out
xml = domish.Element(('jabber:client', 'stream:features'))
xml.addElement('bind', self.config.get('general', 'namespace'))
xs.send(xml)
self.defer_authenticated.callback(None)
def client_closed(self, connector, reason):
self.defer_closed.callback(None)
def client_init_failed(self, failure):
log.error('Client init failed: %s' % failure)
def create_service_iq(self, type=None, id=None, user=None, group=None,
timeout=None, input=None, service=None):
iq = xmlstream.IQ(self.xmlStream)
if service is not None:
service = iq.addElement((self.config.get('general', 'namespace'),
'service'))
if type is not None:
service.attributes['type'] = type
if id is not None:
service.attributes['id'] = id or uuid.uuid4().get_hex()
if user is not None:
service.attributes['user'] = user
if group is not None:
service.attributes['group'] = group
if timeout is not None:
service.attributes['timeout'] = unicode(timeout)
if input and not input.endswith('\n'):
input = input + '\n'
if input is not None:
service.addElement('input', content=input)
return iq
def create_service(self, type='', input='', handle_success=None,
handle_error=None, destination=None, user=None,
group=None, timeout=None, id='', service=True, iq=None):
def default_success_func(xml):
pass
if handle_success is None:
handle_success = default_success_func
if destination is None:
destination = self.config.get('general', 'destination')
if iq is None:
iq = self.create_service_iq(
service=service,
type=type,
id=id,
user=user,
group=group,
timeout=timeout,
input=input,
)
# send iq
d = iq.send(destination)
d.addCallback(handle_success)
if handle_error is not None:
d.addErrback(handle_error)
return d
def parse_service(self, xml):
response = Response()
for e1 in xml.elements():
if e1.name == 'service':
response.code = e1.attributes.get('code')
response.id = e1.attributes.get('id')
response.type = e1.attributes.get('type')
for e2 in e1.elements():
if e2.name == 'output':
response.output = unicode(e2).strip()
elif e2.name == 'error':
response.error = unicode(e2).strip()
return response
@property
def handle_service_unavailable_success(self):
def handle(xml):
raise Exception('Should have got feature-not-implemented')
return handle
@property
def handle_service_unavailable_error(self):
def handle(failure):
self.assertTrue(failure.check(error.StanzaError))
self.assertTrue('feature-not-implemented' in failure.getErrorMessage())
return handle
|
|
# Author: Nikolay Mayorov <[email protected]>
# License: 3-clause BSD
from __future__ import division
import numpy as np
from scipy.sparse import issparse
from scipy.special import digamma
from ..externals.six import moves
from ..metrics.cluster.supervised import mutual_info_score
from ..neighbors import NearestNeighbors
from ..preprocessing import scale
from ..utils import check_random_state
from ..utils.validation import check_X_y
from ..utils.multiclass import check_classification_targets
def _compute_mi_cc(x, y, n_neighbors):
"""Compute mutual information between two continuous variables.
Parameters
----------
x, y : ndarray, shape (n_samples,)
Samples of two continuous random variables, must have an identical
shape.
n_neighbors : int
Number of nearest neighbors to search for each point, see [1]_.
Returns
-------
mi : float
Estimated mutual information. If it turned out to be negative it is
replace by 0.
Notes
-----
True mutual information can't be negative. If its estimate by a numerical
method is negative, it means (providing the method is adequate) that the
mutual information is close to 0 and replacing it by 0 is a reasonable
strategy.
References
----------
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
"""
n_samples = x.size
x = x.reshape((-1, 1))
y = y.reshape((-1, 1))
xy = np.hstack((x, y))
# Here we rely on NearestNeighbors to select the fastest algorithm.
nn = NearestNeighbors(metric='chebyshev', n_neighbors=n_neighbors)
nn.fit(xy)
radius = nn.kneighbors()[0]
radius = np.nextafter(radius[:, -1], 0)
# Algorithm is selected explicitly to allow passing an array as radius
# later (not all algorithms support this).
nn.set_params(algorithm='kd_tree')
nn.fit(x)
ind = nn.radius_neighbors(radius=radius, return_distance=False)
nx = np.array([i.size for i in ind])
nn.fit(y)
ind = nn.radius_neighbors(radius=radius, return_distance=False)
ny = np.array([i.size for i in ind])
mi = (digamma(n_samples) + digamma(n_neighbors) -
np.mean(digamma(nx + 1)) - np.mean(digamma(ny + 1)))
return max(0, mi)
def _compute_mi_cd(c, d, n_neighbors):
"""Compute mutual information between continuous and discrete variables.
Parameters
----------
c : ndarray, shape (n_samples,)
Samples of a continuous random variable.
d : ndarray, shape (n_samples,)
Samples of a discrete random variable.
n_neighbors : int
Number of nearest neighbors to search for each point, see [1]_.
Returns
-------
mi : float
Estimated mutual information. If it turned out to be negative it is
replace by 0.
Notes
-----
True mutual information can't be negative. If its estimate by a numerical
method is negative, it means (providing the method is adequate) that the
mutual information is close to 0 and replacing it by 0 is a reasonable
strategy.
References
----------
.. [1] B. C. Ross "Mutual Information between Discrete and Continuous
Data Sets". PLoS ONE 9(2), 2014.
"""
n_samples = c.shape[0]
c = c.reshape((-1, 1))
radius = np.empty(n_samples)
label_counts = np.empty(n_samples)
k_all = np.empty(n_samples)
nn = NearestNeighbors()
for label in np.unique(d):
mask = d == label
count = np.sum(mask)
if count > 1:
k = min(n_neighbors, count - 1)
nn.set_params(n_neighbors=k)
nn.fit(c[mask])
r = nn.kneighbors()[0]
radius[mask] = np.nextafter(r[:, -1], 0)
k_all[mask] = k
label_counts[mask] = count
# Ignore points with unique labels.
mask = label_counts > 1
n_samples = np.sum(mask)
label_counts = label_counts[mask]
k_all = k_all[mask]
c = c[mask]
radius = radius[mask]
nn.set_params(algorithm='kd_tree')
nn.fit(c)
ind = nn.radius_neighbors(radius=radius, return_distance=False)
m_all = np.array([i.size for i in ind])
mi = (digamma(n_samples) + np.mean(digamma(k_all)) -
np.mean(digamma(label_counts)) -
np.mean(digamma(m_all + 1)))
return max(0, mi)
def _compute_mi(x, y, x_discrete, y_discrete, n_neighbors=3):
"""Compute mutual information between two variables.
This is a simple wrapper which selects a proper function to call based on
whether `x` and `y` are discrete or not.
"""
if x_discrete and y_discrete:
return mutual_info_score(x, y)
elif x_discrete and not y_discrete:
return _compute_mi_cd(y, x, n_neighbors)
elif not x_discrete and y_discrete:
return _compute_mi_cd(x, y, n_neighbors)
else:
return _compute_mi_cc(x, y, n_neighbors)
def _iterate_columns(X, columns=None):
"""Iterate over columns of a matrix.
Parameters
----------
X : ndarray or csc_matrix, shape (n_samples, n_features)
Matrix over which to iterate.
columns : iterable or None, default None
Indices of columns to iterate over. If None, iterate over all columns.
Yields
------
x : ndarray, shape (n_samples,)
Columns of `X` in dense format.
"""
if columns is None:
columns = range(X.shape[1])
if issparse(X):
for i in columns:
x = np.zeros(X.shape[0])
start_ptr, end_ptr = X.indptr[i], X.indptr[i + 1]
x[X.indices[start_ptr:end_ptr]] = X.data[start_ptr:end_ptr]
yield x
else:
for i in columns:
yield X[:, i]
def _estimate_mi(X, y, discrete_features='auto', discrete_target=False,
n_neighbors=3, copy=True, random_state=None):
"""Estimate mutual information between the features and the target.
Parameters
----------
X : array_like or sparse matrix, shape (n_samples, n_features)
Feature matrix.
y : array_like, shape (n_samples,)
Target vector.
discrete_features : {'auto', bool, array_like}, default 'auto'
If bool, then determines whether to consider all features discrete
or continuous. If array, then it should be either a boolean mask
with shape (n_features,) or array with indices of discrete features.
If 'auto', it is assigned to False for dense `X` and to True for
sparse `X`.
discrete_target : bool, default False
Whether to consider `y` as a discrete variable.
n_neighbors : int, default 3
Number of neighbors to use for MI estimation for continuous variables,
see [1]_ and [2]_. Higher values reduce variance of the estimation, but
could introduce a bias.
copy : bool, default True
Whether to make a copy of the given data. If set to False, the initial
data will be overwritten.
random_state : int, RandomState instance or None, optional, default None
The seed of the pseudo random number generator for adding small noise
to continuous variables in order to remove repeated values. If int,
random_state is the seed used by the random number generator; If
RandomState instance, random_state is the random number generator; If
None, the random number generator is the RandomState instance used by
`np.random`.
Returns
-------
mi : ndarray, shape (n_features,)
Estimated mutual information between each feature and the target.
A negative value will be replaced by 0.
References
----------
.. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
.. [2] B. C. Ross "Mutual Information between Discrete and Continuous
Data Sets". PLoS ONE 9(2), 2014.
"""
X, y = check_X_y(X, y, accept_sparse='csc', y_numeric=not discrete_target)
n_samples, n_features = X.shape
if discrete_features == 'auto':
discrete_features = issparse(X)
if isinstance(discrete_features, bool):
discrete_mask = np.empty(n_features, dtype=bool)
discrete_mask.fill(discrete_features)
else:
discrete_features = np.asarray(discrete_features)
if discrete_features.dtype != 'bool':
discrete_mask = np.zeros(n_features, dtype=bool)
discrete_mask[discrete_features] = True
else:
discrete_mask = discrete_features
continuous_mask = ~discrete_mask
if np.any(continuous_mask) and issparse(X):
raise ValueError("Sparse matrix `X` can't have continuous features.")
rng = check_random_state(random_state)
if np.any(continuous_mask):
if copy:
X = X.copy()
if not discrete_target:
X[:, continuous_mask] = scale(X[:, continuous_mask],
with_mean=False, copy=False)
# Add small noise to continuous features as advised in Kraskov et. al.
X = X.astype(float)
means = np.maximum(1, np.mean(np.abs(X[:, continuous_mask]), axis=0))
X[:, continuous_mask] += 1e-10 * means * rng.randn(
n_samples, np.sum(continuous_mask))
if not discrete_target:
y = scale(y, with_mean=False)
y += 1e-10 * np.maximum(1, np.mean(np.abs(y))) * rng.randn(n_samples)
mi = [_compute_mi(x, y, discrete_feature, discrete_target, n_neighbors) for
x, discrete_feature in moves.zip(_iterate_columns(X), discrete_mask)]
return np.array(mi)
def mutual_info_regression(X, y, discrete_features='auto', n_neighbors=3,
copy=True, random_state=None):
"""Estimate mutual information for a continuous target variable.
Mutual information (MI) [1]_ between two random variables is a non-negative
value, which measures the dependency between the variables. It is equal
to zero if and only if two random variables are independent, and higher
values mean higher dependency.
The function relies on nonparametric methods based on entropy estimation
from k-nearest neighbors distances as described in [2]_ and [3]_. Both
methods are based on the idea originally proposed in [4]_.
It can be used for univariate features selection, read more in the
:ref:`User Guide <univariate_feature_selection>`.
Parameters
----------
X : array_like or sparse matrix, shape (n_samples, n_features)
Feature matrix.
y : array_like, shape (n_samples,)
Target vector.
discrete_features : {'auto', bool, array_like}, default 'auto'
If bool, then determines whether to consider all features discrete
or continuous. If array, then it should be either a boolean mask
with shape (n_features,) or array with indices of discrete features.
If 'auto', it is assigned to False for dense `X` and to True for
sparse `X`.
n_neighbors : int, default 3
Number of neighbors to use for MI estimation for continuous variables,
see [2]_ and [3]_. Higher values reduce variance of the estimation, but
could introduce a bias.
copy : bool, default True
Whether to make a copy of the given data. If set to False, the initial
data will be overwritten.
random_state : int, RandomState instance or None, optional, default None
The seed of the pseudo random number generator for adding small noise
to continuous variables in order to remove repeated values.
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
Returns
-------
mi : ndarray, shape (n_features,)
Estimated mutual information between each feature and the target.
Notes
-----
1. The term "discrete features" is used instead of naming them
"categorical", because it describes the essence more accurately.
For example, pixel intensities of an image are discrete features
(but hardly categorical) and you will get better results if mark them
as such. Also note, that treating a continuous variable as discrete and
vice versa will usually give incorrect results, so be attentive about that.
2. True mutual information can't be negative. If its estimate turns out
to be negative, it is replaced by zero.
References
----------
.. [1] `Mutual Information <https://en.wikipedia.org/wiki/Mutual_information>`_
on Wikipedia.
.. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
.. [3] B. C. Ross "Mutual Information between Discrete and Continuous
Data Sets". PLoS ONE 9(2), 2014.
.. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
of a Random Vector", Probl. Peredachi Inf., 23:2 (1987), 9-16
"""
return _estimate_mi(X, y, discrete_features, False, n_neighbors,
copy, random_state)
def mutual_info_classif(X, y, discrete_features='auto', n_neighbors=3,
copy=True, random_state=None):
"""Estimate mutual information for a discrete target variable.
Mutual information (MI) [1]_ between two random variables is a non-negative
value, which measures the dependency between the variables. It is equal
to zero if and only if two random variables are independent, and higher
values mean higher dependency.
The function relies on nonparametric methods based on entropy estimation
from k-nearest neighbors distances as described in [2]_ and [3]_. Both
methods are based on the idea originally proposed in [4]_.
It can be used for univariate features selection, read more in the
:ref:`User Guide <univariate_feature_selection>`.
Parameters
----------
X : array_like or sparse matrix, shape (n_samples, n_features)
Feature matrix.
y : array_like, shape (n_samples,)
Target vector.
discrete_features : {'auto', bool, array_like}, default 'auto'
If bool, then determines whether to consider all features discrete
or continuous. If array, then it should be either a boolean mask
with shape (n_features,) or array with indices of discrete features.
If 'auto', it is assigned to False for dense `X` and to True for
sparse `X`.
n_neighbors : int, default 3
Number of neighbors to use for MI estimation for continuous variables,
see [2]_ and [3]_. Higher values reduce variance of the estimation, but
could introduce a bias.
copy : bool, default True
Whether to make a copy of the given data. If set to False, the initial
data will be overwritten.
random_state : int, RandomState instance or None, optional, default None
The seed of the pseudo random number generator for adding small noise
to continuous variables in order to remove repeated values. If int,
random_state is the seed used by the random number generator; If
RandomState instance, random_state is the random number generator; If
None, the random number generator is the RandomState instance used by
`np.random`.
Returns
-------
mi : ndarray, shape (n_features,)
Estimated mutual information between each feature and the target.
Notes
-----
1. The term "discrete features" is used instead of naming them
"categorical", because it describes the essence more accurately.
For example, pixel intensities of an image are discrete features
(but hardly categorical) and you will get better results if mark them
as such. Also note, that treating a continuous variable as discrete and
vice versa will usually give incorrect results, so be attentive about that.
2. True mutual information can't be negative. If its estimate turns out
to be negative, it is replaced by zero.
References
----------
.. [1] `Mutual Information <https://en.wikipedia.org/wiki/Mutual_information>`_
on Wikipedia.
.. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
information". Phys. Rev. E 69, 2004.
.. [3] B. C. Ross "Mutual Information between Discrete and Continuous
Data Sets". PLoS ONE 9(2), 2014.
.. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16
"""
check_classification_targets(y)
return _estimate_mi(X, y, discrete_features, True, n_neighbors,
copy, random_state)
|
|
#!/usr/bin/python3
"""
arith_parse.py: Parse shell-like and C-like arithmetic.
"""
import sys
import tdop
from tdop import Node, CompositeNode
#
# Null Denotation -- token that takes nothing on the left
#
def NullConstant(p, token, bp):
return Node(token)
def NullParen(p, token, bp):
""" Arithmetic grouping """
r = p.ParseUntil(bp)
p.Eat(')')
return r
def NullPrefixOp(p, token, bp):
"""Prefix operator.
Low precedence: return, raise, etc.
return x+y is return (x+y), not (return x) + y
High precedence: logical negation, bitwise complement, etc.
!x && y is (!x) && y, not !(x && y)
"""
r = p.ParseUntil(bp)
return CompositeNode(token, [r])
def NullIncDec(p, token, bp):
""" ++x or ++x[1] """
right = p.ParseUntil(bp)
if right.token.type not in ('name', 'get'):
raise tdop.ParseError("Can't assign to %r (%s)" % (right, right.token))
return CompositeNode(token, [right])
#
# Left Denotation -- token that takes an expression on the left
#
def LeftIncDec(p, token, left, rbp):
""" For i++ and i--
"""
if left.token.type not in ('name', 'get'):
raise tdop.ParseError("Can't assign to %r (%s)" % (left, left.token))
token.type = 'post' + token.type
return CompositeNode(token, [left])
def LeftIndex(p, token, left, unused_bp):
""" index f[x+1] """
# f[x] or f[x][y]
if left.token.type not in ('name', 'get'):
raise tdop.ParseError("%s can't be indexed" % left)
index = p.ParseUntil(0)
p.Eat("]")
token.type = 'get'
return CompositeNode(token, [left, index])
def LeftTernary(p, token, left, bp):
""" e.g. a > 1 ? x : y """
# 0 binding power since any operators allowed until ':'. See:
#
# http://en.cppreference.com/w/c/language/operator_precedence#cite_note-2
#
# "The expression in the middle of the conditional operator (between ? and
# :) is parsed as if parenthesized: its precedence relative to ?: is
# ignored."
true_expr = p.ParseUntil(0)
p.Eat(':')
false_expr = p.ParseUntil(bp)
children = [left, true_expr, false_expr]
return CompositeNode(token, children)
def LeftBinaryOp(p, token, left, rbp):
""" Normal binary operator like 1+2 or 2*3, etc. """
return CompositeNode(token, [left, p.ParseUntil(rbp)])
def LeftAssign(p, token, left, rbp):
""" Normal binary operator like 1+2 or 2*3, etc. """
# x += 1, or a[i] += 1
if left.token.type not in ('name', 'get'):
raise tdop.ParseError("Can't assign to %r (%s)" % (left, left.token))
return CompositeNode(token, [left, p.ParseUntil(rbp)])
def LeftComma(p, token, left, rbp):
""" foo, bar, baz
Could be sequencing operator, or tuple without parens
"""
r = p.ParseUntil(rbp)
if left.token.type == ',': # Keep adding more children
left.children.append(r)
return left
children = [left, r]
return CompositeNode(token, children)
# For overloading of , inside function calls
COMMA_PREC = 1
def LeftFuncCall(p, token, left, unused_bp):
""" Function call f(a, b). """
children = [left]
# f(x) or f[i](x)
if left.token.type not in ('name', 'get'):
raise tdop.ParseError("%s can't be called" % left)
while not p.AtToken(')'):
# We don't want to grab the comma, e.g. it is NOT a sequence operator. So
# set the precedence to 5.
children.append(p.ParseUntil(COMMA_PREC))
if p.AtToken(','):
p.Next()
p.Eat(")")
token.type = 'call'
return CompositeNode(token, children)
def MakeShellParserSpec():
"""
Create a parser.
Compare the code below with this table of C operator precedence:
http://en.cppreference.com/w/c/language/operator_precedence
"""
spec = tdop.ParserSpec()
spec.Left(31, LeftIncDec, ['++', '--'])
spec.Left(31, LeftFuncCall, ['('])
spec.Left(31, LeftIndex, ['['])
# 29 -- binds to everything except function call, indexing, postfix ops
spec.Null(29, NullIncDec, ['++', '--'])
# Right associative: 2 ** 3 ** 2 == 2 ** (3 ** 2)
# Binds more strongly than negation.
spec.LeftRightAssoc(29, LeftBinaryOp, ['**'])
spec.Null(27, NullPrefixOp, ['+', '!', '~', '-'])
spec.Left(25, LeftBinaryOp, ['*', '/', '%'])
spec.Left(23, LeftBinaryOp, ['+', '-'])
spec.Left(21, LeftBinaryOp, ['<<', '>>'])
spec.Left(19, LeftBinaryOp, ['<', '>', '<=', '>='])
spec.Left(17, LeftBinaryOp, ['!=', '=='])
spec.Left(15, LeftBinaryOp, ['&'])
spec.Left(13, LeftBinaryOp, ['^'])
spec.Left(11, LeftBinaryOp, ['|'])
spec.Left(9, LeftBinaryOp, ['&&'])
spec.Left(7, LeftBinaryOp, ['||'])
spec.LeftRightAssoc(5, LeftTernary, ['?'])
# Right associative: a = b = 2 is a = (b = 2)
spec.LeftRightAssoc(3, LeftAssign, [
'=',
'+=', '-=', '*=', '/=', '%=',
'<<=', '>>=', '&=', '^=', '|='])
spec.Left(COMMA_PREC, LeftComma, [','])
# 0 precedence -- doesn't bind until )
spec.Null(0, NullParen, ['(']) # for grouping
# -1 precedence -- never used
spec.Null(-1, NullConstant, ['name', 'number'])
spec.Null(-1, tdop.NullError, [')', ']', ':', 'eof'])
return spec
def MakeParser(s):
"""Used by tests."""
spec = MakeShellParserSpec()
lexer = tdop.Tokenize(s)
p = tdop.Parser(spec, lexer)
return p
def ParseShell(s, expected=None):
"""Used by tests."""
p = MakeParser(s)
tree = p.Parse()
sexpr = repr(tree)
if expected is not None:
assert sexpr == expected, '%r != %r' % (sexpr, expected)
print('%-40s %s' % (s, sexpr))
return tree
def main(argv):
try:
s = argv[1]
except IndexError:
print('Usage: ./arith_parse.py EXPRESSION')
else:
try:
tree = ParseShell(s)
except tdop.ParseError as e:
print('Error parsing %r: %s' % (s, e), file=sys.stderr)
if __name__ == '__main__':
main(sys.argv)
|
|
# Copyright 2012 IBM Corp.
# All Rights Reserved.
#
# 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.
import datetime
from iso8601 import iso8601
from oslo_utils import timeutils
import webob.exc
from jacket.api.storage.storage.contrib import services
from jacket.api.storage.storage import extensions
from jacket import context
from jacket import db
from jacket.storage import exception
from jacket.storage import policy
from jacket.storage import test
from jacket.tests.storage.unit.api import fakes
fake_services_list = [
{'binary': 'storage-scheduler',
'host': 'host1',
'availability_zone': 'storage',
'id': 1,
'disabled': True,
'updated_at': datetime.datetime(2012, 10, 29, 13, 42, 2),
'created_at': datetime.datetime(2012, 9, 18, 2, 46, 27),
'disabled_reason': 'test1',
'modified_at': ''},
{'binary': 'storage-volume',
'host': 'host1',
'availability_zone': 'storage',
'id': 2,
'disabled': True,
'updated_at': datetime.datetime(2012, 10, 29, 13, 42, 5),
'created_at': datetime.datetime(2012, 9, 18, 2, 46, 27),
'disabled_reason': 'test2',
'modified_at': ''},
{'binary': 'storage-scheduler',
'host': 'host2',
'availability_zone': 'storage',
'id': 3,
'disabled': False,
'updated_at': datetime.datetime(2012, 9, 19, 6, 55, 34),
'created_at': datetime.datetime(2012, 9, 18, 2, 46, 28),
'disabled_reason': '',
'modified_at': ''},
{'binary': 'storage-volume',
'host': 'host2',
'availability_zone': 'storage',
'id': 4,
'disabled': True,
'updated_at': datetime.datetime(2012, 9, 18, 8, 3, 38),
'created_at': datetime.datetime(2012, 9, 18, 2, 46, 28),
'disabled_reason': 'test4',
'modified_at': ''},
{'binary': 'storage-volume',
'host': 'host2',
'availability_zone': 'storage',
'id': 5,
'disabled': True,
'updated_at': datetime.datetime(2012, 9, 18, 8, 3, 38),
'created_at': datetime.datetime(2012, 9, 18, 2, 46, 28),
'disabled_reason': 'test5',
'modified_at': datetime.datetime(2012, 10, 29, 13, 42, 5)},
{'binary': 'storage-volume',
'host': 'host2',
'availability_zone': 'storage',
'id': 6,
'disabled': False,
'updated_at': datetime.datetime(2012, 9, 18, 8, 3, 38),
'created_at': datetime.datetime(2012, 9, 18, 2, 46, 28),
'disabled_reason': '',
'modified_at': datetime.datetime(2012, 9, 18, 8, 1, 38)},
{'binary': 'storage-scheduler',
'host': 'host2',
'availability_zone': 'storage',
'id': 6,
'disabled': False,
'updated_at': None,
'created_at': datetime.datetime(2012, 9, 18, 2, 46, 28),
'disabled_reason': '',
'modified_at': None},
]
class FakeRequest(object):
environ = {"storage.context": context.get_admin_context()}
GET = {}
# NOTE(uni): deprecating service request key, binary takes precedence
# Still keeping service key here for API compatibility sake.
class FakeRequestWithService(object):
environ = {"storage.context": context.get_admin_context()}
GET = {"service": "storage-volume"}
class FakeRequestWithBinary(object):
environ = {"storage.context": context.get_admin_context()}
GET = {"binary": "storage-volume"}
class FakeRequestWithHost(object):
environ = {"storage.context": context.get_admin_context()}
GET = {"host": "host1"}
# NOTE(uni): deprecating service request key, binary takes precedence
# Still keeping service key here for API compatibility sake.
class FakeRequestWithHostService(object):
environ = {"storage.context": context.get_admin_context()}
GET = {"host": "host1", "service": "storage-volume"}
class FakeRequestWithHostBinary(object):
environ = {"storage.context": context.get_admin_context()}
GET = {"host": "host1", "binary": "storage-volume"}
def fake_service_get_all(context, filters=None):
filters = filters or {}
host = filters.get('host')
binary = filters.get('binary')
return [s for s in fake_services_list
if (not host or s['host'] == host or
s['host'].startswith(host + '@'))
and (not binary or s['binary'] == binary)]
def fake_service_get_by_host_binary(context, host, binary):
for service in fake_services_list:
if service['host'] == host and service['binary'] == binary:
return service
return None
def fake_service_get_by_id(value):
for service in fake_services_list:
if service['id'] == value:
return service
return None
def fake_service_update(context, service_id, values):
service = fake_service_get_by_id(service_id)
if service is None:
raise exception.ServiceNotFound(service_id=service_id)
else:
{'host': 'host1', 'service': 'storage-volume',
'disabled': values['disabled']}
def fake_policy_enforce(context, action, target):
pass
def fake_utcnow(with_timezone=False):
tzinfo = iso8601.Utc() if with_timezone else None
return datetime.datetime(2012, 10, 29, 13, 42, 11, tzinfo=tzinfo)
class ServicesTest(test.TestCase):
def setUp(self):
super(ServicesTest, self).setUp()
self.stubs.Set(storage, "service_get_all", fake_service_get_all)
self.stubs.Set(timeutils, "utcnow", fake_utcnow)
self.stubs.Set(storage, "service_get_by_args",
fake_service_get_by_host_binary)
self.stubs.Set(storage, "service_update", fake_service_update)
self.stubs.Set(policy, "enforce", fake_policy_enforce)
self.context = context.get_admin_context()
self.ext_mgr = extensions.ExtensionManager()
self.ext_mgr.extensions = {}
self.controller = services.ServiceController(self.ext_mgr)
def test_services_list(self):
req = FakeRequest()
res_dict = self.controller.index(req)
response = {'services': [{'binary': 'storage-scheduler',
'host': 'host1', 'zone': 'storage',
'status': 'disabled', 'state': 'up',
'updated_at': datetime.datetime(
2012, 10, 29, 13, 42, 2)},
{'binary': 'storage-volume',
'host': 'host1', 'zone': 'storage',
'status': 'disabled', 'state': 'up',
'updated_at': datetime.datetime(
2012, 10, 29, 13, 42, 5)},
{'binary': 'storage-scheduler',
'host': 'host2',
'zone': 'storage',
'status': 'enabled', 'state': 'down',
'updated_at': datetime.datetime(
2012, 9, 19, 6, 55, 34)},
{'binary': 'storage-volume',
'host': 'host2',
'zone': 'storage',
'status': 'disabled', 'state': 'down',
'updated_at': datetime.datetime(
2012, 9, 18, 8, 3, 38)},
{'binary': 'storage-volume',
'host': 'host2',
'zone': 'storage',
'status': 'disabled', 'state': 'down',
'updated_at': datetime.datetime(
2012, 10, 29, 13, 42, 5)},
{'binary': 'storage-volume',
'host': 'host2',
'zone': 'storage',
'status': 'enabled', 'state': 'down',
'updated_at': datetime.datetime(
2012, 9, 18, 8, 3, 38)},
{'binary': 'storage-scheduler',
'host': 'host2',
'zone': 'storage',
'status': 'enabled', 'state': 'down',
'updated_at': None},
]}
self.assertEqual(response, res_dict)
def test_services_detail(self):
self.ext_mgr.extensions['os-extended-services'] = True
self.controller = services.ServiceController(self.ext_mgr)
req = FakeRequest()
res_dict = self.controller.index(req)
response = {'services': [{'binary': 'storage-scheduler',
'host': 'host1', 'zone': 'storage',
'status': 'disabled', 'state': 'up',
'updated_at': datetime.datetime(
2012, 10, 29, 13, 42, 2),
'disabled_reason': 'test1'},
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'frozen': False,
'host': 'host1', 'zone': 'storage',
'status': 'disabled', 'state': 'up',
'updated_at': datetime.datetime(
2012, 10, 29, 13, 42, 5),
'disabled_reason': 'test2'},
{'binary': 'storage-scheduler',
'host': 'host2',
'zone': 'storage',
'status': 'enabled', 'state': 'down',
'updated_at': datetime.datetime(
2012, 9, 19, 6, 55, 34),
'disabled_reason': ''},
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'frozen': False,
'host': 'host2',
'zone': 'storage',
'status': 'disabled', 'state': 'down',
'updated_at': datetime.datetime(
2012, 9, 18, 8, 3, 38),
'disabled_reason': 'test4'},
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'frozen': False,
'host': 'host2',
'zone': 'storage',
'status': 'disabled', 'state': 'down',
'updated_at': datetime.datetime(
2012, 10, 29, 13, 42, 5),
'disabled_reason': 'test5'},
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'frozen': False,
'host': 'host2',
'zone': 'storage',
'status': 'enabled', 'state': 'down',
'updated_at': datetime.datetime(
2012, 9, 18, 8, 3, 38),
'disabled_reason': ''},
{'binary': 'storage-scheduler',
'host': 'host2',
'zone': 'storage',
'status': 'enabled', 'state': 'down',
'updated_at': None,
'disabled_reason': ''},
]}
self.assertEqual(response, res_dict)
def test_services_list_with_host(self):
req = FakeRequestWithHost()
res_dict = self.controller.index(req)
response = {'services': [
{'binary': 'storage-scheduler',
'host': 'host1',
'zone': 'storage',
'status': 'disabled', 'state': 'up',
'updated_at': datetime.datetime(2012, 10,
29, 13, 42, 2)},
{'binary': 'storage-volume',
'host': 'host1',
'zone': 'storage',
'status': 'disabled', 'state': 'up',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5)}]}
self.assertEqual(response, res_dict)
def test_services_detail_with_host(self):
self.ext_mgr.extensions['os-extended-services'] = True
self.controller = services.ServiceController(self.ext_mgr)
req = FakeRequestWithHost()
res_dict = self.controller.index(req)
response = {'services': [
{'binary': 'storage-scheduler',
'host': 'host1',
'zone': 'storage',
'status': 'disabled', 'state': 'up',
'updated_at': datetime.datetime(2012, 10,
29, 13, 42, 2),
'disabled_reason': 'test1'},
{'binary': 'storage-volume',
'frozen': False,
'replication_status': None,
'active_backend_id': None,
'host': 'host1',
'zone': 'storage',
'status': 'disabled', 'state': 'up',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5),
'disabled_reason': 'test2'}]}
self.assertEqual(response, res_dict)
def test_services_list_with_service(self):
req = FakeRequestWithService()
res_dict = self.controller.index(req)
response = {'services': [
{'binary': 'storage-volume',
'host': 'host1',
'zone': 'storage',
'status': 'disabled',
'state': 'up',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5)},
{'binary': 'storage-volume',
'host': 'host2',
'zone': 'storage',
'status': 'disabled',
'state': 'down',
'updated_at': datetime.datetime(2012, 9, 18,
8, 3, 38)},
{'binary': 'storage-volume',
'host': 'host2',
'zone': 'storage',
'status': 'disabled',
'state': 'down',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5)},
{'binary': 'storage-volume',
'host': 'host2',
'zone': 'storage',
'status': 'enabled',
'state': 'down',
'updated_at': datetime.datetime(2012, 9, 18,
8, 3, 38)}]}
self.assertEqual(response, res_dict)
def test_services_detail_with_service(self):
self.ext_mgr.extensions['os-extended-services'] = True
self.controller = services.ServiceController(self.ext_mgr)
req = FakeRequestWithService()
res_dict = self.controller.index(req)
response = {'services': [
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'frozen': False,
'host': 'host1',
'zone': 'storage',
'status': 'disabled',
'state': 'up',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5),
'disabled_reason': 'test2'},
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'frozen': False,
'host': 'host2',
'zone': 'storage',
'status': 'disabled',
'state': 'down',
'updated_at': datetime.datetime(2012, 9, 18,
8, 3, 38),
'disabled_reason': 'test4'},
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'frozen': False,
'host': 'host2',
'zone': 'storage',
'status': 'disabled',
'state': 'down',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5),
'disabled_reason': 'test5'},
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'frozen': False,
'host': 'host2',
'zone': 'storage',
'status': 'enabled',
'state': 'down',
'updated_at': datetime.datetime(2012, 9, 18,
8, 3, 38),
'disabled_reason': ''}]}
self.assertEqual(response, res_dict)
def test_services_list_with_binary(self):
req = FakeRequestWithBinary()
res_dict = self.controller.index(req)
response = {'services': [
{'binary': 'storage-volume',
'host': 'host1',
'zone': 'storage',
'status': 'disabled',
'state': 'up',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5)},
{'binary': 'storage-volume',
'host': 'host2',
'zone': 'storage',
'status': 'disabled',
'state': 'down',
'updated_at': datetime.datetime(2012, 9, 18,
8, 3, 38)},
{'binary': 'storage-volume',
'host': 'host2',
'zone': 'storage',
'status': 'disabled',
'state': 'down',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5)},
{'binary': 'storage-volume',
'host': 'host2',
'zone': 'storage',
'status': 'enabled',
'state': 'down',
'updated_at': datetime.datetime(2012, 9, 18,
8, 3, 38)}]}
self.assertEqual(response, res_dict)
def test_services_detail_with_binary(self):
self.ext_mgr.extensions['os-extended-services'] = True
self.controller = services.ServiceController(self.ext_mgr)
req = FakeRequestWithBinary()
res_dict = self.controller.index(req)
response = {'services': [
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'host': 'host1',
'zone': 'storage',
'status': 'disabled',
'state': 'up',
'frozen': False,
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5),
'disabled_reason': 'test2'},
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'host': 'host2',
'zone': 'storage',
'status': 'disabled',
'state': 'down',
'frozen': False,
'updated_at': datetime.datetime(2012, 9, 18,
8, 3, 38),
'disabled_reason': 'test4'},
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'host': 'host2',
'zone': 'storage',
'status': 'disabled',
'state': 'down',
'frozen': False,
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5),
'disabled_reason': 'test5'},
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'host': 'host2',
'zone': 'storage',
'status': 'enabled',
'state': 'down',
'frozen': False,
'updated_at': datetime.datetime(2012, 9, 18,
8, 3, 38),
'disabled_reason': ''}]}
self.assertEqual(response, res_dict)
def test_services_list_with_host_service(self):
req = FakeRequestWithHostService()
res_dict = self.controller.index(req)
response = {'services': [
{'binary': 'storage-volume',
'host': 'host1',
'zone': 'storage',
'status': 'disabled',
'state': 'up',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5)}]}
self.assertEqual(response, res_dict)
def test_services_detail_with_host_service(self):
self.ext_mgr.extensions['os-extended-services'] = True
self.controller = services.ServiceController(self.ext_mgr)
req = FakeRequestWithHostService()
res_dict = self.controller.index(req)
response = {'services': [
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'host': 'host1',
'zone': 'storage',
'status': 'disabled',
'state': 'up',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5),
'disabled_reason': 'test2',
'frozen': False}]}
self.assertEqual(response, res_dict)
def test_services_list_with_host_binary(self):
req = FakeRequestWithHostBinary()
res_dict = self.controller.index(req)
response = {'services': [
{'binary': 'storage-volume',
'host': 'host1',
'zone': 'storage',
'status': 'disabled',
'state': 'up',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5)}]}
self.assertEqual(response, res_dict)
def test_services_detail_with_host_binary(self):
self.ext_mgr.extensions['os-extended-services'] = True
self.controller = services.ServiceController(self.ext_mgr)
req = FakeRequestWithHostBinary()
res_dict = self.controller.index(req)
response = {'services': [
{'binary': 'storage-volume',
'replication_status': None,
'active_backend_id': None,
'frozen': False,
'host': 'host1',
'zone': 'storage',
'status': 'disabled',
'state': 'up',
'updated_at': datetime.datetime(2012, 10, 29,
13, 42, 5),
'disabled_reason': 'test2'}]}
self.assertEqual(response, res_dict)
def test_services_enable_with_service_key(self):
body = {'host': 'host1', 'service': 'storage-volume'}
req = fakes.HTTPRequest.blank('/v2/fake/os-services/enable')
res_dict = self.controller.update(req, "enable", body)
self.assertEqual('enabled', res_dict['status'])
def test_services_enable_with_binary_key(self):
body = {'host': 'host1', 'binary': 'storage-volume'}
req = fakes.HTTPRequest.blank('/v2/fake/os-services/enable')
res_dict = self.controller.update(req, "enable", body)
self.assertEqual('enabled', res_dict['status'])
def test_services_disable_with_service_key(self):
req = fakes.HTTPRequest.blank('/v2/fake/os-services/disable')
body = {'host': 'host1', 'service': 'storage-volume'}
res_dict = self.controller.update(req, "disable", body)
self.assertEqual('disabled', res_dict['status'])
def test_services_disable_with_binary_key(self):
req = fakes.HTTPRequest.blank('/v2/fake/os-services/disable')
body = {'host': 'host1', 'binary': 'storage-volume'}
res_dict = self.controller.update(req, "disable", body)
self.assertEqual('disabled', res_dict['status'])
def test_services_disable_log_reason(self):
self.ext_mgr.extensions['os-extended-services'] = True
self.controller = services.ServiceController(self.ext_mgr)
req = (
fakes.HTTPRequest.blank('v1/fake/os-services/disable-log-reason'))
body = {'host': 'host1',
'binary': 'storage-scheduler',
'disabled_reason': 'test-reason',
}
res_dict = self.controller.update(req, "disable-log-reason", body)
self.assertEqual('disabled', res_dict['status'])
self.assertEqual('test-reason', res_dict['disabled_reason'])
def test_services_disable_log_reason_none(self):
self.ext_mgr.extensions['os-extended-services'] = True
self.controller = services.ServiceController(self.ext_mgr)
req = (
fakes.HTTPRequest.blank('v1/fake/os-services/disable-log-reason'))
body = {'host': 'host1',
'binary': 'storage-scheduler',
'disabled_reason': None,
}
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller.update,
req, "disable-log-reason", body)
def test_invalid_reason_field(self):
reason = ' '
self.assertFalse(self.controller._is_valid_as_reason(reason))
reason = 'a' * 256
self.assertFalse(self.controller._is_valid_as_reason(reason))
reason = 'it\'s a valid reason.'
self.assertTrue(self.controller._is_valid_as_reason(reason))
reason = None
self.assertFalse(self.controller._is_valid_as_reason(reason))
|
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Extremely random forest graph builder. go/brain-tree."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numbers
import random
from google.protobuf import text_format
from tensorflow.contrib.decision_trees.proto import generic_tree_model_pb2 as _tree_proto
from tensorflow.contrib.framework.python.ops import variables as framework_variables
from tensorflow.contrib.tensor_forest.proto import tensor_forest_params_pb2 as _params_proto
from tensorflow.contrib.tensor_forest.python.ops import data_ops
from tensorflow.contrib.tensor_forest.python.ops import model_ops
from tensorflow.contrib.tensor_forest.python.ops import stats_ops
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables as tf_variables
from tensorflow.python.platform import tf_logging as logging
# Stores tuples of (leaf model type, stats model type)
CLASSIFICATION_LEAF_MODEL_TYPES = {
'all_dense': (_params_proto.MODEL_DENSE_CLASSIFICATION,
_params_proto.STATS_DENSE_GINI),
'all_sparse': (_params_proto.MODEL_SPARSE_CLASSIFICATION,
_params_proto.STATS_SPARSE_GINI),
'sparse_then_dense':
(_params_proto.MODEL_SPARSE_OR_DENSE_CLASSIFICATION,
_params_proto.STATS_SPARSE_THEN_DENSE_GINI),
}
REGRESSION_MODEL_TYPE = (
_params_proto.MODEL_REGRESSION,
_params_proto.STATS_LEAST_SQUARES_REGRESSION,
_params_proto.COLLECTION_BASIC)
FINISH_TYPES = {
'basic': _params_proto.SPLIT_FINISH_BASIC,
'hoeffding': _params_proto.SPLIT_FINISH_DOMINATE_HOEFFDING,
'bootstrap': _params_proto.SPLIT_FINISH_DOMINATE_BOOTSTRAP
}
PRUNING_TYPES = {
'none': _params_proto.SPLIT_PRUNE_NONE,
'half': _params_proto.SPLIT_PRUNE_HALF,
'quarter': _params_proto.SPLIT_PRUNE_QUARTER,
'10_percent': _params_proto.SPLIT_PRUNE_10_PERCENT,
'hoeffding': _params_proto.SPLIT_PRUNE_HOEFFDING,
}
SPLIT_TYPES = {
'less_or_equal': _tree_proto.InequalityTest.LESS_OR_EQUAL,
'less': _tree_proto.InequalityTest.LESS_THAN
}
def parse_number_or_string_to_proto(proto, param):
if isinstance(param, numbers.Number):
proto.constant_value = param
else: # assume it's a string
if param.isdigit():
proto.constant_value = int(param)
else:
text_format.Merge(param, proto)
def build_params_proto(params):
"""Build a TensorForestParams proto out of the V4ForestHParams object."""
proto = _params_proto.TensorForestParams()
proto.num_trees = params.num_trees
proto.max_nodes = params.max_nodes
proto.is_regression = params.regression
proto.num_outputs = params.num_classes
proto.num_features = params.num_features
proto.leaf_type = params.leaf_model_type
proto.stats_type = params.stats_model_type
proto.collection_type = _params_proto.COLLECTION_BASIC
proto.pruning_type.type = params.pruning_type
proto.finish_type.type = params.finish_type
proto.inequality_test_type = params.split_type
proto.drop_final_class = False
proto.collate_examples = params.collate_examples
proto.checkpoint_stats = params.checkpoint_stats
proto.use_running_stats_method = params.use_running_stats_method
proto.initialize_average_splits = params.initialize_average_splits
proto.inference_tree_paths = params.inference_tree_paths
parse_number_or_string_to_proto(proto.pruning_type.prune_every_samples,
params.prune_every_samples)
parse_number_or_string_to_proto(proto.finish_type.check_every_steps,
params.early_finish_check_every_samples)
parse_number_or_string_to_proto(proto.split_after_samples,
params.split_after_samples)
parse_number_or_string_to_proto(proto.num_splits_to_consider,
params.num_splits_to_consider)
proto.dominate_fraction.constant_value = params.dominate_fraction
if params.param_file:
with open(params.param_file) as f:
text_format.Merge(f.read(), proto)
return proto
# A convenience class for holding random forest hyperparameters.
#
# To just get some good default parameters, use:
# hparams = ForestHParams(num_classes=2, num_features=40).fill()
#
# Note that num_classes can not be inferred and so must always be specified.
# Also, either num_splits_to_consider or num_features should be set.
#
# To override specific values, pass them to the constructor:
# hparams = ForestHParams(num_classes=5, num_trees=10, num_features=5).fill()
#
# TODO(thomaswc): Inherit from tf.HParams when that is publicly available.
class ForestHParams(object):
"""A base class for holding hyperparameters and calculating good defaults."""
def __init__(
self,
num_trees=100,
max_nodes=10000,
bagging_fraction=1.0,
num_splits_to_consider=0,
feature_bagging_fraction=1.0,
max_fertile_nodes=0, # deprecated, unused.
split_after_samples=250,
valid_leaf_threshold=1,
dominate_method='bootstrap',
dominate_fraction=0.99,
model_name='all_dense',
split_finish_name='basic',
split_pruning_name='none',
prune_every_samples=0,
early_finish_check_every_samples=0,
collate_examples=False,
checkpoint_stats=False,
use_running_stats_method=False,
initialize_average_splits=False,
inference_tree_paths=False,
param_file=None,
split_name='less_or_equal',
**kwargs):
self.num_trees = num_trees
self.max_nodes = max_nodes
self.bagging_fraction = bagging_fraction
self.feature_bagging_fraction = feature_bagging_fraction
self.num_splits_to_consider = num_splits_to_consider
self.max_fertile_nodes = max_fertile_nodes
self.split_after_samples = split_after_samples
self.valid_leaf_threshold = valid_leaf_threshold
self.dominate_method = dominate_method
self.dominate_fraction = dominate_fraction
self.model_name = model_name
self.split_finish_name = split_finish_name
self.split_pruning_name = split_pruning_name
self.collate_examples = collate_examples
self.checkpoint_stats = checkpoint_stats
self.use_running_stats_method = use_running_stats_method
self.initialize_average_splits = initialize_average_splits
self.inference_tree_paths = inference_tree_paths
self.param_file = param_file
self.split_name = split_name
self.early_finish_check_every_samples = early_finish_check_every_samples
self.prune_every_samples = prune_every_samples
for name, value in kwargs.items():
setattr(self, name, value)
def values(self):
return self.__dict__
def fill(self):
"""Intelligently sets any non-specific parameters."""
# Fail fast if num_classes or num_features isn't set.
_ = getattr(self, 'num_classes')
_ = getattr(self, 'num_features')
self.bagged_num_features = int(self.feature_bagging_fraction *
self.num_features)
self.bagged_features = None
if self.feature_bagging_fraction < 1.0:
self.bagged_features = [random.sample(
range(self.num_features),
self.bagged_num_features) for _ in range(self.num_trees)]
self.regression = getattr(self, 'regression', False)
# Num_outputs is the actual number of outputs (a single prediction for
# classification, a N-dimenensional point for regression).
self.num_outputs = self.num_classes if self.regression else 1
# Add an extra column to classes for storing counts, which is needed for
# regression and avoids having to recompute sums for classification.
self.num_output_columns = self.num_classes + 1
# Our experiments have found that num_splits_to_consider = num_features
# gives good accuracy.
self.num_splits_to_consider = self.num_splits_to_consider or min(
max(10, math.floor(math.sqrt(self.num_features))), 1000)
# If base_random_seed is 0, the current time will be used to seed the
# random number generators for each tree. If non-zero, the i-th tree
# will be seeded with base_random_seed + i.
self.base_random_seed = getattr(self, 'base_random_seed', 0)
# How to store leaf models.
self.leaf_model_type = (
REGRESSION_MODEL_TYPE[0] if self.regression else
CLASSIFICATION_LEAF_MODEL_TYPES[self.model_name][0])
# How to store stats objects.
self.stats_model_type = (
REGRESSION_MODEL_TYPE[1] if self.regression else
CLASSIFICATION_LEAF_MODEL_TYPES[self.model_name][1])
self.finish_type = (
_params_proto.SPLIT_FINISH_BASIC if self.regression else
FINISH_TYPES[self.split_finish_name])
self.pruning_type = PRUNING_TYPES[self.split_pruning_name]
if self.pruning_type == _params_proto.SPLIT_PRUNE_NONE:
self.prune_every_samples = 0
else:
if (not self.prune_every_samples and
not (isinstance(numbers.Number) or
self.split_after_samples.isdigit())):
logging.error(
'Must specify prune_every_samples if using a depth-dependent '
'split_after_samples')
# Pruning half-way through split_after_samples seems like a decent
# default, making it easy to select the number being pruned with
# pruning_type while not paying the cost of pruning too often. Note that
# this only holds if not using a depth-dependent split_after_samples.
self.prune_every_samples = (self.prune_every_samples or
int(self.split_after_samples) / 2)
if self.finish_type == _params_proto.SPLIT_FINISH_BASIC:
self.early_finish_check_every_samples = 0
else:
if (not self.early_finish_check_every_samples and
not (isinstance(numbers.Number) or
self.split_after_samples.isdigit())):
logging.error(
'Must specify prune_every_samples if using a depth-dependent '
'split_after_samples')
# Checking for early finish every quarter through split_after_samples
# seems like a decent default. We don't want to incur the checking cost
# too often, but (at least for hoeffding) it's lower than the cost of
# pruning so we can do it a little more frequently.
self.early_finish_check_every_samples = (
self.early_finish_check_every_samples or
int(self.split_after_samples) / 4)
self.split_type = SPLIT_TYPES[self.split_name]
return self
def get_epoch_variable():
"""Returns the epoch variable, or [0] if not defined."""
# Grab epoch variable defined in
# //third_party/tensorflow/python/training/input.py::limit_epochs
for v in tf_variables.local_variables():
if 'limit_epochs/epoch' in v.op.name:
return array_ops.reshape(v, [1])
# TODO(thomaswc): Access epoch from the data feeder.
return [0]
# A simple container to hold the training variables for a single tree.
class TreeTrainingVariables(object):
"""Stores tf.Variables for training a single random tree.
Uses tf.get_variable to get tree-specific names so that this can be used
with a tf.learn-style implementation (one that trains a model, saves it,
then relies on restoring that model to evaluate).
"""
def __init__(self, params, tree_num, training):
if (not hasattr(params, 'params_proto') or
not isinstance(params.params_proto,
_params_proto.TensorForestParams)):
params.params_proto = build_params_proto(params)
params.serialized_params_proto = params.params_proto.SerializeToString()
self.stats = None
if training:
# TODO(gilberth): Manually shard this to be able to fit it on
# multiple machines.
self.stats = stats_ops.fertile_stats_variable(
params, '', self.get_tree_name('stats', tree_num))
self.tree = model_ops.tree_variable(
params, '', self.stats, self.get_tree_name('tree', tree_num))
def get_tree_name(self, name, num):
return '{0}-{1}'.format(name, num)
class ForestTrainingVariables(object):
"""A container for a forests training data, consisting of multiple trees.
Instantiates a TreeTrainingVariables object for each tree. We override the
__getitem__ and __setitem__ function so that usage looks like this:
forest_variables = ForestTrainingVariables(params)
... forest_variables.tree ...
"""
def __init__(self, params, device_assigner, training=True,
tree_variables_class=TreeTrainingVariables):
self.variables = []
# Set up some scalar variables to run through the device assigner, then
# we can use those to colocate everything related to a tree.
self.device_dummies = []
with ops.device(device_assigner):
for i in range(params.num_trees):
self.device_dummies.append(variable_scope.get_variable(
name='device_dummy_%d' % i, shape=0))
for i in range(params.num_trees):
with ops.device(self.device_dummies[i].device):
self.variables.append(tree_variables_class(params, i, training))
def __setitem__(self, t, val):
self.variables[t] = val
def __getitem__(self, t):
return self.variables[t]
class RandomForestGraphs(object):
"""Builds TF graphs for random forest training and inference."""
def __init__(self,
params,
device_assigner=None,
variables=None,
tree_variables_class=TreeTrainingVariables,
tree_graphs=None,
training=True):
self.params = params
self.device_assigner = (
device_assigner or framework_variables.VariableDeviceChooser())
logging.info('Constructing forest with params = ')
logging.info(self.params.__dict__)
self.variables = variables or ForestTrainingVariables(
self.params, device_assigner=self.device_assigner, training=training,
tree_variables_class=tree_variables_class)
tree_graph_class = tree_graphs or RandomTreeGraphs
self.trees = [
tree_graph_class(self.variables[i], self.params, i)
for i in range(self.params.num_trees)
]
def _bag_features(self, tree_num, input_data):
split_data = array_ops.split(
value=input_data, num_or_size_splits=self.params.num_features, axis=1)
return array_ops.concat(
[split_data[ind] for ind in self.params.bagged_features[tree_num]], 1)
def get_all_resource_handles(self):
return ([self.variables[i].tree for i in range(len(self.trees))] +
[self.variables[i].stats for i in range(len(self.trees))])
def training_graph(self,
input_data,
input_labels,
num_trainers=1,
trainer_id=0,
**tree_kwargs):
"""Constructs a TF graph for training a random forest.
Args:
input_data: A tensor or dict of string->Tensor for input data.
input_labels: A tensor or placeholder for labels associated with
input_data.
num_trainers: Number of parallel trainers to split trees among.
trainer_id: Which trainer this instance is.
**tree_kwargs: Keyword arguments passed to each tree's training_graph.
Returns:
The last op in the random forest training graph.
Raises:
NotImplementedError: If trying to use bagging with sparse features.
"""
processed_dense_features, processed_sparse_features, data_spec = (
data_ops.ParseDataTensorOrDict(input_data))
if input_labels is not None:
labels = data_ops.ParseLabelTensorOrDict(input_labels)
data_spec = data_spec or self.get_default_data_spec(input_data)
tree_graphs = []
trees_per_trainer = self.params.num_trees / num_trainers
tree_start = int(trainer_id * trees_per_trainer)
tree_end = int((trainer_id + 1) * trees_per_trainer)
for i in range(tree_start, tree_end):
with ops.device(self.variables.device_dummies[i].device):
seed = self.params.base_random_seed
if seed != 0:
seed += i
# If using bagging, randomly select some of the input.
tree_data = processed_dense_features
tree_labels = labels
if self.params.bagging_fraction < 1.0:
# TODO(gilberth): Support bagging for sparse features.
if processed_sparse_features is not None:
raise NotImplementedError(
'Bagging not supported with sparse features.')
# TODO(thomaswc): This does sampling without replacement. Consider
# also allowing sampling with replacement as an option.
batch_size = array_ops.strided_slice(
array_ops.shape(processed_dense_features), [0], [1])
r = random_ops.random_uniform(batch_size, seed=seed)
mask = math_ops.less(
r, array_ops.ones_like(r) * self.params.bagging_fraction)
gather_indices = array_ops.squeeze(
array_ops.where(mask), squeeze_dims=[1])
# TODO(thomaswc): Calculate out-of-bag data and labels, and store
# them for use in calculating statistics later.
tree_data = array_ops.gather(processed_dense_features, gather_indices)
tree_labels = array_ops.gather(labels, gather_indices)
if self.params.bagged_features:
if processed_sparse_features is not None:
raise NotImplementedError(
'Feature bagging not supported with sparse features.')
tree_data = self._bag_features(i, tree_data)
tree_graphs.append(self.trees[i].training_graph(
tree_data,
tree_labels,
seed,
data_spec=data_spec,
sparse_features=processed_sparse_features,
**tree_kwargs))
return control_flow_ops.group(*tree_graphs, name='train')
def inference_graph(self, input_data, **inference_args):
"""Constructs a TF graph for evaluating a random forest.
Args:
input_data: A tensor or dict of string->Tensor for the input data.
This input_data must generate the same spec as the
input_data used in training_graph: the dict must have
the same keys, for example, and all tensors must have
the same size in their first dimension.
**inference_args: Keyword arguments to pass through to each tree.
Returns:
A tuple of (probabilities, tree_paths, variance), where variance
is the variance over all the trees for regression problems only.
Raises:
NotImplementedError: If trying to use feature bagging with sparse
features.
"""
processed_dense_features, processed_sparse_features, data_spec = (
data_ops.ParseDataTensorOrDict(input_data))
probabilities = []
paths = []
for i in range(self.params.num_trees):
with ops.device(self.variables.device_dummies[i].device):
tree_data = processed_dense_features
if self.params.bagged_features:
if processed_sparse_features is not None:
raise NotImplementedError(
'Feature bagging not supported with sparse features.')
tree_data = self._bag_features(i, tree_data)
probs, path = self.trees[i].inference_graph(
tree_data,
data_spec,
sparse_features=processed_sparse_features,
**inference_args)
probabilities.append(probs)
paths.append(path)
with ops.device(self.variables.device_dummies[0].device):
# shape of all_predict should be [batch_size, num_trees, num_outputs]
all_predict = array_ops.stack(probabilities, axis=1)
average_values = math_ops.div(
math_ops.reduce_sum(all_predict, 1),
self.params.num_trees,
name='probabilities')
tree_paths = array_ops.stack(paths, axis=1)
regression_variance = None
if self.params.regression:
expected_squares = math_ops.div(
math_ops.reduce_sum(all_predict * all_predict, 1),
self.params.num_trees)
regression_variance = math_ops.maximum(
0., expected_squares - average_values * average_values)
return average_values, tree_paths, regression_variance
def average_size(self):
"""Constructs a TF graph for evaluating the average size of a forest.
Returns:
The average number of nodes over the trees.
"""
sizes = []
for i in range(self.params.num_trees):
with ops.device(self.variables.device_dummies[i].device):
sizes.append(self.trees[i].size())
return math_ops.reduce_mean(math_ops.to_float(array_ops.stack(sizes)))
# pylint: disable=unused-argument
def training_loss(self, features, labels, name='training_loss'):
return math_ops.negative(self.average_size(), name=name)
# pylint: disable=unused-argument
def validation_loss(self, features, labels):
return math_ops.negative(self.average_size())
def average_impurity(self):
"""Constructs a TF graph for evaluating the leaf impurity of a forest.
Returns:
The last op in the graph.
"""
impurities = []
for i in range(self.params.num_trees):
with ops.device(self.variables.device_dummies[i].device):
impurities.append(self.trees[i].average_impurity())
return math_ops.reduce_mean(array_ops.stack(impurities))
def feature_importances(self):
tree_counts = [self.trees[i].feature_usage_counts()
for i in range(self.params.num_trees)]
total_counts = math_ops.reduce_sum(array_ops.stack(tree_counts, 0), 0)
return total_counts / math_ops.reduce_sum(total_counts)
class RandomTreeGraphs(object):
"""Builds TF graphs for random tree training and inference."""
def __init__(self, variables, params, tree_num):
self.variables = variables
self.params = params
self.tree_num = tree_num
def training_graph(self,
input_data,
input_labels,
random_seed,
data_spec,
sparse_features=None,
input_weights=None):
"""Constructs a TF graph for training a random tree.
Args:
input_data: A tensor or placeholder for input data.
input_labels: A tensor or placeholder for labels associated with
input_data.
random_seed: The random number generator seed to use for this tree. 0
means use the current time as the seed.
data_spec: A data_ops.TensorForestDataSpec object specifying the
original feature/columns of the data.
sparse_features: A tf.SparseTensor for sparse input data.
input_weights: A float tensor or placeholder holding per-input weights,
or None if all inputs are to be weighted equally.
Returns:
The last op in the random tree training graph.
"""
# TODO(gilberth): Use this.
unused_epoch = math_ops.to_int32(get_epoch_variable())
if input_weights is None:
input_weights = []
sparse_indices = []
sparse_values = []
sparse_shape = []
if sparse_features is not None:
sparse_indices = sparse_features.indices
sparse_values = sparse_features.values
sparse_shape = sparse_features.dense_shape
if input_data is None:
input_data = []
leaf_ids = model_ops.traverse_tree_v4(
self.variables.tree,
input_data,
sparse_indices,
sparse_values,
sparse_shape,
input_spec=data_spec.SerializeToString(),
params=self.params.serialized_params_proto)
update_model = model_ops.update_model_v4(
self.variables.tree,
leaf_ids,
input_labels,
input_weights,
params=self.params.serialized_params_proto)
finished_nodes = stats_ops.process_input_v4(
self.variables.tree,
self.variables.stats,
input_data,
sparse_indices,
sparse_values,
sparse_shape,
input_labels,
input_weights,
leaf_ids,
input_spec=data_spec.SerializeToString(),
random_seed=random_seed,
params=self.params.serialized_params_proto)
with ops.control_dependencies([update_model]):
return stats_ops.grow_tree_v4(
self.variables.tree,
self.variables.stats,
finished_nodes,
params=self.params.serialized_params_proto)
def inference_graph(self, input_data, data_spec, sparse_features=None):
"""Constructs a TF graph for evaluating a random tree.
Args:
input_data: A tensor or placeholder for input data.
data_spec: A TensorForestDataSpec proto specifying the original
input columns.
sparse_features: A tf.SparseTensor for sparse input data.
Returns:
A tuple of (probabilities, tree_paths).
"""
sparse_indices = []
sparse_values = []
sparse_shape = []
if sparse_features is not None:
sparse_indices = sparse_features.indices
sparse_values = sparse_features.values
sparse_shape = sparse_features.dense_shape
if input_data is None:
input_data = []
return model_ops.tree_predictions_v4(
self.variables.tree,
input_data,
sparse_indices,
sparse_values,
sparse_shape,
input_spec=data_spec.SerializeToString(),
params=self.params.serialized_params_proto)
def size(self):
"""Constructs a TF graph for evaluating the current number of nodes.
Returns:
The current number of nodes in the tree.
"""
return model_ops.tree_size(self.variables.tree)
def feature_usage_counts(self):
return model_ops.feature_usage_counts(
self.variables.tree, params=self.params.serialized_params_proto)
|
|
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# 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.
"""
Tests dealing with HTTP rate-limiting.
"""
import httplib
import json
import StringIO
import stubout
import time
import unittest
import webob
from xml.dom.minidom import parseString
from nova.api.openstack import limits
TEST_LIMITS = [
limits.Limit("GET", "/delayed", "^/delayed", 1, limits.PER_MINUTE),
limits.Limit("POST", "*", ".*", 7, limits.PER_MINUTE),
limits.Limit("POST", "/servers", "^/servers", 3, limits.PER_MINUTE),
limits.Limit("PUT", "*", "", 10, limits.PER_MINUTE),
limits.Limit("PUT", "/servers", "^/servers", 5, limits.PER_MINUTE),
]
class BaseLimitTestSuite(unittest.TestCase):
"""Base test suite which provides relevant stubs and time abstraction."""
def setUp(self):
"""Run before each test."""
self.time = 0.0
self.stubs = stubout.StubOutForTesting()
self.stubs.Set(limits.Limit, "_get_time", self._get_time)
def tearDown(self):
"""Run after each test."""
self.stubs.UnsetAll()
def _get_time(self):
"""Return the "time" according to this test suite."""
return self.time
class LimitsControllerV10Test(BaseLimitTestSuite):
"""
Tests for `limits.LimitsControllerV10` class.
"""
def setUp(self):
"""Run before each test."""
BaseLimitTestSuite.setUp(self)
self.controller = limits.LimitsControllerV10()
def _get_index_request(self, accept_header="application/json"):
"""Helper to set routing arguments."""
request = webob.Request.blank("/")
request.accept = accept_header
request.environ["wsgiorg.routing_args"] = (None, {
"action": "index",
"controller": "",
})
return request
def _populate_limits(self, request):
"""Put limit info into a request."""
_limits = [
limits.Limit("GET", "*", ".*", 10, 60).display(),
limits.Limit("POST", "*", ".*", 5, 60 * 60).display(),
]
request.environ["nova.limits"] = _limits
return request
def test_empty_index_json(self):
"""Test getting empty limit details in JSON."""
request = self._get_index_request()
response = request.get_response(self.controller)
expected = {
"limits": {
"rate": [],
"absolute": {},
},
}
body = json.loads(response.body)
self.assertEqual(expected, body)
def test_index_json(self):
"""Test getting limit details in JSON."""
request = self._get_index_request()
request = self._populate_limits(request)
response = request.get_response(self.controller)
expected = {
"limits": {
"rate": [{
"regex": ".*",
"resetTime": 0,
"URI": "*",
"value": 10,
"verb": "GET",
"remaining": 10,
"unit": "MINUTE",
},
{
"regex": ".*",
"resetTime": 0,
"URI": "*",
"value": 5,
"verb": "POST",
"remaining": 5,
"unit": "HOUR",
}],
"absolute": {},
},
}
body = json.loads(response.body)
self.assertEqual(expected, body)
def test_empty_index_xml(self):
"""Test getting limit details in XML."""
request = self._get_index_request("application/xml")
response = request.get_response(self.controller)
expected = parseString("""
<limits
xmlns="http://docs.rackspacecloud.com/servers/api/v1.0">
<rate/>
<absolute/>
</limits>
""".replace(" ", ""))
body = parseString(response.body.replace(" ", ""))
self.assertEqual(expected.toxml(), body.toxml())
def test_index_xml(self):
"""Test getting limit details in XML."""
request = self._get_index_request("application/xml")
request = self._populate_limits(request)
response = request.get_response(self.controller)
expected = parseString("""
<limits
xmlns="http://docs.rackspacecloud.com/servers/api/v1.0">
<rate>
<limit URI="*" regex=".*" remaining="10" resetTime="0"
unit="MINUTE" value="10" verb="GET"/>
<limit URI="*" regex=".*" remaining="5" resetTime="0"
unit="HOUR" value="5" verb="POST"/>
</rate>
<absolute/>
</limits>
""".replace(" ", ""))
body = parseString(response.body.replace(" ", ""))
self.assertEqual(expected.toxml(), body.toxml())
class LimitsControllerV11Test(BaseLimitTestSuite):
"""
Tests for `limits.LimitsControllerV11` class.
"""
def setUp(self):
"""Run before each test."""
BaseLimitTestSuite.setUp(self)
self.controller = limits.LimitsControllerV11()
def _get_index_request(self, accept_header="application/json"):
"""Helper to set routing arguments."""
request = webob.Request.blank("/")
request.accept = accept_header
request.environ["wsgiorg.routing_args"] = (None, {
"action": "index",
"controller": "",
})
return request
def _populate_limits(self, request):
"""Put limit info into a request."""
_limits = [
limits.Limit("GET", "*", ".*", 10, 60).display(),
limits.Limit("POST", "*", ".*", 5, 60 * 60).display(),
limits.Limit("GET", "changes-since*", "changes-since",
5, 60).display(),
]
request.environ["nova.limits"] = _limits
return request
def test_empty_index_json(self):
"""Test getting empty limit details in JSON."""
request = self._get_index_request()
response = request.get_response(self.controller)
expected = {
"limits": {
"rate": [],
"absolute": {},
},
}
body = json.loads(response.body)
self.assertEqual(expected, body)
def test_index_json(self):
"""Test getting limit details in JSON."""
request = self._get_index_request()
request = self._populate_limits(request)
response = request.get_response(self.controller)
expected = {
"limits": {
"rate": [
{
"regex": ".*",
"uri": "*",
"limit": [
{
"verb": "GET",
"next-available": 0,
"unit": "MINUTE",
"value": 10,
"remaining": 10,
},
{
"verb": "POST",
"next-available": 0,
"unit": "HOUR",
"value": 5,
"remaining": 5,
},
],
},
{
"regex": "changes-since",
"uri": "changes-since*",
"limit": [
{
"verb": "GET",
"next-available": 0,
"unit": "MINUTE",
"value": 5,
"remaining": 5,
},
],
},
],
"absolute": {},
},
}
body = json.loads(response.body)
self.assertEqual(expected, body)
class LimitMiddlewareTest(BaseLimitTestSuite):
"""
Tests for the `limits.RateLimitingMiddleware` class.
"""
@webob.dec.wsgify
def _empty_app(self, request):
"""Do-nothing WSGI app."""
pass
def setUp(self):
"""Prepare middleware for use through fake WSGI app."""
BaseLimitTestSuite.setUp(self)
_limits = [
limits.Limit("GET", "*", ".*", 1, 60),
]
self.app = limits.RateLimitingMiddleware(self._empty_app, _limits)
def test_good_request(self):
"""Test successful GET request through middleware."""
request = webob.Request.blank("/")
response = request.get_response(self.app)
self.assertEqual(200, response.status_int)
def test_limited_request_json(self):
"""Test a rate-limited (403) GET request through middleware."""
request = webob.Request.blank("/")
response = request.get_response(self.app)
self.assertEqual(200, response.status_int)
request = webob.Request.blank("/")
response = request.get_response(self.app)
self.assertEqual(response.status_int, 403)
body = json.loads(response.body)
expected = "Only 1 GET request(s) can be made to * every minute."
value = body["overLimitFault"]["details"].strip()
self.assertEqual(value, expected)
def test_limited_request_xml(self):
"""Test a rate-limited (403) response as XML"""
request = webob.Request.blank("/")
response = request.get_response(self.app)
self.assertEqual(200, response.status_int)
request = webob.Request.blank("/")
request.accept = "application/xml"
response = request.get_response(self.app)
self.assertEqual(response.status_int, 403)
root = parseString(response.body).childNodes[0]
expected = "Only 1 GET request(s) can be made to * every minute."
details = root.getElementsByTagName("details")
self.assertEqual(details.length, 1)
value = details.item(0).firstChild.data.strip()
self.assertEqual(value, expected)
class LimitTest(BaseLimitTestSuite):
"""
Tests for the `limits.Limit` class.
"""
def test_GET_no_delay(self):
"""Test a limit handles 1 GET per second."""
limit = limits.Limit("GET", "*", ".*", 1, 1)
delay = limit("GET", "/anything")
self.assertEqual(None, delay)
self.assertEqual(0, limit.next_request)
self.assertEqual(0, limit.last_request)
def test_GET_delay(self):
"""Test two calls to 1 GET per second limit."""
limit = limits.Limit("GET", "*", ".*", 1, 1)
delay = limit("GET", "/anything")
self.assertEqual(None, delay)
delay = limit("GET", "/anything")
self.assertEqual(1, delay)
self.assertEqual(1, limit.next_request)
self.assertEqual(0, limit.last_request)
self.time += 4
delay = limit("GET", "/anything")
self.assertEqual(None, delay)
self.assertEqual(4, limit.next_request)
self.assertEqual(4, limit.last_request)
class LimiterTest(BaseLimitTestSuite):
"""
Tests for the in-memory `limits.Limiter` class.
"""
def setUp(self):
"""Run before each test."""
BaseLimitTestSuite.setUp(self)
self.limiter = limits.Limiter(TEST_LIMITS)
def _check(self, num, verb, url, username=None):
"""Check and yield results from checks."""
for x in xrange(num):
yield self.limiter.check_for_delay(verb, url, username)[0]
def _check_sum(self, num, verb, url, username=None):
"""Check and sum results from checks."""
results = self._check(num, verb, url, username)
return sum(item for item in results if item)
def test_no_delay_GET(self):
"""
Simple test to ensure no delay on a single call for a limit verb we
didn"t set.
"""
delay = self.limiter.check_for_delay("GET", "/anything")
self.assertEqual(delay, (None, None))
def test_no_delay_PUT(self):
"""
Simple test to ensure no delay on a single call for a known limit.
"""
delay = self.limiter.check_for_delay("PUT", "/anything")
self.assertEqual(delay, (None, None))
def test_delay_PUT(self):
"""
Ensure the 11th PUT will result in a delay of 6.0 seconds until
the next request will be granced.
"""
expected = [None] * 10 + [6.0]
results = list(self._check(11, "PUT", "/anything"))
self.assertEqual(expected, results)
def test_delay_POST(self):
"""
Ensure the 8th POST will result in a delay of 6.0 seconds until
the next request will be granced.
"""
expected = [None] * 7
results = list(self._check(7, "POST", "/anything"))
self.assertEqual(expected, results)
expected = 60.0 / 7.0
results = self._check_sum(1, "POST", "/anything")
self.failUnlessAlmostEqual(expected, results, 8)
def test_delay_GET(self):
"""
Ensure the 11th GET will result in NO delay.
"""
expected = [None] * 11
results = list(self._check(11, "GET", "/anything"))
self.assertEqual(expected, results)
def test_delay_PUT_servers(self):
"""
Ensure PUT on /servers limits at 5 requests, and PUT elsewhere is still
OK after 5 requests...but then after 11 total requests, PUT limiting
kicks in.
"""
# First 6 requests on PUT /servers
expected = [None] * 5 + [12.0]
results = list(self._check(6, "PUT", "/servers"))
self.assertEqual(expected, results)
# Next 5 request on PUT /anything
expected = [None] * 4 + [6.0]
results = list(self._check(5, "PUT", "/anything"))
self.assertEqual(expected, results)
def test_delay_PUT_wait(self):
"""
Ensure after hitting the limit and then waiting for the correct
amount of time, the limit will be lifted.
"""
expected = [None] * 10 + [6.0]
results = list(self._check(11, "PUT", "/anything"))
self.assertEqual(expected, results)
# Advance time
self.time += 6.0
expected = [None, 6.0]
results = list(self._check(2, "PUT", "/anything"))
self.assertEqual(expected, results)
def test_multiple_delays(self):
"""
Ensure multiple requests still get a delay.
"""
expected = [None] * 10 + [6.0] * 10
results = list(self._check(20, "PUT", "/anything"))
self.assertEqual(expected, results)
self.time += 1.0
expected = [5.0] * 10
results = list(self._check(10, "PUT", "/anything"))
self.assertEqual(expected, results)
def test_multiple_users(self):
"""
Tests involving multiple users.
"""
# User1
expected = [None] * 10 + [6.0] * 10
results = list(self._check(20, "PUT", "/anything", "user1"))
self.assertEqual(expected, results)
# User2
expected = [None] * 10 + [6.0] * 5
results = list(self._check(15, "PUT", "/anything", "user2"))
self.assertEqual(expected, results)
self.time += 1.0
# User1 again
expected = [5.0] * 10
results = list(self._check(10, "PUT", "/anything", "user1"))
self.assertEqual(expected, results)
self.time += 1.0
# User1 again
expected = [4.0] * 5
results = list(self._check(5, "PUT", "/anything", "user2"))
self.assertEqual(expected, results)
class WsgiLimiterTest(BaseLimitTestSuite):
"""
Tests for `limits.WsgiLimiter` class.
"""
def setUp(self):
"""Run before each test."""
BaseLimitTestSuite.setUp(self)
self.app = limits.WsgiLimiter(TEST_LIMITS)
def _request_data(self, verb, path):
"""Get data decribing a limit request verb/path."""
return json.dumps({"verb": verb, "path": path})
def _request(self, verb, url, username=None):
"""Make sure that POSTing to the given url causes the given username
to perform the given action. Make the internal rate limiter return
delay and make sure that the WSGI app returns the correct response.
"""
if username:
request = webob.Request.blank("/%s" % username)
else:
request = webob.Request.blank("/")
request.method = "POST"
request.body = self._request_data(verb, url)
response = request.get_response(self.app)
if "X-Wait-Seconds" in response.headers:
self.assertEqual(response.status_int, 403)
return response.headers["X-Wait-Seconds"]
self.assertEqual(response.status_int, 204)
def test_invalid_methods(self):
"""Only POSTs should work."""
requests = []
for method in ["GET", "PUT", "DELETE", "HEAD", "OPTIONS"]:
request = webob.Request.blank("/")
request.body = self._request_data("GET", "/something")
response = request.get_response(self.app)
self.assertEqual(response.status_int, 405)
def test_good_url(self):
delay = self._request("GET", "/something")
self.assertEqual(delay, None)
def test_escaping(self):
delay = self._request("GET", "/something/jump%20up")
self.assertEqual(delay, None)
def test_response_to_delays(self):
delay = self._request("GET", "/delayed")
self.assertEqual(delay, None)
delay = self._request("GET", "/delayed")
self.assertEqual(delay, '60.00')
def test_response_to_delays_usernames(self):
delay = self._request("GET", "/delayed", "user1")
self.assertEqual(delay, None)
delay = self._request("GET", "/delayed", "user2")
self.assertEqual(delay, None)
delay = self._request("GET", "/delayed", "user1")
self.assertEqual(delay, '60.00')
delay = self._request("GET", "/delayed", "user2")
self.assertEqual(delay, '60.00')
class FakeHttplibSocket(object):
"""
Fake `httplib.HTTPResponse` replacement.
"""
def __init__(self, response_string):
"""Initialize new `FakeHttplibSocket`."""
self._buffer = StringIO.StringIO(response_string)
def makefile(self, _mode, _other):
"""Returns the socket's internal buffer."""
return self._buffer
class FakeHttplibConnection(object):
"""
Fake `httplib.HTTPConnection`.
"""
def __init__(self, app, host):
"""
Initialize `FakeHttplibConnection`.
"""
self.app = app
self.host = host
def request(self, method, path, body="", headers={}):
"""
Requests made via this connection actually get translated and routed
into our WSGI app, we then wait for the response and turn it back into
an `httplib.HTTPResponse`.
"""
req = webob.Request.blank(path)
req.method = method
req.headers = headers
req.host = self.host
req.body = body
resp = str(req.get_response(self.app))
resp = "HTTP/1.0 %s" % resp
sock = FakeHttplibSocket(resp)
self.http_response = httplib.HTTPResponse(sock)
self.http_response.begin()
def getresponse(self):
"""Return our generated response from the request."""
return self.http_response
def wire_HTTPConnection_to_WSGI(host, app):
"""Monkeypatches HTTPConnection so that if you try to connect to host, you
are instead routed straight to the given WSGI app.
After calling this method, when any code calls
httplib.HTTPConnection(host)
the connection object will be a fake. Its requests will be sent directly
to the given WSGI app rather than through a socket.
Code connecting to hosts other than host will not be affected.
This method may be called multiple times to map different hosts to
different apps.
"""
class HTTPConnectionDecorator(object):
"""Wraps the real HTTPConnection class so that when you instantiate
the class you might instead get a fake instance."""
def __init__(self, wrapped):
self.wrapped = wrapped
def __call__(self, connection_host, *args, **kwargs):
if connection_host == host:
return FakeHttplibConnection(app, host)
else:
return self.wrapped(connection_host, *args, **kwargs)
httplib.HTTPConnection = HTTPConnectionDecorator(httplib.HTTPConnection)
class WsgiLimiterProxyTest(BaseLimitTestSuite):
"""
Tests for the `limits.WsgiLimiterProxy` class.
"""
def setUp(self):
"""
Do some nifty HTTP/WSGI magic which allows for WSGI to be called
directly by something like the `httplib` library.
"""
BaseLimitTestSuite.setUp(self)
self.app = limits.WsgiLimiter(TEST_LIMITS)
wire_HTTPConnection_to_WSGI("169.254.0.1:80", self.app)
self.proxy = limits.WsgiLimiterProxy("169.254.0.1:80")
def test_200(self):
"""Successful request test."""
delay = self.proxy.check_for_delay("GET", "/anything")
self.assertEqual(delay, (None, None))
def test_403(self):
"""Forbidden request test."""
delay = self.proxy.check_for_delay("GET", "/delayed")
self.assertEqual(delay, (None, None))
delay, error = self.proxy.check_for_delay("GET", "/delayed")
error = error.strip()
expected = ("60.00", "403 Forbidden\n\nOnly 1 GET request(s) can be "\
"made to /delayed every minute.")
self.assertEqual((delay, error), expected)
|
|
# -*- coding: utf-8 -*-
from anima.ui.lib import QtCore, QtWidgets
class TaskDashboardWidget(QtWidgets.QWidget):
"""A widget that displays task related information"""
def __init__(self, task=None, parent=None, **kwargs):
self._task = None
self.parent = parent
super(TaskDashboardWidget, self).__init__(parent=parent)
# storage for UI stuff
self.vertical_layout = None
self.widget_label = None
self.task_thumbnail_widget = None
self.schedule_info_form_layout = None
self.task_detail_widget = None
self.task_timing_widget = None
self.description_label = None
self.description_field = None
self.description_field_is_updating = False
self.responsible_info_widget = None
self.resource_info_widget = None
self.task_versions_usage_info_widget = None
self.watch_task_button = None
self.fix_task_status_button = None
self.task_status_label = None
self.task_progress = None
self.task_notes_widget = None
self._setup_ui()
self.task = task
def _setup_ui(self):
"""create the UI widgets"""
# we need a main layout
# may be a vertical one
# or a form layout
self.vertical_layout = QtWidgets.QVBoxLayout(self)
# -------------------------
# Dialog Label and buttons
horizontal_layout3 = QtWidgets.QHBoxLayout()
self.vertical_layout.addLayout(horizontal_layout3)
self.widget_label = QtWidgets.QLabel(self)
self.widget_label.setStyleSheet("color: rgb(71, 143, 202);\nfont: 18pt;")
horizontal_layout3.addWidget(self.widget_label)
horizontal_layout3.addStretch(1)
# Add Watch Task button
self.watch_task_button = QtWidgets.QPushButton(self)
self.watch_task_button.setMaximumWidth(24)
self.watch_task_button.setMaximumHeight(24)
self.watch_task_button.setText("W")
self.watch_task_button.setToolTip("Watch Task")
self.fix_task_status_button = QtWidgets.QPushButton(self)
self.fix_task_status_button.setMaximumWidth(24)
self.fix_task_status_button.setMaximumHeight(24)
self.fix_task_status_button.setText("F")
self.fix_task_status_button.setToolTip("Fix Task Status")
horizontal_layout3.addWidget(self.watch_task_button)
horizontal_layout3.addWidget(self.fix_task_status_button)
QtCore.QObject.connect(
self.fix_task_status_button,
QtCore.SIGNAL("clicked()"),
self.fix_task_status,
)
# Add Status Label
vertical_layout3 = QtWidgets.QVBoxLayout()
from anima.ui.widgets.task_status_label import TaskStatusLabel
self.task_status_label = TaskStatusLabel(task=self.task)
self.task_status_label.setMaximumHeight(12)
vertical_layout3.addWidget(self.task_status_label)
# Add ProgressBar
self.task_progress = QtWidgets.QProgressBar(self)
self.task_progress.setMinimum(0)
self.task_progress.setMaximum(100)
self.task_progress.setValue(50)
self.task_progress.setAlignment(QtCore.Qt.AlignCenter)
self.task_progress.setMaximumHeight(12)
self.task_progress.setStyleSheet(
"""
QProgressBar::chunk {
background-color: #3add36;
width: 1px;
}
"""
)
vertical_layout3.addWidget(self.task_progress)
# set items closer to each other
vertical_layout3.setSpacing(0)
horizontal_layout3.addLayout(vertical_layout3)
# Add divider
line = QtWidgets.QFrame(self)
line.setFrameShape(QtWidgets.QFrame.HLine)
line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.vertical_layout.addWidget(line)
horizontal_layout1 = QtWidgets.QHBoxLayout()
self.vertical_layout.addLayout(horizontal_layout1)
vertical_layout1 = QtWidgets.QVBoxLayout()
vertical_layout2 = QtWidgets.QVBoxLayout()
horizontal_layout1.addLayout(vertical_layout1)
horizontal_layout1.addLayout(vertical_layout2)
# --------------------------
# Horizontal Layout for thumbnail and detail widgets
horizontal_layout2 = QtWidgets.QHBoxLayout()
vertical_layout1.addLayout(horizontal_layout2)
# --------------------------
# Task Thumbnail
from anima.ui.widgets.entity_thumbnail import EntityThumbnailWidget
self.task_thumbnail_widget = EntityThumbnailWidget(task=self.task, parent=self)
horizontal_layout2.addWidget(self.task_thumbnail_widget)
# --------------------------
# Task Detail Info
from anima.ui.widgets.task_detail import TaskDetailWidget
self.task_detail_widget = TaskDetailWidget(task=self.task, parent=self)
horizontal_layout2.addWidget(self.task_detail_widget)
# --------------------------
# Task Timing Info
from anima.ui.widgets.task_timing import TaskTimingInfoWidget
self.task_timing_widget = TaskTimingInfoWidget(task=self.task, parent=self)
horizontal_layout2.addWidget(self.task_timing_widget)
# add stretcher
# horizontal_layout2.addStretch(1)
# --------------------------
# Description field
self.description_label = QtWidgets.QLabel(self)
self.description_label.setStyleSheet(
"""
background-color: gray;
color: white;
font-weight: bold;
padding: 0.5em;
"""
)
self.description_label.setText("Description")
self.description_field = QtWidgets.QTextEdit(self)
self.description_field.setAcceptRichText(True)
vertical_layout1.addWidget(self.description_label)
vertical_layout1.addWidget(self.description_field)
# add stretcher
vertical_layout1.addStretch(1)
# connect signal
self.description_field.textChanged.connect(self.update_description)
# ---------------------------
# Responsible Info
from anima.ui.widgets.responsible_info import ResponsibleInfoWidget
self.responsible_info_widget = ResponsibleInfoWidget(
task=self.task, parent=self
)
vertical_layout2.addWidget(self.responsible_info_widget)
# ---------------------------
# Resource Info
from anima.ui.widgets.resource_info import ResourceInfoWidget
self.resource_info_widget = ResourceInfoWidget(task=self.task, parent=self)
vertical_layout2.addWidget(self.resource_info_widget)
# ---------------------------
# Task Versions Usage Info
from anima.ui.widgets.task_version_usage_info import TaskVersionUsageInfoWidget
self.task_versions_usage_info_widget = TaskVersionUsageInfoWidget(
task=self.task, parent=self
)
vertical_layout2.addWidget(self.task_versions_usage_info_widget)
vertical_layout2.addStretch(1)
horizontal_layout1.setStretch(0, 2)
horizontal_layout1.setStretch(1, 1)
# ---------------------------
# Task Notes
from anima.ui.widgets.entity_notes import EntityNotesWidgets
self.task_notes_widget = EntityNotesWidgets(entity=self.task, parent=self)
self.vertical_layout.addWidget(self.task_notes_widget)
@property
def task(self):
"""getter for the _task attribute"""
return self._task
@task.setter
def task(self, task):
"""setter for the task attribute"""
from stalker import Task
if isinstance(task, Task):
self._task = task
else:
self._task = None
# self.description_label = None
# self.description_field = None
# self.responsible_info_widget = None
# self.resource_info_widget = None
# self.task_versions_usage_info_widget = None
# self.watch_task_button = None
# self.fix_task_status_button = None
# self.task_progress = None
if self._task:
self.description_field_is_updating = True
self.description_field.setText(self._task.description)
self.description_field_is_updating = False
self.task_progress.setValue(self._task.percent_complete)
else:
self.description_field_is_updating = True
self.description_field.setText("")
self.description_field_is_updating = False
self.task_progress.setValue(0)
self.widget_label.setText(self._task.name if self._task else "Task Name")
self.task_thumbnail_widget.task = self._task
self.task_detail_widget.task = self._task
self.task_timing_widget.task = self._task
self.task_status_label.task = self._task
self.task_notes_widget.task = self._task
def fix_task_status(self):
"""fix current task status"""
from stalker import Task
assert isinstance(self.task, Task)
from anima import utils
utils.fix_task_statuses(self.task)
utils.fix_task_computed_time(self.task)
from stalker.db.session import DBSession
DBSession.add(self.task)
DBSession.commit()
def update_description(self):
"""runs when description field has changed"""
if self.description_field_is_updating:
return
self.description_field_is_updating = True
self.task.description = self.description_field.toPlainText()
from stalker.db.session import DBSession
DBSession.add(self.task)
DBSession.commit()
self.description_field_is_updating = False
|
|
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import shutil
import tempfile
from pants.invalidation.build_invalidator import BuildInvalidator, CacheKeyGenerator
from pants.invalidation.cache_manager import InvalidationCacheManager, VersionedTargetSet
from pants.util.dirutil import safe_mkdir, safe_rmtree
from pants_test.base_test import BaseTest
class InvalidationCacheManagerTest(BaseTest):
@staticmethod
def is_empty(dir_name):
return not os.listdir(dir_name)
@staticmethod
def has_symlinked_result_dir(vt):
return os.path.realpath(vt.results_dir) == os.path.realpath(vt.current_results_dir)
@staticmethod
def clobber_symlink(vt):
# Munge the state to mimic a common error found before we added the clean- it accidentally clobbers the symlink!
# Commonly caused by safe_mkdir(vt.results_dir, clean=True), broken up here to keep the tests from being brittle.
safe_rmtree(vt.results_dir)
safe_mkdir(vt.results_dir)
def setUp(self):
super(InvalidationCacheManagerTest, self).setUp()
self._dir = tempfile.mkdtemp()
self.cache_manager = InvalidationCacheManager(
results_dir_root=os.path.join(self._dir, 'results'),
cache_key_generator=CacheKeyGenerator(),
build_invalidator=BuildInvalidator(os.path.join(self._dir, 'build_invalidator')),
invalidate_dependents=True,
)
def tearDown(self):
shutil.rmtree(self._dir, ignore_errors=True)
super(InvalidationCacheManagerTest, self).tearDown()
def make_vt(self):
# Create an arbitrary VT. It will mimic the state of the VT handed back by a task.
a_target = self.make_target(':a', dependencies=[])
ic = self.cache_manager.check([a_target])
vt = ic.all_vts[0]
self.task_execute(vt)
vt.update()
return vt
def task_execute(self, vt):
vt.create_results_dir()
task_output = os.path.join(vt.results_dir, 'a_file')
self.create_file(task_output, 'foo')
def test_creates_stable_result_dir_symlink(self):
vt = self.make_vt()
vt.create_results_dir()
parent, unstable_dir_name = os.path.split(vt._current_results_dir)
self.assertSetEqual({'current', unstable_dir_name}, set(os.listdir(parent)))
symlink = os.path.join(parent, 'current')
self.assertTrue(os.path.islink(symlink))
self.assertEquals(unstable_dir_name, os.readlink(symlink))
self.assertEquals(symlink, vt.results_dir)
# Repoint the symlink, but keep the vt valid (simulates the case where the underlying target's
# version has changed, so the symlink is pointed to that version, but now the version has
# reverted, so we must point it back).
os.unlink(symlink)
os.symlink(unstable_dir_name + '.other', symlink)
vt.create_results_dir()
self.assertEquals(unstable_dir_name, os.readlink(symlink))
def test_creates_stable_results_dir_prefix_symlink(self):
parent, unstable_dir_name = os.path.split(self.cache_manager._results_dir_prefix)
self.assertSetEqual({'current', unstable_dir_name}, set(os.listdir(parent)))
symlink = os.path.join(parent, 'current')
self.assertTrue(os.path.islink(symlink))
self.assertTrue(unstable_dir_name, os.readlink(symlink))
def test_check_marks_all_as_invalid_by_default(self):
a = self.make_target(':a', dependencies=[])
b = self.make_target(':b', dependencies=[a])
c = self.make_target(':c', dependencies=[b])
d = self.make_target(':d', dependencies=[c, a])
e = self.make_target(':e', dependencies=[d])
targets = [a, b, c, d, e]
ic = self.cache_manager.check(targets)
all_vts = ic.all_vts
invalid_vts = ic.invalid_vts
self.assertEquals(5, len(invalid_vts))
self.assertEquals(5, len(all_vts))
vts_targets = [vt.targets[0] for vt in all_vts]
self.assertEquals(set(targets), set(vts_targets))
def test_force_invalidate(self):
vt = self.make_vt()
self.assertTrue(vt.valid)
vt.force_invalidate()
self.assertFalse(vt.valid)
def test_invalid_vts_are_cleaned(self):
# Ensure that calling create_results_dir on an invalid target will wipe any pre-existing output.
vt = self.make_vt()
self.assertFalse(self.is_empty(vt.results_dir))
# Force invalidate should change no state under the results_dir.
vt.force_invalidate()
self.assertFalse(self.is_empty(vt.results_dir))
vt.create_results_dir()
self.assertTrue(self.has_symlinked_result_dir(vt))
self.assertTrue(self.is_empty(vt.results_dir))
def test_valid_vts_are_not_cleaned(self):
# No cleaning of results_dir occurs, since create_results_dir short-circuits if the VT is valid.
vt = self.make_vt()
self.assertFalse(self.is_empty(vt.results_dir))
file_names = os.listdir(vt.results_dir)
vt.create_results_dir()
self.assertFalse(self.is_empty(vt.results_dir))
self.assertTrue(self.has_symlinked_result_dir(vt))
# Show that the files inside the directory have not changed during the create_results_dir noop.
self.assertEqual(file_names, os.listdir(vt.results_dir))
def test_illegal_results_dir_cannot_be_updated_to_valid(self):
# A regression test for a former bug. Calling safe_mkdir(vt.results_dir, clean=True) would silently
# delete the results_dir symlink and yet leave any existing crufty content behind in the vt.current_results_dir.
# https://github.com/pantsbuild/pants/issues/4137
# https://github.com/pantsbuild/pants/issues/4051
vt = self.make_vt()
# Show all is right with the world, there is content from the task run and it's visible from both legal result_dirs.
self.assertFalse(self.is_empty(vt.results_dir))
self.assertTrue(self.has_symlinked_result_dir(vt))
vt.force_invalidate()
self.clobber_symlink(vt)
# Arg, and the resultingly unlinked current_results_dir is uncleaned. The two directories have diverging contents!
self.assertFalse(self.has_symlinked_result_dir(vt))
self.assertFalse(self.has_symlinked_result_dir(vt))
# Big consequences- the files used for Products(vt.results_dir) and the cache(vt.current_results_dir) have diverged!
self.assertNotEqual(os.listdir(vt.results_dir), os.listdir(vt.current_results_dir))
# The main protection for this is the exception raised when the cache_manager attempts to mark the VT valid.
self.assertFalse(vt.valid)
with self.assertRaises(VersionedTargetSet.IllegalResultsDir):
vt.update()
def test_exception_for_invalid_vt_result_dirs(self):
# Show that the create_results_dir will error if a previous operation changed the results_dir from a symlink.
vt = self.make_vt()
self.clobber_symlink(vt)
self.assertFalse(self.has_symlinked_result_dir(vt))
# This only is caught here if the VT is still invalid for some reason, otherwise it's caught by the update() method.
vt.force_invalidate()
with self.assertRaisesRegexp(ValueError, r'Path for link.*overwrite an existing directory*'):
vt.create_results_dir()
def test_raises_for_clobbered_symlink(self):
vt = self.make_vt()
self.clobber_symlink(vt)
with self.assertRaisesRegexp(VersionedTargetSet.IllegalResultsDir, r'The.*symlink*'):
vt.ensure_legal()
def test_raises_missing_current_results_dir(self):
vt = self.make_vt()
safe_rmtree(vt.current_results_dir)
with self.assertRaisesRegexp(VersionedTargetSet.IllegalResultsDir, r'The.*current_results_dir*'):
vt.ensure_legal()
def test_raises_both_clobbered_symlink_and_missing_current_results_dir(self):
vt = self.make_vt()
self.clobber_symlink(vt)
safe_rmtree(vt.current_results_dir)
with self.assertRaisesRegexp(VersionedTargetSet.IllegalResultsDir, r'The.*symlink*'):
vt.ensure_legal()
with self.assertRaisesRegexp(VersionedTargetSet.IllegalResultsDir, r'The.*current_results_dir*'):
vt.ensure_legal()
def test_for_illegal_vts(self):
# The update() checks this through vts.ensure_legal, checked here since those checks are on different branches.
vt = self.make_vt()
self.clobber_symlink(vt)
vts = VersionedTargetSet.from_versioned_targets([vt])
with self.assertRaises(VersionedTargetSet.IllegalResultsDir):
vts.update()
|
|
#
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google 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:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 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 HOLDER 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.
"""Node related commands"""
# pylint: disable=W0401,W0613,W0614,C0103
# W0401: Wildcard import ganeti.cli
# W0613: Unused argument, since all functions follow the same API
# W0614: Unused import %s from wildcard import (since we need cli)
# C0103: Invalid name gnt-node
import itertools
import errno
from ganeti.cli import *
from ganeti import cli
from ganeti import bootstrap
from ganeti import opcodes
from ganeti import utils
from ganeti import constants
from ganeti import errors
from ganeti import netutils
from ganeti import pathutils
from ganeti import ssh
from ganeti import compat
from ganeti import confd
from ganeti.confd import client as confd_client
#: default list of field for L{ListNodes}
_LIST_DEF_FIELDS = [
"name", "dtotal", "dfree",
"mtotal", "mnode", "mfree",
"pinst_cnt", "sinst_cnt",
]
#: Default field list for L{ListVolumes}
_LIST_VOL_DEF_FIELDS = ["node", "phys", "vg", "name", "size", "instance"]
#: default list of field for L{ListStorage}
_LIST_STOR_DEF_FIELDS = [
constants.SF_NODE,
constants.SF_TYPE,
constants.SF_NAME,
constants.SF_SIZE,
constants.SF_USED,
constants.SF_FREE,
constants.SF_ALLOCATABLE,
]
#: default list of power commands
_LIST_POWER_COMMANDS = ["on", "off", "cycle", "status"]
#: headers (and full field list) for L{ListStorage}
_LIST_STOR_HEADERS = {
constants.SF_NODE: "Node",
constants.SF_TYPE: "Type",
constants.SF_NAME: "Name",
constants.SF_SIZE: "Size",
constants.SF_USED: "Used",
constants.SF_FREE: "Free",
constants.SF_ALLOCATABLE: "Allocatable",
}
#: User-facing storage unit types
_USER_STORAGE_TYPE = {
constants.ST_FILE: "file",
constants.ST_LVM_PV: "lvm-pv",
constants.ST_LVM_VG: "lvm-vg",
constants.ST_SHARED_FILE: "sharedfile",
constants.ST_GLUSTER: "gluster",
}
_STORAGE_TYPE_OPT = \
cli_option("-t", "--storage-type",
dest="user_storage_type",
choices=_USER_STORAGE_TYPE.keys(),
default=None,
metavar="STORAGE_TYPE",
help=("Storage type (%s)" %
utils.CommaJoin(_USER_STORAGE_TYPE.keys())))
_REPAIRABLE_STORAGE_TYPES = \
[st for st, so in constants.VALID_STORAGE_OPERATIONS.iteritems()
if constants.SO_FIX_CONSISTENCY in so]
_MODIFIABLE_STORAGE_TYPES = constants.MODIFIABLE_STORAGE_FIELDS.keys()
_OOB_COMMAND_ASK = compat.UniqueFrozenset([
constants.OOB_POWER_OFF,
constants.OOB_POWER_CYCLE,
])
_ENV_OVERRIDE = compat.UniqueFrozenset(["list"])
NONODE_SETUP_OPT = cli_option("--no-node-setup", default=True,
action="store_false", dest="node_setup",
help=("Do not make initial SSH setup on remote"
" node (needs to be done manually)"))
IGNORE_STATUS_OPT = cli_option("--ignore-status", default=False,
action="store_true", dest="ignore_status",
help=("Ignore the Node(s) offline status"
" (potentially DANGEROUS)"))
def ConvertStorageType(user_storage_type):
"""Converts a user storage type to its internal name.
"""
try:
return _USER_STORAGE_TYPE[user_storage_type]
except KeyError:
raise errors.OpPrereqError("Unknown storage type: %s" % user_storage_type,
errors.ECODE_INVAL)
def _TryReadFile(path):
"""Tries to read a file.
If the file is not found, C{None} is returned.
@type path: string
@param path: Filename
@rtype: None or string
@todo: Consider adding a generic ENOENT wrapper
"""
try:
return utils.ReadFile(path)
except EnvironmentError, err:
if err.errno == errno.ENOENT:
return None
else:
raise
def _ReadSshKeys(keyfiles, _tostderr_fn=ToStderr):
"""Reads the DSA SSH keys according to C{keyfiles}.
@type keyfiles: dict
@param keyfiles: Dictionary with keys of L{constants.SSHK_ALL} and two-values
tuples (private and public key file)
@rtype: list
@return: List of three-values tuples (L{constants.SSHK_ALL}, private and
public key as strings)
"""
result = []
for (kind, (private_file, public_file)) in keyfiles.items():
private_key = _TryReadFile(private_file)
public_key = _TryReadFile(public_file)
if public_key and private_key:
result.append((kind, private_key, public_key))
elif public_key or private_key:
_tostderr_fn("Couldn't find a complete set of keys for kind '%s';"
" files '%s' and '%s'", kind, private_file, public_file)
return result
def _SetupSSH(options, cluster_name, node, ssh_port, cl):
"""Configures a destination node's SSH daemon.
@param options: Command line options
@type cluster_name
@param cluster_name: Cluster name
@type node: string
@param node: Destination node name
@type ssh_port: int
@param ssh_port: Destination node ssh port
@param cl: luxi client
"""
# Retrieve the list of master and master candidates
candidate_filter = ["|", ["=", "role", "M"], ["=", "role", "C"]]
result = cl.Query(constants.QR_NODE, ["uuid"], candidate_filter)
if len(result.data) < 1:
raise errors.OpPrereqError("No master or master candidate node is found.")
candidates = [uuid for ((_, uuid),) in result.data]
candidate_keys = ssh.QueryPubKeyFile(candidates)
if options.force_join:
ToStderr("The \"--force-join\" option is no longer supported and will be"
" ignored.")
host_keys = _ReadSshKeys(constants.SSH_DAEMON_KEYFILES)
(_, root_keyfiles) = \
ssh.GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=False, dircheck=False)
dsa_root_keyfiles = dict((kind, value) for (kind, value)
in root_keyfiles.items()
if kind == constants.SSHK_DSA)
root_keys = _ReadSshKeys(dsa_root_keyfiles)
(_, cert_pem) = \
utils.ExtractX509Certificate(utils.ReadFile(pathutils.NODED_CERT_FILE))
(ssh_key_type, ssh_key_bits) = \
cl.QueryConfigValues(["ssh_key_type", "ssh_key_bits"])
data = {
constants.SSHS_CLUSTER_NAME: cluster_name,
constants.SSHS_NODE_DAEMON_CERTIFICATE: cert_pem,
constants.SSHS_SSH_HOST_KEY: host_keys,
constants.SSHS_SSH_ROOT_KEY: root_keys,
constants.SSHS_SSH_AUTHORIZED_KEYS: candidate_keys,
constants.SSHS_SSH_KEY_TYPE: ssh_key_type,
constants.SSHS_SSH_KEY_BITS: ssh_key_bits,
}
ssh.RunSshCmdWithStdin(cluster_name, node, pathutils.PREPARE_NODE_JOIN,
ssh_port, data,
debug=options.debug, verbose=options.verbose,
use_cluster_key=False, ask_key=options.ssh_key_check,
strict_host_check=options.ssh_key_check)
(_, pub_keyfile) = root_keyfiles[ssh_key_type]
pub_key = ssh.ReadRemoteSshPubKey(pub_keyfile, node, cluster_name, ssh_port,
options.ssh_key_check,
options.ssh_key_check)
# Unfortunately, we have to add the key with the node name rather than
# the node's UUID here, because at this point, we do not have a UUID yet.
# The entry will be corrected in noded later.
ssh.AddPublicKey(node, pub_key)
@UsesRPC
def AddNode(opts, args):
"""Add a node to the cluster.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the new node name
@rtype: int
@return: the desired exit code
"""
cl = GetClient()
node = netutils.GetHostname(name=args[0]).name
readd = opts.readd
# Retrieve relevant parameters of the node group.
ssh_port = None
try:
# Passing [] to QueryGroups means query the default group:
node_groups = [opts.nodegroup] if opts.nodegroup is not None else []
output = cl.QueryGroups(names=node_groups, fields=["ndp/ssh_port"],
use_locking=False)
(ssh_port, ) = output[0]
except (errors.OpPrereqError, errors.OpExecError):
pass
try:
output = cl.QueryNodes(names=[node],
fields=["name", "sip", "master",
"ndp/ssh_port"],
use_locking=False)
if len(output) == 0:
node_exists = ""
sip = None
else:
node_exists, sip, is_master, ssh_port = output[0]
except (errors.OpPrereqError, errors.OpExecError):
node_exists = ""
sip = None
if readd:
if not node_exists:
ToStderr("Node %s not in the cluster"
" - please retry without '--readd'", node)
return 1
if is_master:
ToStderr("Node %s is the master, cannot readd", node)
return 1
else:
if node_exists:
ToStderr("Node %s already in the cluster (as %s)"
" - please retry with '--readd'", node, node_exists)
return 1
sip = opts.secondary_ip
# read the cluster name from the master
(cluster_name, ) = cl.QueryConfigValues(["cluster_name"])
if not opts.node_setup:
ToStdout("-- WARNING -- \n"
"The option --no-node-setup is disabled. Whether or not the\n"
"SSH setup is manipulated while adding a node is determined\n"
"by the 'modify_ssh_setup' value in the cluster-wide\n"
"configuration instead.\n")
(modify_ssh_setup, ) = \
cl.QueryConfigValues(["modify_ssh_setup"])
if modify_ssh_setup:
ToStderr("-- WARNING -- \n"
"Performing this operation is going to perform the following\n"
"changes to the target machine (%s) and the current cluster\n"
"nodes:\n"
"* A new SSH daemon key pair is generated on the target machine.\n"
"* The public SSH keys of all master candidates of the cluster\n"
" are added to the target machine's 'authorized_keys' file.\n"
"* In case the target machine is a master candidate, its newly\n"
" generated public SSH key will be distributed to all other\n"
" cluster nodes.\n", node)
if modify_ssh_setup:
_SetupSSH(opts, cluster_name, node, ssh_port, cl)
bootstrap.SetupNodeDaemon(opts, cluster_name, node, ssh_port)
if opts.disk_state:
disk_state = utils.FlatToDict(opts.disk_state)
else:
disk_state = {}
hv_state = dict(opts.hv_state)
op = opcodes.OpNodeAdd(node_name=args[0], secondary_ip=sip,
readd=opts.readd, group=opts.nodegroup,
vm_capable=opts.vm_capable, ndparams=opts.ndparams,
master_capable=opts.master_capable,
disk_state=disk_state,
hv_state=hv_state,
node_setup=modify_ssh_setup,
verbose=opts.verbose,
debug=opts.debug > 0)
SubmitOpCode(op, opts=opts)
def ListNodes(opts, args):
"""List nodes and their properties.
@param opts: the command line options selected by the user
@type args: list
@param args: nodes to list, or empty for all
@rtype: int
@return: the desired exit code
"""
selected_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
fmtoverride = dict.fromkeys(["pinst_list", "sinst_list", "tags"],
(",".join, False))
cl = GetClient()
return GenericList(constants.QR_NODE, selected_fields, args, opts.units,
opts.separator, not opts.no_headers,
format_override=fmtoverride, verbose=opts.verbose,
force_filter=opts.force_filter, cl=cl)
def ListNodeFields(opts, args):
"""List node fields.
@param opts: the command line options selected by the user
@type args: list
@param args: fields to list, or empty for all
@rtype: int
@return: the desired exit code
"""
cl = GetClient()
return GenericListFields(constants.QR_NODE, args, opts.separator,
not opts.no_headers, cl=cl)
def EvacuateNode(opts, args):
"""Relocate all secondary instance from a node.
@param opts: the command line options selected by the user
@type args: list
@param args: should be an empty list
@rtype: int
@return: the desired exit code
"""
if opts.dst_node is not None:
ToStderr("New secondary node given (disabling iallocator), hence evacuating"
" secondary instances only.")
opts.secondary_only = True
opts.primary_only = False
if opts.secondary_only and opts.primary_only:
raise errors.OpPrereqError("Only one of the --primary-only and"
" --secondary-only options can be passed",
errors.ECODE_INVAL)
elif opts.primary_only:
mode = constants.NODE_EVAC_PRI
elif opts.secondary_only:
mode = constants.NODE_EVAC_SEC
else:
mode = constants.NODE_EVAC_ALL
# Determine affected instances
fields = []
if not opts.secondary_only:
fields.append("pinst_list")
if not opts.primary_only:
fields.append("sinst_list")
cl = GetClient()
qcl = GetClient()
result = qcl.QueryNodes(names=args, fields=fields, use_locking=False)
qcl.Close()
instances = set(itertools.chain(*itertools.chain(*itertools.chain(result))))
if not instances:
# No instances to evacuate
ToStderr("No instances to evacuate on node(s) %s, exiting.",
utils.CommaJoin(args))
return constants.EXIT_SUCCESS
if not (opts.force or
AskUser("Relocate instance(s) %s from node(s) %s?" %
(utils.CommaJoin(utils.NiceSort(instances)),
utils.CommaJoin(args)))):
return constants.EXIT_CONFIRMATION
# Evacuate node
op = opcodes.OpNodeEvacuate(node_name=args[0], mode=mode,
remote_node=opts.dst_node,
iallocator=opts.iallocator,
early_release=opts.early_release,
ignore_soft_errors=opts.ignore_soft_errors)
result = SubmitOrSend(op, opts, cl=cl)
# Keep track of submitted jobs
jex = JobExecutor(cl=cl, opts=opts)
for (status, job_id) in result[constants.JOB_IDS_KEY]:
jex.AddJobId(None, status, job_id)
results = jex.GetResults()
bad_cnt = len([row for row in results if not row[0]])
if bad_cnt == 0:
ToStdout("All instances evacuated successfully.")
rcode = constants.EXIT_SUCCESS
else:
ToStdout("There were %s errors during the evacuation.", bad_cnt)
rcode = constants.EXIT_FAILURE
return rcode
def FailoverNode(opts, args):
"""Failover all primary instance on a node.
@param opts: the command line options selected by the user
@type args: list
@param args: should be an empty list
@rtype: int
@return: the desired exit code
"""
cl = GetClient()
force = opts.force
selected_fields = ["name", "pinst_list"]
# these fields are static data anyway, so it doesn't matter, but
# locking=True should be safer
qcl = GetClient()
result = qcl.QueryNodes(names=args, fields=selected_fields,
use_locking=False)
qcl.Close()
node, pinst = result[0]
if not pinst:
ToStderr("No primary instances on node %s, exiting.", node)
return 0
pinst = utils.NiceSort(pinst)
retcode = 0
if not force and not AskUser("Fail over instance(s) %s?" %
(",".join("'%s'" % name for name in pinst))):
return 2
jex = JobExecutor(cl=cl, opts=opts)
for iname in pinst:
op = opcodes.OpInstanceFailover(instance_name=iname,
ignore_consistency=opts.ignore_consistency,
iallocator=opts.iallocator)
jex.QueueJob(iname, op)
results = jex.GetResults()
bad_cnt = len([row for row in results if not row[0]])
if bad_cnt == 0:
ToStdout("All %d instance(s) failed over successfully.", len(results))
else:
ToStdout("There were errors during the failover:\n"
"%d error(s) out of %d instance(s).", bad_cnt, len(results))
return retcode
def MigrateNode(opts, args):
"""Migrate all primary instance on a node.
"""
cl = GetClient()
force = opts.force
selected_fields = ["name", "pinst_list"]
qcl = GetClient()
result = qcl.QueryNodes(names=args, fields=selected_fields, use_locking=False)
qcl.Close()
((node, pinst), ) = result
if not pinst:
ToStdout("No primary instances on node %s, exiting." % node)
return 0
pinst = utils.NiceSort(pinst)
if not (force or
AskUser("Migrate instance(s) %s?" %
utils.CommaJoin(utils.NiceSort(pinst)))):
return constants.EXIT_CONFIRMATION
# this should be removed once --non-live is deprecated
if not opts.live and opts.migration_mode is not None:
raise errors.OpPrereqError("Only one of the --non-live and "
"--migration-mode options can be passed",
errors.ECODE_INVAL)
if not opts.live: # --non-live passed
mode = constants.HT_MIGRATION_NONLIVE
else:
mode = opts.migration_mode
op = opcodes.OpNodeMigrate(node_name=args[0], mode=mode,
iallocator=opts.iallocator,
target_node=opts.dst_node,
allow_runtime_changes=opts.allow_runtime_chgs,
ignore_ipolicy=opts.ignore_ipolicy)
result = SubmitOrSend(op, opts, cl=cl)
# Keep track of submitted jobs
jex = JobExecutor(cl=cl, opts=opts)
for (status, job_id) in result[constants.JOB_IDS_KEY]:
jex.AddJobId(None, status, job_id)
results = jex.GetResults()
bad_cnt = len([row for row in results if not row[0]])
if bad_cnt == 0:
ToStdout("All instances migrated successfully.")
rcode = constants.EXIT_SUCCESS
else:
ToStdout("There were %s errors during the node migration.", bad_cnt)
rcode = constants.EXIT_FAILURE
return rcode
def _FormatNodeInfo(node_info):
"""Format node information for L{cli.PrintGenericInfo()}.
"""
(name, primary_ip, secondary_ip, pinst, sinst, is_mc, drained, offline,
master_capable, vm_capable, powered, ndparams, ndparams_custom) = node_info
info = [
("Node name", name),
("primary ip", primary_ip),
("secondary ip", secondary_ip),
("master candidate", is_mc),
("drained", drained),
("offline", offline),
]
if powered is not None:
info.append(("powered", powered))
info.extend([
("master_capable", master_capable),
("vm_capable", vm_capable),
])
if vm_capable:
info.extend([
("primary for instances",
[iname for iname in utils.NiceSort(pinst)]),
("secondary for instances",
[iname for iname in utils.NiceSort(sinst)]),
])
info.append(("node parameters",
FormatParamsDictInfo(ndparams_custom, ndparams)))
return info
def ShowNodeConfig(opts, args):
"""Show node information.
@param opts: the command line options selected by the user
@type args: list
@param args: should either be an empty list, in which case
we show information about all nodes, or should contain
a list of nodes to be queried for information
@rtype: int
@return: the desired exit code
"""
cl = GetClient()
result = cl.QueryNodes(fields=["name", "pip", "sip",
"pinst_list", "sinst_list",
"master_candidate", "drained", "offline",
"master_capable", "vm_capable", "powered",
"ndparams", "custom_ndparams"],
names=args, use_locking=False)
PrintGenericInfo([
_FormatNodeInfo(node_info)
for node_info in result
])
return 0
def RemoveNode(opts, args):
"""Remove a node from the cluster.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the name of
the node to be removed
@rtype: int
@return: the desired exit code
"""
op = opcodes.OpNodeRemove(node_name=args[0],
debug=opts.debug > 0,
verbose=opts.verbose)
SubmitOpCode(op, opts=opts)
return 0
def PowercycleNode(opts, args):
"""Remove a node from the cluster.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the name of
the node to be removed
@rtype: int
@return: the desired exit code
"""
node = args[0]
if (not opts.confirm and
not AskUser("Are you sure you want to hard powercycle node %s?" % node)):
return 2
op = opcodes.OpNodePowercycle(node_name=node, force=opts.force)
result = SubmitOrSend(op, opts)
if result:
ToStderr(result)
return 0
def PowerNode(opts, args):
"""Change/ask power state of a node.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the name of
the node to be removed
@rtype: int
@return: the desired exit code
"""
command = args.pop(0)
if opts.no_headers:
headers = None
else:
headers = {"node": "Node", "status": "Status"}
if command not in _LIST_POWER_COMMANDS:
ToStderr("power subcommand %s not supported." % command)
return constants.EXIT_FAILURE
oob_command = "power-%s" % command
if oob_command in _OOB_COMMAND_ASK:
if not args:
ToStderr("Please provide at least one node for this command")
return constants.EXIT_FAILURE
elif not opts.force and not ConfirmOperation(args, "nodes",
"power %s" % command):
return constants.EXIT_FAILURE
assert len(args) > 0
opcodelist = []
if not opts.ignore_status and oob_command == constants.OOB_POWER_OFF:
# TODO: This is a little ugly as we can't catch and revert
for node in args:
opcodelist.append(opcodes.OpNodeSetParams(node_name=node, offline=True,
auto_promote=opts.auto_promote))
opcodelist.append(opcodes.OpOobCommand(node_names=args,
command=oob_command,
ignore_status=opts.ignore_status,
timeout=opts.oob_timeout,
power_delay=opts.power_delay))
cli.SetGenericOpcodeOpts(opcodelist, opts)
job_id = cli.SendJob(opcodelist)
# We just want the OOB Opcode status
# If it fails PollJob gives us the error message in it
result = cli.PollJob(job_id)[-1]
errs = 0
data = []
for node_result in result:
(node_tuple, data_tuple) = node_result
(_, node_name) = node_tuple
(data_status, data_node) = data_tuple
if data_status == constants.RS_NORMAL:
if oob_command == constants.OOB_POWER_STATUS:
if data_node[constants.OOB_POWER_STATUS_POWERED]:
text = "powered"
else:
text = "unpowered"
data.append([node_name, text])
else:
# We don't expect data here, so we just say, it was successfully invoked
data.append([node_name, "invoked"])
else:
errs += 1
data.append([node_name, cli.FormatResultError(data_status, True)])
data = GenerateTable(separator=opts.separator, headers=headers,
fields=["node", "status"], data=data)
for line in data:
ToStdout(line)
if errs:
return constants.EXIT_FAILURE
else:
return constants.EXIT_SUCCESS
def Health(opts, args):
"""Show health of a node using OOB.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the name of
the node to be removed
@rtype: int
@return: the desired exit code
"""
op = opcodes.OpOobCommand(node_names=args, command=constants.OOB_HEALTH,
timeout=opts.oob_timeout)
result = SubmitOpCode(op, opts=opts)
if opts.no_headers:
headers = None
else:
headers = {"node": "Node", "status": "Status"}
errs = 0
data = []
for node_result in result:
(node_tuple, data_tuple) = node_result
(_, node_name) = node_tuple
(data_status, data_node) = data_tuple
if data_status == constants.RS_NORMAL:
data.append([node_name, "%s=%s" % tuple(data_node[0])])
for item, status in data_node[1:]:
data.append(["", "%s=%s" % (item, status)])
else:
errs += 1
data.append([node_name, cli.FormatResultError(data_status, True)])
data = GenerateTable(separator=opts.separator, headers=headers,
fields=["node", "status"], data=data)
for line in data:
ToStdout(line)
if errs:
return constants.EXIT_FAILURE
else:
return constants.EXIT_SUCCESS
def ListVolumes(opts, args):
"""List logical volumes on node(s).
@param opts: the command line options selected by the user
@type args: list
@param args: should either be an empty list, in which case
we list data for all nodes, or contain a list of nodes
to display data only for those
@rtype: int
@return: the desired exit code
"""
selected_fields = ParseFields(opts.output, _LIST_VOL_DEF_FIELDS)
op = opcodes.OpNodeQueryvols(nodes=args, output_fields=selected_fields)
output = SubmitOpCode(op, opts=opts)
if not opts.no_headers:
headers = {"node": "Node", "phys": "PhysDev",
"vg": "VG", "name": "Name",
"size": "Size", "instance": "Instance"}
else:
headers = None
unitfields = ["size"]
numfields = ["size"]
data = GenerateTable(separator=opts.separator, headers=headers,
fields=selected_fields, unitfields=unitfields,
numfields=numfields, data=output, units=opts.units)
for line in data:
ToStdout(line)
return 0
def ListStorage(opts, args):
"""List physical volumes on node(s).
@param opts: the command line options selected by the user
@type args: list
@param args: should either be an empty list, in which case
we list data for all nodes, or contain a list of nodes
to display data only for those
@rtype: int
@return: the desired exit code
"""
selected_fields = ParseFields(opts.output, _LIST_STOR_DEF_FIELDS)
op = opcodes.OpNodeQueryStorage(nodes=args,
storage_type=opts.user_storage_type,
output_fields=selected_fields)
output = SubmitOpCode(op, opts=opts)
if not opts.no_headers:
headers = {
constants.SF_NODE: "Node",
constants.SF_TYPE: "Type",
constants.SF_NAME: "Name",
constants.SF_SIZE: "Size",
constants.SF_USED: "Used",
constants.SF_FREE: "Free",
constants.SF_ALLOCATABLE: "Allocatable",
}
else:
headers = None
unitfields = [constants.SF_SIZE, constants.SF_USED, constants.SF_FREE]
numfields = [constants.SF_SIZE, constants.SF_USED, constants.SF_FREE]
# change raw values to nicer strings
for row in output:
for idx, field in enumerate(selected_fields):
val = row[idx]
if field == constants.SF_ALLOCATABLE:
if val:
val = "Y"
else:
val = "N"
row[idx] = str(val)
data = GenerateTable(separator=opts.separator, headers=headers,
fields=selected_fields, unitfields=unitfields,
numfields=numfields, data=output, units=opts.units)
for line in data:
ToStdout(line)
return 0
def ModifyStorage(opts, args):
"""Modify storage volume on a node.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain 3 items: node name, storage type and volume name
@rtype: int
@return: the desired exit code
"""
(node_name, user_storage_type, volume_name) = args
storage_type = ConvertStorageType(user_storage_type)
changes = {}
if opts.allocatable is not None:
changes[constants.SF_ALLOCATABLE] = opts.allocatable
if changes:
op = opcodes.OpNodeModifyStorage(node_name=node_name,
storage_type=storage_type,
name=volume_name,
changes=changes)
SubmitOrSend(op, opts)
else:
ToStderr("No changes to perform, exiting.")
def RepairStorage(opts, args):
"""Repairs a storage volume on a node.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain 3 items: node name, storage type and volume name
@rtype: int
@return: the desired exit code
"""
(node_name, user_storage_type, volume_name) = args
storage_type = ConvertStorageType(user_storage_type)
op = opcodes.OpRepairNodeStorage(node_name=node_name,
storage_type=storage_type,
name=volume_name,
ignore_consistency=opts.ignore_consistency)
SubmitOrSend(op, opts)
def SetNodeParams(opts, args):
"""Modifies a node.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the node name
@rtype: int
@return: the desired exit code
"""
all_changes = [opts.master_candidate, opts.drained, opts.offline,
opts.master_capable, opts.vm_capable, opts.secondary_ip,
opts.ndparams]
if (all_changes.count(None) == len(all_changes) and
not (opts.hv_state or opts.disk_state)):
ToStderr("Please give at least one of the parameters.")
return 1
if opts.disk_state:
disk_state = utils.FlatToDict(opts.disk_state)
else:
disk_state = {}
hv_state = dict(opts.hv_state)
op = opcodes.OpNodeSetParams(node_name=args[0],
master_candidate=opts.master_candidate,
offline=opts.offline,
drained=opts.drained,
master_capable=opts.master_capable,
vm_capable=opts.vm_capable,
secondary_ip=opts.secondary_ip,
force=opts.force,
ndparams=opts.ndparams,
auto_promote=opts.auto_promote,
powered=opts.node_powered,
hv_state=hv_state,
disk_state=disk_state,
verbose=opts.verbose,
debug=opts.debug > 0)
# even if here we process the result, we allow submit only
result = SubmitOrSend(op, opts)
if result:
ToStdout("Modified node %s", args[0])
for param, data in result:
ToStdout(" - %-5s -> %s", param, data)
return 0
def RestrictedCommand(opts, args):
"""Runs a remote command on node(s).
@param opts: Command line options selected by user
@type args: list
@param args: Command line arguments
@rtype: int
@return: Exit code
"""
cl = GetClient()
if len(args) > 1 or opts.nodegroup:
# Expand node names
nodes = GetOnlineNodes(nodes=args[1:], cl=cl, nodegroup=opts.nodegroup)
else:
raise errors.OpPrereqError("Node group or node names must be given",
errors.ECODE_INVAL)
op = opcodes.OpRestrictedCommand(command=args[0], nodes=nodes,
use_locking=opts.do_locking)
result = SubmitOrSend(op, opts, cl=cl)
exit_code = constants.EXIT_SUCCESS
for (node, (status, text)) in zip(nodes, result):
ToStdout("------------------------------------------------")
if status:
if opts.show_machine_names:
for line in text.splitlines():
ToStdout("%s: %s", node, line)
else:
ToStdout("Node: %s", node)
ToStdout(text)
else:
exit_code = constants.EXIT_FAILURE
ToStdout(text)
return exit_code
def RepairCommand(opts, args):
cl = GetClient()
if opts.input:
inp = opts.input.decode('string_escape')
else:
inp = None
op = opcodes.OpRepairCommand(command=args[0], node_name=args[1],
input=inp)
result = SubmitOrSend(op, opts, cl=cl)
print result
return constants.EXIT_SUCCESS
class ReplyStatus(object):
"""Class holding a reply status for synchronous confd clients.
"""
def __init__(self):
self.failure = True
self.answer = False
def ListDrbd(opts, args):
"""Modifies a node.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the node name
@rtype: int
@return: the desired exit code
"""
if len(args) != 1:
ToStderr("Please give one (and only one) node.")
return constants.EXIT_FAILURE
status = ReplyStatus()
def ListDrbdConfdCallback(reply):
"""Callback for confd queries"""
if reply.type == confd_client.UPCALL_REPLY:
answer = reply.server_reply.answer
reqtype = reply.orig_request.type
if reqtype == constants.CONFD_REQ_NODE_DRBD:
if reply.server_reply.status != constants.CONFD_REPL_STATUS_OK:
ToStderr("Query gave non-ok status '%s': %s" %
(reply.server_reply.status,
reply.server_reply.answer))
status.failure = True
return
if not confd.HTNodeDrbd(answer):
ToStderr("Invalid response from server: expected %s, got %s",
confd.HTNodeDrbd, answer)
status.failure = True
else:
status.failure = False
status.answer = answer
else:
ToStderr("Unexpected reply %s!?", reqtype)
status.failure = True
node = args[0]
hmac = utils.ReadFile(pathutils.CONFD_HMAC_KEY)
filter_callback = confd_client.ConfdFilterCallback(ListDrbdConfdCallback)
counting_callback = confd_client.ConfdCountingCallback(filter_callback)
cf_client = confd_client.ConfdClient(hmac, [constants.IP4_ADDRESS_LOCALHOST],
counting_callback)
req = confd_client.ConfdClientRequest(type=constants.CONFD_REQ_NODE_DRBD,
query=node)
def DoConfdRequestReply(req):
counting_callback.RegisterQuery(req.rsalt)
cf_client.SendRequest(req, async=False)
while not counting_callback.AllAnswered():
if not cf_client.ReceiveReply():
ToStderr("Did not receive all expected confd replies")
break
DoConfdRequestReply(req)
if status.failure:
return constants.EXIT_FAILURE
fields = ["node", "minor", "instance", "disk", "role", "peer"]
if opts.no_headers:
headers = None
else:
headers = {"node": "Node", "minor": "Minor", "instance": "Instance",
"disk": "Disk", "role": "Role", "peer": "PeerNode"}
data = GenerateTable(separator=opts.separator, headers=headers,
fields=fields, data=sorted(status.answer),
numfields=["minor"])
for line in data:
ToStdout(line)
return constants.EXIT_SUCCESS
commands = {
"add": (
AddNode, [ArgHost(min=1, max=1)],
[SECONDARY_IP_OPT, READD_OPT, NOSSH_KEYCHECK_OPT, NODE_FORCE_JOIN_OPT,
NONODE_SETUP_OPT, VERBOSE_OPT, NODEGROUP_OPT, PRIORITY_OPT,
CAPAB_MASTER_OPT, CAPAB_VM_OPT, NODE_PARAMS_OPT, HV_STATE_OPT,
DISK_STATE_OPT],
"[-s ip] [--readd] [--no-ssh-key-check] [--force-join]"
" [--no-node-setup] [--verbose] [--network] [--debug] <node_name>",
"Add a node to the cluster"),
"evacuate": (
EvacuateNode, ARGS_ONE_NODE,
[FORCE_OPT, IALLOCATOR_OPT, IGNORE_SOFT_ERRORS_OPT, NEW_SECONDARY_OPT,
EARLY_RELEASE_OPT, PRIORITY_OPT, PRIMARY_ONLY_OPT, SECONDARY_ONLY_OPT]
+ SUBMIT_OPTS,
"[-f] {-I <iallocator> | -n <dst>} [-p | -s] [options...] <node>",
"Relocate the primary and/or secondary instances from a node"),
"failover": (
FailoverNode, ARGS_ONE_NODE, [FORCE_OPT, IGNORE_CONSIST_OPT,
IALLOCATOR_OPT, PRIORITY_OPT],
"[-f] <node>",
"Stops the primary instances on a node and start them on their"
" secondary node (only for instances with drbd disk template)"),
"migrate": (
MigrateNode, ARGS_ONE_NODE,
[FORCE_OPT, NONLIVE_OPT, MIGRATION_MODE_OPT, DST_NODE_OPT,
IALLOCATOR_OPT, PRIORITY_OPT, IGNORE_IPOLICY_OPT,
NORUNTIME_CHGS_OPT] + SUBMIT_OPTS,
"[-f] <node>",
"Migrate all the primary instance on a node away from it"
" (only for instances of type drbd)"),
"info": (
ShowNodeConfig, ARGS_MANY_NODES, [],
"[<node_name>...]", "Show information about the node(s)"),
"list": (
ListNodes, ARGS_MANY_NODES,
[NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, VERBOSE_OPT,
FORCE_FILTER_OPT],
"[nodes...]",
"Lists the nodes in the cluster. The available fields can be shown using"
" the \"list-fields\" command (see the man page for details)."
" The default field list is (in order): %s." %
utils.CommaJoin(_LIST_DEF_FIELDS)),
"list-fields": (
ListNodeFields, [ArgUnknown()],
[NOHDR_OPT, SEP_OPT],
"[fields...]",
"Lists all available fields for nodes"),
"modify": (
SetNodeParams, ARGS_ONE_NODE,
[FORCE_OPT] + SUBMIT_OPTS +
[MC_OPT, DRAINED_OPT, OFFLINE_OPT,
CAPAB_MASTER_OPT, CAPAB_VM_OPT, SECONDARY_IP_OPT,
AUTO_PROMOTE_OPT, DRY_RUN_OPT, PRIORITY_OPT, NODE_PARAMS_OPT,
NODE_POWERED_OPT, HV_STATE_OPT, DISK_STATE_OPT, VERBOSE_OPT],
"<node_name>", "Alters the parameters of a node"),
"powercycle": (
PowercycleNode, ARGS_ONE_NODE,
[FORCE_OPT, CONFIRM_OPT, DRY_RUN_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
"<node_name>", "Tries to forcefully powercycle a node"),
"power": (
PowerNode,
[ArgChoice(min=1, max=1, choices=_LIST_POWER_COMMANDS),
ArgNode()],
SUBMIT_OPTS +
[AUTO_PROMOTE_OPT, PRIORITY_OPT,
IGNORE_STATUS_OPT, FORCE_OPT, NOHDR_OPT, SEP_OPT, OOB_TIMEOUT_OPT,
POWER_DELAY_OPT],
"on|off|cycle|status [nodes...]",
"Change power state of node by calling out-of-band helper."),
"remove": (
RemoveNode, ARGS_ONE_NODE, [DRY_RUN_OPT, PRIORITY_OPT, VERBOSE_OPT],
"[--verbose] [--debug] <node_name>", "Removes a node from the cluster"),
"volumes": (
ListVolumes, [ArgNode()],
[NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, PRIORITY_OPT],
"[<node_name>...]", "List logical volumes on node(s)"),
"list-storage": (
ListStorage, ARGS_MANY_NODES,
[NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, _STORAGE_TYPE_OPT,
PRIORITY_OPT],
"[<node_name>...]", "List physical volumes on node(s). The available"
" fields are (see the man page for details): %s." %
(utils.CommaJoin(_LIST_STOR_HEADERS))),
"modify-storage": (
ModifyStorage,
[ArgNode(min=1, max=1),
ArgChoice(min=1, max=1, choices=_MODIFIABLE_STORAGE_TYPES),
ArgFile(min=1, max=1)],
[ALLOCATABLE_OPT, DRY_RUN_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
"<node_name> <storage_type> <name>", "Modify storage volume on a node"),
"repair-storage": (
RepairStorage,
[ArgNode(min=1, max=1),
ArgChoice(min=1, max=1, choices=_REPAIRABLE_STORAGE_TYPES),
ArgFile(min=1, max=1)],
[IGNORE_CONSIST_OPT, DRY_RUN_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
"<node_name> <storage_type> <name>",
"Repairs a storage volume on a node"),
"list-tags": (
ListTags, ARGS_ONE_NODE, [],
"<node_name>", "List the tags of the given node"),
"add-tags": (
AddTags, [ArgNode(min=1, max=1), ArgUnknown()],
[TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
"<node_name> tag...", "Add tags to the given node"),
"remove-tags": (
RemoveTags, [ArgNode(min=1, max=1), ArgUnknown()],
[TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
"<node_name> tag...", "Remove tags from the given node"),
"health": (
Health, ARGS_MANY_NODES,
[NOHDR_OPT, SEP_OPT, PRIORITY_OPT, OOB_TIMEOUT_OPT],
"[<node_name>...]", "List health of node(s) using out-of-band"),
"list-drbd": (
ListDrbd, ARGS_ONE_NODE,
[NOHDR_OPT, SEP_OPT],
"[<node_name>]", "Query the list of used DRBD minors on the given node"),
"restricted-command": (
RestrictedCommand, [ArgUnknown(min=1, max=1)] + ARGS_MANY_NODES,
[SYNC_OPT, PRIORITY_OPT] + SUBMIT_OPTS + [SHOW_MACHINE_OPT, NODEGROUP_OPT],
"<command> <node_name> [<node_name>...]",
"Executes a restricted command on node(s)"),
"repair-command": (
RepairCommand, [ArgUnknown(min=1, max=1), ArgNode(min=1, max=1)],
[SUBMIT_OPT, INPUT_OPT], "{--input <input>} <command> <node_name>",
"Executes a repair command on a node"),
}
#: dictionary with aliases for commands
aliases = {
"show": "info",
}
def Main():
return GenericMain(commands, aliases=aliases,
override={"tag_type": constants.TAG_NODE},
env_override=_ENV_OVERRIDE)
|
|
# coding: utf-8
"""
OpenAPI spec version:
Generated by: https://github.com/swagger-api/swagger-codegen.git
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.
"""
from pprint import pformat
from six import iteritems
import re
class V1LimitRange(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
operations = [
{
'class': 'ApiV1',
'type': 'update',
'method': 'replace_namespaced_limitrange',
'namespaced': True
},
{
'class': 'ApiV1',
'type': 'delete',
'method': 'delete_namespaced_limitrange',
'namespaced': True
},
{
'class': 'ApiV1',
'type': 'read',
'method': 'get_namespaced_limitrange',
'namespaced': True
},
{
'class': 'ApiV1',
'type': 'create',
'method': 'create_namespaced_limitrange',
'namespaced': True
},
{
'class': 'ApiV1',
'type': 'create',
'method': 'create_limitrange',
'namespaced': False
},
]
# The key is attribute name
# and the value is attribute type.
swagger_types = {
'kind': 'str',
'api_version': 'str',
'metadata': 'V1ObjectMeta',
'spec': 'V1LimitRangeSpec'
}
# The key is attribute name
# and the value is json key in definition.
attribute_map = {
'kind': 'kind',
'api_version': 'apiVersion',
'metadata': 'metadata',
'spec': 'spec'
}
def __init__(self, kind=None, api_version=None, metadata=None, spec=None):
"""
V1LimitRange - a model defined in Swagger
"""
self._kind = kind
self._api_version = api_version
self._metadata = metadata
self._spec = spec
@property
def kind(self):
"""
Gets the kind of this V1LimitRange.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds
:return: The kind of this V1LimitRange.
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""
Sets the kind of this V1LimitRange.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds
:param kind: The kind of this V1LimitRange.
:type: str
"""
self._kind = kind
@property
def api_version(self):
"""
Gets the api_version of this V1LimitRange.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#resources
:return: The api_version of this V1LimitRange.
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""
Sets the api_version of this V1LimitRange.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#resources
:param api_version: The api_version of this V1LimitRange.
:type: str
"""
self._api_version = api_version
@property
def metadata(self):
"""
Gets the metadata of this V1LimitRange.
Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata
:return: The metadata of this V1LimitRange.
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""
Sets the metadata of this V1LimitRange.
Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata
:param metadata: The metadata of this V1LimitRange.
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def spec(self):
"""
Gets the spec of this V1LimitRange.
Spec defines the limits enforced. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status
:return: The spec of this V1LimitRange.
:rtype: V1LimitRangeSpec
"""
return self._spec
@spec.setter
def spec(self, spec):
"""
Sets the spec of this V1LimitRange.
Spec defines the limits enforced. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status
:param spec: The spec of this V1LimitRange.
:type: V1LimitRangeSpec
"""
self._spec = spec
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(V1LimitRange.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
|
XXXXXXXXX XXXXX
XXXXXX
XXXXXX
XXXXX XXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX XXXXXXX X XXXXXXX XXXX XXX XXXXX XXX XXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXX X
XXXXXX XXXXX
X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XX X
XXXXXXXXXXXXX XXX XXXXX XXXXXX
X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XX X
XXXXXXXXXXXX XXX XXXXX XXXXXX
X
XXXXXXXX
XXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXX X
XXX XXXXX X XXXXXXXXXXXXXXXXXXXXXXXX X
XXXXXXXX X XX XXXXX XX
XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXX X
X XXXXXX XXX XXXXX XXXXX XXXXXXXXXXXXXXX XX XX
X XXXXXX XXXXXXX XXXXX XXXXXX XX
X XXXXXX XXXXXXXXXXX XXXXX XXXXXXXXXX XX
X XXXXXX XXXXXXXXX XXXXX XXXXXXXX XX
X XXXXXX XXXXXXXX XXXXX XXXXXX XX
X XXXXXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXX XX
X XXXXXX XXXXXXXXX XXXXX XXXXXXXX XX
X XXXXXX XXX XXXXX XXXXX XXXXXXXXXXXXXXX XX X
XX
XXXXXXXXXXXXX XXXXXXXX XX X
XXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX X
XXXXX XXXXX
XXXXXX XXXX
X XX
X
X XX
XXXXXXXXX XXXXXXXXX XXXXXXXXXXX XXXXXXXX XX X
XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXX XX X
XXXXXXXXXXXXXX X XXXX
X XX
XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXX XX X
XXXXXXXXXXXXXX X XXXX
X XX
X XXXXXXXXX
X XX
XXXXXXXXX
XXXXXXX
XXXXX XXXXXXXXXXXXXXXXXXX
XXXX XXXXXXXXXXXXXXXXXX
XXXXXXXXX
XXXXXXXXXXXXXXX XXXXXXX XXXXXXXXXXXXX XXXX XXX XXXXX XXX XXXXXXXXXXXXXXXXX
XXXX XXXXXXXXXXXXX
XXXXXXXXXXXXXX XXXXXXXX XXX XXXXXXX XX XXX XX XXXXX XXX XXXXXXX XXXXXXX XXXX XXX XXXXX XXXXXXX XX XXX
XXXXXX XXXXX XXX XXXXXXXXXX XX XXX XXXXXXXXXXXX
XXX XXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX X XXXXXXX XXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXX X XXXXXXX XXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXX X XXXXXXX XXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXX X XXXXXXX XXXXXXXXXX
XXXXX
XXXXXXX XXXXXXX XXXXX XXXX XXXX XXX XXXXX XXXXXXX XXXX XXXXX XXXXXXX XX XXX XXXX XXX XXXXXXXXXX
XXXXXXX XXXX XX XXXX X XXXXXXXXX XX XXXXX XXX XX XXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXX XX XXXX XXXXXXX
XXXXXXXXXXXX XX XXX XXXX XX XXX XXX XXXXXXXXX XXXXXXX XXXXX XXXX XXXXXXXXXXXXXXX
XXXXXX
XXXXXX XXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX
XXX XXXXXXXXXXXXX
XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXXX
XXXXXXXXXXXXXXX XXXXXXXXXXX
XXXXX
XXXX XXXXXXXXXXXXX
XXXX XXXXXXXXXXX
XXXXXX XXXXXXXXXX XXXXX XXXXX XX XXXX XX XXXXXXXXXX XXX XXXXX XXXXX XX XXXX
XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X
XXX XXXXX X XXXXXXXXXXXXXXXXXXXXXXXX X
XXXXXXXXXXXXXXXXXX X XX XXXXX XX
XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX X
X XXXXXX XXX XXXXX XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXX XX
X XXXXXX XXXXXXX XXXXX XXXXXXXXXXXXXXXX XX
X XXXXXX XXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXX XX
X XXXXXX XXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXX XX
X XXXXXX XXXXXXXX XXXXX XXXXXXXXXXXXXXXX XX
X XXXXXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXX XX
X XXXXXX XXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXX XX
X XXXXXX XXX XXXXX XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXX X
XX
XXXXXXXXXXXXX XXXXXXXX XX X
XXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX X
XXXXX XXXXX
XXXXXX XXXX
X XX
X
X XX
XXXXXXXXX XXXXXXXXX XXXXXXXXXXX XXXXXXXX XX X
XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXX XX X
XXXXXXXXXXXXXX X XXXX
X XX
XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXX XX X
XXXXXXXXXXXXXX X XXXX
X XX
X XXXXXXXXX
X XXXXXXXXX
XXXXX XXXXXXXX XX XXX XXXXX XXXXX XXX XXXXXXXXX XXXXXXXXXX XXXXXXX XXXXX XXX XXXXXX XXX XXX XX XXXX
XXXXXXXXXXXX
XXXX
XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXX XXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX
XXXXXX
XXXX XXXXXXXXXXXXXX
XXXXXX XXXX XXXXX XXXXX XX XXX XXX XXXX XXXXX XXXXXXXX XXXXXX XX XXX XXXX XXXXXXXX XX
XXXXXXXXXXXXXXX
XXXXXX
XXXX XXXXXXXXXXXX
XXXXX
XXXXXXX XXXXXXX XXXX X XXXXXX XXX XX XXXXXXXXXX XXX XXXXXX XXXX XX XXXXXX XXXX XXX XXXXXXX
XXXXX XXXXXXXX XX XXXXX XX XXXXXXXXX XXXXXXX XXX XXXXXX XXX XXXXXXXXXX XXX XXXX XX XXXXX
XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX X
XXXXXX XXXXX
X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XX X
XXXXXXXXXXXXX XXX XXXXX XXXXXX
X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XX X
XXXXXXXXXXXX XXX XXXXX XXXXXX
XXXXXXXX
XXXXXX
XXXXXX XXXXXXXXX XXX XXXXXXX XXXXX XXX XXXXXX XXX XXX XX XXXX XXXXXXX XX XXXXXXX XXX XXXXXXX XX XXX
XXXXXXXXXX
XXXX
XXXXXX XXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX
XXXXXX
XXXX XXXXXXXXXXXXX
XXXXXXX XXXXX XXXXX XXXX XX XXXXX XXX XXXXXX XXXX XXXX XXX XXXX XXXXXX XX XXXXX XXXXXX XXXX XXXX
XXXX XXXXXX XXXXXXXXXXXXX XX XXX XXXXXXXXXX XXXX XX XXXXXXXXXXX
XXXXXX
XXXX XXXXXXXXXXXX
XXXXXX XXXXXX XXXX XX XXXXXXX XXX XXXXXXXXXXX XXXXXXXXXX XXX XXXX XXXXX XX XXXXX XXXXXX XXXXXX XXXX
XXXX XXXX XX XXXX XX XXXXXXX XXXXXX XXXXX XXXX XXXXXXXXXXX XXXXXXXXXX XXXXXXX XXX XX XXXXXXX XX XXX
XXXXXXXXX XXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXXXXX XX XXX
XXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX
XXXXXX
XXXXXX
XXXXXXXXXX
XXXXXX
XXXXXXXXX
XXXX XXXXXXXXXXXXXXX
XXXX XXXXXXXXXXXXXXXXXXXXXXX
XXXX XXXXXXXXXXXXXX
XXXXXXXXX XXXXXXXXXXXXX
XXXX XXXXXXXXXXXX
XXXX XXXXXXXXXXXXXXXXXX
XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXX XXXXXXXXXX XXXXXXXX
XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX
XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXX XXXXXXXXXXXXXX
XXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXX XXXXX XXX
XXXXXXXXXXXXXX
XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX
XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX
XXXXX
XXXXXX
XXXXXX
XXXX XXXXXXXXXXXXXXXXX
XXXXXXXXX XXXXX XX XXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXX XXXX
XXXXXXXXXXX XXXXX XXX XXX XXXXXXXXXX XXX XXXXXXXXXXXX
XXXXXXXXXXXXX XXXXX XXX X XXXX XXXXX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX
XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXX XXX XXXXXXXXXXXX XX
XXXXXXXXXXXXXXX
XX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXX XXXXXXX XX XX XXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX XXXXXX XXXXXXXXXXXXX
XXXXXXXXXX XX XXXXXXXX XXXXX XXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXXXXXX
XXXXXXX
XXXXXXX
|
|
import FWCore.ParameterSet.Config as cms
#---------------------------------------------------------------------------------------------------
# M A I N
#---------------------------------------------------------------------------------------------------
# create the process
process = cms.Process('FILEFI')
# say how many events to process (-1 means no limit)
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(10)
)
#>> input source
process.source = cms.Source(
"PoolSource",
#fileNames = cms.untracked.vstring('root://xrootd.unl.edu//store/mc/RunIIFall15DR76/TT_TuneCUETP8M1_13TeV-amcatnlo-pythia8/AODSIM/PU25nsData2015v1_76X_mcRun2_asymptotic_v12-v1/30000/029641E2-37A2-E511-9AB4-A0369F7F8E80.root')
fileNames = cms.untracked.vstring('file:/tmp/029641E2-37A2-E511-9AB4-A0369F7F8E80.root')
)
process.source.inputCommands = cms.untracked.vstring(
"keep *",
"drop *_MEtoEDMConverter_*_*",
"drop L1GlobalTriggerObjectMapRecord_hltL1GtObjectMap__HLT"
)
#>> configurations
# determine the global tag to use
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff')
process.GlobalTag.globaltag = 'MCRUN2_74_V9'
# define meta data for this production
process.configurationMetadata = cms.untracked.PSet(
name = cms.untracked.string('BambuProd'),
version = cms.untracked.string('Mit_043'),
annotation = cms.untracked.string('AODSIM')
)
#>> standard sequences
# load some standard sequences we will need
process.load('Configuration.StandardSequences.Services_cff')
process.load('Configuration.StandardSequences.GeometryDB_cff')
process.load('Configuration.StandardSequences.MagneticField_38T_cff')
process.load('Configuration.EventContent.EventContent_cff')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('RecoVertex.PrimaryVertexProducer.OfflinePrimaryVertices_cfi')
process.load('TrackingTools.TransientTrack.TransientTrackBuilder_cfi')
# define sequence for ProductNotFound
process.options = cms.untracked.PSet(
Rethrow = cms.untracked.vstring('ProductNotFound'),
fileMode = cms.untracked.string('NOMERGE'),
wantSummary = cms.untracked.bool(False)
)
# Import/Load the filler so all is already available for config changes
from MitProd.TreeFiller.MitTreeFiller_cfi import MitTreeFiller
process.load('MitProd.TreeFiller.MitTreeFiller_cfi')
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
#
# R E C O S E Q U E N C E
#
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
## Load stablePart producers
from MitEdm.Producers.conversionElectronsStable_cfi import electronsStable
process.load('MitEdm.Producers.conversionElectronsStable_cfi')
# Load Mit Mvf Conversion producer
# MultiVertexFitter is currently broken
#from MitProd.TreeFiller.conversionProducer_cff import conversionProducer, addConversionFiller
#process.load('MitProd.TreeFiller.conversionProducer_cff')
#addConversionFiller(MitTreeFiller)
# Electron likelihood-based id
from RecoEgamma.ElectronIdentification.ElectronMVAValueMapProducer_cfi import electronMVAValueMapProducer
process.load('RecoEgamma.ElectronIdentification.ElectronMVAValueMapProducer_cfi')
MitTreeFiller.Electrons.eIDLikelihoodName = 'electronMVAValueMapProducer:ElectronMVAEstimatorRun2Spring15Trig25nsV1Values'
# Load basic particle flow collections
# Used for rho calculation
from CommonTools.ParticleFlow.goodOfflinePrimaryVertices_cfi import goodOfflinePrimaryVertices
from CommonTools.ParticleFlow.pfParticleSelection_cff import pfParticleSelectionSequence, pfPileUp, pfNoPileUp, pfPileUpIso, pfNoPileUpIso
from CommonTools.ParticleFlow.pfPhotons_cff import pfPhotonSequence
from CommonTools.ParticleFlow.pfElectrons_cff import pfElectronSequence
from CommonTools.ParticleFlow.pfMuons_cff import pfMuonSequence
from CommonTools.ParticleFlow.TopProjectors.pfNoMuon_cfi import pfNoMuon
from CommonTools.ParticleFlow.TopProjectors.pfNoElectron_cfi import pfNoElectron
process.load('CommonTools.ParticleFlow.goodOfflinePrimaryVertices_cfi')
process.load('CommonTools.ParticleFlow.pfParticleSelection_cff')
process.load('CommonTools.ParticleFlow.pfPhotons_cff')
process.load('CommonTools.ParticleFlow.pfElectrons_cff')
process.load('CommonTools.ParticleFlow.pfMuons_cff')
process.load('CommonTools.ParticleFlow.TopProjectors.pfNoMuon_cfi')
process.load('CommonTools.ParticleFlow.TopProjectors.pfNoElectron_cfi')
# Loading PFProducer to get the ptrs
from RecoParticleFlow.PFProducer.pfLinker_cff import particleFlowPtrs
process.load('RecoParticleFlow.PFProducer.pfLinker_cff')
# Load PUPPI
from MitProd.TreeFiller.PuppiSetup_cff import puppiSequence
process.load('MitProd.TreeFiller.PuppiSetup_cff')
# recluster fat jets, btag subjets
from MitProd.TreeFiller.utils.makeFatJets import initFatJets,makeFatJets
pfbrecoSequence = initFatJets(process, isData = False)
ak8chsSequence = makeFatJets(process, isData = False, algoLabel = 'AK', jetRadius = 0.8)
ak8puppiSequence = makeFatJets(process, isData = False, algoLabel = 'AK', jetRadius = 0.8, pfCandidates = 'puppiNoLepPlusLep')
ca15chsSequence = makeFatJets(process, isData = False, algoLabel = 'CA', jetRadius = 1.5)
ca15puppiSequence = makeFatJets(process, isData = False, algoLabel = 'CA', jetRadius = 1.5, pfCandidates = 'puppiNoLepPlusLep')
# unload unwanted PAT stuff
delattr(process, 'pfNoTauPFBRECOPFlow')
delattr(process, 'loadRecoTauTagMVAsFromPrepDBPFlow')
pfPileUp.PFCandidates = 'particleFlowPtrs'
pfNoPileUp.bottomCollection = 'particleFlowPtrs'
pfPileUpIso.PFCandidates = 'particleFlowPtrs'
pfNoPileUpIso.bottomCollection='particleFlowPtrs'
pfPileUp.Enable = True
pfPileUp.Vertices = 'goodOfflinePrimaryVertices'
pfPileUp.checkClosestZVertex = cms.bool(False)
# PUPPI jets
from RecoJets.JetProducers.ak4PFJetsPuppi_cfi import ak4PFJetsPuppi
process.load('RecoJets.JetProducers.ak4PFJetsPuppi_cfi')
ak4PFJetsPuppi.src = cms.InputTag('puppiNoLepPlusLep')
ak4PFJetsPuppi.doAreaFastjet = True
# Load FastJet L1 corrections
#from MitProd.TreeFiller.FastJetCorrection_cff import l1FastJetSequence
#process.load('MitProd.TreeFiller.FastJetCorrection_cff')
# Setup jet corrections
process.load('JetMETCorrections.Configuration.JetCorrectionServices_cff')
# Load btagging
from MitProd.TreeFiller.utils.setupBTag import setupBTag
ak4PFBTagSequence = setupBTag(process, 'ak4PFJets', 'AKt4PF')
ak4PFCHSBTagSequence = setupBTag(process, 'ak4PFJetsCHS', 'AKt4PFCHS')
ak4PFPuppiBTagSequence = setupBTag(process, 'ak4PFJetsPuppi', 'AKt4PFPuppi')
# Load HPS tau reconstruction (tau in AOD is older than the latest reco in release)
from RecoTauTag.Configuration.RecoPFTauTag_cff import PFTau
process.load('RecoTauTag.Configuration.RecoPFTauTag_cff')
#> Setup the met filters
from MitProd.TreeFiller.metFilters_cff import metFilters
process.load('MitProd.TreeFiller.metFilters_cff')
#> The bambu reco sequence
recoSequence = cms.Sequence(
electronsStable *
electronMVAValueMapProducer *
# conversionProducer *
goodOfflinePrimaryVertices *
particleFlowPtrs *
pfParticleSelectionSequence *
pfPhotonSequence *
pfMuonSequence *
pfNoMuon *
pfElectronSequence *
pfNoElectron *
PFTau *
puppiSequence *
ak4PFJetsPuppi *
# l1FastJetSequence *
ak4PFBTagSequence *
ak4PFCHSBTagSequence *
ak4PFPuppiBTagSequence *
pfbrecoSequence*
ak8chsSequence*
ak8puppiSequence*
ca15chsSequence*
ca15puppiSequence*
metFilters
)
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
#
# G E N S E Q U E N C E
#
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
# Import/Load genjets
from RecoJets.Configuration.GenJetParticles_cff import genJetParticles
process.load('RecoJets.Configuration.GenJetParticles_cff')
from RecoJets.Configuration.RecoGenJets_cff import ak4GenJets, ak8GenJets
process.load('RecoJets.Configuration.RecoGenJets_cff')
genSequence = cms.Sequence(
genJetParticles *
ak4GenJets *
ak8GenJets
)
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
#
# B A M B U S E Q U E N C E
#
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
# remember the bambu sequence has been imported and loaded already in the beginning
# configure the filler
MitTreeFiller.TreeWriter.fileName = 'bambu-output-file-tmp'
MitTreeFiller.PileupInfo.active = True
MitTreeFiller.MCParticles.active = True
MitTreeFiller.MCEventInfo.active = True
MitTreeFiller.MCVertexes.active = True
# define fill bambu filler sequence
bambuFillerSequence = cms.Sequence(
MitTreeFiller
)
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
#
# C M S S W P A T H
#
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
process.path = cms.Path(
recoSequence *
genSequence *
bambuFillerSequence
)
|
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
# flake8: noqa
class Migration(DataMigration):
def forwards(self, orm):
"""Delete duplicate action items for post event metrics.
This affects only the events with end date after the 1st of May 2015.
"""
from remo.dashboard.models import ActionItem
event_type = orm['contenttypes.ContentType'].objects.get(
app_label='events', model='Event')
end = datetime.datetime.combine(datetime.date(2015, 5, 1),
datetime.datetime.min.time())
events = orm['events.Event'].objects.filter(end__gt=end)
for event in events:
action_item_q = {'content_type': event_type,
'object_id': event.id,
'priority': ActionItem.NORMAL,
'user': event.owner}
action_items = list(orm['dashboard.ActionItem'].objects.filter(
**action_item_q).order_by('id').values_list('id', flat=True))
if len(action_items) > 1:
orm['dashboard.ActionItem'].objects.filter(pk__in=action_items[1:]).delete()
def backwards(self, orm):
"""Do nothing please."""
pass
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'})
},
'dashboard.actionitem': {
'Meta': {'ordering': "['-due_date', '-updated_on', '-created_on']", 'object_name': 'ActionItem'},
'completed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'created_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'due_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'priority': ('django.db.models.fields.IntegerField', [], {}),
'resolved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'updated_on': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'action_items_assigned'", 'to': "orm['auth.User']"})
},
'events.attendance': {
'Meta': {'object_name': 'Attendance'},
'date_subscribed': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Event']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'events.event': {
'Meta': {'ordering': "['start']", 'object_name': 'Event'},
'actual_attendance': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'attendees': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'events_attended'", 'symmetrical': 'False', 'through': "orm['events.Attendance']", 'to': "orm['auth.User']"}),
'budget_bug': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'event_budget_requests'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['remozilla.Bug']"}),
'campaign': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'events'", 'null': 'True', 'to': "orm['reports.Campaign']"}),
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'events_categories'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['profiles.FunctionalArea']"}),
'city': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '50'}),
'converted_visitors': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'country': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'created_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {}),
'end': ('django.db.models.fields.DateTimeField', [], {}),
'estimated_attendance': ('django.db.models.fields.PositiveIntegerField', [], {}),
'external_link': ('django.db.models.fields.URLField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}),
'extra_content': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'goals': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'events_goals'", 'blank': 'True', 'to': "orm['events.EventGoal']"}),
'has_new_metrics': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'hashtag': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '50', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'lat': ('django.db.models.fields.FloatField', [], {}),
'lon': ('django.db.models.fields.FloatField', [], {}),
'metrics': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['events.EventMetric']", 'through': "orm['events.EventMetricOutcome']", 'symmetrical': 'False'}),
'mozilla_event': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'events_created'", 'to': "orm['auth.User']"}),
'planning_pad_url': ('django.db.models.fields.URLField', [], {'max_length': '300', 'blank': 'True'}),
'region': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '50', 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '100', 'blank': 'True'}),
'start': ('django.db.models.fields.DateTimeField', [], {}),
'swag_bug': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'event_swag_requests'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['remozilla.Bug']"}),
'times_edited': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'timezone': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'updated_on': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'venue': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'events.eventcomment': {
'Meta': {'ordering': "['id']", 'object_name': 'EventComment'},
'comment': ('django.db.models.fields.TextField', [], {}),
'created_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Event']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'events.eventgoal': {
'Meta': {'ordering': "['name']", 'object_name': 'EventGoal'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '127'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '127', 'blank': 'True'})
},
'events.eventmetric': {
'Meta': {'ordering': "['name']", 'object_name': 'EventMetric'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'events.eventmetricoutcome': {
'Meta': {'object_name': 'EventMetricOutcome'},
'details': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Event']"}),
'expected_outcome': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'metric': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.EventMetric']"}),
'outcome': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'})
},
'events.metric': {
'Meta': {'object_name': 'Metric'},
'event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['events.Event']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'outcome': ('django.db.models.fields.CharField', [], {'max_length': '300'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '300'})
},
'profiles.functionalarea': {
'Meta': {'ordering': "['name']", 'object_name': 'FunctionalArea'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '100', 'blank': 'True'})
},
'remozilla.bug': {
'Meta': {'ordering': "['-bug_last_change_time']", 'object_name': 'Bug'},
'assigned_to': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'bugs_assigned'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['auth.User']"}),
'budget_needinfo': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.User']", 'symmetrical': 'False'}),
'bug_creation_time': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'bug_id': ('django.db.models.fields.PositiveIntegerField', [], {'unique': 'True'}),
'bug_last_change_time': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'cc': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'bugs_cced'", 'symmetrical': 'False', 'to': "orm['auth.User']"}),
'component': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'council_member_assigned': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'council_vote_requested': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'created_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'creator': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'bugs_created'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['auth.User']"}),
'first_comment': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'pending_mentor_validation': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'resolution': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '30'}),
'status': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '30'}),
'summary': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '500'}),
'updated_on': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'whiteboard': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '500'})
},
'reports.campaign': {
'Meta': {'ordering': "['name']", 'object_name': 'Campaign'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['events']
symmetrical = True
|
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import pytest
from marshmallow.compat import PY2
from marshmallow import validate, ValidationError
@pytest.mark.parametrize('valid_url', [
'http://example.org',
'https://example.org',
'ftp://example.org',
'ftps://example.org',
'http://example.co.jp',
'http://www.example.com/a%C2%B1b',
'http://www.example.com/~username/',
'http://info.example.com/?fred',
'http://xn--mgbh0fb.xn--kgbechtv/',
'http://example.com/blue/red%3Fand+green',
'http://www.example.com/?array%5Bkey%5D=value',
'http://xn--rsum-bpad.example.org/',
'http://123.45.67.8/',
'http://2001:db8::ff00:42:8329',
'http://www.example.com:8000/foo',
])
def test_url_absolute_valid(valid_url):
validator = validate.URL(relative=False)
assert validator(valid_url) == valid_url
@pytest.mark.parametrize('invalid_url', [
'http:///example.com/',
'https:///example.com/',
'https://example.org\\',
'ftp:///example.com/',
'ftps:///example.com/',
'http//example.org',
'http:///',
'http:/example.org',
'foo://example.org',
'../icons/logo.gif',
'abc',
'..',
'/',
' ',
'',
None,
])
def test_url_absolute_invalid(invalid_url):
validator = validate.URL(relative=False)
with pytest.raises(ValidationError):
validator(invalid_url)
@pytest.mark.parametrize('valid_url', [
'http://example.org',
'http://123.45.67.8/',
'http://example.com/foo/bar/../baz',
'https://example.com/../icons/logo.gif',
'http://example.com/./icons/logo.gif',
'ftp://example.com/../../../../g',
'http://example.com/g?y/./x',
])
def test_url_relative_valid(valid_url):
validator = validate.URL(relative=True)
assert validator(valid_url) == valid_url
@pytest.mark.parametrize('invalid_url', [
'http//example.org',
'suppliers.html',
'../icons/logo.gif',
'\icons/logo.gif',
'../.../g',
'...',
'\\',
' ',
'',
None,
])
def test_url_relative_invalid(invalid_url):
validator = validate.URL(relative=True)
with pytest.raises(ValidationError):
validator(invalid_url)
def test_url_custom_message():
validator = validate.URL(error="{input} ain't an URL")
with pytest.raises(ValidationError) as excinfo:
validator('invalid')
assert "invalid ain't an URL" in str(excinfo)
def test_url_repr():
assert (
repr(validate.URL(relative=False, error=None)) ==
'<URL(relative=False, error={0!r})>'
.format('Invalid URL.')
)
assert (
repr(validate.URL(relative=True, error='foo')) ==
'<URL(relative=True, error={0!r})>'
.format('foo')
)
@pytest.mark.parametrize('valid_email', [
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'"[email protected]"@example.com',
"!#$%&'*+-/=?^_`{}|[email protected]",
'niceandsimple@[64.233.160.0]',
'niceandsimple@localhost',
])
def test_email_valid(valid_email):
validator = validate.Email()
assert validator(valid_email) == valid_email
@pytest.mark.parametrize('invalid_email', [
'a"b(c)d,e:f;g<h>i[j\\k][email protected]',
'just"not"[email protected]',
'this is"not\[email protected]',
'this\\ still\\"not\\\\[email protected]',
'"much.more unusual"@example.com',
'"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com',
'" "@example.org',
'user@example',
'@nouser.com',
'example.com',
'user',
'',
None,
])
def test_email_invalid(invalid_email):
validator = validate.Email()
with pytest.raises(ValidationError):
validator(invalid_email)
def test_email_custom_message():
validator = validate.Email(error='{input} is not an email addy.')
with pytest.raises(ValidationError) as excinfo:
validator('invalid')
assert 'invalid is not an email addy.' in str(excinfo)
def test_email_repr():
assert (
repr(validate.Email(error=None)) ==
'<Email(error={0!r})>'
.format('Invalid email address.')
)
assert (
repr(validate.Email(error='foo')) ==
'<Email(error={0!r})>'
.format('foo')
)
def test_range_min():
assert validate.Range(1, 2)(1) == 1
assert validate.Range(0)(1) == 1
assert validate.Range()(1) == 1
assert validate.Range(1, 1)(1) == 1
with pytest.raises(ValidationError):
validate.Range(2, 3)(1)
with pytest.raises(ValidationError):
validate.Range(2)(1)
def test_range_max():
assert validate.Range(1, 2)(2) == 2
assert validate.Range(None, 2)(2) == 2
assert validate.Range()(2) == 2
assert validate.Range(2, 2)(2) == 2
with pytest.raises(ValidationError):
validate.Range(0, 1)(2)
with pytest.raises(ValidationError):
validate.Range(None, 1)(2)
def test_range_custom_message():
v = validate.Range(2, 3, error='{input} is not between {min} and {max}')
with pytest.raises(ValidationError) as excinfo:
v(1)
assert '1 is not between 2 and 3' in str(excinfo)
v = validate.Range(2, None, error='{input} is less than {min}')
with pytest.raises(ValidationError) as excinfo:
v(1)
assert '1 is less than 2' in str(excinfo)
v = validate.Range(None, 3, error='{input} is greater than {max}')
with pytest.raises(ValidationError) as excinfo:
v(4)
assert '4 is greater than 3' in str(excinfo)
def test_range_repr():
assert (
repr(validate.Range(min=None, max=None, error=None)) ==
'<Range(min=None, max=None, error=None)>'
)
assert (
repr(validate.Range(min=1, max=3, error='foo')) ==
'<Range(min=1, max=3, error={0!r})>'
.format('foo')
)
def test_length_min():
assert validate.Length(3, 5)('foo') == 'foo'
assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3]
assert validate.Length(0)('a') == 'a'
assert validate.Length(0)([1]) == [1]
assert validate.Length()('') == ''
assert validate.Length()([]) == []
assert validate.Length(1, 1)('a') == 'a'
assert validate.Length(1, 1)([1]) == [1]
with pytest.raises(ValidationError):
validate.Length(4, 5)('foo')
with pytest.raises(ValidationError):
validate.Length(4, 5)([1, 2, 3])
with pytest.raises(ValidationError):
validate.Length(5)('foo')
with pytest.raises(ValidationError):
validate.Length(5)([1, 2, 3])
def test_length_max():
assert validate.Length(1, 3)('foo') == 'foo'
assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3]
assert validate.Length(None, 1)('a') == 'a'
assert validate.Length(None, 1)([1]) == [1]
assert validate.Length()('') == ''
assert validate.Length()([]) == []
assert validate.Length(2, 2)('ab') == 'ab'
assert validate.Length(2, 2)([1, 2]) == [1, 2]
with pytest.raises(ValidationError):
validate.Length(1, 2)('foo')
with pytest.raises(ValidationError):
validate.Length(1, 2)([1, 2, 3])
with pytest.raises(ValidationError):
validate.Length(None, 2)('foo')
with pytest.raises(ValidationError):
validate.Length(None, 2)([1, 2, 3])
def test_length_custom_message():
v = validate.Length(5, 6, error='{input} is not between {min} and {max}')
with pytest.raises(ValidationError) as excinfo:
v('foo')
assert 'foo is not between 5 and 6' in str(excinfo)
v = validate.Length(5, None, error='{input} is shorter than {min}')
with pytest.raises(ValidationError) as excinfo:
v('foo')
assert 'foo is shorter than 5' in str(excinfo)
v = validate.Length(None, 2, error='{input} is longer than {max}')
with pytest.raises(ValidationError) as excinfo:
v('foo')
assert 'foo is longer than 2' in str(excinfo)
def test_length_repr():
assert (
repr(validate.Length(min=None, max=None, error=None)) ==
'<Length(min=None, max=None, error=None)>'
)
assert (
repr(validate.Length(min=1, max=3, error='foo')) ==
'<Length(min=1, max=3, error={0!r})>'
.format('foo')
)
def test_equal():
assert validate.Equal('a')('a') == 'a'
assert validate.Equal(1)(1) == 1
assert validate.Equal([1])([1]) == [1]
with pytest.raises(ValidationError):
validate.Equal('b')('a')
with pytest.raises(ValidationError):
validate.Equal(2)(1)
with pytest.raises(ValidationError):
validate.Equal([2])([1])
def test_equal_custom_message():
v = validate.Equal('a', error='{input} is not equal to {other}.')
with pytest.raises(ValidationError) as excinfo:
v('b')
assert 'b is not equal to a.' in str(excinfo)
def test_equal_repr():
assert (
repr(validate.Equal(comparable=123, error=None)) ==
'<Equal(comparable=123, error={0!r})>'
.format('Must be equal to {other}.')
)
assert (
repr(validate.Equal(comparable=123, error='foo')) ==
'<Equal(comparable=123, error={0!r})>'
.format('foo')
)
def test_regexp_str():
assert validate.Regexp(r'a')('a') == 'a'
assert validate.Regexp(r'\w')('_') == '_'
assert validate.Regexp(r'\s')(' ') == ' '
assert validate.Regexp(r'1')('1') == '1'
assert validate.Regexp(r'[0-9]+')('1') == '1'
assert validate.Regexp(r'a', re.IGNORECASE)('A') == 'A'
with pytest.raises(ValidationError):
validate.Regexp(r'[0-9]+')('a')
with pytest.raises(ValidationError):
validate.Regexp(r'[a-z]+')('1')
with pytest.raises(ValidationError):
validate.Regexp(r'a')('A')
def test_regexp_compile():
assert validate.Regexp(re.compile(r'a'))('a') == 'a'
assert validate.Regexp(re.compile(r'\w'))('_') == '_'
assert validate.Regexp(re.compile(r'\s'))(' ') == ' '
assert validate.Regexp(re.compile(r'1'))('1') == '1'
assert validate.Regexp(re.compile(r'[0-9]+'))('1') == '1'
assert validate.Regexp(re.compile(r'a', re.IGNORECASE))('A') == 'A'
assert validate.Regexp(re.compile(r'a', re.IGNORECASE), re.IGNORECASE)('A') == 'A'
with pytest.raises(ValidationError):
validate.Regexp(re.compile(r'[0-9]+'))('a')
with pytest.raises(ValidationError):
validate.Regexp(re.compile(r'[a-z]+'))('1')
with pytest.raises(ValidationError):
validate.Regexp(re.compile(r'a'))('A')
with pytest.raises(ValidationError):
validate.Regexp(re.compile(r'a'), re.IGNORECASE)('A')
def test_regexp_custom_message():
rex = r'[0-9]+'
v = validate.Regexp(rex, error='{input} does not match {regex}')
with pytest.raises(ValidationError) as excinfo:
v('a')
assert 'a does not match [0-9]+' in str(excinfo)
def test_regexp_repr():
assert (
repr(validate.Regexp(regex='abc', flags=0, error=None)) ==
'<Regexp(regex={0!r}, error={1!r})>'
.format(re.compile('abc'), 'String does not match expected pattern.')
)
assert (
repr(validate.Regexp(regex='abc', flags=re.IGNORECASE, error='foo')) ==
'<Regexp(regex={0!r}, error={1!r})>'
.format(re.compile('abc', re.IGNORECASE), 'foo')
)
def test_predicate():
class Dummy(object):
def _true(self):
return True
def _false(self):
return False
def _list(self):
return [1, 2, 3]
def _empty(self):
return []
def _identity(self, arg):
return arg
d = Dummy()
assert validate.Predicate('_true')(d) == d
assert validate.Predicate('_list')(d) == d
assert validate.Predicate('_identity', arg=True)(d) == d
assert validate.Predicate('_identity', arg=1)(d) == d
assert validate.Predicate('_identity', arg='abc')(d) == d
with pytest.raises(ValidationError) as excinfo:
validate.Predicate('_false')(d)
assert 'Invalid input.' in str(excinfo)
with pytest.raises(ValidationError):
validate.Predicate('_empty')(d)
with pytest.raises(ValidationError):
validate.Predicate('_identity', arg=False)(d)
with pytest.raises(ValidationError):
validate.Predicate('_identity', arg=0)(d)
with pytest.raises(ValidationError):
validate.Predicate('_identity', arg='')(d)
def test_predicate_custom_message():
class Dummy(object):
def _false(self):
return False
def __str__(self):
return 'Dummy'
d = Dummy()
with pytest.raises(ValidationError) as excinfo:
validate.Predicate('_false', error='{input}.{method} is invalid!')(d)
assert 'Dummy._false is invalid!' in str(excinfo)
def test_predicate_repr():
assert (
repr(validate.Predicate(method='foo', error=None)) ==
'<Predicate(method={0!r}, kwargs={1!r}, error={2!r})>'
.format('foo', {}, 'Invalid input.')
)
assert (
repr(validate.Predicate(method='foo', error='bar', zoo=1)) ==
'<Predicate(method={0!r}, kwargs={1!r}, error={2!r})>'
.format('foo', {str('zoo') if PY2 else 'zoo': 1}, 'bar')
)
def test_noneof():
assert validate.NoneOf([1, 2, 3])(4) == 4
assert validate.NoneOf('abc')('d') == 'd'
assert validate.NoneOf('')([]) == []
assert validate.NoneOf([])('') == ''
assert validate.NoneOf([])([]) == []
assert validate.NoneOf([1, 2, 3])(None) is None
with pytest.raises(ValidationError) as excinfo:
validate.NoneOf([1, 2, 3])(3)
assert 'Invalid input.' in str(excinfo)
with pytest.raises(ValidationError):
validate.NoneOf('abc')('c')
with pytest.raises(ValidationError):
validate.NoneOf([1, 2, None])(None)
with pytest.raises(ValidationError):
validate.NoneOf('')('')
def test_noneof_custom_message():
with pytest.raises(ValidationError) as excinfo:
validate.NoneOf([1, 2], error='<not valid>')(1)
assert '<not valid>' in str(excinfo)
none_of = validate.NoneOf(
[1, 2],
error='{input} cannot be one of {values}'
)
with pytest.raises(ValidationError) as excinfo:
none_of(1)
assert '1 cannot be one of 1, 2' in str(excinfo)
def test_noneof_repr():
assert (
repr(validate.NoneOf(iterable=[1, 2, 3], error=None)) ==
'<NoneOf(iterable=[1, 2, 3], error={0!r})>'
.format('Invalid input.')
)
assert (
repr(validate.NoneOf(iterable=[1, 2, 3], error='foo')) ==
'<NoneOf(iterable=[1, 2, 3], error={0!r})>'
.format('foo')
)
def test_oneof():
assert validate.OneOf([1, 2, 3])(2) == 2
assert validate.OneOf('abc')('b') == 'b'
assert validate.OneOf('')('') == ''
assert validate.OneOf(dict(a=0, b=1))('a') == 'a'
assert validate.OneOf((1, 2, None))(None) is None
with pytest.raises(ValidationError) as excinfo:
validate.OneOf([1, 2, 3])(4)
assert 'Not a valid choice.' in str(excinfo)
with pytest.raises(ValidationError):
validate.OneOf('abc')('d')
with pytest.raises(ValidationError):
validate.OneOf((1, 2, 3))(None)
with pytest.raises(ValidationError):
validate.OneOf([])([])
with pytest.raises(ValidationError):
validate.OneOf(())(())
with pytest.raises(ValidationError):
validate.OneOf(dict(a=0, b=1))(0)
with pytest.raises(ValidationError):
validate.OneOf('123')(1)
def test_oneof_options():
oneof = validate.OneOf([1, 2, 3], ['one', 'two', 'three'])
expected = [('1', 'one'), ('2', 'two'), ('3', 'three')]
assert list(oneof.options()) == expected
oneof = validate.OneOf([1, 2, 3], ['one', 'two'])
expected = [('1', 'one'), ('2', 'two'), ('3', '')]
assert list(oneof.options()) == expected
oneof = validate.OneOf([1, 2], ['one', 'two', 'three'])
expected = [('1', 'one'), ('2', 'two'), ('', 'three')]
assert list(oneof.options()) == expected
oneof = validate.OneOf([1, 2])
expected = [('1', ''), ('2', '')]
assert list(oneof.options()) == expected
def test_oneof_text():
oneof = validate.OneOf([1, 2, 3], ['one', 'two', 'three'])
assert oneof.choices_text == '1, 2, 3'
assert oneof.labels_text == 'one, two, three'
oneof = validate.OneOf([1], ['one'])
assert oneof.choices_text == '1'
assert oneof.labels_text == 'one'
oneof = validate.OneOf(dict(a=0, b=1))
assert ', '.join(sorted(oneof.choices_text.split(', '))) == 'a, b'
assert oneof.labels_text == ''
def test_oneof_custom_message():
oneof = validate.OneOf([1, 2, 3], error='{input} is not one of {choices}')
expected = '4 is not one of 1, 2, 3'
with pytest.raises(ValidationError) as excinfo:
oneof(4)
assert expected in str(expected)
oneof = validate.OneOf([1, 2, 3],
['one', 'two', 'three'],
error='{input} is not one of {labels}'
)
expected = '4 is not one of one, two, three'
with pytest.raises(ValidationError) as excinfo:
oneof(4)
assert expected in str(expected)
def test_oneof_repr():
assert (
repr(validate.OneOf(choices=[1, 2, 3], labels=None, error=None)) ==
'<OneOf(choices=[1, 2, 3], labels=[], error={0!r})>'
.format('Not a valid choice.')
)
assert (
repr(validate.OneOf(choices=[1, 2, 3], labels=['a', 'b', 'c'], error='foo')) ==
'<OneOf(choices=[1, 2, 3], labels={0!r}, error={1!r})>'
.format(['a', 'b', 'c'], 'foo')
)
def test_containsonly_in_list():
assert validate.ContainsOnly([])([]) == []
assert validate.ContainsOnly([1, 2, 3])([1]) == [1]
assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1]
assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2]
assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1]
assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3]
assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2]
assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1]
with pytest.raises(ValidationError):
validate.ContainsOnly([1, 2, 3])([4])
with pytest.raises(ValidationError):
validate.ContainsOnly([1, 2, 3])([])
with pytest.raises(ValidationError):
validate.ContainsOnly([])([1])
def test_contains_only_unhashable_types():
assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]]
assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]]
assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]]
assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]]
assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]]
assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]]
assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]]
with pytest.raises(ValidationError):
validate.ContainsOnly([[1], [2], [3]])([[4]])
with pytest.raises(ValidationError):
validate.ContainsOnly([[1], [2], [3]])([])
with pytest.raises(ValidationError):
validate.ContainsOnly([])([1])
def test_containsonly_in_tuple():
assert validate.ContainsOnly(())(()) == ()
assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,)
assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1)
assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2)
assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1)
assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3)
assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2)
assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1)
with pytest.raises(ValidationError):
validate.ContainsOnly((1, 2, 3))((4,))
with pytest.raises(ValidationError):
validate.ContainsOnly((1, 2, 3))(())
with pytest.raises(ValidationError):
validate.ContainsOnly(())((1,))
def test_contains_only_in_string():
assert validate.ContainsOnly('')('') == ''
assert validate.ContainsOnly('abc')('a') == 'a'
assert validate.ContainsOnly('aab')('aa') == 'aa'
assert validate.ContainsOnly('abc')('ab') == 'ab'
assert validate.ContainsOnly('abc')('ba') == 'ba'
assert validate.ContainsOnly('abc')('abc') == 'abc'
assert validate.ContainsOnly('abc')('cab') == 'cab'
assert validate.ContainsOnly('abc')('bca') == 'bca'
with pytest.raises(ValidationError):
validate.ContainsOnly('abc')('d')
with pytest.raises(ValidationError):
validate.ContainsOnly('abc')('')
with pytest.raises(ValidationError):
validate.ContainsOnly('')('a')
def test_contains_only_invalid():
with pytest.raises(ValidationError) as excinfo:
validate.ContainsOnly([1, 2, 3])([1, 1])
assert 'One or more of the choices you made was not acceptable.' in str(excinfo)
with pytest.raises(ValidationError):
validate.ContainsOnly([1, 1, 2])([2, 2])
with pytest.raises(ValidationError):
validate.ContainsOnly([1, 1, 2])([1, 1, 1])
def test_containsonly_custom_message():
containsonly = validate.ContainsOnly(
[1, 2, 3],
error='{input} is not one of {choices}'
)
expected = '4, 5 is not one of 1, 2, 3'
with pytest.raises(ValidationError) as excinfo:
containsonly([4, 5])
assert expected in str(expected)
containsonly = validate.ContainsOnly([1, 2, 3],
['one', 'two', 'three'],
error='{input} is not one of {labels}'
)
expected = '4, 5 is not one of one, two, three'
with pytest.raises(ValidationError) as excinfo:
containsonly([4, 5])
assert expected in str(expected)
def test_containsonly_repr():
assert (
repr(validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None)) ==
'<ContainsOnly(choices=[1, 2, 3], labels=[], error={0!r})>'
.format('One or more of the choices you made was not acceptable.')
)
assert (
repr(validate.ContainsOnly(choices=[1, 2, 3], labels=['a', 'b', 'c'], error='foo')) ==
'<ContainsOnly(choices=[1, 2, 3], labels={0!r}, error={1!r})>'
.format(['a', 'b', 'c'], 'foo')
)
|
|
"""payu.manifest
===============
Provides an manifest class to store manifest data, which uses a
subclassed yamanifest PayuManifest class
:copyright: Copyright 2011 Marshall Ward, see AUTHORS for details.
:license: Apache License, Version 2.0, see LICENSE for details.
"""
# Python3 preparation
from __future__ import print_function, absolute_import
# Local
from payu import envmod
from payu.fsops import make_symlink, get_git_revision_hash, is_ancestor
# External
from yamanifest.manifest import Manifest as YaManifest
import yamanifest as ym
from copy import deepcopy
import os, sys, fnmatch
import shutil
from distutils.dir_util import mkpath
# fast_hashes = ['nchash','binhash']
fast_hashes = ['binhash']
full_hashes = ['md5']
all_hashes = fast_hashes + full_hashes
class PayuManifest(YaManifest):
"""
A manifest object sub-classed from yamanifest object with some payu specific
additions and enhancements
"""
def __init__(self, path, hashes=None, ignore=None, **kwargs):
super(PayuManifest, self).__init__(path, hashes, **kwargs)
if ignore is not None:
self.ignore = ignore
self.needsync = False
def check_fast(self, reproduce=False, **args):
"""
Check hash value for all filepaths using a fast hash function and fall back to slower
full hash functions if fast hashes fail to agree
"""
hashvals = {}
# Run a fast check
if not self.check_file(filepaths=self.data.keys(),hashvals=hashvals,hashfn=fast_hashes,shortcircuit=True,**args):
# Save all the fast hashes for failed files that we've already calculated
for filepath in hashvals:
for hash, val in hashvals[filepath].items():
self.data[filepath]["hashes"][hash] = val
if reproduce:
for filepath in hashvals:
print("Check failed for {} {}".format(filepath,hashvals[filepath]))
tmphash = {}
if self.check_file(filepaths=filepath,hashfn=full_hashes,hashvals=tmphash,shortcircuit=False,**args):
# File is still ok, so replace fast hashes
print("Full hashes ({}) checked ok".format(full_hashes))
print("Updating fast hashes for {} in {}".format(filepath,self.path))
self.add_fast(filepath,force=True)
print("Saving updated manifest")
self.needsync = True
else:
sys.stderr.write("Run cannot reproduce: manifest {} is not correct\n".format(self.path))
for path, hashdict in tmphash.items():
print(" {}:".format(path))
for hash, val in hashdict.items():
print(" {}: {} != {}".format(hash,val,self.data[path]['hashes'].get(hash,None)))
sys.exit(1)
else:
# Not relevant if full hashes are correct. Regenerate full hashes for all
# filepaths that failed fast check
print("Updating full hashes for {} files in {}".format(len(hashvals),self.path))
# Add all full hashes at once -- much faster. Definitely want to force
# the full hash to be updated. In the specific case of an empty hash the
# value will be None, without force it will be written as null
self.add(filepaths=list(hashvals.keys()),hashfn=full_hashes,force=True)
# Flag need to update version on disk
self.needsync = True
def add_filepath(self, filepath, fullpath, copy=False):
"""
Bespoke function to add filepath & fullpath to manifest
object without hashing. Can defer hashing until all files are
added. Hashing all at once is much faster as overhead for
threading is spread over all files
"""
# Ignore directories
if os.path.isdir(fullpath):
return
# Ignore anything matching the ignore patterns
for pattern in self.ignore:
if fnmatch.fnmatch(os.path.basename(fullpath), pattern):
return
if filepath not in self.data:
self.data[filepath] = {}
self.data[filepath]['fullpath'] = fullpath
if 'hashes' not in self.data[filepath]:
self.data[filepath]['hashes'] = {hash: None for hash in all_hashes}
if copy:
self.data[filepath]['copy'] = copy
def add_fast(self, filepath, hashfn=fast_hashes, force=False):
"""
Bespoke function to add filepaths but set shortcircuit to True, which means
only the first calculatable hash will be stored. In this way only one "fast"
hashing function need be called for each filepath
"""
self.add(filepath, hashfn, force, shortcircuit=True)
def copy_file(self, filepath):
"""
Returns flag which says to copy rather than link a file
"""
copy_file = False
try:
copy_file = self.data[filepath]['copy']
except KeyError:
return False
return copy_file
def make_links(self):
"""
Payu integration function for creating symlinks in work directories which point
back to the original file
"""
delete_list = []
for filepath in self:
# Check file exists. It may have been deleted but still in manifest
if not os.path.exists(self.fullpath(filepath)):
delete_list.append(filepath)
continue
if self.copy_file(filepath):
shutil.copy(self.fullpath(filepath), filepath)
else:
make_symlink(self.fullpath(filepath), filepath)
for filepath in delete_list:
print("File not found: {} removing from manifest".format(self.fullpath(filepath)))
self.delete(filepath)
self.needsync = True
def copy(self, path):
"""
Copy myself to another location
"""
shutil.copy(self.path, path)
class Manifest(object):
"""
A Manifest class which stores all manifests for file tracking and
methods to operate on them
"""
def __init__(self, expt, reproduce):
# Inherit experiment configuration
self.expt = expt
self.reproduce = reproduce
# Manifest control configuration
self.manifest_config = self.expt.config.get('manifest', {})
# If the run sets reproduce, default to reproduce executables. Allow user
# to specify not to reproduce executables (might not be feasible if
# executables don't match platform, or desirable if bugs existed in old exe)
self.reproduce_exe = self.reproduce and self.manifest_config.get('reproduce_exe',True)
# Not currently supporting specifying hash functions
# self.hash_functions = manifest_config.get('hashfns', ['nchash','binhash','md5'])
self.ignore = self.manifest_config.get('ignore',['.*'])
self.ignore = [self.ignore] if isinstance(self.ignore, str) else self.ignore
# Intialise manifests
self.manifests = {}
for mf in ['input', 'restart', 'exe']:
self.manifests[mf] = PayuManifest(os.path.join('manifests','{}.yaml'.format(mf)), ignore=self.ignore)
self.have_manifest = {}
for mf in self.manifests:
self.have_manifest[mf] = False
# Make sure the manifests directory exists
mkpath(os.path.dirname(self.manifests['exe'].path))
self.scaninputs = self.manifest_config.get('scaninputs',True)
def __iter__(self):
"""
Iterator method
"""
for mf in self.manifests:
yield self.manifests[mf]
def __len__(self):
"""
Return the number of manifests in the manifest class
"""
return len(self.manifests)
def setup(self):
# Check if manifest files exist
self.have_manifest['restart'] = os.path.exists(self.manifests['restart'].path)
if os.path.exists(self.manifests['input'].path) and not self.manifest_config.get('overwrite',False):
# Read manifest
print("Loading input manifest: {}".format(self.manifests['input'].path))
self.manifests['input'].load()
if len(self.manifests['input']) > 0:
self.have_manifest['input'] = True
if os.path.exists(self.manifests['exe'].path):
# Read manifest
print("Loading exe manifest: {}".format(self.manifests['exe'].path))
self.manifests['exe'].load()
if len(self.manifests['exe']) > 0:
self.have_manifest['exe'] = True
if self.reproduce:
# Read restart manifest
print("Loading restart manifest: {}".format(self.have_manifest['restart']))
self.manifests['restart'].load()
if len(self.manifests['restart']) > 0:
self.have_manifest['restart'] = True
# MUST have input and restart manifests to be able to reproduce a run
for mf in ['restart', 'input']:
if not self.have_manifest[mf]:
print("{} manifest cannot be empty if reproduce is True".format(mf.capitalize()))
exit(1)
if self.reproduce_exe and not self.have_manifest['exe']:
print("Executable manifest cannot empty if reproduce and reproduce_exe are True")
exit(1)
for model in self.expt.models:
model.have_restart_manifest = True
# Inspect the restart manifest for an appropriate value of # experiment
# counter if not specified on the command line (and this env var set)
if not os.environ.get('PAYU_CURRENT_RUN'):
for filepath in self.manifests['restart']:
head = os.path.dirname(self.manifests['restart'].fullpath(filepath))
# Inspect each element of the fullpath looking for restartxxx style
# directories. Exit
while True:
head, tail = os.path.split(head)
if tail.startswith('restart'):
try:
n = int(tail.lstrip('restart'))
except ValueError:
pass
else:
self.expt.counter = n + 1
break
# Short circuit as soon as restart dir found
if self.expt.counter == 0: break
else:
self.have_manifest['restart'] = False
def make_links(self):
print("Making links from manifests")
for mf in self.manifests:
self.manifests[mf].make_links()
print("Checking exe and input manifests")
self.manifests['exe'].check_fast(reproduce=self.reproduce_exe)
self.manifests['input'].check_fast(reproduce=self.reproduce)
if self.reproduce:
print("Checking restart manifest")
else:
print("Creating restart manifest")
self.manifests['restart'].check_fast(reproduce=self.reproduce)
# Write updates to version on disk
for mf in self.manifests:
if self.manifests[mf].needsync:
print("Writing {}".format(self.manifests[mf].path))
self.manifests[mf].dump()
def copy_manifests(self, path):
mkpath(path)
try:
for mf in self.manifests:
self.manifests[mf].copy(path)
except IOError:
pass
def add_filepath(self, manifest, filepath, fullpath, copy=False):
"""
Wrapper to the add_filepath function in PayuManifest. Prevents outside
code from directly calling anything in PayuManifest.
"""
self.manifests[manifest].add_filepath(filepath, fullpath, copy)
|
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
import copy
import uuid
import mock
from mock import call
import requests
import yaml
from mistralclient.api.v2 import executions
from mistralclient.api.v2 import workflows
from oslo_config import cfg
# XXX: actionsensor import depends on config being setup.
import st2tests.config as tests_config
tests_config.parse_args()
from mistral_v2 import MistralRunner
from st2common.bootstrap import actionsregistrar
from st2common.bootstrap import runnersregistrar
from st2common.constants import action as action_constants
from st2common.models.db.execution import ActionExecutionDB
from st2common.models.db.liveaction import LiveActionDB
from st2common.persistence.liveaction import LiveAction
from st2common.runners import base as runners
from st2common.services import action as action_service
from st2common.transport.liveaction import LiveActionPublisher
from st2common.transport.publishers import CUDPublisher
from st2common.util import loader
from st2tests import DbTestCase
from st2tests import fixturesloader
from st2tests.mocks.liveaction import MockLiveActionPublisher
TEST_PACK = 'mistral_tests'
TEST_PACK_PATH = fixturesloader.get_fixtures_packs_base_path() + '/' + TEST_PACK
PACKS = [
TEST_PACK_PATH,
fixturesloader.get_fixtures_packs_base_path() + '/core'
]
# Action executions requirements
ACTION_PARAMS = {'friend': 'Rocky'}
NON_EMPTY_RESULT = 'non-empty'
# Non-workbook with a single workflow
WF1_META_FILE_NAME = 'workflow_v2.yaml'
WF1_META_FILE_PATH = TEST_PACK_PATH + '/actions/' + WF1_META_FILE_NAME
WF1_META_CONTENT = loader.load_meta_file(WF1_META_FILE_PATH)
WF1_NAME = WF1_META_CONTENT['pack'] + '.' + WF1_META_CONTENT['name']
WF1_ENTRY_POINT = TEST_PACK_PATH + '/actions/' + WF1_META_CONTENT['entry_point']
WF1_ENTRY_POINT_X = WF1_ENTRY_POINT.replace(WF1_META_FILE_NAME, 'xformed_' + WF1_META_FILE_NAME)
WF1_SPEC = yaml.safe_load(MistralRunner.get_workflow_definition(WF1_ENTRY_POINT_X))
WF1_YAML = yaml.safe_dump(WF1_SPEC, default_flow_style=False)
WF1 = workflows.Workflow(None, {'name': WF1_NAME, 'definition': WF1_YAML})
WF1_OLD = workflows.Workflow(None, {'name': WF1_NAME, 'definition': ''})
WF1_EXEC = {'id': str(uuid.uuid4()), 'state': 'RUNNING', 'workflow_name': WF1_NAME}
WF1_EXEC_CANCELLED = copy.deepcopy(WF1_EXEC)
WF1_EXEC_CANCELLED['state'] = 'CANCELLED'
# Workflow with a subworkflow action
WF2_META_FILE_NAME = 'workflow_v2_call_workflow_action.yaml'
WF2_META_FILE_PATH = TEST_PACK_PATH + '/actions/' + WF2_META_FILE_NAME
WF2_META_CONTENT = loader.load_meta_file(WF2_META_FILE_PATH)
WF2_NAME = WF2_META_CONTENT['pack'] + '.' + WF2_META_CONTENT['name']
WF2_ENTRY_POINT = TEST_PACK_PATH + '/actions/' + WF2_META_CONTENT['entry_point']
WF2_ENTRY_POINT_X = WF2_ENTRY_POINT.replace(WF2_META_FILE_NAME, 'xformed_' + WF2_META_FILE_NAME)
WF2_SPEC = yaml.safe_load(MistralRunner.get_workflow_definition(WF2_ENTRY_POINT_X))
WF2_YAML = yaml.safe_dump(WF2_SPEC, default_flow_style=False)
WF2 = workflows.Workflow(None, {'name': WF2_NAME, 'definition': WF2_YAML})
WF2_EXEC = {'id': str(uuid.uuid4()), 'state': 'RUNNING', 'workflow_name': WF2_NAME}
WF2_EXEC_CANCELLED = copy.deepcopy(WF2_EXEC)
WF2_EXEC_CANCELLED['state'] = 'CANCELLED'
@mock.patch.object(
CUDPublisher,
'publish_update',
mock.MagicMock(return_value=None))
@mock.patch.object(
CUDPublisher,
'publish_create',
mock.MagicMock(side_effect=MockLiveActionPublisher.publish_create))
@mock.patch.object(
LiveActionPublisher,
'publish_state',
mock.MagicMock(side_effect=MockLiveActionPublisher.publish_state))
class MistralRunnerCancelTest(DbTestCase):
@classmethod
def setUpClass(cls):
super(MistralRunnerCancelTest, cls).setUpClass()
# Override the retry configuration here otherwise st2tests.config.parse_args
# in DbTestCase.setUpClass will reset these overrides.
cfg.CONF.set_override('retry_exp_msec', 100, group='mistral')
cfg.CONF.set_override('retry_exp_max_msec', 200, group='mistral')
cfg.CONF.set_override('retry_stop_max_msec', 200, group='mistral')
cfg.CONF.set_override('api_url', 'http://0.0.0.0:9101', group='auth')
# Register runners.
runnersregistrar.register_runners()
# Register test pack(s).
actions_registrar = actionsregistrar.ActionsRegistrar(
use_pack_cache=False,
fail_on_failure=True
)
for pack in PACKS:
actions_registrar.register_from_pack(pack)
@classmethod
def get_runner_class(cls, runner_name):
return runners.get_runner(runner_name).__class__
@mock.patch.object(
workflows.WorkflowManager, 'list',
mock.MagicMock(return_value=[]))
@mock.patch.object(
workflows.WorkflowManager, 'get',
mock.MagicMock(return_value=WF1))
@mock.patch.object(
workflows.WorkflowManager, 'create',
mock.MagicMock(return_value=[WF1]))
@mock.patch.object(
executions.ExecutionManager, 'create',
mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC)))
@mock.patch.object(
executions.ExecutionManager, 'update',
mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC_CANCELLED)))
def test_cancel(self):
liveaction = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS)
liveaction, execution = action_service.request(liveaction)
liveaction = LiveAction.get_by_id(str(liveaction.id))
self.assertEqual(liveaction.status, action_constants.LIVEACTION_STATUS_RUNNING)
mistral_context = liveaction.context.get('mistral', None)
self.assertIsNotNone(mistral_context)
self.assertEqual(mistral_context['execution_id'], WF1_EXEC.get('id'))
self.assertEqual(mistral_context['workflow_name'], WF1_EXEC.get('workflow_name'))
requester = cfg.CONF.system_user.user
liveaction, execution = action_service.request_cancellation(liveaction, requester)
executions.ExecutionManager.update.assert_called_with(WF1_EXEC.get('id'), 'CANCELLED')
liveaction = LiveAction.get_by_id(str(liveaction.id))
self.assertEqual(liveaction.status, action_constants.LIVEACTION_STATUS_CANCELED)
@mock.patch.object(
workflows.WorkflowManager, 'list',
mock.MagicMock(return_value=[]))
@mock.patch.object(
workflows.WorkflowManager, 'get',
mock.MagicMock(side_effect=[WF2, WF1]))
@mock.patch.object(
workflows.WorkflowManager, 'create',
mock.MagicMock(side_effect=[[WF2], [WF1]]))
@mock.patch.object(
executions.ExecutionManager, 'create',
mock.MagicMock(side_effect=[
executions.Execution(None, WF2_EXEC),
executions.Execution(None, WF1_EXEC)]))
@mock.patch.object(
executions.ExecutionManager, 'update',
mock.MagicMock(side_effect=[
executions.Execution(None, WF2_EXEC_CANCELLED),
executions.Execution(None, WF1_EXEC_CANCELLED)]))
def test_cancel_subworkflow_action(self):
liveaction1 = LiveActionDB(action=WF2_NAME, parameters=ACTION_PARAMS)
liveaction1, execution1 = action_service.request(liveaction1)
liveaction1 = LiveAction.get_by_id(str(liveaction1.id))
self.assertEqual(liveaction1.status, action_constants.LIVEACTION_STATUS_RUNNING)
liveaction2 = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS)
liveaction2, execution2 = action_service.request(liveaction2)
liveaction2 = LiveAction.get_by_id(str(liveaction2.id))
self.assertEqual(liveaction2.status, action_constants.LIVEACTION_STATUS_RUNNING)
# Mock the children of the parent execution to make this
# test case has subworkflow execution.
ActionExecutionDB.children = mock.PropertyMock(return_value=[execution2.id])
mistral_context = liveaction1.context.get('mistral', None)
self.assertIsNotNone(mistral_context)
self.assertEqual(mistral_context['execution_id'], WF2_EXEC.get('id'))
self.assertEqual(mistral_context['workflow_name'], WF2_EXEC.get('workflow_name'))
requester = cfg.CONF.system_user.user
liveaction1, execution1 = action_service.request_cancellation(liveaction1, requester)
self.assertTrue(executions.ExecutionManager.update.called)
self.assertEqual(executions.ExecutionManager.update.call_count, 2)
calls = [
mock.call(WF2_EXEC.get('id'), 'CANCELLED'),
mock.call(WF1_EXEC.get('id'), 'CANCELLED')
]
executions.ExecutionManager.update.assert_has_calls(calls, any_order=False)
@mock.patch.object(
workflows.WorkflowManager, 'list',
mock.MagicMock(return_value=[]))
@mock.patch.object(
workflows.WorkflowManager, 'get',
mock.MagicMock(return_value=WF1))
@mock.patch.object(
workflows.WorkflowManager, 'create',
mock.MagicMock(return_value=[WF1]))
@mock.patch.object(
executions.ExecutionManager, 'create',
mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC)))
@mock.patch.object(
executions.ExecutionManager, 'update',
mock.MagicMock(side_effect=[requests.exceptions.ConnectionError(),
executions.Execution(None, WF1_EXEC_CANCELLED)]))
def test_cancel_retry(self):
liveaction = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS)
liveaction, execution = action_service.request(liveaction)
liveaction = LiveAction.get_by_id(str(liveaction.id))
self.assertEqual(liveaction.status, action_constants.LIVEACTION_STATUS_RUNNING)
mistral_context = liveaction.context.get('mistral', None)
self.assertIsNotNone(mistral_context)
self.assertEqual(mistral_context['execution_id'], WF1_EXEC.get('id'))
self.assertEqual(mistral_context['workflow_name'], WF1_EXEC.get('workflow_name'))
requester = cfg.CONF.system_user.user
liveaction, execution = action_service.request_cancellation(liveaction, requester)
executions.ExecutionManager.update.assert_called_with(WF1_EXEC.get('id'), 'CANCELLED')
liveaction = LiveAction.get_by_id(str(liveaction.id))
self.assertEqual(liveaction.status, action_constants.LIVEACTION_STATUS_CANCELED)
@mock.patch.object(
workflows.WorkflowManager, 'list',
mock.MagicMock(return_value=[]))
@mock.patch.object(
workflows.WorkflowManager, 'get',
mock.MagicMock(return_value=WF1))
@mock.patch.object(
workflows.WorkflowManager, 'create',
mock.MagicMock(return_value=[WF1]))
@mock.patch.object(
executions.ExecutionManager, 'create',
mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC)))
@mock.patch.object(
executions.ExecutionManager, 'update',
mock.MagicMock(side_effect=requests.exceptions.ConnectionError('Connection refused')))
def test_cancel_retry_exhausted(self):
liveaction = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS)
liveaction, execution = action_service.request(liveaction)
liveaction = LiveAction.get_by_id(str(liveaction.id))
self.assertEqual(liveaction.status, action_constants.LIVEACTION_STATUS_RUNNING)
mistral_context = liveaction.context.get('mistral', None)
self.assertIsNotNone(mistral_context)
self.assertEqual(mistral_context['execution_id'], WF1_EXEC.get('id'))
self.assertEqual(mistral_context['workflow_name'], WF1_EXEC.get('workflow_name'))
requester = cfg.CONF.system_user.user
liveaction, execution = action_service.request_cancellation(liveaction, requester)
calls = [call(WF1_EXEC.get('id'), 'CANCELLED') for i in range(0, 2)]
executions.ExecutionManager.update.assert_has_calls(calls)
liveaction = LiveAction.get_by_id(str(liveaction.id))
self.assertEqual(liveaction.status, action_constants.LIVEACTION_STATUS_CANCELING)
|
|
import time
import datetime
import serial
import logging
from pyoperant.interfaces import base_
from pyoperant import utils, InterfaceError
logger = logging.getLogger(__name__)
# TODO: Smart find arduinos using something like this: http://stackoverflow.com/questions/19809867/how-to-check-if-serial-port-is-already-open-by-another-process-in-linux-using
# TODO: Attempt to reconnect device if it can't be reached
# TODO: Allow device to be connected to through multiple python instances. This kind of works but needs to be tested thoroughly.
class ArduinoInterface(base_.BaseInterface):
"""Creates a pyserial interface to communicate with an Arduino via the serial connection.
Communication is through two byte messages where the first byte specifies the channel and the second byte specifies the action.
Valid actions are:
0. Read input value
1. Set output to ON
2. Set output to OFF
3. Sets channel as an output
4. Sets channel as an input
5. Sets channel as an input with a pullup resistor (basically inverts the input values)
:param device_name: The address of the device on the local system (e.g. /dev/tty.usbserial)
:param baud_rate: The baud (bits/second) rate for serial communication. If this is changed, then it also needs to be changed in the arduino project code.
"""
_default_state = dict(invert=False,
held=False,
)
def __init__(self, device_name, baud_rate=19200, inputs=None, outputs=None, *args, **kwargs):
super(ArduinoInterface, self).__init__(*args, **kwargs)
self.device_name = device_name
self.baud_rate = baud_rate
self.device = None
self.read_params = ('channel', 'pullup')
self._state = dict()
self.inputs = []
self.outputs = []
self.open()
if inputs is not None:
for input_ in inputs:
self._config_read(*input_)
if outputs is not None:
for output in outputs:
self._config_write(output)
def __str__(self):
return "Arduino device at %s: %d input channels and %d output channels configured" % (self.device_name, len(self.inputs), len(self.outputs))
def __repr__(self):
# Add inputs and outputs to this
return "ArduinoInterface(%s, baud_rate=%d)" % (self.device_name, self.baud_rate)
def open(self):
'''Open a serial connection for the device
:return: None
'''
logger.debug("Opening device %s" % self)
self.device = serial.Serial(port=self.device_name,
baudrate=self.baud_rate,
timeout=5)
if self.device is None:
raise InterfaceError('Could not open serial device %s' % self.device_name)
logger.debug("Waiting for device to open")
self.device.readline()
self.device.flushInput()
logger.info("Successfully opened device %s" % self)
def close(self):
'''Close a serial connection for the device
:return: None
'''
logger.debug("Closing %s" % self)
self.device.close()
def _config_read(self, channel, pullup=False, **kwargs):
''' Configure the channel to act as an input
:param channel: the channel number to configure
:param pullup: the channel should be configured in pullup mode. On the arduino this has the effect of
returning HIGH when unpressed and LOW when pressed. The returned value will have to be inverted.
:return: None
'''
logger.debug("Configuring %s, channel %d as input" % (self.device_name, channel))
if pullup is False:
self.device.write(self._make_arg(channel, 4))
else:
self.device.write(self._make_arg(channel, 5))
if channel in self.outputs:
self.outputs.remove(channel)
if channel not in self.inputs:
self.inputs.append(channel)
self._state.setdefault(channel, self._default_state.copy())
self._state[channel]["invert"] = pullup
def _config_write(self, channel, **kwargs):
''' Configure the channel to act as an output
:param channel: the channel number to configure
:return: None
'''
logger.debug("Configuring %s, channel %d as output" % (self.device_name, channel))
self.device.write(self._make_arg(channel, 3))
if channel in self.inputs:
self.inputs.remove(channel)
if channel not in self.outputs:
self.outputs.append(channel)
self._state.setdefault(channel, self._default_state.copy())
def _read_bool(self, channel, **kwargs):
''' Read a value from the specified channel
:param channel: the channel from which to read
:return: value
Raises
------
ArduinoException
Reading from the device failed.
'''
if channel not in self._state:
raise InterfaceError("Channel %d is not configured on device %s" % (channel, self.device_name))
if self.device.inWaiting() > 0: # There is currently data in the input buffer
self.device.flushInput()
self.device.write(self._make_arg(channel, 0))
# Also need to make sure self.device.read() returns something that ord can work with. Possibly except TypeError
while True:
try:
v = ord(self.device.read())
break
# serial.SerialException("Testing")
except serial.SerialException:
# This is to make it robust in case it accidentally disconnects or you try to access the arduino in
# multiple ways
pass
except TypeError:
ArduinoException("Could not read from arduino device")
logger.debug("Read value of %d from channel %d on %s" % (v, channel, self))
if v in [0, 1]:
if self._state[channel]["invert"]:
v = 1 - v
return v == 1
else:
logger.error("Device %s returned unexpected value of %d on reading channel %d" % (self, v, channel))
# raise InterfaceError('Could not read from serial device "%s", channel %d' % (self.device, channel))
def _poll(self, channel, timeout=None, wait=None, suppress_longpress=True, **kwargs):
""" runs a loop, querying for pecks. returns peck time or None if polling times out
:param channel: the channel from which to read
:param timeout: the time, in seconds, until polling times out. Defaults to no timeout.
:param wait: the time, in seconds, between subsequent reads. Defaults to 0.
:param suppress_longpress: only return a successful read if the previous read was False. This can be helpful when using a button, where a press might trigger multiple times.
:return: timestamp of True read
"""
if timeout is not None:
start = time.time()
logger.debug("Begin polling from device %s" % self.device_name)
while True:
if not self._read_bool(channel):
logger.debug("Polling: %s" % False)
# Read returned False. If the channel was previously "held" then that flag is removed
if self._state[channel]["held"]:
self._state[channel]["held"] = False
else:
logger.debug("Polling: %s" % True)
# As long as the channel is not currently held, or longpresses are not being supressed, register the press
if (not self._state[channel]["held"]) or (not suppress_longpress):
break
if timeout is not None:
if time.time() - start >= timeout: # Return GoodNite exception?
logger.debug("Polling timed out. Returning")
return None
# Wait for a specified amount of time before continuing on with the next loop
if wait is not None:
utils.wait(wait)
self._state[channel]["held"] = True
logger.debug("Input detected. Returning")
return datetime.datetime.now()
def _write_bool(self, channel, value, **kwargs):
'''Write a value to the specified channel
:param channel: the channel to write to
:param value: the value to write
:return: value written if succeeded
'''
if channel not in self._state:
raise InterfaceError("Channel %d is not configured on device %s" % (channel, self))
logger.debug("Writing %s to device %s, channel %d" % (value, self, channel))
if value:
s = self.device.write(self._make_arg(channel, 1))
else:
s = self.device.write(self._make_arg(channel, 2))
if s:
return value
else:
raise InterfaceError('Could not write to serial device %s, channel %d' % (self.device, channel))
@staticmethod
def _make_arg(channel, value):
""" Turns a channel and boolean value into a 2 byte hex string to be fed to the arduino
:return: 2-byte hex string for input to arduino
"""
return "".join([chr(channel), chr(value)])
class ArduinoException(Exception):
pass
|
|
u""" Genetic Algrithm.
"""
import numpy as np
from random import random
import copy
from multiprocessing import Process, Queue
from math import exp,cos,sin,log
large= 1e+10
tiny = 1e-10
init_murate= 0.06
maxid= 0
def test_rosen(var,*args):
import scipy.optimize as opt
return opt.rosen(var)
def test_func(var,*args):
x,y= var
res= x**2 +y**2 +100*exp(-x**2 -y**2)*sin(2.0*(x+y))*cos(2*(x-y)) \
+80*exp(-(x-1)**2 -(y-1)**2)*cos(x+4*y)*sin(2*x-y) \
+200*sin(x+y)*exp(-(x-3)**2-(y-1)**2)
return res
def fitfunc1(val):
return exp(-val)
def fitfunc2(val):
return log(1.0/val +1.0)
def dec_to_bin(dec,nbitlen):
bin= np.zeros(nbitlen,dtype=int)
for i in range(nbitlen):
bin[i]= dec % 2
dec /= 2
return bin
def bin_to_dec(bin,nbitlen):
dec= 0
for i in range(nbitlen):
dec += bin[i]*2**(i)
return dec
def crossover(ind1,ind2):
u"""
Homogeneous crossover of two individuals to create a offspring
which has some similarities to the parents.
"""
ind= copy.deepcopy(ind1)
nbitlen= ind.genes[0].nbitlen
for i in range(len(ind.genes)):
g1= ind1.genes[i]
g2= ind1.genes[i]
for ib in range(nbitlen):
if g1.brep[ib] != g2.brep[ib] and random() < 0.5:
ind.genes[i].brep[ib]= g2.brep[ib]
return ind
def make_pairs(num):
u"""makes random pairs from num elements.
"""
arr= range(num)
pairs=[]
while len(arr) >= 2:
i= int(random()*len(arr))
ival= arr.pop(i)
j= int(random()*len(arr))
jval= arr.pop(j)
pairs.append((ival,jval))
return pairs
class Gene:
u"""Gene made of *nbitlen* bits.
"""
def __init__(self,nbitlen,var,min=-large,max=large):
self.nbitlen= nbitlen
self.brep = np.zeros(nbitlen,dtype=int)
self.set_range(min,max)
self.set_var(var)
def set_range(self,min,max):
self.min= float(min)
self.max= float(max)
def set_var(self,var):
dec= int((var-self.min)/(self.max-self.min) *(2**self.nbitlen-1))
self.brep= dec_to_bin(dec,self.nbitlen)
def get_var(self):
dec= bin_to_dec(self.brep,self.nbitlen)
return self.min +dec*(self.max-self.min)/(2**self.nbitlen-1)
def mutate(self,rate):
for i in range(self.nbitlen):
if random() < rate:
self.brep[i] = (self.brep[i]+1) % 2
class Individual:
u"""Individual made of some genes which should return evaluation value..
"""
def __init__(self,id,ngene,murate,func,*args):
self.id= id
self.ngene= ngene
self.murate= murate
self.func= func
self.args= args
self.value= 0.0
def set_genes(self,genes):
if len(genes) != self.ngene:
print "{0:*>20}: len(genes) != ngene !!!".format(' Error')
exit()
self.genes= genes
def calc_func_value(self,q):
u"""
calculates the value of given function.
"""
vars= np.zeros(len(self.genes))
for i in range(len(self.genes)):
vars[i]= self.genes[i].get_var()
val= self.func(vars,self.args)
q.put(val)
#self.value= self.func(vars,self.args)
print ' ID{0:05d}: value= {1:15.7f}'.format(self.id,val)
def mutate(self):
for gene in self.genes:
gene.mutate(self.murate)
def set_mutation_rate(self,rate):
self.murate= rate
def get_variables(self):
vars= []
for gene in self.genes:
vars.append(gene.get_var())
return vars
class GA:
u""" Genetic Algorithm class.
"""
def __init__(self,nindv,ngene,nbitlen,func,vars,vranges,fitfunc,*args):
u"""Constructor of GA class.
func
function to be evaluated with arguments vars and *args.
fitfunc
function for fitness evaluation with using function value obtained above.
"""
self.nindv= nindv
self.ngene= ngene
self.nbitlen= nbitlen
self.func= func
self.vars= vars
self.vranges= vranges
self.fitfunc= fitfunc
self.args= args
self.create_population()
def keep_best_individual(self):
vals= []
for i in range(len(self.population)):
vals.append(self.population[i].value)
minval= min(vals)
if minval < self.best_individual.value:
idx= vals.index(minval)
self.best_individual= copy.deepcopy(self.population[idx])
def create_population(self):
u"""creates *nindv* individuals around the initial guess."""
global maxid
self.population= []
#.....0th individual is the initial guess if there is
ind= Individual(0,self.ngene,init_murate,self.func,self.args)
genes=[]
for ig in range(self.ngene):
g= Gene(self.nbitlen,self.vars[ig]
,min=self.vranges[ig,0],max=self.vranges[ig,1])
genes.append(g)
ind.set_genes(genes)
self.population.append(ind)
#.....other individuals whose genes are randomly distributed
for i in range(self.nindv-1):
ind= Individual(i+1,self.ngene,init_murate,self.func,self.args)
maxid= i+1
genes= []
for ig in range(self.ngene):
g= Gene(self.nbitlen,self.vars[ig]
,min=self.vranges[ig,0],max=self.vranges[ig,1])
#.....randomize by mutating with high rate
g.mutate(0.25)
genes.append(g)
ind.set_genes(genes)
self.population.append(ind)
def roulette_selection(self):
u"""selects *nindv* individuals according to their fitnesses
by means of roulette.
"""
#.....calc all the probabilities
prob= []
for ind in self.population:
prob.append(self.fitfunc(ind.value))
print prob
self.keep_best_individual()
istore=[]
for i in range(len(self.population)):
istore.append(0)
print istore
for i in range(self.nindv):
ptot= 0.0
for ii in range(len(self.population)):
if istore[ii] == 1: continue
ptot += prob[ii]
prnd= random()*ptot
ptot= 0.0
for ii in range(len(self.population)):
if istore[ii] == 1: continue
ptot= ptot +prob[ii]
#print ii,prnd,ptot
if prnd < ptot:
istore[ii]= 1
break
print istore
while istore.count(0) > 0:
idx= istore.index(0)
del self.population[idx]
del istore[idx]
if len(self.population) != self.nindv:
print "{0:*>20}: len(self.population != self.nindv) !!!".format(' Error')
print len(self.population), self.nindv
exit()
def run(self,maxiter=100):
u"""main loop of GA.
"""
global maxid
#.....parallel processes of function evaluations
prcs= []
qs= []
for i in range(self.nindv):
qs.append(Queue())
prcs.append(Process(target=self.population[i].calc_func_value
,args=(qs[i],)))
for p in prcs:
p.start()
for p in prcs:
p.join()
for i in range(self.nindv):
self.population[i].value= qs[i].get()
for it in range(maxiter):
print ' step= {0:8d}'.format(it+1)
#.....give birth to some offsprings by crossover
pairs= make_pairs(self.nindv)
for pair in pairs:
new_ind= crossover(self.population[pair[0]],
self.population[pair[1]])
maxid += 1
new_ind.id= maxid
self.population.append(new_ind)
#.....mutation of new born offsprings
for i in range(self.nindv,len(self.population)):
self.population[i].mutate()
#.....evaluate function values of new born offsprings
prcs= []
qs= []
j=0
for i in range(self.nindv,len(self.population)):
qs.append(Queue())
prcs.append(Process(target=self.population[i].calc_func_value,
args=(qs[j],)))
j += 1
for p in prcs:
p.start()
for p in prcs:
p.join()
j=0
for i in range(self.nindv,len(self.population)):
self.population[i].value= qs[j].get()
j += 1
#.....selection
self.roulette_selection()
#.....output the current best if needed
self.out_current_best()
print ' Best record:'
best= self.best_individual
print ' ID= {0:05d}'.format(best.id)
print ' value= {0:15.7f}'.format(best.value)
print ' variables= ',best.get_variables()
def out_current_best(self):
best= self.best_individual
print ' current best ID{0:05d}, '.format(best.id) \
+'value= {0:15.7f}'.format(best.value)
f=open('out.current_best','w')
f.write('ID= {0:05d}\n'.format(best.id))
f.write('value= {0:15.7f}\n'.format(best.value))
f.write('variables:\n')
vars= best.get_variables()
for var in vars:
f.write('{0:15.7e}\n'.format(var))
f.close()
if __name__ == '__main__':
vars= np.array([0.1,0.2])
vranges= np.array([[-5.0,5.0],[-5.0,5.0]])
ga= GA(10,2,16,test_func,vars,vranges,fitfunc1)
ga.run(20)
|
|
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
"""Unit tests for the pipeline options module."""
# pytype: skip-file
from __future__ import absolute_import
import logging
import unittest
import hamcrest as hc
from apache_beam.options.pipeline_options import DebugOptions
from apache_beam.options.pipeline_options import GoogleCloudOptions
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import ProfilingOptions
from apache_beam.options.pipeline_options import TypeOptions
from apache_beam.options.pipeline_options import WorkerOptions
from apache_beam.options.value_provider import RuntimeValueProvider
from apache_beam.options.value_provider import StaticValueProvider
from apache_beam.transforms.display import DisplayData
from apache_beam.transforms.display_test import DisplayDataItemMatcher
class PipelineOptionsTest(unittest.TestCase):
def setUp(self):
# Reset runtime options to avoid side-effects caused by other tests.
# Note that is_accessible assertions require runtime_options to
# be uninitialized.
RuntimeValueProvider.set_runtime_options(None)
def tearDown(self):
# Reset runtime options to avoid side-effects in other tests.
RuntimeValueProvider.set_runtime_options(None)
TEST_CASES = [
{
'flags': ['--num_workers', '5'],
'expected': {
'num_workers': 5,
'mock_flag': False,
'mock_option': None,
'mock_multi_option': None
},
'display_data': [DisplayDataItemMatcher('num_workers', 5)]
},
{
'flags': ['--direct_num_workers', '5'],
'expected': {
'direct_num_workers': 5,
'mock_flag': False,
'mock_option': None,
'mock_multi_option': None
},
'display_data': [DisplayDataItemMatcher('direct_num_workers', 5)]
},
{
'flags': ['--direct_running_mode', 'multi_threading'],
'expected': {
'direct_running_mode': 'multi_threading',
'mock_flag': False,
'mock_option': None,
'mock_multi_option': None
},
'display_data': [
DisplayDataItemMatcher('direct_running_mode', 'multi_threading')
]
},
{
'flags': ['--direct_running_mode', 'multi_processing'],
'expected': {
'direct_running_mode': 'multi_processing',
'mock_flag': False,
'mock_option': None,
'mock_multi_option': None
},
'display_data': [
DisplayDataItemMatcher('direct_running_mode', 'multi_processing')
]
},
{
'flags': [
'--profile_cpu', '--profile_location', 'gs://bucket/', 'ignored'
],
'expected': {
'profile_cpu': True,
'profile_location': 'gs://bucket/',
'mock_flag': False,
'mock_option': None,
'mock_multi_option': None
},
'display_data': [
DisplayDataItemMatcher('profile_cpu', True),
DisplayDataItemMatcher('profile_location', 'gs://bucket/')
]
},
{
'flags': ['--num_workers', '5', '--mock_flag'],
'expected': {
'num_workers': 5,
'mock_flag': True,
'mock_option': None,
'mock_multi_option': None
},
'display_data': [
DisplayDataItemMatcher('num_workers', 5),
DisplayDataItemMatcher('mock_flag', True)
]
},
{
'flags': ['--mock_option', 'abc'],
'expected': {
'mock_flag': False,
'mock_option': 'abc',
'mock_multi_option': None
},
'display_data': [DisplayDataItemMatcher('mock_option', 'abc')]
},
{
'flags': ['--mock_option', ' abc def '],
'expected': {
'mock_flag': False,
'mock_option': ' abc def ',
'mock_multi_option': None
},
'display_data': [DisplayDataItemMatcher('mock_option', ' abc def ')]
},
{
'flags': ['--mock_option= abc xyz '],
'expected': {
'mock_flag': False,
'mock_option': ' abc xyz ',
'mock_multi_option': None
},
'display_data': [DisplayDataItemMatcher('mock_option', ' abc xyz ')]
},
{
'flags': [
'--mock_option=gs://my bucket/my folder/my file',
'--mock_multi_option=op1',
'--mock_multi_option=op2'
],
'expected': {
'mock_flag': False,
'mock_option': 'gs://my bucket/my folder/my file',
'mock_multi_option': ['op1', 'op2']
},
'display_data': [
DisplayDataItemMatcher(
'mock_option', 'gs://my bucket/my folder/my file'),
DisplayDataItemMatcher('mock_multi_option', ['op1', 'op2'])
]
},
{
'flags': ['--mock_multi_option=op1', '--mock_multi_option=op2'],
'expected': {
'mock_flag': False,
'mock_option': None,
'mock_multi_option': ['op1', 'op2']
},
'display_data': [
DisplayDataItemMatcher('mock_multi_option', ['op1', 'op2'])
]
},
]
# Used for testing newly added flags.
class MockOptions(PipelineOptions):
@classmethod
def _add_argparse_args(cls, parser):
parser.add_argument('--mock_flag', action='store_true', help='mock flag')
parser.add_argument('--mock_option', help='mock option')
parser.add_argument(
'--mock_multi_option', action='append', help='mock multi option')
parser.add_argument('--option with space', help='mock option with space')
# Use with MockOptions in test cases where multiple option classes are needed.
class FakeOptions(PipelineOptions):
@classmethod
def _add_argparse_args(cls, parser):
parser.add_argument('--fake_flag', action='store_true', help='fake flag')
parser.add_argument('--fake_option', help='fake option')
parser.add_argument(
'--fake_multi_option', action='append', help='fake multi option')
def test_display_data(self):
for case in PipelineOptionsTest.TEST_CASES:
options = PipelineOptions(flags=case['flags'])
dd = DisplayData.create_from(options)
hc.assert_that(dd.items, hc.contains_inanyorder(*case['display_data']))
def test_get_all_options_subclass(self):
for case in PipelineOptionsTest.TEST_CASES:
options = PipelineOptionsTest.MockOptions(flags=case['flags'])
self.assertDictContainsSubset(case['expected'], options.get_all_options())
self.assertEqual(
options.view_as(PipelineOptionsTest.MockOptions).mock_flag,
case['expected']['mock_flag'])
self.assertEqual(
options.view_as(PipelineOptionsTest.MockOptions).mock_option,
case['expected']['mock_option'])
self.assertEqual(
options.view_as(PipelineOptionsTest.MockOptions).mock_multi_option,
case['expected']['mock_multi_option'])
def test_get_all_options(self):
for case in PipelineOptionsTest.TEST_CASES:
options = PipelineOptions(flags=case['flags'])
self.assertDictContainsSubset(case['expected'], options.get_all_options())
self.assertEqual(
options.view_as(PipelineOptionsTest.MockOptions).mock_flag,
case['expected']['mock_flag'])
self.assertEqual(
options.view_as(PipelineOptionsTest.MockOptions).mock_option,
case['expected']['mock_option'])
self.assertEqual(
options.view_as(PipelineOptionsTest.MockOptions).mock_multi_option,
case['expected']['mock_multi_option'])
def test_sublcalsses_of_pipeline_options_can_be_instantiated(self):
for case in PipelineOptionsTest.TEST_CASES:
mock_options = PipelineOptionsTest.MockOptions(flags=case['flags'])
self.assertEqual(mock_options.mock_flag, case['expected']['mock_flag'])
self.assertEqual(
mock_options.mock_option, case['expected']['mock_option'])
self.assertEqual(
mock_options.mock_multi_option, case['expected']['mock_multi_option'])
def test_views_can_be_constructed_from_pipeline_option_subclasses(self):
for case in PipelineOptionsTest.TEST_CASES:
fake_options = PipelineOptionsTest.FakeOptions(flags=case['flags'])
mock_options = fake_options.view_as(PipelineOptionsTest.MockOptions)
self.assertEqual(mock_options.mock_flag, case['expected']['mock_flag'])
self.assertEqual(
mock_options.mock_option, case['expected']['mock_option'])
self.assertEqual(
mock_options.mock_multi_option, case['expected']['mock_multi_option'])
def test_views_do_not_expose_options_defined_by_other_views(self):
flags = ['--mock_option=mock_value', '--fake_option=fake_value']
options = PipelineOptions(flags)
assert options.view_as(
PipelineOptionsTest.MockOptions).mock_option == 'mock_value'
assert options.view_as(
PipelineOptionsTest.FakeOptions).fake_option == 'fake_value'
assert options.view_as(PipelineOptionsTest.MockOptions).view_as(
PipelineOptionsTest.FakeOptions).fake_option == 'fake_value'
self.assertRaises(
AttributeError,
lambda: options.view_as(PipelineOptionsTest.MockOptions).fake_option)
self.assertRaises(
AttributeError,
lambda: options.view_as(PipelineOptionsTest.MockOptions).view_as(
PipelineOptionsTest.FakeOptions).view_as(
PipelineOptionsTest.MockOptions).fake_option)
def test_from_dictionary(self):
for case in PipelineOptionsTest.TEST_CASES:
options = PipelineOptions(flags=case['flags'])
all_options_dict = options.get_all_options()
options_from_dict = PipelineOptions.from_dictionary(all_options_dict)
self.assertEqual(
options_from_dict.view_as(PipelineOptionsTest.MockOptions).mock_flag,
case['expected']['mock_flag'])
self.assertEqual(
options.view_as(PipelineOptionsTest.MockOptions).mock_option,
case['expected']['mock_option'])
def test_option_with_space(self):
options = PipelineOptions(flags=['--option with space= value with space'])
self.assertEqual(
getattr(
options.view_as(PipelineOptionsTest.MockOptions),
'option with space'),
' value with space')
options_from_dict = PipelineOptions.from_dictionary(
options.get_all_options())
self.assertEqual(
getattr(
options_from_dict.view_as(PipelineOptionsTest.MockOptions),
'option with space'),
' value with space')
def test_retain_unknown_options_binary_store_string(self):
options = PipelineOptions(['--unknown_option', 'some_value'])
result = options.get_all_options(retain_unknown_options=True)
self.assertEqual(result['unknown_option'], 'some_value')
def test_retain_unknown_options_binary_equals_store_string(self):
options = PipelineOptions(['--unknown_option=some_value'])
result = options.get_all_options(retain_unknown_options=True)
self.assertEqual(result['unknown_option'], 'some_value')
def test_retain_unknown_options_binary_multi_equals_store_string(self):
options = PipelineOptions(['--unknown_option=expr = "2 + 2 = 5"'])
result = options.get_all_options(retain_unknown_options=True)
self.assertEqual(result['unknown_option'], 'expr = "2 + 2 = 5"')
def test_retain_unknown_options_binary_single_dash_store_string(self):
options = PipelineOptions(['-i', 'some_value'])
result = options.get_all_options(retain_unknown_options=True)
self.assertEqual(result['i'], 'some_value')
def test_retain_unknown_options_unary_store_true(self):
options = PipelineOptions(['--unknown_option'])
result = options.get_all_options(retain_unknown_options=True)
self.assertEqual(result['unknown_option'], True)
def test_retain_unknown_options_consecutive_unary_store_true(self):
options = PipelineOptions(['--option_foo', '--option_bar'])
result = options.get_all_options(retain_unknown_options=True)
self.assertEqual(result['option_foo'], True)
self.assertEqual(result['option_bar'], True)
def test_retain_unknown_options_unary_single_dash_store_true(self):
options = PipelineOptions(['-i'])
result = options.get_all_options(retain_unknown_options=True)
self.assertEqual(result['i'], True)
def test_retain_unknown_options_unary_missing_prefix(self):
options = PipelineOptions(['bad_option'])
with self.assertRaises(SystemExit):
options.get_all_options(retain_unknown_options=True)
def test_override_options(self):
base_flags = ['--num_workers', '5']
options = PipelineOptions(base_flags)
self.assertEqual(options.get_all_options()['num_workers'], 5)
self.assertEqual(options.get_all_options()['mock_flag'], False)
options.view_as(PipelineOptionsTest.MockOptions).mock_flag = True
self.assertEqual(options.get_all_options()['num_workers'], 5)
self.assertTrue(options.get_all_options()['mock_flag'])
def test_override_init_options(self):
base_flags = ['--num_workers', '5']
options = PipelineOptions(base_flags, mock_flag=True)
self.assertEqual(options.get_all_options()['num_workers'], 5)
self.assertEqual(options.get_all_options()['mock_flag'], True)
def test_invalid_override_init_options(self):
base_flags = ['--num_workers', '5']
options = PipelineOptions(base_flags, mock_invalid_flag=True)
self.assertEqual(options.get_all_options()['num_workers'], 5)
self.assertEqual(options.get_all_options()['mock_flag'], False)
def test_experiments(self):
options = PipelineOptions(['--experiment', 'abc', '--experiment', 'def'])
self.assertEqual(
sorted(options.get_all_options()['experiments']), ['abc', 'def'])
options = PipelineOptions(['--experiments', 'abc', '--experiments', 'def'])
self.assertEqual(
sorted(options.get_all_options()['experiments']), ['abc', 'def'])
options = PipelineOptions(flags=[''])
self.assertEqual(options.get_all_options()['experiments'], None)
def test_worker_options(self):
options = PipelineOptions(['--machine_type', 'abc', '--disk_type', 'def'])
worker_options = options.view_as(WorkerOptions)
self.assertEqual(worker_options.machine_type, 'abc')
self.assertEqual(worker_options.disk_type, 'def')
options = PipelineOptions(
['--worker_machine_type', 'abc', '--worker_disk_type', 'def'])
worker_options = options.view_as(WorkerOptions)
self.assertEqual(worker_options.machine_type, 'abc')
self.assertEqual(worker_options.disk_type, 'def')
def test_option_modifications_are_shared_between_views(self):
pipeline_options = PipelineOptions([
'--mock_option',
'value',
'--mock_flag',
'--mock_multi_option',
'value1',
'--mock_multi_option',
'value2',
])
mock_options = PipelineOptionsTest.MockOptions([
'--mock_option',
'value',
'--mock_flag',
'--mock_multi_option',
'value1',
'--mock_multi_option',
'value2',
])
for options in [pipeline_options, mock_options]:
view1 = options.view_as(PipelineOptionsTest.MockOptions)
view2 = options.view_as(PipelineOptionsTest.MockOptions)
view1.mock_option = 'new_value'
view1.mock_flag = False
view1.mock_multi_option.append('value3')
view3 = options.view_as(PipelineOptionsTest.MockOptions)
view4 = view1.view_as(PipelineOptionsTest.MockOptions)
view5 = options.view_as(TypeOptions).view_as(
PipelineOptionsTest.MockOptions)
for view in [view1, view2, view3, view4, view5]:
self.assertEqual('new_value', view.mock_option)
self.assertFalse(view.mock_flag)
self.assertEqual(['value1', 'value2', 'value3'], view.mock_multi_option)
def test_uninitialized_option_modifications_are_shared_between_views(self):
options = PipelineOptions([])
view1 = options.view_as(PipelineOptionsTest.MockOptions)
view2 = options.view_as(PipelineOptionsTest.MockOptions)
view1.mock_option = 'some_value'
view1.mock_flag = False
view1.mock_multi_option = ['value1', 'value2']
view3 = options.view_as(PipelineOptionsTest.MockOptions)
view4 = view1.view_as(PipelineOptionsTest.MockOptions)
view5 = options.view_as(TypeOptions).view_as(
PipelineOptionsTest.MockOptions)
for view in [view1, view2, view3, view4, view5]:
self.assertEqual('some_value', view.mock_option)
self.assertFalse(view.mock_flag)
self.assertEqual(['value1', 'value2'], view.mock_multi_option)
def test_extra_package(self):
options = PipelineOptions([
'--extra_package',
'abc',
'--extra_packages',
'def',
'--extra_packages',
'ghi'
])
self.assertEqual(
sorted(options.get_all_options()['extra_packages']),
['abc', 'def', 'ghi'])
options = PipelineOptions(flags=[''])
self.assertEqual(options.get_all_options()['extra_packages'], None)
def test_dataflow_job_file(self):
options = PipelineOptions(['--dataflow_job_file', 'abc'])
self.assertEqual(options.get_all_options()['dataflow_job_file'], 'abc')
options = PipelineOptions(flags=[''])
self.assertEqual(options.get_all_options()['dataflow_job_file'], None)
def test_template_location(self):
options = PipelineOptions(['--template_location', 'abc'])
self.assertEqual(options.get_all_options()['template_location'], 'abc')
options = PipelineOptions(flags=[''])
self.assertEqual(options.get_all_options()['template_location'], None)
def test_redefine_options(self):
class TestRedefinedOptions(PipelineOptions): # pylint: disable=unused-variable
@classmethod
def _add_argparse_args(cls, parser):
parser.add_argument('--redefined_flag', action='store_true')
class TestRedefinedOptions(PipelineOptions):
@classmethod
def _add_argparse_args(cls, parser):
parser.add_argument('--redefined_flag', action='store_true')
options = PipelineOptions(['--redefined_flag'])
self.assertTrue(options.get_all_options()['redefined_flag'])
# TODO(BEAM-1319): Require unique names only within a test.
# For now, <file name acronym>_vp_arg<number> will be the convention
# to name value-provider arguments in tests, as opposed to
# <file name acronym>_non_vp_arg<number> for non-value-provider arguments.
# The number will grow per file as tests are added.
def test_value_provider_options(self):
class UserOptions(PipelineOptions):
@classmethod
def _add_argparse_args(cls, parser):
parser.add_value_provider_argument(
'--pot_vp_arg1', help='This flag is a value provider')
parser.add_value_provider_argument('--pot_vp_arg2', default=1, type=int)
parser.add_argument('--pot_non_vp_arg1', default=1, type=int)
# Provide values: if not provided, the option becomes of the type runtime vp
options = UserOptions(['--pot_vp_arg1', 'hello'])
self.assertIsInstance(options.pot_vp_arg1, StaticValueProvider)
self.assertIsInstance(options.pot_vp_arg2, RuntimeValueProvider)
self.assertIsInstance(options.pot_non_vp_arg1, int)
# Values can be overwritten
options = UserOptions(
pot_vp_arg1=5,
pot_vp_arg2=StaticValueProvider(value_type=str, value='bye'),
pot_non_vp_arg1=RuntimeValueProvider(
option_name='foo', value_type=int, default_value=10))
self.assertEqual(options.pot_vp_arg1, 5)
self.assertTrue(
options.pot_vp_arg2.is_accessible(),
'%s is not accessible' % options.pot_vp_arg2)
self.assertEqual(options.pot_vp_arg2.get(), 'bye')
self.assertFalse(options.pot_non_vp_arg1.is_accessible())
with self.assertRaises(RuntimeError):
options.pot_non_vp_arg1.get()
# Converts extra arguments to list value.
def test_extra_args(self):
options = PipelineOptions([
'--extra_arg',
'val1',
'--extra_arg',
'val2',
'--extra_arg=val3',
'--unknown_arg',
'val4'
])
def add_extra_options(parser):
parser.add_argument("--extra_arg", action='append')
self.assertEqual(
options.get_all_options(
add_extra_args_fn=add_extra_options)['extra_arg'],
['val1', 'val2', 'val3'])
# The argparse package by default tries to autocomplete option names. This
# results in an "ambiguous option" error from argparse when an unknown option
# matching multiple known ones are used. This tests that we suppress this
# error.
def test_unknown_option_prefix(self):
# Test that the "ambiguous option" error is suppressed.
options = PipelineOptions(['--profi', 'val1'])
options.view_as(ProfilingOptions)
# Test that valid errors are not suppressed.
with self.assertRaises(SystemExit):
# Invalid option choice.
options = PipelineOptions(['--type_check_strictness', 'blahblah'])
options.view_as(TypeOptions)
def test_add_experiment(self):
options = PipelineOptions([])
options.view_as(DebugOptions).add_experiment('new_experiment')
self.assertEqual(['new_experiment'],
options.view_as(DebugOptions).experiments)
def test_add_experiment_preserves_existing_experiments(self):
options = PipelineOptions(['--experiment=existing_experiment'])
options.view_as(DebugOptions).add_experiment('new_experiment')
self.assertEqual(['existing_experiment', 'new_experiment'],
options.view_as(DebugOptions).experiments)
def test_lookup_experiments(self):
options = PipelineOptions([
'--experiment=existing_experiment',
'--experiment',
'key=value',
'--experiment',
'master_key=k1=v1,k2=v2',
])
debug_options = options.view_as(DebugOptions)
self.assertEqual(
'default_value',
debug_options.lookup_experiment('nonexistent', 'default_value'))
self.assertEqual(
'value', debug_options.lookup_experiment('key', 'default_value'))
self.assertEqual(
'k1=v1,k2=v2', debug_options.lookup_experiment('master_key'))
self.assertEqual(
True, debug_options.lookup_experiment('existing_experiment'))
def test_transform_name_mapping(self):
options = PipelineOptions(['--transform_name_mapping={\"from\":\"to\"}'])
mapping = options.view_as(GoogleCloudOptions).transform_name_mapping
self.assertEqual(mapping['from'], 'to')
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
unittest.main()
|
|
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
"""This module contains a Google Calendar API hook"""
from datetime import datetime
from typing import Any, Dict, Optional, Sequence, Union
from googleapiclient.discovery import build
from airflow.exceptions import AirflowException
from airflow.providers.google.common.hooks.base_google import GoogleBaseHook
class GoogleCalendarHook(GoogleBaseHook):
"""
Interact with Google Calendar via Google Cloud connection
Reading and writing cells in Google Sheet:
https://developers.google.com/calendar/api/v3/reference
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param api_version: API Version. For example v3
:param delegate_to: The account to impersonate using domain-wide delegation of authority,
if any. For this to work, the service account making the request must have
domain-wide delegation enabled.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account.
"""
def __init__(
self,
api_version: str,
gcp_conn_id: str = 'google_cloud_default',
delegate_to: Optional[str] = None,
impersonation_chain: Optional[Union[str, Sequence[str]]] = None,
) -> None:
super().__init__(
gcp_conn_id=gcp_conn_id,
delegate_to=delegate_to,
impersonation_chain=impersonation_chain,
)
self.gcp_conn_id = gcp_conn_id
self.api_version = api_version
self.delegate_to = delegate_to
self._conn = None
def get_conn(self) -> Any:
"""
Retrieves connection to Google Calendar.
:return: Google Calendar services object.
:rtype: Any
"""
if not self._conn:
http_authorized = self._authorize()
self._conn = build('calendar', self.api_version, http=http_authorized, cache_discovery=False)
return self._conn
def get_events(
self,
calendar_id: str = 'primary',
i_cal_uid: Optional[str] = None,
max_attendees: Optional[int] = None,
max_results: Optional[int] = None,
order_by: Optional[str] = None,
private_extended_property: Optional[str] = None,
q: Optional[str] = None,
shared_extended_property: Optional[str] = None,
show_deleted: Optional[bool] = False,
show_hidden_invitation: Optional[bool] = False,
single_events: Optional[bool] = False,
sync_token: Optional[str] = None,
time_max: Optional[datetime] = None,
time_min: Optional[datetime] = None,
time_zone: Optional[str] = None,
updated_min: Optional[datetime] = None,
) -> list:
"""
Gets events from Google Calendar from a single calendar_id
https://developers.google.com/calendar/api/v3/reference/events/list
:param calendar_id: The Google Calendar ID to interact with
:param i_cal_uid: Optional. Specifies event ID in the ``iCalendar`` format in the response.
:param max_attendees: Optional. If there are more than the specified number of attendees,
only the participant is returned.
:param max_results: Optional. Maximum number of events returned on one result page.
Incomplete pages can be detected by a non-empty ``nextPageToken`` field in the response.
By default the value is 250 events. The page size can never be larger than 2500 events
:param order_by: Optional. Acceptable values are ``"startTime"`` or "updated"
:param private_extended_property: Optional. Extended properties constraint specified as
``propertyName=value``. Matches only private properties. This parameter might be repeated
multiple times to return events that match all given constraints.
:param q: Optional. Free text search.
:param shared_extended_property: Optional. Extended properties constraint specified as
``propertyName=value``. Matches only shared properties. This parameter might be repeated
multiple times to return events that match all given constraints.
:param show_deleted: Optional. False by default
:param show_hidden_invitation: Optional. False by default
:param single_events: Optional. False by default
:param sync_token: Optional. Token obtained from the ``nextSyncToken`` field returned
:param time_max: Optional. Upper bound (exclusive) for an event's start time to filter by.
Default is no filter
:param time_min: Optional. Lower bound (exclusive) for an event's end time to filter by.
Default is no filter
:param time_zone: Optional. Time zone used in response. Default is calendars time zone.
:param updated_min: Optional. Lower bound for an event's last modification time
:rtype: List
"""
service = self.get_conn()
page_token = None
events = []
while True:
response = (
service.events()
.list(
calendarId=calendar_id,
iCalUID=i_cal_uid,
maxAttendees=max_attendees,
maxResults=max_results,
orderBy=order_by,
pageToken=page_token,
privateExtendedProperty=private_extended_property,
q=q,
sharedExtendedProperty=shared_extended_property,
showDeleted=show_deleted,
showHiddenInvitations=show_hidden_invitation,
singleEvents=single_events,
syncToken=sync_token,
timeMax=time_max,
timeMin=time_min,
timeZone=time_zone,
updatedMin=updated_min,
)
.execute(num_retries=self.num_retries)
)
events.extend(response["items"])
page_token = response.get("nextPageToken")
if not page_token:
break
return events
def create_event(
self,
event: Dict[str, Any],
calendar_id: str = 'primary',
conference_data_version: Optional[int] = 0,
max_attendees: Optional[int] = None,
send_notifications: Optional[bool] = False,
send_updates: Optional[str] = 'false',
supports_attachments: Optional[bool] = False,
) -> dict:
"""
Create event on the specified calendar
https://developers.google.com/calendar/api/v3/reference/events/insert
:param calendar_id: The Google Calendar ID to interact with
:param conference_data_version: Optional. Version number of conference data
supported by the API client.
:param max_attendees: Optional. If there are more than the specified number of attendees,
only the participant is returned.
:param send_notifications: Optional. Default is False
:param send_updates: Optional. Default is "false". Acceptable values as "all", "none",
``"externalOnly"``
https://developers.google.com/calendar/api/v3/reference/events#resource
:rtype: Dict
"""
if "start" not in event or "end" not in event:
raise AirflowException(
f"start and end must be specified in the event body while creating an event. API docs:"
f"https://developers.google.com/calendar/api/{self.api_version}/reference/events/insert "
)
service = self.get_conn()
response = (
service.events()
.insert(
calendarId=calendar_id,
conferenceDataVersion=conference_data_version,
maxAttendees=max_attendees,
sendNotifications=send_notifications,
sendUpdates=send_updates,
supportsAttachments=supports_attachments,
body=event,
)
.execute(num_retries=self.num_retries)
)
return response
|
|
"""Check and Setup Phylotyper Ontology and Subtyping Schemes
Example:
$ python ontolog.py -s stx1
"""
import logging
import os
from rdflib import Graph, Literal, XSD
from modules.phylotyper.exceptions import ValuesError, DatabaseError
from middleware.graphers.turtle_utils import generate_uri as gu
from middleware.decorators import submit, prefix, tojson
from middleware.blazegraph.upload_graph import upload_turtle, upload_graph
from modules.phylotyper.graph_refs import graph_refs
log = logging.getLogger(__name__)
typing_ontology_version = '<https://www.github.com/superphy/typing/1.0.0>'
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
LOCI = {
'stx1': [':stx1A', ':stx1B'],
'stx2': [':stx2A', ':stx2B'],
'eae': [':eae']
}
@submit
@prefix
def version_query(v):
"""
Queries for a given typing ontology version
returns:
dictionary
"""
query = '''
SELECT ?version
WHERE {{
?version rdf:type owl:Ontology .
?version owl:versionIRI {ver}
}}
'''.format(ver=v)
return query
@tojson
@submit
@prefix
def schema_query(subtype):
"""
Queries for a phylotyper subtype definition
Returns:
dictionary
"""
query = '''
SELECT ?i ?locus
WHERE {{
VALUES ?subtype {{ {} }}
?subtype rdf:type subt:Phylotyper ;
typon:hasSchema ?schema .
?schema typon:hasSchemaPart ?schemaPart .
?schemaPart typon:index ?i ;
typon:hasLocus ?locus
}}
'''.format(subtype)
return query
@tojson
@submit
@prefix
def subtypeset_query(subtype):
"""
Queries for a phylotyper subtype values
Returns:
dictionary
"""
query = '''
SELECT ?part ?value
WHERE {{
VALUES ?subtype {{ {} }}
?subtype rdf:type subt:Phylotyper ;
subt:hasSubtypeSet ?sset .
?sset subt:hasDefinedClass ?part .
?part subt:subtypeValue ?value
}}
'''.format(subtype)
return query
@submit
@prefix
def subtype_query(subtype, rdftype='subt:Phylotyper'):
"""
Queries for a specific URI of given type
Returns:
dictionary
"""
query = '''
SELECT ?subtype
WHERE {{
?subtype rdf:type {} .
VALUES ?subtype {{ {} }}
}}
'''.format(rdftype, subtype)
return query
def match_version(version):
"""
Returns true if ontology with given version is already in database
Args:
version(str): ontology version string e.g. <https://www.github.com/superphy/typing/1.0.0>
"""
result = version_query(version)
if result['results']['bindings']:
return True
else:
return False
def find_object(uri, rdftype):
"""
Returns true if URI is already in database
Args:
uri(str): URI with prefix defined in config.py
rdftype(str): the URI linked by a rdf:type relationship to URI
"""
result = subtype_query(uri, rdftype)
if result['results']['bindings']:
return True
else:
return False
def generate_graph(uri, loci, values):
"""
Returns graph object that defines phylotyper subtype schema
"""
subtype = uri.split(':')[1]
# Check for existance of schema Marker components
# for l in loci:
# if not find_object(l, ':Marker'):
# raise DatabaseError(uri, l)
# Proceed with creating subtype schema
graph = Graph()
# Create instance of phylotyper subtype
phylotyper = gu(uri)
a = gu('rdf:type')
label = gu('rdfs:label')
graph.add((phylotyper, a, gu('subt:Phylotyper')))
# Define Schema
schema_uri = uri + 'Schema'
schema = gu(schema_uri)
graph.add((schema, a, gu('typon:Schema')))
graph.add((schema, label, Literal('{} schema'.format(subtype), lang='en')))
part = 1
for l in loci:
schemapart = gu(schema_uri+'_part_{}'.format(part))
graph.add((schemapart, a, gu('typon:SchemaPart')))
graph.add((schemapart, label, Literal('{} schema part {}'.format(subtype, part), lang='en')))
graph.add((schemapart, gu('typon:index'), Literal(part, datatype=XSD.integer)))
graph.add((schemapart, gu('typon:hasLocus'), gu(l)))
graph.add((schema, gu('typon:hasSchemaPart'), schemapart))
part += 1
graph.add((phylotyper, gu('typon:hasSchema'), schema))
# Define Subtype Values
set_uri = uri + 'SubtypeSet'
subtype_set = gu(set_uri)
graph.add((subtype_set, a, gu('subt:SubtypeSet')))
graph.add((subtype_set, label, Literal('{} subtype set'.format(subtype), lang='en')))
for v in values:
setpart = gu(set_uri+'_class_{}'.format(v))
graph.add((setpart, a, gu('subt:SubtypeClass')))
graph.add((setpart, label, Literal('{} subtype class {}'.format(subtype, v), lang='en')))
graph.add((setpart, gu('subt:subtypeValue'), Literal(v, datatype=XSD.string)))
graph.add((subtype_set, gu('subt:hasDefinedClass'), setpart))
graph.add((phylotyper, gu('subt:hasSubtypeSet'), subtype_set))
return graph
def stx1_graph():
"""
Returns graph object that defines stx2 phylotyper subtype schema
"""
return generate_graph('subt:stx1', LOCI['stx1'], ['a','c','d','untypeable'])
def stx2_graph():
"""
Returns graph object that defines stx2 phylotyper subtype schema
"""
return generate_graph('subt:stx2', LOCI['stx2'], ['a','b','c','d','e','f','g','untypeable'])
def eae_graph():
"""
Returns graph object that defines eae phylotyper subtype schema
"""
return generate_graph('subt:eae', LOCI['eae'],
["alpha-1","alpha-2","beta-1","beta-2","epsilon-1","epsilon-2","eta-1","eta-2",
"gamma-1","iota-1","iota-2","kappa-1","lambda-1","mu-1","nu-1","omicron-1","pi-1",
"rho-1","sigma-1","theta-2","xi-1","zeta-1","untypeable"])
def load(subtype):
"""
Loads typing ontology and schema for a given phylotyper subtype
Args:
subtype(str): A subtype name that matches one of the defined subtype initialization methods in this module
Returns:
list with marker URIs that make up schema for subtype
"""
func_name = subtype+'_graph'
uri = 'subt:'+subtype
if not func_name in globals():
raise ValuesError(subtype)
graph_func = globals()[func_name]
ontology_turtle_file = os.path.join(__location__, 'superphy_subtyping.ttl')
if not match_version(typing_ontology_version):
log.info('Uploading subtyping ontolog version: {}'.format(typing_ontology_version))
response = upload_turtle(ontology_turtle_file)
log.info('Upload returned response: {}'.format(response))
# add reference graph of ecoli_vf
log.info('Uploading VF reference genes')
vf_graph = graph_refs()
vf_response = upload_graph(vf_graph)
log.info('Upload returned response: {}'.format(vf_response))
if not find_object(uri, 'subt:Phylotyper'):
log.info('Uploading subtype definition: {}'.format(subtype))
graph = graph_func()
response = upload_graph(graph)
log.info('Upload returned response: {}'.format(response))
# Database ready to recieve phylotyper data for this subtype
if __name__=='__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"-s",
help="Phylotyper subtype scheme",
required=True
)
args = parser.parse_args()
load(args.s)
|
|
# This document is part of Acronym
# https://github.com/geowurster/Acronym
# =================================================================================== #
#
# New BSD License
#
# Copyright (c) 2014, Kevin D. Wurster
# 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.
#
# * The names of its contributors may not 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 HOLDER 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.
#
# =================================================================================== #
"""Geoprocessing operations"""
import sys
try:
from osgeo import ogr
from osgeo import osr
except ImportError:
import ogr
ogr.UseExceptions()
osr.UseExceptions()
#/* ======================================================================= */#
#/* Define _buffer() function
#/* ======================================================================= */#
def _buffer(geometry, *args):
distance = args[0]
return geometry.Buffer(distance)
#/* ======================================================================= */#
#/* Define _bbox() function
#/* ======================================================================= */#
def _bbox(geometry, *args, **kwargs):
add_z = kwargs.get('add_z', None)
if add_z:
envelope = geometry.Envelope3D()
else:
envelope = geometry.Envelope()
return envelope
#/* ======================================================================= */#
#/* Define _union() function
#/* ======================================================================= */#
def _union(geometry, *args, **kwargs):
union_geom = args[0]
return geometry.Union(union_geom)
#/* ======================================================================= */#
#/* Define _symmetrical_difference() function
#/* ======================================================================= */#
def _symmetrical_difference(geometry, *args):
return geometry.SymDifference()
#/* ======================================================================= */#
#/* Define _convex_hull() function
#/* ======================================================================= */#
def _convex_hull(geometry, *args):
return geometry.ConvexHull()
#/* ======================================================================= */#
#/* Define _centroids() function
#/* ======================================================================= */#
def _centroid(geometry, *args):
return geometry.Centroid()
#/* ======================================================================= */#
#/* Define _reproject() function
#/* ======================================================================= */#
def _reproject(geometry, *args):
transformer = args[0]
return geometry.Transform(transformer)
#/* ======================================================================= */#
#/* Define _affine() function
#/* ======================================================================= */#
def _affine():
raise NotImplementedError
#/* ======================================================================= */#
#/* Define _scale() function
#/* ======================================================================= */#
def _scale():
raise NotImplementedError
#/* ======================================================================= */#
#/* Define _clip() function
#/* ======================================================================= */#
def _clip(geometry, *args, **kwargs):
clip_geom = args[0]
return geometry.Intersection(clip_geom)
#/* ======================================================================= */#
#/* Define _reverse_clip() function
#/* ======================================================================= */#
def _reverse_clip(geometry, *args, **kwargs):
clip_geom = args[0]
return geometry.Difference(clip_geom)
#/* ======================================================================= */#
#/* Define _simplify() function
#/* ======================================================================= */#
def _simplify(geometry, *args, **kwargs):
tolerance = args[0]
preserve_topology = kwargs.get('preserve_topology', None)
if preserve_topology:
simplified = geometry.SimplifyPreserveTopology(tolerance)
else:
simplified = geometry.Simplify(tolerance)
return simplified
#/* ======================================================================= */#
#/* Define _segmentize() function
#/* ======================================================================= */#
def _segmentize(geometry, *args, **kwargs):
max_length = args[0]
return geometry.SimplifyPreserveTopology(max_length)
#/* ======================================================================= */#
#/* Define _standard_geoprocessor() function
#/* ======================================================================= */#
def _standard_geometry_processor(src_layer, dst_layer, *args, **kwargs):
# Parse arguments
processor = kwargs['processor']
update = kwargs.get('update', False)
# Figure out where to send the new features
if update:
tgt_layer = src_layer
else:
tgt_layer = dst_layer
# Perform buffer
for feature in src_layer:
geometry = feature.GetGeometryRef()
feature.SetGeometry(processor(geometry, *args, **kwargs))
# Update feature in OGR list or append new feature to output list
try:
tgt_layer.SetFeature(feature)
except AttributeError:
tgt_layer.append(feature)
# Cleanup
try:
# If input is a list of features reset will fail even
src_layer.ResetReading()
except AttributeError:
pass
geometry = None
feature = None
return tgt_layer
#/* ======================================================================= */#
#/* Define geometry_checker() function
#/* ======================================================================= */#
def geometry_checker(layer, stream=sys.stdout):
layer.ResetReading()
for feature in layer:
geometry = feature.GetGeometryRef()
result = geometry.IsSimple()
if result is not False:
stream.write(result)
# Cleanup
layer.ResetReading()
geometry = None
feature = None
return layer
#/* ======================================================================= */#
#/* Define buffer() function
#/* ======================================================================= */#
def buffer(src_layer, dst_layer, *args, **kwargs):
return _standard_geometry_processor(src_layer, dst_layer, processor=_buffer, *args, **kwargs)
#/* ======================================================================= */#
#/* Define dissolve() function
#/* ======================================================================= */#
def geometry_dissolve():
raise NotImplementedError
#/* ======================================================================= */#
#/* Define bbox() function
#/* ======================================================================= */#
def bbox(src_layer, dst_layer, *args, **kwargs):
return _standard_geometry_processor(src_layer, dst_layer, processor=_bbox, *args, **kwargs)
#/* ======================================================================= */#
#/* Define union() function
#/* ======================================================================= */#
def union(src_layer, dst_layer, *args, **kwargs):
return _standard_geometry_processor(src_layer, dst_layer, processor=_union, *args, **kwargs)
#/* ======================================================================= */#
#/* Define symmetrical_difference() function
#/* ======================================================================= */#
def symmetrical_difference(src_layer, dst_layer, *args, **kwargs):
return _standard_geometry_processor(src_layer, dst_layer, processor=_symmetrical_difference, *args, **kwargs)
#/* ======================================================================= */#
#/* Define explode() function
#/* ======================================================================= */#
def explode(update=False, *args):
"""Turn multi-geometries into single features
:param update: specify whether or not the src_layer should be modified in place
:type update: bool
:param args: src_layer [dst_layer]
:type args: list|tuple
:return: handle to modified layer
:rtype: ogr.Layer"""
# Parse arguments
if len(args) is 1:
src_layer = args[0]
dst_layer = None
else:
src_layer, dst_layer = args
if update:
tgt_layer = src_layer
else:
tgt_layer = dst_layer
# Validate arguments
if dst_layer is None and update is False:
raise ValueError("ERROR: Update=%s and dst_layer=%s" % (update, dst_layer))
# Explode all geometries
for feature in src_layer:
geometry = feature.GetGeometryRef()
for i in range(geometry.GetGeometryCount()):
sub_geom = geometry.GetGeometryRef(i)
new_feature = feature.Clone()
new_feature.SetGeometry(sub_geom)
tgt_layer.SetFeature(feature)
# Cleanup
src_layer.ResetReading()
tgt_layer.ResetReading() # This resets dst_layer
new_geom = None
new_feature = None
geometry = None
feature = None
return tgt_layer
#/* ======================================================================= */#
#/* Define fishnet() function
#/* ======================================================================= */#
def fishnet():
raise NotImplementedError
#/* ======================================================================= */#
#/* Define convex_hull() function
#/* ======================================================================= */#
def convex_hull(src_layer, dst_layer, *args, **kwargs):
return _standard_geometry_processor(src_layer, dst_layer, processor=_convex_hull, *args, **kwargs)
#/* ======================================================================= */#
#/* Define centroid() function
#/* ======================================================================= */#
def centroid(src_layer, dst_layer, *args, **kwargs):
return _standard_geometry_processor(src_layer, dst_layer, processor=_centroid, *args, **kwargs)
#/* ======================================================================= */#
#/* Define reproject() function
#/* ======================================================================= */#
def reproject(src_layer, dst_layer, *args, **kwargs):
# No transform was explicitly defined - pull from src and dst layers
if len(args) is 0:
s_srs = src_layer.GetSpatialRef()
t_srs = src_layer.GetSpatialRef()
transform = osr.CoordinateTransformation(s_srs, t_srs)
# User specified something - create a transformation if it isn't already one
elif len(args) is 1:
transform = args[0]
if not isinstance(transform, osr.CoordinateTransformation):
s_srs = src_layer.GetSpatialRef()
t_srs = osr.SpatialReference()
t_srs.SetFromUserInput(transform)
transform = osr.CoordinateTransformation(s_srs, t_srs)
# User specified two things - build a transformation from a source and destination SRS
elif len(args) is 2:
s_srs, t_srs = args
if not isinstance(s_srs, osr.SpatialReference):
s_user_input = s_srs
s_srs = osr.SpatialReference()
s_srs.SetFromUserInput(s_user_input)
if not isinstance(t_srs, osr.SpatialReference):
t_user_input = t_srs
t_srs = osr.SpatialReference()
t_srs.SetFromUserInput(t_user_input)
transform = osr.CoordinateTransformation(s_srs, t_srs)
# Force an error
else:
transform = None
# Prepare arguments for the call
args = [transform]
return _standard_geometry_processor(src_layer, dst_layer, processor=_reproject, *args, **kwargs)
#/* ======================================================================= */#
#/* Define affine() function
#/* ======================================================================= */#
def affine():
raise NotImplementedError
#/* ======================================================================= */#
#/* Define scale() function
#/* ======================================================================= */#
def scale():
raise NotImplementedError
#/* ======================================================================= */#
#/* Define clip() function
#/* ======================================================================= */#
def clip(src_layer, dst_layer, *args, **kwargs):
return _standard_geometry_processor(src_layer, dst_layer, processor=_clip, *args, **kwargs)
#/* ======================================================================= */#
#/* Define reverse_clip() function
#/* ======================================================================= */#
def reverse_clip(src_layer, dst_layer, *args, **kwargs):
return _standard_geometry_processor(src_layer, dst_layer, processor=_reverse_clip, *args, **kwargs)
#/* ======================================================================= */#
#/* Define simplify() function
#/* ======================================================================= */#
def simplify(src_layer, dst_layer, *args, **kwargs):
return _standard_geometry_processor(src_layer, dst_layer, processor=_simplify, *args, **kwargs)
#/* ======================================================================= */#
#/* Define segmentize() function
#/* ======================================================================= */#
def segmentize(src_layer, dst_layer, *args, **kwargs):
return _standard_geometry_processor(src_layer, dst_layer, processor=_segmentize, *args, **kwargs)
|
|
"""
Refactored helper methods for working with the database. This is a work in
progress. You should probably be looking at ui.voyager until this work is
more fully developed.
"""
import re
import pymarc
import logging
from PyZ3950 import zoom
from django.db import connections
from django.conf import settings
# oracle specific configuration since Voyager's Oracle requires ASCII
if settings.DATABASES['voyager']['ENGINE'] == 'django.db.backends.oracle':
import django.utils.encoding
import django.db.backends.oracle.base
# connections are in ascii
django.db.backends.oracle.base._setup_environment([
('NLS_LANG', '.US7ASCII'),
])
# string bind parameters must not be promoted to Unicode in order to use
# Voyager's antiquated Oracle indexes properly
# https://github.com/gwu-libraries/launchpad/issues/611
django.db.backends.oracle.base.convert_unicode = \
django.utils.encoding.force_bytes
def get_item(bibid):
"""
Get JSON-LD for a given bibid.
"""
item = {
'@type': 'Book',
}
marc = get_marc(bibid)
item['wrlc'] = bibid
# get item name (title)
item['name'] = marc['245']['a'].strip(' /')
# get oclc number
for f in marc.get_fields('035'):
if f['a'] and f['a'].startswith('(OCoLC)'):
if 'oclc' not in item:
item['oclc'] = []
oclc = f['a'].replace('(OCoLC)', '').replace('OCM', '')
item['oclc'].append(oclc)
# get lccn
f = marc['010']
if f:
item['lccn'] = marc['010']['a'].strip()
# get isbns
for f in marc.get_fields('020'):
if 'isbn' not in item:
item['isbn'] = []
isbn = f['a']
# extract just the isbn, e.g. "0801883814 (hardcover : alk. paper)"
isbn = isbn.split()[0]
item['isbn'].append(isbn)
# get issns
for f in marc.get_fields('022'):
if 'issn' not in item:
item['issn'] = []
item['issn'].append(f['a'])
return item
def get_marc(bibid):
"""
Get pymarc.Record for a given bibid.
"""
query = "SELECT wrlcdb.getBibBlob(%s) AS marcblob from bib_master"
cursor = connections['voyager'].cursor()
cursor.execute(query, [bibid])
row = cursor.fetchone()
raw_marc = str(row[0])
record = pymarc.record.Record(data=raw_marc)
return record
def get_availability(bibid):
"""
Get availability information as JSON-LD for a given bibid.
"""
if not isinstance(bibid, basestring):
raise Exception("supplied a non-string: %s" % bibid)
url = 'http://%s/item/%s' % (_get_hostname(), bibid)
results = {
'@context': {
'@vocab': 'http://schema.org/',
},
'@id': url,
'offers': [],
'wrlc': bibid,
}
# if the bibid is numeric we can look it up locally in Voyager
if re.match('^\d+$', bibid):
results['offers'] = _get_offers(bibid)
# George Mason and Georgetown have special ids in Summon and we need
# to talk to their catalogs to determine availability
else:
if bibid.startswith('m'):
results['offers'] = _get_offers_z3950(bibid, 'George Mason')
elif bibid.startswith('b'):
results['offers'] = _get_offers_z3950(bibid, 'Georgetown')
else:
raise Exception("unknown bibid format %s" % bibid)
# update wrlc id if there is a record in voyager for it
wrlc_id = get_bibid_from_summonid(bibid)
if wrlc_id:
results['wrlc'] = wrlc_id
results['summon'] = bibid
return results
def get_bibid_from_summonid(id):
"""
For some reason Georgetown and GeorgeMason loaded Summon with their
own IDs so we need to look them up differently.
"""
if re.match('^\d+$', id):
return id
if id.startswith('b'):
return get_bibid_from_gtid(id)
elif id.startswith('m'):
return get_bibid_from_gmid(id)
else:
return None
def get_bibid_from_gtid(id):
query = \
"""
SELECT bib_index.bib_id
FROM bib_index, bib_master
WHERE bib_index.normal_heading = %s
AND bib_index.index_code = '907A'
AND bib_index.bib_id = bib_master.bib_id
AND bib_master.library_id IN ('14', '15')
"""
cursor = connections['voyager'].cursor()
cursor.execute(query, [id.upper()])
results = cursor.fetchone()
return str(results[0]) if results else None
def get_bibid_from_gmid(id):
id = id.lstrip("m")
query = \
"""
SELECT bib_index.bib_id
FROM bib_index, bib_master
WHERE bib_index.index_code = '035A'
AND bib_index.bib_id=bib_master.bib_id
AND bib_index.normal_heading=bib_index.display_heading
AND bib_master.library_id = '6'
AND bib_index.normal_heading = %s
"""
cursor = connections['voyager'].cursor()
cursor.execute(query, [id.upper()])
results = cursor.fetchone()
return str(results[0]) if results else None
def get_related_bibids(item):
bibid = item['wrlc']
bibids = set([bibid])
bibids |= set(get_related_bibids_by_oclc(item))
bibids |= set(get_related_bibids_by_lccn(item))
bibids |= set(get_related_bibids_by_isbn(item))
return list(bibids)
def get_related_bibids_by_lccn(item):
if 'lccn' not in item:
return []
q = '''
SELECT DISTINCT bib_index.bib_id, bib_text.title
FROM bib_index, library, bib_master, bib_text
WHERE bib_index.bib_id=bib_master.bib_id
AND bib_master.library_id=library.library_id
AND bib_master.suppress_in_opac='N'
AND bib_index.index_code IN ('010A')
AND bib_index.normal_heading != 'OCOLC'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
AND bib_text.bib_id = bib_master.bib_id
AND bib_index.normal_heading IN (
SELECT bib_index.normal_heading
FROM bib_index
WHERE bib_index.index_code IN ('010A')
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
AND bib_id IN (
SELECT DISTINCT bib_index.bib_id
FROM bib_index
WHERE bib_index.index_code IN ('010A')
AND bib_index.normal_heading = %s
AND bib_index.normal_heading != 'OCOLC'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
)
)
ORDER BY bib_index.bib_id
'''
rows = _fetch_all(q, [item['lccn']])
rows = _filter_by_title(rows, item['name'])
return rows
def get_related_bibids_by_oclc(item):
if 'oclc' not in item or len(item['oclc']) == 0:
return []
binds = ','.join(['%s'] * len(item['oclc']))
q = u'''
SELECT DISTINCT bib_index.bib_id, bib_text.title
FROM bib_index, bib_master, bib_text
WHERE bib_index.bib_id=bib_master.bib_id
AND bib_master.suppress_in_opac='N'
AND bib_index.index_code IN ('035A')
AND bib_index.normal_heading != 'OCOLC'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
AND bib_text.bib_id = bib_master.bib_id
AND bib_index.normal_heading IN (
SELECT bib_index.normal_heading
FROM bib_index
WHERE bib_index.index_code IN ('035A')
AND bib_index.normal_heading != bib_index.display_heading
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
AND bib_id IN (
SELECT DISTINCT bib_index.bib_id
FROM bib_index
WHERE bib_index.index_code IN ('035A')
AND bib_index.normal_heading IN (%s)
AND bib_index.normal_heading != 'OCOLC'
AND bib_index.normal_heading != bib_index.display_heading
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
)
)
ORDER BY bib_index.bib_id
''' % binds
rows = _fetch_all(q, item['oclc'])
rows = _filter_by_title(rows, item['name'])
return rows
def get_related_bibids_by_isbn(item):
if 'isbn' not in item or len(item['isbn']) == 0:
return []
binds = ','.join(['%s'] * len(item['isbn']))
q = '''
SELECT DISTINCT bib_index.bib_id, bib_text.title
FROM bib_index, bib_master, bib_text
WHERE bib_index.bib_id=bib_master.bib_id
AND bib_master.suppress_in_opac='N'
AND bib_index.index_code IN ('020N','020A','ISB3','020Z')
AND bib_index.normal_heading != 'OCOLC'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
AND bib_text.bib_id = bib_master.bib_id
AND bib_index.normal_heading IN (
SELECT bib_index.normal_heading
FROM bib_index
WHERE bib_index.index_code IN ('020N','020A','ISB3','020Z')
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
AND bib_id IN (
SELECT DISTINCT bib_index.bib_id
FROM bib_index
WHERE bib_index.index_code IN ('020N','020A','ISB3','020Z')
AND bib_index.normal_heading IN (%s)
AND bib_index.normal_heading != 'OCOLC'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
)
)
ORDER BY bib_index.bib_id
''' % binds
rows = _fetch_all(q, item['isbn'])
rows = _filter_by_title(rows, item['name'])
return rows
def get_related_bibids_by_issn(item):
if 'issn' not in item or len(item['issn']) == 0:
return []
binds = ','.join(['%s'] * len(item['issn']))
q = '''
SELECT DISTINCT bib_index.bib_id, bib_text.title
FROM bib_index, bib_master, bib_text
WHERE bib_index.bib_id=bib_master.bib_id
AND bib_master.suppress_in_opac='N'
AND bib_index.index_code IN ('022A','022Z','022L')
AND bib_index.normal_heading != 'OCOLC'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
AND bib_text.bib_id = bib_master.bib_id
AND bib_index.normal_heading IN (
SELECT bib_index.normal_heading
FROM bib_index
WHERE bib_index.index_code IN ('022A','022Z','022L')
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
AND bib_id IN (
SELECT DISTINCT bib_index.bib_id
FROM bib_index
WHERE bib_index.index_code IN ('022A','022Z','022L')
AND bib_index.normal_heading IN (%s)
AND bib_index.normal_heading != 'OCOLC'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SET%%%%'
AND UPPER(bib_index.display_heading) NOT LIKE '%%%%SER%%%%'
)
)
ORDER BY bib_index.bib_id
''' % binds
# voyager wants "1059-1028" to look like "1059 1028"
issns = [i.replace('-', ' ') for i in item['issn']]
rows = _fetch_all(q, issns)
rows = _filter_by_title(rows, item['name'])
return rows
def _get_offers(bibid):
offers = []
query = \
"""
SELECT DISTINCT
display_call_no,
item_status_desc,
item_status.item_status,
perm_location.location_display_name as PermLocation,
temp_location.location_display_name as TempLocation,
mfhd_item.item_enum,
mfhd_item.chron,
item.item_id,
item_status_date,
to_char(CIRC_TRANSACTIONS.CHARGE_DUE_DATE, 'yyyy-mm-dd') AS DUE,
library.library_display_name,
holding_location.location_display_name as HoldingLocation
FROM bib_master
JOIN library ON library.library_id = bib_master.library_id
JOIN bib_mfhd ON bib_master.bib_id = bib_mfhd.bib_id
JOIN mfhd_master ON mfhd_master.mfhd_id = bib_mfhd.mfhd_id
JOIN library ON bib_master.library_id = library.library_id
JOIN location holding_location
ON mfhd_master.location_id = holding_location.location_id
LEFT OUTER JOIN mfhd_item
ON mfhd_item.mfhd_id = mfhd_master.mfhd_id
LEFT OUTER JOIN item
ON item.item_id = mfhd_item.item_id
LEFT OUTER JOIN item_status
ON item_status.item_id = item.item_id
LEFT OUTER JOIN item_status_type
ON item_status.item_status = item_status_type.item_status_type
LEFT OUTER JOIN location perm_location
ON perm_location.location_id = item.perm_location
LEFT OUTER JOIN location temp_location
ON temp_location.location_id = item.temp_location
LEFT OUTER JOIN circ_transactions
ON item.item_id = circ_transactions.item_id
WHERE bib_master.bib_id = %s
AND mfhd_master.suppress_in_opac != 'Y'
ORDER BY PermLocation, TempLocation, item_status_date desc
"""
cursor = connections['voyager'].cursor()
cursor.execute(query, [bibid])
# this will get set to true for libraries that require a z39.50 lookup
need_z3950_lookup = False
for row in cursor.fetchall():
seller = settings.LIB_LOOKUP.get(row[10], '?')
desc = row[1] or 'Available'
if row[9] == '2382-12-31' or row[9] == '2022-02-20' or \
(row[9] is None and
row[11] == 'WRLC Shared Collections Facility'):
desc = 'Off Site'
if desc == 'Not Charged':
desc = 'Available'
o = {
'@type': 'Offer',
'seller': seller,
'sku': row[0],
'availability': _normalize_status(row[2]),
'description': desc,
}
# use temp location if there is one, otherwise use perm location
# or the holding location in cases where there is no item record
if row[4]:
o['availabilityAtOrFrom'] = _normalize_location(row[4])
elif row[3]:
o['availabilityAtOrFrom'] = _normalize_location(row[3])
else:
o['availabilityAtOrFrom'] = _normalize_location(row[11])
# serial number can be null, apparently
if row[7]:
o['serialNumber'] = str(row[7])
# add due date if we have one
if row[9]:
# due date of 2382-12-31 means it's in offsite storage
if row[9] == '2382-12-31' or row[9] == '2020-02-20':
o['availability'] = 'http://schema.org/InStock'
else:
o['availabilityStarts'] = row[9]
# z39.50 lookups
if seller == 'George Mason' or seller == 'Georgetown':
need_z3950_lookup = True
offers.append(o)
if need_z3950_lookup:
library = offers[0]['seller']
return _get_offers_z3950(bibid, library)
return offers
def _get_offers_z3950(id, library):
offers = []
# determine which server to talk to
if library == 'Georgetown':
conf = settings.Z3950_SERVERS['GT']
elif library == 'George Mason':
id = id.strip('m')
conf = settings.Z3950_SERVERS['GM']
else:
raise Exception("unrecognized library %s" % library)
# search for the id, and get the first record
z = zoom.Connection(conf['IP'], conf['PORT'])
z.databaseName = conf['DB']
z.preferredRecordSyntax = conf['SYNTAX']
q = zoom.Query('PQF', '@attr 1=12 %s' % id.encode('utf-8'))
results = z.search(q)
if len(results) == 0:
return []
rec = results[0]
# normalize holdings information as schema.org offers
if hasattr(rec, 'data') and not hasattr(rec.data, 'holdingsData'):
return []
for holdings_data in rec.data.holdingsData:
h = holdings_data[1]
o = {'@type': 'Offer', 'seller': library}
if hasattr(h, 'callNumber'):
o['sku'] = h.callNumber.rstrip('\x00').strip()
if hasattr(h, 'localLocation'):
o['availabilityAtOrFrom'] = h.localLocation.rstrip('\x00')
if hasattr(h, 'publicNote') and library == 'Georgetown':
note = h.publicNote.rstrip('\x00')
if note == 'AVAILABLE':
o['availability'] = 'http://schema.org/InStock'
o['description'] = 'Available'
elif note in ('SPC USE ONLY', 'LIB USE ONLY'):
o['availability'] = 'http://schema.org/InStoreOnly'
o['description'] = 'Available'
else:
# set availabilityStarts from "DUE 09-15-14"
m = re.match('DUE (\d\d)-(\d\d)-(\d\d)', note)
if m:
m, d, y = [int(i) for i in m.groups()]
o['availabilityStarts'] = "20%02i-%02i-%02i" % (y, m, d)
o['availability'] = 'http://schema.org/OutOfStock'
o['description'] = 'Checked Out'
elif hasattr(h, 'circulationData'):
cd = h.circulationData[0]
if cd.availableNow is True:
o['availability'] = 'http://schema.org/InStock'
o['description'] = 'Available'
else:
if hasattr(cd, 'availabilityDate') and cd.availablityDate:
m = re.match("^(\d{4}-\d{2}-\d{2}).+", cd.availablityDate)
if m:
o['availabilityStarts'] = m.group(1)
o['availability'] = 'http://schema.org/OutOfStock'
o['description'] = 'Checked Out'
else:
logging.warn("unknown availability: bibid=%s library=%s h=%s",
id, library, h)
# some locations have a weird period before the name
o['availabilityAtOrFrom'] = o.get('availabilityAtOrFrom',
'').lstrip('.')
offers.append(o)
return offers
def _normalize_status(status_id):
"""
This function will turn one of the standard item status codes
into a GoodRelations URI:
http://www.w3.org/community/schemabibex/wiki/Holdings_via_Offer
Here is a snapshot in time of item_status_ids, their description,
and count:
1 Not Charged 5897029
2 Charged 1832241
3 Renewed 39548
17 Withdrawn 26613
4 Overdue 22966
14 Lost--System Applied 16687
12 Missing 15816
19 Cataloging Review 15584
20 Circulation Review 11225
9 In Transit Discharged 7493
13 Lost--Library Applied 7262
11 Discharged 2001
18 At Bindery 1603
15 Claims Returned 637
16 Damaged 525
22 In Process 276
6 Hold Request 39
10 In Transit On Hold 24
8 In Transit 23
5 Recall Request 17
7 On Hold 6
24 Short Loan Request 2
"""
# TODO: more granularity needed?
if status_id == 1:
return 'http://schema.org/InStock'
elif status_id in (19, 20):
return 'http://schema.org/PreOrder'
elif status_id:
return 'http://schema.org/OutOfStock'
else:
return 'http://schema.org/InStock'
def _fetch_one(query, params=[]):
cursor = connections['voyager'].cursor()
cursor.execute(query, params)
return cursor.fetchone()
def _fetch_all(query, params=None):
cursor = connections['voyager'].cursor()
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
return cursor.fetchall()
def _normalize_location(location):
if not location:
return None
parts = location.split(': ', 1)
norm_location = parts.pop().title()
if norm_location == "Wrlc Shared Collections Facility":
norm_location = norm_location.replace('Wrlc', 'WRLC')
if parts:
tmp = parts.pop()
if tmp == "GW Law" or tmp == "GW Medical":
norm_location = "%s: %s" % (tmp, norm_location)
return norm_location
def _get_hostname():
if len(settings.ALLOWED_HOSTS) > 0:
return settings.ALLOWED_HOSTS[0]
return 'localhost'
def _filter_by_title(rows, expected):
bibids = []
for bibid, title in rows:
min_len = min(len(expected), len(title))
if title.lower()[0:min_len] == expected.lower()[0:min_len]:
bibids.append(str(bibid))
return bibids
|
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Functional tests for slice op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
class SliceTest(tf.test.TestCase):
def _testEmpty(self, use_gpu):
inp = np.random.rand(4, 4).astype("f")
for k in xrange(4):
with self.test_session(use_gpu=use_gpu):
a = tf.constant(inp, shape=[4, 4], dtype=tf.float32)
slice_t = a[2, k:k]
slice_val = slice_t.eval()
self.assertAllEqual(slice_val, inp[2, k:k])
def testEmptyAll(self):
self._testEmpty(use_gpu=False)
self._testEmpty(use_gpu=True)
def _testInt32(self, use_gpu):
inp = np.random.rand(4, 4).astype("i")
for k in xrange(4):
with self.test_session(use_gpu=use_gpu):
a = tf.constant(inp, shape=[4, 4], dtype=tf.int32)
slice_t = a[2, k:k]
slice_val = slice_t.eval()
self.assertAllEqual(slice_val, inp[2, k:k])
def testInt32(self):
self._testEmpty(use_gpu=False)
self._testEmpty(use_gpu=True)
def _testSelectAll(self, use_gpu):
with self.test_session(use_gpu=use_gpu):
inp = np.random.rand(4, 4, 4, 4).astype("f")
a = tf.constant(inp, shape=[4, 4, 4, 4],
dtype=tf.float32)
slice_explicit_t = tf.slice(a, [0, 0, 0, 0], [-1, -1, -1, -1])
slice_implicit_t = a[:, :, :, :]
self.assertAllEqual(inp, slice_explicit_t.eval())
self.assertAllEqual(inp, slice_implicit_t.eval())
self.assertEqual(inp.shape, slice_explicit_t.get_shape())
self.assertEqual(inp.shape, slice_implicit_t.get_shape())
def testSelectAll(self):
for _ in range(10):
self._testSelectAll(use_gpu=False)
self._testSelectAll(use_gpu=True)
def _testSingleDimension(self, use_gpu):
with self.test_session(use_gpu=use_gpu):
inp = np.random.rand(10).astype("f")
a = tf.constant(inp, shape=[10], dtype=tf.float32)
hi = np.random.randint(0, 9)
scalar_t = a[hi]
scalar_val = scalar_t.eval()
self.assertAllEqual(scalar_val, inp[hi])
if hi > 0:
lo = np.random.randint(0, hi)
else:
lo = 0
slice_t = a[lo:hi]
slice_val = slice_t.eval()
self.assertAllEqual(slice_val, inp[lo:hi])
def testSingleDimension(self):
for _ in range(10):
self._testSingleDimension(use_gpu=False)
self._testSingleDimension(use_gpu=True)
def _testSliceMatrixDim0(self, x, begin, size, use_gpu):
with self.test_session(use_gpu=use_gpu):
tf_ans = tf.slice(x, [begin, 0], [size, x.shape[1]]).eval()
np_ans = x[begin:begin+size, :]
self.assertAllEqual(tf_ans, np_ans)
def testSliceMatrixDim0(self):
for use_gpu in [False, True]:
x = np.random.rand(8, 4).astype("f")
self._testSliceMatrixDim0(x, 1, 2, use_gpu)
self._testSliceMatrixDim0(x, 3, 3, use_gpu)
y = np.random.rand(8, 7).astype("f") # 7 * sizeof(float) is not aligned
self._testSliceMatrixDim0(y, 1, 2, use_gpu)
self._testSliceMatrixDim0(y, 3, 3, use_gpu)
def _testIndexAndSlice(self, use_gpu):
with self.test_session(use_gpu=use_gpu):
inp = np.random.rand(4, 4).astype("f")
a = tf.constant(inp, shape=[4, 4], dtype=tf.float32)
x, y = np.random.randint(0, 3, size=2).tolist()
slice_t = a[x, 0:y]
slice_val = slice_t.eval()
self.assertAllEqual(slice_val, inp[x, 0:y])
def testSingleElementAll(self):
for _ in range(10):
self._testIndexAndSlice(use_gpu=False)
self._testIndexAndSlice(use_gpu=True)
def _testSimple(self, use_gpu):
with self.test_session(use_gpu=use_gpu) as sess:
inp = np.random.rand(4, 4).astype("f")
a = tf.constant([float(x) for x in inp.ravel(order="C")],
shape=[4, 4], dtype=tf.float32)
slice_t = tf.slice(a, [0, 0], [2, 2])
slice2_t = a[:2, :2]
slice_val, slice2_val = sess.run([slice_t, slice2_t])
self.assertAllEqual(slice_val, inp[:2, :2])
self.assertAllEqual(slice2_val, inp[:2, :2])
self.assertEqual(slice_val.shape, slice_t.get_shape())
self.assertEqual(slice2_val.shape, slice2_t.get_shape())
def testSimpleAll(self):
self._testSimple(use_gpu=False)
self._testSimple(use_gpu=True)
def _testComplex(self, use_gpu):
with self.test_session(use_gpu=use_gpu):
inp = np.random.rand(4, 10, 10, 4).astype("f")
a = tf.constant(inp, dtype=tf.float32)
x = np.random.randint(0, 9)
z = np.random.randint(0, 9)
if z > 0:
y = np.random.randint(0, z)
else:
y = 0
slice_t = a[:, x, y:z, :]
self.assertAllEqual(slice_t.eval(), inp[:, x, y:z, :])
def testComplex(self):
for _ in range(10):
self._testComplex(use_gpu=False)
self._testComplex(use_gpu=True)
def _RunAndVerifyResult(self, use_gpu):
# Random dims of rank 6
input_shape = np.random.randint(0, 20, size=6)
inp = np.random.rand(*input_shape).astype("f")
with self.test_session(use_gpu=use_gpu) as sess:
a = tf.constant([float(x) for x in inp.ravel(order="C")],
shape=input_shape, dtype=tf.float32)
indices = [0 if x == 0 else np.random.randint(x) for x in input_shape]
sizes = [np.random.randint(0, input_shape[i] - indices[i] + 1)
for i in range(6)]
slice_t = tf.slice(a, indices, sizes)
slice2_t = a[indices[0]:indices[0]+sizes[0],
indices[1]:indices[1]+sizes[1],
indices[2]:indices[2]+sizes[2],
indices[3]:indices[3]+sizes[3],
indices[4]:indices[4]+sizes[4],
indices[5]:indices[5]+sizes[5]]
slice_val, slice2_val = sess.run([slice_t, slice2_t])
expected_val = inp[indices[0]:indices[0]+sizes[0],
indices[1]:indices[1]+sizes[1],
indices[2]:indices[2]+sizes[2],
indices[3]:indices[3]+sizes[3],
indices[4]:indices[4]+sizes[4],
indices[5]:indices[5]+sizes[5]]
self.assertAllEqual(slice_val, expected_val)
self.assertAllEqual(slice2_val, expected_val)
self.assertEqual(expected_val.shape, slice_t.get_shape())
self.assertEqual(expected_val.shape, slice2_t.get_shape())
def testRandom(self):
for _ in range(10):
self._RunAndVerifyResult(use_gpu=False)
self._RunAndVerifyResult(use_gpu=True)
def _testGradientSlice(self, input_shape, slice_begin, slice_size, use_gpu):
with self.test_session(use_gpu=use_gpu):
num_inputs = np.prod(input_shape)
num_grads = np.prod(slice_size)
inp = np.random.rand(num_inputs).astype("f").reshape(input_shape)
a = tf.constant([float(x) for x in inp.ravel(order="C")],
shape=input_shape, dtype=tf.float32)
slice_t = tf.slice(a, slice_begin, slice_size)
grads = np.random.rand(num_grads).astype("f").reshape(slice_size)
grad_tensor = tf.constant(grads)
grad = tf.gradients(slice_t, [a], grad_tensor)[0]
result = grad.eval()
# Create a zero tensor of the input shape ane place
# the grads into the right location to compare against TensorFlow.
np_ans = np.zeros(input_shape)
slices = []
for i in xrange(len(input_shape)):
slices.append(slice(slice_begin[i], slice_begin[i] + slice_size[i]))
np_ans[slices] = grads
self.assertAllClose(np_ans, result)
def _testGradientVariableSize(self, use_gpu):
with self.test_session(use_gpu=use_gpu):
inp = tf.constant([1.0, 2.0, 3.0], name="in")
out = tf.slice(inp, [1], [-1])
grad_actual = tf.gradients(out, inp)[0].eval()
self.assertAllClose([0., 1., 1.], grad_actual)
def _testGradientsSimple(self, use_gpu):
# Slice the middle square out of a 4x4 input
self._testGradientSlice([4, 4], [1, 1], [2, 2], use_gpu)
# Slice the upper left square out of a 4x4 input
self._testGradientSlice([4, 4], [0, 0], [2, 2], use_gpu)
# Slice a non-square input starting from (2,1)
self._testGradientSlice([4, 4], [2, 1], [1, 2], use_gpu)
# Slice a 3D tensor
self._testGradientSlice([3, 3, 3], [0, 1, 0], [2, 1, 1], use_gpu)
# Use -1 as a slice dimension.
self._testGradientVariableSize(use_gpu)
def testGradientsAll(self):
self._testGradientsSimple(use_gpu=False)
self._testGradientsSimple(use_gpu=True)
def testNotIterable(self):
# NOTE(mrry): If we register __getitem__ as an overloaded
# operator, Python will valiantly attempt to iterate over the
# Tensor from 0 to infinity. This test ensures that this
# unintended behavior is prevented.
c = tf.constant(5.0)
with self.assertRaisesWithPredicateMatch(
TypeError,
lambda e: "'Tensor' object is not iterable" in str(e)):
for _ in c:
pass
if __name__ == "__main__":
tf.test.main()
|
|
from __future__ import print_function
import sys
import logging
from collections import namedtuple
from .tabulate import tabulate
TableInfo = namedtuple("TableInfo", ['checks', 'relkind', 'hasindex',
'hasrules', 'hastriggers', 'hasoids', 'tablespace', 'reloptions', 'reloftype',
'relpersistence'])
log = logging.getLogger(__name__)
class MockLogging(object):
def debug(self, string):
print ("***** Query ******")
print (string)
print ("******************")
print ()
#log = MockLogging()
use_expanded_output = False
def is_expanded_output():
return use_expanded_output
def parse_special_command(sql):
command, _, arg = sql.partition(' ')
verbose = '+' in command
return (command.strip(), verbose, arg.strip())
def describe_table_details(cur, pattern, verbose):
"""
Returns (rows, headers, status)
"""
# This is a simple \d command. No table name to follow.
if not pattern:
sql = """SELECT n.nspname as "Schema", c.relname as "Name", CASE
c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN
'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN
's' THEN 'special' WHEN 'f' THEN 'foreign table' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner" FROM
pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid =
c.relnamespace WHERE c.relkind IN ('r','v','m','S','f','') AND
n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema' AND
n.nspname !~ '^pg_toast' AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2"""
log.debug(sql)
cur.execute(sql)
if cur.description:
headers = [x[0] for x in cur.description]
return [(cur.fetchall(), headers, cur.statusmessage)]
# This is a \d <tablename> command. A royal pain in the ass.
sql = '''SELECT c.oid, n.nspname, c.relname FROM pg_catalog.pg_class c LEFT
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace '''
schema, relname = sql_name_pattern(pattern)
if relname:
sql += ' WHERE c.relname ~ ' + relname
if schema:
sql += ' AND n.nspname ~ ' + schema
sql += ' AND pg_catalog.pg_table_is_visible(c.oid) '
sql += ' ORDER BY 2,3'
# Execute the sql, get the results and call describe_one_table_details on each table.
log.debug(sql)
cur.execute(sql)
if not (cur.rowcount > 0):
return [(None, None, 'Did not find any relation named %s.' % pattern)]
results = []
for oid, nspname, relname in cur.fetchall():
results.append(describe_one_table_details(cur, nspname, relname, oid, verbose))
return results
def describe_one_table_details(cur, schema_name, relation_name, oid, verbose):
if verbose:
suffix = """pg_catalog.array_to_string(c.reloptions || array(select
'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', ')"""
else:
suffix = "''"
sql = """SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules,
c.relhastriggers, c.relhasoids, %s, c.reltablespace, CASE WHEN c.reloftype
= 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END,
c.relpersistence FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_class
tc ON (c.reltoastrelid = tc.oid) WHERE c.oid = '%s'""" % (suffix, oid)
# Create a namedtuple called tableinfo and match what's in describe.c
log.debug(sql)
cur.execute(sql)
if (cur.rowcount > 0):
tableinfo = TableInfo._make(cur.fetchone())
else:
return (None, None, 'Did not find any relation with OID %s.' % oid)
# If it's a seq, fetch it's value and store it for later.
if tableinfo.relkind == 'S':
# Do stuff here.
sql = '''SELECT * FROM "%s"."%s"''' % (schema_name, relation_name)
log.debug(sql)
cur.execute(sql)
if not (cur.rowcount > 0):
return (None, None, 'Something went wrong.')
seq_values = cur.fetchone()
# Get column info
sql = """
SELECT a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod),
(SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum =
a.attnum AND a.atthasdef), a.attnotnull, a.attnum, (SELECT c.collname
FROM pg_catalog.pg_collation c, pg_catalog.pg_type t WHERE c.oid =
a.attcollation AND t.oid = a.atttypid AND a.attcollation <>
t.typcollation) AS attcollation"""
if tableinfo.relkind == 'i':
sql += """, pg_catalog.pg_get_indexdef(a.attrelid, a.attnum, TRUE)
AS indexdef"""
else:
sql += """, NULL AS indexdef"""
if tableinfo.relkind == 'f':
sql += """, CASE WHEN attfdwoptions IS NULL THEN '' ELSE '(' ||
array_to_string(ARRAY(SELECT quote_ident(option_name) || ' '
|| quote_literal(option_value) FROM
pg_options_to_table(attfdwoptions)), ', ') || ')' END AS
attfdwoptions"""
else:
sql += """, NULL AS attfdwoptions"""
if verbose:
sql += """, a.attstorage"""
sql += """, CASE WHEN a.attstattarget=-1 THEN NULL ELSE
a.attstattarget END AS attstattarget"""
if (tableinfo.relkind == 'r' or tableinfo.relkind == 'v' or
tableinfo.relkind == 'm' or tableinfo.relkind == 'f' or
tableinfo.relkind == 'c'):
sql += """, pg_catalog.col_description(a.attrelid,
a.attnum)"""
sql += """ FROM pg_catalog.pg_attribute a WHERE a.attrelid = '%s' AND
a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum; """ % oid
log.debug(sql)
cur.execute(sql)
res = cur.fetchall()
title = (tableinfo.relkind, schema_name, relation_name)
# Set the column names.
headers = ['Column', 'Type']
show_modifiers = False
if (tableinfo.relkind == 'r' or tableinfo.relkind == 'v' or
tableinfo.relkind == 'm' or tableinfo.relkind == 'f' or
tableinfo.relkind == 'c'):
headers.append('Modifiers')
show_modifiers = True
if (tableinfo.relkind == 'S'):
headers.append("Value")
if (tableinfo.relkind == 'i'):
headers.append("Definition")
if (tableinfo.relkind == 'f'):
headers.append("FDW Options")
if (verbose):
headers.append("Storage")
if (tableinfo.relkind == 'r' or tableinfo.relkind == 'm' or
tableinfo.relkind == 'f'):
headers.append("Stats target")
# Column comments, if the relkind supports this feature. */
if (tableinfo.relkind == 'r' or tableinfo.relkind == 'v' or
tableinfo.relkind == 'm' or
tableinfo.relkind == 'c' or tableinfo.relkind == 'f'):
headers.append("Description")
view_def = ''
# /* Check if table is a view or materialized view */
if ((tableinfo.relkind == 'v' or tableinfo.relkind == 'm') and verbose):
sql = """SELECT pg_catalog.pg_get_viewdef('%s'::pg_catalog.oid, true)""" % oid
log.debug(sql)
cur.execute(sql)
if cur.rowcount > 0:
view_def = cur.fetchone()
# Prepare the cells of the table to print.
cells = []
for i, row in enumerate(res):
cell = []
cell.append(row[0]) # Column
cell.append(row[1]) # Type
if show_modifiers:
modifier = ''
if row[5]:
modifier += ' collate %s' % row[5]
if row[3]:
modifier += ' not null'
if row[2]:
modifier += ' default %s' % row[2]
cell.append(modifier)
# Sequence
if tableinfo.relkind == 'S':
cell.append(seq_values[i])
# Index column
if TableInfo.relkind == 'i':
cell.append(row[6])
# /* FDW options for foreign table column, only for 9.2 or later */
if tableinfo.relkind == 'f':
cell.append(row[7])
if verbose:
storage = row[8]
if storage[0] == 'p':
cell.append('plain')
elif storage[0] == 'm':
cell.append('main')
elif storage[0] == 'x':
cell.append('extended')
elif storage[0] == 'e':
cell.append('external')
else:
cell.append('???')
if (tableinfo.relkind == 'r' or tableinfo.relkind == 'm' or
tableinfo.relkind == 'f'):
cell.append(row[9])
# /* Column comments, if the relkind supports this feature. */
if (tableinfo.relkind == 'r' or tableinfo.relkind == 'v' or
tableinfo.relkind == 'm' or
tableinfo.relkind == 'c' or tableinfo.relkind == 'f'):
cell.append(row[10])
cells.append(cell)
# Make Footers
status = []
if (tableinfo.relkind == 'i'):
# /* Footer information about an index */
sql = """SELECT i.indisunique, i.indisprimary, i.indisclustered,
i.indisvalid, (NOT i.indimmediate) AND EXISTS (SELECT 1 FROM
pg_catalog.pg_constraint WHERE conrelid = i.indrelid AND conindid =
i.indexrelid AND contype IN ('p','u','x') AND condeferrable) AS
condeferrable, (NOT i.indimmediate) AND EXISTS (SELECT 1 FROM
pg_catalog.pg_constraint WHERE conrelid = i.indrelid AND conindid =
i.indexrelid AND contype IN ('p','u','x') AND condeferred) AS
condeferred, a.amname, c2.relname, pg_catalog.pg_get_expr(i.indpred,
i.indrelid, true) FROM pg_catalog.pg_index i, pg_catalog.pg_class c,
pg_catalog.pg_class c2, pg_catalog.pg_am a WHERE i.indexrelid = c.oid
AND c.oid = '%s' AND c.relam = a.oid AND i.indrelid = c2.oid;""" % oid
log.debug(sql)
cur.execute(sql)
(indisunique, indisprimary, indisclustered, indisvalid,
deferrable, deferred, indamname, indtable, indpred) = cur.fetchone()
if indisprimary:
status.append("primary key, ")
elif indisunique:
status.append("unique, ")
status.append("%s, " % indamname)
#/* we assume here that index and table are in same schema */
status.append('for table "%s.%s"' % (schema_name, indtable))
if indpred:
status.append(", predicate (%s)" % indpred)
if indisclustered:
status.append(", clustered")
if indisvalid:
status.append(", invalid")
if deferrable:
status.append(", deferrable")
if deferred:
status.append(", initially deferred")
status.append('\n')
#add_tablespace_footer(&cont, tableinfo.relkind,
#tableinfo.tablespace, true);
elif tableinfo.relkind == 'S':
# /* Footer information about a sequence */
# /* Get the column that owns this sequence */
sql = ("SELECT pg_catalog.quote_ident(nspname) || '.' ||"
"\n pg_catalog.quote_ident(relname) || '.' ||"
"\n pg_catalog.quote_ident(attname)"
"\nFROM pg_catalog.pg_class c"
"\nINNER JOIN pg_catalog.pg_depend d ON c.oid=d.refobjid"
"\nINNER JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace"
"\nINNER JOIN pg_catalog.pg_attribute a ON ("
"\n a.attrelid=c.oid AND"
"\n a.attnum=d.refobjsubid)"
"\nWHERE d.classid='pg_catalog.pg_class'::pg_catalog.regclass"
"\n AND d.refclassid='pg_catalog.pg_class'::pg_catalog.regclass"
"\n AND d.objid=%s \n AND d.deptype='a'" % oid)
log.debug(sql)
cur.execute(sql)
result = cur.fetchone()
status.append("Owned by: %s" % result[0])
#/*
#* If we get no rows back, don't show anything (obviously). We should
#* never get more than one row back, but if we do, just ignore it and
#* don't print anything.
#*/
elif (tableinfo.relkind == 'r' or tableinfo.relkind == 'm' or
tableinfo.relkind == 'f'):
#/* Footer information about a table */
if (tableinfo.hasindex):
sql = "SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, "
sql += "i.indisvalid, "
sql += "pg_catalog.pg_get_indexdef(i.indexrelid, 0, true),\n "
sql += ("pg_catalog.pg_get_constraintdef(con.oid, true), "
"contype, condeferrable, condeferred")
sql += ", c2.reltablespace"
sql += ("\nFROM pg_catalog.pg_class c, pg_catalog.pg_class c2, "
"pg_catalog.pg_index i\n")
sql += " LEFT JOIN pg_catalog.pg_constraint con ON (conrelid = i.indrelid AND conindid = i.indexrelid AND contype IN ('p','u','x'))\n"
sql += ("WHERE c.oid = '%s' AND c.oid = i.indrelid AND i.indexrelid = c2.oid\n"
"ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname;") % oid
log.debug(sql)
result = cur.execute(sql)
if (cur.rowcount > 0):
status.append("Indexes:\n")
for row in cur:
#/* untranslated index name */
status.append(' "%s"' % row[0])
#/* If exclusion constraint, print the constraintdef */
if row[7] == "x":
status.append(row[6])
else:
#/* Label as primary key or unique (but not both) */
if row[1]:
status.append(" PRIMARY KEY,")
elif row[2]:
if row[7] == "u":
status.append(" UNIQUE CONSTRAINT,")
else:
status.append(" UNIQUE,")
# /* Everything after "USING" is echoed verbatim */
indexdef = row[5]
usingpos = indexdef.find(" USING ")
if (usingpos >= 0):
indexdef = indexdef[(usingpos + 7):]
status.append(" %s" % indexdef)
# /* Need these for deferrable PK/UNIQUE indexes */
if row[8]:
status.append(" DEFERRABLE")
if row[9]:
status.append(" INITIALLY DEFERRED")
# /* Add these for all cases */
if row[3]:
status.append(" CLUSTER")
if not row[4]:
status.append(" INVALID")
status.append('\n')
# printTableAddFooter(&cont, buf.data);
# /* Print tablespace of the index on the same line */
# add_tablespace_footer(&cont, 'i',
# atooid(PQgetvalue(result, i, 10)),
# false);
# /* print table (and column) check constraints */
if (tableinfo.checks):
sql = ("SELECT r.conname, "
"pg_catalog.pg_get_constraintdef(r.oid, true)\n"
"FROM pg_catalog.pg_constraint r\n"
"WHERE r.conrelid = '%s' AND r.contype = 'c'\n"
"ORDER BY 1;" % oid)
log.debug(sql)
cur.execute(sql)
if (cur.rowcount > 0):
status.append("Check constraints:\n")
for row in cur:
#/* untranslated contraint name and def */
status.append(" \"%s\" %s" % row)
status.append('\n')
#/* print foreign-key constraints (there are none if no triggers) */
if (tableinfo.hastriggers):
sql = ("SELECT conname,\n"
" pg_catalog.pg_get_constraintdef(r.oid, true) as condef\n"
"FROM pg_catalog.pg_constraint r\n"
"WHERE r.conrelid = '%s' AND r.contype = 'f' ORDER BY 1;" %
oid)
log.debug(sql)
cur.execute(sql)
if (cur.rowcount > 0):
status.append("Foreign-key constraints:\n")
for row in cur:
#/* untranslated constraint name and def */
status.append(" \"%s\" %s\n" % row)
#/* print incoming foreign-key references (none if no triggers) */
if (tableinfo.hastriggers):
sql = ("SELECT conname, conrelid::pg_catalog.regclass,\n"
" pg_catalog.pg_get_constraintdef(c.oid, true) as condef\n"
"FROM pg_catalog.pg_constraint c\n"
"WHERE c.confrelid = '%s' AND c.contype = 'f' ORDER BY 1;" %
oid)
log.debug(sql)
cur.execute(sql)
if (cur.rowcount > 0):
status.append("Referenced by:\n")
for row in cur:
status.append(" TABLE \"%s\" CONSTRAINT \"%s\" %s\n" % row)
# /* print rules */
if (tableinfo.hasrules and tableinfo.relkind != 'm'):
sql = ("SELECT r.rulename, trim(trailing ';' from pg_catalog.pg_get_ruledef(r.oid, true)), "
"ev_enabled\n"
"FROM pg_catalog.pg_rewrite r\n"
"WHERE r.ev_class = '%s' ORDER BY 1;" %
oid)
log.debug(sql)
cur.execute(sql)
if (cur.rowcount > 0):
for category in range(4):
have_heading = False
for row in cur:
if category == 0 and row[2] == 'O':
list_rule = True
elif category == 1 and row[2] == 'D':
list_rule = True
elif category == 2 and row[2] == 'A':
list_rule = True
elif category == 3 and row[2] == 'R':
list_rule = True
if not list_rule:
continue
if not have_heading:
if category == 0:
status.append("Rules:")
if category == 1:
status.append("Disabled rules:")
if category == 2:
status.append("Rules firing always:")
if category == 3:
status.append("Rules firing on replica only:")
have_heading = True
# /* Everything after "CREATE RULE" is echoed verbatim */
ruledef = row[1]
ruledef += 12
status.append(" %s", ruledef)
if (view_def):
#/* Footer information about a view */
status.append("View definition:\n")
status.append("%s \n" % view_def)
#/* print rules */
if tableinfo.hasrules:
sql = ("SELECT r.rulename, trim(trailing ';' from pg_catalog.pg_get_ruledef(r.oid, true))\n"
"FROM pg_catalog.pg_rewrite r\n"
"WHERE r.ev_class = '%s' AND r.rulename != '_RETURN' ORDER BY 1;" % oid)
log.debug(sql)
cur.execute(sql)
if (cur.rowcount > 0):
status.append("Rules:\n")
for row in cur:
#/* Everything after "CREATE RULE" is echoed verbatim */
ruledef = row[1]
ruledef += 12;
status.append(" %s\n", ruledef)
#/*
# * Print triggers next, if any (but only user-defined triggers). This
# * could apply to either a table or a view.
# */
if tableinfo.hastriggers:
sql = ( "SELECT t.tgname, "
"pg_catalog.pg_get_triggerdef(t.oid, true), "
"t.tgenabled\n"
"FROM pg_catalog.pg_trigger t\n"
"WHERE t.tgrelid = '%s' AND " % oid);
sql += "NOT t.tgisinternal"
sql += "\nORDER BY 1;"
log.debug(sql)
cur.execute(sql)
if cur.rowcount > 0:
#/*
#* split the output into 4 different categories. Enabled triggers,
#* disabled triggers and the two special ALWAYS and REPLICA
#* configurations.
#*/
for category in range(4):
have_heading = False;
list_trigger = False;
for row in cur:
#/*
# * Check if this trigger falls into the current category
# */
tgenabled = row[2]
if category ==0:
if (tgenabled == 'O' or tgenabled == True):
list_trigger = True
elif category ==1:
if (tgenabled == 'D' or tgenabled == False):
list_trigger = True
elif category ==2:
if (tgenabled == 'A'):
list_trigger = True
elif category ==3:
if (tgenabled == 'R'):
list_trigger = True
if list_trigger == False:
continue;
# /* Print the category heading once */
if not have_heading:
if category == 0:
status.append("Triggers:")
elif category == 1:
status.append("Disabled triggers:")
elif category == 2:
status.append("Triggers firing always:")
elif category == 3:
status.append("Triggers firing on replica only:")
status.append('\n')
have_heading = True
#/* Everything after "TRIGGER" is echoed verbatim */
tgdef = row[1]
triggerpos = indexdef.find(" TRIGGER ")
if triggerpos >= 0:
tgdef = triggerpos + 9;
status.append(" %s\n" % tgdef);
#/*
#* Finish printing the footer information about a table.
#*/
if (tableinfo.relkind == 'r' or tableinfo.relkind == 'm' or
tableinfo.relkind == 'f'):
# /* print foreign server name */
if tableinfo.relkind == 'f':
#/* Footer information about foreign table */
sql = ("SELECT s.srvname,\n"
" array_to_string(ARRAY(SELECT "
" quote_ident(option_name) || ' ' || "
" quote_literal(option_value) FROM "
" pg_options_to_table(ftoptions)), ', ') "
"FROM pg_catalog.pg_foreign_table f,\n"
" pg_catalog.pg_foreign_server s\n"
"WHERE f.ftrelid = %s AND s.oid = f.ftserver;" % oid)
log.debug(sql)
cur.execute(sql)
row = cur.fetchone()
# /* Print server name */
status.append("Server: %s\n" % row[0])
# /* Print per-table FDW options, if any */
if (row[1]):
status.append("FDW Options: (%s)\n" % ftoptions)
#/* print inherited tables */
sql = ("SELECT c.oid::pg_catalog.regclass FROM pg_catalog.pg_class c, "
"pg_catalog.pg_inherits i WHERE c.oid=i.inhparent AND "
"i.inhrelid = '%s' ORDER BY inhseqno;" % oid)
log.debug(sql)
cur.execute(sql)
spacer = ''
if cur.rowcount > 0:
status.append("Inherits")
for row in cur:
status.append("%s: %s,\n" % (spacer, row))
spacer = ' ' * len('Inherits')
#/* print child tables */
sql = ("SELECT c.oid::pg_catalog.regclass FROM pg_catalog.pg_class c,"
" pg_catalog.pg_inherits i WHERE c.oid=i.inhrelid AND"
" i.inhparent = '%s' ORDER BY"
" c.oid::pg_catalog.regclass::pg_catalog.text;" % oid)
log.debug(sql)
cur.execute(sql)
if not verbose:
#/* print the number of child tables, if any */
if (cur.rowcount > 0):
status.append("Number of child tables: %d (Use \d+ to list"
"them.)\n" % cur.rowcount)
else:
spacer = ''
if (cur.rowcount >0):
status.append('Child tables')
#/* display the list of child tables */
for row in cur:
status.append("%s: %s,\n" % (spacer, row))
spacer = ' ' * len('Child tables')
#/* Table type */
if (tableinfo.reloftype):
status.append("Typed table of type: %s\n" % tableinfo.reloftype)
#/* OIDs, if verbose and not a materialized view */
if (verbose and tableinfo.relkind != 'm'):
status.append("Has OIDs: %s\n" %
("yes" if tableinfo.hasoids else "no"))
#/* Tablespace info */
#add_tablespace_footer(&cont, tableinfo.relkind, tableinfo.tablespace,
#true);
# /* reloptions, if verbose */
if (verbose and tableinfo.reloptions):
status.append("Options: %s\n" % tableinfo.reloptions)
return (cells, headers, "".join(status))
def sql_name_pattern(pattern):
"""
Takes a wildcard-pattern and converts to an appropriate SQL pattern to be
used in a WHERE clause.
Returns: schema_pattern, table_pattern
"""
def replacements(pattern):
result = pattern.replace('*', '.*')
result = result.replace('?', '.')
result = result.replace('$', '\\$')
return result
schema, _, relname = pattern.rpartition('.')
if schema:
schema = "'^(" + replacements(schema) + ")$'"
if relname:
relname = "'^(" + replacements(relname) + ")$'"
return schema, relname
def show_help(cur, arg, verbose): # All the parameters are ignored.
headers = ['Command', 'Description']
result = []
for command, value in sorted(CASE_SENSITIVE_COMMANDS.iteritems()):
if value[1]:
result.append(value[1])
return [(result, headers, None)]
def change_db(cur, arg, verbose):
raise NotImplementedError
def expanded_output(cur, arg, verbose):
global use_expanded_output
use_expanded_output = not use_expanded_output
message = u"Expanded display is "
message += u"on" if use_expanded_output else u"off"
return [(None, None, message + u".")]
CASE_SENSITIVE_COMMANDS = {
'\?': (show_help, ['\?', 'Help on pgcli commands.']),
'\c': (change_db, ['\c database_name', 'Connect to a new database.']),
'\l': ('''SELECT datname FROM pg_database;''', ['\l', 'list databases.']),
'\d': (describe_table_details, ['\d [pattern]', 'list or describe tables, views and sequences.']),
'\\x': (expanded_output, ['\\x', 'Toggle expanded output.']),
'\dt': ('''SELECT n.nspname as "Schema", c.relname as "Name", CASE
c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN
'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence'
WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' END as
"Type", pg_catalog.pg_get_userbyid(c.relowner) as "Owner" FROM
pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid
= c.relnamespace WHERE c.relkind IN ('r','') AND n.nspname <>
'pg_catalog' AND n.nspname <> 'information_schema' AND n.nspname !~
'^pg_toast' AND pg_catalog.pg_table_is_visible(c.oid) ORDER BY
1,2;''', ['\dt', 'list tables.']),
'\di': ('''SELECT n.nspname as "Schema", c.relname as "Name", CASE
c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN
'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence'
WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' END as
"Type", pg_catalog.pg_get_userbyid(c.relowner) as "Owner",
c2.relname as "Table" FROM pg_catalog.pg_class c LEFT JOIN
pg_catalog.pg_namespace n ON n.oid = c.relnamespace LEFT JOIN
pg_catalog.pg_index i ON i.indexrelid = c.oid LEFT JOIN
pg_catalog.pg_class c2 ON i.indrelid = c2.oid WHERE c.relkind
IN ('i','') AND n.nspname <> 'pg_catalog' AND
n.nspname <> 'information_schema' AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;''', ['\di', 'list indexes.']),
'\dv': ('''SELECT n.nspname as "Schema", c.relname as "Name", CASE
c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN
'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence'
WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' END as
"Type", pg_catalog.pg_get_userbyid(c.relowner) as "Owner" FROM
pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON
n.oid = c.relnamespace WHERE c.relkind IN ('v','') AND
n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema'
AND n.nspname !~ '^pg_toast' AND
pg_catalog.pg_table_is_visible(c.oid) ORDER BY 1,2;''',
['\dv', 'list views.']),
}
NON_CASE_SENSITIVE_COMMANDS = {
'describe': (describe_table_details, ['DESCRIBE [pattern]', '']),
}
def execute(cur, sql):
"""Execute a special command and return the results. If the special command
is not supported a KeyError will be raised.
"""
command, verbose, arg = parse_special_command(sql)
# Look up the command in the case-sensitive dict, if it's not there look in
# non-case-sensitive dict. If not there either, throw a KeyError exception.
global CASE_SENSITIVE_COMMANDS
global NON_CASE_SENSITIVE_COMMANDS
try:
command_executor = CASE_SENSITIVE_COMMANDS[command][0]
except KeyError:
command_executor = NON_CASE_SENSITIVE_COMMANDS[command.lower()][0]
# If the command executor is a function, then call the function with the
# args. If it's a string, then assume it's an SQL command and run it.
if callable(command_executor):
return command_executor(cur, arg, verbose)
elif isinstance(command_executor, str):
cur.execute(command_executor)
if cur.description:
headers = [x[0] for x in cur.description]
return [(cur.fetchall(), headers, cur.statusmessage)]
else:
return [(None, None, cur.statusmessage)]
if __name__ == '__main__':
import psycopg2
con = psycopg2.connect(database='misago_testforum')
cur = con.cursor()
table = sys.argv[1]
for rows, headers, status in describe_table_details(cur, table, False):
print(tabulate(rows, headers, tablefmt='psql'))
print(status)
|
|
# pylint: skip-file
# flake8: noqa
class OCcsr(OpenShiftCLI):
''' Class to wrap the oc adm certificate command line'''
kind = 'csr'
# pylint: disable=too-many-arguments
def __init__(self,
nodes=None,
approve_all=False,
service_account=None,
kubeconfig='/etc/origin/master/admin.kubeconfig',
verbose=False):
''' Constructor for oc adm certificate '''
super(OCcsr, self).__init__(None, kubeconfig, verbose)
self.service_account = service_account
self.nodes = self.create_nodes(nodes)
self._csrs = []
self.approve_all = approve_all
self.verbose = verbose
@property
def csrs(self):
'''property for managing csrs'''
# any processing needed??
self._csrs = self._get(resource=self.kind)['results'][0]['items']
return self._csrs
def create_nodes(self, nodes):
'''create a node object to track csr signing status'''
nodes_list = []
if nodes is None:
return nodes_list
results = self._get(resource='nodes')['results'][0]['items']
for node in nodes:
nodes_list.append(dict(name=node, csrs={}, accepted=False, denied=False))
for ocnode in results:
if node in ocnode['metadata']['name']:
nodes_list[-1]['accepted'] = True
return nodes_list
def get(self):
'''get the current certificate signing requests'''
return self.csrs
@staticmethod
def action_needed(csr, action):
'''check to see if csr is in desired state'''
if csr['status'] == {}:
return True
state = csr['status']['conditions'][0]['type']
if action == 'approve' and state != 'Approved':
return True
elif action == 'deny' and state != 'Denied':
return True
return False
def get_csr_request(self, request):
'''base64 decode the request object and call openssl to determine the
subject and specifically the CN: from the request
Output:
(0, '...
Subject: O=system:nodes, CN=system:node:ip-172-31-54-54.ec2.internal
...')
'''
import base64
return self._run(['openssl', 'req', '-noout', '-text'], base64.b64decode(request))[1]
def match_node(self, csr):
'''match an inc csr to a node in self.nodes'''
for node in self.nodes:
# we need to match based upon the csr's request certificate's CN
if node['name'] in self.get_csr_request(csr['spec']['request']):
node['csrs'][csr['metadata']['name']] = csr
# check that the username is the node and type is 'Approved'
if node['name'] in csr['spec']['username'] and csr['status']:
if csr['status']['conditions'][0]['type'] == 'Approved':
node['accepted'] = True
# check type is 'Denied' and mark node as such
if csr['status'] and csr['status']['conditions'][0]['type'] == 'Denied':
node['denied'] = True
return node
return None
def finished(self):
'''determine if there are more csrs to sign'''
# if nodes is set and we have nodes then return if all nodes are 'accepted'
if self.nodes is not None and len(self.nodes) > 0:
return all([node['accepted'] or node['denied'] for node in self.nodes])
# we are approving everything or we still have nodes outstanding
return False
def manage(self, action):
'''run openshift oc adm ca create-server-cert cmd and store results into self.nodes
we attempt to verify if the node is one that was given to us to accept.
action - (allow | deny)
'''
results = []
# There are 2 types of requests:
# - node-bootstrapper-client-ip-172-31-51-246-ec2-internal
# The client request allows the client to talk to the api/controller
# - node-bootstrapper-server-ip-172-31-51-246-ec2-internal
# The server request allows the server to join the cluster
# Here we need to determine how to approve/deny
# we should query the csrs and verify they are from the nodes we thought
for csr in self.csrs:
node = self.match_node(csr)
# oc adm certificate <approve|deny> csr
# there are 3 known states: Denied, Aprroved, {}
# verify something is needed by OCcsr.action_needed
# if approve_all, then do it
# if you passed in nodes, you must have a node that matches
if self.approve_all or (node and OCcsr.action_needed(csr, action)):
result = self.openshift_cmd(['certificate', action, csr['metadata']['name']], oadm=True)
# if we successfully approved
if result['returncode'] == 0:
# client should have service account name in username field
# server should have node name in username field
if node and csr['metadata']['name'] not in node['csrs']:
node['csrs'][csr['metadata']['name']] = csr
# accept node in cluster
if node['name'] in csr['spec']['username']:
node['accepted'] = True
results.append(result)
return results
@staticmethod
def run_ansible(params, check_mode=False):
'''run the idempotent ansible code'''
client = OCcsr(params['nodes'],
params['approve_all'],
params['service_account'],
params['kubeconfig'],
params['debug'])
state = params['state']
api_rval = client.get()
if state == 'list':
return {'changed': False, 'results': api_rval, 'state': state}
if state in ['approve', 'deny']:
if check_mode:
return {'changed': True,
'msg': "CHECK_MODE: Would have {} the certificate.".format(params['state']),
'state': state}
all_results = []
finished = False
timeout = False
# loop for timeout or block until all nodes pass
ctr = 0
while True:
all_results.extend(client.manage(params['state']))
if client.finished():
finished = True
break
if params['timeout'] == 0:
if not params['approve_all']:
ctr = 0
if ctr * 2 > params['timeout']:
timeout = True
break
# This provides time for the nodes to send their csr requests between approvals
time.sleep(2)
ctr += 1
for result in all_results:
if result['returncode'] != 0:
return {'failed': True, 'msg': all_results, 'timeout': timeout}
return dict(changed=len(all_results) > 0,
results=all_results,
nodes=client.nodes,
state=state,
finished=finished,
timeout=timeout)
return {'failed': True,
'msg': 'Unknown state passed. %s' % state}
|
|
import mock
import unittest
from .helper import _ResourceMixin
class ReceiptTest(_ResourceMixin, unittest.TestCase):
def _getTargetClass(self):
from .. import Receipt
return Receipt
def _getCollectionClass(self):
from .. import Collection
return Collection
def _getLazyCollectionClass(self):
from .. import LazyCollection
return LazyCollection
def _makeOne(self):
return self._getTargetClass().from_data({
'object': 'receipt',
'id': 'rcpt_test',
'number': 'OMTH201710110001',
'location': '/receipts/rcpt_test',
'date': '2017-10-11T16:59:59Z',
'customer_name': 'John Doe',
'customer_address': 'Crystal Design Center (CDC)',
'customer_tax_id': 'Tax ID 1234',
'customer_email': '[email protected]',
'customer_statement_name': 'John',
'company_name': 'Omise Company Limited',
'company_address': 'Crystal Design Center (CDC)',
'company_tax_id': '0000000000000',
'charge_fee': 1315,
'voided_fee': 0,
'transfer_fee': 0,
'subtotal': 1315,
'vat': 92,
'wht': 0,
'total': 1407,
'credit_note': False,
'currency': 'thb'
})
@mock.patch('requests.get')
def test_retrieve(self, api_call):
class_ = self._getTargetClass()
self.mockResponse(api_call, """{
"object": "receipt",
"id": "rcpt_test",
"number": "OMTH201710110001",
"location": "/receipts/rcpt_test",
"date": "2017-10-11T16:59:59Z",
"customer_name": "John Doe",
"customer_address": "Crystal Design Center (CDC)",
"customer_tax_id": "Tax ID 1234",
"customer_email": "[email protected]",
"customer_statement_name": "John",
"company_name": "Omise Company Limited",
"company_address": "Crystal Design Center (CDC)",
"company_tax_id": "0000000000000",
"charge_fee": 1315,
"voided_fee": 0,
"transfer_fee": 0,
"subtotal": 1315,
"vat": 92,
"wht": 0,
"total": 1407,
"credit_note": false,
"currency": "thb"
}""")
receipt = class_.retrieve('rcpt_test')
self.assertTrue(isinstance(receipt, class_))
self.assertEqual(receipt.id, 'rcpt_test')
self.assertEqual(receipt.number, 'OMTH201710110001')
self.assertEqual(receipt.company_tax_id, '0000000000000')
self.assertEqual(receipt.charge_fee, 1315)
self.assertEqual(receipt.voided_fee, 0)
self.assertEqual(receipt.transfer_fee, 0)
self.assertEqual(receipt.subtotal, 1315)
self.assertEqual(receipt.total, 1407)
self.assertEqual(receipt.currency, 'thb')
self.assertRequest(
api_call,
'https://api.omise.co/receipts/rcpt_test'
)
@mock.patch('requests.get')
def test_retrieve_no_args(self, api_call):
class_ = self._getTargetClass()
collection_class_ = self._getCollectionClass()
self.mockResponse(api_call, """{
"object": "list",
"from": "1970-01-01T00:00:00Z",
"to": "2017-10-11T23:59:59Z",
"offset": 0,
"limit": 20,
"total": 1,
"order": "chronological",
"location": "/receipts",
"data": [
{
"object": "receipt",
"id": "rcpt_test",
"number": "OMTH201710110001",
"location": "/receipts/rcpt_test",
"date": "2017-10-11T16:59:59Z",
"customer_name": "John Doe",
"customer_address": "Crystal Design Center (CDC)",
"customer_tax_id": "Tax ID 1234",
"customer_email": "[email protected]",
"customer_statement_name": "John",
"company_name": "Omise Company Limited",
"company_address": "Crystal Design Center (CDC)",
"company_tax_id": "0000000000000",
"charge_fee": 1315,
"voided_fee": 0,
"transfer_fee": 0,
"subtotal": 1315,
"vat": 92,
"wht": 0,
"total": 1407,
"credit_note": false,
"currency": "thb"
}
]
}""")
receipts = class_.retrieve()
self.assertTrue(isinstance(receipts, collection_class_))
self.assertTrue(isinstance(receipts[0], class_))
self.assertEqual(receipts[0].id, 'rcpt_test')
self.assertEqual(receipts[0].number, 'OMTH201710110001')
self.assertEqual(receipts[0].company_tax_id, '0000000000000')
self.assertEqual(receipts[0].charge_fee, 1315)
self.assertEqual(receipts[0].voided_fee, 0)
self.assertEqual(receipts[0].transfer_fee, 0)
self.assertEqual(receipts[0].subtotal, 1315)
self.assertEqual(receipts[0].total, 1407)
self.assertEqual(receipts[0].currency, 'thb')
self.assertRequest(
api_call,
'https://api.omise.co/receipts'
)
@mock.patch('requests.get')
def test_list(self, api_call):
class_ = self._getTargetClass()
lazy_collection_class_ = self._getLazyCollectionClass()
self.mockResponse(api_call, """{
"object": "list",
"from": "1970-01-01T00:00:00Z",
"to": "2017-10-11T23:59:59Z",
"offset": 0,
"limit": 20,
"total": 1,
"order": "chronological",
"location": "/receipts",
"data": [
{
"object": "receipt",
"id": "rcpt_test",
"number": "OMTH201710110001",
"location": "/receipts/rcpt_test",
"date": "2017-10-11T16:59:59Z",
"customer_name": "John Doe",
"customer_address": "Crystal Design Center (CDC)",
"customer_tax_id": "Tax ID 1234",
"customer_email": "[email protected]",
"customer_statement_name": "John",
"company_name": "Omise Company Limited",
"company_address": "Crystal Design Center (CDC)",
"company_tax_id": "0000000000000",
"charge_fee": 1315,
"voided_fee": 0,
"transfer_fee": 0,
"subtotal": 1315,
"vat": 92,
"wht": 0,
"total": 1407,
"credit_note": false,
"currency": "thb"
}
]
}""")
receipts = class_.list()
self.assertTrue(isinstance(receipts, lazy_collection_class_))
receipts = list(receipts)
self.assertTrue(isinstance(receipts[0], class_))
self.assertEqual(receipts[0].id, 'rcpt_test')
self.assertEqual(receipts[0].number, 'OMTH201710110001')
self.assertEqual(receipts[0].company_tax_id, '0000000000000')
self.assertEqual(receipts[0].charge_fee, 1315)
self.assertEqual(receipts[0].voided_fee, 0)
self.assertEqual(receipts[0].transfer_fee, 0)
self.assertEqual(receipts[0].subtotal, 1315)
self.assertEqual(receipts[0].total, 1407)
self.assertEqual(receipts[0].currency, 'thb')
|
|
#!/usr/bin/env python
# Copyright 2018 The Clspv Authors. All rights reserved.
#
# 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.
import argparse
import collections
import os
import re
import subprocess
import tempfile
DESCRIPTION = """This script can be used to help with writing test cases for clspv.
When passed an OpenCL C source file, it will:
1. Build a SPIR-V module using clspv
2. Disassemble the module
3. Post-process the disassembly to introduce FileCheck variables and CHECK directives
4. Prepend appropriate run commands, append the source and print the final test case
When passed a SPIR-V module, only the post-processed disassembly is printed.
"""
# When one of these regular expressions matches on a disassembly line
# CHECK-DAG will be used instead of CHECK
CHECK_DAG_INSTRUCTION_REGEXES = (
r'OpType[a-zA-Z]+',
r'OpConstant[a-zA-Z]*',
r'OpSpecConstant[a-zA-Z]*',
r'OpCapability',
r'OpUndef',
r'OpVariable',
)
CHECK_DAG = '// CHECK-DAG:'
CHECK = '// CHECK:'
DROP_REGEXES = {
'boilerplate': (
r'^;',
r'OpCapability',
r'OpExtension',
r'OpMemoryModel',
r'OpEntryPoint',
r'OpExecutionMode',
r'OpSource',
r'OpDecorate',
r'OpMemberDecorate',
),
'functions': (
r'OpTypeFunction',
r'OpFunction',
r'OpLabel',
r'OpReturn',
r'OpFunctionEnd',
),
'memory': (
r'OpTypeRuntimeArray',
r'OpTypePointer',
r'OpVariable',
r'OpAccessChain',
r'OpLoad',
r'OpStore',
),
}
# Keep track of the FileCheck variables we're defining
variables = set()
def substitute_backreference(regex, value):
return regex.replace(r'\1', value)
def replace_ids_with_filecheck_variables(line):
# regex to match IDs, (variable name pattern, variable definition pattern)
regexp_repl = collections.OrderedDict((
(r'%([0-9]+)', (r'__original_id_\1', r'%[[\1:[0-9]+]]')),
(r'%([0-9a-zA-Z_]+)', (r'\1', r'%[[\1:[0-9a-zA-Z_]+]]')),
))
def repl(m):
namerex, defrex = regexp_repl[m.re.pattern]
var_match = m.group(1)
# Get the final FileCheck variable name
var = substitute_backreference(namerex, var_match)
# Do we know that variable?
if var in variables:
# Just use it
return '%[[{}]]'.format(var)
else:
# Add it to the list of known variables and define it in the output
variables.add(var)
return substitute_backreference(defrex, var)
for rr in regexp_repl.items():
line = re.sub(rr[0], repl, line)
return line
def process_disasm_line(args, line):
def format_line(check, line):
return '{:{}} {}'.format(check, len(CHECK_DAG), line.strip())
# Drop the line?
for drop_group in args.drop:
for rex in DROP_REGEXES[drop_group]:
if re.search(rex, line):
return ''
# First deal with IDs
line = replace_ids_with_filecheck_variables(line)
# Can we use CHECK-DAG?
for rex in CHECK_DAG_INSTRUCTION_REGEXES:
if re.search(rex, line):
return format_line(CHECK_DAG, line)
# Nope, use CHECK
return format_line(CHECK, line)
def generate_run_section(args):
clspv_options = ' '.join(args.clspv_options)
runsec = ''
runsec += '// RUN: clspv {} %s -o %t.spv\n'.format(clspv_options)
runsec += '// RUN: spirv-dis -o %t2.spvasm %t.spv\n'
runsec += '// RUN: FileCheck %s < %t2.spvasm\n'
runsec += '// RUN: spirv-val --target-env vulkan1.0 %t.spv\n'
runsec += '\n'
return runsec
def disassemble_and_post_process(args, spirv_module):
ret = ''
# Get SPIR-V disassembly for the module
cmd = [
'spirv-dis',
spirv_module
]
disasm = subprocess.check_output(cmd).decode('utf-8')
# Process the disassembly
for line in disasm.split('\n'):
if line.strip() == '':
continue
processed_line = process_disasm_line(args, line)
if processed_line:
ret += '{}\n'.format(processed_line)
return ret
def generate_test_case_from_source(args):
tc = ''
# Start with the RUN directives
tc += generate_run_section(args)
# Then compile the source
fd, spirvfile = tempfile.mkstemp()
os.close(fd)
cmd = [
args.clspv,
] + args.clspv_options + [
'-o', spirvfile,
args.spirv_module_or_cl_source
]
subprocess.check_call(cmd)
# Append the processed disassembly
tc += disassemble_and_post_process(args, spirvfile)
# Append the original source
tc += '\n'
with open(args.spirv_module_or_cl_source) as f:
tc += f.read()
# Finally, delete the temporary SPIR-V module
os.remove(spirvfile)
return tc
def generate_test_case(args):
# Determine whether we got source or SPIR-V
_, inputext = os.path.splitext(args.spirv_module_or_cl_source)
# Now choose the behaviour
if inputext == '.cl':
tc = generate_test_case_from_source(args)
else:
tc = disassemble_and_post_process(args.spirv_module_or_cl_source)
return tc
if __name__ == '__main__':
# Parse command line arguments
class HelpFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):
pass
parser = argparse.ArgumentParser(
description=DESCRIPTION,
formatter_class=HelpFormatter
)
parser.add_argument(
'--clspv', default='clspv',
help='clspv binary to use'
)
parser.add_argument(
'--clspv-options', action='append', default=[],
help='Pass an option to clspv when building (can be used multiple times)'
)
parser.add_argument(
'--drop', action='append', default=[], choices=DROP_REGEXES.keys(),
help='Remove specific groups of instructions from generated SPIR-V disassembly'
)
parser.add_argument(
'spirv_module_or_cl_source',
help='SPIR-V module or OpenCL C source file'
)
args = parser.parse_args()
# Generate test case and print to stdout
print(generate_test_case(args))
|
|
import inspect
from inspect import getsource
import os.path as op
from pkgutil import walk_packages
import re
import sys
from unittest import SkipTest
import pytest
import mne
from mne.utils import run_tests_if_main, requires_numpydoc, _pl
public_modules = [
# the list of modules users need to access for all functionality
'mne',
'mne.baseline',
'mne.beamformer',
'mne.chpi',
'mne.connectivity',
'mne.cov',
'mne.cuda',
'mne.datasets',
'mne.datasets.brainstorm',
'mne.datasets.hf_sef',
'mne.datasets.sample',
'mne.decoding',
'mne.dipole',
'mne.filter',
'mne.forward',
'mne.inverse_sparse',
'mne.io',
'mne.io.kit',
'mne.minimum_norm',
'mne.preprocessing',
'mne.report',
'mne.simulation',
'mne.source_estimate',
'mne.source_space',
'mne.surface',
'mne.stats',
'mne.time_frequency',
'mne.time_frequency.tfr',
'mne.viz',
]
def _func_name(func, cls=None):
"""Get the name."""
parts = []
if cls is not None:
module = inspect.getmodule(cls)
else:
module = inspect.getmodule(func)
if module:
parts.append(module.__name__)
if cls is not None:
parts.append(cls.__name__)
parts.append(func.__name__)
return '.'.join(parts)
# functions to ignore args / docstring of
docstring_ignores = {
'mne.externals',
'mne.fixes',
'mne.io.write',
'mne.io.meas_info.Info',
'mne.utils.docs.deprecated',
}
char_limit = 800 # XX eventually we should probably get this lower
tab_ignores = [
'mne.externals.tqdm._tqdm.__main__',
'mne.externals.tqdm._tqdm.cli',
'mne.channels.tests.test_montage',
'mne.io.curry.tests.test_curry',
]
error_ignores = {
# These we do not live by:
'GL01', # Docstring should start in the line immediately after the quotes
'EX01', 'EX02', # examples failed (we test them separately)
'ES01', # no extended summary
'SA01', # no see also
'YD01', # no yields section
'SA04', # no description in See Also
'PR04', # Parameter "shape (n_channels" has no type
'RT02', # The first line of the Returns section should contain only the type, unless multiple values are being returned # noqa
# XXX should also verify that | is used rather than , to separate params
# XXX should maybe also restore the parameter-desc-length < 800 char check
}
error_ignores_specific = { # specific instances to skip
('regress_artifact', 'SS05'), # "Regress" is actually imperative
}
subclass_name_ignores = (
(dict, {'values', 'setdefault', 'popitems', 'keys', 'pop', 'update',
'copy', 'popitem', 'get', 'items', 'fromkeys', 'clear'}),
(list, {'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'sort'}),
(mne.fixes.BaseEstimator, {'get_params', 'set_params', 'fit_transform'}),
)
def check_parameters_match(func, cls=None):
"""Check docstring, return list of incorrect results."""
from numpydoc.validate import validate
name = _func_name(func, cls)
skip = (not name.startswith('mne.') or
any(re.match(d, name) for d in docstring_ignores) or
'deprecation_wrapped' in getattr(
getattr(func, '__code__', None), 'co_name', ''))
if skip:
return list()
if cls is not None:
for subclass, ignores in subclass_name_ignores:
if issubclass(cls, subclass) and name.split('.')[-1] in ignores:
return list()
incorrect = ['%s : %s : %s' % (name, err[0], err[1])
for err in validate(name)['errors']
if err[0] not in error_ignores and
(name.split('.')[-1], err[0]) not in error_ignores_specific]
return incorrect
@pytest.mark.slowtest
@requires_numpydoc
def test_docstring_parameters():
"""Test module docstring formatting."""
from numpydoc import docscrape
# skip modules that require mayavi if mayavi is not installed
public_modules_ = public_modules[:]
try:
import mayavi # noqa: F401 analysis:ignore
public_modules_.append('mne.gui')
except ImportError:
pass
incorrect = []
for name in public_modules_:
# Assert that by default we import all public names with `import mne`
if name not in ('mne', 'mne.gui'):
extra = name.split('.')[1]
assert hasattr(mne, extra)
with pytest.warns(None): # traits warnings
module = __import__(name, globals())
for submod in name.split('.')[1:]:
module = getattr(module, submod)
classes = inspect.getmembers(module, inspect.isclass)
for cname, cls in classes:
if cname.startswith('_'):
continue
incorrect += check_parameters_match(cls)
cdoc = docscrape.ClassDoc(cls)
for method_name in cdoc.methods:
method = getattr(cls, method_name)
incorrect += check_parameters_match(method, cls=cls)
if hasattr(cls, '__call__') and \
'of type object' not in str(cls.__call__):
incorrect += check_parameters_match(cls.__call__, cls)
functions = inspect.getmembers(module, inspect.isfunction)
for fname, func in functions:
if fname.startswith('_'):
continue
incorrect += check_parameters_match(func)
incorrect = sorted(list(set(incorrect)))
msg = '\n' + '\n'.join(incorrect)
msg += '\n%d error%s' % (len(incorrect), _pl(incorrect))
if len(incorrect) > 0:
raise AssertionError(msg)
def test_tabs():
"""Test that there are no tabs in our source files."""
# avoid importing modules that require mayavi if mayavi is not installed
ignore = tab_ignores[:]
try:
import mayavi # noqa: F401 analysis:ignore
except ImportError:
ignore.extend('mne.gui.' + name for name in
('_coreg_gui', '_fiducials_gui', '_file_traits', '_help',
'_kit2fiff_gui', '_marker_gui', '_viewer'))
for _, modname, ispkg in walk_packages(mne.__path__, prefix='mne.'):
# because we don't import e.g. mne.tests w/mne
if not ispkg and modname not in ignore:
# mod = importlib.import_module(modname) # not py26 compatible!
try:
with pytest.warns(None):
__import__(modname)
except Exception: # can't import properly
continue
mod = sys.modules[modname]
try:
source = getsource(mod)
except IOError: # user probably should have run "make clean"
continue
assert '\t' not in source, ('"%s" has tabs, please remove them '
'or add it to the ignore list'
% modname)
documented_ignored_mods = (
'mne.fixes',
'mne.io.write',
'mne.utils',
'mne.viz.utils',
)
documented_ignored_names = """
BaseEstimator
ContainsMixin
CrossSpectralDensity
FilterMixin
GeneralizationAcrossTime
RawFIF
TimeMixin
ToDataFrameMixin
TransformerMixin
UpdateChannelsMixin
activate_proj
adjust_axes
apply_maxfilter
apply_trans
channel_type
check_n_jobs
combine_kit_markers
combine_tfr
combine_transforms
design_mne_c_filter
detrend
dir_tree_find
fast_cross_3d
fiff_open
find_source_space_hemi
find_tag
get_score_funcs
get_version
invert_transform
is_power2
is_fixed_orient
kit2fiff
label_src_vertno_sel
make_eeg_average_ref_proj
make_projector
mesh_dist
mesh_edges
next_fast_len
parallel_func
pick_channels_evoked
plot_epochs_psd
plot_epochs_psd_topomap
plot_raw_psd_topo
plot_source_spectrogram
prepare_inverse_operator
read_bad_channels
read_fiducials
read_tag
rescale
setup_proj
source_estimate_quantification
tddr
whiten_evoked
write_fiducials
write_info
""".split('\n')
def test_documented():
"""Test that public functions and classes are documented."""
# skip modules that require mayavi if mayavi is not installed
public_modules_ = public_modules[:]
try:
import mayavi # noqa: F401, analysis:ignore
except ImportError:
pass
else:
public_modules_.append('mne.gui')
doc_file = op.abspath(op.join(op.dirname(__file__), '..', '..', 'doc',
'python_reference.rst'))
if not op.isfile(doc_file):
raise SkipTest('Documentation file not found: %s' % doc_file)
known_names = list()
with open(doc_file, 'rb') as fid:
for line in fid:
line = line.decode('utf-8')
if not line.startswith(' '): # at least two spaces
continue
line = line.split()
if len(line) == 1 and line[0] != ':':
known_names.append(line[0].split('.')[-1])
known_names = set(known_names)
missing = []
for name in public_modules_:
with pytest.warns(None): # traits warnings
module = __import__(name, globals())
for submod in name.split('.')[1:]:
module = getattr(module, submod)
classes = inspect.getmembers(module, inspect.isclass)
functions = inspect.getmembers(module, inspect.isfunction)
checks = list(classes) + list(functions)
for name, cf in checks:
if not name.startswith('_') and name not in known_names:
from_mod = inspect.getmodule(cf).__name__
if (from_mod.startswith('mne') and
not from_mod.startswith('mne.externals') and
not any(from_mod.startswith(x)
for x in documented_ignored_mods) and
name not in documented_ignored_names):
missing.append('%s (%s.%s)' % (name, from_mod, name))
if len(missing) > 0:
raise AssertionError('\n\nFound new public members missing from '
'doc/python_reference.rst:\n\n* ' +
'\n* '.join(sorted(set(missing))))
run_tests_if_main()
|
|
# -*- coding: utf-8 -*-
"""
OSM Deviation Finder - Web Interface
~~~~~~~~~~~~~~~~~~~~
Implementation of a web interface for the OSM Deviation Finder library.
It uses the flask microframework by Armin Ronacher
For more information see https://github.com/mitsuhiko/flask/
To interact with the GeoServer REST API, the GeoServer configuration client library by boundlessgeo is used, see:
https://github.com/boundlessgeo/gsconfig
On the client side it uses jquery.js, leaflet.js, nprogress.js and the UIKit framework, for further information
see the README.md file.
:copyright: (c) 2015 by Martin Hochenwarter
:license: MIT
"""
__author__ = 'Martin Hochenwarter'
__version__ = '0.1'
from web import db
from models import DevMap
from flask import Blueprint, jsonify, make_response
from flask.ext.login import (current_user, login_required)
from functools import wraps, update_wrapper
from datetime import datetime
#: Blueprint for geojson requests used by leaflet.js to load map data
geojsonapi = Blueprint('geojsonapi', __name__, template_folder='templates')
def nocache(view):
@wraps(view)
def no_cache(*args, **kwargs):
response = make_response(view(*args, **kwargs))
response.headers['Last-Modified'] = datetime.now()
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '-1'
return response
return update_wrapper(no_cache, view)
@geojsonapi.route('/listed/geojson', methods=['GET'])
@nocache
def listedbboxes():
"""Returns all bounding polygons of listed maps as geojson, if none are found an error is returend.
This can used to display the boundings of listed maps in a leaflet.js map an the front- and browse-page
"""
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f.boundsyx)) As features '
'FROM (SELECT boundsyx, title, datasource, datalicense '
'FROM dev_map where listed=true) As f ) As fc;').fetchone()
if data[0]['features'] is not None:
return jsonify(data[0])
else:
message = {
'status': 404,
'message': 'Not Found',
}
resp = jsonify(message)
resp.status_code = 404
return resp
@geojsonapi.route('/manage/geojson', methods=['GET'])
@nocache
@login_required
def managebboxes():
"""Returns all bounding polygons of the deviation maps of the currently logged in user as geojson.
If the user is admin, the bounding polygons of all deviationsmaps in the database are returend as geojson.
If no deviation maps are found an error is returend.
This can used to display the boundings of the deviation maps of the current user / all users (admin) in
a leaflet.js map on the manage page.
"""
if current_user.is_authenticated():
if current_user.role == 1: # Admin
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f.boundsyx)) As features '
'FROM (SELECT boundsyx FROM dev_map) As f) As fc;').fetchone()
else:
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f.boundsyx)) As features '
'FROM (SELECT boundsyx FROM dev_map '
'WHERE dev_map.user_id = '+str(current_user.id)+') As f) As fc;').fetchone()
if data[0]['features'] is not None:
return jsonify(data[0])
else:
message = {
'status': 404,
'message': 'Not Found',
}
resp = jsonify(message)
resp.status_code = 404
return resp
@geojsonapi.route('/<uid>/geojson/boundsxy', methods=['GET'])
@nocache
def boundsxy(uid):
"""Returns the boundig polygon in XY format (used by overpass) of the current map with uid <uid> as geojson
"""
uid = uid.encode('ISO-8859-1')
dm = DevMap.query.filter_by(uid=uid).first()
bounds = dm.boundsxy
return jsonify(bounds)
@geojsonapi.route('/<uid>/geojson/boundsyx', methods=['GET'])
@nocache
def boundsyx(uid):
"""Returns the boundig polygon in YX format (used by leaflet) of the current map with uid <uid> as geojson
"""
uid = uid.encode('ISO-8859-1')
dm = DevMap.query.filter_by(uid=uid).first()
bounds = dm.boundsyx
return jsonify(bounds)
@geojsonapi.route('/<uid>/geojson/reference', methods=['GET'])
@nocache
def referencelines(uid):
"""Returns the original reference lines and their id as geojson.
This can used to display the original reference lines in a leaflet.js map.
"""
uid = uid.encode('ISO-8859-1')
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f)) As features '
'FROM (SELECT \'Feature\' As type, ST_AsGeoJSON(lg.geom)::json As geometry, '
'row_to_json((SELECT l FROM (SELECT id) As l)) As properties '
'FROM odf_'+uid+'_ref As lg ) As f ) As fc;').fetchone()
return jsonify(data[0])
@geojsonapi.route('/<uid>/geojson/osm', methods=['GET'])
@nocache
def osmlines(uid):
"""Returns the original osm lines and their id as geojson.
This can used to display the original osm lines in a leaflet.js map.
"""
uid = uid.encode('ISO-8859-1')
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f)) As features '
'FROM (SELECT \'Feature\' As type, ST_AsGeoJSON(lg.geom)::json As geometry, '
'row_to_json((SELECT l FROM (SELECT id) As l)) As properties '
'FROM odf_'+uid+'_osm As lg ) As f ) As fc;').fetchone()
return jsonify(data[0])
@geojsonapi.route('/<uid>/geojson/referencesplitted', methods=['GET'])
@nocache
def referencesplitted(uid):
"""Returns the harmoized reference lines and their id, parent_id and name as geojson.
This can used to display the original reference lines in a leaflet.js map.
"""
uid = uid.encode('ISO-8859-1')
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f)) As features '
'FROM (SELECT \'Feature\' As type, ST_AsGeoJSON(lg.geom)::json As geometry, '
'row_to_json((SELECT l FROM (SELECT id, old_id, name) As l)) As properties '
'FROM odf_'+uid+'_ref_splitted As lg ) As f ) As fc;').fetchone()
return jsonify(data[0])
@geojsonapi.route('/<uid>/geojson/osmsplitted', methods=['GET'])
@nocache
def osmsplitted(uid):
"""Returns the harmoized osm lines and their id, osm_id and name as geojson.
This can used to display the harmoized osm lines in a leaflet.js map.
"""
uid = uid.encode('ISO-8859-1')
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f)) As features '
'FROM (SELECT \'Feature\' As type, ST_AsGeoJSON(lg.geom)::json As geometry, '
'row_to_json((SELECT l FROM (SELECT id, osm_id, name) As l)) As properties '
'FROM odf_'+uid+'_osm_splitted As lg ) As f ) As fc;').fetchone()
return jsonify(data[0])
@geojsonapi.route('/<uid>/geojson/referencematched', methods=['GET'])
@nocache
def referencematched(uid):
"""Returns the harmoized and matched reference lines and their id, parentid and name as geojson.
This can used to display the original reference lines in a leaflet.js map.
"""
uid = uid.encode('ISO-8859-1')
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f)) As features '
'FROM (SELECT \'Feature\' As type, ST_AsGeoJSON(lg.geom)::json As geometry, '
'row_to_json((SELECT l FROM (SELECT id, old_id, name) As l)) As properties '
'FROM odf_'+uid+'_ref_splitted As lg ) As f ) As fc;').fetchone()
return jsonify(data[0])
@geojsonapi.route('/<uid>/geojson/osmmatched', methods=['GET'])
@nocache
def osmmatched(uid):
"""Returns the harmoized and matched osm lines and their id, osm_id and name as geojson.
This can used to display the harmoized osm lines in a leaflet.js map.
"""
uid = uid.encode('ISO-8859-1')
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f)) As features '
'FROM (SELECT \'Feature\' As type, ST_AsGeoJSON(lg.geom)::json As geometry, '
'row_to_json((SELECT l FROM (SELECT id, osm_id, name) As l)) As properties '
'FROM odf_'+uid+'_osm_splitted As lg ) As f ) As fc;').fetchone()
return jsonify(data[0])
@geojsonapi.route('/<uid>/geojson/deviationlines', methods=['GET'])
@nocache
def deviationlines(uid):
"""Returns the deviation lines generated as result and their deviation attribute as geojson.
This can be used to display the original reference lines in a leaflet.js map.
"""
uid = uid.encode('ISO-8859-1')
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f)) As features FROM (SELECT \'Feature\' As type, '
'ST_AsGeoJSON(lg.geom)::json As geometry, row_to_json((SELECT l '
'FROM (SELECT fit) As l)) As properties '
'FROM odf_'+uid+'_posdevlines As lg) As f) As fc;').fetchone()
return jsonify(data[0])
@geojsonapi.route('/<uid>/geojson/referencejunctions', methods=['GET'])
@nocache
def referencejunctions(uid):
"""Returns the genereated reference junction points as geojson.
This can be used to display the generated reference junction points in a leaflet.js map.
"""
uid = uid.encode('ISO-8859-1')
try:
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f)) As features FROM (SELECT \'Feature\' As type, '
'ST_AsGeoJSON(lg.geom)::json As geometry, '
'row_to_json((SELECT l FROM (SELECT id) As l)) As properties '
'FROM odf_'+uid+'_ref_junctions As lg ) As f ) As fc;').fetchone()
except Exception:
message = {
'status': 404,
'message': 'Not Found',
}
resp = jsonify(message)
resp.status_code = 404
return resp
return jsonify(data[0])
@geojsonapi.route('/<uid>/geojson/osmjunctions', methods=['GET'])
@nocache
def osmjunctions(uid):
"""Returns the generated osm junction points as geojson.
This can be used to display the generated osm junction points in a leaflet.js map.
"""
try:
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f)) As features FROM (SELECT \'Feature\' As type, '
'ST_AsGeoJSON(lg.geom)::json As geometry, '
'row_to_json((SELECT l FROM (SELECT id) As l)) As properties '
'FROM odf_'+uid+'_osm_junctions As lg ) As f ) As fc;').fetchone()
except Exception:
message = {
'status': 404,
'message': 'Not Found',
}
resp = jsonify(message)
resp.status_code = 404
return resp
if data[0]['features'] is not None:
return jsonify(data[0])
else:
message = {
'status': 404,
'message': 'Not Found',
}
resp = jsonify(message)
resp.status_code = 404
return resp
@geojsonapi.route('/<uid>/geojson/junctiondeviationlines', methods=['GET'])
@nocache
def junctiondeviationlines(uid):
"""Returns the genereated junction deviation lines as geojson.
This can be used to display junction deviation lines in a leaflet.js map.
"""
uid = uid.encode('ISO-8859-1')
data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'FeatureCollection\' As type, '
'array_to_json(array_agg(f)) As features FROM (SELECT \'Feature\' As type, '
'ST_AsGeoJSON(lg.geom)::json As geometry, '
'row_to_json((SELECT l FROM (SELECT id) As l)) As properties '
'FROM odf_'+uid+'_junction_devlines As lg ) As f ) As fc;').fetchone()
return jsonify(data[0])
|
|
"""Device, context and memory management on PyCUDA and scikit-cuda.
Chainer uses PyCUDA facilities (with very thin wrapper) to exploit the speed of
GPU computation. Following modules and classes are imported to :mod:`cuda`
module for convenience (refer to this table when reading chainer's source
codes).
============================ =================================
imported name original name
============================ =================================
``chainer.cuda.cublas`` :mod:`skcuda.cublas`
``chainer.cuda.cumath`` :mod:`pycuda.cumath`
``chainer.cuda.curandom`` :mod:`pycuda.curandom`
``chainer.cuda.culinalg`` :mod:`skcuda.linalg`
``chainer.cuda.cumisc`` :mod:`skcuda.misc`
``chainer.cuda.gpuarray`` :mod:`pycuda.gpuarray`
``chainer.cuda.Context`` :mod:`pycuda.driver.Context`
``chainer.cuda.Device`` :mod:`pycuda.driver.Device`
``chainer.cuda.Event`` :mod:`pycuda.driver.Event`
``chainer.cuda.GPUArray`` :mod:`pycuda.gpuarray.GPUArray`
``chainer.cuda.Stream`` :mod:`pycuda.driver.Stream`
============================ =================================
Chainer provides thin wrappers of GPUArray allocation routines, which use
:func:`mem_alloc` as the allocator. This allocator uses device-wise instance of
:class:`~pycuda.tools.DeviceMemoryPool`, which enables the reuse of device
memory over multiple forward/backward computations. :func:`mem_alloc` also
inserts an additional attribute to the allocated memory called ``device``,
which indicates the device that the memory is allocated on. Functions of
:mod:`cuda` uses this attribute to select appropriate device on each
manipulation routine.
"""
import atexit
import os
import warnings
import numpy
import pkg_resources
import six
try:
try:
pkg_resources.require('scikits.cuda')
except pkg_resources.ResolutionError as e:
pass
else:
msg = '''
`scikits.cuda` package is found. This is deprecated.
Clean both the old and new `scikit-cuda` packages, and then re-install
`chainer-cuda-deps`.
$ pip uninstall scikits.cuda scikit-cuda
$ pip install -U chainer-cuda-deps
'''
warnings.warn(msg)
_requires = [
'pycuda>=2014.1',
'scikit-cuda>=0.5.0',
'Mako',
'six>=1.9.0',
]
pkg_resources.require(_requires)
import pycuda.cumath
import pycuda.curandom
import pycuda.driver as drv
import pycuda.elementwise
import pycuda.gpuarray
import pycuda.reduction
import pycuda.tools
import skcuda.cublas
import skcuda.linalg
import skcuda.misc
available = True
cublas = skcuda.cublas
cumath = pycuda.cumath
curandom = pycuda.curandom
culinalg = skcuda.linalg
cumisc = skcuda.misc
cutools = pycuda.tools
gpuarray = pycuda.gpuarray
except pkg_resources.ResolutionError as e:
available = False
_resolution_error = e
# ------------------------------------------------------------------------------
# Basic types
# ------------------------------------------------------------------------------
if available:
import pycuda.driver
import pycuda.gpuarray
Context = pycuda.driver.Context
Device = pycuda.driver.Device
Event = pycuda.driver.Event
Stream = pycuda.driver.Stream
GPUArray = pycuda.gpuarray.GPUArray
else:
# Dummy classes
class Context(object):
pass
class Device(object):
pass
class Event(object):
pass
class Stream(object):
pass
class GPUArray(object):
pass
# ------------------------------------------------------------------------------
# Global states
# ------------------------------------------------------------------------------
generator = None
_contexts = {}
_pools = {}
_generators = {}
_cublas_handles = {}
_pid = None
def _check_cuda_available():
if not available:
global _resolution_error
msg = '''CUDA environment is not correctly set up.
Use `pip install -U chainer-cuda-deps` to install libraries.
'''
# Note that error message depends on its type
if isinstance(_resolution_error, pkg_resources.DistributionNotFound):
msg += 'Required package is not found: ' + str(_resolution_error)
elif isinstance(_resolution_error, pkg_resources.VersionConflict):
msg += 'Version conflict: ' + str(_resolution_error)
else:
msg += 'Unknwon error: ' + str(_resolution_error)
raise RuntimeError(msg)
def init(device=None):
"""Initializes CUDA global state.
Chainer maintains CUDA context, CUBLAS context, random number generator and
device memory pool for each GPU device and for each process (the main
process or a process forked by :mod:`multiprocessing`) as global states.
When called for the first time on the process, this function initializes
these global states.
.. warning::
This function also initializes PyCUDA and scikit-cuda. Since these
packages do not support forking after initialization, do not call this
function before forking the process.
This function also registers :func:`shutdown` to :mod:`atexit` slot.
It also initializes random number generator. User can set fixed seed with
``CHAINER_SEED`` environment variable.
Args:
device (``int`` or :class:`~pycuda.driver.Device` or ``None``): Device
ID to initialize on.
"""
global _contexts, _cublas_handles, _generators, _pid, _pools
_check_cuda_available()
pid = os.getpid()
if _pid == pid: # already initialized
return
drv.init()
if device is None: # use default device
context = cutools.make_default_context()
device = Context.get_device()
else:
device = Device(device)
context = device.make_context()
_contexts = {device: context}
_generators = {}
_pools = {}
_cublas_handles = {}
cumisc.init(mem_alloc)
seed(os.environ.get('CHAINER_SEED'))
_pid = pid # mark as initialized
atexit.register(shutdown)
def shutdown():
"""Finalizes CUDA global state.
This function is automatically called by :mod:`atexit`. Multiple calls are
allowed, so user can manually call this function if necessary.
"""
global _contexts, _cublas_handles, _pid, _pools
_check_cuda_available()
pid = os.getpid()
if _pid != pid: # not initialized
return
for cublas_handle in six.itervalues(_cublas_handles):
cublas.cublasDestroy(cublas_handle)
_cublas_handles = {}
cumisc.shutdown()
_pools = {}
for ctx in six.itervalues(_contexts):
ctx.detach()
_contexts = {}
_pid = None # mark as uninitialized
def get_device(arg=None):
"""Gets the device from ID arg or given chainer's.
:class:`~pycuda.gpuarray.GPUArray`.
Args:
arg: Value to specify a GPU device.
Returns:
Device object specified by given ``arg``.
The rule of device selection is following.
==================================== =====================================
Type of ``arg`` Return value
==================================== =====================================
``None`` Current device
``int`` Device of ID ``arg``
:class:`~pycuda.driver.Device` ``arg``
:class:`~pycuda.gpuarray.GPUArray` Device given array was allocated on
:class:`~numpy.ndarray` ``None``
==================================== =====================================
"""
if arg is None:
return Context.get_device()
elif isinstance(arg, Device):
return arg
elif isinstance(arg, numpy.ndarray):
return None
elif isinstance(arg, GPUArray):
while not hasattr(arg.gpudata, 'device'):
arg = arg.base
return arg.gpudata.device
return drv.Device(arg)
def use_device(arg, pop=True):
"""Switches the CUDA context to use given device.
Args:
arg: Argument of :func:`get_device`.
pop (bool): If True, pop the current context from context
stack.
"""
device = get_device(arg)
if device is None:
return
if pop:
drv.Context.pop()
if device not in _contexts:
_contexts[device] = device.make_context()
else:
_contexts[device].push()
class DeviceUser(object):
"""RAII-style CUDA context swithcer.
Args:
arg: Argument of :func:`get_device`.
Attributes:
device (~pycuda.driver.Device): Selected device.
"""
def __init__(self, arg):
if arg is None:
self.device = None
else:
self.device = get_device(arg)
def __enter__(self):
if self.is_active:
use_device(self.device, pop=False)
return self
def __exit__(self, typ, value, traceback):
if self.is_active:
drv.Context.pop()
self.device = None
@property
def is_active(self):
return self.device is not None
def using_device(*args):
"""Returns a DeviceUser object of the first GPUArray argument.
If none of the arguments specifies a GPU device, then it returns a dummy
:class:`DeviceUser` object which is inactive.
Args:
*args: Objects based on which an appropriate device should be selected.
Returns:
DeviceUser: Device user instance of selected argument.
.. admonition:: Example
Suppose ``arrays`` is a list of arrays of type either
:class:`~numpy.ndarray` or :class:`~pycuda.gpuarray.GPUArray`. Then,
the following code invokes ``do_something_on`` with an appropriate
context::
with using_device(*arrays):
do_something_on(arrays)
"""
for arg in args:
user = DeviceUser(arg)
if user.is_active:
return user
return DeviceUser(None)
def get_context(arg=None):
"""Gets the context corresponding to the specified device.
Args:
arg: Argument of :func:`get_device`.
Returns:
~pycuda.driver.Context: Context object corresponding to the specified
device.
"""
device = get_device(arg)
if device is None:
return None
return _contexts[device]
def mem_alloc(nbytes):
"""Allocates device memory of given size from memory pool.
This function chooses memory pool corresponding to the current device.
Args:
nbytes (int): The size of memory in bytes.
Returns:
pycuda.tools.PooledDeviceAllocation: Allocated memory with additional
``device`` attribute. This attribute is used to determine on which GPU
the memory resides.
"""
global _pools
device = Context.get_device()
pool = _pools.get(device, None)
if pool is None:
pool = drv.DeviceMemoryPool()
_pools[device] = pool
allocation = pool.allocate(nbytes)
setattr(allocation, 'device', device)
return allocation
def _get_seed_getter(s=None):
if s is None:
return curandom.seed_getter_uniform
else:
return lambda N: full((N,), s, numpy.int32)
def get_generator(device=None):
"""Gets the random number generator for the given device.
Args:
device: Device specifier (an arugment of :func:`get_device`)
Returns:
pycuda.curandom.XORWOWRandomNumberGenerator: Random number generator.
"""
global _generators
device = get_device(device)
gen = _generators.get(device)
if gen is not None:
return gen
with using_device(device):
s = os.environ.get('CHAINER_SEED')
seed_getter = _get_seed_getter(s)
gen = curandom.XORWOWRandomNumberGenerator(seed_getter=seed_getter)
_generators[device] = gen
return gen
def seed(s=None, device=None):
"""Resets the random number generator of the specified device.
Args:
s (int or None): Seed value. If it is ``None``, it initializes the
generator without fixed seed.
device: Device specifier (i.e. argument of :func:`get_device`).
"""
global _generators
with DeviceUser(device) as user:
seed_getter = _get_seed_getter(s)
gen = curandom.XORWOWRandomNumberGenerator(seed_getter=seed_getter)
_generators[user.device] = gen
# ------------------------------------------------------------------------------
# GPUArray allocation and copy
# ------------------------------------------------------------------------------
# Workaround: the original GPUArray.copy does not use the user-defined
# allocator, so we have to replace it. A good solution is to inherit GPUArray
# and override copy method, but since many functions of pycuda.gpuarray
# directly use the original GPUArray class, we choose easy and ugly solution
# that directly replaces the original method.
# TODO(beam2d): Fix this ugly solution
def _gpuarray_copy(array):
if not array.flags.forc:
raise RuntimeError('only contiguous arrays may copied.')
new = GPUArray(array.shape, array.dtype, allocator=array.allocator)
drv.memcpy_dtod(new.gpudata, array.gpudata, array.nbytes)
return new
GPUArray.copy = _gpuarray_copy
def to_gpu(array, device=None):
"""Copies the given CPU array to specified device.
Args:
array: Array to be sent to GPU.
device: Device specifier.
Returns:
~pycuda.gpuarray.GPUArray: Array on GPU.
If ``array`` is already on GPU, then this function just returns
``array`` without performing any copy. Note that this function does not
copy GPUArray into specified device.
"""
_check_cuda_available()
if isinstance(array, GPUArray):
return array
with using_device(device):
return gpuarray.to_gpu(array, allocator=mem_alloc)
# Pickle redefinition of GPUArray. Note that pickling and unpickling of
# GPUArray do not preserve device information, i.e. the unpickled GPUArray may
# reside on a GPU different from the GPU that the original has resided on.
def _reconstruct(array, is_chainer_array):
if is_chainer_array:
return to_gpu(array)
return gpuarray.to_gpu(array)
six.moves.copyreg.pickle(
GPUArray,
lambda data: (_reconstruct, (data.get(), hasattr(data.gpudata, 'device'))),
_reconstruct)
def to_gpu_async(array, stream=None):
"""Copies the given CPU array asynchronously to the current device.
Args:
array: Array to be sent to GPU. If it is :class:`~numpy.ndarray`, then
its memory must be pagelocked.
stream (~pycuda.driver.Stream): CUDA stream.
Returns:
~pycuda.gpuarray.GPUArray: Array on GPU.
If given ``array`` is already on GPU, then this function just returns
``array`` without performing any copy.
"""
_check_cuda_available()
if isinstance(array, GPUArray):
return array
return gpuarray.to_gpu_async(array, allocator=mem_alloc, stream=stream)
def to_cpu(array):
"""Copies the given GPU array to host CPU.
Args:
array: Array to be sent to GPU.
Returns:
~numpy.ndarray: Array on CPU.
If given ``array`` is already on CPU, then this function just returns
``array`` without performing any copy.
"""
if isinstance(array, GPUArray):
return array.get()
return array
def to_cpu_async(array, stream=None):
"""Copies the given GPU array asynchronously to host CPU.
Args:
array: Array to be sent to GPU.
stream (~pycuda.driver.Stream): CUDA stream.
Returns:
~numpy.ndarray: Array on CPU.
If given ``array`` is already on CPU, then this function just returns
``array`` without performing any copy.
"""
if isinstance(array, numpy.ndarray):
return array
return array.get_async(stream=stream)
def empty(shape, dtype=numpy.float32):
"""Creates an uninitialized GPUArray object.
Args:
shape (tuple of ints): The shape of array.
dtype (numpy.dtype): Element type.
Returns:
~pycuda.gpuarray.GPUArray: Uninitialized GPU array allocated by memory
pool.
"""
_check_cuda_available()
return gpuarray.empty(shape, dtype, allocator=mem_alloc)
def full(shape, fill_value, dtype=numpy.float32, stream=None):
"""Creates a constant-filled GPUArray object.
Args:
shape (tuple of ints): The shape of array.
fill_value: Constant to fill the array by.
dtype (numpy.dtype): Element type.
stream (~pycuda.driver.Stream): CUDA stream.
Returns:
~pycuda.gpuarray.GPUArray: Constant-filled GPU array allocated by
memory pool.
"""
array = empty(shape, dtype)
array.fill(fill_value, stream=stream)
return array
def zeros(shape, dtype=numpy.float32, stream=None):
"""Creates a zero-filled GPUArray object.
This function is equivalent to ``full(shape, 0, dtype, stream)``.
"""
return full(shape, 0, dtype, stream=stream)
def ones(shape, dtype=numpy.float32, stream=None):
"""Creates a zero-filled GPUArray object.
This function is equivalent to ``full(shape, 1, dtype, stream)``.
"""
return full(shape, 1, dtype, stream=stream)
def empty_like(array):
"""Alias to :func:`pycuda.gpuarray.empty_like`."""
_check_cuda_available()
return gpuarray.empty_like(array)
def full_like(array, fill_value, stream=None):
"""Creates a constant-filled GPUArray object like the given array.
Args:
array (~pycuda.gpuarray.GPUArray): Base array.
fill_value: Constant value to fill the array by.
stream (~pycuda.driver.Stream): CUDA stream.
Returns:
~pycuda.gpuarray.GPUArray: Constant-filled array.
"""
array = empty_like(array)
array.fill(fill_value, stream=stream)
return array
def zeros_like(array, stream=None):
"""Creates a zero-filled GPUArray object like the given array.
This function is equivalent to ``full_like(array, 0, stream)``.
"""
return full_like(array, 0, stream=stream)
def ones_like(array, stream=None):
"""Creates a one-filled GPUArray object like the given array.
This function is equivalent to ``full_like(array, 1, stream)``.
"""
return full_like(array, 1, stream=stream)
def copy(array, out=None, out_device=None):
"""Copies a GPUArray object using the default stream.
This function can copy the device array to the destination array on another
device.
Args:
array (~pycuda.gpuarray.GPUArray): Array to be copied.
out (~pycuda.gpuarray.GPUArray): Destination array.
If it is not ``None``, then ``out_device`` argument is ignored.
out_device: Destination device specifier. Actual device object is
obtained by passing this value to :func:`get_device`.
Returns:
~pycuda.gpuarray.GPUArray: Copied array.
If ``out`` is not specified, then the array is allocated on the device
specified by ``out_device`` argument.
"""
in_device = get_device(array)
if out is None:
if out_device is None:
out_device = in_device
else:
out_device = get_device(out_device)
with using_device(out_device):
out = empty_like(array)
else:
out_device = get_device(out)
with using_device(in_device):
if in_device == out_device:
drv.memcpy_dtod(out.ptr, array.ptr, out.nbytes)
else:
drv.memcpy_peer(
out.ptr, array.ptr, out.nbytes, out_device, in_device)
return out
def copy_async(array, out=None, out_device=None, stream=None):
"""Copies a GPUArray object using the given stream.
This function can copy the device array to the destination array on another
device.
Args:
array (~pycuda.gpuarray.GPUArray): Array to be copied.
out (~pycuda.gpuarray.GPUArray): Destination array.
If it is not ``None``, then ``out_device`` argument is ignored.
out_device: Destination device specifier. Actual device object is
obtained by passing this value to :func:`get_device`.
stream (~pycuda.driver.Stream): CUDA stream.
Returns:
~pycuda.gpuarray.GPUArray: Copied array.
If ``out`` is not specified, then the array is allocated on the device
specified by ``out_device`` argument.
.. warning::
Currently, copy_async over different devices raises exception, since
PyCUDA drops the definition of :func:`pycuda.driver.memcopy_peer_async`.
"""
in_device = get_device(array)
if out is None:
if out_device is None:
out_device = in_device
else:
out_device = get_device(out_device)
with using_device(out_device):
out = empty_like(array)
else:
out_device = get_device(out)
with using_device(in_device):
if in_device == out_device:
drv.memcpy_dtod_async(
out.ptr, array.ptr, out.nbytes, stream=stream)
else:
drv.memcpy_peer_async(out.ptr, array.ptr, out.nbytes, out_device,
in_device, stream=stream)
return out
# ------------------------------------------------------------------------------
# Add comparison of `__array_priority__` to GPUArray binary operator
# ------------------------------------------------------------------------------
def _wrap_operation(obj, op):
op_name = '__{}__'.format(op)
rop_name = '__r{}__'.format(op)
raw_op = getattr(obj, op_name)
def new_op(self, other):
rop = getattr(other, rop_name, None)
if rop is None:
return raw_op(self, other)
self_pri = getattr(self, '__array_priority__', 0.0)
other_pri = getattr(other, '__array_priority__', 0.0)
if self_pri >= other_pri:
return raw_op(self, other)
return rop(self)
setattr(obj, op_name, new_op)
if available:
for op in ('add', 'sub', 'mul', 'div', 'pow', 'truediv'):
_wrap_operation(GPUArray, op)
# ------------------------------------------------------------------------------
# Interprocess communication
# ------------------------------------------------------------------------------
class IPCEvent(Event):
"""Event object for interprocess synchronization on GPU."""
def __init__(self):
super(IPCEvent, self).__init__(
drv.event_flags.INTERPROCESS | drv.event_flags.DISABLE_TIMING)
class IPCArrayHandle(object):
"""Converter between GPUArray and its Inter-Process Communication handle.
It holds IPC memory handle with shape and dtype information. The instance
can be pickled, which means it can be passed through IPC path way, e.g.
Pipe and Queue. The other process can extract shared GPUArray by calling
:meth:`get`. Also, the extracted array can be re-converted into another
IPCArrayHandle.
"""
def __init__(self, array):
"""Creates an IPC memory handle of the device array.
Args:
array (~pycuda.gpuarray.GPUArray): GPU array to be shared
accross processes.
"""
if isinstance(array, drv.IPCMemoryHandle):
# do not doubly extract IPC memory handle
self.handle = array.ipc_handle
else:
self.handle = drv.mem_get_ipc_handle(array.ptr)
self.shape = array.shape
self.dtype = array.dtype
self.size = array.size
self.mem_size = array.mem_size
def get(self):
"""Creates a GPUArray object from the IPC memory handle.
Returns:
~pycuda.gpuarray.GPUArray: Recovered GPU array with memory shared
accross processes.
.. note::
Note that :mod:`cuda` does not take care of data race between
multiple processes.
"""
drv.IPCMemoryHandle(self.handle)
array = gpuarray.GPUArray((0,), dtype=self.dtype)
array.shape = self.shape
array.size = self.size
array.mem_size = self.mem_size
setattr(array, 'ipc_handle', self.handle)
return array
# ------------------------------------------------------------------------------
# Kernel definition utility
# ------------------------------------------------------------------------------
if available:
@cutools.context_dependent_memoize
def _eltwise_kernel(arguments, operation, name, keep, options,
preamble, loop_prep, after_loop):
return pycuda.elementwise.ElementwiseKernel(
arguments, operation, name, keep, options,
preamble=preamble, loop_prep=loop_prep, after_loop=after_loop)
def elementwise(arguments, operation, name, keep=False, options=None,
preamble='', loop_prep='', after_loop=''):
"""Creates an elementwise kernel function.
This function uses :func:`pycuda.tools.context_dependent_memoize` to cache
the resulting kernel object, i.e. the resulting kernel object is cached for
each arguments and CUDA context.
The arguments are the same as those for
:func:`pycuda.elementwise.ElementwiseKernel`, except that ``name`` argument
is mandatory.
"""
return _eltwise_kernel(arguments, operation, name, keep, options,
preamble, loop_prep, after_loop)
if available:
@cutools.context_dependent_memoize
def _reduce_kernel(dtype_out, neutral, reduce_expr, map_expr, arguments,
name, keep, options, preamble):
return pycuda.reduction.ReductionKernel(
dtype_out, neutral, reduce_expr, map_expr,
arguments, name, keep, options, preamble)
def reduce(arguments, map_expr, reduce_expr, neutral, name,
dtype_out=numpy.float32, keep=False, options=None, preamble=''):
"""Creates a global reduction kernel function.
This function uses :func:`pycuda.tools.context_dependent_memoize` to cache
the resulting kernel object, i.e. the resulting kernel object is cached for
each argument and CUDA context.
The arguments are the same as those for
:func:`pycuda.reduction.ReductionKernel`, except that their order is
different and ``name`` argument is mandatory.
"""
kern = _reduce_kernel(dtype_out, neutral, reduce_expr, map_expr, arguments,
name, keep, options, preamble)
def call_kern(*args, **kwargs):
kwargs['allocator'] = mem_alloc
return kern(*args, **kwargs)
return call_kern
# ------------------------------------------------------------------------------
# CUBLAS
# ------------------------------------------------------------------------------
def get_cublas_handle():
"""Gets CUBLAS handle for the current device.
Returns:
CUBLAS handle.
"""
global _cublas_handles
device = Context.get_device()
if device in _cublas_handles:
return _cublas_handles[device]
handle = cublas.cublasCreate()
_cublas_handles[device] = handle
return handle
class CumiscUser(object):
"""RAII-style switcher of scikits-cuda's default CUBLAS handle."""
def __init__(self, handle):
"""Initializes the misc user by given handle.
Args:
handle: CUBLAS handle.
"""
self.handle = cumisc._global_cublas_handle
self.tmp_handle = handle
def __enter__(self):
cumisc._global_cublas_handle = self.tmp_handle
def __exit__(self, typ, value, traceback):
cumisc._global_cublas_handle = self.handle
def using_cumisc(handle=None):
"""Temporarily set chainer's CUBLAS handle to scikit-cuda.
The usage is similar to :func:`using_device`.
Args:
handle: CUBLAS handle. If ``None`` is specified, it uses CUBLAS handle
for the current device.
Returns:
CumiscUser: Misc user object.
"""
if handle is None:
handle = get_cublas_handle()
return CumiscUser(handle)
|
|
"""Support for QNAP NAS Sensors."""
from __future__ import annotations
from datetime import timedelta
import logging
from qnapstats import QNAPStats
import voluptuous as vol
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import (
ATTR_NAME,
CONF_HOST,
CONF_MONITORED_CONDITIONS,
CONF_PASSWORD,
CONF_PORT,
CONF_SSL,
CONF_TIMEOUT,
CONF_USERNAME,
CONF_VERIFY_SSL,
DATA_GIBIBYTES,
DATA_RATE_MEBIBYTES_PER_SECOND,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
TEMP_CELSIUS,
)
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
ATTR_DRIVE = "Drive"
ATTR_DRIVE_SIZE = "Drive Size"
ATTR_IP = "IP Address"
ATTR_MAC = "MAC Address"
ATTR_MASK = "Mask"
ATTR_MAX_SPEED = "Max Speed"
ATTR_MEMORY_SIZE = "Memory Size"
ATTR_MODEL = "Model"
ATTR_PACKETS_TX = "Packets (TX)"
ATTR_PACKETS_RX = "Packets (RX)"
ATTR_PACKETS_ERR = "Packets (Err)"
ATTR_SERIAL = "Serial #"
ATTR_TYPE = "Type"
ATTR_UPTIME = "Uptime"
ATTR_VOLUME_SIZE = "Volume Size"
CONF_DRIVES = "drives"
CONF_NICS = "nics"
CONF_VOLUMES = "volumes"
DEFAULT_NAME = "QNAP"
DEFAULT_PORT = 8080
DEFAULT_TIMEOUT = 5
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
NOTIFICATION_ID = "qnap_notification"
NOTIFICATION_TITLE = "QNAP Sensor Setup"
_SYSTEM_MON_COND: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="status",
name="Status",
icon="mdi:checkbox-marked-circle-outline",
),
SensorEntityDescription(
key="system_temp",
name="System Temperature",
native_unit_of_measurement=TEMP_CELSIUS,
device_class=DEVICE_CLASS_TEMPERATURE,
),
)
_CPU_MON_COND: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="cpu_temp",
name="CPU Temperature",
native_unit_of_measurement=TEMP_CELSIUS,
device_class=DEVICE_CLASS_TEMPERATURE,
),
SensorEntityDescription(
key="cpu_usage",
name="CPU Usage",
native_unit_of_measurement=PERCENTAGE,
icon="mdi:chip",
),
)
_MEMORY_MON_COND: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="memory_free",
name="Memory Available",
native_unit_of_measurement=DATA_GIBIBYTES,
icon="mdi:memory",
),
SensorEntityDescription(
key="memory_used",
name="Memory Used",
native_unit_of_measurement=DATA_GIBIBYTES,
icon="mdi:memory",
),
SensorEntityDescription(
key="memory_percent_used",
name="Memory Usage",
native_unit_of_measurement=PERCENTAGE,
icon="mdi:memory",
),
)
_NETWORK_MON_COND: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="network_link_status",
name="Network Link",
icon="mdi:checkbox-marked-circle-outline",
),
SensorEntityDescription(
key="network_tx",
name="Network Up",
native_unit_of_measurement=DATA_RATE_MEBIBYTES_PER_SECOND,
icon="mdi:upload",
),
SensorEntityDescription(
key="network_rx",
name="Network Down",
native_unit_of_measurement=DATA_RATE_MEBIBYTES_PER_SECOND,
icon="mdi:download",
),
)
_DRIVE_MON_COND: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="drive_smart_status",
name="SMART Status",
icon="mdi:checkbox-marked-circle-outline",
),
SensorEntityDescription(
key="drive_temp",
name="Temperature",
native_unit_of_measurement=TEMP_CELSIUS,
device_class=DEVICE_CLASS_TEMPERATURE,
),
)
_VOLUME_MON_COND: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="volume_size_used",
name="Used Space",
native_unit_of_measurement=DATA_GIBIBYTES,
icon="mdi:chart-pie",
),
SensorEntityDescription(
key="volume_size_free",
name="Free Space",
native_unit_of_measurement=DATA_GIBIBYTES,
icon="mdi:chart-pie",
),
SensorEntityDescription(
key="volume_percentage_used",
name="Volume Used",
native_unit_of_measurement=PERCENTAGE,
icon="mdi:chart-pie",
),
)
SENSOR_KEYS: list[str] = [
desc.key
for desc in (
*_SYSTEM_MON_COND,
*_CPU_MON_COND,
*_MEMORY_MON_COND,
*_NETWORK_MON_COND,
*_DRIVE_MON_COND,
*_VOLUME_MON_COND,
)
]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_SSL, default=False): cv.boolean,
vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_MONITORED_CONDITIONS): vol.All(
cv.ensure_list, [vol.In(SENSOR_KEYS)]
),
vol.Optional(CONF_NICS): cv.ensure_list,
vol.Optional(CONF_DRIVES): cv.ensure_list,
vol.Optional(CONF_VOLUMES): cv.ensure_list,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the QNAP NAS sensor."""
api = QNAPStatsAPI(config)
api.update()
# QNAP is not available
if not api.data:
raise PlatformNotReady
monitored_conditions = config[CONF_MONITORED_CONDITIONS]
sensors = []
# Basic sensors
sensors.extend(
[
QNAPSystemSensor(api, description)
for description in _SYSTEM_MON_COND
if description.key in monitored_conditions
]
)
sensors.extend(
[
QNAPCPUSensor(api, description)
for description in _CPU_MON_COND
if description.key in monitored_conditions
]
)
sensors.extend(
[
QNAPMemorySensor(api, description)
for description in _MEMORY_MON_COND
if description.key in monitored_conditions
]
)
# Network sensors
sensors.extend(
[
QNAPNetworkSensor(api, description, nic)
for nic in config.get(CONF_NICS, api.data["system_stats"]["nics"])
for description in _NETWORK_MON_COND
if description.key in monitored_conditions
]
)
# Drive sensors
sensors.extend(
[
QNAPDriveSensor(api, description, drive)
for drive in config.get(CONF_DRIVES, api.data["smart_drive_health"])
for description in _DRIVE_MON_COND
if description.key in monitored_conditions
]
)
# Volume sensors
sensors.extend(
[
QNAPVolumeSensor(api, description, volume)
for volume in config.get(CONF_VOLUMES, api.data["volumes"])
for description in _VOLUME_MON_COND
if description.key in monitored_conditions
]
)
add_entities(sensors)
def round_nicely(number):
"""Round a number based on its size (so it looks nice)."""
if number < 10:
return round(number, 2)
if number < 100:
return round(number, 1)
return round(number)
class QNAPStatsAPI:
"""Class to interface with the API."""
def __init__(self, config):
"""Initialize the API wrapper."""
protocol = "https" if config[CONF_SSL] else "http"
self._api = QNAPStats(
f"{protocol}://{config.get(CONF_HOST)}",
config.get(CONF_PORT),
config.get(CONF_USERNAME),
config.get(CONF_PASSWORD),
verify_ssl=config.get(CONF_VERIFY_SSL),
timeout=config.get(CONF_TIMEOUT),
)
self.data = {}
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Update API information and store locally."""
try:
self.data["system_stats"] = self._api.get_system_stats()
self.data["system_health"] = self._api.get_system_health()
self.data["smart_drive_health"] = self._api.get_smart_disk_health()
self.data["volumes"] = self._api.get_volumes()
self.data["bandwidth"] = self._api.get_bandwidth()
except: # noqa: E722 pylint: disable=bare-except
_LOGGER.exception("Failed to fetch QNAP stats from the NAS")
class QNAPSensor(SensorEntity):
"""Base class for a QNAP sensor."""
def __init__(self, api, description: SensorEntityDescription, monitor_device=None):
"""Initialize the sensor."""
self.entity_description = description
self.monitor_device = monitor_device
self._api = api
@property
def name(self):
"""Return the name of the sensor, if any."""
server_name = self._api.data["system_stats"]["system"]["name"]
if self.monitor_device is not None:
return (
f"{server_name} {self.entity_description.name} ({self.monitor_device})"
)
return f"{server_name} {self.entity_description.name}"
def update(self):
"""Get the latest data for the states."""
self._api.update()
class QNAPCPUSensor(QNAPSensor):
"""A QNAP sensor that monitors CPU stats."""
@property
def native_value(self):
"""Return the state of the sensor."""
if self.entity_description.key == "cpu_temp":
return self._api.data["system_stats"]["cpu"]["temp_c"]
if self.entity_description.key == "cpu_usage":
return self._api.data["system_stats"]["cpu"]["usage_percent"]
class QNAPMemorySensor(QNAPSensor):
"""A QNAP sensor that monitors memory stats."""
@property
def native_value(self):
"""Return the state of the sensor."""
free = float(self._api.data["system_stats"]["memory"]["free"]) / 1024
if self.entity_description.key == "memory_free":
return round_nicely(free)
total = float(self._api.data["system_stats"]["memory"]["total"]) / 1024
used = total - free
if self.entity_description.key == "memory_used":
return round_nicely(used)
if self.entity_description.key == "memory_percent_used":
return round(used / total * 100)
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if self._api.data:
data = self._api.data["system_stats"]["memory"]
size = round_nicely(float(data["total"]) / 1024)
return {ATTR_MEMORY_SIZE: f"{size} {DATA_GIBIBYTES}"}
class QNAPNetworkSensor(QNAPSensor):
"""A QNAP sensor that monitors network stats."""
@property
def native_value(self):
"""Return the state of the sensor."""
if self.entity_description.key == "network_link_status":
nic = self._api.data["system_stats"]["nics"][self.monitor_device]
return nic["link_status"]
data = self._api.data["bandwidth"][self.monitor_device]
if self.entity_description.key == "network_tx":
return round_nicely(data["tx"] / 1024 / 1024)
if self.entity_description.key == "network_rx":
return round_nicely(data["rx"] / 1024 / 1024)
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if self._api.data:
data = self._api.data["system_stats"]["nics"][self.monitor_device]
return {
ATTR_IP: data["ip"],
ATTR_MASK: data["mask"],
ATTR_MAC: data["mac"],
ATTR_MAX_SPEED: data["max_speed"],
ATTR_PACKETS_TX: data["tx_packets"],
ATTR_PACKETS_RX: data["rx_packets"],
ATTR_PACKETS_ERR: data["err_packets"],
}
class QNAPSystemSensor(QNAPSensor):
"""A QNAP sensor that monitors overall system health."""
@property
def native_value(self):
"""Return the state of the sensor."""
if self.entity_description.key == "status":
return self._api.data["system_health"]
if self.entity_description.key == "system_temp":
return int(self._api.data["system_stats"]["system"]["temp_c"])
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if self._api.data:
data = self._api.data["system_stats"]
days = int(data["uptime"]["days"])
hours = int(data["uptime"]["hours"])
minutes = int(data["uptime"]["minutes"])
return {
ATTR_NAME: data["system"]["name"],
ATTR_MODEL: data["system"]["model"],
ATTR_SERIAL: data["system"]["serial_number"],
ATTR_UPTIME: f"{days:0>2d}d {hours:0>2d}h {minutes:0>2d}m",
}
class QNAPDriveSensor(QNAPSensor):
"""A QNAP sensor that monitors HDD/SSD drive stats."""
@property
def native_value(self):
"""Return the state of the sensor."""
data = self._api.data["smart_drive_health"][self.monitor_device]
if self.entity_description.key == "drive_smart_status":
return data["health"]
if self.entity_description.key == "drive_temp":
return int(data["temp_c"]) if data["temp_c"] is not None else 0
@property
def name(self):
"""Return the name of the sensor, if any."""
server_name = self._api.data["system_stats"]["system"]["name"]
return f"{server_name} {self.entity_description.name} (Drive {self.monitor_device})"
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if self._api.data:
data = self._api.data["smart_drive_health"][self.monitor_device]
return {
ATTR_DRIVE: data["drive_number"],
ATTR_MODEL: data["model"],
ATTR_SERIAL: data["serial"],
ATTR_TYPE: data["type"],
}
class QNAPVolumeSensor(QNAPSensor):
"""A QNAP sensor that monitors storage volume stats."""
@property
def native_value(self):
"""Return the state of the sensor."""
data = self._api.data["volumes"][self.monitor_device]
free_gb = int(data["free_size"]) / 1024 / 1024 / 1024
if self.entity_description.key == "volume_size_free":
return round_nicely(free_gb)
total_gb = int(data["total_size"]) / 1024 / 1024 / 1024
used_gb = total_gb - free_gb
if self.entity_description.key == "volume_size_used":
return round_nicely(used_gb)
if self.entity_description.key == "volume_percentage_used":
return round(used_gb / total_gb * 100)
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if self._api.data:
data = self._api.data["volumes"][self.monitor_device]
total_gb = int(data["total_size"]) / 1024 / 1024 / 1024
return {ATTR_VOLUME_SIZE: f"{round_nicely(total_gb)} {DATA_GIBIBYTES}"}
|
|
"""
Support for interfacing to the Logitech SqueezeBox API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.squeezebox/
"""
import logging
import asyncio
import urllib.parse
import json
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components.media_player import (
ATTR_MEDIA_ENQUEUE, SUPPORT_PLAY_MEDIA,
MEDIA_TYPE_MUSIC, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, PLATFORM_SCHEMA,
SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, SUPPORT_TURN_OFF, SUPPORT_TURN_ON,
SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_PLAY, MediaPlayerDevice)
from homeassistant.const import (
CONF_HOST, CONF_PASSWORD, CONF_USERNAME, STATE_IDLE, STATE_OFF,
STATE_PAUSED, STATE_PLAYING, STATE_UNKNOWN, CONF_PORT)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
_LOGGER = logging.getLogger(__name__)
DEFAULT_PORT = 9000
TIMEOUT = 10
KNOWN_DEVICES = []
SUPPORT_SQUEEZEBOX = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | \
SUPPORT_VOLUME_MUTE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | \
SUPPORT_SEEK | SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_PLAY_MEDIA | \
SUPPORT_PLAY
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_PASSWORD): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_USERNAME): cv.string,
})
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup the squeezebox platform."""
import socket
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
if discovery_info is not None:
host = discovery_info[0]
port = None # Port is not collected in netdisco 0.8.1
else:
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
# In case the port is not discovered
if port is None:
port = DEFAULT_PORT
# Get IP of host, to prevent duplication of same host (different DNS names)
try:
ipaddr = socket.gethostbyname(host)
except (OSError) as error:
_LOGGER.error("Could not communicate with %s:%d: %s",
host, port, error)
return False
# Combine it with port to allow multiple servers at the same host
key = "{}:{}".format(ipaddr, port)
# Only add a media server once
if key in KNOWN_DEVICES:
return False
KNOWN_DEVICES.append(key)
_LOGGER.debug("Creating LMS object for %s", ipaddr)
lms = LogitechMediaServer(hass, host, port, username, password)
if lms is False:
return False
players = yield from lms.create_players()
yield from async_add_devices(players)
return True
class LogitechMediaServer(object):
"""Representation of a Logitech media server."""
def __init__(self, hass, host, port, username, password):
"""Initialize the Logitech device."""
self.hass = hass
self.host = host
self.port = port
self._username = username
self._password = password
@asyncio.coroutine
def create_players(self):
"""Create a list of devices connected to LMS."""
result = []
data = yield from self.async_query('players', 'status')
for players in data['players_loop']:
player = SqueezeBoxDevice(
self, players['playerid'], players['name'])
yield from player.async_update()
result.append(player)
return result
@asyncio.coroutine
def async_query(self, *command, player=""):
"""Abstract out the JSON-RPC connection."""
response = None
auth = None if self._username is None else aiohttp.BasicAuth(
self._username, self._password)
url = "http://{}:{}/jsonrpc.js".format(
self.host, self.port)
data = json.dumps({
"id": "1",
"method": "slim.request",
"params": [player, command]
})
_LOGGER.debug("URL: %s Data: %s", url, data)
try:
websession = async_get_clientsession(self.hass)
with async_timeout.timeout(TIMEOUT, loop=self.hass.loop):
response = yield from websession.post(
url,
data=data,
auth=auth)
if response.status == 200:
data = yield from response.json()
else:
_LOGGER.error(
"Query failed, response code: %s Full message: %s",
response.status, response)
return False
except (asyncio.TimeoutError,
aiohttp.errors.ClientError,
aiohttp.errors.ClientDisconnectedError) as error:
_LOGGER.error("Failed communicating with LMS: %s", type(error))
return False
finally:
if response is not None:
yield from response.release()
try:
return data['result']
except AttributeError:
_LOGGER.error("Received invalid response: %s", data)
return False
class SqueezeBoxDevice(MediaPlayerDevice):
"""Representation of a SqueezeBox device."""
def __init__(self, lms, player_id, name):
"""Initialize the SqueezeBox device."""
super(SqueezeBoxDevice, self).__init__()
self._lms = lms
self._id = player_id
self._status = {}
self._name = name
_LOGGER.debug("Creating SqueezeBox object: %s, %s", name, player_id)
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def state(self):
"""Return the state of the device."""
if 'power' in self._status and self._status['power'] == '0':
return STATE_OFF
if 'mode' in self._status:
if self._status['mode'] == 'pause':
return STATE_PAUSED
if self._status['mode'] == 'play':
return STATE_PLAYING
if self._status['mode'] == 'stop':
return STATE_IDLE
return STATE_UNKNOWN
def async_query(self, *parameters):
"""Send a command to the LMS.
This method must be run in the event loop and returns a coroutine.
"""
return self._lms.async_query(
*parameters, player=self._id)
def query(self, *parameters):
"""Queue up a command to send the LMS."""
self.hass.loop.create_task(self.async_query(*parameters))
@asyncio.coroutine
def async_update(self):
"""Retrieve the current state of the player."""
tags = 'adKl'
response = yield from self.async_query(
"status", "-", "1", "tags:{tags}"
.format(tags=tags))
try:
self._status = response.copy()
self._status.update(response["remoteMeta"])
except KeyError:
pass
@property
def volume_level(self):
"""Volume level of the media player (0..1)."""
if 'mixer volume' in self._status:
return int(float(self._status['mixer volume'])) / 100.0
@property
def is_volume_muted(self):
"""Return true if volume is muted."""
if 'mixer volume' in self._status:
return str(self._status['mixer volume']).startswith('-')
@property
def media_content_id(self):
"""Content ID of current playing media."""
if 'current_title' in self._status:
return self._status['current_title']
@property
def media_content_type(self):
"""Content type of current playing media."""
return MEDIA_TYPE_MUSIC
@property
def media_duration(self):
"""Duration of current playing media in seconds."""
if 'duration' in self._status:
return int(float(self._status['duration']))
@property
def media_image_url(self):
"""Image url of current playing media."""
if 'artwork_url' in self._status:
media_url = self._status['artwork_url']
elif 'id' in self._status:
media_url = ('/music/{track_id}/cover.jpg').format(
track_id=self._status['id'])
else:
media_url = ('/music/current/cover.jpg?player={player}').format(
player=self._id)
# pylint: disable=protected-access
if self._lms._username:
base_url = 'http://{username}:{password}@{server}:{port}/'.format(
username=self._lms._username,
password=self._lms._password,
server=self._lms.host,
port=self._lms.port)
else:
base_url = 'http://{server}:{port}/'.format(
server=self._lms.host,
port=self._lms.port)
url = urllib.parse.urljoin(base_url, media_url)
return url
@property
def media_title(self):
"""Title of current playing media."""
if 'title' in self._status:
return self._status['title']
if 'current_title' in self._status:
return self._status['current_title']
@property
def media_artist(self):
"""Artist of current playing media."""
if 'artist' in self._status:
return self._status['artist']
@property
def media_album_name(self):
"""Album of current playing media."""
if 'album' in self._status:
return self._status['album']
@property
def supported_media_commands(self):
"""Flag of media commands that are supported."""
return SUPPORT_SQUEEZEBOX
def turn_off(self):
"""Turn off media player."""
self.query('power', '0')
self.update_ha_state()
def volume_up(self):
"""Volume up media player."""
self.query('mixer', 'volume', '+5')
self.update_ha_state()
def volume_down(self):
"""Volume down media player."""
self.query('mixer', 'volume', '-5')
self.update_ha_state()
def set_volume_level(self, volume):
"""Set volume level, range 0..1."""
volume_percent = str(int(volume*100))
self.query('mixer', 'volume', volume_percent)
self.update_ha_state()
def mute_volume(self, mute):
"""Mute (true) or unmute (false) media player."""
mute_numeric = '1' if mute else '0'
self.query('mixer', 'muting', mute_numeric)
self.update_ha_state()
def media_play_pause(self):
"""Send pause command to media player."""
self.query('pause')
self.update_ha_state()
def media_play(self):
"""Send play command to media player."""
self.query('play')
self.update_ha_state()
def media_pause(self):
"""Send pause command to media player."""
self.query('pause', '1')
self.update_ha_state()
def media_next_track(self):
"""Send next track command."""
self.query('playlist', 'index', '+1')
self.update_ha_state()
def media_previous_track(self):
"""Send next track command."""
self.query('playlist', 'index', '-1')
self.update_ha_state()
def media_seek(self, position):
"""Send seek command."""
self.query('time', position)
self.update_ha_state()
def turn_on(self):
"""Turn the media player on."""
self.query('power', '1')
self.update_ha_state()
def play_media(self, media_type, media_id, **kwargs):
"""
Send the play_media command to the media player.
If ATTR_MEDIA_ENQUEUE is True, add `media_id` to the current playlist.
"""
if kwargs.get(ATTR_MEDIA_ENQUEUE):
self._add_uri_to_playlist(media_id)
else:
self._play_uri(media_id)
def _play_uri(self, media_id):
"""Replace the current play list with the uri."""
self.query('playlist', 'play', media_id)
self.update_ha_state()
def _add_uri_to_playlist(self, media_id):
"""Add a items to the existing playlist."""
self.query('playlist', 'add', media_id)
self.update_ha_state()
|
|
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
# ==========================================================================
# Copyright (C) 2016 Dr. Alejandro Pina Ortega
#
# 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.
# ==========================================================================
"""
Class for slots of type 0
"""
# ==========================================================================
# Program: type0.py
# Author: ajpina
# Date: 12/23/16
# Version: 0.1.1
#
# Revision History:
# Date Version Author Description
# - 12/23/16: 0.1.1 ajpina Defines mandatory methods and properties
#
# ==========================================================================
__author__ = 'ajpina'
import numpy as np
from uffema.slots import Slot
from uffema.misc.constants import *
class Type0(Slot):
@property
def h0(self):
return self._h0
@h0.setter
def h0(self, value):
self._h0 = value
@property
def h1(self):
return self._h1
@h1.setter
def h1(self, value):
self._h1 = value
@property
def h2(self):
return self._h2
@h2.setter
def h2(self, value):
self._h2 = value
@property
def h3(self):
return self._h3
@h3.setter
def h3(self, value):
self._h3 = value
@property
def w0(self):
return self._w0
@w0.setter
def w0(self, value):
self._w0 = value
@property
def w1(self):
return self._w1
@w1.setter
def w1(self, value):
self._w1 = value
@property
def w2(self):
return self._w2
@w2.setter
def w2(self, value):
self._w2 = value
@property
def so_position(self):
return self._so_position
@so_position.setter
def so_position(self, value):
self._so_position = value
@property
def s_position(self):
return self._s_position
@s_position.setter
def s_position(self, value):
self._s_position = value
@property
def liner_thickness(self):
return self._liner_thickness
@liner_thickness.setter
def liner_thickness(self, value):
self._liner_thickness = value
@property
def orientation(self):
return self._orientation
@orientation.setter
def orientation(self, value):
self._orientation = value
@property
def type(self):
return self._type
@type.setter
def type(self, value):
self._type = value
def __init__(self, slot_settings, stator_mode):
super(Type0, self).__init__(slot_settings)
self.h0 = slot_settings['h0']
self.h1 = slot_settings['h1']
self.h2 = slot_settings['h2']
self.h3 = slot_settings['h3']
self.w0 = slot_settings['w0']
self.w1 = slot_settings['w1']
self.w2 = slot_settings['w2']
self.so_position = slot_settings['SOpos']
self.s_position = slot_settings['Spos']
# It is assumed an insulation liner of 0.5mm thickness
self.liner_thickness = 0.5e-3
self.type = self.type + 'Type0'
self.orientation = stator_mode
def get_slot_center(self):
return self.h0 + self.h1 + (2.0/3.0)*self.h2
def get_type(self):
return 'Type0'
def get_area(self):
return 0
def get_slot_total_height(self):
return self.h0 + self.h1 + self.h2 + self.h3
def get_conductor_area_width(self):
return (self.w1 + self.w2) / 2.0
def get_conductor_area_height(self):
return self.h2
def get_coil_area_base_point(self, radius):
if self.orientation == 'outer':
return radius + self.h0 + self.h1
else:
return radius - self.h0 - self.h1 - self.h2
def get_slot_opening_geometry(self, radius):
delta_5 = np.arctan2(-self.w0 / 2.0, radius)
r_5 = radius
if self.orientation == 'outer':
points = {
'2': [radius, 0, 0],
'3': [radius + self.h0, 0, 0],
'4': [radius + self.h0, -self.w0/2.0, 0],
'5': [r_5*np.cos(delta_5), r_5*np.sin(delta_5) , 0]
}
lines = {
'1': [2, 3],
'2': [3, 4],
'3': [4, 5],
'4': [5, 2]
}
else:
points = {
'2': [radius, 0, 0],
'3': [radius - self.h0, 0, 0],
'4': [radius - self.h0, -self.w0 / 2.0, 0],
'5': [r_5 * np.cos(delta_5), r_5 * np.sin(delta_5), 0]
}
lines = {
'1': [2, 3],
'2': [3, 4],
'3': [4, 5],
'4': [5, 2]
}
return points, lines
def get_slot_wedge_geometry(self, radius):
if self.orientation == 'outer':
points = {
'6': [radius + self.h0 + self.h1, 0, 0],
'7': [radius + self.h0 + self.h1, -self.w1/2, 0]
}
lines = {
'5': [3, 6],
'6': [6, 7],
'7': [7, 4],
'-2': [0]
}
else:
points = {
'6': [radius - self.h0 - self.h1, 0, 0],
'7': [radius - self.h0 - self.h1, -self.w1 / 2, 0]
}
lines = {
'5': [3, 6],
'6': [6, 7],
'7': [7, 4],
'-2': [0]
}
return points, lines
def get_coil_area_geometry(self, radius):
if self.orientation == 'outer':
points = {
'8': [radius + self.h0 + self.h1 + self.h2 + self.h3, 0, 0],
'9': [radius + self.h0 + self.h1 + self.h2, -self.w2 / 2, 0]
}
lines = {
'8': [6, 8],
'-9': [0],
'-10': [0],
'-6': [0]
}
else:
points = {
'8': [radius - self.h0 - self.h1 - self.h2 - self.h3, 0, 0],
'9': [radius - self.h0 - self.h1 - self.h2, -self.w2 / 2, 0]
}
lines = {
'8': [6, 8],
'-9': [0],
'-10': [0],
'-6': [0]
}
return points, lines
def get_backiron_geometry(self, inner_radius, outer_radius, slot_number):
slot_pitch = 360 * DEG2RAD / slot_number
if self.orientation == 'outer':
points = {
'8': [inner_radius + self.h0 + self.h1 + self.h2 + self.h3, 0, 0],
'9': [inner_radius + self.h0 + self.h1 + self.h2, -self.w2 / 2, 0],
'10': [outer_radius, 0, 0],
'11': [outer_radius * np.cos( -slot_pitch/2.0 ), outer_radius * np.sin( -slot_pitch/2.0 ), 0],
'12': [(inner_radius + self.h0 + self.h1 + self.h2) * np.cos( -slot_pitch/2.0 ),
(inner_radius + self.h0 + self.h1 + self.h2) * np.sin( -slot_pitch/2.0 ) , 0]
}
lines = {
'9': [9, 8],
'11': [8, 10],
'12': [10, 1, 11],
'13': [11, 12],
'14': [12, 9]
}
else:
points = {
'8': [outer_radius - self.h0 - self.h1 - self.h2 - self.h3, 0, 0],
'9': [outer_radius - self.h0 - self.h1 - self.h2, -self.w2 / 2, 0],
'10': [inner_radius, 0, 0],
'11': [inner_radius * np.cos(-slot_pitch / 2.0), inner_radius * np.sin(-slot_pitch / 2.0), 0],
'12': [(outer_radius - self.h0 - self.h1 - self.h2) * np.cos(-slot_pitch / 2.0),
(outer_radius - self.h0 - self.h1 - self.h2) * np.sin(-slot_pitch / 2.0), 0]
}
lines = {
'9': [9, 8],
'11': [8, 10],
'12': [10, 1, 11],
'13': [11, 12],
'14': [12, 9]
}
return points, lines
def get_tooth_geometry(self, radius, slot_number):
slot_pitch = 360 * DEG2RAD / slot_number
if self.orientation == 'outer':
points = {
'13': [(radius + self.h0 + self.h1) * np.cos( -slot_pitch/2.0 ),
(radius + self.h0 + self.h1) * np.sin( -slot_pitch/2.0 ) , 0]
}
lines = {
'15': [12, 13],
'16': [13, 7],
'10': [7, 9],
'-14': [0]
}
else:
points = {
'13': [(radius - self.h0 - self.h1) * np.cos(-slot_pitch / 2.0),
(radius - self.h0 - self.h1) * np.sin(-slot_pitch / 2.0), 0]
}
lines = {
'15': [12, 13],
'16': [13, 7],
'10': [7, 9],
'-14': [0]
}
return points, lines
def get_toothtip_geometry(self, radius, slot_number):
slot_pitch = 360 * DEG2RAD / slot_number
if self.orientation == 'outer':
points = {
'14': [radius * np.cos( -slot_pitch/2.0 ), radius * np.sin( -slot_pitch/2.0 ) , 0]
}
lines = {
'17': [13, 14],
'18': [14, 1, 5],
'-3': [0],
'-7': [0],
'-16': [0]
}
else:
points = {
'14': [radius * np.cos(-slot_pitch / 2.0), radius * np.sin(-slot_pitch / 2.0), 0]
}
lines = {
'17': [13, 14],
'18': [14, 1, 5],
'-3': [0],
'-7': [0],
'-16': [0]
}
return points, lines
def get_stator_airgap_geometry(self, airgap_radius, slot_number):
slot_pitch = 360 * DEG2RAD / slot_number
if self.orientation == 'outer':
points = {
'15': [airgap_radius * np.cos( -slot_pitch/2.0 ), airgap_radius * np.sin( -slot_pitch/2.0 ) , 0],
'16': [airgap_radius, 0, 0]
}
lines = {
'19': [14, 15],
'20': [15, 1, 16],
'21': [16, 2],
'-4': [0],
'-18': [0]
}
else:
points = {
'15': [airgap_radius * np.cos(-slot_pitch / 2.0), airgap_radius * np.sin(-slot_pitch / 2.0), 0],
'16': [airgap_radius, 0, 0]
}
lines = {
'19': [14, 15],
'20': [15, 1, 16],
'21': [16, 2],
'-4': [0],
'-18': [0]
}
return points, lines
def get_stator_airgap_boundary(self):
return {'20': [15, 1, 16]}
def get_outer_stator_boundary(self):
return [12]
def get_master_boundary(self):
return [13, 15, 17, 19]
|
|
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from gpu_tests.webgl_conformance_expectations import WebGLConformanceExpectations
# See the GpuTestExpectations class for documentation.
class WebGL2ConformanceExpectations(WebGLConformanceExpectations):
def __init__(self, conformance_path):
super(WebGL2ConformanceExpectations, self).__init__(conformance_path)
def SetExpectations(self):
# All platforms.
self.Skip('deqp/data/gles3/shaders/functions.html', bug=483282)
self.Skip('deqp/data/gles3/shaders/linkage.html', bug=483282)
self.Skip('deqp/data/gles3/shaders/preprocessor.html', bug=483282)
self.Skip('deqp/framework/opengl/simplereference/referencecontext.html',
bug=483282)
self.Skip('deqp/functional/gles3/attriblocation.html', bug=483282)
self.Skip('deqp/functional/gles3/builtinprecision*.html', bug=483282)
self.Skip('deqp/functional/gles3/draw.html', bug=483282)
self.Skip('deqp/functional/gles3/fbocolorbuffer.html', bug=483282)
self.Skip('deqp/functional/gles3/fbocompleteness.html', bug=483282)
self.Skip('deqp/functional/gles3/fbodepthbuffer.html', bug=483282)
self.Skip('deqp/functional/gles3/fboinvalidate.html', bug=483282)
self.Skip('deqp/functional/gles3/fbomultisample.html', bug=483282)
self.Skip('deqp/functional/gles3/fborender.html', bug=483282)
self.Skip('deqp/functional/gles3/fragmentoutput.html', bug=483282)
self.Skip('deqp/functional/gles3/framebufferblit.html', bug=483282)
self.Skip('deqp/functional/gles3/instancedrendering.html', bug=483282)
self.Skip('deqp/functional/gles3/integerstatequery.html', bug=483282)
self.Skip('deqp/functional/gles3/internalformatquery.html', bug=483282)
self.Skip('deqp/functional/gles3/lifetime.html', bug=483282)
self.Skip('deqp/functional/gles3/multisample.html', bug=483282)
self.Skip('deqp/functional/gles3/negativebufferapi.html', bug=483282)
self.Skip('deqp/functional/gles3/negativefragmentapi.html', bug=483282)
self.Skip('deqp/functional/gles3/negativetextureapi.html', bug=483282)
self.Skip('deqp/functional/gles3/negativevertexarrayapi.html', bug=483282)
self.Skip('deqp/functional/gles3/occlusionquery.html', bug=483282)
self.Skip('deqp/functional/gles3/pixelbufferobject.html', bug=483282)
self.Skip('deqp/functional/gles3/primitiverestart.html', bug=483282)
self.Skip('deqp/functional/gles3/rasterizerdiscard.html', bug=483282)
self.Skip('deqp/functional/gles3/shaderbuiltinvar.html', bug=483282)
self.Skip('deqp/functional/gles3/shadercommonfunction.html', bug=483282)
self.Skip('deqp/functional/gles3/shaderderivate.html', bug=483282)
self.Skip('deqp/functional/gles3/shaderindexing.html', bug=483282)
self.Skip('deqp/functional/gles3/shaderloop.html', bug=483282)
self.Skip('deqp/functional/gles3/shadermatrix.html', bug=483282)
self.Skip('deqp/functional/gles3/shaderoperator.html', bug=483282)
self.Skip('deqp/functional/gles3/shaderpackingfunction.html', bug=483282)
self.Skip('deqp/functional/gles3/shaderprecision.html', bug=483282)
self.Skip('deqp/functional/gles3/shaderstatequery.html', bug=483282)
self.Skip('deqp/functional/gles3/shadertexturefunction*.html', bug=483282)
self.Skip('deqp/functional/gles3/sync.html', bug=483282)
self.Skip('deqp/functional/gles3/texturefiltering*.html', bug=483282)
self.Skip('deqp/functional/gles3/textureformat.html', bug=483282)
self.Skip('deqp/functional/gles3/textureshadow.html', bug=483282)
self.Skip('deqp/functional/gles3/texturespecification*.html', bug=483282)
self.Skip('deqp/functional/gles3/texturewrap.html', bug=483282)
self.Skip('deqp/functional/gles3/transformfeedback.html', bug=483282)
self.Skip('deqp/functional/gles3/uniformapi.html', bug=483282)
self.Skip('deqp/functional/gles3/uniformbuffers.html', bug=483282)
self.Skip('deqp/functional/gles3/vertexarrays.html', bug=483282)
self.Fail('conformance2/glsl3/array-complex-indexing.html', bug=483282)
self.Fail('conformance2/glsl3/forbidden-operators.html', bug=483282)
# Note that this test fails on ['win', 'intel'] with bug=483282
self.Fail('conformance2/buffers/uniform-buffers.html', bug=577368)
self.Fail('conformance2/misc/expando-loss-2.html', bug=483282)
# Windows only.
self.Fail('conformance2/textures/canvas/tex-image-and-sub-image-2d' +
'-with-canvas-r8-red-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/canvas/tex-image-and-sub-image-2d' +
'-with-canvas-rg8-rg-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/canvas/tex-image-and-sub-image-2d' +
'-with-canvas-rgb8-rgb-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/canvas/tex-image-and-sub-image-2d' +
'-with-canvas-rgb565-rgb-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/canvas/tex-image-and-sub-image-2d' +
'-with-canvas-rgb565-rgb-unsigned_short_5_6_5.html',
['win'], bug=483282)
self.Fail('conformance2/textures/canvas/tex-image-and-sub-image-2d' +
'-with-canvas-rgb5_a1-rgba-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/canvas/tex-image-and-sub-image-2d' +
'-with-canvas-rgb5_a1-rgba-unsigned_short_5_5_5_1.html',
['win'], bug=483282)
self.Fail('conformance2/textures/canvas/tex-image-and-sub-image-2d' +
'-with-canvas-rgba4-rgba-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/canvas/tex-image-and-sub-image-2d' +
'-with-canvas-rgba4-rgba-unsigned_short_4_4_4_4.html',
['win'], bug=483282)
self.Fail('conformance2/textures/webgl_canvas/tex-image-and-sub-image-2d' +
'-with-webgl-canvas-r8-red-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/webgl_canvas/tex-image-and-sub-image-2d' +
'-with-webgl-canvas-rg8-rg-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/webgl_canvas/tex-image-and-sub-image-2d' +
'-with-webgl-canvas-rgb8-rgb-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/webgl_canvas/tex-image-and-sub-image-2d' +
'-with-webgl-canvas-rgb565-rgb-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/webgl_canvas/tex-image-and-sub-image-2d' +
'-with-webgl-canvas-rgb565-rgb-unsigned_short_5_6_5.html',
['win'], bug=483282)
self.Fail('conformance2/textures/webgl_canvas/tex-image-and-sub-image-2d' +
'-with-webgl-canvas-rgb5_a1-rgba-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/webgl_canvas/tex-image-and-sub-image-2d' +
'-with-webgl-canvas-rgb5_a1-rgba-unsigned_short_5_5_5_1.html',
['win'], bug=483282)
self.Fail('conformance2/textures/webgl_canvas/tex-image-and-sub-image-2d' +
'-with-webgl-canvas-rgba4-rgba-unsigned_byte.html',
['win'], bug=483282)
self.Fail('conformance2/textures/webgl_canvas/tex-image-and-sub-image-2d' +
'-with-webgl-canvas-rgba4-rgba-unsigned_short_4_4_4_4.html',
['win'], bug=483282)
self.Flaky('deqp/functional/gles3/buffercopy.html', ['win'], bug=587601)
self.Skip('deqp/functional/gles3/readpixel.html', ['win'], bug=483282)
self.Skip('deqp/functional/gles3/texturestatequery.html',
['win'], bug=483282)
self.Fail('deqp/functional/gles3/shaderstruct.html',
['win'], bug=483282)
self.Fail('conformance2/glsl3/array-in-complex-expression.html',
['win'], bug=483282)
self.Fail('conformance2/reading/read-pixels-from-fbo-test.html',
['win'], bug=483282)
self.Skip('conformance2/reading/read-pixels-pack-parameters.html',
['win'], bug=483282)
self.Fail('conformance2/textures/misc/gl-get-tex-parameter.html',
['win'], bug=483282)
self.Fail('conformance2/textures/misc/tex-input-validation.html',
['win'], bug=483282)
self.Skip('conformance2/textures/misc/tex-mipmap-levels.html',
['win'], bug=483282)
self.Skip('conformance2/transform_feedback/transform_feedback.html',
['win'], bug=483282)
self.Fail('conformance2/glsl3/const-array-init.html',
['win'], bug=1198) # angle bug ID
self.Skip('conformance2/reading/read-pixels-into-pixel-pack-buffer.html',
['win'], bug=1266) # angle bug ID
self.Skip('conformance2/textures/misc/copy-texture-image.html',
['win'], bug=577144) # crash on debug
self.Fail('conformance2/state/gl-object-get-calls.html',
['win'], bug=483282)
# Windows 8 only.
self.Fail('conformance2/textures/image_data/tex-image-and-sub-image-2d' +
'-with-image-data-rgb565-rgb-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_data/tex-image-and-sub-image-2d' +
'-with-image-data-rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image/tex-image-and-sub-image-2d' +
'-with-image-rgb565-rgb-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image/tex-image-and-sub-image-2d' +
'-with-image-rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/svg_image/tex-image-and-sub-image-2d' +
'-with-svg-image-rgb565-rgb-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/svg_image/tex-image-and-sub-image-2d' +
'-with-svg-image-rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/video/tex-image-and-sub-image-2d' +
'-with-video-rgb565-rgb-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/video/tex-image-and-sub-image-2d' +
'-with-video-rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_image_data/' +
'tex-image-and-sub-image-2d-with-image-bitmap-from-image-data-' +
'rgb565-rgb-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_image_data/' +
'tex-image-and-sub-image-2d-with-image-bitmap-from-image-data-' +
'rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_image/' +
'tex-image-and-sub-image-2d-with-image-bitmap-from-image-' +
'rgb565-rgb-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_image/' +
'tex-image-and-sub-image-2d-with-image-bitmap-from-image-' +
'rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_video/' +
'tex-image-and-sub-image-2d-with-image-bitmap-from-video-' +
'rgb565-rgb-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_video/' +
'tex-image-and-sub-image-2d-with-image-bitmap-from-video-' +
'rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/video/tex-image-and-sub-image-3d' +
'-with-video-rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=560555)
self.Fail('conformance2/textures/video/tex-image-and-sub-image-3d' +
'-with-video-rgb565-rgb-unsigned_byte.html',
['win8'], bug=560555)
self.Fail('conformance2/textures/image_data/tex-image-and-sub-image-3d' +
'-with-image-data-rgb565-rgb-unsigned_byte.html',
['win8'], bug=560555)
self.Fail('conformance2/textures/image_data/tex-image-and-sub-image-3d' +
'-with-image-data-rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=560555)
self.Fail('conformance2/textures/image/tex-image-and-sub-image-3d' +
'-with-image-rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=560555)
self.Fail('conformance2/textures/image/tex-image-and-sub-image-3d' +
'-with-image-rgb565-rgb-unsigned_byte.html',
['win8'], bug=560555)
self.Fail('conformance2/textures/svg_image/tex-image-and-sub-image-3d' +
'-with-svg-image-rgb565-rgb-unsigned_byte.html',
['win8'], bug=560555)
self.Fail('conformance2/textures/svg_image/tex-image-and-sub-image-3d' +
'-with-svg-image-rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=560555)
self.Fail('conformance2/textures/image_bitmap_from_image_data/' +
'tex-image-and-sub-image-3d-with-image-bitmap-from-image-data-' +
'rgb565-rgb-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_image_data/' +
'tex-image-and-sub-image-3d-with-image-bitmap-from-image-data-' +
'rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_image/' +
'tex-image-and-sub-image-3d-with-image-bitmap-from-image-' +
'rgb565-rgb-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_image/' +
'tex-image-and-sub-image-3d-with-image-bitmap-from-image-' +
'rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_video/' +
'tex-image-and-sub-image-3d-with-image-bitmap-from-video-' +
'rgb565-rgb-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_video/' +
'tex-image-and-sub-image-3d-with-image-bitmap-from-video-' +
'rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=483282)
self.Fail('conformance2/textures/canvas/tex-image-and-sub-image-3d' +
'-with-canvas-rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=560555)
self.Fail('conformance2/textures/canvas/tex-image-and-sub-image-3d' +
'-with-canvas-rgb565-rgb-unsigned_byte.html',
['win8'], bug=560555)
self.Fail('conformance2/textures/webgl_canvas/tex-image-and-sub-image-3d' +
'-with-webgl-canvas-rgb5_a1-rgba-unsigned_byte.html',
['win8'], bug=560555)
self.Fail('conformance2/textures/webgl_canvas/tex-image-and-sub-image-3d' +
'-with-webgl-canvas-rgb565-rgb-unsigned_byte.html',
['win8'], bug=560555)
# Windows Debug. Causing assertions in the GPU process which raise
# a dialog box, so have to skip them rather than mark them as
# failing.
self.Skip('conformance2/textures/canvas/tex-image-and-sub-image-2d' +
'-with-canvas-rgba8-rgba-unsigned_byte.html',
['win', 'debug'], bug=542901)
# Win / AMD.
self.Flaky('deqp/functional/gles3/clipping.html',
['win', 'amd'], bug=491419)
self.Flaky('deqp/functional/gles3/samplerobject.html',
['win', 'amd'], bug=491419)
# Mac only.
self.Skip('deqp/data/gles3/shaders/qualification_order.html',
['mac'], bug=483282)
self.Skip('deqp/data/gles3/shaders/scoping.html',
['mac'], bug=483282)
self.Skip('deqp/functional/gles3/defaultvertexattribute.html',
['mac'], bug=483282)
self.Skip('deqp/functional/gles3/floatstatequery.html',
['mac'], bug=483282)
self.Skip('deqp/functional/gles3/texturestatequery.html',
['mac'], bug=483282)
self.Skip('deqp/functional/gles3/vertexarrayobject.html',
['mac'], bug=483282)
self.Skip('deqp/functional/gles3/shaderswitch.html',
['mavericks'], bug=483282)
self.Fail('deqp/functional/gles3/rbostatequery.html',
['mac'], bug=569808)
self.Fail('deqp/functional/gles3/fbostatequery.html',
['mac'], bug=483282)
self.Fail('deqp/functional/gles3/negativeshaderapi.html',
['mac'], bug=483282)
self.Fail('conformance2/buffers/buffer-overflow-test.html',
['mac'], bug=483282)
self.Fail('conformance2/buffers/buffer-type-restrictions.html',
['mac'], bug=483282)
self.Fail('conformance2/misc/uninitialized-test-2.html',
['mac'], bug=483282)
self.Fail('conformance2/renderbuffers/' +
'multisampled-renderbuffer-initialization.html',
['mac'], bug=483282)
self.Fail('conformance2/textures/misc/compressed-tex-image.html',
['mac'], bug=565438)
self.Fail('conformance2/textures/video/*', ['mac'], bug=483282)
self.Fail('conformance2/textures/misc/gl-get-tex-parameter.html',
['mac'], bug=483282)
self.Fail('conformance2/textures/misc/texture-npot.html',
['mac'], bug=483282)
self.Fail('conformance2/textures/misc/tex-storage-compressed-formats.html',
['mac'], bug=295792)
self.Fail('conformance2/renderbuffers/invalidate-framebuffer.html',
['mac'], bug=483282)
self.Fail('conformance2/renderbuffers/framebuffer-test.html',
['mac'], bug=483282)
self.Fail('conformance2/renderbuffers/readbuffer.html',
['mac'], bug=570453)
self.Fail('conformance2/textures/misc/copy-texture-image.html',
['mac'], bug=577144)
self.Fail('conformance2/textures/misc/tex-storage-and-subimage-3d.html',
['mac'], bug=483282)
# The following failure is 10.10 only, but we don't have a keyword yet.
self.Fail('conformance2/reading/read-pixels-from-fbo-test.html',
['mac'], bug=584994)
self.Fail('conformance2/state/gl-object-get-calls.html',
['mac'], bug=483282)
self.Fail('conformance2/textures/image_bitmap_from_image/*',
['mac'], bug=589930)
# Mac Retina NVIDIA
self.Fail('conformance2/rendering/draw-buffers.html',
['mac', ('nvidia', 0xfe9)], bug=483282)
self.Fail('conformance2/textures/misc/tex-input-validation.html',
['mac', ('nvidia', 0xfe9)], bug=483282)
self.Fail('conformance2/textures/misc/tex-mipmap-levels.html',
['mac', ('nvidia', 0xfe9)], bug=483282)
self.Fail('deqp/functional/gles3/shaderstruct.html',
['mac', ('nvidia', 0xfe9)], bug=483282)
# Mac AMD
self.Fail('deqp/functional/gles3/clipping.html',
['mac', 'amd'], bug=483282)
# Linux only.
self.Skip('deqp/functional/gles3/shaderswitch.html',
['linux'], bug=483282)
self.Fail('conformance2/glsl3/vector-dynamic-indexing.html',
['linux'], bug=483282)
self.Fail('conformance2/rendering/draw-buffers.html',
['linux'], bug=483282)
self.Fail('deqp/functional/gles3/fbostatequery.html',
['linux'], bug=483282)
self.Flaky('deqp/functional/gles3/negativeshaderapi.html',
['linux'], bug=483282)
# Linux AMD only.
# It looks like AMD shader compiler rejects many valid ES3 semantics.
self.Skip('deqp/data/gles3/shaders/arrays.html',
['linux', 'amd'], bug=483282)
self.Skip('deqp/data/gles3/shaders/qualification_order.html',
['linux', 'amd'], bug=483282)
self.Skip('deqp/functional/gles3/texturestatequery.html',
['linux', 'amd'], bug=483282)
self.Fail('conformance2/buffers/buffer-type-restrictions.html',
['linux', 'amd'], bug=483282)
self.Fail('conformance2/buffers/buffer-overflow-test.html',
['linux', 'amd'], bug=483282)
self.Fail('conformance2/renderbuffers/framebuffer-texture-layer.html',
['linux', 'amd'], bug=295792)
self.Fail('conformance2/textures/misc/tex-storage-compressed-formats.html',
['linux', 'amd'], bug=295792)
# Linux Intel: driver is GL 3.0 and doesn't support features needed for ES3.
self.Skip('*', ['linux', 'intel'], bug=540543)
# Conflicting expectations to test that the
# "Expectations Have No collisions" unittest works.
# page_name = 'conformance/glsl/constructors/glsl-construct-ivec4.html'
# Conflict when all conditions match
# self.Fail(page_name,
# ['linux', ('nvidia', 0x1), 'debug', 'opengl'])
# self.Fail(page_name,
# ['linux', ('nvidia', 0x1), 'debug', 'opengl'])
# Conflict when all conditions match (and different sets)
# self.Fail(page_name,
# ['linux', 'win', ('nvidia', 0x1), 'debug', 'opengl'])
# self.Fail(page_name,
# ['linux', 'mac', ('nvidia', 0x1), 'amd', 'debug', 'opengl'])
# Conflict with one aspect not specified
# self.Fail(page_name,
# ['linux', ('nvidia', 0x1), 'debug'])
# self.Fail(page_name,
# ['linux', ('nvidia', 0x1), 'debug', 'opengl'])
# Conflict with one aspect not specified (in both conditions)
# self.Fail(page_name,
# ['linux', ('nvidia', 0x1), 'debug'])
# self.Fail(page_name,
# ['linux', ('nvidia', 0x1), 'debug'])
# Conflict even if the GPU is specified in a device ID
# self.Fail(page_name,
# ['linux', ('nvidia', 0x1), 'debug'])
# self.Fail(page_name,
# ['linux', 'nvidia', 'debug'])
# Test there are no conflicts between two different devices
# self.Fail(page_name,
# ['linux', ('nvidia', 0x1), 'debug'])
# self.Fail(page_name,
# ['linux', ('nvidia', 0x2), 'debug'])
# Test there are no conflicts between two devices with different vendors
# self.Fail(page_name,
# ['linux', ('nvidia', 0x1), 'debug'])
# self.Fail(page_name,
# ['linux', ('amd', 0x1), 'debug'])
# Conflicts if there is a device and nothing specified for the other's
# GPU vendors
# self.Fail(page_name,
# ['linux', ('nvidia', 0x1), 'debug'])
# self.Fail(page_name,
# ['linux', 'debug'])
# Test no conflicts happen when only one aspect differs
# self.Fail(page_name,
# ['linux', ('nvidia', 0x1), 'debug', 'opengl'])
# self.Fail(page_name,
# ['win', ('nvidia', 0x1), 'debug', 'opengl'])
# Conflicts if between a generic os condition and a specific version
# self.Fail(page_name,
# ['xp', ('nvidia', 0x1), 'debug', 'opengl'])
# self.Fail(page_name,
# ['win', ('nvidia', 0x1), 'debug', 'opengl'])
|
|
from __future__ import absolute_import, unicode_literals
import copy
import os
import re
import sys
from io import BytesIO
from pprint import pformat
from django.conf import settings
from django.core import signing
from django.core.exceptions import DisallowedHost, ImproperlyConfigured
from django.core.files import uploadhandler
from django.http.multipartparser import MultiPartParser
from django.utils import six
from django.utils.datastructures import MultiValueDict, ImmutableList
from django.utils.encoding import force_bytes, force_text, force_str, iri_to_uri
from django.utils.six.moves.urllib.parse import parse_qsl, urlencode, quote, urljoin
RAISE_ERROR = object()
absolute_http_url_re = re.compile(r"^https?://", re.I)
host_validation_re = re.compile(r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9:]+\])(:\d+)?$")
class UnreadablePostError(IOError):
pass
class HttpRequest(object):
"""A basic HTTP request."""
# The encoding used in GET/POST dicts. None means use default setting.
_encoding = None
_upload_handlers = []
def __init__(self):
# WARNING: The `WSGIRequest` subclass doesn't call `super`.
# Any variable assignment made here should also happen in
# `WSGIRequest.__init__()`.
self.GET, self.POST, self.COOKIES, self.META, self.FILES = {}, {}, {}, {}, {}
self.path = ''
self.path_info = ''
self.method = None
self.resolver_match = None
self._post_parse_error = False
def __repr__(self):
return build_request_repr(self)
def get_host(self):
"""Returns the HTTP host using the environment or request headers."""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in self.META):
host = self.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in self.META:
host = self.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = self.META['SERVER_NAME']
server_port = str(self.META['SERVER_PORT'])
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
allowed_hosts = ['*'] if settings.DEBUG else settings.ALLOWED_HOSTS
domain, port = split_domain_port(host)
if domain and validate_host(domain, allowed_hosts):
return host
else:
msg = "Invalid HTTP_HOST header: %r." % host
if domain:
msg += "You may need to add %r to ALLOWED_HOSTS." % domain
raise DisallowedHost(msg)
def get_full_path(self):
# RFC 3986 requires query string arguments to be in the ASCII range.
# Rather than crash if this doesn't happen, we encode defensively.
return '%s%s' % (self.path, ('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) if self.META.get('QUERY_STRING', '') else '')
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
"""
Attempts to return a signed cookie. If the signature fails or the
cookie has expired, raises an exception... unless you provide the
default argument in which case that value will be returned instead.
"""
try:
cookie_value = self.COOKIES[key]
except KeyError:
if default is not RAISE_ERROR:
return default
else:
raise
try:
value = signing.get_cookie_signer(salt=key + salt).unsign(
cookie_value, max_age=max_age)
except signing.BadSignature:
if default is not RAISE_ERROR:
return default
else:
raise
return value
def build_absolute_uri(self, location=None):
"""
Builds an absolute URI from the location and the variables available in
this request. If no location is specified, the absolute URI is built on
``request.get_full_path()``.
"""
if not location:
location = self.get_full_path()
if not absolute_http_url_re.match(location):
current_uri = '%s://%s%s' % ('https' if self.is_secure() else 'http',
self.get_host(), self.path)
location = urljoin(current_uri, location)
return iri_to_uri(location)
def _is_secure(self):
return os.environ.get("HTTPS") == "on"
def is_secure(self):
# First, check the SECURE_PROXY_SSL_HEADER setting.
if settings.SECURE_PROXY_SSL_HEADER:
try:
header, value = settings.SECURE_PROXY_SSL_HEADER
except ValueError:
raise ImproperlyConfigured('The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.')
if self.META.get(header, None) == value:
return True
# Failing that, fall back to _is_secure(), which is a hook for
# subclasses to implement.
return self._is_secure()
def is_ajax(self):
return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
@property
def encoding(self):
return self._encoding
@encoding.setter
def encoding(self, val):
"""
Sets the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, it is removed and recreated on the
next access (so that it is decoded correctly).
"""
self._encoding = val
if hasattr(self, '_get'):
del self._get
if hasattr(self, '_post'):
del self._post
def _initialize_handlers(self):
self._upload_handlers = [uploadhandler.load_handler(handler, self)
for handler in settings.FILE_UPLOAD_HANDLERS]
@property
def upload_handlers(self):
if not self._upload_handlers:
# If there are no upload handlers defined, initialize them from settings.
self._initialize_handlers()
return self._upload_handlers
@upload_handlers.setter
def upload_handlers(self, upload_handlers):
if hasattr(self, '_files'):
raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
self._upload_handlers = upload_handlers
def parse_file_upload(self, META, post_data):
"""Returns a tuple of (POST QueryDict, FILES MultiValueDict)."""
self.upload_handlers = ImmutableList(
self.upload_handlers,
warning="You cannot alter upload handlers after the upload has been processed."
)
parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
return parser.parse()
@property
def body(self):
if not hasattr(self, '_body'):
if self._read_started:
raise Exception("You cannot access body after reading from request's data stream")
try:
self._body = self.read()
except IOError as e:
six.reraise(UnreadablePostError, UnreadablePostError(*e.args), sys.exc_info()[2])
self._stream = BytesIO(self._body)
return self._body
def _mark_post_parse_error(self):
self._post = QueryDict('')
self._files = MultiValueDict()
self._post_parse_error = True
def _load_post_and_files(self):
"""Populate self._post and self._files if the content-type is a form type"""
if self.method != 'POST':
self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()
return
if self._read_started and not hasattr(self, '_body'):
self._mark_post_parse_error()
return
if self.META.get('CONTENT_TYPE', '').startswith('multipart/form-data'):
if hasattr(self, '_body'):
# Use already read data
data = BytesIO(self._body)
else:
data = self
try:
self._post, self._files = self.parse_file_upload(self.META, data)
except:
# An error occured while parsing POST data. Since when
# formatting the error the request handler might access
# self.POST, set self._post and self._file to prevent
# attempts to parse POST data again.
# Mark that an error occured. This allows self.__repr__ to
# be explicit about it instead of simply representing an
# empty POST
self._mark_post_parse_error()
raise
elif self.META.get('CONTENT_TYPE', '').startswith('application/x-www-form-urlencoded'):
self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
else:
self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()
## File-like and iterator interface.
##
## Expects self._stream to be set to an appropriate source of bytes by
## a corresponding request subclass (e.g. WSGIRequest).
## Also when request data has already been read by request.POST or
## request.body, self._stream points to a BytesIO instance
## containing that data.
def read(self, *args, **kwargs):
self._read_started = True
try:
return self._stream.read(*args, **kwargs)
except IOError as e:
six.reraise(UnreadablePostError, UnreadablePostError(*e.args), sys.exc_info()[2])
def readline(self, *args, **kwargs):
self._read_started = True
try:
return self._stream.readline(*args, **kwargs)
except IOError as e:
six.reraise(UnreadablePostError, UnreadablePostError(*e.args), sys.exc_info()[2])
def xreadlines(self):
while True:
buf = self.readline()
if not buf:
break
yield buf
__iter__ = xreadlines
def readlines(self):
return list(iter(self))
class QueryDict(MultiValueDict):
"""
A specialized MultiValueDict which represents a query string.
A QueryDict can be used to represent GET or POST data. It subclasses
MultiValueDict since keys in such data can be repeated, for instance
in the data from a form with a <select multiple> field.
By default QueryDicts are immutable, though the copy() method
will always return a mutable copy.
Both keys and values set on this class are converted from the given encoding
(DEFAULT_CHARSET by default) to unicode.
"""
# These are both reset in __init__, but is specified here at the class
# level so that unpickling will have valid values
_mutable = True
_encoding = None
def __init__(self, query_string, mutable=False, encoding=None):
super(QueryDict, self).__init__()
if not encoding:
encoding = settings.DEFAULT_CHARSET
self.encoding = encoding
if six.PY3:
if isinstance(query_string, bytes):
# query_string normally contains URL-encoded data, a subset of ASCII.
try:
query_string = query_string.decode(encoding)
except UnicodeDecodeError:
# ... but some user agents are misbehaving :-(
query_string = query_string.decode('iso-8859-1')
for key, value in parse_qsl(query_string or '',
keep_blank_values=True,
encoding=encoding):
self.appendlist(key, value)
else:
for key, value in parse_qsl(query_string or '',
keep_blank_values=True):
self.appendlist(force_text(key, encoding, errors='replace'),
force_text(value, encoding, errors='replace'))
self._mutable = mutable
@property
def encoding(self):
if self._encoding is None:
self._encoding = settings.DEFAULT_CHARSET
return self._encoding
@encoding.setter
def encoding(self, value):
self._encoding = value
def _assert_mutable(self):
if not self._mutable:
raise AttributeError("This QueryDict instance is immutable")
def __setitem__(self, key, value):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
value = bytes_to_text(value, self.encoding)
super(QueryDict, self).__setitem__(key, value)
def __delitem__(self, key):
self._assert_mutable()
super(QueryDict, self).__delitem__(key)
def __copy__(self):
result = self.__class__('', mutable=True, encoding=self.encoding)
for key, value in six.iterlists(self):
result.setlist(key, value)
return result
def __deepcopy__(self, memo):
result = self.__class__('', mutable=True, encoding=self.encoding)
memo[id(self)] = result
for key, value in six.iterlists(self):
result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo))
return result
def setlist(self, key, list_):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
list_ = [bytes_to_text(elt, self.encoding) for elt in list_]
super(QueryDict, self).setlist(key, list_)
def setlistdefault(self, key, default_list=None):
self._assert_mutable()
return super(QueryDict, self).setlistdefault(key, default_list)
def appendlist(self, key, value):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
value = bytes_to_text(value, self.encoding)
super(QueryDict, self).appendlist(key, value)
def pop(self, key, *args):
self._assert_mutable()
return super(QueryDict, self).pop(key, *args)
def popitem(self):
self._assert_mutable()
return super(QueryDict, self).popitem()
def clear(self):
self._assert_mutable()
super(QueryDict, self).clear()
def setdefault(self, key, default=None):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
default = bytes_to_text(default, self.encoding)
return super(QueryDict, self).setdefault(key, default)
def copy(self):
"""Returns a mutable copy of this object."""
return self.__deepcopy__({})
def urlencode(self, safe=None):
"""
Returns an encoded string of all query string arguments.
:arg safe: Used to specify characters which do not require quoting, for
example::
>>> q = QueryDict('', mutable=True)
>>> q['next'] = '/a&b/'
>>> q.urlencode()
'next=%2Fa%26b%2F'
>>> q.urlencode(safe='/')
'next=/a%26b/'
"""
output = []
if safe:
safe = force_bytes(safe, self.encoding)
encode = lambda k, v: '%s=%s' % ((quote(k, safe), quote(v, safe)))
else:
encode = lambda k, v: urlencode({k: v})
for k, list_ in self.lists():
k = force_bytes(k, self.encoding)
output.extend([encode(k, force_bytes(v, self.encoding))
for v in list_])
return '&'.join(output)
def build_request_repr(request, path_override=None, GET_override=None,
POST_override=None, COOKIES_override=None,
META_override=None):
"""
Builds and returns the request's representation string. The request's
attributes may be overridden by pre-processed values.
"""
# Since this is called as part of error handling, we need to be very
# robust against potentially malformed input.
try:
get = (pformat(GET_override)
if GET_override is not None
else pformat(request.GET))
except Exception:
get = '<could not parse>'
if request._post_parse_error:
post = '<could not parse>'
else:
try:
post = (pformat(POST_override)
if POST_override is not None
else pformat(request.POST))
except Exception:
post = '<could not parse>'
try:
cookies = (pformat(COOKIES_override)
if COOKIES_override is not None
else pformat(request.COOKIES))
except Exception:
cookies = '<could not parse>'
try:
meta = (pformat(META_override)
if META_override is not None
else pformat(request.META))
except Exception:
meta = '<could not parse>'
path = path_override if path_override is not None else request.path
return force_str('<%s\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' %
(request.__class__.__name__,
path,
six.text_type(get),
six.text_type(post),
six.text_type(cookies),
six.text_type(meta)))
# It's neither necessary nor appropriate to use
# django.utils.encoding.smart_text for parsing URLs and form inputs. Thus,
# this slightly more restricted function, used by QueryDict.
def bytes_to_text(s, encoding):
"""
Converts basestring objects to unicode, using the given encoding. Illegally
encoded input characters are replaced with Unicode "unknown" codepoint
(\ufffd).
Returns any non-basestring objects without change.
"""
if isinstance(s, bytes):
return six.text_type(s, encoding, 'replace')
else:
return s
def split_domain_port(host):
"""
Return a (domain, port) tuple from a given host.
Returned domain is lower-cased. If the host is invalid, the domain will be
empty.
"""
host = host.lower()
if not host_validation_re.match(host):
return '', ''
if host[-1] == ']':
# It's an IPv6 address without a port.
return host, ''
bits = host.rsplit(':', 1)
if len(bits) == 2:
return tuple(bits)
return bits[0], ''
def validate_host(host, allowed_hosts):
"""
Validate the given host for this site.
Check that the host looks valid and matches a host or host pattern in the
given list of ``allowed_hosts``. Any pattern beginning with a period
matches a domain and all its subdomains (e.g. ``.example.com`` matches
``example.com`` and any subdomain), ``*`` matches anything, and anything
else must match exactly.
Note: This function assumes that the given host is lower-cased and has
already had the port, if any, stripped off.
Return ``True`` for a valid host, ``False`` otherwise.
"""
for pattern in allowed_hosts:
pattern = pattern.lower()
match = (
pattern == '*' or
pattern.startswith('.') and (
host.endswith(pattern) or host == pattern[1:]
) or
pattern == host
)
if match:
return True
return False
|
|
##########################################################################
#
# Copyright (c) 2017, Image Engine Design 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 Image Engine Design nor the names of
# any other contributors to this software 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.
#
##########################################################################
import os
import unittest
import imath
import IECore
import IECoreImage
import Gaffer
import GafferImage
import GafferImageTest
import math
class FilterAlgoTest( GafferImageTest.ImageTestCase ) :
derivativesReferenceParallelFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/filterDerivativesTest.parallel.exr" )
derivativesReferenceBoxFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/filterDerivativesTest.box.exr" )
# Artificial test of several filters passing in different derivatives, including a bunch of 15 degree rotations
def testFilterDerivatives( self ):
# Size of one grid cell
subSize = 35
# Each grid cell gets a dot in the middle
redDot = GafferImage.Constant()
redDot["format"].setValue( GafferImage.Format( 1, 1, 1.000 ) )
redDot["color"].setValue( imath.Color4f( 10, 0, 0, 1 ) )
redDotCentered = GafferImage.Crop( "Crop" )
redDotCentered["in"].setInput( redDot["out"] )
redDotCentered["area"].setValue( imath.Box2i( imath.V2i( -(subSize-1)/2 ), imath.V2i( (subSize-1)/2 + 1 ) ) )
borderForFilterWidth = 40
sampleRegion = redDotCentered["out"]["dataWindow"].getValue()
sampleRegion.setMin( sampleRegion.min() - imath.V2i( borderForFilterWidth ) )
sampleRegion.setMax( sampleRegion.max() + imath.V2i( borderForFilterWidth ) )
s = GafferImage.Sampler( redDotCentered["out"], "R", sampleRegion, GafferImage.Sampler.BoundingMode.Black )
filters = [
'box', 'triangle', 'gaussian', 'sharp-gaussian', 'catmull-rom', 'blackman-harris',
'sinc', 'lanczos3', 'radial-lanczos3', 'mitchell', 'bspline', 'disk', 'cubic',
'keys', 'simon', 'rifman', 'smoothGaussian',
]
if filters != GafferImage.FilterAlgo.filterNames() :
print(
"INFO : GafferImageTest.FilterAlgoTest.testFilterDerivatives : " +
"Some image filters have not been tested ({}). Consider updating the reference images to account for the newly available filters.".format(
list(set(filters).symmetric_difference(set(GafferImage.FilterAlgo.filterNames())))
)
)
dirs = [
(imath.V2f(1,0), imath.V2f(0,1)),
(imath.V2f(5,0), imath.V2f(0,1)),
(imath.V2f(1,0), imath.V2f(0,5)),
(imath.V2f(5,0), imath.V2f(0,5)) ]
for angle in range( 0, 91, 15 ):
sa = math.sin( angle / 180.0 * math.pi )
ca = math.cos( angle / 180.0 * math.pi )
dirs.append( ( imath.V2f(ca * 5, sa * 5 ), imath.V2f(-sa * 3, ca * 3 ) ) )
size = subSize * imath.V2i( len( dirs ), len( filters ) )
w = imath.Box2i( imath.V2i( 0 ), size - imath.V2i( 1 ) )
parallelogramImage = IECoreImage.ImagePrimitive( w, w )
boxImage = IECoreImage.ImagePrimitive( w, w )
parallelogramR = IECore.FloatVectorData( size[0] * size[1] )
boxR = IECore.FloatVectorData( size[0] * size[1] )
for x_sub, d in enumerate( dirs ):
for y_sub, f in enumerate( filters ):
for y in range( subSize ):
for x in range( subSize ):
p = imath.V2f( x + 0.5, y + 0.5 )
inputDerivatives = GafferImage.FilterAlgo.derivativesToAxisAligned( p, d[0], d[1] )
boxR[ ( y_sub * subSize + y ) * size[0] + x_sub * subSize + x ] = GafferImage.FilterAlgo.sampleBox(
s, p, inputDerivatives[0], inputDerivatives[1], f )
parallelogramR[ ( y_sub * subSize + y ) * size[0] + x_sub * subSize + x ] = GafferImage.FilterAlgo.sampleParallelogram(
s, p, d[0], d[1], f )
parallelogramImage["R"] = parallelogramR
boxImage["R"] = boxR
# Enable to write out images for visual comparison
if False:
IECore.Writer.create( parallelogramImage, "/tmp/filterDerivativesTestResult.parallelogram.exr" ).write()
IECore.Writer.create( boxImage, "/tmp/filterDerivativesTestResult.box.exr" ).write()
parallelogramReference = IECore.Reader.create( self.derivativesReferenceParallelFileName ).read()
boxReference = IECore.Reader.create( self.derivativesReferenceBoxFileName ).read()
for i in range( len( parallelogramImage["R"] ) ):
self.assertAlmostEqual( parallelogramReference["R"][i], parallelogramImage["R"][i], places = 5 )
self.assertAlmostEqual( boxReference["R"][i], boxImage["R"][i], places = 5 )
def testMatchesResample( self ):
def __test( fileName, size, filter ) :
inputFileName = os.path.dirname( __file__ ) + "/images/" + fileName
reader = GafferImage.ImageReader()
reader["fileName"].setValue( inputFileName )
inSize = reader["out"]["format"].getValue().getDisplayWindow().size()
inSize = imath.V2f( inSize.x, inSize.y )
deleteChannels = GafferImage.DeleteChannels()
deleteChannels["mode"].setValue( 1 )
deleteChannels["channels"].setValue( IECore.StringVectorData( [ 'R' ] ) )
deleteChannels["in"].setInput( reader["out"] )
scale = imath.V2f( size.x, size.y ) / inSize
resample = GafferImage.Resample()
resample["in"].setInput( deleteChannels["out"] )
resample["matrix"].setValue(
imath.M33f().scale( scale )
)
resample["filter"].setValue( filter )
resample["boundingMode"].setValue( GafferImage.Sampler.BoundingMode.Clamp )
crop = GafferImage.Crop()
crop["in"].setInput( resample["out"] )
crop["area"].setValue( imath.Box2i( imath.V2i( 0 ), size ) )
borderForFilterWidth = 60
sampleRegion = reader["out"]["dataWindow"].getValue()
sampleRegion.setMin( sampleRegion.min() - imath.V2i( borderForFilterWidth ) )
sampleRegion.setMax( sampleRegion.max() + imath.V2i( borderForFilterWidth ) )
s = GafferImage.Sampler( reader["out"], "R", sampleRegion, GafferImage.Sampler.BoundingMode.Clamp )
resampledS = GafferImage.Sampler( resample["out"], "R", resample["out"]["dataWindow"].getValue() )
for y in range( size.y ):
for x in range( size.x ):
resampled = resampledS.sample( x, y )
self.assertAlmostEqual( resampled, GafferImage.FilterAlgo.sampleBox(
s,
imath.V2f( x + 0.5, y + 0.5 ) / scale,
max( 1.0 / scale[0], 1.0 ),
max( 1.0 / scale[1], 1.0 ),
filter
), places = 5 )
self.assertAlmostEqual( resampled, GafferImage.FilterAlgo.sampleParallelogram(
s,
imath.V2f( x + 0.5, y + 0.5 ) / scale,
imath.V2f( 1.0 / scale[0], 0),
imath.V2f( 0, 1.0 / scale[1]),
filter
), places = 5 )
tests = [
( "resamplePatterns.exr", imath.V2i( 4 ), "lanczos3" ),
( "resamplePatterns.exr", imath.V2i( 40 ), "box" ),
( "resamplePatterns.exr", imath.V2i( 101 ), "gaussian" ),
( "resamplePatterns.exr", imath.V2i( 119 ), "mitchell" ),
( "resamplePatterns.exr", imath.V2i( 300 ), "sinc" ),
]
for args in tests :
__test( *args )
if __name__ == "__main__":
unittest.main()
|
|
# -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.yangtypes import YANGDynClass
from pyangbind.lib.yangtypes import ReferenceType
from pyangbind.lib.base import PybindBase
from collections import OrderedDict
from decimal import Decimal
from bitarray import bitarray
import six
# PY3 support of some PY2 keywords (needs improved)
if six.PY3:
import builtins as __builtin__
long = int
elif six.PY2:
import __builtin__
class state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/protocols/protocol/bgp/global/use-multiple-paths/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: State parameters relating to multipath
"""
__slots__ = ("_path_helper", "_extmethods", "__enabled")
_yang_name = "state"
_pybind_generated_by = "container"
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__enabled = YANGDynClass(
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="boolean",
is_config=False,
)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path() + [self._yang_name]
else:
return [
"network-instances",
"network-instance",
"protocols",
"protocol",
"bgp",
"global",
"use-multiple-paths",
"state",
]
def _get_enabled(self):
"""
Getter method for enabled, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/use_multiple_paths/state/enabled (boolean)
YANG Description: Whether the use of multiple paths for the same NLRI is
enabled for the neighbor. This value is overridden by
any more specific configuration value.
"""
return self.__enabled
def _set_enabled(self, v, load=False):
"""
Setter method for enabled, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/use_multiple_paths/state/enabled (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_enabled is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_enabled() directly.
YANG Description: Whether the use of multiple paths for the same NLRI is
enabled for the neighbor. This value is overridden by
any more specific configuration value.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="boolean",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """enabled must be of a type compatible with boolean""",
"defined-type": "boolean",
"generated-type": """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enabled", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='boolean', is_config=False)""",
}
)
self.__enabled = t
if hasattr(self, "_set"):
self._set()
def _unset_enabled(self):
self.__enabled = YANGDynClass(
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="boolean",
is_config=False,
)
enabled = __builtin__.property(_get_enabled)
_pyangbind_elements = OrderedDict([("enabled", enabled)])
class state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance-l2 - based on the path /network-instances/network-instance/protocols/protocol/bgp/global/use-multiple-paths/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: State parameters relating to multipath
"""
__slots__ = ("_path_helper", "_extmethods", "__enabled")
_yang_name = "state"
_pybind_generated_by = "container"
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__enabled = YANGDynClass(
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="boolean",
is_config=False,
)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path() + [self._yang_name]
else:
return [
"network-instances",
"network-instance",
"protocols",
"protocol",
"bgp",
"global",
"use-multiple-paths",
"state",
]
def _get_enabled(self):
"""
Getter method for enabled, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/use_multiple_paths/state/enabled (boolean)
YANG Description: Whether the use of multiple paths for the same NLRI is
enabled for the neighbor. This value is overridden by
any more specific configuration value.
"""
return self.__enabled
def _set_enabled(self, v, load=False):
"""
Setter method for enabled, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/use_multiple_paths/state/enabled (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_enabled is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_enabled() directly.
YANG Description: Whether the use of multiple paths for the same NLRI is
enabled for the neighbor. This value is overridden by
any more specific configuration value.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="boolean",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """enabled must be of a type compatible with boolean""",
"defined-type": "boolean",
"generated-type": """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enabled", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='boolean', is_config=False)""",
}
)
self.__enabled = t
if hasattr(self, "_set"):
self._set()
def _unset_enabled(self):
self.__enabled = YANGDynClass(
base=YANGBool,
default=YANGBool("false"),
is_leaf=True,
yang_name="enabled",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="boolean",
is_config=False,
)
enabled = __builtin__.property(_get_enabled)
_pyangbind_elements = OrderedDict([("enabled", enabled)])
|
|
"""
BaseHTTPServer that implements the Python WSGI protocol (PEP 333, rev 1.21).
Adapted from wsgiref.simple_server: http://svn.eby-sarna.com/wsgiref/
This is a simple server for use in testing or debugging Django apps. It hasn't
been reviewed for security issues. Don't use it for production use.
"""
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import mimetypes
import os
import re
import stat
import sys
import urllib
from django.utils.http import http_date
__version__ = "0.1"
__all__ = ['WSGIServer','WSGIRequestHandler']
server_version = "WSGIServer/" + __version__
sys_version = "Python/" + sys.version.split()[0]
software_version = server_version + ' ' + sys_version
class WSGIServerException(Exception):
pass
class FileWrapper(object):
"""Wrapper to convert file-like objects to iterables"""
def __init__(self, filelike, blksize=8192):
self.filelike = filelike
self.blksize = blksize
if hasattr(filelike,'close'):
self.close = filelike.close
def __getitem__(self,key):
data = self.filelike.read(self.blksize)
if data:
return data
raise IndexError
def __iter__(self):
return self
def next(self):
data = self.filelike.read(self.blksize)
if data:
return data
raise StopIteration
# Regular expression that matches `special' characters in parameters, the
# existence of which force quoting of the parameter value.
tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
def _formatparam(param, value=None, quote=1):
"""Convenience function to format and return a key=value pair.
This will quote the value if needed or if quote is true.
"""
if value is not None and len(value) > 0:
if quote or tspecials.search(value):
value = value.replace('\\', '\\\\').replace('"', r'\"')
return '%s="%s"' % (param, value)
else:
return '%s=%s' % (param, value)
else:
return param
class Headers(object):
"""Manage a collection of HTTP response headers"""
def __init__(self,headers):
if not isinstance(headers, list):
raise TypeError("Headers must be a list of name/value tuples")
self._headers = headers
def __len__(self):
"""Return the total number of headers, including duplicates."""
return len(self._headers)
def __setitem__(self, name, val):
"""Set the value of a header."""
del self[name]
self._headers.append((name, val))
def __delitem__(self,name):
"""Delete all occurrences of a header, if present.
Does *not* raise an exception if the header is missing.
"""
name = name.lower()
self._headers[:] = [kv for kv in self._headers if kv[0].lower()<>name]
def __getitem__(self,name):
"""Get the first header value for 'name'
Return None if the header is missing instead of raising an exception.
Note that if the header appeared multiple times, the first exactly which
occurrance gets returned is undefined. Use getall() to get all
the values matching a header field name.
"""
return self.get(name)
def has_key(self, name):
"""Return true if the message contains the header."""
return self.get(name) is not None
__contains__ = has_key
def get_all(self, name):
"""Return a list of all the values for the named field.
These will be sorted in the order they appeared in the original header
list or were added to this instance, and may contain duplicates. Any
fields deleted and re-inserted are always appended to the header list.
If no fields exist with the given name, returns an empty list.
"""
name = name.lower()
return [kv[1] for kv in self._headers if kv[0].lower()==name]
def get(self,name,default=None):
"""Get the first header value for 'name', or return 'default'"""
name = name.lower()
for k,v in self._headers:
if k.lower()==name:
return v
return default
def keys(self):
"""Return a list of all the header field names.
These will be sorted in the order they appeared in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
"""
return [k for k, v in self._headers]
def values(self):
"""Return a list of all header values.
These will be sorted in the order they appeared in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
"""
return [v for k, v in self._headers]
def items(self):
"""Get all the header fields and values.
These will be sorted in the order they were in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
"""
return self._headers[:]
def __repr__(self):
return "Headers(%s)" % `self._headers`
def __str__(self):
"""str() returns the formatted headers, complete with end line,
suitable for direct HTTP transmission."""
return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['',''])
def setdefault(self,name,value):
"""Return first matching header value for 'name', or 'value'
If there is no header named 'name', add a new header with name 'name'
and value 'value'."""
result = self.get(name)
if result is None:
self._headers.append((name,value))
return value
else:
return result
def add_header(self, _name, _value, **_params):
"""Extended header setting.
_name is the header field to add. keyword arguments can be used to set
additional parameters for the header field, with underscores converted
to dashes. Normally the parameter will be added as key="value" unless
value is None, in which case only the key will be added.
Example:
h.add_header('content-disposition', 'attachment', filename='bud.gif')
Note that unlike the corresponding 'email.Message' method, this does
*not* handle '(charset, language, value)' tuples: all values must be
strings or None.
"""
parts = []
if _value is not None:
parts.append(_value)
for k, v in _params.items():
if v is None:
parts.append(k.replace('_', '-'))
else:
parts.append(_formatparam(k.replace('_', '-'), v))
self._headers.append((_name, "; ".join(parts)))
def guess_scheme(environ):
"""Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https'
"""
if environ.get("HTTPS") in ('yes','on','1'):
return 'https'
else:
return 'http'
_hop_headers = {
'connection':1, 'keep-alive':1, 'proxy-authenticate':1,
'proxy-authorization':1, 'te':1, 'trailers':1, 'transfer-encoding':1,
'upgrade':1
}
def is_hop_by_hop(header_name):
"""Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header"""
return header_name.lower() in _hop_headers
class ServerHandler(object):
"""Manage the invocation of a WSGI application"""
# Configuration parameters; can override per-subclass or per-instance
wsgi_version = (1,0)
wsgi_multithread = True
wsgi_multiprocess = True
wsgi_run_once = False
origin_server = True # We are transmitting direct to client
http_version = "1.0" # Version that should be used for response
server_software = software_version
# os_environ is used to supply configuration from the OS environment:
# by default it's a copy of 'os.environ' as of import time, but you can
# override this in e.g. your __init__ method.
os_environ = dict(os.environ.items())
# Collaborator classes
wsgi_file_wrapper = FileWrapper # set to None to disable
headers_class = Headers # must be a Headers-like class
# Error handling (also per-subclass or per-instance)
traceback_limit = None # Print entire traceback to self.get_stderr()
error_status = "500 INTERNAL SERVER ERROR"
error_headers = [('Content-Type','text/plain')]
# State variables (don't mess with these)
status = result = None
headers_sent = False
headers = None
bytes_sent = 0
def __init__(self, stdin, stdout, stderr, environ, multithread=True,
multiprocess=False):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.base_env = environ
self.wsgi_multithread = multithread
self.wsgi_multiprocess = multiprocess
def run(self, application):
"""Invoke the application"""
# Note to self: don't move the close()! Asynchronous servers shouldn't
# call close() from finish_response(), so if you close() anywhere but
# the double-error branch here, you'll break asynchronous servers by
# prematurely closing. Async servers must return from 'run()' without
# closing if there might still be output to iterate over.
try:
self.setup_environ()
self.result = application(self.environ, self.start_response)
self.finish_response()
except:
try:
self.handle_error()
except:
# If we get an error handling an error, just give up already!
self.close()
raise # ...and let the actual server figure it out.
def setup_environ(self):
"""Set up the environment for one request"""
env = self.environ = self.os_environ.copy()
self.add_cgi_vars()
env['wsgi.input'] = self.get_stdin()
env['wsgi.errors'] = self.get_stderr()
env['wsgi.version'] = self.wsgi_version
env['wsgi.run_once'] = self.wsgi_run_once
env['wsgi.url_scheme'] = self.get_scheme()
env['wsgi.multithread'] = self.wsgi_multithread
env['wsgi.multiprocess'] = self.wsgi_multiprocess
if self.wsgi_file_wrapper is not None:
env['wsgi.file_wrapper'] = self.wsgi_file_wrapper
if self.origin_server and self.server_software:
env.setdefault('SERVER_SOFTWARE',self.server_software)
def finish_response(self):
"""Send any iterable data, then close self and the iterable
Subclasses intended for use in asynchronous servers will
want to redefine this method, such that it sets up callbacks
in the event loop to iterate over the data, and to call
'self.close()' once the response is finished.
"""
if not self.result_is_file() and not self.sendfile():
for data in self.result:
self.write(data)
self.finish_content()
self.close()
def get_scheme(self):
"""Return the URL scheme being used"""
return guess_scheme(self.environ)
def set_content_length(self):
"""Compute Content-Length or switch to chunked encoding if possible"""
try:
blocks = len(self.result)
except (TypeError, AttributeError, NotImplementedError):
pass
else:
if blocks==1:
self.headers['Content-Length'] = str(self.bytes_sent)
return
# XXX Try for chunked encoding if origin server and client is 1.1
def cleanup_headers(self):
"""Make any necessary header changes or defaults
Subclasses can extend this to add other defaults.
"""
if 'Content-Length' not in self.headers:
self.set_content_length()
def start_response(self, status, headers,exc_info=None):
"""'start_response()' callable as specified by PEP 333"""
if exc_info:
try:
if self.headers_sent:
# Re-raise original exception if headers sent
raise exc_info[0], exc_info[1], exc_info[2]
finally:
exc_info = None # avoid dangling circular ref
elif self.headers is not None:
raise AssertionError("Headers already set!")
assert isinstance(status, str),"Status must be a string"
assert len(status)>=4,"Status must be at least 4 characters"
assert int(status[:3]),"Status message must begin w/3-digit code"
assert status[3]==" ", "Status message must have a space after code"
if __debug__:
for name,val in headers:
assert isinstance(name, str),"Header names must be strings"
assert isinstance(val, str),"Header values must be strings"
assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed"
self.status = status
self.headers = self.headers_class(headers)
return self.write
def send_preamble(self):
"""Transmit version/status/date/server, via self._write()"""
if self.origin_server:
if self.client_is_modern():
self._write('HTTP/%s %s\r\n' % (self.http_version,self.status))
if 'Date' not in self.headers:
self._write(
'Date: %s\r\n' % http_date()
)
if self.server_software and 'Server' not in self.headers:
self._write('Server: %s\r\n' % self.server_software)
else:
self._write('Status: %s\r\n' % self.status)
def write(self, data):
"""'write()' callable as specified by PEP 333"""
assert isinstance(data, str), "write() argument must be string"
if not self.status:
raise AssertionError("write() before start_response()")
elif not self.headers_sent:
# Before the first output, send the stored headers
self.bytes_sent = len(data) # make sure we know content-length
self.send_headers()
else:
self.bytes_sent += len(data)
# XXX check Content-Length and truncate if too many bytes written?
# If data is too large, socket will choke, so write chunks no larger
# than 32MB at a time.
length = len(data)
if length > 33554432:
offset = 0
while offset < length:
chunk_size = min(33554432, length)
self._write(data[offset:offset+chunk_size])
self._flush()
offset += chunk_size
else:
self._write(data)
self._flush()
def sendfile(self):
"""Platform-specific file transmission
Override this method in subclasses to support platform-specific
file transmission. It is only called if the application's
return iterable ('self.result') is an instance of
'self.wsgi_file_wrapper'.
This method should return a true value if it was able to actually
transmit the wrapped file-like object using a platform-specific
approach. It should return a false value if normal iteration
should be used instead. An exception can be raised to indicate
that transmission was attempted, but failed.
NOTE: this method should call 'self.send_headers()' if
'self.headers_sent' is false and it is going to attempt direct
transmission of the file1.
"""
return False # No platform-specific transmission by default
def finish_content(self):
"""Ensure headers and content have both been sent"""
if not self.headers_sent:
self.headers['Content-Length'] = "0"
self.send_headers()
else:
pass # XXX check if content-length was too short?
def close(self):
try:
self.request_handler.log_request(self.status.split(' ',1)[0], self.bytes_sent)
finally:
try:
if hasattr(self.result,'close'):
self.result.close()
finally:
self.result = self.headers = self.status = self.environ = None
self.bytes_sent = 0; self.headers_sent = False
def send_headers(self):
"""Transmit headers to the client, via self._write()"""
self.cleanup_headers()
self.headers_sent = True
if not self.origin_server or self.client_is_modern():
self.send_preamble()
self._write(str(self.headers))
def result_is_file(self):
"""True if 'self.result' is an instance of 'self.wsgi_file_wrapper'"""
wrapper = self.wsgi_file_wrapper
return wrapper is not None and isinstance(self.result,wrapper)
def client_is_modern(self):
"""True if client can accept status and headers"""
return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
def log_exception(self,exc_info):
"""Log the 'exc_info' tuple in the server log
Subclasses may override to retarget the output or change its format.
"""
try:
from traceback import print_exception
stderr = self.get_stderr()
print_exception(
exc_info[0], exc_info[1], exc_info[2],
self.traceback_limit, stderr
)
stderr.flush()
finally:
exc_info = None
def handle_error(self):
"""Log current error, and send error output to client if possible"""
self.log_exception(sys.exc_info())
if not self.headers_sent:
self.result = self.error_output(self.environ, self.start_response)
self.finish_response()
# XXX else: attempt advanced recovery techniques for HTML or text?
def error_output(self, environ, start_response):
import traceback
start_response(self.error_status, self.error_headers[:], sys.exc_info())
return ['\n'.join(traceback.format_exception(*sys.exc_info()))]
# Pure abstract methods; *must* be overridden in subclasses
def _write(self,data):
self.stdout.write(data)
self._write = self.stdout.write
def _flush(self):
self.stdout.flush()
self._flush = self.stdout.flush
def get_stdin(self):
return self.stdin
def get_stderr(self):
return self.stderr
def add_cgi_vars(self):
self.environ.update(self.base_env)
class WSGIServer(HTTPServer):
"""BaseHTTPServer that implements the Python WSGI protocol"""
application = None
def server_bind(self):
"""Override server_bind to store the server name."""
try:
HTTPServer.server_bind(self)
except Exception, e:
raise WSGIServerException, e
self.setup_environ()
def setup_environ(self):
# Set up base environment
env = self.base_environ = {}
env['SERVER_NAME'] = self.server_name
env['GATEWAY_INTERFACE'] = 'CGI/1.1'
env['SERVER_PORT'] = str(self.server_port)
env['REMOTE_HOST']=''
env['CONTENT_LENGTH']=''
env['SCRIPT_NAME'] = ''
def get_app(self):
return self.application
def set_app(self,application):
self.application = application
class WSGIRequestHandler(BaseHTTPRequestHandler):
server_version = "WSGIServer/" + __version__
def __init__(self, *args, **kwargs):
from django.conf import settings
self.admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
# We set self.path to avoid crashes in log_message() on unsupported
# requests (like "OPTIONS").
self.path = ''
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def get_environ(self):
env = self.server.base_environ.copy()
env['SERVER_PROTOCOL'] = self.request_version
env['REQUEST_METHOD'] = self.command
if '?' in self.path:
path,query = self.path.split('?',1)
else:
path,query = self.path,''
env['PATH_INFO'] = urllib.unquote(path)
env['QUERY_STRING'] = query
env['REMOTE_ADDR'] = self.client_address[0]
if self.headers.typeheader is None:
env['CONTENT_TYPE'] = self.headers.type
else:
env['CONTENT_TYPE'] = self.headers.typeheader
length = self.headers.getheader('content-length')
if length:
env['CONTENT_LENGTH'] = length
for h in self.headers.headers:
k,v = h.split(':',1)
k=k.replace('-','_').upper(); v=v.strip()
if k in env:
continue # skip content length, type,etc.
if 'HTTP_'+k in env:
env['HTTP_'+k] += ','+v # comma-separate multiple headers
else:
env['HTTP_'+k] = v
return env
def get_stderr(self):
return sys.stderr
def handle(self):
"""Handle a single HTTP request"""
self.raw_requestline = self.rfile.readline()
if not self.parse_request(): # An error code has been sent, just exit
return
handler = ServerHandler(self.rfile, self.wfile, self.get_stderr(), self.get_environ())
handler.request_handler = self # backpointer for logging
handler.run(self.server.get_app())
def log_message(self, format, *args):
# Don't bother logging requests for admin images or the favicon.
if self.path.startswith(self.admin_media_prefix) or self.path == '/favicon.ico':
return
sys.stderr.write("[%s] %s\n" % (self.log_date_time_string(), format % args))
class AdminMediaHandler(object):
"""
WSGI middleware that intercepts calls to the admin media directory, as
defined by the ADMIN_MEDIA_PREFIX setting, and serves those images.
Use this ONLY LOCALLY, for development! This hasn't been tested for
security and is not super efficient.
"""
def __init__(self, application, media_dir=None):
from django.conf import settings
self.application = application
if not media_dir:
import django
self.media_dir = django.__path__[0] + '/contrib/admin/media'
else:
self.media_dir = media_dir
self.media_url = settings.ADMIN_MEDIA_PREFIX
def __call__(self, environ, start_response):
import os.path
# Ignore requests that aren't under ADMIN_MEDIA_PREFIX. Also ignore
# all requests if ADMIN_MEDIA_PREFIX isn't a relative URL.
if self.media_url.startswith('http://') or self.media_url.startswith('https://') \
or not environ['PATH_INFO'].startswith(self.media_url):
return self.application(environ, start_response)
# Find the admin file and serve it up, if it exists and is readable.
relative_url = environ['PATH_INFO'][len(self.media_url):]
file_path = os.path.join(self.media_dir, relative_url)
if not os.path.exists(file_path):
status = '404 NOT FOUND'
headers = {'Content-type': 'text/plain'}
output = ['Page not found: %s' % file_path]
else:
try:
fp = open(file_path, 'rb')
except IOError:
status = '401 UNAUTHORIZED'
headers = {'Content-type': 'text/plain'}
output = ['Permission denied: %s' % file_path]
else:
# This is a very simple implementation of conditional GET with
# the Last-Modified header. It makes media files a bit speedier
# because the files are only read off disk for the first
# request (assuming the browser/client supports conditional
# GET).
mtime = http_date(os.stat(file_path)[stat.ST_MTIME])
headers = {'Last-Modified': mtime}
if environ.get('HTTP_IF_MODIFIED_SINCE', None) == mtime:
status = '304 NOT MODIFIED'
output = []
else:
status = '200 OK'
mime_type = mimetypes.guess_type(file_path)[0]
if mime_type:
headers['Content-Type'] = mime_type
output = [fp.read()]
fp.close()
start_response(status, headers.items())
return output
def run(addr, port, wsgi_handler):
server_address = (addr, port)
httpd = WSGIServer(server_address, WSGIRequestHandler)
httpd.set_app(wsgi_handler)
httpd.serve_forever()
|
|
from __future__ import unicode_literals
from django import forms
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericStackedInline
from django.core import checks
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase, ignore_warnings, override_settings
from .models import Album, Book, City, Influence, Song, State, TwoAlbumFKAndAnE
class SongForm(forms.ModelForm):
pass
class ValidFields(admin.ModelAdmin):
form = SongForm
fields = ['title']
class ValidFormFieldsets(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
class ExtraFieldForm(SongForm):
name = forms.CharField(max_length=50)
return ExtraFieldForm
fieldsets = (
(None, {
'fields': ('name',),
}),
)
class MyAdmin(admin.ModelAdmin):
@classmethod
def check(cls, model, **kwargs):
return ['error!']
@override_settings(
SILENCED_SYSTEM_CHECKS=['fields.W342'], # ForeignKey(unique=True)
INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes', 'admin_checks']
)
class SystemChecksTestCase(TestCase):
@override_settings(DEBUG=True)
def test_checks_are_performed(self):
admin.site.register(Song, MyAdmin)
try:
errors = checks.run_checks()
expected = ['error!']
self.assertEqual(errors, expected)
finally:
admin.site.unregister(Song)
admin.sites.system_check_errors = []
@override_settings(DEBUG=True)
def test_custom_adminsite(self):
class CustomAdminSite(admin.AdminSite):
pass
custom_site = CustomAdminSite()
custom_site.register(Song, MyAdmin)
try:
errors = checks.run_checks()
expected = ['error!']
self.assertEqual(errors, expected)
finally:
custom_site.unregister(Song)
admin.sites.system_check_errors = []
def test_field_name_not_in_list_display(self):
class SongAdmin(admin.ModelAdmin):
list_editable = ["original_release"]
errors = SongAdmin.check(model=Song)
expected = [
checks.Error(
"The value of 'list_editable[0]' refers to 'original_release', "
"which is not contained in 'list_display'.",
hint=None,
obj=SongAdmin,
id='admin.E122',
)
]
self.assertEqual(errors, expected)
def test_readonly_and_editable(self):
class SongAdmin(admin.ModelAdmin):
readonly_fields = ["original_release"]
list_display = ["pk", "original_release"]
list_editable = ["original_release"]
fieldsets = [
(None, {
"fields": ["title", "original_release"],
}),
]
errors = SongAdmin.check(model=Song)
expected = [
checks.Error(
("The value of 'list_editable[0]' refers to 'original_release', "
"which is not editable through the admin."),
hint=None,
obj=SongAdmin,
id='admin.E125',
)
]
self.assertEqual(errors, expected)
def test_editable(self):
class SongAdmin(admin.ModelAdmin):
list_display = ["pk", "title"]
list_editable = ["title"]
fieldsets = [
(None, {
"fields": ["title", "original_release"],
}),
]
errors = SongAdmin.check(model=Song)
self.assertEqual(errors, [])
def test_custom_modelforms_with_fields_fieldsets(self):
"""
# Regression test for #8027: custom ModelForms with fields/fieldsets
"""
errors = ValidFields.check(model=Song)
self.assertEqual(errors, [])
def test_custom_get_form_with_fieldsets(self):
"""
Ensure that the fieldsets checks are skipped when the ModelAdmin.get_form() method
is overridden.
Refs #19445.
"""
errors = ValidFormFieldsets.check(model=Song)
self.assertEqual(errors, [])
def test_fieldsets_fields_non_tuple(self):
"""
Tests for a tuple/list for the first fieldset's fields.
"""
class NotATupleAdmin(admin.ModelAdmin):
list_display = ["pk", "title"]
list_editable = ["title"]
fieldsets = [
(None, {
"fields": "title" # not a tuple
}),
]
errors = NotATupleAdmin.check(model=Song)
expected = [
checks.Error(
"The value of 'fieldsets[0][1]['fields']' must be a list or tuple.",
hint=None,
obj=NotATupleAdmin,
id='admin.E008',
)
]
self.assertEqual(errors, expected)
def test_nonfirst_fieldset(self):
"""
Tests for a tuple/list for the second fieldset's fields.
"""
class NotATupleAdmin(admin.ModelAdmin):
fieldsets = [
(None, {
"fields": ("title",)
}),
('foo', {
"fields": "author" # not a tuple
}),
]
errors = NotATupleAdmin.check(model=Song)
expected = [
checks.Error(
"The value of 'fieldsets[1][1]['fields']' must be a list or tuple.",
hint=None,
obj=NotATupleAdmin,
id='admin.E008',
)
]
self.assertEqual(errors, expected)
def test_exclude_values(self):
"""
Tests for basic system checks of 'exclude' option values (#12689)
"""
class ExcludedFields1(admin.ModelAdmin):
exclude = 'foo'
errors = ExcludedFields1.check(model=Book)
expected = [
checks.Error(
"The value of 'exclude' must be a list or tuple.",
hint=None,
obj=ExcludedFields1,
id='admin.E014',
)
]
self.assertEqual(errors, expected)
def test_exclude_duplicate_values(self):
class ExcludedFields2(admin.ModelAdmin):
exclude = ('name', 'name')
errors = ExcludedFields2.check(model=Book)
expected = [
checks.Error(
"The value of 'exclude' contains duplicate field(s).",
hint=None,
obj=ExcludedFields2,
id='admin.E015',
)
]
self.assertEqual(errors, expected)
def test_exclude_in_inline(self):
class ExcludedFieldsInline(admin.TabularInline):
model = Song
exclude = 'foo'
class ExcludedFieldsAlbumAdmin(admin.ModelAdmin):
model = Album
inlines = [ExcludedFieldsInline]
errors = ExcludedFieldsAlbumAdmin.check(model=Album)
expected = [
checks.Error(
"The value of 'exclude' must be a list or tuple.",
hint=None,
obj=ExcludedFieldsInline,
id='admin.E014',
)
]
self.assertEqual(errors, expected)
def test_exclude_inline_model_admin(self):
"""
Regression test for #9932 - exclude in InlineModelAdmin should not
contain the ForeignKey field used in ModelAdmin.model
"""
class SongInline(admin.StackedInline):
model = Song
exclude = ['album']
class AlbumAdmin(admin.ModelAdmin):
model = Album
inlines = [SongInline]
errors = AlbumAdmin.check(model=Album)
expected = [
checks.Error(
("Cannot exclude the field 'album', because it is the foreign key "
"to the parent model 'admin_checks.Album'."),
hint=None,
obj=SongInline,
id='admin.E201',
)
]
self.assertEqual(errors, expected)
def test_valid_generic_inline_model_admin(self):
"""
Regression test for #22034 - check that generic inlines don't look for
normal ForeignKey relations.
"""
class InfluenceInline(GenericStackedInline):
model = Influence
class SongAdmin(admin.ModelAdmin):
inlines = [InfluenceInline]
errors = SongAdmin.check(model=Song)
self.assertEqual(errors, [])
def test_generic_inline_model_admin_non_generic_model(self):
"""
Ensure that a model without a GenericForeignKey raises problems if it's included
in an GenericInlineModelAdmin definition.
"""
class BookInline(GenericStackedInline):
model = Book
class SongAdmin(admin.ModelAdmin):
inlines = [BookInline]
errors = SongAdmin.check(model=Song)
expected = [
checks.Error(
"'admin_checks.Book' has no GenericForeignKey.",
hint=None,
obj=BookInline,
id='admin.E301',
)
]
self.assertEqual(errors, expected)
def test_generic_inline_model_admin_bad_ct_field(self):
"A GenericInlineModelAdmin raises problems if the ct_field points to a non-existent field."
class InfluenceInline(GenericStackedInline):
model = Influence
ct_field = 'nonexistent'
class SongAdmin(admin.ModelAdmin):
inlines = [InfluenceInline]
errors = SongAdmin.check(model=Song)
expected = [
checks.Error(
"'ct_field' references 'nonexistent', which is not a field on 'admin_checks.Influence'.",
hint=None,
obj=InfluenceInline,
id='admin.E302',
)
]
self.assertEqual(errors, expected)
def test_generic_inline_model_admin_bad_fk_field(self):
"A GenericInlineModelAdmin raises problems if the ct_fk_field points to a non-existent field."
class InfluenceInline(GenericStackedInline):
model = Influence
ct_fk_field = 'nonexistent'
class SongAdmin(admin.ModelAdmin):
inlines = [InfluenceInline]
errors = SongAdmin.check(model=Song)
expected = [
checks.Error(
"'ct_fk_field' references 'nonexistent', which is not a field on 'admin_checks.Influence'.",
hint=None,
obj=InfluenceInline,
id='admin.E303',
)
]
self.assertEqual(errors, expected)
def test_generic_inline_model_admin_non_gfk_ct_field(self):
"A GenericInlineModelAdmin raises problems if the ct_field points to a field that isn't part of a GenericForeignKey"
class InfluenceInline(GenericStackedInline):
model = Influence
ct_field = 'name'
class SongAdmin(admin.ModelAdmin):
inlines = [InfluenceInline]
errors = SongAdmin.check(model=Song)
expected = [
checks.Error(
"'admin_checks.Influence' has no GenericForeignKey using content type field 'name' and object ID field 'object_id'.",
hint=None,
obj=InfluenceInline,
id='admin.E304',
)
]
self.assertEqual(errors, expected)
def test_generic_inline_model_admin_non_gfk_fk_field(self):
"A GenericInlineModelAdmin raises problems if the ct_fk_field points to a field that isn't part of a GenericForeignKey"
class InfluenceInline(GenericStackedInline):
model = Influence
ct_fk_field = 'name'
class SongAdmin(admin.ModelAdmin):
inlines = [InfluenceInline]
errors = SongAdmin.check(model=Song)
expected = [
checks.Error(
"'admin_checks.Influence' has no GenericForeignKey using content type field 'content_type' and object ID field 'name'.",
hint=None,
obj=InfluenceInline,
id='admin.E304',
)
]
self.assertEqual(errors, expected)
def test_app_label_in_admin_checks(self):
"""
Regression test for #15669 - Include app label in admin system check messages
"""
class RawIdNonexistingAdmin(admin.ModelAdmin):
raw_id_fields = ('nonexisting',)
errors = RawIdNonexistingAdmin.check(model=Album)
expected = [
checks.Error(
("The value of 'raw_id_fields[0]' refers to 'nonexisting', which is "
"not an attribute of 'admin_checks.Album'."),
hint=None,
obj=RawIdNonexistingAdmin,
id='admin.E002',
)
]
self.assertEqual(errors, expected)
def test_fk_exclusion(self):
"""
Regression test for #11709 - when testing for fk excluding (when exclude is
given) make sure fk_name is honored or things blow up when there is more
than one fk to the parent model.
"""
class TwoAlbumFKAndAnEInline(admin.TabularInline):
model = TwoAlbumFKAndAnE
exclude = ("e",)
fk_name = "album1"
class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline]
errors = MyAdmin.check(model=Album)
self.assertEqual(errors, [])
def test_inline_self_check(self):
class TwoAlbumFKAndAnEInline(admin.TabularInline):
model = TwoAlbumFKAndAnE
class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline]
errors = MyAdmin.check(model=Album)
expected = [
checks.Error(
"'admin_checks.TwoAlbumFKAndAnE' has more than one ForeignKey to 'admin_checks.Album'.",
hint=None,
obj=TwoAlbumFKAndAnEInline,
id='admin.E202',
)
]
self.assertEqual(errors, expected)
def test_inline_with_specified(self):
class TwoAlbumFKAndAnEInline(admin.TabularInline):
model = TwoAlbumFKAndAnE
fk_name = "album1"
class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline]
errors = MyAdmin.check(model=Album)
self.assertEqual(errors, [])
def test_readonly(self):
class SongAdmin(admin.ModelAdmin):
readonly_fields = ("title",)
errors = SongAdmin.check(model=Song)
self.assertEqual(errors, [])
def test_readonly_on_method(self):
def my_function(obj):
pass
class SongAdmin(admin.ModelAdmin):
readonly_fields = (my_function,)
errors = SongAdmin.check(model=Song)
self.assertEqual(errors, [])
def test_readonly_on_modeladmin(self):
class SongAdmin(admin.ModelAdmin):
readonly_fields = ("readonly_method_on_modeladmin",)
def readonly_method_on_modeladmin(self, obj):
pass
errors = SongAdmin.check(model=Song)
self.assertEqual(errors, [])
def test_readonly_method_on_model(self):
class SongAdmin(admin.ModelAdmin):
readonly_fields = ("readonly_method_on_model",)
errors = SongAdmin.check(model=Song)
self.assertEqual(errors, [])
def test_nonexistent_field(self):
class SongAdmin(admin.ModelAdmin):
readonly_fields = ("title", "nonexistent")
errors = SongAdmin.check(model=Song)
expected = [
checks.Error(
("The value of 'readonly_fields[1]' is not a callable, an attribute "
"of 'SongAdmin', or an attribute of 'admin_checks.Song'."),
hint=None,
obj=SongAdmin,
id='admin.E035',
)
]
self.assertEqual(errors, expected)
def test_nonexistent_field_on_inline(self):
class CityInline(admin.TabularInline):
model = City
readonly_fields = ['i_dont_exist'] # Missing attribute
errors = CityInline.check(State)
expected = [
checks.Error(
("The value of 'readonly_fields[0]' is not a callable, an attribute "
"of 'CityInline', or an attribute of 'admin_checks.City'."),
hint=None,
obj=CityInline,
id='admin.E035',
)
]
self.assertEqual(errors, expected)
def test_extra(self):
class SongAdmin(admin.ModelAdmin):
def awesome_song(self, instance):
if instance.title == "Born to Run":
return "Best Ever!"
return "Status unknown."
errors = SongAdmin.check(model=Song)
self.assertEqual(errors, [])
def test_readonly_lambda(self):
class SongAdmin(admin.ModelAdmin):
readonly_fields = (lambda obj: "test",)
errors = SongAdmin.check(model=Song)
self.assertEqual(errors, [])
def test_graceful_m2m_fail(self):
"""
Regression test for #12203/#12237 - Fail more gracefully when a M2M field that
specifies the 'through' option is included in the 'fields' or the 'fieldsets'
ModelAdmin options.
"""
class BookAdmin(admin.ModelAdmin):
fields = ['authors']
errors = BookAdmin.check(model=Book)
expected = [
checks.Error(
("The value of 'fields' cannot include the ManyToManyField 'authors', "
"because that field manually specifies a relationship model."),
hint=None,
obj=BookAdmin,
id='admin.E013',
)
]
self.assertEqual(errors, expected)
def test_cannot_include_through(self):
class FieldsetBookAdmin(admin.ModelAdmin):
fieldsets = (
('Header 1', {'fields': ('name',)}),
('Header 2', {'fields': ('authors',)}),
)
errors = FieldsetBookAdmin.check(model=Book)
expected = [
checks.Error(
("The value of 'fieldsets[1][1][\"fields\"]' cannot include the ManyToManyField "
"'authors', because that field manually specifies a relationship model."),
hint=None,
obj=FieldsetBookAdmin,
id='admin.E013',
)
]
self.assertEqual(errors, expected)
def test_nested_fields(self):
class NestedFieldsAdmin(admin.ModelAdmin):
fields = ('price', ('name', 'subtitle'))
errors = NestedFieldsAdmin.check(model=Book)
self.assertEqual(errors, [])
def test_nested_fieldsets(self):
class NestedFieldsetAdmin(admin.ModelAdmin):
fieldsets = (
('Main', {'fields': ('price', ('name', 'subtitle'))}),
)
errors = NestedFieldsetAdmin.check(model=Book)
self.assertEqual(errors, [])
def test_explicit_through_override(self):
"""
Regression test for #12209 -- If the explicitly provided through model
is specified as a string, the admin should still be able use
Model.m2m_field.through
"""
class AuthorsInline(admin.TabularInline):
model = Book.authors.through
class BookAdmin(admin.ModelAdmin):
inlines = [AuthorsInline]
errors = BookAdmin.check(model=Book)
self.assertEqual(errors, [])
def test_non_model_fields(self):
"""
Regression for ensuring ModelAdmin.fields can contain non-model fields
that broke with r11737
"""
class SongForm(forms.ModelForm):
extra_data = forms.CharField()
class FieldsOnFormOnlyAdmin(admin.ModelAdmin):
form = SongForm
fields = ['title', 'extra_data']
errors = FieldsOnFormOnlyAdmin.check(model=Song)
self.assertEqual(errors, [])
def test_non_model_first_field(self):
"""
Regression for ensuring ModelAdmin.field can handle first elem being a
non-model field (test fix for UnboundLocalError introduced with r16225).
"""
class SongForm(forms.ModelForm):
extra_data = forms.CharField()
class Meta:
model = Song
fields = '__all__'
class FieldsOnFormOnlyAdmin(admin.ModelAdmin):
form = SongForm
fields = ['extra_data', 'title']
errors = FieldsOnFormOnlyAdmin.check(model=Song)
self.assertEqual(errors, [])
@ignore_warnings(module='django.contrib.admin.options')
def test_validator_compatibility(self):
class MyValidator(object):
def validate(self, cls, model):
raise ImproperlyConfigured("error!")
class MyModelAdmin(admin.ModelAdmin):
validator_class = MyValidator
errors = MyModelAdmin.check(model=Song)
expected = [
checks.Error(
'error!',
hint=None,
obj=MyModelAdmin,
)
]
self.assertEqual(errors, expected)
def test_check_sublists_for_duplicates(self):
class MyModelAdmin(admin.ModelAdmin):
fields = ['state', ['state']]
errors = MyModelAdmin.check(model=Song)
expected = [
checks.Error(
"The value of 'fields' contains duplicate field(s).",
hint=None,
obj=MyModelAdmin,
id='admin.E006'
)
]
self.assertEqual(errors, expected)
def test_check_fieldset_sublists_for_duplicates(self):
class MyModelAdmin(admin.ModelAdmin):
fieldsets = [
(None, {
'fields': ['title', 'album', ('title', 'album')]
}),
]
errors = MyModelAdmin.check(model=Song)
expected = [
checks.Error(
"There are duplicate field(s) in 'fieldsets[0][1]'.",
hint=None,
obj=MyModelAdmin,
id='admin.E012'
)
]
self.assertEqual(errors, expected)
def test_list_filter_works_on_through_field_even_when_apps_not_ready(self):
"""
Ensure list_filter can access reverse fields even when the app registry
is not ready; refs #24146.
"""
class BookAdminWithListFilter(admin.ModelAdmin):
list_filter = ['authorsbooks__featured']
# Temporarily pretending apps are not ready yet. This issue can happen
# if the value of 'list_filter' refers to a 'through__field'.
Book._meta.apps.ready = False
try:
errors = BookAdminWithListFilter.check(model=Book)
self.assertEqual(errors, [])
finally:
Book._meta.apps.ready = True
|
|
# -*- coding: utf-8 -*-
#
# libuv documentation documentation build configuration file, created by
# sphinx-quickstart on Sun Jul 27 11:47:51 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
import re
import sys
def get_libuv_version():
with open('../../include/uv-version.h') as f:
data = f.read()
try:
m = re.search(r"""^#define UV_VERSION_MAJOR (\d+)$""", data, re.MULTILINE)
major = int(m.group(1))
m = re.search(r"""^#define UV_VERSION_MINOR (\d+)$""", data, re.MULTILINE)
minor = int(m.group(1))
m = re.search(r"""^#define UV_VERSION_PATCH (\d+)$""", data, re.MULTILINE)
patch = int(m.group(1))
m = re.search(r"""^#define UV_VERSION_IS_RELEASE (\d)$""", data, re.MULTILINE)
is_release = int(m.group(1))
m = re.search(r"""^#define UV_VERSION_SUFFIX \"(\w*)\"$""", data, re.MULTILINE)
suffix = m.group(1)
return '%d.%d.%d%s' % (major, minor, patch, '-%s' % suffix if not is_release else '')
except Exception:
return 'unknown'
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('sphinx-plugins'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['manpage']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'libuv API documentation'
copyright = u'2014-present, libuv contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = get_libuv_version()
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'nature'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = 'libuv documentation'
# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = 'libuv %s documentation' % version
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = 'static/logo.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = 'static/favicon.ico'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'libuv'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'libuv.tex', u'libuv documentation',
u'libuv contributors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'libuv', u'libuv documentation',
[u'libuv contributors'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'libuv', u'libuv documentation',
u'libuv contributors', 'libuv', 'Cross-platform asynchronous I/O',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u'libuv documentation'
epub_author = u'libuv contributors'
epub_publisher = u'libuv contributors'
epub_copyright = u'2014-present, libuv contributors'
# The basename for the epub file. It defaults to the project name.
epub_basename = u'libuv'
# The HTML theme for the epub output. Since the default themes are not optimized
# for small screen space, using the same theme for HTML and epub output is
# usually not wise. This defaults to 'epub', a theme designed to save visual
# space.
#epub_theme = 'epub'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
# Choose between 'default' and 'includehidden'.
#epub_tocscope = 'default'
# Fix unsupported image types using the PIL.
#epub_fix_images = False
# Scale large images.
#epub_max_image_width = 0
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#epub_show_urls = 'inline'
# If false, no index is generated.
#epub_use_index = True
|
|
"""
Tests for win_file execution module
"""
import pytest
import salt.modules.win_file as win_file
import salt.utils.win_dacl as win_dacl
from salt.exceptions import CommandExecutionError
from tests.support.mock import patch
pytestmark = [
pytest.mark.windows_whitelisted,
pytest.mark.skip_unless_on_windows,
]
@pytest.fixture
def configure_loader_modules():
return {
win_file: {
"__utils__": {
"dacl.check_perms": win_dacl.check_perms,
"dacl.set_perms": win_dacl.set_perms,
}
},
win_dacl: {"__opts__": {"test": False}},
}
@pytest.fixture(scope="function")
def test_file():
with pytest.helpers.temp_file("win_file_test.file") as test_file:
yield test_file
def test_check_perms_set_owner_test_true(test_file):
"""
Test setting the owner of a file with test=True
"""
expected = {
"comment": "",
"changes": {"owner": "Backup Operators"},
"name": str(test_file),
"result": None,
}
with patch.dict(win_dacl.__opts__, {"test": True}):
result = win_file.check_perms(
path=str(test_file), owner="Backup Operators", inheritance=None
)
assert result == expected
def test_check_perms_set_owner(test_file):
"""
Test setting the owner of a file
"""
expected = {
"comment": "",
"changes": {"owner": "Backup Operators"},
"name": str(test_file),
"result": True,
}
result = win_file.check_perms(
path=str(test_file), owner="Backup Operators", inheritance=None
)
assert result == expected
def test_check_perms_deny_test_true(test_file):
"""
Test setting deny perms on a file with test=True
"""
expected = {
"comment": "",
"changes": {"deny_perms": {"Users": {"permissions": "read_execute"}}},
"name": str(test_file),
"result": None,
}
with patch.dict(win_dacl.__opts__, {"test": True}):
result = win_file.check_perms(
path=str(test_file),
deny_perms={"Users": {"perms": "read_execute"}},
inheritance=None,
)
assert result == expected
def test_check_perms_deny(test_file):
"""
Test setting deny perms on a file
"""
expected = {
"comment": "",
"changes": {"deny_perms": {"Users": {"permissions": "read_execute"}}},
"name": str(test_file),
"result": True,
}
result = win_file.check_perms(
path=str(test_file),
deny_perms={"Users": {"perms": "read_execute"}},
inheritance=None,
)
assert result == expected
def test_check_perms_grant_test_true(test_file):
"""
Test setting grant perms on a file with test=True
"""
expected = {
"comment": "",
"changes": {"grant_perms": {"Users": {"permissions": "read_execute"}}},
"name": str(test_file),
"result": None,
}
with patch.dict(win_dacl.__opts__, {"test": True}):
result = win_file.check_perms(
path=str(test_file),
grant_perms={"Users": {"perms": "read_execute"}},
inheritance=None,
)
assert result == expected
def test_check_perms_grant(test_file):
"""
Test setting grant perms on a file
"""
expected = {
"comment": "",
"changes": {"grant_perms": {"Users": {"permissions": "read_execute"}}},
"name": str(test_file),
"result": True,
}
result = win_file.check_perms(
path=str(test_file),
grant_perms={"Users": {"perms": "read_execute"}},
inheritance=None,
)
assert result == expected
def test_check_perms_inheritance_false_test_true(test_file):
"""
Test setting inheritance to False with test=True
"""
expected = {
"comment": "",
"changes": {"inheritance": False},
"name": str(test_file),
"result": None,
}
with patch.dict(win_dacl.__opts__, {"test": True}):
result = win_file.check_perms(path=str(test_file), inheritance=False)
assert result == expected
def test_check_perms_inheritance_false(test_file):
"""
Test setting inheritance to False
"""
expected = {
"comment": "",
"changes": {"inheritance": False},
"name": str(test_file),
"result": True,
}
result = win_file.check_perms(path=str(test_file), inheritance=False)
assert result == expected
def test_check_perms_inheritance_true(test_file):
"""
Test setting inheritance to true when it's already true (default)
"""
expected = {
"comment": "",
"changes": {},
"name": str(test_file),
"result": True,
}
result = win_file.check_perms(path=str(test_file), inheritance=True)
assert result == expected
def test_check_perms_reset_test_true(test_file):
"""
Test resetting perms with test=True. This shows minimal changes
"""
# Turn off inheritance
win_dacl.set_inheritance(obj_name=str(test_file), enabled=False, clear=True)
# Set some permissions
win_dacl.set_permissions(
obj_name=str(test_file),
principal="Administrator",
permissions="full_control",
)
expected = {
"comment": "",
"changes": {
"grant_perms": {
"Administrators": {"permissions": "full_control"},
"Users": {"permissions": "read_execute"},
},
"remove_perms": {
"Administrator": {
"grant": {
"applies to": "This folder only",
"permissions": "Full control",
}
}
},
},
"name": str(test_file),
"result": None,
}
with patch.dict(win_dacl.__opts__, {"test": True}):
result = win_file.check_perms(
path=str(test_file),
grant_perms={
"Users": {"perms": "read_execute"},
"Administrators": {"perms": "full_control"},
},
inheritance=False,
reset=True,
)
assert result == expected
def test_check_perms_reset(test_file):
"""
Test resetting perms on a File
"""
# Turn off inheritance
win_dacl.set_inheritance(obj_name=str(test_file), enabled=False, clear=True)
# Set some permissions
win_dacl.set_permissions(
obj_name=str(test_file),
principal="Administrator",
permissions="full_control",
)
expected = {
"comment": "",
"changes": {
"grant_perms": {
"Administrators": {"permissions": "full_control"},
"Users": {"permissions": "read_execute"},
},
"remove_perms": {
"Administrator": {
"grant": {
"applies to": "This folder only",
"permissions": "Full control",
}
}
},
},
"name": str(test_file),
"result": True,
}
result = win_file.check_perms(
path=str(test_file),
grant_perms={
"Users": {"perms": "read_execute"},
"Administrators": {"perms": "full_control"},
},
inheritance=False,
reset=True,
)
assert result == expected
def test_check_perms_issue_43328(test_file):
"""
Make sure that a CommandExecutionError is raised if the file does NOT
exist
"""
fake_file = test_file.parent / "fake.file"
with pytest.raises(CommandExecutionError):
win_file.check_perms(str(fake_file))
|
|
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=unused-argument
import six
import mock
from pyfakefs import fake_filesystem_unittest
from py_utils import cloud_storage
import dependency_manager
from dependency_manager import exceptions
class DependencyManagerTest(fake_filesystem_unittest.TestCase):
def setUp(self):
self.lp_info012 = dependency_manager.LocalPathInfo(
['path0', 'path1', 'path2'])
self.cloud_storage_info = dependency_manager.CloudStorageInfo(
'cs_bucket', 'cs_hash', 'download_path', 'cs_remote_path')
self.dep_info = dependency_manager.DependencyInfo(
'dep', 'platform', 'config_file', local_path_info=self.lp_info012,
cloud_storage_info=self.cloud_storage_info)
self.setUpPyfakefs()
def tearDown(self):
self.tearDownPyfakefs()
# TODO(crbug.com/1111556): add a test that construct
# dependency_manager.DependencyManager from a list of DependencyInfo.
def testErrorInit(self):
with self.assertRaises(ValueError):
dependency_manager.DependencyManager(None)
with self.assertRaises(ValueError):
dependency_manager.DependencyManager('config_file?')
def testInitialUpdateDependencies(self):
dep_manager = dependency_manager.DependencyManager([])
# Empty BaseConfig.
dep_manager._lookup_dict = {}
base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)
base_config_mock.IterDependencyInfo.return_value = iter([])
dep_manager._UpdateDependencies(base_config_mock)
self.assertFalse(dep_manager._lookup_dict)
# One dependency/platform in a BaseConfig.
dep_manager._lookup_dict = {}
base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)
dep_info = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep = 'dependency'
plat = 'platform'
dep_info.dependency = dep
dep_info.platform = plat
base_config_mock.IterDependencyInfo.return_value = iter([dep_info])
expected_lookup_dict = {dep: {plat: dep_info}}
dep_manager._UpdateDependencies(base_config_mock)
self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
self.assertFalse(dep_info.Update.called)
# One dependency multiple platforms in a BaseConfig.
dep_manager._lookup_dict = {}
base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)
dep = 'dependency'
plat1 = 'platform1'
plat2 = 'platform2'
dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info1.dependency = dep
dep_info1.platform = plat1
dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info2.dependency = dep
dep_info2.platform = plat2
base_config_mock.IterDependencyInfo.return_value = iter([dep_info1,
dep_info2])
expected_lookup_dict = {dep: {plat1: dep_info1,
plat2: dep_info2}}
dep_manager._UpdateDependencies(base_config_mock)
self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
self.assertFalse(dep_info1.Update.called)
self.assertFalse(dep_info2.Update.called)
# Multiple dependencies, multiple platforms in a BaseConfig.
dep_manager._lookup_dict = {}
base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)
dep1 = 'dependency1'
dep2 = 'dependency2'
plat1 = 'platform1'
plat2 = 'platform2'
dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info1.dependency = dep1
dep_info1.platform = plat1
dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info2.dependency = dep1
dep_info2.platform = plat2
dep_info3 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info3.dependency = dep2
dep_info3.platform = plat2
base_config_mock.IterDependencyInfo.return_value = iter(
[dep_info1, dep_info2, dep_info3])
expected_lookup_dict = {dep1: {plat1: dep_info1,
plat2: dep_info2},
dep2: {plat2: dep_info3}}
dep_manager._UpdateDependencies(base_config_mock)
self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
self.assertFalse(dep_info1.Update.called)
self.assertFalse(dep_info2.Update.called)
self.assertFalse(dep_info3.Update.called)
def testFollowupUpdateDependenciesNoOverlap(self):
dep_manager = dependency_manager.DependencyManager([])
dep = 'dependency'
dep1 = 'dependency1'
dep2 = 'dependency2'
dep3 = 'dependency3'
plat1 = 'platform1'
plat2 = 'platform2'
plat3 = 'platform3'
dep_info_a = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info_a.dependency = dep1
dep_info_a.platform = plat1
dep_info_b = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info_b.dependency = dep1
dep_info_b.platform = plat2
dep_info_c = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info_c.dependency = dep
dep_info_c.platform = plat1
start_lookup_dict = {dep: {plat1: dep_info_a,
plat2: dep_info_b},
dep1: {plat1: dep_info_c}}
base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)
# Empty BaseConfig.
dep_manager._lookup_dict = start_lookup_dict.copy()
base_config_mock.IterDependencyInfo.return_value = iter([])
dep_manager._UpdateDependencies(base_config_mock)
self.assertEqual(start_lookup_dict, dep_manager._lookup_dict)
# One dependency/platform in a BaseConfig.
dep_manager._lookup_dict = start_lookup_dict.copy()
dep_info = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info.dependency = dep3
dep_info.platform = plat1
base_config_mock.IterDependencyInfo.return_value = iter([dep_info])
expected_lookup_dict = {dep: {plat1: dep_info_a,
plat2: dep_info_b},
dep1: {plat1: dep_info_c},
dep3: {plat3: dep_info}}
dep_manager._UpdateDependencies(base_config_mock)
six.assertCountEqual(self, expected_lookup_dict, dep_manager._lookup_dict)
self.assertFalse(dep_info.Update.called)
self.assertFalse(dep_info_a.Update.called)
self.assertFalse(dep_info_b.Update.called)
self.assertFalse(dep_info_c.Update.called)
# One dependency multiple platforms in a BaseConfig.
dep_manager._lookup_dict = start_lookup_dict.copy()
dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info1.dependency = dep2
dep_info1.platform = plat1
dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info2.dependency = dep2
dep_info2.platform = plat2
base_config_mock.IterDependencyInfo.return_value = iter([dep_info1,
dep_info2])
expected_lookup_dict = {dep: {plat1: dep_info_a,
plat2: dep_info_b},
dep1: {plat1: dep_info_c},
dep2: {plat1: dep_info1,
plat2: dep_info2}}
dep_manager._UpdateDependencies(base_config_mock)
self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
self.assertFalse(dep_info1.Update.called)
self.assertFalse(dep_info2.Update.called)
self.assertFalse(dep_info_a.Update.called)
self.assertFalse(dep_info_b.Update.called)
self.assertFalse(dep_info_c.Update.called)
# Multiple dependencies, multiple platforms in a BaseConfig.
dep_manager._lookup_dict = start_lookup_dict.copy()
dep1 = 'dependency1'
plat1 = 'platform1'
plat2 = 'platform2'
dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info1.dependency = dep2
dep_info1.platform = plat1
dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info2.dependency = dep2
dep_info2.platform = plat2
dep_info3 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info3.dependency = dep3
dep_info3.platform = plat2
base_config_mock.IterDependencyInfo.return_value = iter(
[dep_info1, dep_info2, dep_info3])
expected_lookup_dict = {dep: {plat1: dep_info_a,
plat2: dep_info_b},
dep1: {plat1: dep_info_c},
dep2: {plat1: dep_info1,
plat2: dep_info2},
dep3: {plat2: dep_info3}}
dep_manager._UpdateDependencies(base_config_mock)
self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
self.assertFalse(dep_info1.Update.called)
self.assertFalse(dep_info2.Update.called)
self.assertFalse(dep_info3.Update.called)
self.assertFalse(dep_info_a.Update.called)
self.assertFalse(dep_info_b.Update.called)
self.assertFalse(dep_info_c.Update.called)
# Ensure the testing data wasn't corrupted.
self.assertEqual(start_lookup_dict,
{dep: {plat1: dep_info_a,
plat2: dep_info_b},
dep1: {plat1: dep_info_c}})
def testFollowupUpdateDependenciesWithCollisions(self):
dep_manager = dependency_manager.DependencyManager([])
dep = 'dependency'
dep1 = 'dependency1'
dep2 = 'dependency2'
plat1 = 'platform1'
plat2 = 'platform2'
dep_info_a = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info_a.dependency = dep1
dep_info_a.platform = plat1
dep_info_b = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info_b.dependency = dep1
dep_info_b.platform = plat2
dep_info_c = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info_c.dependency = dep
dep_info_c.platform = plat1
start_lookup_dict = {dep: {plat1: dep_info_a,
plat2: dep_info_b},
dep1: {plat1: dep_info_c}}
base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)
# One dependency/platform.
dep_manager._lookup_dict = start_lookup_dict.copy()
dep_info = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info.dependency = dep
dep_info.platform = plat1
base_config_mock.IterDependencyInfo.return_value = iter([dep_info])
expected_lookup_dict = {dep: {plat1: dep_info_a,
plat2: dep_info_b},
dep1: {plat1: dep_info_c}}
dep_manager._UpdateDependencies(base_config_mock)
six.assertCountEqual(self, expected_lookup_dict, dep_manager._lookup_dict)
dep_info_a.Update.assert_called_once_with(dep_info)
self.assertFalse(dep_info.Update.called)
self.assertFalse(dep_info_b.Update.called)
self.assertFalse(dep_info_c.Update.called)
dep_info_a.reset_mock()
dep_info_b.reset_mock()
dep_info_c.reset_mock()
# One dependency multiple platforms in a BaseConfig.
dep_manager._lookup_dict = start_lookup_dict.copy()
dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info1.dependency = dep1
dep_info1.platform = plat1
dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info2.dependency = dep2
dep_info2.platform = plat2
base_config_mock.IterDependencyInfo.return_value = iter([dep_info1,
dep_info2])
expected_lookup_dict = {dep: {plat1: dep_info_a,
plat2: dep_info_b},
dep1: {plat1: dep_info_c},
dep2: {plat2: dep_info2}}
dep_manager._UpdateDependencies(base_config_mock)
self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
self.assertFalse(dep_info1.Update.called)
self.assertFalse(dep_info2.Update.called)
self.assertFalse(dep_info_a.Update.called)
self.assertFalse(dep_info_b.Update.called)
dep_info_c.Update.assert_called_once_with(dep_info1)
dep_info_a.reset_mock()
dep_info_b.reset_mock()
dep_info_c.reset_mock()
# Multiple dependencies, multiple platforms in a BaseConfig.
dep_manager._lookup_dict = start_lookup_dict.copy()
dep1 = 'dependency1'
plat1 = 'platform1'
plat2 = 'platform2'
dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info1.dependency = dep
dep_info1.platform = plat1
dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info2.dependency = dep1
dep_info2.platform = plat1
dep_info3 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info3.dependency = dep2
dep_info3.platform = plat2
base_config_mock.IterDependencyInfo.return_value = iter(
[dep_info1, dep_info2, dep_info3])
expected_lookup_dict = {dep: {plat1: dep_info_a,
plat2: dep_info_b},
dep1: {plat1: dep_info_c},
dep2: {plat2: dep_info3}}
dep_manager._UpdateDependencies(base_config_mock)
self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
self.assertFalse(dep_info1.Update.called)
self.assertFalse(dep_info2.Update.called)
self.assertFalse(dep_info3.Update.called)
self.assertFalse(dep_info_b.Update.called)
dep_info_a.Update.assert_called_once_with(dep_info1)
dep_info_c.Update.assert_called_once_with(dep_info2)
# Collision error.
dep_manager._lookup_dict = start_lookup_dict.copy()
dep_info = mock.MagicMock(spec=dependency_manager.DependencyInfo)
dep_info.dependency = dep
dep_info.platform = plat1
base_config_mock.IterDependencyInfo.return_value = iter([dep_info])
dep_info_a.Update.side_effect = ValueError
self.assertRaises(ValueError,
dep_manager._UpdateDependencies, base_config_mock)
# Ensure the testing data wasn't corrupted.
self.assertEqual(start_lookup_dict,
{dep: {plat1: dep_info_a,
plat2: dep_info_b},
dep1: {plat1: dep_info_c}})
def testGetDependencyInfo(self):
dep_manager = dependency_manager.DependencyManager([])
self.assertFalse(dep_manager._lookup_dict)
# No dependencies in the dependency manager.
self.assertEqual(None, dep_manager._GetDependencyInfo('missing_dep',
'missing_plat'))
dep_manager._lookup_dict = {'dep1': {'plat1': 'dep_info11',
'plat2': 'dep_info12',
'plat3': 'dep_info13'},
'dep2': {'plat1': 'dep_info11',
'plat2': 'dep_info21',
'plat3': 'dep_info23',
'default': 'dep_info2d'},
'dep3': {'plat1': 'dep_info31',
'plat2': 'dep_info32',
'default': 'dep_info3d'}}
# Dependency not in the dependency manager.
self.assertEqual(None, dep_manager._GetDependencyInfo(
'missing_dep', 'missing_plat'))
# Dependency in the dependency manager, but not the platform. No default.
self.assertEqual(None, dep_manager._GetDependencyInfo(
'dep1', 'missing_plat'))
# Dependency in the dependency manager, but not the platform, but a default
# exists.
self.assertEqual('dep_info2d', dep_manager._GetDependencyInfo(
'dep2', 'missing_plat'))
# Dependency and platform in the dependency manager. A default exists.
self.assertEqual('dep_info23', dep_manager._GetDependencyInfo(
'dep2', 'plat3'))
# Dependency and platform in the dependency manager. No default exists.
self.assertEqual('dep_info12', dep_manager._GetDependencyInfo(
'dep1', 'plat2'))
@mock.patch(
'dependency_manager.dependency_info.DependencyInfo.GetRemotePath') # pylint: disable=line-too-long
def testFetchPathUnititializedDependency(
self, cs_path_mock):
dep_manager = dependency_manager.DependencyManager([])
self.assertFalse(cs_path_mock.call_args)
cs_path = 'cs_path'
cs_path_mock.return_value = cs_path
# Empty lookup_dict
with self.assertRaises(exceptions.NoPathFoundError):
dep_manager.FetchPath('dep', 'plat_arch_x86')
# Non-empty lookup dict that doesn't contain the dependency we're looking
# for.
dep_manager._lookup_dict = {'dep1': mock.MagicMock(),
'dep2': mock.MagicMock()}
with self.assertRaises(exceptions.NoPathFoundError):
dep_manager.FetchPath('dep', 'plat_arch_x86')
@mock.patch('os.path')
@mock.patch(
'dependency_manager.DependencyManager._GetDependencyInfo')
@mock.patch(
'dependency_manager.dependency_info.DependencyInfo.GetRemotePath') # pylint: disable=line-too-long
def testFetchPathLocalFile(self, cs_path_mock, dep_info_mock, path_mock):
dep_manager = dependency_manager.DependencyManager([])
self.assertFalse(cs_path_mock.call_args)
cs_path = 'cs_path'
dep_info = self.dep_info
cs_path_mock.return_value = cs_path
# The DependencyInfo returned should be passed through to LocalPath.
dep_info_mock.return_value = dep_info
# Non-empty lookup dict that contains the dependency we're looking for.
# Local path exists.
dep_manager._lookup_dict = {'dep': {'platform' : self.dep_info},
'dep2': mock.MagicMock()}
self.fs.CreateFile('path1')
found_path = dep_manager.FetchPath('dep', 'platform')
self.assertEqual('path1', found_path)
self.assertFalse(cs_path_mock.call_args)
@mock.patch(
'dependency_manager.dependency_info.DependencyInfo.GetRemotePath') # pylint: disable=line-too-long
def testFetchPathRemoteFile(
self, cs_path_mock):
dep_manager = dependency_manager.DependencyManager([])
self.assertFalse(cs_path_mock.call_args)
cs_path = 'cs_path'
def FakeCSPath():
self.fs.CreateFile(cs_path)
return cs_path
cs_path_mock.side_effect = FakeCSPath
# Non-empty lookup dict that contains the dependency we're looking for.
# Local path doesn't exist, but cloud_storage_path is downloaded.
dep_manager._lookup_dict = {'dep': {'platform' : self.dep_info,
'plat1': mock.MagicMock()},
'dep2': {'plat2': mock.MagicMock()}}
found_path = dep_manager.FetchPath('dep', 'platform')
self.assertEqual(cs_path, found_path)
@mock.patch(
'dependency_manager.dependency_info.DependencyInfo.GetRemotePath') # pylint: disable=line-too-long
def testFetchPathError(
self, cs_path_mock):
dep_manager = dependency_manager.DependencyManager([])
self.assertFalse(cs_path_mock.call_args)
cs_path_mock.return_value = None
dep_manager._lookup_dict = {'dep': {'platform' : self.dep_info,
'plat1': mock.MagicMock()},
'dep2': {'plat2': mock.MagicMock()}}
# Non-empty lookup dict that contains the dependency we're looking for.
# Local path doesn't exist, and cloud_storage path wasn't successfully
# found.
self.assertRaises(exceptions.NoPathFoundError,
dep_manager.FetchPath, 'dep', 'platform')
cs_path_mock.side_effect = cloud_storage.CredentialsError
self.assertRaises(cloud_storage.CredentialsError,
dep_manager.FetchPath, 'dep', 'platform')
cs_path_mock.side_effect = cloud_storage.CloudStorageError
self.assertRaises(cloud_storage.CloudStorageError,
dep_manager.FetchPath, 'dep', 'platform')
cs_path_mock.side_effect = cloud_storage.PermissionError
self.assertRaises(cloud_storage.PermissionError,
dep_manager.FetchPath, 'dep', 'platform')
def testLocalPath(self):
dep_manager = dependency_manager.DependencyManager([])
# Empty lookup_dict
with self.assertRaises(exceptions.NoPathFoundError):
dep_manager.LocalPath('dep', 'plat')
def testLocalPathNoDependency(self):
# Non-empty lookup dict that doesn't contain the dependency we're looking
# for.
dep_manager = dependency_manager.DependencyManager([])
dep_manager._lookup_dict = {'dep1': mock.MagicMock(),
'dep2': mock.MagicMock()}
with self.assertRaises(exceptions.NoPathFoundError):
dep_manager.LocalPath('dep', 'plat')
def testLocalPathExists(self):
# Non-empty lookup dict that contains the dependency we're looking for.
# Local path exists.
dep_manager = dependency_manager.DependencyManager([])
dep_manager._lookup_dict = {'dependency' : {'platform': self.dep_info},
'dep1': mock.MagicMock(),
'dep2': mock.MagicMock()}
self.fs.CreateFile('path1')
found_path = dep_manager.LocalPath('dependency', 'platform')
self.assertEqual('path1', found_path)
def testLocalPathMissingPaths(self):
# Non-empty lookup dict that contains the dependency we're looking for.
# Local path is found but doesn't exist.
dep_manager = dependency_manager.DependencyManager([])
dep_manager._lookup_dict = {'dependency' : {'platform': self.dep_info},
'dep1': mock.MagicMock(),
'dep2': mock.MagicMock()}
self.assertRaises(exceptions.NoPathFoundError,
dep_manager.LocalPath, 'dependency', 'platform')
def testLocalPathNoPaths(self):
# Non-empty lookup dict that contains the dependency we're looking for.
# Local path isn't found.
dep_manager = dependency_manager.DependencyManager([])
dep_info = dependency_manager.DependencyInfo(
'dep', 'platform', 'config_file',
cloud_storage_info=self.cloud_storage_info)
dep_manager._lookup_dict = {'dependency' : {'platform': dep_info},
'dep1': mock.MagicMock(),
'dep2': mock.MagicMock()}
self.assertRaises(exceptions.NoPathFoundError,
dep_manager.LocalPath, 'dependency', 'platform')
|
|
# -*- coding: utf-8 -*-
# pylint: disable-msg=E1101,W0612
from copy import copy, deepcopy
from warnings import catch_warnings, simplefilter
import numpy as np
import pytest
from pandas.compat import PY3, range, zip
from pandas.core.dtypes.common import is_scalar
import pandas as pd
from pandas import DataFrame, MultiIndex, Panel, Series, date_range
import pandas.util.testing as tm
from pandas.util.testing import (
assert_frame_equal, assert_panel_equal, assert_series_equal)
import pandas.io.formats.printing as printing
# ----------------------------------------------------------------------
# Generic types test cases
class Generic(object):
@property
def _ndim(self):
return self._typ._AXIS_LEN
def _axes(self):
""" return the axes for my object typ """
return self._typ._AXIS_ORDERS
def _construct(self, shape, value=None, dtype=None, **kwargs):
""" construct an object for the given shape
if value is specified use that if its a scalar
if value is an array, repeat it as needed """
if isinstance(shape, int):
shape = tuple([shape] * self._ndim)
if value is not None:
if is_scalar(value):
if value == 'empty':
arr = None
# remove the info axis
kwargs.pop(self._typ._info_axis_name, None)
else:
arr = np.empty(shape, dtype=dtype)
arr.fill(value)
else:
fshape = np.prod(shape)
arr = value.ravel()
new_shape = fshape / arr.shape[0]
if fshape % arr.shape[0] != 0:
raise Exception("invalid value passed in _construct")
arr = np.repeat(arr, new_shape).reshape(shape)
else:
arr = np.random.randn(*shape)
return self._typ(arr, dtype=dtype, **kwargs)
def _compare(self, result, expected):
self._comparator(result, expected)
def test_rename(self):
# single axis
idx = list('ABCD')
# relabeling values passed into self.rename
args = [
str.lower,
{x: x.lower() for x in idx},
Series({x: x.lower() for x in idx}),
]
for axis in self._axes():
kwargs = {axis: idx}
obj = self._construct(4, **kwargs)
for arg in args:
# rename a single axis
result = obj.rename(**{axis: arg})
expected = obj.copy()
setattr(expected, axis, list('abcd'))
self._compare(result, expected)
# multiple axes at once
def test_get_numeric_data(self):
n = 4
kwargs = {self._typ._AXIS_NAMES[i]: list(range(n))
for i in range(self._ndim)}
# get the numeric data
o = self._construct(n, **kwargs)
result = o._get_numeric_data()
self._compare(result, o)
# non-inclusion
result = o._get_bool_data()
expected = self._construct(n, value='empty', **kwargs)
self._compare(result, expected)
# get the bool data
arr = np.array([True, True, False, True])
o = self._construct(n, value=arr, **kwargs)
result = o._get_numeric_data()
self._compare(result, o)
# _get_numeric_data is includes _get_bool_data, so can't test for
# non-inclusion
def test_get_default(self):
# GH 7725
d0 = "a", "b", "c", "d"
d1 = np.arange(4, dtype='int64')
others = "e", 10
for data, index in ((d0, d1), (d1, d0)):
s = Series(data, index=index)
for i, d in zip(index, data):
assert s.get(i) == d
assert s.get(i, d) == d
assert s.get(i, "z") == d
for other in others:
assert s.get(other, "z") == "z"
assert s.get(other, other) == other
def test_nonzero(self):
# GH 4633
# look at the boolean/nonzero behavior for objects
obj = self._construct(shape=4)
pytest.raises(ValueError, lambda: bool(obj == 0))
pytest.raises(ValueError, lambda: bool(obj == 1))
pytest.raises(ValueError, lambda: bool(obj))
obj = self._construct(shape=4, value=1)
pytest.raises(ValueError, lambda: bool(obj == 0))
pytest.raises(ValueError, lambda: bool(obj == 1))
pytest.raises(ValueError, lambda: bool(obj))
obj = self._construct(shape=4, value=np.nan)
pytest.raises(ValueError, lambda: bool(obj == 0))
pytest.raises(ValueError, lambda: bool(obj == 1))
pytest.raises(ValueError, lambda: bool(obj))
# empty
obj = self._construct(shape=0)
pytest.raises(ValueError, lambda: bool(obj))
# invalid behaviors
obj1 = self._construct(shape=4, value=1)
obj2 = self._construct(shape=4, value=1)
def f():
if obj1:
printing.pprint_thing("this works and shouldn't")
pytest.raises(ValueError, f)
pytest.raises(ValueError, lambda: obj1 and obj2)
pytest.raises(ValueError, lambda: obj1 or obj2)
pytest.raises(ValueError, lambda: not obj1)
def test_downcast(self):
# test close downcasting
o = self._construct(shape=4, value=9, dtype=np.int64)
result = o.copy()
result._data = o._data.downcast(dtypes='infer')
self._compare(result, o)
o = self._construct(shape=4, value=9.)
expected = o.astype(np.int64)
result = o.copy()
result._data = o._data.downcast(dtypes='infer')
self._compare(result, expected)
o = self._construct(shape=4, value=9.5)
result = o.copy()
result._data = o._data.downcast(dtypes='infer')
self._compare(result, o)
# are close
o = self._construct(shape=4, value=9.000000000005)
result = o.copy()
result._data = o._data.downcast(dtypes='infer')
expected = o.astype(np.int64)
self._compare(result, expected)
def test_constructor_compound_dtypes(self):
# see gh-5191
# Compound dtypes should raise NotImplementedError.
def f(dtype):
return self._construct(shape=3, value=1, dtype=dtype)
pytest.raises(NotImplementedError, f, [("A", "datetime64[h]"),
("B", "str"),
("C", "int32")])
# these work (though results may be unexpected)
f('int64')
f('float64')
f('M8[ns]')
def check_metadata(self, x, y=None):
for m in x._metadata:
v = getattr(x, m, None)
if y is None:
assert v is None
else:
assert v == getattr(y, m, None)
def test_metadata_propagation(self):
# check that the metadata matches up on the resulting ops
o = self._construct(shape=3)
o.name = 'foo'
o2 = self._construct(shape=3)
o2.name = 'bar'
# TODO
# Once panel can do non-trivial combine operations
# (currently there is an a raise in the Panel arith_ops to prevent
# this, though it actually does work)
# can remove all of these try: except: blocks on the actual operations
# ----------
# preserving
# ----------
# simple ops with scalars
for op in ['__add__', '__sub__', '__truediv__', '__mul__']:
result = getattr(o, op)(1)
self.check_metadata(o, result)
# ops with like
for op in ['__add__', '__sub__', '__truediv__', '__mul__']:
try:
result = getattr(o, op)(o)
self.check_metadata(o, result)
except (ValueError, AttributeError):
pass
# simple boolean
for op in ['__eq__', '__le__', '__ge__']:
v1 = getattr(o, op)(o)
self.check_metadata(o, v1)
try:
self.check_metadata(o, v1 & v1)
except (ValueError):
pass
try:
self.check_metadata(o, v1 | v1)
except (ValueError):
pass
# combine_first
try:
result = o.combine_first(o2)
self.check_metadata(o, result)
except (AttributeError):
pass
# ---------------------------
# non-preserving (by default)
# ---------------------------
# add non-like
try:
result = o + o2
self.check_metadata(result)
except (ValueError, AttributeError):
pass
# simple boolean
for op in ['__eq__', '__le__', '__ge__']:
# this is a name matching op
v1 = getattr(o, op)(o)
v2 = getattr(o, op)(o2)
self.check_metadata(v2)
try:
self.check_metadata(v1 & v2)
except (ValueError):
pass
try:
self.check_metadata(v1 | v2)
except (ValueError):
pass
def test_head_tail(self):
# GH5370
o = self._construct(shape=10)
# check all index types
for index in [tm.makeFloatIndex, tm.makeIntIndex, tm.makeStringIndex,
tm.makeUnicodeIndex, tm.makeDateIndex,
tm.makePeriodIndex]:
axis = o._get_axis_name(0)
setattr(o, axis, index(len(getattr(o, axis))))
# Panel + dims
try:
o.head()
except (NotImplementedError):
pytest.skip('not implemented on {0}'.format(
o.__class__.__name__))
self._compare(o.head(), o.iloc[:5])
self._compare(o.tail(), o.iloc[-5:])
# 0-len
self._compare(o.head(0), o.iloc[0:0])
self._compare(o.tail(0), o.iloc[0:0])
# bounded
self._compare(o.head(len(o) + 1), o)
self._compare(o.tail(len(o) + 1), o)
# neg index
self._compare(o.head(-3), o.head(7))
self._compare(o.tail(-3), o.tail(7))
def test_sample(self):
# Fixes issue: 2419
o = self._construct(shape=10)
###
# Check behavior of random_state argument
###
# Check for stability when receives seed or random state -- run 10
# times.
for test in range(10):
seed = np.random.randint(0, 100)
self._compare(
o.sample(n=4, random_state=seed), o.sample(n=4,
random_state=seed))
self._compare(
o.sample(frac=0.7, random_state=seed), o.sample(
frac=0.7, random_state=seed))
self._compare(
o.sample(n=4, random_state=np.random.RandomState(test)),
o.sample(n=4, random_state=np.random.RandomState(test)))
self._compare(
o.sample(frac=0.7, random_state=np.random.RandomState(test)),
o.sample(frac=0.7, random_state=np.random.RandomState(test)))
os1, os2 = [], []
for _ in range(2):
np.random.seed(test)
os1.append(o.sample(n=4))
os2.append(o.sample(frac=0.7))
self._compare(*os1)
self._compare(*os2)
# Check for error when random_state argument invalid.
with pytest.raises(ValueError):
o.sample(random_state='astring!')
###
# Check behavior of `frac` and `N`
###
# Giving both frac and N throws error
with pytest.raises(ValueError):
o.sample(n=3, frac=0.3)
# Check that raises right error for negative lengths
with pytest.raises(ValueError):
o.sample(n=-3)
with pytest.raises(ValueError):
o.sample(frac=-0.3)
# Make sure float values of `n` give error
with pytest.raises(ValueError):
o.sample(n=3.2)
# Check lengths are right
assert len(o.sample(n=4) == 4)
assert len(o.sample(frac=0.34) == 3)
assert len(o.sample(frac=0.36) == 4)
###
# Check weights
###
# Weight length must be right
with pytest.raises(ValueError):
o.sample(n=3, weights=[0, 1])
with pytest.raises(ValueError):
bad_weights = [0.5] * 11
o.sample(n=3, weights=bad_weights)
with pytest.raises(ValueError):
bad_weight_series = Series([0, 0, 0.2])
o.sample(n=4, weights=bad_weight_series)
# Check won't accept negative weights
with pytest.raises(ValueError):
bad_weights = [-0.1] * 10
o.sample(n=3, weights=bad_weights)
# Check inf and -inf throw errors:
with pytest.raises(ValueError):
weights_with_inf = [0.1] * 10
weights_with_inf[0] = np.inf
o.sample(n=3, weights=weights_with_inf)
with pytest.raises(ValueError):
weights_with_ninf = [0.1] * 10
weights_with_ninf[0] = -np.inf
o.sample(n=3, weights=weights_with_ninf)
# All zeros raises errors
zero_weights = [0] * 10
with pytest.raises(ValueError):
o.sample(n=3, weights=zero_weights)
# All missing weights
nan_weights = [np.nan] * 10
with pytest.raises(ValueError):
o.sample(n=3, weights=nan_weights)
# Check np.nan are replaced by zeros.
weights_with_nan = [np.nan] * 10
weights_with_nan[5] = 0.5
self._compare(
o.sample(n=1, axis=0, weights=weights_with_nan), o.iloc[5:6])
# Check None are also replaced by zeros.
weights_with_None = [None] * 10
weights_with_None[5] = 0.5
self._compare(
o.sample(n=1, axis=0, weights=weights_with_None), o.iloc[5:6])
def test_size_compat(self):
# GH8846
# size property should be defined
o = self._construct(shape=10)
assert o.size == np.prod(o.shape)
assert o.size == 10 ** len(o.axes)
def test_split_compat(self):
# xref GH8846
o = self._construct(shape=10)
assert len(np.array_split(o, 5)) == 5
assert len(np.array_split(o, 2)) == 2
def test_unexpected_keyword(self): # GH8597
df = DataFrame(np.random.randn(5, 2), columns=['jim', 'joe'])
ca = pd.Categorical([0, 0, 2, 2, 3, np.nan])
ts = df['joe'].copy()
ts[2] = np.nan
with pytest.raises(TypeError, match='unexpected keyword'):
df.drop('joe', axis=1, in_place=True)
with pytest.raises(TypeError, match='unexpected keyword'):
df.reindex([1, 0], inplace=True)
with pytest.raises(TypeError, match='unexpected keyword'):
ca.fillna(0, inplace=True)
with pytest.raises(TypeError, match='unexpected keyword'):
ts.fillna(0, in_place=True)
# See gh-12301
def test_stat_unexpected_keyword(self):
obj = self._construct(5)
starwars = 'Star Wars'
errmsg = 'unexpected keyword'
with pytest.raises(TypeError, match=errmsg):
obj.max(epic=starwars) # stat_function
with pytest.raises(TypeError, match=errmsg):
obj.var(epic=starwars) # stat_function_ddof
with pytest.raises(TypeError, match=errmsg):
obj.sum(epic=starwars) # cum_function
with pytest.raises(TypeError, match=errmsg):
obj.any(epic=starwars) # logical_function
def test_api_compat(self):
# GH 12021
# compat for __name__, __qualname__
obj = self._construct(5)
for func in ['sum', 'cumsum', 'any', 'var']:
f = getattr(obj, func)
assert f.__name__ == func
if PY3:
assert f.__qualname__.endswith(func)
def test_stat_non_defaults_args(self):
obj = self._construct(5)
out = np.array([0])
errmsg = "the 'out' parameter is not supported"
with pytest.raises(ValueError, match=errmsg):
obj.max(out=out) # stat_function
with pytest.raises(ValueError, match=errmsg):
obj.var(out=out) # stat_function_ddof
with pytest.raises(ValueError, match=errmsg):
obj.sum(out=out) # cum_function
with pytest.raises(ValueError, match=errmsg):
obj.any(out=out) # logical_function
def test_truncate_out_of_bounds(self):
# GH11382
# small
shape = [int(2e3)] + ([1] * (self._ndim - 1))
small = self._construct(shape, dtype='int8', value=1)
self._compare(small.truncate(), small)
self._compare(small.truncate(before=0, after=3e3), small)
self._compare(small.truncate(before=-1, after=2e3), small)
# big
shape = [int(2e6)] + ([1] * (self._ndim - 1))
big = self._construct(shape, dtype='int8', value=1)
self._compare(big.truncate(), big)
self._compare(big.truncate(before=0, after=3e6), big)
self._compare(big.truncate(before=-1, after=2e6), big)
def test_validate_bool_args(self):
df = DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
invalid_values = [1, "True", [1, 2, 3], 5.0]
for value in invalid_values:
with pytest.raises(ValueError):
super(DataFrame, df).rename_axis(mapper={'a': 'x', 'b': 'y'},
axis=1, inplace=value)
with pytest.raises(ValueError):
super(DataFrame, df).drop('a', axis=1, inplace=value)
with pytest.raises(ValueError):
super(DataFrame, df).sort_index(inplace=value)
with pytest.raises(ValueError):
super(DataFrame, df)._consolidate(inplace=value)
with pytest.raises(ValueError):
super(DataFrame, df).fillna(value=0, inplace=value)
with pytest.raises(ValueError):
super(DataFrame, df).replace(to_replace=1, value=7,
inplace=value)
with pytest.raises(ValueError):
super(DataFrame, df).interpolate(inplace=value)
with pytest.raises(ValueError):
super(DataFrame, df)._where(cond=df.a > 2, inplace=value)
with pytest.raises(ValueError):
super(DataFrame, df).mask(cond=df.a > 2, inplace=value)
def test_copy_and_deepcopy(self):
# GH 15444
for shape in [0, 1, 2]:
obj = self._construct(shape)
for func in [copy,
deepcopy,
lambda x: x.copy(deep=False),
lambda x: x.copy(deep=True)]:
obj_copy = func(obj)
assert obj_copy is not obj
self._compare(obj_copy, obj)
@pytest.mark.parametrize("periods,fill_method,limit,exp", [
(1, "ffill", None, [np.nan, np.nan, np.nan, 1, 1, 1.5, 0, 0]),
(1, "ffill", 1, [np.nan, np.nan, np.nan, 1, 1, 1.5, 0, np.nan]),
(1, "bfill", None, [np.nan, 0, 0, 1, 1, 1.5, np.nan, np.nan]),
(1, "bfill", 1, [np.nan, np.nan, 0, 1, 1, 1.5, np.nan, np.nan]),
(-1, "ffill", None, [np.nan, np.nan, -.5, -.5, -.6, 0, 0, np.nan]),
(-1, "ffill", 1, [np.nan, np.nan, -.5, -.5, -.6, 0, np.nan, np.nan]),
(-1, "bfill", None, [0, 0, -.5, -.5, -.6, np.nan, np.nan, np.nan]),
(-1, "bfill", 1, [np.nan, 0, -.5, -.5, -.6, np.nan, np.nan, np.nan])
])
def test_pct_change(self, periods, fill_method, limit, exp):
vals = [np.nan, np.nan, 1, 2, 4, 10, np.nan, np.nan]
obj = self._typ(vals)
func = getattr(obj, 'pct_change')
res = func(periods=periods, fill_method=fill_method, limit=limit)
if type(obj) is DataFrame:
tm.assert_frame_equal(res, DataFrame(exp))
else:
tm.assert_series_equal(res, Series(exp))
class TestNDFrame(object):
# tests that don't fit elsewhere
def test_sample(sel):
# Fixes issue: 2419
# additional specific object based tests
# A few dataframe test with degenerate weights.
easy_weight_list = [0] * 10
easy_weight_list[5] = 1
df = pd.DataFrame({'col1': range(10, 20),
'col2': range(20, 30),
'colString': ['a'] * 10,
'easyweights': easy_weight_list})
sample1 = df.sample(n=1, weights='easyweights')
assert_frame_equal(sample1, df.iloc[5:6])
# Ensure proper error if string given as weight for Series, panel, or
# DataFrame with axis = 1.
s = Series(range(10))
with pytest.raises(ValueError):
s.sample(n=3, weights='weight_column')
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
panel = Panel(items=[0, 1, 2], major_axis=[2, 3, 4],
minor_axis=[3, 4, 5])
with pytest.raises(ValueError):
panel.sample(n=1, weights='weight_column')
with pytest.raises(ValueError):
df.sample(n=1, weights='weight_column', axis=1)
# Check weighting key error
with pytest.raises(KeyError):
df.sample(n=3, weights='not_a_real_column_name')
# Check that re-normalizes weights that don't sum to one.
weights_less_than_1 = [0] * 10
weights_less_than_1[0] = 0.5
tm.assert_frame_equal(
df.sample(n=1, weights=weights_less_than_1), df.iloc[:1])
###
# Test axis argument
###
# Test axis argument
df = pd.DataFrame({'col1': range(10), 'col2': ['a'] * 10})
second_column_weight = [0, 1]
assert_frame_equal(
df.sample(n=1, axis=1, weights=second_column_weight), df[['col2']])
# Different axis arg types
assert_frame_equal(df.sample(n=1, axis='columns',
weights=second_column_weight),
df[['col2']])
weight = [0] * 10
weight[5] = 0.5
assert_frame_equal(df.sample(n=1, axis='rows', weights=weight),
df.iloc[5:6])
assert_frame_equal(df.sample(n=1, axis='index', weights=weight),
df.iloc[5:6])
# Check out of range axis values
with pytest.raises(ValueError):
df.sample(n=1, axis=2)
with pytest.raises(ValueError):
df.sample(n=1, axis='not_a_name')
with pytest.raises(ValueError):
s = pd.Series(range(10))
s.sample(n=1, axis=1)
# Test weight length compared to correct axis
with pytest.raises(ValueError):
df.sample(n=1, axis=1, weights=[0.5] * 10)
# Check weights with axis = 1
easy_weight_list = [0] * 3
easy_weight_list[2] = 1
df = pd.DataFrame({'col1': range(10, 20),
'col2': range(20, 30),
'colString': ['a'] * 10})
sample1 = df.sample(n=1, axis=1, weights=easy_weight_list)
assert_frame_equal(sample1, df[['colString']])
# Test default axes
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
p = Panel(items=['a', 'b', 'c'], major_axis=[2, 4, 6],
minor_axis=[1, 3, 5])
assert_panel_equal(
p.sample(n=3, random_state=42), p.sample(n=3, axis=1,
random_state=42))
assert_frame_equal(
df.sample(n=3, random_state=42), df.sample(n=3, axis=0,
random_state=42))
# Test that function aligns weights with frame
df = DataFrame(
{'col1': [5, 6, 7],
'col2': ['a', 'b', 'c'], }, index=[9, 5, 3])
s = Series([1, 0, 0], index=[3, 5, 9])
assert_frame_equal(df.loc[[3]], df.sample(1, weights=s))
# Weights have index values to be dropped because not in
# sampled DataFrame
s2 = Series([0.001, 0, 10000], index=[3, 5, 10])
assert_frame_equal(df.loc[[3]], df.sample(1, weights=s2))
# Weights have empty values to be filed with zeros
s3 = Series([0.01, 0], index=[3, 5])
assert_frame_equal(df.loc[[3]], df.sample(1, weights=s3))
# No overlap in weight and sampled DataFrame indices
s4 = Series([1, 0], index=[1, 2])
with pytest.raises(ValueError):
df.sample(1, weights=s4)
def test_squeeze(self):
# noop
for s in [tm.makeFloatSeries(), tm.makeStringSeries(),
tm.makeObjectSeries()]:
tm.assert_series_equal(s.squeeze(), s)
for df in [tm.makeTimeDataFrame()]:
tm.assert_frame_equal(df.squeeze(), df)
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
for p in [tm.makePanel()]:
tm.assert_panel_equal(p.squeeze(), p)
# squeezing
df = tm.makeTimeDataFrame().reindex(columns=['A'])
tm.assert_series_equal(df.squeeze(), df['A'])
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
p = tm.makePanel().reindex(items=['ItemA'])
tm.assert_frame_equal(p.squeeze(), p['ItemA'])
p = tm.makePanel().reindex(items=['ItemA'], minor_axis=['A'])
tm.assert_series_equal(p.squeeze(), p.loc['ItemA', :, 'A'])
# don't fail with 0 length dimensions GH11229 & GH8999
empty_series = Series([], name='five')
empty_frame = DataFrame([empty_series])
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
empty_panel = Panel({'six': empty_frame})
[tm.assert_series_equal(empty_series, higher_dim.squeeze())
for higher_dim in [empty_series, empty_frame, empty_panel]]
# axis argument
df = tm.makeTimeDataFrame(nper=1).iloc[:, :1]
assert df.shape == (1, 1)
tm.assert_series_equal(df.squeeze(axis=0), df.iloc[0])
tm.assert_series_equal(df.squeeze(axis='index'), df.iloc[0])
tm.assert_series_equal(df.squeeze(axis=1), df.iloc[:, 0])
tm.assert_series_equal(df.squeeze(axis='columns'), df.iloc[:, 0])
assert df.squeeze() == df.iloc[0, 0]
pytest.raises(ValueError, df.squeeze, axis=2)
pytest.raises(ValueError, df.squeeze, axis='x')
df = tm.makeTimeDataFrame(3)
tm.assert_frame_equal(df.squeeze(axis=0), df)
def test_numpy_squeeze(self):
s = tm.makeFloatSeries()
tm.assert_series_equal(np.squeeze(s), s)
df = tm.makeTimeDataFrame().reindex(columns=['A'])
tm.assert_series_equal(np.squeeze(df), df['A'])
def test_transpose(self):
msg = (r"transpose\(\) got multiple values for "
r"keyword argument 'axes'")
for s in [tm.makeFloatSeries(), tm.makeStringSeries(),
tm.makeObjectSeries()]:
# calls implementation in pandas/core/base.py
tm.assert_series_equal(s.transpose(), s)
for df in [tm.makeTimeDataFrame()]:
tm.assert_frame_equal(df.transpose().transpose(), df)
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
for p in [tm.makePanel()]:
tm.assert_panel_equal(p.transpose(2, 0, 1)
.transpose(1, 2, 0), p)
with pytest.raises(TypeError, match=msg):
p.transpose(2, 0, 1, axes=(2, 0, 1))
def test_numpy_transpose(self):
msg = "the 'axes' parameter is not supported"
s = tm.makeFloatSeries()
tm.assert_series_equal(np.transpose(s), s)
with pytest.raises(ValueError, match=msg):
np.transpose(s, axes=1)
df = tm.makeTimeDataFrame()
tm.assert_frame_equal(np.transpose(np.transpose(df)), df)
with pytest.raises(ValueError, match=msg):
np.transpose(df, axes=1)
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
p = tm.makePanel()
tm.assert_panel_equal(np.transpose(
np.transpose(p, axes=(2, 0, 1)),
axes=(1, 2, 0)), p)
def test_take(self):
indices = [1, 5, -2, 6, 3, -1]
for s in [tm.makeFloatSeries(), tm.makeStringSeries(),
tm.makeObjectSeries()]:
out = s.take(indices)
expected = Series(data=s.values.take(indices),
index=s.index.take(indices), dtype=s.dtype)
tm.assert_series_equal(out, expected)
for df in [tm.makeTimeDataFrame()]:
out = df.take(indices)
expected = DataFrame(data=df.values.take(indices, axis=0),
index=df.index.take(indices),
columns=df.columns)
tm.assert_frame_equal(out, expected)
indices = [-3, 2, 0, 1]
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
for p in [tm.makePanel()]:
out = p.take(indices)
expected = Panel(data=p.values.take(indices, axis=0),
items=p.items.take(indices),
major_axis=p.major_axis,
minor_axis=p.minor_axis)
tm.assert_panel_equal(out, expected)
def test_take_invalid_kwargs(self):
indices = [-3, 2, 0, 1]
s = tm.makeFloatSeries()
df = tm.makeTimeDataFrame()
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
p = tm.makePanel()
for obj in (s, df, p):
msg = r"take\(\) got an unexpected keyword argument 'foo'"
with pytest.raises(TypeError, match=msg):
obj.take(indices, foo=2)
msg = "the 'out' parameter is not supported"
with pytest.raises(ValueError, match=msg):
obj.take(indices, out=indices)
msg = "the 'mode' parameter is not supported"
with pytest.raises(ValueError, match=msg):
obj.take(indices, mode='clip')
def test_equals(self):
s1 = pd.Series([1, 2, 3], index=[0, 2, 1])
s2 = s1.copy()
assert s1.equals(s2)
s1[1] = 99
assert not s1.equals(s2)
# NaNs compare as equal
s1 = pd.Series([1, np.nan, 3, np.nan], index=[0, 2, 1, 3])
s2 = s1.copy()
assert s1.equals(s2)
s2[0] = 9.9
assert not s1.equals(s2)
idx = MultiIndex.from_tuples([(0, 'a'), (1, 'b'), (2, 'c')])
s1 = Series([1, 2, np.nan], index=idx)
s2 = s1.copy()
assert s1.equals(s2)
# Add object dtype column with nans
index = np.random.random(10)
df1 = DataFrame(
np.random.random(10, ), index=index, columns=['floats'])
df1['text'] = 'the sky is so blue. we could use more chocolate.'.split(
)
df1['start'] = date_range('2000-1-1', periods=10, freq='T')
df1['end'] = date_range('2000-1-1', periods=10, freq='D')
df1['diff'] = df1['end'] - df1['start']
df1['bool'] = (np.arange(10) % 3 == 0)
df1.loc[::2] = np.nan
df2 = df1.copy()
assert df1['text'].equals(df2['text'])
assert df1['start'].equals(df2['start'])
assert df1['end'].equals(df2['end'])
assert df1['diff'].equals(df2['diff'])
assert df1['bool'].equals(df2['bool'])
assert df1.equals(df2)
assert not df1.equals(object)
# different dtype
different = df1.copy()
different['floats'] = different['floats'].astype('float32')
assert not df1.equals(different)
# different index
different_index = -index
different = df2.set_index(different_index)
assert not df1.equals(different)
# different columns
different = df2.copy()
different.columns = df2.columns[::-1]
assert not df1.equals(different)
# DatetimeIndex
index = pd.date_range('2000-1-1', periods=10, freq='T')
df1 = df1.set_index(index)
df2 = df1.copy()
assert df1.equals(df2)
# MultiIndex
df3 = df1.set_index(['text'], append=True)
df2 = df1.set_index(['text'], append=True)
assert df3.equals(df2)
df2 = df1.set_index(['floats'], append=True)
assert not df3.equals(df2)
# NaN in index
df3 = df1.set_index(['floats'], append=True)
df2 = df1.set_index(['floats'], append=True)
assert df3.equals(df2)
# GH 8437
a = pd.Series([False, np.nan])
b = pd.Series([False, np.nan])
c = pd.Series(index=range(2))
d = pd.Series(index=range(2))
e = pd.Series(index=range(2))
f = pd.Series(index=range(2))
c[:-1] = d[:-1] = e[0] = f[0] = False
assert a.equals(a)
assert a.equals(b)
assert a.equals(c)
assert a.equals(d)
assert a.equals(e)
assert e.equals(f)
def test_describe_raises(self):
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
with pytest.raises(NotImplementedError):
tm.makePanel().describe()
def test_pipe(self):
df = DataFrame({'A': [1, 2, 3]})
f = lambda x, y: x ** y
result = df.pipe(f, 2)
expected = DataFrame({'A': [1, 4, 9]})
assert_frame_equal(result, expected)
result = df.A.pipe(f, 2)
assert_series_equal(result, expected.A)
def test_pipe_tuple(self):
df = DataFrame({'A': [1, 2, 3]})
f = lambda x, y: y
result = df.pipe((f, 'y'), 0)
assert_frame_equal(result, df)
result = df.A.pipe((f, 'y'), 0)
assert_series_equal(result, df.A)
def test_pipe_tuple_error(self):
df = DataFrame({"A": [1, 2, 3]})
f = lambda x, y: y
with pytest.raises(ValueError):
df.pipe((f, 'y'), x=1, y=0)
with pytest.raises(ValueError):
df.A.pipe((f, 'y'), x=1, y=0)
def test_pipe_panel(self):
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
wp = Panel({'r1': DataFrame({"A": [1, 2, 3]})})
f = lambda x, y: x + y
result = wp.pipe(f, 2)
expected = wp + 2
assert_panel_equal(result, expected)
result = wp.pipe((f, 'y'), x=1)
expected = wp + 1
assert_panel_equal(result, expected)
with pytest.raises(ValueError):
wp.pipe((f, 'y'), x=1, y=1)
@pytest.mark.parametrize('box', [pd.Series, pd.DataFrame])
def test_axis_classmethods(self, box):
obj = box()
values = (list(box._AXIS_NAMES.keys()) +
list(box._AXIS_NUMBERS.keys()) +
list(box._AXIS_ALIASES.keys()))
for v in values:
assert obj._get_axis_number(v) == box._get_axis_number(v)
assert obj._get_axis_name(v) == box._get_axis_name(v)
assert obj._get_block_manager_axis(v) == \
box._get_block_manager_axis(v)
|
|
# 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.
import sys
from oslo_log import log
from oslo_log import versionutils
from oslo_utils import importutils
import six
import stevedore
from keystone.common import dependency
from keystone.common import utils
import keystone.conf
from keystone import exception
from keystone.i18n import _, _LI, _LE
from keystone.identity.backends import resource_options as ro
LOG = log.getLogger(__name__)
CONF = keystone.conf.CONF
# registry of authentication methods
AUTH_METHODS = {}
AUTH_PLUGINS_LOADED = False
def load_auth_method(method):
plugin_name = CONF.auth.get(method) or 'default'
namespace = 'keystone.auth.%s' % method
try:
driver_manager = stevedore.DriverManager(namespace, plugin_name,
invoke_on_load=True)
return driver_manager.driver
except RuntimeError:
LOG.debug('Failed to load the %s driver (%s) using stevedore, will '
'attempt to load using import_object instead.',
method, plugin_name)
driver = importutils.import_object(plugin_name)
msg = (_(
'Direct import of auth plugin %(name)r is deprecated as of Liberty in '
'favor of its entrypoint from %(namespace)r and may be removed in '
'N.') %
{'name': plugin_name, 'namespace': namespace})
versionutils.report_deprecated_feature(LOG, msg)
return driver
def load_auth_methods():
global AUTH_PLUGINS_LOADED
if AUTH_PLUGINS_LOADED:
# Only try and load methods a single time.
return
# config.setup_authentication should be idempotent, call it to ensure we
# have setup all the appropriate configuration options we may need.
keystone.conf.auth.setup_authentication()
for plugin in set(CONF.auth.methods):
AUTH_METHODS[plugin] = load_auth_method(plugin)
AUTH_PLUGINS_LOADED = True
def get_auth_method(method_name):
global AUTH_METHODS
if method_name not in AUTH_METHODS:
raise exception.AuthMethodNotSupported()
return AUTH_METHODS[method_name]
class AuthContext(dict):
"""Retrofitting auth_context to reconcile identity attributes.
The identity attributes must not have conflicting values among the
auth plug-ins. The only exception is `expires_at`, which is set to its
earliest value.
"""
# identity attributes need to be reconciled among the auth plugins
IDENTITY_ATTRIBUTES = frozenset(['user_id', 'project_id',
'access_token_id', 'domain_id',
'expires_at'])
def __setitem__(self, key, val):
"""Override __setitem__ to prevent conflicting values."""
if key in self.IDENTITY_ATTRIBUTES and key in self:
existing_val = self[key]
if key == 'expires_at':
# special treatment for 'expires_at', we are going to take
# the earliest expiration instead.
if existing_val != val:
LOG.info(_LI('"expires_at" has conflicting values '
'%(existing)s and %(new)s. Will use the '
'earliest value.'),
{'existing': existing_val, 'new': val})
if existing_val is None or val is None:
val = existing_val or val
else:
val = min(existing_val, val)
elif existing_val != val:
msg = _('Unable to reconcile identity attribute %(attribute)s '
'as it has conflicting values %(new)s and %(old)s') % (
{'attribute': key,
'new': val,
'old': existing_val})
raise exception.Unauthorized(msg)
return super(AuthContext, self).__setitem__(key, val)
def update(self, E=None, **F):
"""Override update to prevent conflicting values."""
# NOTE(notmorgan): This will not be nearly as performant as the
# use of the built-in "update" method on the dict, however, the
# volume of data being changed here is very minimal in most cases
# and should not see a significant impact by iterating instead of
# explicit setting of values.
update_dicts = (E or {}, F or {})
for d in update_dicts:
for key, val in d.items():
self[key] = val
@dependency.requires('resource_api', 'trust_api')
class AuthInfo(object):
"""Encapsulation of "auth" request."""
@staticmethod
def create(auth=None, scope_only=False):
auth_info = AuthInfo(auth=auth)
auth_info._validate_and_normalize_auth_data(scope_only)
return auth_info
def __init__(self, auth=None):
self.auth = auth
self._scope_data = (None, None, None, None)
# self._scope_data is (domain_id, project_id, trust_ref, unscoped)
# project scope: (None, project_id, None, None)
# domain scope: (domain_id, None, None, None)
# trust scope: (None, None, trust_ref, None)
# unscoped: (None, None, None, 'unscoped')
def _assert_project_is_enabled(self, project_ref):
# ensure the project is enabled
try:
self.resource_api.assert_project_enabled(
project_id=project_ref['id'],
project=project_ref)
except AssertionError as e:
LOG.warning(six.text_type(e))
six.reraise(exception.Unauthorized, exception.Unauthorized(e),
sys.exc_info()[2])
def _assert_domain_is_enabled(self, domain_ref):
try:
self.resource_api.assert_domain_enabled(
domain_id=domain_ref['id'],
domain=domain_ref)
except AssertionError as e:
LOG.warning(six.text_type(e))
six.reraise(exception.Unauthorized, exception.Unauthorized(e),
sys.exc_info()[2])
def _lookup_domain(self, domain_info):
domain_id = domain_info.get('id')
domain_name = domain_info.get('name')
try:
if domain_name:
if (CONF.resource.domain_name_url_safe == 'strict' and
utils.is_not_url_safe(domain_name)):
msg = _('Domain name cannot contain reserved characters.')
LOG.warning(msg)
raise exception.Unauthorized(message=msg)
domain_ref = self.resource_api.get_domain_by_name(
domain_name)
else:
domain_ref = self.resource_api.get_domain(domain_id)
except exception.DomainNotFound as e:
LOG.warning(six.text_type(e))
raise exception.Unauthorized(e)
self._assert_domain_is_enabled(domain_ref)
return domain_ref
def _lookup_project(self, project_info):
project_id = project_info.get('id')
project_name = project_info.get('name')
try:
if project_name:
if (CONF.resource.project_name_url_safe == 'strict' and
utils.is_not_url_safe(project_name)):
msg = _('Project name cannot contain reserved characters.')
LOG.warning(msg)
raise exception.Unauthorized(message=msg)
if 'domain' not in project_info:
raise exception.ValidationError(attribute='domain',
target='project')
domain_ref = self._lookup_domain(project_info['domain'])
project_ref = self.resource_api.get_project_by_name(
project_name, domain_ref['id'])
else:
project_ref = self.resource_api.get_project(project_id)
# NOTE(morganfainberg): The _lookup_domain method will raise
# exception.Unauthorized if the domain isn't found or is
# disabled.
self._lookup_domain({'id': project_ref['domain_id']})
except exception.ProjectNotFound as e:
LOG.warning(six.text_type(e))
raise exception.Unauthorized(e)
self._assert_project_is_enabled(project_ref)
return project_ref
def _lookup_trust(self, trust_info):
trust_id = trust_info.get('id')
if not trust_id:
raise exception.ValidationError(attribute='trust_id',
target='trust')
trust = self.trust_api.get_trust(trust_id)
return trust
def _validate_and_normalize_scope_data(self):
"""Validate and normalize scope data."""
if 'scope' not in self.auth:
return
if sum(['project' in self.auth['scope'],
'domain' in self.auth['scope'],
'unscoped' in self.auth['scope'],
'OS-TRUST:trust' in self.auth['scope']]) != 1:
raise exception.ValidationError(
attribute='project, domain, OS-TRUST:trust or unscoped',
target='scope')
if 'unscoped' in self.auth['scope']:
self._scope_data = (None, None, None, 'unscoped')
return
if 'project' in self.auth['scope']:
project_ref = self._lookup_project(self.auth['scope']['project'])
self._scope_data = (None, project_ref['id'], None, None)
elif 'domain' in self.auth['scope']:
domain_ref = self._lookup_domain(self.auth['scope']['domain'])
self._scope_data = (domain_ref['id'], None, None, None)
elif 'OS-TRUST:trust' in self.auth['scope']:
if not CONF.trust.enabled:
raise exception.Forbidden('Trusts are disabled.')
trust_ref = self._lookup_trust(
self.auth['scope']['OS-TRUST:trust'])
# TODO(ayoung): when trusts support domains, fill in domain data
if trust_ref.get('project_id') is not None:
project_ref = self._lookup_project(
{'id': trust_ref['project_id']})
self._scope_data = (None, project_ref['id'], trust_ref, None)
else:
self._scope_data = (None, None, trust_ref, None)
def _validate_auth_methods(self):
# make sure all the method data/payload are provided
for method_name in self.get_method_names():
if method_name not in self.auth['identity']:
raise exception.ValidationError(attribute=method_name,
target='identity')
# make sure auth method is supported
for method_name in self.get_method_names():
if method_name not in AUTH_METHODS:
raise exception.AuthMethodNotSupported()
def _validate_and_normalize_auth_data(self, scope_only=False):
"""Make sure "auth" is valid.
:param scope_only: If it is True, auth methods will not be
validated but only the scope data.
:type scope_only: boolean
"""
# make sure "auth" exist
if not self.auth:
raise exception.ValidationError(attribute='auth',
target='request body')
# NOTE(chioleong): Tokenless auth does not provide auth methods,
# we only care about using this method to validate the scope
# information. Therefore, validating the auth methods here is
# insignificant and we can skip it when scope_only is set to
# true.
if scope_only is False:
self._validate_auth_methods()
self._validate_and_normalize_scope_data()
def get_method_names(self):
"""Return the identity method names.
:returns: list of auth method names
"""
# Sanitizes methods received in request's body
# Filters out duplicates, while keeping elements' order.
method_names = []
for method in self.auth['identity']['methods']:
if method not in method_names:
method_names.append(method)
return method_names
def get_method_data(self, method):
"""Get the auth method payload.
:returns: auth method payload
"""
if method not in self.auth['identity']['methods']:
raise exception.ValidationError(attribute=method,
target='identity')
return self.auth['identity'][method]
def get_scope(self):
"""Get scope information.
Verify and return the scoping information.
:returns: (domain_id, project_id, trust_ref, unscoped).
If scope to a project, (None, project_id, None, None)
will be returned.
If scoped to a domain, (domain_id, None, None, None)
will be returned.
If scoped to a trust, (None, project_id, trust_ref, None),
Will be returned, where the project_id comes from the
trust definition.
If unscoped, (None, None, None, 'unscoped') will be
returned.
"""
return self._scope_data
def set_scope(self, domain_id=None, project_id=None, trust=None,
unscoped=None):
"""Set scope information."""
if domain_id and project_id:
msg = _('Scoping to both domain and project is not allowed')
raise ValueError(msg)
if domain_id and trust:
msg = _('Scoping to both domain and trust is not allowed')
raise ValueError(msg)
if project_id and trust:
msg = _('Scoping to both project and trust is not allowed')
raise ValueError(msg)
self._scope_data = (domain_id, project_id, trust, unscoped)
@dependency.requires('identity_api')
class UserMFARulesValidator(object):
"""Helper object that can validate the MFA Rules."""
@property
def _auth_methods(self):
if AUTH_PLUGINS_LOADED:
return set(AUTH_METHODS.keys())
raise RuntimeError(_('Auth Method Plugins are not loaded.'))
def check_auth_methods_against_rules(self, user_id, auth_methods):
"""Validate the MFA rules against the successful auth methods.
:param user_id: The user's ID (uuid).
:type user_id: str
:param auth_methods: List of methods that were used for auth
:type auth_methods: set
:returns: Boolean, ``True`` means rules match and auth may proceed,
``False`` means rules do not match.
"""
user_ref = self.identity_api.get_user(user_id)
mfa_rules = user_ref['options'].get(ro.MFA_RULES_OPT.option_name, [])
mfa_rules_enabled = user_ref['options'].get(
ro.MFA_ENABLED_OPT.option_name, True)
rules = self._parse_rule_structure(mfa_rules, user_ref['id'])
if not rules or not mfa_rules_enabled:
# return quickly if the rules are disabled for the user or not set
LOG.debug('MFA Rules not processed for user `%(user_id)s`. '
'Rule list: `%(rules)s` (Enabled: `%(enabled)s`).',
{'user_id': user_id,
'rules': mfa_rules,
'enabled': mfa_rules_enabled})
return True
for r in rules:
# NOTE(notmorgan): We only check against the actually loaded
# auth methods meaning that the keystone administrator may
# disable an auth method, and a rule will still pass making it
# impossible to accidently lock-out a subset of users with a
# bad keystone.conf
r_set = set(r).intersection(self._auth_methods)
if set(auth_methods).issuperset(r_set):
# Rule Matches no need to continue, return here.
LOG.debug('Auth methods for user `%(user_id)s`, `%(methods)s` '
'matched MFA rule `%(rule)s`. Loaded '
'auth_methods: `%(loaded)s`',
{'user_id': user_id,
'rule': list(r_set),
'methods': auth_methods,
'loaded': self._auth_methods})
return True
LOG.debug('Auth methods for user `%(user_id)s`, `%(methods)s` did not '
'match a MFA rule in `%(rules)s`.',
{'user_id': user_id,
'methods': auth_methods,
'rules': rules})
return False
@staticmethod
def _parse_rule_structure(rules, user_id):
"""Validate and parse the rule data structure.
Rule sets must be in the form of list of lists. The lists may not
have duplicates and must not be empty. The top-level list may be empty
indicating that no rules exist.
:param rules: The list of rules from the user_ref
:type rules: list
:param user_id: the user_id, used for logging purposes
:type user_id: str
:returns: list of list, duplicates are stripped
"""
# NOTE(notmorgan): Most of this is done at the API request validation
# and in the storage layer, it makes sense to also validate here and
# ensure the data returned from the DB is sane, This will not raise
# any exceptions, but just produce a usable set of data for rules
# processing.
rule_set = []
if not isinstance(rules, list):
LOG.error(_LE('Corrupt rule data structure for user %(user_id)s, '
'no rules loaded.'),
{'user_id': user_id})
# Corrupt Data means no rules. Auth success > MFA rules in this
# case.
return rule_set
elif not rules:
# Exit early, nothing to do here.
return rule_set
for r_list in rules:
if not isinstance(r_list, list):
# Rule was not a list, it is invalid, drop the rule from
# being considered.
LOG.info(_LI('Ignoring Rule %(rule)r; rule must be a list of '
'strings.'),
{'type': type(r_list)})
continue
if r_list:
# No empty rules are allowed.
_ok_rule = True
for item in r_list:
if not isinstance(item, six.string_types):
# Rules may only contain strings for method names
# Reject a rule with non-string values
LOG.info(_LI('Ignoring Rule %(rule)r; rule contains '
'non-string values.'),
{'rule': r_list})
# Rule is known to be bad, drop it from consideration.
_ok_rule = False
break
# NOTE(notmorgan): No FOR/ELSE used here! Though it could be
# done and avoid the use of _ok_rule. This is a note for
# future developers to avoid using for/else and as an example
# of how to implement it that is readable and maintainable.
if _ok_rule:
# Unique the r_list and cast back to a list and then append
# as we know the rule is ok (matches our requirements).
# This is outside the for loop, as the for loop is
# only used to validate the elements in the list. The
# This de-dupe should never be needed, but we are being
# extra careful at all levels of validation for the MFA
# rules.
r_list = list(set(r_list))
rule_set.append(r_list)
return rule_set
|
|
""" --Juana Valeria Hurtado Rincon [email protected]
Signal Processing and Pattern Recognition Research Group
Universidad Nacional de colombia """
from numpy import fft
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
from emokit import emotiv
import gevent
def readEEG(Fs,time,ch):
"""Return EEG matrix nxm (n:time,m:channels) from Emotiv
Parameters: Fs: -int- sampling frequency
time: -int- time recording
ch: -int- number of channels
Returns: EEG: -ndarray- EEG signal
headset: -object- emotiv headset -> emotiv.Emotiv()"""
headset = emotiv.Emotiv()
gevent.spawn(headset.setup)
gevent.sleep(1)
samples = int(Fs*time)
EEG = np.zeros(shape=(samples, ch))
for i in xrange(samples):
packet = headset.dequeue()
EEG[i,0]=value = int(''.join(map(str,list(packet.F3)))) #Tuple to int
EEG[i,1]=value = int(''.join(map(str,list(packet.F4)))) #Tuple to int
EEG[i,2]=value = int(''.join(map(str,list(packet.P7)))) #Tuple to int
EEG[i,3]=value = int(''.join(map(str,list(packet.FC6)))) #Tuple to int
EEG[i,4]=value = int(''.join(map(str,list(packet.F7)))) #Tuple to int
EEG[i,5]=value = int(''.join(map(str,list(packet.F8)))) #Tuple to int
EEG[i,6]=value = int(''.join(map(str,list(packet.T7)))) #Tuple to int
EEG[i,7]=value = int(''.join(map(str,list(packet.P8)))) #Tuple to int
EEG[i,8]=value = int(''.join(map(str,list(packet.FC5)))) #Tuple to int
EEG[i,9]=value = int(''.join(map(str,list(packet.AF4)))) #Tuple to int
EEG[i,10]=value = int(''.join(map(str,list(packet.T8)))) #Tuple to int
EEG[i,11]=value = int(''.join(map(str,list(packet.O2)))) #Tuple to int
EEG[i,12]=value = int(''.join(map(str,list(packet.O1)))) #Tuple to int
EEG[i,13]=value = int(''.join(map(str,list(packet.AF3)))) #Tuple to int
#gevent.sleep(0)
#headset.close()
return(EEG, headset)
def readEEG2(Fs,time,ch,headset):
"""Return EEG matrix nxm (n:time,m:channels) from Emotiv
Parameters: Fs: -int- sampling frequency
time: -int- time recording
ch: -int- number of channels
headset: -object- emotiv headset -> emotiv.Emotiv()
Returns: EEG: -ndarray- EEG signal"""
samples = int(Fs*time)
EEG = np.zeros(shape=(samples, ch))
for i in xrange(samples):
packet = headset.dequeue()
EEG[i,0]=value = int(''.join(map(str,list(packet.F3)))) #Tuple to int
EEG[i,1]=value = int(''.join(map(str,list(packet.F4)))) #Tuple to int
EEG[i,2]=value = int(''.join(map(str,list(packet.P7)))) #Tuple to int
EEG[i,3]=value = int(''.join(map(str,list(packet.FC6)))) #Tuple to int
EEG[i,4]=value = int(''.join(map(str,list(packet.F7)))) #Tuple to int
EEG[i,5]=value = int(''.join(map(str,list(packet.F8)))) #Tuple to int
EEG[i,6]=value = int(''.join(map(str,list(packet.T7)))) #Tuple to int
EEG[i,7]=value = int(''.join(map(str,list(packet.P8)))) #Tuple to int
EEG[i,8]=value = int(''.join(map(str,list(packet.FC5)))) #Tuple to int
EEG[i,9]=value = int(''.join(map(str,list(packet.AF4)))) #Tuple to int
EEG[i,10]=value = int(''.join(map(str,list(packet.T8)))) #Tuple to int
EEG[i,11]=value = int(''.join(map(str,list(packet.O2)))) #Tuple to int
EEG[i,12]=value = int(''.join(map(str,list(packet.O1)))) #Tuple to int
EEG[i,13]=value = int(''.join(map(str,list(packet.AF3)))) #Tuple to int
#gevent.sleep(0)
#headset.close()
return(EEG)
def normalizeEEG(EEG):
"""Return EEG normalized matrix
Parameters: EEG: -ndarray- EEG matrix(time x ch)
Returns: EEG_n: -ndarray- Normalized EEG signal"""
EEG_n = np.zeros(shape=(EEG.shape))
for u in range(EEG.shape[1]):
EEG_n[:,u] = (( EEG[:,u] - np.mean(EEG[:,u]))+100*(u+1)).transpose()
return(EEG_n)
def getChannels(EEG,ch_list):
"""Return the EEG data of the given channel list and the new ch number
Parameters: EEG: -ndarray- EEG matrix(time x ch)
ch_list: -1xn array- contains the numbers that corresponds with the desired channels
0:F3, 1:F4, 2:P7, 3:FC6, 4:F7, 5:F8, 6:T7, 7:P8, 8:FC5, 9:AF4, 10:T8, 11:O2, 12:O1, 13:AF3
Returns: EEG_c: -ndarray- Normalized EEG signal
ch: -int- New number of channels
Examples: 1) getChannels(EEG,[0,3,4,5,10,11,12])
2)ch_list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]
getChannels(EEG,ch_list)"""
EEG_c = np.zeros(shape=(EEG.shape[0], len(ch_list)))
for c in range(len(ch_list)):
EEG_c[:,c] = EEG[:,ch_list[c]]
ch = len(ch_list)
return EEG_c, ch
def saveEEGTxt(EEG,filename,Header):
"""Save the EEG signal in a .txt file
Parameters: EEG: -ndarray- EEG matrix(time x ch)
filename: -str- Name of the file
header: -str- Header of the file"""
m = np.asmatrix(EEG)
np.savetxt(filename + '.txt', m,fmt='%.d',header=str(Header), comments='')
def rhythmsBasicWaves( fs, dx, EEG):
"""Return the basic rhythms (delta, theta, alpha, beta) energy mean of the given EEG signal
Parameters: EEG: -ndarray- EEG matrix(time x ch)
fs: -int- Sampling frequency
dx: -int- 1/fs
Returns: rhythm_mean: -1x4 array- Rhythms energy """
#fs: Is the sampling frequency
#dx: Is 1/fs
#EEG: EEG matrix size: time,ch
#Ritmos delta 0-4 Hz.
#Actividad theta: 4-7 Hz.
#Ritmos alfa: 8-13 Hz.
#Ritmos beta: 14-60 Hz.
delta = [0.8,4]
theta = [4,7]
alfa = [8,13]
beta = [14,60]
freq_rhythms=[delta[0],delta[1],theta[0],theta[1],alfa[0],alfa[1],beta[0],beta[1]] # vector con en rango de frecuencia de los ritmos
X = EEG # Cargar un archivo txt con el EEG
[m,n] = X.shape # Tama\no de la matriz cargada
if (m % 2 != 0): #Dejando como numero par el tama\no
X = X[0:m-1,:] #(evitar problemas al tomar la parte positiva de la transformada)
[m,n] = X.shape
Y = np.zeros(shape=(m,n)) # Creando matrices a utilzar
f = np.zeros(shape=(m,n))
Yf = np.zeros(shape=(m/2,n))
ff = np.zeros(shape=(m/2,n))
prom = np.zeros(len(freq_rhythms)/2)
for i in range(n):
Y[:,i] = fft.fft(X[:,i]) # Transformada rapida de Fourier
Y[:,i]= fft.fftshift(Y[:,i]) # Centrando en cero los valores
Yf[:,i] = Y[len(Y)/2:,i] # Tomando la parte positiva
f[:,i] = fft.fftfreq(len(X[:,i]),0.0078125) # Eje de las frecuencias, !!!!!!cuidado con el dx
f[:,i] = fft.fftshift(f[:,i]) # Centrando en cero los valores
ff[:,i] = f[len(f)/2:,i] # Tomando la parte positiva
Yff = np.sum(Yf,axis=1) #Sumando en la frecuencia los canales
ff = ff[:,0]
posi = []
for p in range(len(freq_rhythms)):
freq_rhythms2 = min(ff, key=lambda x:abs(x-freq_rhythms[p])) #Encontrando los valores mas cercanos al rango de frec de los ritmos
posi.append(np.where(ff == freq_rhythms2)) #en el eje de las frecuencias. Buscando en el eje de las frec las
# posiciones en las que estan los valores ya encontrados
q = 0
for j in range(len(freq_rhythms)/2): # Promedio de la energia en cada rango de frec
ini = posi[q]
fin = posi[q+1]
prom[j] = np.mean(np.square(np.real(Yff[ini[0]:fin[0]])))
q=q+2
#print 'delta, theta, alfa, beta'
rhythm_mean = prom
return rhythm_mean
def rhythmsAllWaves( fs, dx, EEG):
"""Return the rhythms energy mean of the given EEG signal
Parameters: EEG: -ndarray- EEG matrix(time x ch)
fs: -int- Sampling frequency
dx: -int- 1/fs
Returns: rhythm_mean: -1x4 array- Rhythms energy
delta, theta, low_alpha, high_alpha, low_beta, high_beta, low_gamma, high_gamma"""
#fs: Is the sampling frequency
#dx: Is 1/fs
#EEG: EEG matrix size: time,ch
#Ritmos delta 0-4 Hz.
#Actividad theta: 4-7 Hz.
#Ritmos alfa: 8-13 Hz.
#Ritmos beta: 14-60 Hz.
delta = [1.5,3]
theta = [4,7]
low_alpha = [7.5,12.5]
high_alpha = [8,15]
low_beta = [12.5, 18]
high_beta = [18,30]
low_gamma = [30,40]
high_gamma = [35,60]
freq_rhythms=[delta[0],delta[1],theta[0],theta[1],low_alpha[0],low_alpha[1],high_alpha[0],high_alpha[1],low_beta[0],low_beta[1],high_beta[0],high_beta[1],low_gamma[0],low_gamma[1],high_gamma[0],high_gamma[1]] # vector con en rango de frecuencia de los ritmos
X = EEG # Cargar un archivo txt con el EEG
[m,n] = X.shape # Tama\no de la matriz cargada
if (m % 2 != 0): #Dejando como numero par el tama\no
X = X[0:m-1,:] #(evitar problemas al tomar la parte positiva de la transformada)
#(evitar problemas al tomar la parte positiva de la transformada)
[m,n] = X.shape
Y = np.zeros(shape=(m,n)) # Creando matrices a utilzar
f = np.zeros(shape=(m,n))
Yf = np.zeros(shape=(m/2,n))
ff = np.zeros(shape=(m/2,n))
prom = np.zeros(len(freq_rhythms)/2)
for i in range(n):
Y[:,i] = fft.fft(X[:,i]) # Transformada rapida de Fourier
Y[:,i]= fft.fftshift(Y[:,i]) # Centrando en cero los valores
Yf[:,i] = Y[len(Y)/2:,i] # Tomando la parte positiva
f[:,i] = fft.fftfreq(len(X[:,i]),0.0078125) # Eje de las frecuencias, !!!!!!cuidado con el dx
f[:,i] = fft.fftshift(f[:,i]) # Centrando en cero los valores
ff[:,i] = f[len(f)/2:,i] # Tomando la parte positiva
Yff = np.sum(Yf,axis=1) #Sumando en la frecuencia los canales
ff = ff[:,0]
posi = []
for p in range(len(freq_rhythms)):
freq_rhythms2 = min(ff, key=lambda x:abs(x-freq_rhythms[p])) #Encontrando los valores mas cercanos al rango de frec de los ritmos
posi.append(np.where(ff == freq_rhythms2)) #en el eje de las frecuencias. Buscando en el eje de las frec las
# posiciones en las que estan los valores ya encontrados
q = 0
for j in range(len(freq_rhythms)/2): # Promedio de la energia en cada rango de frec
ini = posi[q]
fin = posi[q+1]
prom[j] = np.mean(np.square(np.real(Yff[ini[0]:fin[0]])))
q=q+2
#print 'delta, theta, alfa, beta'
return prom
def rhythmsFromFile( fs, dx,filename):
#fs: Is the sampling frequency
#dx: Is 1/fs
#filename: Is the name (String type) that Corresponds to a .txt file wich contains the EEG data during a t time
#Ritmos delta 0-4 Hz.
#Actividad theta: 4-7 Hz.
#Ritmos alfa: 8-13 Hz.
#Ritmos beta: 14-60 Hz.
delta = [0,4]
theta = [4,7]
alfa = [8,13]
beta = [14,60]
freq_rhythms=[delta[0],delta[1],theta[0],theta[1],alfa[0],alfa[1],beta[0],beta[1]] # vector con en rango de frecuencia de los ritmos
X = np.loadtxt(filename, skiprows=1) # Cargar un archivo txt con el EEG
XT = X.transpose()
[m,n] = XT.shape # Tama\no de la matriz cargada
X = XT
number= 4
if n % 2 != 0:
X = X[0:m-1,:] #Dejando como numero par el tama\no
#(evitar problemas al tomar la parte positiva de la transformada)
[m,n] = X.shape
Y = np.zeros(shape=(m,n)) # Creando matrices a utilzar
f = np.zeros(shape=(m,n))
Yf = np.zeros(shape=(m/2,n))
ff = np.zeros(shape=(m/2,n))
prom = np.zeros(shape=(1,4))
for i in range(n):
Y[:,i] = fft.fft(X[:,i]) # Transformada rapida de Fourier
Y[:,i]= fft.fftshift(Y[:,i]) # Centrando en cero los valores
Yf[:,i] = Y[len(Y)/2:,i] # Tomando la parte positiva
f[:,i] = fft.fftfreq(len(X[:,i]),0.004) # Eje de las frecuencias, !!!!!!cuidado con el dx
f[:,i] = fft.fftshift(f[:,i]) # Centrando en cero los valores
ff[:,i] = f[len(f)/2:,i] # Tomando la parte positiva
Yff = np.sum(Yf,axis=1) #Sumando en la frecuencia los canales
ff = ff[:,0]
posi = []
for p in range(len(freq_rhythms)):
freq_rhythms2 = min(ff, key=lambda x:abs(x-freq_rhythms[p])) #Encontrando los valores mas cercanos al rango de frec de los ritmos
posi.append(np.where(ff == freq_rhythms2)) #en el eje de las frecuencias. Buscando en el eje de las frec las
# posiciones en las que estan los valores ya encontrados
q = 0
for j in range(4): # Promedio de la energia en cada rango de frec
ini = posi[q]
fin = posi[q+1]
prom[0,j] = np.mean(np.square(np.real(Yff[ini[0]:fin[0]])))
q=q+2
#print 'delta, theta, alfa, beta'
#print prom
return prom[0]
def normalizeRhythms(rhy):
"""Return normalized rhythms
Parameters: rhy: -1xn array- Rhythms energy
Returns: rhy_n: -1xn array- Normalized Rhythms"""
rhy_n = (rhy - min(rhy))/max(rhy)*100
return(rhy_n)
def GraphBar(win,y,c):
""" Plot a Bar graphic for each value of y(n array) with its respective color c(n array)"""
bg1 = pg.BarGraphItem(x=[0], height=[y[0]], width=0.5, brush=c[0])
bg2 = pg.BarGraphItem(x=[1], height=[y[1]], width=0.5, brush=c[1])
bg3 = pg.BarGraphItem(x=[2], height=[y[2]], width=0.5, brush=c[2])
bg4 = pg.BarGraphItem(x=[3], height=[y[3]], width=0.5, brush=c[3])
win.addItem(bg1)
win.addItem(bg2)
win.addItem(bg3)
win.addItem(bg4)
win.getAxis('bottom').setTicks([[(0, 'Delta'), (1, 'Theta'), (2, 'Alpha'), (3, 'Beta')]])
win.setLabel('left', 'Energy', units='%')
def wavesDiagram(E,Deg):
"""Return the points to plot the Waves Diagram
Parameters: E: -1xn array- Energy of each rhythm
Deg: -1xn array- Plot angle for each rhythm
Returns: x: -1xn array- plot points in x axis
y: -1xn array- plot points in y axis
Examples: 1) Deg = [90., 45., 330., 300., 240., 210., 150., 120.]
xr,yr = mn.wavesDiagram(r,Deg)
2)Deg = [90., 45., 0. ,315., 270. , 225., 180., 135.]
xr,yr = mn.wavesDiagram(r,Deg)"""
x = np.zeros(len(E)+1)
y = np.zeros(len(E)+1)
for i in range(len(E)):
toDeg = np.pi / 180.
x[i] = E[i]* np.cos(Deg[i]*toDeg)
y[i] = E[i]* np.sin(Deg[i]*toDeg)
x[-1] = x[0]
y[-1] = y[0]
return x,y
|
|
#!/usr/bin/env python
#
# Copyright 2009, Google 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 Google 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.
"""fuse_gtest_files.py v0.2.0
Fuses Google Test source code into a .h file and a .cc file.
SYNOPSIS
fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR
Scans GTEST_ROOT_DIR for Google Test source code, and generates
two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc.
Then you can build your tests by adding OUTPUT_DIR to the include
search path and linking with OUTPUT_DIR/gtest/gtest-all.cc. These
two files contain everything you need to use Google Test. Hence
you can "install" Google Test by copying them to wherever you want.
GTEST_ROOT_DIR can be omitted and defaults to the parent
directory of the directory holding this script.
EXAMPLES
./fuse_gtest_files.py fused_gtest
./fuse_gtest_files.py path/to/unpacked/gtest fused_gtest
This tool is experimental. In particular, it assumes that there is no
conditional inclusion of Google Test headers. Please report any
problems to [email protected]. You can read
http://code.google.com/p/gtest/wiki/GoogleTestAdvancedGuide for
more information.
"""
__author__ = '[email protected] (Zhanyong Wan)'
import os
import re
try:
from sets import Set as set # For Python 2.3 compatibility
except ImportError:
pass
import sys
# We assume that this file is in the scripts/ directory in the Google
# Test root directory.
DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
# Regex for matching '#include "gtest/..."'.
INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gtest/.+)"')
# Regex for matching '#include "src/..."'.
INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"')
# Where to find the source seed files.
GTEST_H_SEED = 'include/gtest/gtest.h'
GTEST_SPI_H_SEED = 'include/gtest/gtest-spi.h'
GTEST_ALL_CC_SEED = 'src/gtest-all.cc'
# Where to put the generated files.
GTEST_H_OUTPUT = 'gtest/gtest.h'
GTEST_ALL_CC_OUTPUT = 'gtest/gtest-all.cc'
def VerifyFileExists(directory, relative_path):
"""Verifies that the given file exists; aborts on failure.
relative_path is the file path relative to the given directory.
"""
if not os.path.isfile(os.path.join(directory, relative_path)):
print('ERROR: Cannot find %s in directory %s.' % (relative_path,
directory))
print('Please either specify a valid project root directory '
'or omit it on the command line.')
sys.exit(1)
def ValidateGTestRootDir(gtest_root):
"""Makes sure gtest_root points to a valid gtest root directory.
The function aborts the program on failure.
"""
VerifyFileExists(gtest_root, GTEST_H_SEED)
VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED)
def VerifyOutputFile(output_dir, relative_path):
"""Verifies that the given output file path is valid.
relative_path is relative to the output_dir directory.
"""
# Makes sure the output file either doesn't exist or can be overwritten.
output_file = os.path.join(output_dir, relative_path)
if os.path.exists(output_file):
# TODO([email protected]): The following user-interaction doesn't
# work with automated processes. We should provide a way for the
# Makefile to force overwriting the files.
print('%s already exists in directory %s - overwrite it? (y/N) ' %
(relative_path, output_dir))
answer = sys.stdin.readline().strip()
if answer not in ['y', 'Y']:
print('ABORTED.')
sys.exit(1)
# Makes sure the directory holding the output file exists; creates
# it and all its ancestors if necessary.
parent_directory = os.path.dirname(output_file)
if not os.path.isdir(parent_directory):
os.makedirs(parent_directory)
def ValidateOutputDir(output_dir):
"""Makes sure output_dir points to a valid output directory.
The function aborts the program on failure.
"""
VerifyOutputFile(output_dir, GTEST_H_OUTPUT)
VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT)
def FuseGTestH(gtest_root, output_dir):
"""Scans folder gtest_root to generate gtest/gtest.h in output_dir."""
output_file = open(os.path.join(output_dir, GTEST_H_OUTPUT), 'w')
processed_files = set() # Holds all gtest headers we've processed.
def ProcessFile(gtest_header_path):
"""Processes the given gtest header file."""
# We don't process the same header twice.
if gtest_header_path in processed_files:
return
processed_files.add(gtest_header_path)
# Reads each line in the given gtest header.
for line in open(os.path.join(gtest_root, gtest_header_path), 'r'):
m = INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
# It's '#include "gtest/..."' - let's process it recursively.
ProcessFile('include/' + m.group(1))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GTEST_H_SEED)
output_file.close()
def FuseGTestAllCcToFile(gtest_root, output_file):
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_file."""
processed_files = set()
def ProcessFile(gtest_source_file):
"""Processes the given gtest source file."""
# We don't process the same #included file twice.
if gtest_source_file in processed_files:
return
processed_files.add(gtest_source_file)
# Reads each line in the given gtest source file.
for line in open(os.path.join(gtest_root, gtest_source_file), 'r'):
m = INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
if 'include/' + m.group(1) == GTEST_SPI_H_SEED:
# It's '#include "gtest/gtest-spi.h"'. This file is not
# #included by "gtest/gtest.h", so we need to process it.
ProcessFile(GTEST_SPI_H_SEED)
else:
# It's '#include "gtest/foo.h"' where foo is not gtest-spi.
# We treat it as '#include "gtest/gtest.h"', as all other
# gtest headers are being fused into gtest.h and cannot be
# #included directly.
# There is no need to #include "gtest/gtest.h" more than once.
if not GTEST_H_SEED in processed_files:
processed_files.add(GTEST_H_SEED)
output_file.write('#include "%s"\n' % (GTEST_H_OUTPUT,))
else:
m = INCLUDE_SRC_FILE_REGEX.match(line)
if m:
# It's '#include "src/foo"' - let's process it recursively.
ProcessFile(m.group(1))
else:
output_file.write(line)
ProcessFile(GTEST_ALL_CC_SEED)
def FuseGTestAllCc(gtest_root, output_dir):
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir."""
output_file = open(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w')
FuseGTestAllCcToFile(gtest_root, output_file)
output_file.close()
def FuseGTest(gtest_root, output_dir):
"""Fuses gtest.h and gtest-all.cc."""
ValidateGTestRootDir(gtest_root)
ValidateOutputDir(output_dir)
FuseGTestH(gtest_root, output_dir)
FuseGTestAllCc(gtest_root, output_dir)
def main():
argc = len(sys.argv)
if argc == 2:
# fuse_gtest_files.py OUTPUT_DIR
FuseGTest(DEFAULT_GTEST_ROOT_DIR, sys.argv[1])
elif argc == 3:
# fuse_gtest_files.py GTEST_ROOT_DIR OUTPUT_DIR
FuseGTest(sys.argv[1], sys.argv[2])
else:
print(__doc__)
sys.exit(1)
if __name__ == '__main__':
main()
|
|
import PyQt4.QtGui as QtGui
import PyQt4.QtCore as QtCore
import xlrd
import xlwt
import functools
import data_mgmt_err_window
import data_writer_new
import cw_tooltips
import pickle
import global_vars
import webbrowser
import os
from database_search import fx_window, gen_tag_window, genre_window
from xlutils.copy import copy
import sys
class ChangeWindow(QtGui.QMainWindow):
def __init__(self, inp_row=None, info_change=False, free_entry=False):
"""
:param inp_row: Specifies input row to be overwritten when user is editing a video entry.
:param info_change: Specifies whether this window is to edit an existing video or enter a new one.
:param free_entry: Specifies whether the user can enter videos without raising errors for missing input.
This is a window used to either enter a new video into the database, or to edit an existing video, depending on
where the user accesses it from within the program.
"""
super(ChangeWindow, self).__init__()
self.cwd = os.getcwd()
self.inp_row = inp_row
self.info_change = info_change
self.free_entry = free_entry
self.book = xlrd.open_workbook(global_vars.global_vars())
self.sheet = self.book.sheet_by_index(0)
self.setFixedSize(self.sizeHint())
self.write_book = copy(self.book)
self.write_sheet = self.write_book.get_sheet(0)
vLayout = QtGui.QVBoxLayout()
grid1 = QtGui.QGridLayout()
grid1.setColumnMinimumWidth(1, 15)
grid1.setRowMinimumHeight(3, 10)
grid1.setRowMinimumHeight(4, 10)
grid1.setRowMinimumHeight(9, 10)
grid1.setRowMinimumHeight(14, 10)
grid1.setRowMinimumHeight(20, 10)
grid1.setRowMinimumHeight(25, 10)
grid1.setRowMinimumHeight(27, 10)
grid1.setRowMinimumHeight(31, 10)
# Row 0 - Edit label and search buttons
self.editEntryLabel = QtGui.QLabel()
self.editEntryLabel.setText('Edit')
self.underlineFontStyle = QtGui.QFont()
self.underlineFontStyle.setUnderline(True)
self.underlineFontStyle.setBold(True)
self.editEntryLabel.setFont(self.underlineFontStyle)
self.YTlogo = QtGui.QIcon(self.cwd + '/icons/YouTube-icon-full_color.png')
self.YTlogoSize = QtCore.QSize(25, 25)
self.orgLogo = QtGui.QIcon(self.cwd + '/icons/AMVLogo2010.png')
self.orgLogoSize = QtCore.QSize(35, 25)
self.searchYT = QtGui.QPushButton()
self.searchYT.setIcon(self.YTlogo)
self.searchYT.setToolTip('Search for this video on YouTube')
self.searchYT.setIconSize(self.YTlogoSize)
self.searchYT.setFixedSize(45, 30)
self.searchOrg = QtGui.QPushButton()
self.searchOrg.setIcon(self.orgLogo)
self.searchOrg.setToolTip('Search for this video on AnimeMusicVideos.org')
self.searchOrg.setIconSize(self.orgLogoSize)
self.searchOrg.setFixedSize(45, 30)
# Row 1 - Editor 1
self.editorLabel = QtGui.QLabel()
self.editorLabel.setText('Editor username(s):')
self.editorBox1 = QtGui.QLineEdit()
self.changeEditor = QtGui.QCheckBox()
self.editorBox1.setFixedWidth(150)
grid1.addWidget(self.editorLabel, 1, 2)
grid1.addWidget(self.editorBox1, 1, 3, 1, 4)
# Row 2 - Editor 2
self.editorBox2 = QtGui.QLineEdit()
self.MEPcheckbox = QtGui.QCheckBox('More than two')
self.editorBox2.setFixedWidth(150)
self.editorList = []
for row in xrange(1, self.sheet.nrows):
if unicode(self.sheet.cell_value(row, 0)) not in self.editorList:
if ' // ' in unicode(self.sheet.cell_value(row, 0)):
temp_list = unicode(self.sheet.cell_value(row, 0)).split(' // ')
for editor in temp_list:
if editor not in self.editorList:
self.editorList.append(editor)
else:
self.editorList.append(unicode(self.sheet.cell_value(row, 0)))
self.editorListSorted = sorted(self.editorList, key=lambda x: x.lower())
self.editorCompleter = QtGui.QCompleter(self.editorListSorted)
self.editorCompleter.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.editorCompleter.setMaxVisibleItems(15)
self.editorBox1.setCompleter(self.editorCompleter)
self.editorBox2.setCompleter(self.editorCompleter)
grid1.addWidget(self.editorBox2, 2, 3, 1, 4)
grid1.addWidget(self.MEPcheckbox, 2, 7, 1, 4)
# Row 3 - Pseudonyms
self.pseudoLabel = QtGui.QLabel()
self.pseudoLabel.setText('Additional usernames\n'
'(pseudonyms):')
self.changePseudo = QtGui.QCheckBox()
self.pseudoBox = QtGui.QLineEdit()
self.pseudoBox.setFixedWidth(150)
grid1.addWidget(self.pseudoLabel, 3, 2)
grid1.addWidget(self.pseudoBox, 3, 3, 1, 4)
# Row 4 - spacer
# Row 5 - Video title
self.videoLabel = QtGui.QLabel()
self.videoLabel.setText('Video title:')
self.videoBox = QtGui.QLineEdit()
self.changeVideoTitle = QtGui.QCheckBox()
self.videoBox.setFixedWidth(150)
grid1.addWidget(self.videoLabel, 5, 2)
grid1.addWidget(self.videoBox, 5, 3, 1, 4)
# Row 6 - Release date
self.dateLabel = QtGui.QLabel()
self.dateLabel.setText('Release date:')
self.dateMonth = QtGui.QComboBox()
self.dateYear = QtGui.QComboBox()
self.dateUnk = QtGui.QCheckBox('Date unknown')
self.changeDate = QtGui.QCheckBox()
self.monthDict = {"01 (Jan)": 1,
"02 (Feb)": 2,
"03 (Mar)": 3,
"04 (Apr)": 4,
"05 (May)": 5,
"06 (Jun)": 6,
"07 (Jul)": 7,
"08 (Aug)": 8,
"09 (Sep)": 9,
"10 (Oct)": 10,
"11 (Nov)": 11,
"12 (Dec)": 12}
self.yearDict = {"1982": 42, "1983": 41, "1984": 40, "1985": 39, "1986": 38, "1987": 37,
"1988": 36, "1989": 35, "1990": 34, "1991": 33, "1992": 31, "1993": 30,
"1994": 29, "1995": 28, "1996": 27, "1997": 26, "1998": 25, "1999": 24,
"2000": 23, "2001": 22, "2002": 21, "2003": 20, "2004": 19, "2005": 18,
"2006": 17, "2007": 16, "2008": 15, "2009": 14, "2010": 13, "2011": 12,
"2012": 11, "2013": 10, "2014": 9, "2015": 8, "2016": 7, "2017": 6,
"2018": 5, "2019": 4, "2020": 3, "2021": 2, "2022": 1
}
self.monthList = []
for key, val in self.monthDict.iteritems():
self.monthList.append(key)
self.monthList.sort()
self.monthList.insert(0, '')
for month in self.monthList:
self.dateMonth.addItem(month)
self.yearList = []
for key, val in self.yearDict.iteritems():
self.yearList.append(key)
self.yearList.sort()
self.yearList.reverse()
self.yearList.insert(0, '')
for year in self.yearList:
self.dateYear.addItem(year)
self.dateMonth.setMaxVisibleItems(13)
self.dateYear.setMaxVisibleItems(20)
grid1.addWidget(self.dateLabel, 6, 2)
grid1.addWidget(self.dateMonth, 6, 3, 1, 2)
grid1.addWidget(self.dateYear, 6, 5, 1, 2)
grid1.addWidget(self.dateUnk, 6, 7, 1, 4)
# Row 7 - My Rating
self.myRatingLabel = QtGui.QLabel()
self.myRatingLabel.setText('My Rating:')
self.myRatingDrop = QtGui.QComboBox()
self.changeMyRating = QtGui.QCheckBox()
self.myRatingChoices = [0.0, 0.5]
for x in xrange(1, 11):
self.myRatingChoices.append(x + 0.0)
self.myRatingChoices.append(x + 0.5)
for rating in self.myRatingChoices:
if rating != self.myRatingChoices[-1]:
self.myRatingDrop.addItem(str(rating))
grid1.addWidget(self.myRatingLabel, 7, 2)
grid1.addWidget(self.myRatingDrop, 7, 3, 1, 2)
# Row 8 - Star rating
self.starRatingLabel = QtGui.QLabel()
self.starRatingLabel.setText('Star Rating:')
self.starRatingBox = QtGui.QLineEdit()
self.changeStarRating = QtGui.QCheckBox()
self.starRatingBox.setFixedWidth(50)
grid1.addWidget(self.starRatingLabel, 8, 2)
grid1.addWidget(self.starRatingBox, 8, 3, 1, 2)
# Row 9 - spacer
# Row 10 - Anime 1
self.animeLabel = QtGui.QLabel()
self.animeLabel.setText('Anime:')
self.animeBox1 = QtGui.QLineEdit()
self.changeAnime = QtGui.QCheckBox()
grid1.addWidget(self.animeLabel, 10, 2)
grid1.addWidget(self.animeBox1, 10, 3, 1, 4)
# Row 11 - Anime 2
self.animeBox2 = QtGui.QLineEdit()
grid1.addWidget(self.animeBox2, 11, 3, 1, 4)
# Row 12 - Anime 3
self.animeBox3 = QtGui.QLineEdit()
grid1.addWidget(self.animeBox3, 12, 3, 1, 4)
# Row 13 - Anime 4
self.animeBox4 = QtGui.QLineEdit()
self.animeVarious = QtGui.QCheckBox('More than four')
self.animeList = []
for row in xrange(1, self.sheet.nrows):
if (unicode(self.sheet.cell_value(row, 6)) not in self.animeList) and \
(' // ' not in unicode(self.sheet.cell_value(row, 6))):
self.animeList.append(unicode(self.sheet.cell_value(row, 6)))
elif ' // ' in unicode(self.sheet.cell_value(row, 6)):
temp_anime_list = unicode(self.sheet.cell_value(row, 6)).split(' // ')
for anime in temp_anime_list:
if anime not in self.animeList:
self.animeList.append(anime)
self.animeListSorted = sorted(self.animeList, key=lambda x: x.lower())
self.animeCompleter = QtGui.QCompleter(self.animeListSorted)
self.animeCompleter.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.animeCompleter.setMaxVisibleItems(15)
self.animeBox1.setCompleter(self.animeCompleter)
self.animeBox2.setCompleter(self.animeCompleter)
self.animeBox3.setCompleter(self.animeCompleter)
self.animeBox4.setCompleter(self.animeCompleter)
grid1.addWidget(self.animeBox4, 13, 3, 1, 4)
grid1.addWidget(self.animeVarious, 13, 7, 1, 4)
# Row 14 - spacer
# Row 15 - Artist
self.artistLabel = QtGui.QLabel()
self.artistLabel.setText('Song artist:')
self.artistBox = QtGui.QLineEdit()
self.changeArtist = QtGui.QCheckBox()
self.artistBox.setFixedWidth(150)
self.artistList = []
for row in xrange(1, self.sheet.nrows):
if unicode(self.sheet.cell_value(row, 7)) not in self.artistList:
self.artistList.append(unicode(self.sheet.cell_value(row, 7)))
self.artistListSorted = sorted(self.artistList, key=lambda x: x.lower())
self.artistCompleter = QtGui.QCompleter(self.artistListSorted)
self.artistCompleter.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.artistCompleter.setMaxVisibleItems(15)
self.artistBox.setCompleter(self.artistCompleter)
grid1.addWidget(self.artistLabel, 15, 2)
grid1.addWidget(self.artistBox, 15, 3, 1, 4)
# Row 16 - Song title
self.songTitleLabel = QtGui.QLabel()
self.songTitleLabel.setText('Song title:')
self.songTitleBox = QtGui.QLineEdit()
self.changeSongTitle = QtGui.QCheckBox()
self.songTitleBox.setFixedWidth(150)
grid1.addWidget(self.songTitleLabel, 16, 2)
grid1.addWidget(self.songTitleBox, 16, 3, 1, 4)
# Row 17 - Song genre
self.songGenreLabel = QtGui.QLabel()
self.songGenreLabel.setText('Song genre:')
self.songGenreBox = QtGui.QLineEdit()
self.changeSongGenre = QtGui.QCheckBox()
self.songGenreDrop = QtGui.QComboBox()
self.songGenreBox.setFixedWidth(100)
self.songGenreDrop.setFixedWidth(170)
self.songGenreList = [""]
for row in xrange(1, self.sheet.nrows):
if self.sheet.cell_value(row, 9).lower() not in self.songGenreList:
self.songGenreList.append(self.sheet.cell_value(row, 9).lower())
self.songGenreList.sort()
for entry in self.songGenreList:
self.songGenreDrop.addItem(entry.capitalize())
self.songGenreDrop.setMaxVisibleItems(20)
grid1.addWidget(self.songGenreLabel, 17, 2)
grid1.addWidget(self.songGenreDrop, 17, 3, 1, 4)
grid1.addWidget(self.songGenreBox, 17, 7, 1, 4)
# Row 18 - spacer
# Row 19 - Video length
self.lengthLabel = QtGui.QLabel()
self.lengthLabel.setText('Video length:')
self.lengthMinBox = QtGui.QLineEdit()
self.lengthMinBox.setFixedWidth(20)
self.lengthMinLabel = QtGui.QLabel()
self.lengthMinLabel.setText('min')
self.lengthSecBox = QtGui.QLineEdit()
self.lengthSecBox.setFixedWidth(25)
self.lengthSecLabel = QtGui.QLabel()
self.lengthSecLabel.setText('sec')
self.changeLength = QtGui.QCheckBox()
grid1.addWidget(self.lengthLabel, 19, 2)
grid1.addWidget(self.lengthMinBox, 19, 3)
grid1.addWidget(self.lengthMinLabel, 19, 4)
grid1.addWidget(self.lengthSecBox, 19, 5)
grid1.addWidget(self.lengthSecLabel, 19, 6)
# Row 20 - spacer
# Row 21 - Genre tags
self.genreTagButton = QtGui.QPushButton('Genre tags')
self.genreTagBox = QtGui.QLineEdit()
self.genreTagBox.setReadOnly(True)
self.changeGenreTags = QtGui.QCheckBox()
self.genreTagXBtn = QtGui.QPushButton('X')
self.genreTagBox.setFixedWidth(220)
self.genreTagXBtn.setFixedWidth(20)
self.genreTagXBtn.setToolTip('Clear genre tags')
grid1.addWidget(self.genreTagButton, 21, 2)
grid1.addWidget(self.genreTagBox, 21, 3, 1, 5)
grid1.addWidget(self.genreTagXBtn, 21, 8)
# Row 22 - General tags
self.generalTagButton = QtGui.QPushButton('General tags')
self.generalTagBox = QtGui.QLineEdit()
self.generalTagBox.setReadOnly(True)
self.changeGeneralTags = QtGui.QCheckBox()
self.generalTagXBtn = QtGui.QPushButton('X')
self.generalTagBox.setFixedWidth(220)
self.generalTagXBtn.setFixedWidth(20)
self.generalTagXBtn.setToolTip('Clear general tags')
grid1.addWidget(self.generalTagButton, 22, 2)
grid1.addWidget(self.generalTagBox, 22, 3, 1, 5)
grid1.addWidget(self.generalTagXBtn, 22, 8)
# Row 23 - FX tags
self.fxTagButton = QtGui.QPushButton('FX tags')
self.fxTagBox = QtGui.QLineEdit()
self.fxTagBox.setReadOnly(True)
self.changeFXTags = QtGui.QCheckBox()
self.fxTagXBtn = QtGui.QPushButton('X')
self.fxTagBox.setFixedWidth(220)
self.fxTagXBtn.setFixedWidth(20)
self.fxTagXBtn.setToolTip('Clear FX tags')
grid1.addWidget(self.fxTagButton, 23, 2)
grid1.addWidget(self.fxTagBox, 23, 3, 1, 5)
grid1.addWidget(self.fxTagXBtn, 23, 8)
# Row 24 - Tag radio buttons
# REMOVED
# Row 25 - spacer
# Row 26 - Comments
self.commentsLabel = QtGui.QLabel()
self.commentsLabel.setText('Comments:')
self.commentsBox = QtGui.QTextEdit()
self.commentsBox.setFixedSize(220, 60)
self.changeComments = QtGui.QCheckBox()
grid1.addWidget(self.commentsLabel, 26, 2)
grid1.addWidget(self.commentsBox, 26, 3, 1, 5)
# Row 27 - spacer
# Row 28 - URL
self.URLlabel = QtGui.QLabel()
self.URLlabel.setText('Video URL:')
self.URLbox = QtGui.QLineEdit()
self.URLbox.setFixedWidth(220)
self.URLX = QtGui.QPushButton('X')
self.URLX.setFixedWidth(20)
self.URLX.setToolTip('Clear URL')
self.URLgo = QtGui.QPushButton('Go')
self.URLgo.setFixedWidth(45)
self.URLgo.setToolTip('Open URL in the default browser')
self.changeURL = QtGui.QCheckBox()
grid1.addWidget(self.URLlabel, 28, 2)
grid1.addWidget(self.URLbox, 28, 3, 1, 5)
grid1.addWidget(self.URLX, 28, 8)
# Row 29 - Local file
self.localFileButton = QtGui.QPushButton('Local file')
self.localFileButton.setFixedWidth(76)
self.localFileBox = QtGui.QLineEdit()
self.localFileBox.setFixedWidth(220)
self.localFileBox.setReadOnly(True)
self.localFileX = QtGui.QPushButton('X')
self.localFileX.setFixedWidth(20)
self.localFileX.setToolTip('Clear local file path')
self.watchLocalFile = QtGui.QPushButton('Watch')
self.watchLocalFile.setFixedWidth(45)
self.watchLocalFile.setToolTip('Open video file in default video player')
self.changeLocalFile = QtGui.QCheckBox()
grid1.addWidget(self.localFileButton, 29, 2, 1, 2)
grid1.addWidget(self.localFileBox, 29, 3, 1, 5)
grid1.addWidget(self.localFileX, 29, 8)
grid1.addWidget(self.watchLocalFile, 29, 9)
# Row 30 - Delete button
self.deleteButton = QtGui.QPushButton('Delete entry')
self.changeDeleteButton = QtGui.QCheckBox()
# Row 31 - spacer
# Row 32 - Action buttons
self.backButton = QtGui.QPushButton('Back')
self.submitButton = QtGui.QPushButton('Submit')
self.copyButton = QtGui.QPushButton('Copy video')
self.copyButton.setFixedWidth(80)
self.copyButton.setToolTip('Copies video from current database to\na database of your choice.')
if info_change == True:
self.backButton.setFixedWidth(150)
self.submitButton.setFixedWidth(150)
grid1.addWidget(self.backButton, 32, 0, 1, 5)
grid1.addWidget(self.submitButton, 32, 4, 1, 3)
else:
self.backButton.setFixedWidth(150)
self.submitButton.setFixedWidth(150)
grid1.addWidget(self.backButton, 32, 2, 1, 4)
grid1.addWidget(self.submitButton, 32, 6, 1, 5)
# For edit mode
if info_change == True:
grid1.setRowMinimumHeight(31, 10)
grid1.addWidget(self.editEntryLabel, 0, 0)
grid1.addWidget(self.searchYT, 0, 8)
grid1.addWidget(self.searchOrg, 0, 9)
grid1.addWidget(self.changeEditor, 1, 0)
grid1.addWidget(self.changePseudo, 3, 0)
grid1.addWidget(self.changeVideoTitle, 5, 0)
grid1.addWidget(self.changeDate, 6, 0)
grid1.addWidget(self.changeMyRating, 7, 0)
grid1.addWidget(self.changeStarRating, 8, 0)
grid1.addWidget(self.changeAnime, 10, 0)
grid1.addWidget(self.changeArtist, 15, 0)
grid1.addWidget(self.changeSongTitle, 16, 0)
grid1.addWidget(self.changeSongGenre, 17, 0)
grid1.addWidget(self.changeLength, 19, 0)
grid1.addWidget(self.changeGenreTags, 21, 0)
grid1.addWidget(self.changeGeneralTags, 22, 0)
grid1.addWidget(self.changeFXTags, 23, 0)
grid1.addWidget(self.changeComments, 26, 0)
grid1.addWidget(self.changeURL, 28, 0)
grid1.addWidget(self.URLgo, 28, 9)
grid1.addWidget(self.changeLocalFile, 29, 0)
grid1.addWidget(self.changeDeleteButton, 30, 0)
grid1.addWidget(self.deleteButton, 30, 2, 1, 2)
grid1.addWidget(self.copyButton, 32, 8, 1, 3)
grid1.setAlignment(self.copyButton, QtCore.Qt.AlignRight)
# Edit checkbox associations
self.editCheckboxAssc = {self.changeEditor: [self.editorBox1, self.editorBox2, self.MEPcheckbox],
self.changePseudo: [self.pseudoBox],
self.changeVideoTitle: [self.videoBox],
self.changeDate: [self.dateMonth, self.dateYear, self.dateUnk],
self.changeMyRating: [self.myRatingDrop],
self.changeStarRating: [self.starRatingBox],
self.changeAnime: [self.animeBox1, self.animeBox2, self.animeBox3, self.animeBox4,
self.animeVarious],
self.changeArtist: [self.artistBox],
self.changeSongTitle: [self.songTitleBox],
self.changeSongGenre: [self.songGenreDrop, self.songGenreBox],
self.changeLength: [self.lengthMinBox, self.lengthSecBox],
self.changeGenreTags: [self.genreTagButton, self.genreTagBox, self.genreTagXBtn],
self.changeGeneralTags: [self.generalTagButton, self.generalTagBox,
self.generalTagXBtn],
self.changeFXTags: [self.fxTagButton, self.fxTagBox, self.fxTagXBtn],
self.changeComments: [self.commentsBox],
self.changeURL: [self.URLbox, self.URLX],
self.changeLocalFile: [self.localFileButton, self.localFileBox, self.localFileX],
self.changeDeleteButton: [self.deleteButton]
}
for key, val in self.editCheckboxAssc.iteritems():
for wid in val:
wid.setDisabled(True)
# Edit checkbox signals / slots
self.changeEditor.clicked.connect(
lambda: self.change_check(self.changeEditor, self.editCheckboxAssc[self.changeEditor]))
self.changePseudo.clicked.connect(
lambda: self.change_check(self.changePseudo, self.editCheckboxAssc[self.changePseudo]))
self.changeVideoTitle.clicked.connect(
lambda: self.change_check(self.changeVideoTitle, self.editCheckboxAssc[self.changeVideoTitle]))
self.changeDate.clicked.connect(
lambda: self.change_check(self.changeDate, self.editCheckboxAssc[self.changeDate]))
self.changeMyRating.clicked.connect(
lambda: self.change_check(self.changeMyRating, self.editCheckboxAssc[self.changeMyRating]))
self.changeStarRating.clicked.connect(
lambda: self.change_check(self.changeStarRating, self.editCheckboxAssc[self.changeStarRating]))
self.changeAnime.clicked.connect(
lambda: self.change_check(self.changeAnime, self.editCheckboxAssc[self.changeAnime]))
self.changeArtist.clicked.connect(
lambda: self.change_check(self.changeArtist, self.editCheckboxAssc[self.changeArtist]))
self.changeSongTitle.clicked.connect(
lambda: self.change_check(self.changeSongTitle, self.editCheckboxAssc[self.changeSongTitle]))
self.changeSongGenre.clicked.connect(
lambda: self.change_check(self.changeSongGenre, self.editCheckboxAssc[self.changeSongGenre]))
self.changeLength.clicked.connect(
lambda: self.change_check(self.changeLength, self.editCheckboxAssc[self.changeLength]))
self.changeGenreTags.clicked.connect(
lambda: self.change_check(self.changeGenreTags, self.editCheckboxAssc[self.changeGenreTags]))
self.changeGeneralTags.clicked.connect(
lambda: self.change_check(self.changeGeneralTags, self.editCheckboxAssc[self.changeGeneralTags]))
self.changeFXTags.clicked.connect(
lambda: self.change_check(self.changeFXTags, self.editCheckboxAssc[self.changeFXTags]))
self.changeComments.clicked.connect(
lambda: self.change_check(self.changeComments, self.editCheckboxAssc[self.changeComments]))
self.changeURL.clicked.connect(
lambda: self.change_check(self.changeURL, self.editCheckboxAssc[self.changeURL]))
self.changeLocalFile.clicked.connect(
lambda: self.change_check(self.changeLocalFile, self.editCheckboxAssc[self.changeLocalFile]))
self.changeDeleteButton.clicked.connect(
lambda: self.change_check(self.changeDeleteButton, self.editCheckboxAssc[self.changeDeleteButton]))
# Blank line check
self.videoBox.editingFinished.connect(
lambda: self.blank_line_check(self.changeVideoTitle, self.videoBox, 1))
self.artistBox.editingFinished.connect(lambda: self.blank_line_check(self.changeArtist, self.artistBox, 7))
self.songTitleBox.editingFinished.connect(
lambda: self.blank_line_check(self.changeSongTitle, self.songTitleBox, 8))
self.songGenreBox.editingFinished.connect(
lambda: self.blank_line_check(self.changeSongGenre, self.songGenreBox, 9))
# Delete button warning
self.changeDeleteButton.clicked.connect(self.delete_warning)
self.edit_mode()
# Tooltips
self.editorLabel.setToolTip(cw_tooltips.cwTooltips['Editor'])
self.pseudoLabel.setToolTip(cw_tooltips.cwTooltips['Pseudonym'])
self.videoLabel.setToolTip(cw_tooltips.cwTooltips['Video'])
self.dateLabel.setToolTip(cw_tooltips.cwTooltips['Release date'])
self.myRatingLabel.setToolTip(cw_tooltips.cwTooltips['My Rating'])
self.starRatingLabel.setToolTip(cw_tooltips.cwTooltips['Star Rating'])
self.animeLabel.setToolTip(cw_tooltips.cwTooltips['Anime'])
self.artistLabel.setToolTip(cw_tooltips.cwTooltips['Artist'])
self.songTitleLabel.setToolTip(cw_tooltips.cwTooltips['Song'])
self.songGenreLabel.setToolTip(cw_tooltips.cwTooltips['Genre'])
self.lengthLabel.setToolTip(cw_tooltips.cwTooltips['Length'])
self.genreTagButton.setToolTip(cw_tooltips.cwTooltips['Genre tags'])
self.generalTagButton.setToolTip(cw_tooltips.cwTooltips['General tags'])
self.fxTagButton.setToolTip(cw_tooltips.cwTooltips['FX tags'])
self.commentsLabel.setToolTip(cw_tooltips.cwTooltips['Comments'])
self.URLlabel.setToolTip(cw_tooltips.cwTooltips['URL'])
self.localFileButton.setToolTip(cw_tooltips.cwTooltips['Local file'])
# Buttons
self.searchYT.clicked.connect(self.yt_button_clicked)
self.searchOrg.clicked.connect(self.org_button_clicked)
self.fxTagButton.clicked.connect(lambda: self.tag_window('fx', str(self.fxTagBox.text())))
self.genreTagButton.clicked.connect(lambda: self.tag_window('genre', str(self.genreTagBox.text())))
self.generalTagButton.clicked.connect(lambda: self.tag_window('general', str(self.generalTagBox.text())))
self.genreTagXBtn.clicked.connect(lambda: self.x_button_clicked(self.genreTagBox))
self.generalTagXBtn.clicked.connect(lambda: self.x_button_clicked(self.generalTagBox))
self.fxTagXBtn.clicked.connect(lambda: self.x_button_clicked(self.fxTagBox))
self.backButton.clicked.connect(self.close)
self.URLgo.clicked.connect(self.URL_go)
self.URLX.clicked.connect(lambda: self.x_button_clicked(self.URLbox))
self.localFileButton.clicked.connect(self.local_file_clicked)
self.watchLocalFile.clicked.connect(self.watch_local_video)
self.localFileX.clicked.connect(lambda: self.x_button_clicked(self.localFileBox))
self.deleteButton.clicked.connect(lambda: self.submit_button_clicked(delete=True))
self.submitButton.clicked.connect(self.submit_button_clicked)
self.copyButton.clicked.connect(lambda: self.submit_button_clicked(copy_btn=True))
# Duration input check
self.lengthMinBox.editingFinished.connect(lambda: self.length_type_check(self.lengthMinBox))
self.lengthSecBox.editingFinished.connect(lambda: self.length_type_check(self.lengthSecBox))
# Other
self.starRatingBox.editingFinished.connect(self.star_rating_range)
self.songGenreDrop.activated.connect(self.genre_box_fill)
if info_change == False:
self.editorBox1.editingFinished.connect(self.same_video_check)
self.editorBox2.editingFinished.connect(self.same_video_check)
self.videoBox.editingFinished.connect(self.same_video_check)
# Layout
vLayout.addLayout(grid1)
# Widget
self.windowPos = pickle.load(open('position.p', 'rb'))
self.wid = QtGui.QWidget()
self.wid.setLayout(vLayout)
if self.info_change == True:
self.setWindowTitle(self.sheet.cell_value(self.inp_row, 0) + ' - ' +
self.sheet.cell_value(self.inp_row, 1))
else:
if self.free_entry == True:
self.setWindowTitle('Enter a video (Free Entry)')
else:
self.setWindowTitle('Enter a video (Genome Project Entry)')
self.move(self.windowPos.x(), self.windowPos.y() - 100)
self.setCentralWidget(self.wid)
def edit_mode(self):
# Editor box
if self.changeEditor.isChecked() == False:
editor = unicode(self.sheet.cell_value(self.inp_row, 0))
if ' // ' in editor:
split_editor = editor.split(' // ')
self.editorBox1.setText(split_editor[0])
self.editorBox1.setCursorPosition(0)
if '// Various' in editor:
self.MEPcheckbox.setChecked(True)
else:
self.editorBox2.setText(split_editor[1])
self.editorBox2.setCursorPosition(0)
else:
self.editorBox1.setText(editor)
self.editorBox1.setCursorPosition(0)
# Pseudonym(s)
pseudonym = unicode(self.sheet.cell_value(self.inp_row, 15))
self.pseudoBox.setText(pseudonym)
self.pseudoBox.setCursorPosition(0)
# Video box
video = unicode(self.sheet.cell_value(self.inp_row, 1))
self.videoBox.setText(video)
self.videoBox.setCursorPosition(0)
# Release date
if self.sheet.cell_value(self.inp_row, 5) == '?' or self.sheet.cell_value(self.inp_row, 5) == '':
self.dateUnk.setChecked(True)
else:
date = xlrd.xldate_as_tuple(self.sheet.cell_value(self.inp_row, 5), 0)
for key, val in self.monthDict.iteritems():
if val == date[1]:
self.dateMonth.setCurrentIndex(val)
for key, val in self.yearDict.iteritems():
if key == str(date[0]):
self.dateYear.setCurrentIndex(val)
# My rating
myRating = self.sheet.cell_value(self.inp_row, 2)
self.myRatingDrop.setCurrentIndex(myRating * 2)
# Star rating
starRating = self.sheet.cell_value(self.inp_row, 3)
self.starRatingBox.setText(str(starRating))
# Anime
anime = unicode(self.sheet.cell_value(self.inp_row, 6))
animeList = anime.split(' // ')
if anime == 'Various':
self.animeVarious.setChecked(True)
else:
if len(animeList) >= 1:
self.animeBox1.setText(animeList[0])
self.animeBox1.setCursorPosition(0)
if len(animeList) >= 2:
self.animeBox2.setText(animeList[1])
self.animeBox2.setCursorPosition(0)
if len(animeList) >= 3:
self.animeBox3.setText(animeList[2])
self.animeBox3.setCursorPosition(0)
if animeList == 4:
self.animeBox4.setText(animeList[3])
self.animeBox4.setCursorPosition(0)
# Song artist
songArtist = unicode(self.sheet.cell_value(self.inp_row, 7))
self.artistBox.setText(songArtist)
self.artistBox.setCursorPosition(0)
# Song title
songTitle = unicode(self.sheet.cell_value(self.inp_row, 8))
self.songTitleBox.setText(songTitle)
self.songTitleBox.setCursorPosition(0)
# Song genre
songGenre = self.sheet.cell_value(self.inp_row, 9)
self.songGenreBox.setText(songGenre)
self.songGenreBox.setCursorPosition(0)
# Video length
if self.sheet.cell_value(self.inp_row, 10) == '':
length = 0
else:
length = self.sheet.cell_value(self.inp_row, 10)
self.lengthMinBox.setText(str(int(length) / 60))
self.lengthSecBox.setText(str(int(length) % 60))
# Genre tags
genreTags = self.sheet.cell_value(self.inp_row, 4)
self.genreTagBox.setText(genreTags)
self.genreTagBox.setCursorPosition(0)
# General tags
generalTags = self.sheet.cell_value(self.inp_row, 11)
self.generalTagBox.setText(generalTags)
self.generalTagBox.setCursorPosition(0)
# FX tags
FXtags = self.sheet.cell_value(self.inp_row, 12)
self.fxTagBox.setText(FXtags)
self.fxTagBox.setCursorPosition(0)
# Comments
comments = self.sheet.cell_value(self.inp_row, 13)
self.commentsBox.setText(comments)
# URL
url = self.sheet.cell_value(self.inp_row, 14)
self.URLbox.setText(url)
self.URLbox.setCursorPosition(0)
# Local file
localFile = self.sheet.cell_value(self.inp_row, 16)
self.localFileBox.setText(localFile)
self.localFileBox.setCursorPosition(0)
def yt_button_clicked(self):
editor = unicode(self.editorBox1.text())
video = unicode(self.videoBox.text())
anime = unicode(self.animeBox1.text())
search_string_spaces = editor + ' ' + video + ' ' + anime
search_string_list = search_string_spaces.split(' ')
search_string = ''
for ind in xrange(0, len(search_string_list)):
if ind == len(search_string_list) - 1:
search_string += search_string_list[ind] + '+amv'
else:
search_string += search_string_list[ind] + '+'
webbrowser.open('https://www.youtube.com/results?search_query=' + search_string)
def org_button_clicked(self):
editor = unicode(self.editorBox1.text())
video = unicode(self.videoBox.text())
webbrowser.open(
'http://www.animemusicvideos.org/search/supersearch.php?anime_criteria=&artist_criteria=&song_criteria=&member_criteria=' + \
editor + '&studio_criteria=&spread=less&title=' + video + \
'&comments=&download=&con=&year=&format_id=&o=7&d=1&recent=on&go=go')
def same_video_check(self):
# Dynamic check to see if the video the user is entering on data entry is already in the database. If so,
# directs user to the video's Edit Mode entry to (potentially) save the user time.
editor_name = self.editorBox1.text() + unicode(' // ') + self.editorBox2.text()
if editor_name[-4:] == ' // ':
editor_name = editor_name[:-4]
elif editor_name[0:4] == ' // ':
editor_name = editor_name[4:]
if self.MEPcheckbox.isChecked():
editor_name += ' // Various'
for row in xrange(self.sheet.nrows):
if editor_name != '' and editor_name == self.sheet.cell_value(row, 0) and \
unicode(self.videoBox.text()) == self.sheet.cell_value(row, 1):
video_row = row
err_window = data_mgmt_err_window.DBMgmtErrorWindow('same video', vid_row=video_row)
if err_window.result == QtGui.QMessageBox.Yes:
self.close()
def change_check(self, checkbox, wid_list):
# Enables or disables widgets depending on whether the corresponding 'Edit' checkbox is checked.
if checkbox.isChecked():
for wid in wid_list:
wid.setEnabled(True)
else:
for wid in wid_list:
wid.setDisabled(True)
def blank_line_check(self, change_check, edit_box, col):
# Confirms that there is always something in certain text boxes, even if user tries to erase the data without
# putting something else in.
if change_check.isChecked() == True and str(edit_box.text()) == '':
edit_box.setText(self.sheet.cell_value(self.inp_row, col))
def length_type_check(self, inp_wid):
# Checks to make sure that the min + sec entered are greater than 0.
try:
int(inp_wid.text())
except:
inp_wid.setText('0')
# Check to confirm input min/sec are not both 0
if self.free_entry == False: # This check does not occur on Free Entry
if self.lengthMinBox.text() != '' and self.lengthSecBox.text() != '':
if (int(self.lengthMinBox.text()) * 60) + int(self.lengthSecBox.text()) == 0:
data_mgmt_err_window.DBMgmtErrorWindow('zero dur')
self.lengthSecBox.setFocus()
if int(inp_wid.text()) < 0:
data_mgmt_err_window.DBMgmtErrorWindow('less than zero')
inp_wid.setFocus()
def star_rating_range(self):
if str(
self.starRatingBox.text()) == '': # If user navigates away from SR box without entering anything, fill w/0
self.starRatingBox.setText('0.00')
else:
try: # Tests to make sure star rating input is correct type and range
float(str(self.starRatingBox.text()))
if float(self.starRatingBox.text()) > 5 or 0 < float(self.starRatingBox.text()) < 1 or \
float(self.starRatingBox.text()) < 0:
data_mgmt_err_window.DBMgmtErrorWindow('star range')
self.starRatingBox.setFocus()
except: # If not correct input type, show error window
data_mgmt_err_window.DBMgmtErrorWindow('star type')
self.starRatingBox.setFocus()
def genre_box_fill(self):
# Fills song genre text box with user-made selection in genre dropdown.
self.songGenreBox.setText(self.songGenreDrop.currentText())
self.songGenreBox.setCursorPosition(0)
def tag_window(self, win_type, inp_tags):
inp_tag_list = inp_tags.split(', ')
if win_type == 'genre':
genreWindow = genre_window.GenreWindow(custom_search=True)
genreWindow.genreSearchLabel.setText('Select at least one of the following\ngenre tags:')
genreWindow.setWindowTitle('Genre Tags')
genreWindow.show()
for tag in inp_tag_list: # Set genre checkboxes to be checked if the tag is listed in text box
for key, val in genreWindow.genreLabels1.iteritems():
if tag.lower() == val.lower():
key.setChecked(True)
for key, val in genreWindow.genreLabels2.iteritems():
if tag.lower() == val.lower():
key.setChecked(True)
genreWindow.searchButton.clicked.connect(lambda: self.tag_window_clicked(
'genre', genreWindow.search_button_clicked(custom=True)))
elif win_type == 'general':
generalWindow = gen_tag_window.GenTagWindow(custom_search=True)
generalWindow.genTagLabel.setText('Select at least one of the following general tags:')
generalWindow.setWindowTitle('General Tags')
if self.MEPcheckbox.isChecked(): # Sets MEP to checked in Gen Tag window
generalWindow.tagMEP.setChecked(True)
elif self.editorBox1.text() != '' and self.editorBox2.text() != '': # Sets Collab to checked in Gen Tag Window
generalWindow.tagCollab.setChecked(True)
generalWindow.show()
for tag in inp_tag_list: # Set general checkboxes to be checked if the tag is listed in text box
for key, val in generalWindow.genTagDict1.iteritems():
if tag.lower() == val.lower():
key.setChecked(True)
for key, val in generalWindow.genTagDict2.iteritems():
if tag.lower() == 'm@d' and val.lower() == 'mad':
key.setChecked(True)
elif tag.lower() == val.lower():
key.setChecked(True)
for key, val in generalWindow.genTagDict3.iteritems():
if tag.lower() == val.lower():
key.setChecked(True)
generalWindow.searchButton.clicked.connect(lambda: self.tag_window_clicked(
'general', generalWindow.gen_tag_button_clicked(custom=True)))
elif win_type == 'fx':
fxWindow = fx_window.FXWindow(custom_search=True)
fxWindow.FXLabel.setText('Select at least one of the following FX\ntags:')
fxWindow.setWindowTitle('FX Tags')
fxWindow.show()
for tag in inp_tag_list: # Set FX checkboxes to be checked if the tag is listed in text box
for key, val in fxWindow.fxTagDict1.iteritems():
if tag.lower() == val.lower():
key.setChecked(True)
for key, val in fxWindow.fxTagDict2.iteritems():
if tag.lower() == val.lower():
key.setChecked(True)
fxWindow.searchButton.clicked.connect(lambda: self.tag_window_clicked(
'fx', fxWindow.search_button_clicked(custom=True)))
def tag_window_clicked(self, win, inp):
if inp == '':
data_mgmt_err_window.DBMgmtErrorWindow('no tags')
else:
if win == 'genre':
if 'fx' in inp and 'no effects' in str(self.fxTagBox.text()).lower():
data_mgmt_err_window.DBMgmtErrorWindow('fx error')
else:
self.genreTagBox.setText(inp)
self.genreTagBox.setCursorPosition(0)
elif win == 'general':
self.generalTagBox.setText(inp)
self.generalTagBox.setCursorPosition(0)
elif win == 'fx':
if 'no effects' in inp and 'fx' in str(self.genreTagBox.text()).lower():
data_mgmt_err_window.DBMgmtErrorWindow('fx error')
else:
self.fxTagBox.setText(inp)
self.fxTagBox.setCursorPosition(0)
def x_button_clicked(self, inp_wid):
inp_wid.setText('')
def URL_go(self):
if self.URLbox.text() != '':
webbrowser.open(self.URLbox.text())
def local_file_clicked(self):
fileName = QtGui.QFileDialog.getOpenFileName(self, 'Select a file')
if fileName:
self.localFileBox.setText(fileName)
def watch_local_video(self):
filePath = self.localFileBox.text()
if filePath != '':
try:
os.startfile(filePath)
except:
data_mgmt_err_window.DBMgmtErrorWindow('file not found')
def delete_warning(self):
if self.changeDeleteButton.isChecked():
data_mgmt_err_window.DBMgmtErrorWindow('delete entry')
def submit_button_clicked(self, delete=False, copy_btn=False):
## Testing for input errors ##
# Missing inputs
missing_inputs = []
missing_inputs_free = []
missing_inp_bool = False
# Editor box
if self.editorBox1.text() == '' and self.editorBox2.text() == '':
missing_inputs.append('Editor name(s)')
missing_inputs_free.append('Editor name(s)')
missing_inp_bool = True
# Video title
if self.videoBox.text() == '':
missing_inputs.append('Video title')
missing_inputs_free.append('Video title')
missing_inp_bool = True
# Anime
if self.animeBox1.text() == '' and self.animeBox2.text() == '' and \
self.animeBox3.text() == '' and self.animeBox4.text() == '' and \
self.animeVarious.isChecked() == False:
missing_inputs.append('Anime')
missing_inp_bool = True
# Song / duration / tags
songDict = {self.artistBox: 'Song artist',
self.songTitleBox: 'Song title',
self.songGenreBox: 'Song genre',
self.lengthMinBox: 'Video length (min)',
self.lengthSecBox: 'Video length (sec)',
self.genreTagBox: 'Genre tags',
self.generalTagBox: 'General tags',
self.fxTagBox: 'FX tags'}
for key, val in songDict.iteritems():
if key.text() == '':
missing_inputs.append(val)
missing_inp_bool = True
missing_inputs.sort()
# Star rating field blank
if self.starRatingBox.text() == '':
self.starRatingBox.setText('0.00')
# Tag discrepancies
tag_discr_bool = False
# Error windows
if self.free_entry == True and missing_inputs_free != []: # Free entry without editor name and video title
data_mgmt_err_window.DBMgmtErrorWindow('missing input', wid_list=missing_inputs_free)
else:
if self.free_entry == False and missing_inp_bool == True: # GP entry missing input
data_mgmt_err_window.DBMgmtErrorWindow('missing input', wid_list=missing_inputs)
elif self.free_entry == False and tag_discr_bool == True: # GP entry w/tag discrepancies
data_mgmt_err_window.DBMgmtErrorWindow('fx 1')
else: # GP or free entry without any input errors
# Editor
if self.editorBox1.text() == '':
editorFinal = unicode(self.editorBox2.text())
elif self.editorBox2.text() == '':
editorFinal = unicode(self.editorBox1.text())
else:
if self.MEPcheckbox.isChecked():
editorFinal = unicode(self.editorBox1.text()) + ' // Various'
else:
editorFinal = unicode(self.editorBox1.text()) + ' // ' + unicode(self.editorBox2.text())
# Pseudonym(s)
pseudoFinal = unicode(self.pseudoBox.text())
# Video title
videoFinal = unicode(self.videoBox.text())
# My rating
myRatingFinal = float(self.myRatingDrop.currentText())
# Star rating
starRatingFinal = float(self.starRatingBox.text())
# Release date
if self.dateUnk.isChecked() or (
self.dateMonth.currentText() == '' or self.dateYear.currentText() == ''):
dateFinal = '?'
else:
for key, val in self.monthDict.iteritems():
if str(self.dateMonth.currentText()) == key:
month = val
year = int(self.dateYear.currentText())
dateFinal = [month, year]
# Anime
if self.animeVarious.isChecked():
animeFinal = 'Various'
else:
animeList = [unicode(self.animeBox1.text()),
unicode(self.animeBox2.text()),
unicode(self.animeBox3.text()),
unicode(self.animeBox4.text())]
animeList.sort()
animeListFinal = [x for x in animeList if x != ''] # Removes blank entries from list
animeFinal = unicode('')
for i in animeListFinal:
if i == unicode(''):
pass
else:
if i == animeListFinal[-1]:
animeFinal += i
else:
animeFinal += i + ' // '
# Artist
artistFinal = unicode(self.artistBox.text())
# Song
songFinal = unicode(self.songTitleBox.text())
# Song genre
songGenreFinal = str(self.songGenreBox.text())
# Duration
if self.free_entry == True and (self.lengthMinBox.text() == '' and self.lengthSecBox.text() == ''):
durationFinal = 0
elif self.free_entry == True and self.lengthMinBox.text() == '':
durationFinal = int(self.lengthSecBox.text())
elif self.free_entry == True and self.lengthSecBox.text() == '':
durationFinal = int(self.lengthMinBox.text())
else:
durationFinal = (int(self.lengthMinBox.text()) * 60) + int(self.lengthSecBox.text())
# Genre tags
genreTagFinal = str(self.genreTagBox.text())
# General tags
generalTagFinal = str(self.generalTagBox.text())
# FX tags
fxTagFinal = str(self.fxTagBox.text())
# Comments
commentsFinal = unicode(self.commentsBox.toPlainText())
# URL
urlFinal = unicode(self.URLbox.text())
# Local file
localFileFinal = unicode(self.localFileBox.text())
data_output = [editorFinal,
videoFinal,
myRatingFinal,
starRatingFinal,
genreTagFinal,
dateFinal,
animeFinal,
artistFinal,
songFinal,
songGenreFinal,
durationFinal,
generalTagFinal,
fxTagFinal,
commentsFinal,
urlFinal,
pseudoFinal,
localFileFinal]
if copy_btn == True: # If this is to copy a video from CWD to another database...
fName = QtGui.QFileDialog.getOpenFileName(self, 'Select a database', '', 'Spreadsheet file (*.xls)')
if fName:
data_writer_new.data_writer(data_output, file_path=fName)
else:
if self.info_change == False: # If this change window is for a new entry...
data_writer_new.data_writer(data_output)
self.close()
else: # If this change window is to edit an existing entry...
edit_bool = False
for row in xrange(1, self.sheet.nrows):
if row == self.inp_row: # When we get to the video to be edited, overwrite
for col in xrange(self.sheet.ncols):
if delete == True: # If user is deleting a video, write blank data to cells
self.write_sheet.write(row, col, '')
else: # If not deleting, write new data to cells
if col == 5 and data_output[col] != '?':
self.write_sheet.write(row, col,
xlrd.xldate.xldate_from_date_tuple(
(dateFinal[1], dateFinal[0], 1),
0))
else:
self.write_sheet.write(row, col, data_output[col])
# Check to make sure at least one edit checkbox is checked
for key, val in self.editCheckboxAssc.iteritems():
if key.isChecked():
edit_bool = True
if edit_bool == True: # If at least one edit checkbox is checked, overwrite
self.write_book.save(global_vars.global_vars())
if delete == False:
data_mgmt_err_window.DBMgmtErrorWindow('edit complete')
else:
data_mgmt_err_window.DBMgmtErrorWindow('video deleted')
self.close()
else: # If no edit checkboxes checked, raise error
data_mgmt_err_window.DBMgmtErrorWindow('edit check')
self.close()
|
|
# Copyright 2016 Google Inc.
#
# 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.
"""Image represented by either a URI or byte stream."""
from base64 import b64encode
from google.cloud._helpers import _to_bytes
from google.cloud._helpers import _bytes_to_unicode
from google.cloud.vision.annotations import Annotations
from google.cloud.vision.feature import Feature
from google.cloud.vision.feature import FeatureTypes
class Image(object):
"""Image representation containing information to be annotate.
:type content: bytes
:param content: Byte stream of an image.
:type filename: str
:param filename: Filename to image.
:type source_uri: str
:param source_uri: Google Cloud Storage URI of image.
:type client: :class:`~google.cloud.vision.client.Client`
:param client: Instance of Vision client.
"""
def __init__(self, client, content=None, filename=None, source_uri=None):
sources = [source for source in (content, filename, source_uri)
if source is not None]
if len(sources) != 1:
raise ValueError(
'Specify exactly one of "content", "filename", or '
'"source_uri".')
self.client = client
if filename is not None:
with open(filename, 'rb') as file_obj:
content = file_obj.read()
if content is not None:
content = _bytes_to_unicode(b64encode(_to_bytes(content)))
self._content = content
self._source = source_uri
def as_dict(self):
"""Generate dictionary structure for request.
:rtype: dict
:returns: Dictionary with source information for image.
"""
if self.content:
return {
'content': self.content
}
else:
return {
'source': {
'gcs_image_uri': self.source
}
}
@property
def content(self):
"""Base64 encoded image content.
:rtype: str
:returns: Base64 encoded image bytes.
"""
return self._content
@property
def source(self):
"""Google Cloud Storage URI.
:rtype: str
:returns: String of Google Cloud Storage URI.
"""
return self._source
def _detect_annotation(self, features):
"""Generic method for detecting annotations.
:type features: list
:param features: List of :class:`~google.cloud.vision.feature.Feature`
indicating the type of annotations to perform.
:rtype: list
:returns: List of
:class:`~google.cloud.vision.entity.EntityAnnotation`,
:class:`~google.cloud.vision.face.Face`,
:class:`~google.cloud.vision.color.ImagePropertiesAnnotation`,
:class:`~google.cloud.vision.sage.SafeSearchAnnotation`,
"""
results = self.client.annotate(self, features)
return Annotations.from_api_repr(results)
def detect(self, features):
"""Detect multiple feature types.
:type features: list of :class:`~google.cloud.vision.feature.Feature`
:param features: List of the ``Feature`` indication the type of
annotation to perform.
:rtype: list
:returns: List of
:class:`~google.cloud.vision.entity.EntityAnnotation`.
"""
return self._detect_annotation(features)
def detect_faces(self, limit=10):
"""Detect faces in image.
:type limit: int
:param limit: The number of faces to try and detect.
:rtype: list
:returns: List of :class:`~google.cloud.vision.face.Face`.
"""
features = [Feature(FeatureTypes.FACE_DETECTION, limit)]
annotations = self._detect_annotation(features)
return annotations.faces
def detect_labels(self, limit=10):
"""Detect labels that describe objects in an image.
:type limit: int
:param limit: The maximum number of labels to try and detect.
:rtype: list
:returns: List of :class:`~google.cloud.vision.entity.EntityAnnotation`
"""
features = [Feature(FeatureTypes.LABEL_DETECTION, limit)]
annotations = self._detect_annotation(features)
return annotations.labels
def detect_landmarks(self, limit=10):
"""Detect landmarks in an image.
:type limit: int
:param limit: The maximum number of landmarks to find.
:rtype: list
:returns: List of
:class:`~google.cloud.vision.entity.EntityAnnotation`.
"""
features = [Feature(FeatureTypes.LANDMARK_DETECTION, limit)]
annotations = self._detect_annotation(features)
return annotations.landmarks
def detect_logos(self, limit=10):
"""Detect logos in an image.
:type limit: int
:param limit: The maximum number of logos to find.
:rtype: list
:returns: List of
:class:`~google.cloud.vision.entity.EntityAnnotation`.
"""
features = [Feature(FeatureTypes.LOGO_DETECTION, limit)]
annotations = self._detect_annotation(features)
return annotations.logos
def detect_properties(self, limit=10):
"""Detect the color properties of an image.
:type limit: int
:param limit: The maximum number of image properties to find.
:rtype: list
:returns: List of
:class:`~google.cloud.vision.color.ImagePropertiesAnnotation`.
"""
features = [Feature(FeatureTypes.IMAGE_PROPERTIES, limit)]
annotations = self._detect_annotation(features)
return annotations.properties
def detect_safe_search(self, limit=10):
"""Retreive safe search properties from an image.
:type limit: int
:param limit: The number of faces to try and detect.
:rtype: list
:returns: List of
:class:`~google.cloud.vision.sage.SafeSearchAnnotation`.
"""
features = [Feature(FeatureTypes.SAFE_SEARCH_DETECTION, limit)]
annotations = self._detect_annotation(features)
return annotations.safe_searches
def detect_text(self, limit=10):
"""Detect text in an image.
:type limit: int
:param limit: The maximum instances of text to find.
:rtype: list
:returns: List of
:class:`~google.cloud.vision.entity.EntityAnnotation`.
"""
features = [Feature(FeatureTypes.TEXT_DETECTION, limit)]
annotations = self._detect_annotation(features)
return annotations.texts
|
|
import numpy as np
from scipy.signal import find_peaks_cwt
from scipy.optimize import curve_fit, minimize_scalar
# PEAKHUNT RANGE
peakhunt_range = 0.40
# HELPER FUNCTIONS
def default():
return labspec_fit
def methods():
return {'gauss_fit': {'function': gauss_fit,
'name': 'Gauss Fit',
'desc': 'G&G'},
'labspec_fit': {'function': labspec_fit,
'name': 'Labspec Fit',
'desc': 'GL&GL'},
'bactrian_fit': {'function': bactrian_fit,
'name': 'Bactrian Fit',
'desc': 'G+G'},
'camel_fit': {'function': camel_fit,
'name': 'Camel Fit',
'desc': 'G+g+G'},
'dromedaries_fit': {'function': dromedaries_fit,
'name': 'Dromedaries Fit',
'desc': 'Gg+Gg'},
'dromedaries_fit_2': {'function': dromedaries_fit_2,
'name': 'Dromedaries Fit_2',
'desc': 'Gg+Gg'}
}
# DOTS MENAGEMENT FUNCTIONS
def trim_to_range(dots, x_beg, x_end):
indices_to_delete = \
[index for index, x in enumerate(dots[:, 0]) if x < x_beg or x > x_end]
return np.delete(dots, indices_to_delete, axis=0)
# BASIC FUNCTIONS
def linear(x, a, b):
""" Input: x - given point for which background is calculated (floats)
a, b - coeffitients for linear background function a * x + b
Return: value of function with desired parameters in x (float)
Descr.: Calculate linear function for given x and parameters"""
return a * x + b
def linear_fixed(a, b):
""" Input: a, b - coeffitients for linear background function a * x + b
Return: linear function of an 'x' parameter (float)
Descr.: Produce linear function with fixed parameters"""
def linear_baby(x):
return linear(x, a, b)
return linear_baby
def bactrian(x, a1, mu1, si1, a2, mu2, si2):
""" Input: x - given point for which camel is calculated
a2, mu2, si2 - r2 gaussian coeffitients
a1, mu1, si1 - r1 gaussian coeffitients (float)s
Return: value of function with desired parameters in x (float)
Descr.: Calculate G+G-type function for given x and parameters"""
return gauss(x, a2, mu2, si2) + gauss(x, a1, mu1, si1)
def bactrian_fixed(a1, mu1, si1, a2, mu2, si2):
""" Input: a2, mu2, si2 - r2 gaussian coeffitients
a1, mu1, si1 - r1 gaussian coeffitients (float)s
Return: bactrian function of an 'x' parameter (float)
Descr.: Produce G+G(x)-type function with fixed parameters"""
def bactrian_baby(x):
return bactrian(x, a1, mu1, si1, a2, mu2, si2)
return bactrian_baby
def camel(x, a1, mu1, si1, a2, mu2, si2, a12, mu12, si12):
""" Input: x - given point for which camel is calculated
a2, mu2, si2 - r2 gaussian coeffitients
a1, mu1, si1 - r1 gaussian coeffitients
a12, mu12, si12 - background gaussian coeffitients (float)s
Return: value of function with desired parameters in x (float)
Descr.: Calculate G+g+G-type function for given x and parameters"""
return gauss(x, a2, mu2, si2) + gauss(x, a1, mu1, si1)\
+ gauss(x, a12, mu12, si12)
def camel_fixed(a1, mu1, si1, a2, mu2, si2, a12, mu12, si12):
""" Input: a2, mu2, si2 - r2 gaussian coeffitients
a1, mu1, si1 - r1 gaussian coeffitients
a12, mu12, si12 - background gaussian coeffitients (float)s
Return: camel function of an 'x' parameter (float)
Descr.: Produce G+g+G(x)-type function with fixed parameters"""
def camel_baby(x):
return camel(x, a1, mu1, si1, a2, mu2, si2, a12, mu12, si12)
return camel_baby
def dromedaries(x, mu1, a1, si1, b1, ta1, mu2, a2, si2, b2, ta2):
""" Input: x - given point for which dromedaries is calculated
For each of the maxima: suffix 1 for r1, 2 for r2
mu - center of both gaussian functions
a - height of the signal gaussian function
si - standard deviation of the signal gaussian function
b - height of the noise gaussian function
ta - standard deviation of the noise gaussian function
Return: value of function with desired parameters in x (float)
Descr.: Calculate Gg+Gg-type function for given x and parameters"""
# R2 signal gauss + R2 noise gauss +
# R1 signal gauss + R1 noise gauss
return gauss(x, a2, mu2, si2) + gauss(x, b2, mu2, ta2) + \
gauss(x, a1, mu1, si1) + gauss(x, b1, mu1, ta1)
def dromedaries_fixed(mu1, a1, si1, b1, ta1, mu2, a2, si2, b2, ta2):
""" Input: For each of the maxima: suffix 1 for r1, 2 for r2
mu - center of both gaussian functions
a - height of the signal gaussian function
si - standard deviation of the signal gaussian function
b - height of the noise gaussian function
ta - standard deviation of the noise gaussian function (floats)
Return: dromedaries function of an 'x' parameter (float)
Descr.: Produce Gg+Gg(x)-type function with fixed parameters"""
def dromedaries_baby(x):
return dromedaries(x, mu1, a1, si1, b1, ta1, mu2, a2, si2, b2, ta2)
return dromedaries_baby
def dromedaries_2(x, mu1, a1, si1, b1, ga1, mu2, a2, si2, b2, ga2):
""" Input: x - given point for which dromedaries is calculated
For each of the maxima: suffix 1 for r1, 2 for r2
mu - center of lorentz and gaussian functions
a - height of the signal lorentz function
si - standard deviation of the signal gaussian function
b - height of the signal lorentz function
ga - probable error of the signal lorentz function (floats)
Return: value of function with desired parameters in x (float)
Descr.: Calculate Lg+Lg-type function for given x and parameters"""
# R2 signal gauss + R2 noise gauss +
# R1 signal gauss + R1 noise gauss
return gauss(x, a2, mu2, si2) + lorentz(x, b2, mu2, ga2) + \
gauss(x, a1, mu1, si1) + lorentz(x, b1, mu1, ga1)
def dromedaries_fixed_2(mu1, a1, si1, b1, ga1, mu2, a2, si2, b2, ga2):
""" Input: For each of the maxima: suffix 1 for r1, 2 for r2
mu - center of lorentz and gaussian functions
a - height of the signal lorentz function
si - standard deviation of the signal gaussian function
b - height of the signal lorentz function
ga - probable error of the signal lorentz function (floats)
Return: dromedaries function of an 'x' parameter (float)
Descr.: Produce Gg+Gg(x)-type function with fixed parameters"""
def dromedaries_baby(x):
return dromedaries_2(x, mu1, a1, si1, b1, ga1, mu2, a2, si2, b2, ga2)
return dromedaries_baby
def gauss(x, a, mu, si):
""" Input: x - value and a, mu, si - gaussian coeffitients (float)
Return: value of function with desired parameters in x (float)
Descr.: Calculate G-type function for given x and parameters"""
return a * np.exp(-(x - mu) ** 2 / (2. * si ** 2))
def gauss_fixed(a, mu, si):
""" Input: a, mu, si - gaussian coeffitients (float)
Return: gauss function of an 'x' parameter (float)
Descr.: Produce G(x)-type function with fixed parameters"""
def gauss_baby(x):
return gauss(x, a, mu, si)
return gauss_baby
def labspec(x, mu, a, si, b, ga):
""" Input: x - value
mu - center of lorentz and gaussian functions
a - height of gaussian function
si - standard deviation of the gaussian function
b - height of lorentz function
ga - probable error of the lorentz function (floats)
Return: value of function with desired parameters in x (float)
Descr.: Calculate GL-type function for given x and parameters"""
return gauss(x, a, mu, si) + lorentz(x, b, mu, ga)
def labspec_fixed(mu, a, si, b, ga):
""" Input: mu - center of lorentz and gaussian functions
a - height of gaussian function
si - standard deviation of the gaussian function
b - height of lorentz function
ga - probable error of the lorentz function (floats)
Return: labspec function of an 'x' parameter (float)
Descr.: Produce GL(x)-type function with fixed parameters"""
def labspec_baby(x):
return labspec(x, mu, a, si, b, ga)
return labspec_baby
def lorentz(x, a, mu, ga):
""" Input: x - value and a=I, mu=x_0, ga - lorentz f. coeffitients (float)
Return: value of function with desired parameters in x (float)
Descr.: Calculate L-type function for given x and parameters"""
return (a * ga ** 2) / ((x - mu) ** 2 + ga ** 2)
def peak_search(dots):
""" Input: dots - ruby spectrum data (n x 2 ndarray)
Return: list of data biggest peaks (n x 2 ndarray)
Descr.: Find and sort biggest peaks in dots data"""
peak_indexes = find_peaks_cwt(vector=dots[:, 1], widths=[10])
peaks = np.array([dots[index, :] for index in peak_indexes])
peaks = peaks[peaks[:, 1].argsort()[::-1]]
return peaks
# BACKGROUND ESTIMATION
def estimate_background(dots):
# PREPARE 20 EDGE DOTS TO ESTIMATE BACKGROUND
left_edge_dots = np.array(dots[:10, :], dtype=(float, float))
right_edge_dots = np.array(dots[-10:, :], dtype=(float, float))
edge_dots = np.concatenate((left_edge_dots, right_edge_dots))
# ESTIMATE INITIAL BACKGROUND PARAMETERS
a = (dots[-1, 1] - dots[0, 1]) / (dots[-1, 0] - dots[0, 0])
b = dots[0, 1] - a * dots[0, 0]
guess = (a, b)
# FIT LINEAR BACKGROUND TO THE EDGE DOTS
popt, pcov = curve_fit(linear, xdata=edge_dots[:, 0], ydata=edge_dots[:, 1],
p0=guess)
sigma = np.sqrt(np.diag(pcov))
# PREPARE DOTS CORRECTED FOR BACKGROUND
background = linear_fixed(popt[0], popt[1])
corrected_dots = []
for x, y in zip(dots[:, 0], dots[:, 1]):
corrected_dots.append([x, y - background(x)])
corrected_dots = np.array(corrected_dots, dtype=(float, float))
# RETURN DATA
return {'corrected_dots': corrected_dots,
'background': background}
# FIT FUNCTIONS
def camel_fit(dots):
""" Input: dots - ruby spectrum data (n x 2 ndarray)
Return: dict with r1, r2 and fit description
Descr.: Fit G+g+G-type "camel" function to dots"""
# LOAD PEAKS AND ESTIMATE BACKGROUND
estimated_background = estimate_background(dots)
background = estimated_background['background']
dots = estimated_background['corrected_dots']
peaks = peak_search(dots)[:2, :]
# ESTIMATE INITIAL GAUSSIAN PARAMETERS
si1, si2, si12 = 0.35, 0.35, 1.0
mu1 = peaks[0, 0]
a1 = peaks[0, 1]
mu2 = peaks[1, 0]
a2 = peaks[1, 1]
a12 = 0.1 * (a1 + a2)
mu12 = 0.5 * (mu1 + mu2)
guess = (a1, mu1, si1, a2, mu2, si2, a12, mu12, si12)
# TRIM DATA AND FIT CAMEL CURVE
x_beg = peaks[1, 0] - 2 * peakhunt_range
x_end = peaks[0, 0] + 2 * peakhunt_range
dots = trim_to_range(dots, x_beg, x_end)
dots_sigma = peaks[0, 1] * np.power(dots[:, 1], -1)
popt, pcov = curve_fit(camel, xdata=dots[:, 0], ydata=dots[:, 1], p0=guess,
sigma=dots_sigma)
sigma = np.sqrt(np.diag(pcov))
# FIND ACTUAL MAXIMA AND RETURN DATA
dx = peakhunt_range
r1_val = minimize_scalar(lambda x: -camel_fixed(*popt)(x), method='Bounded',
bounds=(popt[1]-dx, popt[1]+dx)).x
r2_val = minimize_scalar(lambda x: -camel_fixed(*popt)(x), method='Bounded',
bounds=(popt[4]-dx, popt[4]+dx)).x
return {'r1_val': r1_val,
'r1_unc': sigma[1],
'r1_int': camel(r1_val, *popt) + background(r1_val),
'r2_val': r2_val,
'r2_unc': sigma[4],
'r2_int': camel(r2_val, *popt) + background(r2_val),
'fit_function': [lambda x: camel_fixed(*popt)(x) + background(x)],
'fit_range': [(x_beg, x_end), (x_beg, x_end)]}
def bactrian_fit(dots):
""" Input: dots - ruby spectrum data (n x 2 ndarray)
Return: dict with r1, r2 and fit description
Descr.: Fit G+G-type "bactrian" function to dots"""
# LOAD PEAKS AND ESTIMATE BACKGROUND
estimated_background = estimate_background(dots)
background = estimated_background['background']
dots = estimated_background['corrected_dots']
peaks = peak_search(dots)[:2, :]
# ESTIMATE INITIAL GAUSSIAN PARAMETERS
si1, si2 = 0.35, 0.35
mu1 = peaks[0, 0]
a1 = peaks[0, 1]
mu2 = peaks[1, 0]
a2 = peaks[1, 1]
guess = (a1, mu1, si1, a2, mu2, si2)
# TRIM DATA AND FIT THE BACTRIAN CURVE
x_beg = peaks[1, 0] - 2 * peakhunt_range
x_end = peaks[0, 0] + 2 * peakhunt_range
dots = trim_to_range(dots, x_beg, x_end)
dots_sigma = peaks[0, 1] * np.power(dots[:, 1], -1)
popt, pcov = curve_fit(bactrian, xdata=dots[:, 0], ydata=dots[:, 1],
p0=guess, sigma=dots_sigma)
sigma = np.sqrt(np.diag(pcov))
# FIND ACTUAL MAXIMA AND RETURN DATA
return {'r1_val': popt[1],
'r1_unc': sigma[1],
'r1_int': bactrian(popt[1], *popt) + background(popt[1]),
'r2_val': popt[4],
'r2_unc': sigma[4],
'r2_int': bactrian(popt[4], *popt) + background(popt[4]),
'fit_function': [lambda x: bactrian_fixed(*popt)(x) + background(x)],
'fit_range': [(x_beg, x_end)]}
def dromedaries_fit(dots):
""" Input: dots - ruby spectrum data (n x 2 ndarray)
Return: dict with r1, r2 and fit description
Descr.: Fit GLg+GLg-type "dromedaries" function to dots"""
# LOAD PEAKS AND ESTIMATE BACKGROUND
estimated_background = estimate_background(dots)
background = estimated_background['background']
dots = estimated_background['corrected_dots']
peaks = peak_search(dots)[:2, :]
# ESTIMATE INITIAL GAUSSIAN & LORENTZIAN PARAMETERS
mu1, mu2 = peaks[0, 0], peaks[1, 0]
a1, a2 = 0.75 * peaks[0, 1], 0.75 * peaks[1, 1]
si1, si2 = 0.35, 0.35
b1, b2 = 0.20 * peaks[0, 1], 0.20 * peaks[1, 1]
ta1, ta2 = 0.7, 0.7
guess = (mu1, a1, si1, b1, ta1, mu2, a2, si2, b2, ta2)
# TRIM DATA AND FIT THE DROMEDARIES CURVE
x_beg = peaks[1, 0] - 3 * peakhunt_range
x_end = peaks[0, 0] + 3 * peakhunt_range
dots = trim_to_range(dots, x_beg, x_end)
dots_sigma = peaks[0, 1] * np.power(dots[:, 1], -1)
popt, pcov = curve_fit(dromedaries, xdata=dots[:, 0], ydata=dots[:, 1],
p0=guess) # sigma=dots_sigma
# popt, pcov = guess, guess
sigma = np.sqrt(np.diag(pcov))
# RETURN DATA
return {'r1_val': popt[0],
'r1_unc': sigma[0],
'r1_int': dromedaries(popt[0], *popt) + background(popt[0]),
'r2_val': popt[5],
'r2_unc': sigma[5],
'r2_int': dromedaries(popt[5], *popt) + background(popt[5]),
'fit_function':
[lambda x: dromedaries_fixed(*popt)(x) + background(x)],
'fit_range': [(x_beg, x_end)]}
def dromedaries_fit_2(dots):
""" Input: dots - ruby spectrum data (n x 2 ndarray)
Return: dict with r1, r2 and fit description
Descr.: Fit Lg+Lg-type "dromedaries" function to dots"""
# LOAD PEAKS AND ESTIMATE BACKGROUND
estimated_background = estimate_background(dots)
background = estimated_background['background']
dots = estimated_background['corrected_dots']
peaks = peak_search(dots)[:2, :]
# ESTIMATE INITIAL GAUSSIAN & LORENTZIAN PARAMETERS
mu1, mu2 = peaks[0, 0], peaks[1, 0]
a1, a2 = 0.75 * peaks[0, 1], 0.75 * peaks[1, 1]
si1, si2 = 0.35, 0.35
b1, b2 = 0.20 * peaks[0, 1], 0.20 * peaks[1, 1]
ga1, ga2 = 0.7, 0.7
guess = (mu1, a1, si1, b1, ga1, mu2, a2, si2, b2, ga2)
# TRIM DATA AND FIT THE DROMEDARIES CURVE
x_beg = peaks[1, 0] - 3 * peakhunt_range
x_end = peaks[0, 0] + 3 * peakhunt_range
dots = trim_to_range(dots, x_beg, x_end)
dots_sigma = peaks[0, 1] * np.power(dots[:, 1], -1)
popt, pcov = curve_fit(dromedaries_2, xdata=dots[:, 0], ydata=dots[:, 1],
p0=guess)
# popt, pcov = guess, guess
sigma = np.sqrt(np.diag(pcov))
# RETURN DATA
return {'r1_val': popt[0],
'r1_unc': sigma[0],
'r1_int': dromedaries_2(popt[0], *popt) + background(popt[0]),
'r2_val': popt[5],
'r2_unc': sigma[5],
'r2_int': dromedaries_2(popt[5], *popt) + background(popt[5]),
'fit_function':
[lambda x: dromedaries_fixed_2(*popt)(x) + background(x)],
'fit_range': [(x_beg, x_end)]}
def gauss_fit(dots):
""" Input: dots - ruby spectrum data (n x 2 ndarray)
Return: dict with r1, r2 and fit description
Descr.: Fit G&G-type "two gauss" function to dots"""
# LOAD PEAKS AND ESTIMATE BACKGROUND
estimated_background = estimate_background(dots)
background = estimated_background['background']
dots = estimated_background['corrected_dots']
peaks = peak_search(dots)[:2, :]
# ESTIMATE INITIAL GAUSSIAN PARAMETERS
si1, si2 = 0.35, 0.35
mu1, mu2 = peaks[0, 0], peaks[1, 0]
a1, a2 = peaks[0, 1], peaks[1, 1]
guess1, guess2 = (a1, mu1, si1), (a2, mu2, si2)
# CUT DATA TO FITTED SURROUNDING
x_beg1 = peaks[0, 0] - peakhunt_range
x_end1 = peaks[0, 0] + peakhunt_range
x_beg2 = peaks[1, 0] - peakhunt_range
x_end2 = peaks[1, 0] + peakhunt_range
dots1 = trim_to_range(dots, x_beg1, x_end1)
dots2 = trim_to_range(dots, x_beg2, x_end2)
# FIT THE GAUSS CURVES AND RETURN DATA
dots1_sigma = peaks[0, 1] * np.power(dots1[:, 1], -1)
popt1, pcov1 = curve_fit(gauss, xdata=dots1[:, 0], ydata=dots1[:, 1],
p0=guess1, sigma=dots1_sigma)
sigma1 = np.sqrt(np.diag(pcov1))
dots2_sigma = peaks[1, 1] * np.power(dots2[:, 1], -1)
popt2, pcov2 = curve_fit(gauss, xdata=dots2[:, 0], ydata=dots2[:, 1],
p0=guess2, sigma=dots2_sigma)
sigma2 = np.sqrt(np.diag(pcov2))
return {'r1_val': popt1[1],
'r1_unc': sigma1[1],
'r1_int': popt1[0] + background(popt1[1]),
'r2_val': popt2[1],
'r2_unc': sigma2[1],
'r2_int': popt2[0] + background(popt2[1]),
'fit_function':
[lambda x: gauss_fixed(*popt1)(x) + background(x),
lambda x: gauss_fixed(*popt2)(x) + background(x)],
'fit_range': [(x_beg1, x_end1), (x_beg2, x_end2)]}
def labspec_fit(dots):
""" Input: dots - ruby spectrum data (n x 2 ndarray)
Return: dict with r1, r2 and fit description
Descr.: Fit GL-type "two labspec" function to dots"""
# LOAD PEAKS AND ESTIMATE BACKGROUND
estimated_background = estimate_background(dots)
background = estimated_background['background']
dots = estimated_background['corrected_dots']
peaks = peak_search(dots)[:2, :]
# ESTIMATE INITIAL LABSPEC PARAMETERS
mu1, mu2 = peaks[0, 0], peaks[1, 0]
a1, a2 = 0.5*peaks[0, 1], 0.5*peaks[1, 1]
si1, si2 = 0.35, 0.35
b1, b2 = 0.5*peaks[0, 1], 0.5*peaks[1, 1]
ga1, ga2 = 0.20, 0.20
guess1, guess2 = (mu1, a1, si1, b1, ga1), (mu2, a2, si2, b2, ga2)
# CUT DATA TO FITTED SURROUNDING
x_beg1 = peaks[0, 0] - 2 * peakhunt_range
x_end1 = peaks[0, 0] + 2 * peakhunt_range
x_beg2 = peaks[1, 0] - 2 * peakhunt_range
x_end2 = peaks[1, 0] + 2 * peakhunt_range
dots1 = trim_to_range(dots, x_beg1, x_end1)
dots2 = trim_to_range(dots, x_beg2, x_end2)
# FIT THE LABSPEC CURVES AND RETURN DATA
dots1_sigma = peaks[0, 1] * np.power(dots1[:, 1], -1)
popt1, pcov1 = curve_fit(labspec, xdata=dots1[:, 0], ydata=dots1[:, 1],
p0=guess1, sigma=dots1_sigma)
sigma1 = np.sqrt(np.diag(pcov1))
dots2_sigma = peaks[1, 1] * np.power(dots2[:, 1], -1)
popt2, pcov2 = curve_fit(labspec, xdata=dots2[:, 0], ydata=dots2[:, 1],
p0=guess2, sigma=dots2_sigma)
sigma2 = np.sqrt(np.diag(pcov2))
return {'r1_val': popt1[0],
'r1_unc': sigma1[0],
'r1_int': popt1[1] + popt1[3] + background(popt1[0]),
'r2_val': popt2[0],
'r2_unc': sigma2[0],
'r2_int': popt2[1] + popt2[3] + background(popt2[0]),
'fit_function':
[lambda x: labspec_fixed(*popt1)(x) + background(x),
lambda x: labspec_fixed(*popt2)(x) + background(x)],
'fit_range': [(x_beg1, x_end1), (x_beg2, x_end2)]}
if __name__ == '__main__':
pass
|
|
import copy
import itertools
import operator
import string
import warnings
import cupy
from cupy._core import _accelerator
from cupy import _util
from cupy.linalg._einsum_opt import _greedy_path
from cupy.linalg._einsum_opt import _optimal_path
try:
import cupy_backends.cuda.libs.cutensor # NOQA
from cupy import cutensor
except ImportError:
cutensor = None
options = {
'sum_ellipsis': False,
'broadcast_diagonal': False,
}
einsum_symbols = string.ascii_uppercase + string.ascii_lowercase
def _transpose_ex(a, axeses):
"""Transpose and diagonal
Args:
a
axeses (sequence of sequences of ints)
Returns:
ndarray: a with its axes permutated. A writeable view is returned
whenever possible.
"""
shape = []
strides = []
for axes in axeses:
shape.append(a.shape[axes[0]] if axes else 1)
stride = sum(a.strides[axis] for axis in axes)
strides.append(stride)
a = a.view()
# TODO(niboshi): Confirm update_x_contiguity flags
a._set_shape_and_strides(shape, strides, True, True)
return a
def _parse_int_subscript(list_subscript):
str_subscript = ''
for s in list_subscript:
if s is Ellipsis:
str_subscript += '@'
else:
try:
s = operator.index(s)
except TypeError as e:
raise TypeError(
'For this input type lists must contain '
'either int or Ellipsis') from e
str_subscript += einsum_symbols[s]
return str_subscript
def _parse_einsum_input(args):
"""Parse einsum operands.
This function is based on `numpy.core.einsumfunc._parse_einsum_input`
function in NumPy 1.14.
Parameters
----------
args : tuple
The non-keyword arguments to einsum
Returns
-------
input_strings : str
Parsed input strings
output_string : str
Parsed output string
operands : list of array_like
The operands to use in the contraction
Examples
--------
The operand list is simplified to reduce printing:
>>> a = np.random.rand(4, 4)
>>> b = np.random.rand(4, 4, 4)
>>> _parse_einsum_input(('...a,...a->...', a, b))
(['@a, @a'], 'xz', [a, b])
>>> _parse_einsum_input((a, [Ellipsis, 0], b, [Ellipsis, 0]))
(['@a, @a'], 'xz', [a, b])
"""
if len(args) == 0:
raise ValueError(
'must specify the einstein sum subscripts string and at least one '
'operand, or at least one operand and its corresponding '
'subscripts list')
if isinstance(args[0], str):
subscripts = args[0]
operands = list(args[1:])
# Ensure all characters are valid
for s in subscripts:
if s in '.,-> ':
continue
if s not in einsum_symbols:
raise ValueError(
'invalid subscript \'%s\' in einstein sum subscripts '
'string, subscripts must be letters' % s)
# Parse '...'
subscripts = subscripts.replace('...', '@')
if '.' in subscripts:
raise ValueError(
'einstein sum subscripts string contains a \'.\' that is not '
'part of an ellipsis (\'...\')')
# Parse '->'
if ('-' in subscripts) or ('>' in subscripts):
# Check for proper '->'
invalid = subscripts.count('-') > 1 or subscripts.count('>') > 1
subscripts = subscripts.split('->')
if invalid or len(subscripts) != 2:
raise ValueError(
'einstein sum subscript string does not contain proper '
'\'->\' output specified')
input_subscripts, output_subscript = subscripts
output_subscript = output_subscript.replace(' ', '')
else:
input_subscripts = subscripts
output_subscript = None
input_subscripts = input_subscripts.replace(' ', '').split(',')
if len(input_subscripts) != len(operands):
msg = 'more' if len(operands) > len(input_subscripts) else 'fewer'
raise ValueError(
msg + ' operands provided to einstein sum function than '
'specified in the subscripts string')
else:
args = list(args)
operands = []
input_subscripts = []
while len(args) >= 2:
operands.append(args.pop(0))
input_subscripts.append(_parse_int_subscript(args.pop(0)))
if args:
output_subscript = _parse_int_subscript(args[0])
else:
output_subscript = None
return input_subscripts, output_subscript, operands
def _chr(label):
if label < 0:
return '...[%d]' % label
else:
return chr(label)
def _parse_ellipsis_subscript(subscript, idx, ndim=None, ellipsis_len=None):
"""Parse a subscript that may contain ellipsis
Args:
subscript (str): An einsum subscript of an operand or an output. '...'
should be replaced by '@'.
idx (int or None): For error messages, give int idx for the idx-th
operand or None for the output.
ndim (int, optional): ndim of the operand
ellipsis_len (int, optional): number of broadcast dimensions of the
output.
Returns:
list of ints: The parsed subscript
"""
subs = subscript.split('@')
if len(subs) == 1:
sub, = subs
if ndim is not None and len(sub) != ndim:
if len(sub) > ndim:
raise ValueError(
'einstein sum subscripts string %s contains too many '
'subscripts for operand %d' % (sub, idx))
raise ValueError(
'operand %d has more dimensions than subscripts string %s '
'given in einstein sum, but no \'...\' ellipsis provided to '
'broadcast the extra dimensions.' % (idx, sub))
return [ord(label) for label in sub]
elif len(subs) == 2:
left_sub, right_sub = subs
if ndim is not None:
ellipsis_len = ndim - (len(left_sub) + len(right_sub))
if ellipsis_len < 0:
raise ValueError(
'einstein sum subscripts string %s...%s contains too many '
'subscripts for operand %d' % (left_sub, right_sub, idx))
ret = []
ret.extend(ord(label) for label in left_sub)
ret.extend(range(-ellipsis_len, 0))
ret.extend(ord(label) for label in right_sub)
return ret
else:
# >= 2 ellipses for an operand
raise ValueError(
'einstein sum subscripts string contains a \'.\' that is not '
'part of an ellipsis (\'...\') ' +
('in the output' if idx is None else 'for operand %d' % idx))
def _einsum_diagonals(input_subscripts, operands):
"""Compute diagonal for each operand
This function mutates args.
"""
for idx in range(len(input_subscripts)):
sub = input_subscripts[idx]
arr = operands[idx]
if len(set(sub)) < len(sub):
axeses = {}
for axis, label in enumerate(sub):
axeses.setdefault(label, []).append(axis)
axeses = list(axeses.items())
for label, axes in axeses:
if options['broadcast_diagonal']:
axes = [axis for axis in axes if arr.shape[axis] != 1]
dims = {arr.shape[axis] for axis in axes}
if len(dims) >= 2:
dim0 = dims.pop()
dim1 = dims.pop()
raise ValueError(
'dimensions in operand %d'
' for collapsing index \'%s\' don\'t match (%d != %d)'
% (idx, _chr(label), dim0, dim1)
)
sub, axeses = zip(*axeses) # axeses is not empty
input_subscripts[idx] = list(sub)
operands[idx] = _transpose_ex(arr, axeses)
def _iter_path_pairs(path):
"""Decompose path into binary path
Args:
path (sequence of tuples of ints)
Yields:
tuple of ints: pair (idx0, idx1) that represents the operation
{pop(idx0); pop(idx1); append();}
"""
for indices in path:
assert all(idx >= 0 for idx in indices)
# [3, 1, 4, 9] -> [(9, 4), (-1, 3), (-1, 1)]
if len(indices) >= 2:
indices = sorted(indices, reverse=True)
yield indices[0], indices[1]
for idx in indices[2:]:
yield -1, idx
def _flatten_transpose(a, axeses):
"""Transpose and flatten each
Args:
a
axeses (sequence of sequences of ints)
Returns:
aT: a with its axes permutated and flatten
shapes: flattened shapes
"""
transpose_axes = []
shapes = []
for axes in axeses:
transpose_axes.extend(axes)
shapes.append([a.shape[axis] for axis in axes])
return (
a.transpose(transpose_axes).reshape(
tuple([cupy._core.internal.prod(shape) for shape in shapes])),
shapes
)
def _use_cutensor(dtype0, sub0, dtype1, sub1, batch_dims, contract_dims):
if not cutensor.check_availability('contraction'):
return False
if dtype0 != dtype1:
return False
if dtype0 not in (cupy.float32, cupy.float64,
cupy.complex64, cupy.complex128):
return False
return True
def _get_out_shape(shape0, sub0, shape1, sub1, sub_out):
extent = {}
for size, i in zip(shape0 + shape1, sub0 + sub1):
extent[i] = size
out_shape = [extent[i] for i in sub_out]
return out_shape
def _expand_dims_transpose(arr, mode, mode_out):
"""Return a reshaped and transposed array.
The input array ``arr`` having ``mode`` as its modes is reshaped and
transposed so that modes of the output becomes ``mode_out``.
Example
>>> import cupy
>>> a = cupy.zeros((10, 20))
>>> mode_a = ('A', 'B')
>>> mode_out = ('B', 'C', 'A')
>>> out = cupy.linalg.einsum._expand_dims_transpose(a, mode_a,
... mode_out)
>>> out.shape
(20, 1, 10)
Args:
arr (cupy.ndarray):
mode (tuple or list): The modes of input array.
mode_out (tuple or list): The modes of output array.
Returns:
cupy.ndarray: The reshaped and transposed array.
"""
mode = list(mode)
shape = list(arr.shape)
axes = []
for i in mode_out:
if i not in mode:
mode.append(i)
shape.append(1)
axes.append(mode.index(i))
return cupy.transpose(arr.reshape(shape), axes)
def reduced_binary_einsum(arr0, sub0, arr1, sub1, sub_others):
set0 = set(sub0)
set1 = set(sub1)
assert len(set0) == len(sub0), 'operand 0 should be reduced: diagonal'
assert len(set1) == len(sub1), 'operand 1 should be reduced: diagonal'
if len(sub0) == 0 or len(sub1) == 0:
return arr0 * arr1, sub0 + sub1
set_others = set(sub_others)
shared = set0 & set1
batch_dims = shared & set_others
contract_dims = shared - batch_dims
bs0, cs0, ts0 = _make_transpose_axes(sub0, batch_dims, contract_dims)
bs1, cs1, ts1 = _make_transpose_axes(sub1, batch_dims, contract_dims)
sub_b = [sub0[axis] for axis in bs0]
assert sub_b == [sub1[axis] for axis in bs1]
sub_l = [sub0[axis] for axis in ts0]
sub_r = [sub1[axis] for axis in ts1]
sub_out = sub_b + sub_l + sub_r
assert set(sub_out) <= set_others, 'operands should be reduced: unary sum'
if len(contract_dims) == 0:
# Use element-wise multiply when no contraction is needed
if len(sub_out) == len(sub_others):
# to assure final output of einsum is C-contiguous
sub_out = sub_others
arr0 = _expand_dims_transpose(arr0, sub0, sub_out)
arr1 = _expand_dims_transpose(arr1, sub1, sub_out)
return arr0 * arr1, sub_out
for accelerator in _accelerator.get_routine_accelerators():
if (accelerator == _accelerator.ACCELERATOR_CUTENSOR and
cutensor is not None):
if _use_cutensor(arr0.dtype, sub0, arr1.dtype, sub1,
batch_dims, contract_dims):
if len(sub_out) == len(sub_others):
# to assure final output of einsum is C-contiguous
sub_out = sub_others
out_shape = _get_out_shape(
arr0.shape, sub0, arr1.shape, sub1, sub_out)
arr_out = cupy.empty(out_shape, arr0.dtype)
arr0 = cupy.ascontiguousarray(arr0)
arr1 = cupy.ascontiguousarray(arr1)
desc_0 = cutensor.create_tensor_descriptor(arr0)
desc_1 = cutensor.create_tensor_descriptor(arr1)
desc_out = cutensor.create_tensor_descriptor(arr_out)
arr_out = cutensor.contraction(
1.0,
arr0, desc_0, sub0,
arr1, desc_1, sub1,
0.0,
arr_out, desc_out, sub_out)
return arr_out, sub_out
tmp0, shapes0 = _flatten_transpose(arr0, [bs0, ts0, cs0])
tmp1, shapes1 = _flatten_transpose(arr1, [bs1, cs1, ts1])
shapes_out = shapes0[0] + shapes0[1] + shapes1[2]
assert shapes0[0] == shapes1[0]
arr_out = cupy.matmul(tmp0, tmp1).reshape(shapes_out)
return arr_out, sub_out
def _make_transpose_axes(sub, b_dims, c_dims):
bs = []
cs = []
ts = []
for axis, label in enumerate(sub):
if label in b_dims:
bs.append((label, axis))
elif label in c_dims:
cs.append((label, axis))
else:
ts.append((label, axis))
return (
_tuple_sorted_by_0(bs),
_tuple_sorted_by_0(cs),
_tuple_sorted_by_0(ts),
)
def _tuple_sorted_by_0(zs):
return tuple(i for _, i in sorted(zs))
def einsum(*operands, **kwargs):
"""einsum(subscripts, *operands, dtype=False)
Evaluates the Einstein summation convention on the operands.
Using the Einstein summation convention, many common multi-dimensional
array operations can be represented in a simple fashion. This function
provides a way to compute such summations.
.. note::
Memory contiguity of calculation result is not always compatible with
`numpy.einsum`.
``out``, ``order``, and ``casting`` options are not supported.
Args:
subscripts (str): Specifies the subscripts for summation.
operands (sequence of arrays): These are the arrays for the operation.
Returns:
cupy.ndarray:
The calculation based on the Einstein summation convention.
.. seealso:: :func:`numpy.einsum`
"""
input_subscripts, output_subscript, operands = \
_parse_einsum_input(operands)
assert isinstance(input_subscripts, list)
assert isinstance(operands, list)
dtype = kwargs.pop('dtype', None)
# casting = kwargs.pop('casting', 'safe')
casting_kwargs = {} # casting is not supported yet in astype
optimize = kwargs.pop('optimize', False)
if optimize is True:
optimize = 'greedy'
if kwargs:
raise TypeError('Did not understand the following kwargs: %s'
% list(kwargs.keys))
result_dtype = cupy.result_type(*operands) if dtype is None else dtype
operands = [
cupy.asanyarray(arr)
for arr in operands
]
input_subscripts = [
_parse_ellipsis_subscript(sub, idx, ndim=arr.ndim)
for idx, (sub, arr) in enumerate(zip(input_subscripts, operands))
]
# Get length of each unique dimension and ensure all dimensions are correct
dimension_dict = {}
for idx, sub in enumerate(input_subscripts):
sh = operands[idx].shape
for axis, label in enumerate(sub):
dim = sh[axis]
if label in dimension_dict.keys():
# For broadcasting cases we always want the largest dim size
if dimension_dict[label] == 1:
dimension_dict[label] = dim
elif dim not in (1, dimension_dict[label]):
dim_old = dimension_dict[label]
raise ValueError(
'Size of label \'%s\' for operand %d (%d) '
'does not match previous terms (%d).'
% (_chr(label), idx, dim, dim_old))
else:
dimension_dict[label] = dim
if output_subscript is None:
# Build output subscripts
tmp_subscripts = list(itertools.chain.from_iterable(input_subscripts))
output_subscript = [
label
for label in sorted(set(tmp_subscripts))
if label < 0 or tmp_subscripts.count(label) == 1
]
else:
if not options['sum_ellipsis']:
if '@' not in output_subscript and -1 in dimension_dict:
raise ValueError(
'output has more dimensions than subscripts '
'given in einstein sum, but no \'...\' ellipsis '
'provided to broadcast the extra dimensions.')
output_subscript = _parse_ellipsis_subscript(
output_subscript, None,
ellipsis_len=sum(label < 0 for label in dimension_dict.keys())
)
# Make sure output subscripts are in the input
tmp_subscripts = set(itertools.chain.from_iterable(input_subscripts))
for label in output_subscript:
if label not in tmp_subscripts:
raise ValueError(
'einstein sum subscripts string included output subscript '
'\'%s\' which never appeared in an input' % _chr(label))
if len(output_subscript) != len(set(output_subscript)):
for label in output_subscript:
if output_subscript.count(label) >= 2:
raise ValueError(
'einstein sum subscripts string includes output '
'subscript \'%s\' multiple times' % _chr(label))
_einsum_diagonals(input_subscripts, operands)
# no more raises
if len(operands) >= 2:
if any(arr.size == 0 for arr in operands):
return cupy.zeros(
tuple(dimension_dict[label] for label in output_subscript),
dtype=result_dtype
)
# Don't squeeze if unary, because this affects later (in trivial sum)
# whether the return is a writeable view.
for idx in range(len(operands)):
arr = operands[idx]
if 1 in arr.shape:
squeeze_indices = []
sub = []
for axis, label in enumerate(input_subscripts[idx]):
if arr.shape[axis] == 1:
squeeze_indices.append(axis)
else:
sub.append(label)
input_subscripts[idx] = sub
operands[idx] = cupy.squeeze(arr, axis=tuple(squeeze_indices))
assert operands[idx].ndim == len(input_subscripts[idx])
del arr
# unary einsum without summation should return a (writeable) view
returns_view = len(operands) == 1
# unary sum
for idx, sub in enumerate(input_subscripts):
other_subscripts = copy.copy(input_subscripts)
other_subscripts[idx] = output_subscript
other_subscripts = set(itertools.chain.from_iterable(other_subscripts))
sum_axes = tuple(
axis
for axis, label in enumerate(sub)
if label not in other_subscripts
)
if sum_axes:
returns_view = False
input_subscripts[idx] = [
label
for axis, label in enumerate(sub)
if axis not in sum_axes
]
operands[idx] = operands[idx].sum(
axis=sum_axes, dtype=result_dtype)
if returns_view:
operands = [a.view() for a in operands]
else:
operands = [
a.astype(result_dtype, copy=False, **casting_kwargs)
for a in operands
]
# no more casts
optimize_algorithms = {
'greedy': _greedy_path,
'optimal': _optimal_path,
}
if optimize is False:
path = [tuple(range(len(operands)))]
elif len(optimize) and (optimize[0] == 'einsum_path'):
path = optimize[1:]
else:
try:
if len(optimize) == 2 and isinstance(optimize[1], (int, float)):
algo = optimize_algorithms[optimize[0]]
memory_limit = int(optimize[1])
else:
algo = optimize_algorithms[optimize]
memory_limit = 2 ** 31 # TODO(kataoka): fix?
except (TypeError, KeyError): # unhashable type or not found
raise TypeError('Did not understand the path (optimize): %s'
% str(optimize))
input_sets = [set(sub) for sub in input_subscripts]
output_set = set(output_subscript)
path = algo(input_sets, output_set, dimension_dict, memory_limit)
if any(len(indices) > 2 for indices in path):
warnings.warn(
'memory efficient einsum is not supported yet',
_util.PerformanceWarning)
for idx0, idx1 in _iter_path_pairs(path):
# "reduced" binary einsum
arr0 = operands.pop(idx0)
sub0 = input_subscripts.pop(idx0)
arr1 = operands.pop(idx1)
sub1 = input_subscripts.pop(idx1)
sub_others = list(itertools.chain(
output_subscript,
itertools.chain.from_iterable(input_subscripts)))
arr_out, sub_out = reduced_binary_einsum(
arr0, sub0, arr1, sub1, sub_others)
operands.append(arr_out)
input_subscripts.append(sub_out)
del arr0, arr1
# unary einsum at last
arr0, = operands
sub0, = input_subscripts
transpose_axes = []
for label in output_subscript:
if label in sub0:
transpose_axes.append(sub0.index(label))
arr_out = arr0.transpose(transpose_axes).reshape([
dimension_dict[label]
for label in output_subscript
])
assert returns_view or arr_out.dtype == result_dtype
return arr_out
|
|
"""
Numba-specific errors and warnings.
"""
import abc
import contextlib
import os
import sys
import warnings
import numba.core.config
import numpy as np
from collections import defaultdict
from numba.core.utils import chain_exception
from functools import wraps
from abc import abstractmethod
# Filled at the end
__all__ = []
class NumbaWarning(Warning):
"""
Base category for all Numba compiler warnings.
"""
def __init__(self, msg, loc=None, highlighting=True, ):
self.msg = msg
self.loc = loc
if highlighting:
highlight = termcolor().errmsg
else:
def highlight(x):
return x
if loc:
super(NumbaWarning, self).__init__(
highlight("%s\n%s\n" % (msg, loc.strformat())))
else:
super(NumbaWarning, self).__init__(highlight("%s" % (msg,)))
class NumbaPerformanceWarning(NumbaWarning):
"""
Warning category for when an operation might not be
as fast as expected.
"""
class NumbaDeprecationWarning(NumbaWarning):
"""
Warning category for use of a deprecated feature.
"""
class NumbaPendingDeprecationWarning(NumbaWarning):
"""
Warning category for use of a feature that is pending deprecation.
"""
class NumbaParallelSafetyWarning(NumbaWarning):
"""
Warning category for when an operation in a prange
might not have parallel semantics.
"""
class NumbaTypeSafetyWarning(NumbaWarning):
"""
Warning category for unsafe casting operations.
"""
class NumbaExperimentalFeatureWarning(NumbaWarning):
"""
Warning category for using an experimental feature.
"""
class NumbaInvalidConfigWarning(NumbaWarning):
"""
Warning category for using an invalid configuration.
"""
# These are needed in the color formatting of errors setup
class _ColorScheme(metaclass=abc.ABCMeta):
@abstractmethod
def code(self, msg):
pass
@abstractmethod
def errmsg(self, msg):
pass
@abstractmethod
def filename(self, msg):
pass
@abstractmethod
def indicate(self, msg):
pass
@abstractmethod
def highlight(self, msg):
pass
@abstractmethod
def reset(self, msg):
pass
class _DummyColorScheme(_ColorScheme):
def __init__(self, theme=None):
pass
def code(self, msg):
pass
def errmsg(self, msg):
pass
def filename(self, msg):
pass
def indicate(self, msg):
pass
def highlight(self, msg):
pass
def reset(self, msg):
pass
# holds reference to the instance of the terminal color scheme in use
_termcolor_inst = None
try:
import colorama
# If the colorama version is < 0.3.9 it can break stdout/stderr in some
# situations, as a result if this condition is met colorama is disabled and
# the user is warned. Note that early versions did not have a __version__.
colorama_version = getattr(colorama, '__version__', '0.0.0')
if tuple([int(x) for x in colorama_version.split('.')]) < (0, 3, 9):
msg = ("Insufficiently recent colorama version found. "
"Numba requires colorama >= 0.3.9")
# warn the user
warnings.warn(msg)
# trip the exception to disable color errors
raise ImportError
# If Numba is running in testsuite mode then do not use error message
# coloring so CI system output is consistently readable without having
# to read between shell escape characters.
if os.environ.get('NUMBA_DISABLE_ERROR_MESSAGE_HIGHLIGHTING', None):
raise ImportError # just to trigger the exception handler below
except ImportError:
class NOPColorScheme(_DummyColorScheme):
def __init__(self, theme=None):
if theme is not None:
raise ValueError("specifying a theme has no effect")
_DummyColorScheme.__init__(self, theme=theme)
def code(self, msg):
return msg
def errmsg(self, msg):
return msg
def filename(self, msg):
return msg
def indicate(self, msg):
return msg
def highlight(self, msg):
return msg
def reset(self, msg):
return msg
def termcolor():
global _termcolor_inst
if _termcolor_inst is None:
_termcolor_inst = NOPColorScheme()
return _termcolor_inst
else:
from colorama import init, reinit, deinit, Fore, Style
class ColorShell(object):
_has_initialized = False
def __init__(self):
init()
self._has_initialized = True
def __enter__(self):
if self._has_initialized:
reinit()
def __exit__(self, *exc_detail):
Style.RESET_ALL
deinit()
class reset_terminal(object):
def __init__(self):
self._buf = bytearray(b'')
def __enter__(self):
return self._buf
def __exit__(self, *exc_detail):
self._buf += bytearray(Style.RESET_ALL.encode('utf-8'))
# define some default themes, if more are added, update the envvars docs!
themes = {}
# No color added, just bold weighting
themes['no_color'] = {'code': None,
'errmsg': None,
'filename': None,
'indicate': None,
'highlight': None,
'reset': None, }
# suitable for terminals with a dark background
themes['dark_bg'] = {'code': Fore.BLUE,
'errmsg': Fore.YELLOW,
'filename': Fore.WHITE,
'indicate': Fore.GREEN,
'highlight': Fore.RED,
'reset': Style.RESET_ALL, }
# suitable for terminals with a light background
themes['light_bg'] = {'code': Fore.BLUE,
'errmsg': Fore.BLACK,
'filename': Fore.MAGENTA,
'indicate': Fore.BLACK,
'highlight': Fore.RED,
'reset': Style.RESET_ALL, }
# suitable for terminals with a blue background
themes['blue_bg'] = {'code': Fore.WHITE,
'errmsg': Fore.YELLOW,
'filename': Fore.MAGENTA,
'indicate': Fore.CYAN,
'highlight': Fore.RED,
'reset': Style.RESET_ALL, }
# suitable for use in jupyter notebooks
themes['jupyter_nb'] = {'code': Fore.BLACK,
'errmsg': Fore.BLACK,
'filename': Fore.GREEN,
'indicate': Fore.CYAN,
'highlight': Fore.RED,
'reset': Style.RESET_ALL, }
default_theme = themes['no_color']
class HighlightColorScheme(_DummyColorScheme):
def __init__(self, theme=default_theme):
self._code = theme['code']
self._errmsg = theme['errmsg']
self._filename = theme['filename']
self._indicate = theme['indicate']
self._highlight = theme['highlight']
self._reset = theme['reset']
_DummyColorScheme.__init__(self, theme=theme)
def _markup(self, msg, color=None, style=Style.BRIGHT):
features = ''
if color:
features += color
if style:
features += style
with ColorShell():
with reset_terminal() as mu:
mu += features.encode('utf-8')
mu += (msg).encode('utf-8')
return mu.decode('utf-8')
def code(self, msg):
return self._markup(msg, self._code)
def errmsg(self, msg):
return self._markup(msg, self._errmsg)
def filename(self, msg):
return self._markup(msg, self._filename)
def indicate(self, msg):
return self._markup(msg, self._indicate)
def highlight(self, msg):
return self._markup(msg, self._highlight)
def reset(self, msg):
return self._markup(msg, self._reset)
def termcolor():
global _termcolor_inst
if _termcolor_inst is None:
scheme = themes[numba.core.config.COLOR_SCHEME]
_termcolor_inst = HighlightColorScheme(scheme)
return _termcolor_inst
feedback_details = """
Please report the error message and traceback, along with a minimal reproducer
at: https://github.com/numba/numba/issues/new
If more help is needed please feel free to speak to the Numba core developers
directly at: https://gitter.im/numba/numba
Thanks in advance for your help in improving Numba!
"""
unsupported_error_info = """
Unsupported functionality was found in the code Numba was trying to compile.
If this functionality is important to you please file a feature request at:
https://github.com/numba/numba/issues/new
"""
interpreter_error_info = """
Unsupported Python functionality was found in the code Numba was trying to
compile. This error could be due to invalid code, does the code work
without Numba? (To temporarily disable Numba JIT, set the `NUMBA_DISABLE_JIT`
environment variable to non-zero, and then rerun the code).
If the code is valid and the unsupported functionality is important to you
please file a feature request at: https://github.com/numba/numba/issues/new
To see Python/NumPy features supported by the latest release of Numba visit:
https://numba.pydata.org/numba-doc/latest/reference/pysupported.html
and
https://numba.pydata.org/numba-doc/latest/reference/numpysupported.html
"""
constant_inference_info = """
Numba could not make a constant out of something that it decided should be
a constant. This could well be a current limitation in Numba's internals,
however please first check that your code is valid for compilation,
particularly with respect to string interpolation (not supported!) and
the requirement of compile time constants as arguments to exceptions:
https://numba.pydata.org/numba-doc/latest/reference/pysupported.html?highlight=exceptions#constructs
If the code is valid and the unsupported functionality is important to you
please file a feature request at: https://github.com/numba/numba/issues/new
If you think your code should work with Numba. %s
""" % feedback_details
typing_error_info = """
This is not usually a problem with Numba itself but instead often caused by
the use of unsupported features or an issue in resolving types.
To see Python/NumPy features supported by the latest release of Numba visit:
https://numba.pydata.org/numba-doc/latest/reference/pysupported.html
and
https://numba.pydata.org/numba-doc/latest/reference/numpysupported.html
For more information about typing errors and how to debug them visit:
https://numba.pydata.org/numba-doc/latest/user/troubleshoot.html#my-code-doesn-t-compile
If you think your code should work with Numba, please report the error message
and traceback, along with a minimal reproducer at:
https://github.com/numba/numba/issues/new
"""
reportable_issue_info = """
-------------------------------------------------------------------------------
This should not have happened, a problem has occurred in Numba's internals.
You are currently using Numba version %s.
%s
""" % (numba.__version__, feedback_details)
error_extras = dict()
error_extras['unsupported_error'] = unsupported_error_info
error_extras['typing'] = typing_error_info
error_extras['reportable'] = reportable_issue_info
error_extras['interpreter'] = interpreter_error_info
error_extras['constant_inference'] = constant_inference_info
def deprecated(arg):
"""Define a deprecation decorator.
An optional string should refer to the new API to be used instead.
Example:
@deprecated
def old_func(): ...
@deprecated('new_func')
def old_func(): ..."""
subst = arg if isinstance(arg, str) else None
def decorator(func):
def wrapper(*args, **kwargs):
msg = "Call to deprecated function \"{}\"."
if subst:
msg += "\n Use \"{}\" instead."
warnings.warn(msg.format(func.__name__, subst),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
return wraps(func)(wrapper)
if not subst:
return decorator(arg)
else:
return decorator
class WarningsFixer(object):
"""
An object "fixing" warnings of a given category caught during
certain phases. The warnings can have their filename and lineno fixed,
and they are deduplicated as well.
"""
def __init__(self, category):
self._category = category
# {(filename, lineno, category) -> messages}
self._warnings = defaultdict(set)
@contextlib.contextmanager
def catch_warnings(self, filename=None, lineno=None):
"""
Store warnings and optionally fix their filename and lineno.
"""
with warnings.catch_warnings(record=True) as wlist:
warnings.simplefilter('always', self._category)
yield
for w in wlist:
msg = str(w.message)
if issubclass(w.category, self._category):
# Store warnings of this category for deduplication
filename = filename or w.filename
lineno = lineno or w.lineno
self._warnings[filename, lineno, w.category].add(msg)
else:
# Simply emit other warnings again
warnings.warn_explicit(msg, w.category,
w.filename, w.lineno)
def flush(self):
"""
Emit all stored warnings.
"""
def key(arg):
# It is possible through codegen to create entirely identical
# warnings, this leads to comparing types when sorting which breaks
# on Python 3. Key as str() and if the worse happens then `id`
# creates some uniqueness
return str(arg) + str(id(arg))
for (filename, lineno, category), messages in sorted(
self._warnings.items(), key=key):
for msg in sorted(messages):
warnings.warn_explicit(msg, category, filename, lineno)
self._warnings.clear()
class NumbaError(Exception):
def __init__(self, msg, loc=None, highlighting=True):
self.msg = msg
self.loc = loc
if highlighting:
highlight = termcolor().errmsg
else:
def highlight(x):
return x
if loc:
new_msg = "%s\n%s\n" % (msg, loc.strformat())
else:
new_msg = "%s" % (msg,)
super(NumbaError, self).__init__(highlight(new_msg))
@property
def contexts(self):
try:
return self._contexts
except AttributeError:
self._contexts = lst = []
return lst
def add_context(self, msg):
"""
Add contextual info. The exception message is expanded with the new
contextual information.
"""
self.contexts.append(msg)
f = termcolor().errmsg('{0}\n') + termcolor().filename('During: {1}')
newmsg = f.format(self, msg)
self.args = (newmsg,)
return self
def patch_message(self, new_message):
"""
Change the error message to the given new message.
"""
self.args = (new_message,) + self.args[1:]
class UnsupportedError(NumbaError):
"""
Numba does not have an implementation for this functionality.
"""
pass
class UnsupportedRewriteError(UnsupportedError):
"""UnsupportedError from rewrite passes
"""
pass
class IRError(NumbaError):
"""
An error occurred during Numba IR generation.
"""
pass
class RedefinedError(IRError):
"""
An error occurred during interpretation of IR due to variable redefinition.
"""
pass
class NotDefinedError(IRError):
"""
An undefined variable is encountered during interpretation of IR.
"""
def __init__(self, name, loc=None):
self.name = name
msg = ("The compiler failed to analyze the bytecode. "
"Variable '%s' is not defined." % name)
super(NotDefinedError, self).__init__(msg, loc=loc)
class VerificationError(IRError):
"""
An error occurred during IR verification. Once Numba's internal
representation (IR) is constructed it is then verified to ensure that
terminators are both present and in the correct places within the IR. If
it is the case that this condition is not met, a VerificationError is
raised.
"""
pass
class DeprecationError(NumbaError):
"""
Functionality is deprecated.
"""
pass
class LoweringError(NumbaError):
"""
An error occurred during lowering.
"""
def __init__(self, msg, loc=None):
super(LoweringError, self).__init__(msg, loc=loc)
class UnsupportedParforsError(NumbaError):
"""
An error ocurred because parfors is not supported on the platform.
"""
pass
class ForbiddenConstruct(LoweringError):
"""
A forbidden Python construct was encountered (e.g. use of locals()).
"""
pass
class TypingError(NumbaError):
"""
A type inference failure.
"""
pass
class UntypedAttributeError(TypingError):
def __init__(self, value, attr, loc=None):
module = getattr(value, 'pymod', None)
if module is not None and module == np:
# unsupported numpy feature.
msg = ("Use of unsupported NumPy function 'numpy.%s' "
"or unsupported use of the function.") % attr
else:
msg = "Unknown attribute '{attr}' of type {type}"
msg = msg.format(type=value, attr=attr)
super(UntypedAttributeError, self).__init__(msg, loc=loc)
class ByteCodeSupportError(NumbaError):
"""
Failure to extract the bytecode of the user's function.
"""
def __init__(self, msg, loc=None):
super(ByteCodeSupportError, self).__init__(msg, loc=loc)
class CompilerError(NumbaError):
"""
Some high-level error in the compiler.
"""
pass
class ConstantInferenceError(NumbaError):
"""
Failure during constant inference.
"""
def __init__(self, value, loc=None):
super(ConstantInferenceError, self).__init__(value, loc=loc)
class InternalError(NumbaError):
"""
For wrapping internal error occured within the compiler
"""
def __init__(self, exception):
super(InternalError, self).__init__(str(exception))
self.old_exception = exception
class InternalTargetMismatchError(InternalError):
"""For signalling a target mismatch error occurred internally within the
compiler.
"""
def __init__(self, kind, target_hw, hw_clazz):
msg = (f"{kind.title()} being resolved on a target from which it does "
f"not inherit. Local target is {target_hw}, declared "
f"target class is {hw_clazz}.")
super().__init__(msg)
class RequireLiteralValue(TypingError):
"""
For signalling that a function's typing requires a constant value for
some of its arguments.
"""
pass
class ForceLiteralArg(NumbaError):
"""A Pseudo-exception to signal the dispatcher to type an argument literally
Attributes
----------
requested_args : frozenset[int]
requested positions of the arguments.
"""
def __init__(self, arg_indices, fold_arguments=None, loc=None):
"""
Parameters
----------
arg_indices : Sequence[int]
requested positions of the arguments.
fold_arguments: callable
A function ``(tuple, dict) -> tuple`` that binds and flattens
the ``args`` and ``kwargs``.
loc : numba.ir.Loc or None
"""
super(ForceLiteralArg, self).__init__(
"Pseudo-exception to force literal arguments in the dispatcher",
loc=loc,
)
self.requested_args = frozenset(arg_indices)
self.fold_arguments = fold_arguments
def bind_fold_arguments(self, fold_arguments):
"""Bind the fold_arguments function
"""
e = ForceLiteralArg(self.requested_args, fold_arguments,
loc=self.loc)
return chain_exception(e, self)
def combine(self, other):
"""Returns a new instance by or'ing the requested_args.
"""
if not isinstance(other, ForceLiteralArg):
m = '*other* must be a {} but got a {} instead'
raise TypeError(m.format(ForceLiteralArg, type(other)))
return ForceLiteralArg(self.requested_args | other.requested_args)
def __or__(self, other):
"""Same as self.combine(other)
"""
return self.combine(other)
class LiteralTypingError(TypingError):
"""
Failure in typing a Literal type
"""
pass
def _format_msg(fmt, args, kwargs):
return fmt.format(*args, **kwargs)
_numba_path = os.path.dirname(__file__)
loc_info = {}
@contextlib.contextmanager
def new_error_context(fmt_, *args, **kwargs):
"""
A contextmanager that prepend contextual information to any exception
raised within. If the exception type is not an instance of NumbaError,
it will be wrapped into a InternalError. The exception class can be
changed by providing a "errcls_" keyword argument with the exception
constructor.
The first argument is a message that describes the context. It can be a
format string. If there are additional arguments, it will be used as
``fmt_.format(*args, **kwargs)`` to produce the final message string.
"""
errcls = kwargs.pop('errcls_', InternalError)
loc = kwargs.get('loc', None)
if loc is not None and not loc.filename.startswith(_numba_path):
loc_info.update(kwargs)
try:
yield
except NumbaError as e:
e.add_context(_format_msg(fmt_, args, kwargs))
raise
except AssertionError:
# Let assertion error pass through for shorter traceback in debugging
raise
except Exception as e:
newerr = errcls(e).add_context(_format_msg(fmt_, args, kwargs))
tb = sys.exc_info()[2] if numba.core.config.FULL_TRACEBACKS else None
raise newerr.with_traceback(tb)
__all__ += [name for (name, value) in globals().items()
if not name.startswith('_') and isinstance(value, type)
and issubclass(value, (Exception, Warning))]
|
|
#!/usr/bin/env python
"""
Usage: $0 PATIENT_ID VCF CREDENTIALS_FILE SERVER_NAME
Upload the VCF file as an attachment for the given patient. For example:
$0 P0000102 path/to/file.vcf path/to/credentials.txt server_name
credentials.txt should have one line with the form:
username:password
"""
from __future__ import with_statement
import sys
import os
import logging
import json
try:
from httplib import HTTPConnection
except ImportError:
from http.client import HTTPSConnection
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
from base64 import b64encode
import xml.etree.ElementTree as ET
# Set globally after parsing arguments
CREDENTIALS = None
SERVER = None
def load_credentials(filename):
global CREDENTIALS
logging.info('Using credentials in file: {0}'.format(filename))
with open(filename) as ifp:
CREDENTIALS = ifp.read().strip()
class Request(object):
def __init__(self, method, resource, content_type='text/plain', **kwargs):
auth = b64encode(CREDENTIALS.encode()).decode()
self._headers = {
'Authorization': 'Basic {0}'.format(auth),
'Content-Type': content_type,
'Accept': '*/*'
}
self._method = method
self._href = resource
self._kwargs = kwargs
self._conn = None
def __enter__(self):
self._conn = HTTPSConnection(SERVER)
#self._conn.set_debuglevel(1)
self._conn.request(self._method, self._href, headers=self._headers, **self._kwargs)
response = self._conn.getresponse()
return response
def __exit__(self, *args, **kwargs):
if self._conn:
self._conn.close()
def get_consent(record_id):
logging.info('Loading Consents for record: {0}'.format(record_id))
href = '/rest/patients/{0}/consents/'.format(record_id)
result = 'no'
with Request('GET', href) as response:
assert response.status == 200, \
'ERROR getting PhenoTips.VCF object for record: {0}'.format(response.headers)
logging.info('Consents for record: {0}'.format(record_id))
# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)
for consent in json_obj:
if consent['id'] == 'genetic':
result = consent['status']
return result
def get_vcf_object(record_id):
href = '/rest/wikis/xwiki/spaces/data/pages/{0}/objects/PhenoTips.VCF'.format(record_id)
result = {}
with Request('GET', href) as response:
if response.status == 500:
# No VCF object for patient
logging.info('No PhenoTips.VCF object for record: {0}'.format(record_id))
return result
assert response.status == 200, \
'ERROR getting PhenoTips.VCF object for record: {0}'.format(response.headers)
logging.info('Found PhenoTips.VCF object for record: {0}'.format(record_id))
root = ET.fromstring(response.read())
# Server is Python 2.6.6, so does not support namespaces argument
# namespaces = {'xwiki': 'http://www.xwiki.org'}
summary = root.find('{http://www.xwiki.org}objectSummary')
if not summary:
logging.info('No VCF object exist in record: {0}'.format(record_id))
return None
for link in summary.findall('{http://www.xwiki.org}link'):
if link.get('rel') == 'http://www.xwiki.org/rel/object':
href = link.get('href')
logging.info('Found VCF object for {0}: {1}'.format(record_id, href))
result['href'] = href
break
result['headline'] = summary.findtext('{http://www.xwiki.org}headline', '').strip()
return result
def set_vcf_properties(record_id, vcf_object, filename, reference_genome='GRCh37'):
method = 'PUT'
href = vcf_object.get('href') if vcf_object else None
if not href:
# Create VCF missing properties object
method = 'POST'
href = '/rest/wikis/xwiki/spaces/data/pages/{0}/objects'.format(record_id)
filebase = os.path.basename(filename)
params = {
'className': 'PhenoTips.VCF',
'property#filename': filebase,
'property#reference_genome': reference_genome,
}
content_type = 'application/x-www-form-urlencoded'
with Request(method, href, content_type=content_type, body=urlencode(params)) as response:
assert response.status in [201, 202], \
'Unexpected response ({0}) from setting VCF properties'.format(response.status)
if response.status == 201:
href = response.getheader('Location')
logging.info('Created VCF object: {0}'.format(href))
return href
elif response.status == 202:
logging.info('Updated VCF object: {0}'.format(href))
return vcf_object
def delete_old_vcf_file(record_id):
attachment_name = '{0}.vcf'.format(record_id)
href = '/rest/wikis/xwiki/spaces/data/pages/{0}/attachments/{1}'.format(record_id, attachment_name)
with Request('HEAD', href) as response:
if response.status in [200, 500]:
logging.info('Found linked old-style VCF: {0}'.format(attachment_name))
else:
return
with Request('DELETE', href) as response:
assert response.status in [204, 500], \
'Unexpected response ({0}) from deleting VCF file'.format(response.status)
logging.info('Deleted attachment: {0}'.format(attachment_name))
with Request('DELETE', href) as response:
assert response.status == 404, \
'Failed to delete existing old-style VCF file'.format(response.status)
def upload_vcf_file(record_id, filename):
attachment_name = os.path.basename(filename)
href = '/rest/wikis/xwiki/spaces/data/pages/{0}/attachments/{1}'.format(record_id, attachment_name)
with open(filename) as file:
with Request('PUT', href, content_type='text/plain', body=file) as response:
assert response.status in [201, 202], \
'Unexpected response ({0}) from uploading VCF file'.format(response.status)
if response.status == 201:
logging.info('Created attachment: {0}'.format(attachment_name))
elif response.status == 202:
logging.info('Updated attachment: {0}'.format(attachment_name))
def script(record_id, vcf_filename, credentials_file, server_name):
global SERVER
SERVER = server_name
load_credentials(credentials_file)
consent_granted = get_consent(record_id)
if consent_granted == 'no':
logging.info('Record {0} has not granted genetic consent, can not upload VCF'.format(record_id))
return
vcf_object = get_vcf_object(record_id)
vcf_basename = os.path.basename(vcf_filename)
if vcf_object and vcf_object.get('headline', '') == vcf_basename:
# Filename already appears to be properly linked to record, skip
logging.info('Record {0} already has linked VCF file: {1}'.format(record_id, vcf_basename))
else:
href = set_vcf_properties(record_id, vcf_object, vcf_filename)
if href:
upload_vcf_file(record_id, vcf_filename)
# Optional, remove old VCF file
# delete_old_vcf_file(record_id)
def parse_args(args):
from optparse import OptionParser
usage = "usage: %prog [options] PATIENT_ID VCF CREDENTIALS_FILE SERVER_NAME"
parser = OptionParser(usage=usage)
(options, args) = parser.parse_args()
if len(args) != 4:
parser.error('Invalid number of arguments')
return (options, args)
def main(args=sys.argv[1:]):
options, args = parse_args(args)
kwargs = dict(options.__dict__)
logging.basicConfig(level=logging.DEBUG)
script(*args, **kwargs)
if __name__ == '__main__':
sys.exit(main())
|
|
from mock import Mock, patch
from dynpool import DynamicPoolResizer
def test_no_threads_and_no_conns_grows_minthreads():
min_threads = 5
pool = Mock(min=min_threads, max=30, size=0, idle=0, qsize=0)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
assert resizer.grow_value == min_threads
assert resizer.shrink_value == 0
def test_no_threads_and_waiting_conns_grows_enough():
maxspare = 10
pool = Mock(min=5, max=30, size=0, idle=0, qsize=4)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=maxspare)
# We need to have grown enough threads so that we:
# - Have enough to satisfy as many requests in the queue
# - Have enough spare threads (between min and max spare).
assert 9 <= resizer.grow_value <= 14
assert resizer.shrink_value == 0
def test_no_idle_threads_and_waiting_conns_grows_enough():
maxspare = 10
pool = Mock(min=5, max=30, size=4, idle=0, qsize=4)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=maxspare)
# We need to have grown enough threads so that we:
# - Have enough to satisfy as many requests in the queue
# - Have enough spare threads (between min and max spare).
assert 9 <= resizer.grow_value <= 14
assert resizer.shrink_value == 0
def test_no_idle_threads_and_waiting_conns_grows_enough_respecting_max():
maxspare = 40
pool = Mock(min=20, max=40, size=21, idle=0, qsize=4)
resizer = DynamicPoolResizer(pool, minspare=10, maxspare=maxspare)
# We need to have grown enough threads so that we:
# - Have enough to satisfy as many requests in the queue
# - Have enough spare threads (between min and max spare).
# - We do not exceed the maximum number of threads.
assert 14 <= resizer.grow_value <= 40
assert resizer.shrink_value == 0
def test_no_idle_threads_and_waiting_conns_grows_bigger_than_maxspare():
maxspare = 40
pool = Mock(min=20, max=200, size=21, idle=0, qsize=50)
resizer = DynamicPoolResizer(pool, minspare=10, maxspare=maxspare)
# We need to have grown enough threads so that we:
# - Have enough to satisfy as many requests in the queue
# - Have enough spare threads (between min and max spare).
# - We do not exceed the maximum number of threads.
# - We grow more than maxspare (older versions of dynpool would
# limit it to maxspare).
assert 60 <= resizer.grow_value <= 90
assert resizer.shrink_value == 0
def test_less_idle_threads_than_minspare_grows():
idle = 2
minspare = 5
pool = Mock(min=5, max=30, size=10, idle=idle, qsize=0)
resizer = DynamicPoolResizer(pool, minspare=minspare, maxspare=10)
assert resizer.grow_value == minspare - idle
assert resizer.shrink_value == 0
def test_less_threads_than_minimum_grows():
size = 3
minthreads = 5
pool = Mock(min=minthreads, max=30, size=size, idle=4, qsize=0)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
assert resizer.grow_value == minthreads - size
assert resizer.shrink_value == 0
def test_more_threads_than_max_doesnt_grow():
pool = Mock(min=5, max=30, size=100, idle=0, qsize=0)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
assert resizer.grow_value == 0
assert resizer.shrink_value == 0
def test_more_idle_threads_than_maxspare_shrinks_half():
pool = Mock(min=5, max=30, size=20, idle=20, qsize=0)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
assert resizer.grow_value == 0
assert resizer.shrink_value == 15
def test_dont_shrink_when_idle_more_than_maxspare_but_blocked_by_min():
pool = Mock(min=20, max=40, size=20, idle=20, qsize=0)
resizer = DynamicPoolResizer(pool, minspare=10, maxspare=40)
assert resizer.grow_value == 0
assert resizer.shrink_value == 0
def test_normal_thread_counts_without_changes():
pool = Mock(min=5, max=30, size=20, idle=5, qsize=0)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
assert resizer.grow_value == 0
assert resizer.shrink_value == 0
def test_more_threads_than_min_and_all_are_idle_without_incoming_conns_shrink():
pool = Mock(min=5, max=30, size=10, idle=10, qsize=0)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
assert resizer.grow_value == 0
assert resizer.shrink_value == 5
def test_more_idle_threads_than_maxspread_and_no_incoming_conns_shrink():
pool = Mock(min=5, max=30, size=15, idle=12, qsize=0)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
assert resizer.grow_value == 0
assert resizer.shrink_value == 2
def test_more_idle_threads_than_maxspread_and_incoming_conns_shrink():
pool = Mock(min=5, max=30, size=15, idle=12, qsize=2)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
assert resizer.grow_value == 0
assert resizer.shrink_value == 2
def test_more_idle_threads_than_minspread_and_incoming_conns_without_changes():
pool = Mock(min=5, max=30, size=10, idle=7, qsize=3)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
assert resizer.grow_value == 0
assert resizer.shrink_value == 0
def test_more_idle_threads_than_minspread_and_no_incoming_conns_shrink_half():
idle = 17
minspare = 5
expected_shrinking = 6
pool = Mock(min=5, max=30, size=28, idle=idle, qsize=0)
resizer = DynamicPoolResizer(pool, minspare=minspare, maxspare=20)
assert resizer.grow_value == 0
assert resizer.shrink_value == expected_shrinking
def test_user_should_set_a_max_thread_value():
lots_of_threads = 1024*1024
maxspare = 20
pool = Mock(min=5, max=-1, size=lots_of_threads, idle=0, qsize=100)
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=maxspare)
# Despite no maximum provided, we should still grow enough threads
# so that we meet demand - we should be functionally equivalent as
# if the user had specified a very high max value.
assert 105 <= resizer.grow_value <= 120
assert resizer.shrink_value == 0
def test_grow_calls_threadpool_grow():
pool = Mock()
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
resizer.grow(10)
pool.grow.assert_called_once_with(10)
def test_shrink_calls_threadpool_shrink():
pool = Mock()
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
resizer.shrink(10)
pool.shrink.assert_called_once_with(10)
def test_shrink_sets_lastshrink():
pool = Mock()
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
assert resizer.lastshrink is None
resizer.shrink(10)
assert resizer.lastshrink is not None
def test_new_resizer_can_shrink():
pool = Mock()
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
assert resizer.lastshrink is None
assert resizer.can_shrink() is True
def test_can_shrink_past_shrinkfreq():
shrinkfreq = 3
pool = Mock()
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10,
shrinkfreq=shrinkfreq)
resizer.shrink(1)
resizer.lastshrink -= (shrinkfreq + 1)
assert resizer.can_shrink() is True
def test_cannot_shrink_before_shrinkfreq():
shrinkfreq = 3
pool = Mock()
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10,
shrinkfreq=shrinkfreq)
resizer.shrink(1)
resizer.lastshrink -= (shrinkfreq - 1)
assert resizer.can_shrink() is False
# If we have one more thread than minspare, then avoid shrinking.
#
# Otherwise, as soon as a request comes in and is allocated to a thread,
# we will have to create a new thread to satisfy the "minspare"
# requirement. It makes more sense to have a spare thread hanging
# around, rather than having a thread fluttering in and out of
# existence.
def test_no_spare_fluttering_thread():
pool = Mock(min=1, max=30, size=4, idle=3, qsize=0)
resizer = DynamicPoolResizer(pool, minspare=2, maxspare=10)
assert resizer.shrink_value == 0
@patch.multiple('dynpool.DynamicPoolResizer',
grow_value=3, shrink_value=0,
grow=Mock(), shrink=Mock(), can_shrink=Mock())
def test_run_with_grow_value_calls_grow_and_not_shrink():
pool = Mock()
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
resizer.run()
resizer.grow.assert_called_once_with(3)
assert not resizer.can_shrink.called
assert not resizer.shrink.called
@patch.multiple('dynpool.DynamicPoolResizer',
grow_value=0, shrink_value=3,
grow=Mock(), shrink=Mock(), can_shrink=Mock())
def test_run_with_shrink_value_calls_shrink_and_not_grow():
pool = Mock()
resizer = DynamicPoolResizer(pool, minspare=5, maxspare=10)
resizer.run()
assert not resizer.grow.called
assert resizer.can_shrink.called
resizer.shrink.assert_called_once_with(3)
|
|
import sys
import numpy as np
import wx
# from python praxis book
# import wx.lib.newevent s 1076
# from threading import Thread s1078
from jumeg.jumeg_base import JuMEG_Base_Basic
from jumeg.tsv.jumeg_tsv_wx_glcanvas import JuMEG_TSV_Plot2D
import jumeg.tsv.jumeg_tsv_wx_utils as jwx_utils
from jumeg.tsv.jumeg_tsv_data import JuMEG_TSV_DATA
#----------------------------------------------------------------------------------------
class JuMEG_TSV_MainPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
#vbox.Add((20, 30))
self.plt2d = JuMEG_TSV_Plot2D(self)
self.plt2d.SetMinSize((10, 50))
vbox.Add(self.plt2d, 1, wx.ALIGN_CENTER|wx.ALL|wx.EXPAND,5)
#self.plt2d2 = JuMEG_TSV_Plot2D(self)
#self.plt2d2.SetMinSize((10, 50))
#vbox.Add(self.plt2d2, 1, wx.ALIGN_CENTER|wx.ALL|wx.EXPAND,5)
self.SetAutoLayout(True)
self.SetSizer(vbox)
#----------------------------------------------------------------------
class JuMEG_TSV_APP(wx.App):
def __init__(self,**kwargs):
self.TSV_DATA = JuMEG_TSV_DATA(**kwargs)
# redirect stout/err to wx console
wx.App.__init__(self,redirect=True, filename=None)
#self.settings={ 'subplot':{ 'MEG':{'rows':1,'cols':10},
# 'ICA':{'rows':1,'cols':10}},
# 'time':{}
# }
def OnInit(self):
self._ID_OPT_PLOT = wx.NewId()
self._ID_OPT_TIME = wx.NewId()
self._ID_OPT_CHANNELS = wx.NewId()
self.frame = wx.Frame(None, -1, "JuMEG TSV: ", pos=(0,0),
style=wx.DEFAULT_FRAME_STYLE|wx.FULL_REPAINT_ON_RESIZE, name="jumeg_tsv_main")
# self.frame.CreateStatusBar()
self.wx_init_statusbar()
#self.wx_init_toolbar()
self.wx_init_main_menu()
self.frame.Show(True)
self.frame.Bind(wx.EVT_CLOSE, self.OnCloseFrame)
self.Bind(wx.EVT_KEY_DOWN,self.OnKeyDown)
self.plot_panel = JuMEG_TSV_MainPanel(self.frame)
self.plot2d = self.plot_panel.plt2d.plot2d
# set the frame to a good size for showing the two buttons
self.frame.SetSize((640,480))
#self.main_window.SetFocus()
#self.window = win
frect = self.frame.GetRect()
self.SetTopWindow(self.frame)
if self.TSV_DATA.fname:
self.TSV_DATA.load_raw()
self.plot2d.update_data(raw=self.TSV_DATA.raw)
print "DONE ON INIT"
return True
#--- init stuff I/O
#--- click on stuff
def ClickOnOpen(self,event=None):
f = jwx_utils.jumeg_wx_openfile(self.frame,path=self.TSV_DATA.path)
if f:
print f
self.TSV_DATA.update(fname=f)
self.plot2d.update_data(raw=self.TSV_DATA.raw)
print"DONE update"
def ClickOnSave(self,event=None):
print"click_on_save"
def ClickOnClear(self,event=None):
print"click_on_clear"
def ClickOnExit(self,event=None):
ret = wx.MessageBox('Are you sure to quit?', 'Question',wx.YES_NO | wx.NO_DEFAULT, self.frame)
if ret == wx.YES:
self.frame.Close(True)
def ClickOnPlotOpt(self,event=None):
print"click_on_plot"
#r,c =jwx_utils.jumeg_wx_dlg_plot_option( r=3,c=5,rmax=1000,cmax=1000) #,self.option['subplot'])
update = jwx_utils.jumeg_wx_dlg_plot_option( **self.plot2d.plot_options ) #,self.option['subplot'])
if update:
self.plot2d.update_data(raw=self.TSV_DATA.raw)
# self.plot2d.Refresh()
def ClickOnTimeOpt(self,event=None):
print"click_on_time"
def ClickOnChannelsOpt(self,event=None):
print"click_on_channels"
def ClickOnAbout(self,event=None):
jutils.jumeg_wx_utils_about_box()
def wx_init_main_menu(self):
_menubar = wx.MenuBar()
#--- File I/O
_menu_file = wx.Menu()
__id=_menu_file.Append(wx.ID_OPEN, '&Open')
self.Bind(wx.EVT_MENU,self.ClickOnOpen,__id )
__id=_menu_file.Append(wx.ID_SAVE, '&Save')
self.Bind(wx.EVT_MENU,self.ClickOnSave,__id)
_menu_file.AppendSeparator()
__idx=_menu_file.Append(wx.ID_CLEAR,'&Clear')
self.Bind(wx.EVT_MENU,self.ClickOnClear,__id)
_menu_file.AppendSeparator()
__id=_menu_file.Append(wx.ID_EXIT, '&Exit')
self.Bind(wx.EVT_MENU,self.ClickOnExit,__id)
_menubar.Append(_menu_file, '&File')
#--- Options
_menu_opt = wx.Menu()
__id=_menu_opt.Append(self._ID_OPT_PLOT, '&Plot')
self.Bind(wx.EVT_MENU,self.ClickOnPlotOpt,__id)
__id=_menu_opt.Append(self._ID_OPT_TIME, '&Time')
self.Bind(wx.EVT_MENU,self.ClickOnTimeOpt,__id)
__id=_menu_opt.Append(self._ID_OPT_CHANNELS,'&Channels')
self.Bind(wx.EVT_MENU,self.ClickOnChannelsOpt,__id)
_menubar.Append(_menu_opt, '&Options')
#--- About
_menu_about = wx.Menu()
__id=_menu_about.Append(wx.ID_ABOUT, '&About')
self.Bind(wx.EVT_MENU,self.ClickOnAbout,__id)
_menubar.Append(_menu_about, '&About')
self.frame.SetMenuBar(_menubar)
def wx_init_statusbar(self):
self.statusbar = self.frame.CreateStatusBar(3)
# self.statusbar.SetStatusWidths([-1, -1 , -1])
#self.statusbar.SetStatusText('1', '2')
def OnExitApp(self, evt):
self.frame.Close(True)
def OnCloseFrame(self, evt):
if hasattr(self, "window") and hasattr(self.window, "ShutdownDemo"):
self.window.ShutdownDemo()
evt.Skip()
def OnKeyDown(self, e):
key = e.GetKeyCode()
#---escape to quit
if key == wx.WXK_ESCAPE:
self.click_on_exit(e)
def jumeg_tsv_gui(**kwargs):
app = JuMEG_TSV_APP(**kwargs)
# fname=None,path=None,raw=None,experiment=None,verbose=False,debug=False,duration=None,start=None,n_channels=None,bads=None)
app.MainLoop()
if __name__ == '__main__':
jumeg_tsv_gui()
|
|
#
# localDocker.py - Implements the Tango VMMS interface to run Tango jobs in
# docker containers. In this context, VMs are docker containers.
#
import random
import subprocess
import re
import time
import logging
import threading
import os
import sys
import shutil
import config
from tangoObjects import TangoMachine
def timeout(command, time_out=1):
"""timeout - Run a unix command with a timeout. Return -1 on
timeout, otherwise return the return value from the command, which
is typically 0 for success, 1-255 for failure.
"""
# Launch the command
p = subprocess.Popen(
command, stdout=open("/dev/null", "w"), stderr=subprocess.STDOUT
)
# Wait for the command to complete
t = 0.0
while t < time_out and p.poll() is None:
time.sleep(config.Config.TIMER_POLL_INTERVAL)
t += config.Config.TIMER_POLL_INTERVAL
# Determine why the while loop terminated
if p.poll() is None:
try:
os.kill(p.pid, 9)
except OSError:
pass
returncode = -1
else:
returncode = p.poll()
return returncode
def timeoutWithReturnStatus(command, time_out, returnValue=0):
"""timeoutWithReturnStatus - Run a Unix command with a timeout,
until the expected value is returned by the command; On timeout,
return last error code obtained from the command.
"""
p = subprocess.Popen(
command, stdout=open("/dev/null", "w"), stderr=subprocess.STDOUT
)
t = 0.0
while t < time_out:
ret = p.poll()
if ret is None:
time.sleep(config.Config.TIMER_POLL_INTERVAL)
t += config.Config.TIMER_POLL_INTERVAL
elif ret == returnValue:
return ret
else:
p = subprocess.Popen(
command, stdout=open("/dev/null", "w"), stderr=subprocess.STDOUT
)
return ret
#
# User defined exceptions
#
class LocalDocker(object):
def __init__(self):
"""Checks if the machine is ready to run docker containers.
Initialize boot2docker if running on OS X.
"""
try:
self.log = logging.getLogger("LocalDocker")
# Check import docker constants are defined in config
if len(config.Config.DOCKER_VOLUME_PATH) == 0:
raise Exception("DOCKER_VOLUME_PATH not defined in config.")
except Exception as e:
self.log.error(str(e))
exit(1)
def instanceName(self, id, name):
"""instanceName - Constructs a VM instance name. Always use
this function when you need a VM instance name. Never generate
instance names manually.
"""
return "%s-%s-%s" % (config.Config.PREFIX, id, name)
def getVolumePath(self, instanceName):
volumePath = config.Config.DOCKER_VOLUME_PATH
# Last empty string to cause trailing '/'
volumePath = os.path.join(volumePath, instanceName, "")
return volumePath
def getDockerVolumePath(self, dockerPath, instanceName):
# Last empty string to cause trailing '/'
volumePath = os.path.join(dockerPath, instanceName, "")
return volumePath
def domainName(self, vm):
"""Returns the domain name that is stored in the vm
instance.
"""
return vm.domain_name
#
# VMMS API functions
#
def initializeVM(self, vm):
"""initializeVM - Nothing to do for initializeVM"""
return vm
def waitVM(self, vm, max_secs):
"""waitVM - Nothing to do for waitVM"""
return
def copyIn(self, vm, inputFiles):
"""copyIn - Create a directory to be mounted as a volume
for the docker containers. Copy input files to this directory.
"""
instanceName = self.instanceName(vm.id, vm.image)
volumePath = self.getVolumePath(instanceName)
# Create a fresh volume
os.makedirs(volumePath)
for file in inputFiles:
# Create output directory if it does not exist
os.makedirs(os.path.dirname(volumePath), exist_ok=True)
shutil.copy(file.localFile, volumePath + file.destFile)
self.log.debug(
"Copied in file %s to %s" % (file.localFile, volumePath + file.destFile)
)
return 0
def runJob(self, vm, runTimeout, maxOutputFileSize):
"""runJob - Run a docker container by doing the follows:
- mount directory corresponding to this job to /home/autolab
in the container
- run autodriver with corresponding ulimits and timeout as
autolab user
"""
instanceName = self.instanceName(vm.id, vm.image)
volumePath = self.getVolumePath(instanceName)
if os.getenv("DOCKER_TANGO_HOST_VOLUME_PATH"):
volumePath = self.getDockerVolumePath(
os.getenv("DOCKER_TANGO_HOST_VOLUME_PATH"), instanceName
)
args = ["docker", "run", "--name", instanceName, "-v"]
args = args + ["%s:%s" % (volumePath, "/home/mount")]
args = args + [vm.image]
args = args + ["sh", "-c"]
autodriverCmd = (
"autodriver -u %d -f %d -t %d -o %d autolab > output/feedback 2>&1"
% (
config.Config.VM_ULIMIT_USER_PROC,
config.Config.VM_ULIMIT_FILE_SIZE,
runTimeout,
config.Config.MAX_OUTPUT_FILE_SIZE,
)
)
args = args + [
'cp -r mount/* autolab/; su autolab -c "%s"; \
cp output/feedback mount/feedback'
% autodriverCmd
]
self.log.debug("Running job: %s" % str(args))
ret = timeout(args, runTimeout * 2)
self.log.debug("runJob returning %d" % ret)
return ret
def copyOut(self, vm, destFile):
"""copyOut - Copy the autograder feedback from container to
destFile on the Tango host. Then, destroy that container.
Containers are never reused.
"""
instanceName = self.instanceName(vm.id, vm.image)
volumePath = self.getVolumePath(instanceName)
shutil.move(volumePath + "feedback", destFile)
self.log.debug("Copied feedback file to %s" % destFile)
self.destroyVM(vm)
return 0
def destroyVM(self, vm):
"""destroyVM - Delete the docker container."""
instanceName = self.instanceName(vm.id, vm.image)
volumePath = self.getVolumePath("")
# Do a hard kill on corresponding docker container.
# Return status does not matter.
timeout(["docker", "rm", "-f", instanceName], config.Config.DOCKER_RM_TIMEOUT)
# Destroy corresponding volume if it exists.
if instanceName in os.listdir(volumePath):
shutil.rmtree(volumePath + instanceName)
self.log.debug("Deleted volume %s" % instanceName)
return
def safeDestroyVM(self, vm):
"""safeDestroyVM - Delete the docker container and make
sure it is removed.
"""
start_time = time.time()
while self.existsVM(vm):
if time.time() - start_time > config.Config.DESTROY_SECS:
self.log.error("Failed to safely destroy container %s" % vm.name)
return
self.destroyVM(vm)
return
def getVMs(self):
"""getVMs - Executes and parses `docker ps`. This function
is a lot of parsing and can break easily.
"""
# Get all volumes of docker containers
machines = []
volumePath = self.getVolumePath("")
for volume in os.listdir(volumePath):
if re.match("%s-" % config.Config.PREFIX, volume):
machine = TangoMachine()
machine.vmms = "localDocker"
machine.name = volume
volume_l = volume.split("-")
machine.id = volume_l[1]
machine.image = volume_l[2]
machines.append(machine)
return machines
def existsVM(self, vm):
"""existsVM - Executes `docker inspect CONTAINER`, which returns
a non-zero status upon not finding a container.
"""
instanceName = self.instanceName(vm.id, vm.name)
ret = timeout(["docker", "inspect", instanceName])
return ret == 0
def getImages(self):
"""getImages - Executes `docker images` and returns a list of
images that can be used to boot a docker container with. This
function is a lot of parsing and so can break easily.
"""
result = set()
cmd = "docker images"
o = subprocess.check_output("docker images", shell=True).decode("utf-8")
o_l = o.split("\n")
o_l.pop()
o_l.reverse()
o_l.pop()
for row in o_l:
row_l = row.split(" ")
result.add(re.sub(r".*/([^/]*)", r"\1", row_l[0]))
return list(result)
|
|
from __future__ import unicode_literals
from future.builtins import int, range, str
from datetime import date, datetime
from os.path import join, split
from uuid import uuid4
from django import forms
from django.forms.extras import SelectDateWidget
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from django.template import Template
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.utils.timezone import now
from mezzanine.conf import settings
from mezzanine.forms import fields
from mezzanine.forms.models import FormEntry, FieldEntry
from mezzanine.utils.email import split_addresses as split_choices
fs = FileSystemStorage(location=settings.FORMS_UPLOAD_ROOT)
##############################
# Each type of export filter #
##############################
# Text matches
FILTER_CHOICE_CONTAINS = "1"
FILTER_CHOICE_DOESNT_CONTAIN = "2"
# Exact matches
FILTER_CHOICE_EQUALS = "3"
FILTER_CHOICE_DOESNT_EQUAL = "4"
# Greater/less than
FILTER_CHOICE_BETWEEN = "5"
# Multiple values
FILTER_CHOICE_CONTAINS_ANY = "6"
FILTER_CHOICE_CONTAINS_ALL = "7"
FILTER_CHOICE_DOESNT_CONTAIN_ANY = "8"
FILTER_CHOICE_DOESNT_CONTAIN_ALL = "9"
##########################
# Export filters grouped #
##########################
# Text fields
TEXT_FILTER_CHOICES = (
("", _("Nothing")),
(FILTER_CHOICE_CONTAINS, _("Contains")),
(FILTER_CHOICE_DOESNT_CONTAIN, _("Doesn't contain")),
(FILTER_CHOICE_EQUALS, _("Equals")),
(FILTER_CHOICE_DOESNT_EQUAL, _("Doesn't equal")),
)
# Choices with single value entries
CHOICE_FILTER_CHOICES = (
("", _("Nothing")),
(FILTER_CHOICE_CONTAINS_ANY, _("Equals any")),
(FILTER_CHOICE_DOESNT_CONTAIN_ANY, _("Doesn't equal any")),
)
# Choices with multiple value entries
MULTIPLE_FILTER_CHOICES = (
("", _("Nothing")),
(FILTER_CHOICE_CONTAINS_ANY, _("Contains any")),
(FILTER_CHOICE_CONTAINS_ALL, _("Contains all")),
(FILTER_CHOICE_DOESNT_CONTAIN_ANY, _("Doesn't contain any")),
(FILTER_CHOICE_DOESNT_CONTAIN_ALL, _("Doesn't contain all")),
)
# Dates
DATE_FILTER_CHOICES = (
("", _("Nothing")),
(FILTER_CHOICE_BETWEEN, _("Is between")),
)
# The filter function for each filter type
FILTER_FUNCS = {
FILTER_CHOICE_CONTAINS:
lambda val, field: val.lower() in field.lower(),
FILTER_CHOICE_DOESNT_CONTAIN:
lambda val, field: val.lower() not in field.lower(),
FILTER_CHOICE_EQUALS:
lambda val, field: val.lower() == field.lower(),
FILTER_CHOICE_DOESNT_EQUAL:
lambda val, field: val.lower() != field.lower(),
FILTER_CHOICE_BETWEEN:
lambda val_from, val_to, field: (
(not val_from or val_from <= field) and
(not val_to or val_to >= field)
),
FILTER_CHOICE_CONTAINS_ANY:
lambda val, field: set(val) & set(split_choices(field)),
FILTER_CHOICE_CONTAINS_ALL:
lambda val, field: set(val) == set(split_choices(field)),
FILTER_CHOICE_DOESNT_CONTAIN_ANY:
lambda val, field: not set(val) & set(split_choices(field)),
FILTER_CHOICE_DOESNT_CONTAIN_ALL:
lambda val, field: set(val) != set(split_choices(field)),
}
# Export form fields for each filter type grouping
text_filter_field = forms.ChoiceField(label=" ", required=False,
choices=TEXT_FILTER_CHOICES)
choice_filter_field = forms.ChoiceField(label=" ", required=False,
choices=CHOICE_FILTER_CHOICES)
multiple_filter_field = forms.ChoiceField(label=" ", required=False,
choices=MULTIPLE_FILTER_CHOICES)
date_filter_field = forms.ChoiceField(label=" ", required=False,
choices=DATE_FILTER_CHOICES)
class FormForForm(forms.ModelForm):
"""
Form with a set of fields dynamically assigned, directly based on the
given ``forms.models.Form`` instance.
"""
class Meta:
model = FormEntry
exclude = ("form", "entry_time")
def __init__(self, form, context, *args, **kwargs):
"""
Dynamically add each of the form fields for the given form model
instance and its related field model instances.
"""
self.form = form
self.form_fields = form.fields.visible()
initial = kwargs.pop("initial", {})
# If a FormEntry instance is given to edit, populate initial
# with its field values.
field_entries = {}
if kwargs.get("instance"):
for field_entry in kwargs["instance"].fields.all():
field_entries[field_entry.field_id] = field_entry.value
super(FormForForm, self).__init__(*args, **kwargs)
# Create the form fields.
for field in self.form_fields:
field_key = "field_%s" % field.id
field_class = fields.CLASSES[field.field_type]
field_widget = fields.WIDGETS.get(field.field_type)
field_args = {"label": field.label, "required": field.required,
"help_text": field.help_text}
if field.required and not field.help_text:
field_args["help_text"] = _("required")
arg_names = field_class.__init__.__code__.co_varnames
if "max_length" in arg_names:
field_args["max_length"] = settings.FORMS_FIELD_MAX_LENGTH
if "choices" in arg_names:
choices = list(field.get_choices())
if (field.field_type == fields.SELECT and
field.default not in [c[0] for c in choices]):
choices.insert(0, ("", field.placeholder_text))
field_args["choices"] = choices
if field_widget is not None:
field_args["widget"] = field_widget
#
# Initial value for field, in order of preference:
#
# - If a form model instance is given (eg we're editing a
# form response), then use the instance's value for the
# field.
# - If the developer has provided an explicit "initial"
# dict, use it.
# - The default value for the field instance as given in
# the admin.
#
initial_val = None
try:
initial_val = field_entries[field.id]
except KeyError:
try:
initial_val = initial[field_key]
except KeyError:
initial_val = Template(field.default).render(context)
if initial_val:
if field.is_a(*fields.MULTIPLE):
initial_val = split_choices(initial_val)
elif field.field_type == fields.CHECKBOX:
initial_val = initial_val != "False"
self.initial[field_key] = initial_val
self.fields[field_key] = field_class(**field_args)
if field.field_type == fields.DOB:
_now = datetime.now()
years = list(range(_now.year, _now.year - 120, -1))
self.fields[field_key].widget.years = years
# Add identifying type attr to the field for styling.
setattr(self.fields[field_key], "type",
field_class.__name__.lower())
if (field.required and settings.FORMS_USE_HTML5 and
field.field_type != fields.CHECKBOX_MULTIPLE):
self.fields[field_key].widget.attrs["required"] = ""
if field.placeholder_text and not field.default:
text = field.placeholder_text
self.fields[field_key].widget.attrs["placeholder"] = text
def save(self, **kwargs):
"""
Create a ``FormEntry`` instance and related ``FieldEntry``
instances for each form field.
"""
entry = super(FormForForm, self).save(commit=False)
entry.form = self.form
entry.entry_time = now()
entry.save()
entry_fields = entry.fields.values_list("field_id", flat=True)
new_entry_fields = []
for field in self.form_fields:
field_key = "field_%s" % field.id
value = self.cleaned_data[field_key]
if value and self.fields[field_key].widget.needs_multipart_form:
value = fs.save(join("forms", str(uuid4()), value.name), value)
if isinstance(value, list):
value = ", ".join([v.strip() for v in value])
if field.id in entry_fields:
field_entry = entry.fields.get(field_id=field.id)
field_entry.value = value
field_entry.save()
else:
new = {"entry": entry, "field_id": field.id, "value": value}
new_entry_fields.append(FieldEntry(**new))
if new_entry_fields:
FieldEntry.objects.bulk_create(new_entry_fields)
return entry
def email_to(self):
"""
Return the value entered for the first field of type
``forms.EmailField``.
"""
for field in self.form_fields:
if issubclass(fields.CLASSES[field.field_type], forms.EmailField):
return self.cleaned_data["field_%s" % field.id]
return None
class EntriesForm(forms.Form):
"""
Form with a set of fields dynamically assigned that can be used to
filter entries for the given ``forms.models.Form`` instance.
"""
def __init__(self, form, request, *args, **kwargs):
"""
Iterate through the fields of the ``forms.models.Form`` instance and
create the form fields required to control including the field in
the export (with a checkbox) or filtering the field which differs
across field types. User a list of checkboxes when a fixed set of
choices can be chosen from, a pair of date fields for date ranges,
and for all other types provide a textbox for text search.
"""
self.form = form
self.request = request
self.form_fields = form.fields.all()
self.entry_time_name = str(FormEntry._meta.get_field(
"entry_time").verbose_name)
super(EntriesForm, self).__init__(*args, **kwargs)
for field in self.form_fields:
field_key = "field_%s" % field.id
# Checkbox for including in export.
self.fields["%s_export" % field_key] = forms.BooleanField(
label=field.label, initial=True, required=False)
if field.is_a(*fields.CHOICES):
# A fixed set of choices to filter by.
if field.is_a(fields.CHECKBOX):
choices = ((True, _("Checked")), (False, _("Not checked")))
else:
choices = field.get_choices()
contains_field = forms.MultipleChoiceField(label=" ",
choices=choices, widget=forms.CheckboxSelectMultiple(),
required=False)
self.fields["%s_filter" % field_key] = choice_filter_field
self.fields["%s_contains" % field_key] = contains_field
elif field.is_a(*fields.MULTIPLE):
# A fixed set of choices to filter by, with multiple
# possible values in the entry field.
contains_field = forms.MultipleChoiceField(label=" ",
choices=field.get_choices(),
widget=forms.CheckboxSelectMultiple(),
required=False)
self.fields["%s_filter" % field_key] = multiple_filter_field
self.fields["%s_contains" % field_key] = contains_field
elif field.is_a(*fields.DATES):
# A date range to filter by.
self.fields["%s_filter" % field_key] = date_filter_field
self.fields["%s_from" % field_key] = forms.DateField(
label=" ", widget=SelectDateWidget(), required=False)
self.fields["%s_to" % field_key] = forms.DateField(
label=_("and"), widget=SelectDateWidget(), required=False)
else:
# Text box for search term to filter by.
contains_field = forms.CharField(label=" ", required=False)
self.fields["%s_filter" % field_key] = text_filter_field
self.fields["%s_contains" % field_key] = contains_field
# Add ``FormEntry.entry_time`` as a field.
field_key = "field_0"
self.fields["%s_export" % field_key] = forms.BooleanField(initial=True,
label=FormEntry._meta.get_field("entry_time").verbose_name,
required=False)
self.fields["%s_filter" % field_key] = date_filter_field
self.fields["%s_from" % field_key] = forms.DateField(
label=" ", widget=SelectDateWidget(), required=False)
self.fields["%s_to" % field_key] = forms.DateField(
label=_("and"), widget=SelectDateWidget(), required=False)
def __iter__(self):
"""
Yield pairs of include checkbox / filters for each field.
"""
for field_id in [f.id for f in self.form_fields] + [0]:
prefix = "field_%s_" % field_id
fields = [f for f in super(EntriesForm, self).__iter__()
if f.name.startswith(prefix)]
yield fields[0], fields[1], fields[2:]
def columns(self):
"""
Returns the list of selected column names.
"""
fields = [f.label for f in self.form_fields
if self.cleaned_data["field_%s_export" % f.id]]
if self.cleaned_data["field_0_export"]:
fields.append(self.entry_time_name)
return fields
def rows(self, csv=False):
"""
Returns each row based on the selected criteria.
"""
# Store the index of each field against its ID for building each
# entry row with columns in the correct order. Also store the IDs of
# fields with a type of FileField or Date-like for special handling of
# their values.
field_indexes = {}
file_field_ids = []
date_field_ids = []
for field in self.form_fields:
if self.cleaned_data["field_%s_export" % field.id]:
field_indexes[field.id] = len(field_indexes)
if field.is_a(fields.FILE):
file_field_ids.append(field.id)
elif field.is_a(*fields.DATES):
date_field_ids.append(field.id)
num_columns = len(field_indexes)
include_entry_time = self.cleaned_data["field_0_export"]
if include_entry_time:
num_columns += 1
# Get the field entries for the given form and filter by entry_time
# if specified.
field_entries = FieldEntry.objects.filter(
entry__form=self.form).order_by(
"-entry__id").select_related("entry")
if self.cleaned_data["field_0_filter"] == FILTER_CHOICE_BETWEEN:
time_from = self.cleaned_data["field_0_from"]
time_to = self.cleaned_data["field_0_to"]
if time_from and time_to:
field_entries = field_entries.filter(
entry__entry_time__range=(time_from, time_to))
# Loop through each field value ordered by entry, building up each
# entry as a row. Use the ``valid_row`` flag for marking a row as
# invalid if it fails one of the filtering criteria specified.
current_entry = None
current_row = None
valid_row = True
for field_entry in field_entries:
if field_entry.entry_id != current_entry:
# New entry, write out the current row and start a new one.
if valid_row and current_row is not None:
if not csv:
current_row.insert(0, current_entry)
yield current_row
current_entry = field_entry.entry_id
current_row = [""] * num_columns
valid_row = True
if include_entry_time:
current_row[-1] = field_entry.entry.entry_time
field_value = field_entry.value or ""
# Check for filter.
field_id = field_entry.field_id
filter_type = self.cleaned_data.get("field_%s_filter" % field_id)
filter_args = None
if filter_type:
if filter_type == FILTER_CHOICE_BETWEEN:
f, t = "field_%s_from" % field_id, "field_%s_to" % field_id
filter_args = [self.cleaned_data[f], self.cleaned_data[t]]
else:
field_name = "field_%s_contains" % field_id
filter_args = self.cleaned_data[field_name]
if filter_args:
filter_args = [filter_args]
if filter_args:
# Convert dates before checking filter.
if field_id in date_field_ids:
y, m, d = field_value.split(" ")[0].split("-")
dte = date(int(y), int(m), int(d))
filter_args.append(dte)
else:
filter_args.append(field_value)
filter_func = FILTER_FUNCS[filter_type]
if not filter_func(*filter_args):
valid_row = False
# Create download URL for file fields.
if field_entry.value and field_id in file_field_ids:
url = reverse("admin:form_file", args=(field_entry.id,))
field_value = self.request.build_absolute_uri(url)
if not csv:
parts = (field_value, split(field_entry.value)[1])
field_value = mark_safe("<a href=\"%s\">%s</a>" % parts)
# Only use values for fields that were selected.
try:
current_row[field_indexes[field_id]] = field_value
except KeyError:
pass
# Output the final row.
if valid_row and current_row is not None:
if not csv:
current_row.insert(0, current_entry)
yield current_row
|
|
# -*- coding: utf-8 -*-
import os
import gc
import numpy as np
from PIL import Image
import json
from keras.optimizers import SGD
from keras.layers import Input, merge, ZeroPadding2D
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import AveragePooling2D, GlobalAveragePooling2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.models import Model
import keras.backend as K
from scale_layer import Scale
# SCENE_MODEL_SAVE_PATH = "/home/yan/Desktop/QlabChallengerRepo/ai_challenger_scene/imagenet_models"
SCENE_MODEL_SAVE_PATH = "D:/QlabChallengerRepo/ai_challenger_scene/imagenet_models"
SCENE_TEST_DATA_FOLDER_PATH = "D:/QlabChallengerRepo/test/scene_test_direct_resize_224_224"
def densenet161_model(img_rows, img_cols, color_type=1, nb_dense_block=4, growth_rate=48, nb_filter=96, reduction=0.5, dropout_rate=0.0, weight_decay=1e-4, num_classes=None):
'''
DenseNet 161 Model for Keras
Model Schema is based on
https://github.com/flyyufelix/DenseNet-Keras
ImageNet Pretrained Weights
Theano: https://drive.google.com/open?id=0Byy2AcGyEVxfVnlCMlBGTDR3RGs
TensorFlow: https://drive.google.com/open?id=0Byy2AcGyEVxfUDZwVjU2cFNidTA
# Arguments
nb_dense_block: number of dense blocks to add to end
growth_rate: number of filters to add per dense block
nb_filter: initial number of filters
reduction: reduction factor of transition blocks.
dropout_rate: dropout rate
weight_decay: weight decay factor
classes: optional number of classes to classify images
weights_path: path to pre-trained weights
# Returns
A Keras model instance.
'''
eps = 1.1e-5
# compute compression factor
compression = 1.0 - reduction
# Handle Dimension Ordering for different backends
global concat_axis
if K.image_dim_ordering() == 'tf':
concat_axis = 3
img_input = Input(shape=(224, 224, 3), name='data')
else:
concat_axis = 1
img_input = Input(shape=(3, 224, 224), name='data')
# From architecture for ImageNet (Table 1 in the paper)
nb_filter = 96
nb_layers = [6,12,36,24] # For DenseNet-161
# Initial convolution
x = ZeroPadding2D((3, 3), name='conv1_zeropadding')(img_input)
x = Conv2D(nb_filter, (7, 7), name='conv1', strides=(2, 2), use_bias=False)(x)
x = BatchNormalization(epsilon=eps, axis=concat_axis, name='conv1_bn')(x)
x = Scale(axis=concat_axis, name='conv1_scale')(x)
x = Activation('relu', name='relu1')(x)
x = ZeroPadding2D((1, 1), name='pool1_zeropadding')(x)
x = MaxPooling2D((3, 3), strides=(2, 2), name='pool1')(x)
# Add dense blocks
for block_idx in range(nb_dense_block - 1):
stage = block_idx+2
x, nb_filter = dense_block(x, stage, nb_layers[block_idx], nb_filter, growth_rate, dropout_rate=dropout_rate, weight_decay=weight_decay)
# Add transition_block
x = transition_block(x, stage, nb_filter, compression=compression, dropout_rate=dropout_rate, weight_decay=weight_decay)
nb_filter = int(nb_filter * compression)
final_stage = stage + 1
x, nb_filter = dense_block(x, final_stage, nb_layers[-1], nb_filter, growth_rate, dropout_rate=dropout_rate, weight_decay=weight_decay)
x = BatchNormalization(epsilon=eps, axis=concat_axis, name='conv'+str(final_stage)+'_blk_bn')(x)
x = Scale(axis=concat_axis, name='conv'+str(final_stage)+'_blk_scale')(x)
x = Activation('relu', name='relu'+str(final_stage)+'_blk')(x)
# Truncate and replace softmax layer for transfer learning
# Cannot use model.layers.pop() since model is not of Sequential() type
# The method below works since pre-trained weights are stored in layers but not in the model
x_newfc = GlobalAveragePooling2D(name='pool'+str(final_stage))(x)
x_newfc = Dense(num_classes, name='fc6')(x_newfc)
x_newfc = Activation('softmax', name='prob')(x_newfc)
model = Model(img_input, x_newfc)
weights_path = 'imagenet_models/MODEL_WEIGHTS_2017_10_28_19_14_37.h5'
model.load_weights(weights_path, by_name=True)
# Learning rate is changed to 0.001
sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])
return model
def conv_block(x, stage, branch, nb_filter, dropout_rate=None, weight_decay=1e-4):
'''Apply BatchNorm, Relu, bottleneck 1x1 Conv2D, 3x3 Conv2D, and option dropout
# Arguments
x: input tensor
stage: index for dense block
branch: layer index within each dense block
nb_filter: number of filters
dropout_rate: dropout rate
weight_decay: weight decay factor
'''
eps = 1.1e-5
conv_name_base = 'conv' + str(stage) + '_' + str(branch)
relu_name_base = 'relu' + str(stage) + '_' + str(branch)
# 1x1 Convolution (Bottleneck layer)
inter_channel = nb_filter * 4
x = BatchNormalization(epsilon=eps, axis=concat_axis, name=conv_name_base+'_x1_bn')(x)
x = Scale(axis=concat_axis, name=conv_name_base+'_x1_scale')(x)
x = Activation('relu', name=relu_name_base+'_x1')(x)
x = Conv2D(inter_channel, (1, 1), name=conv_name_base+'_x1', use_bias=False)(x)
if dropout_rate:
x = Dropout(dropout_rate)(x)
# 3x3 Convolution
x = BatchNormalization(epsilon=eps, axis=concat_axis, name=conv_name_base+'_x2_bn')(x)
x = Scale(axis=concat_axis, name=conv_name_base+'_x2_scale')(x)
x = Activation('relu', name=relu_name_base+'_x2')(x)
x = ZeroPadding2D((1, 1), name=conv_name_base+'_x2_zeropadding')(x)
x = Conv2D(nb_filter, (3, 3), name=conv_name_base+'_x2', use_bias=False)(x)
if dropout_rate:
x = Dropout(dropout_rate)(x)
return x
def transition_block(x, stage, nb_filter, compression=1.0, dropout_rate=None, weight_decay=1E-4):
''' Apply BatchNorm, 1x1 Convolution, averagePooling, optional compression, dropout
# Arguments
x: input tensor
stage: index for dense block
nb_filter: number of filters
compression: calculated as 1 - reduction. Reduces the number of feature maps in the transition block.
dropout_rate: dropout rate
weight_decay: weight decay factor
'''
eps = 1.1e-5
conv_name_base = 'conv' + str(stage) + '_blk'
relu_name_base = 'relu' + str(stage) + '_blk'
pool_name_base = 'pool' + str(stage)
x = BatchNormalization(epsilon=eps, axis=concat_axis, name=conv_name_base+'_bn')(x)
x = Scale(axis=concat_axis, name=conv_name_base+'_scale')(x)
x = Activation('relu', name=relu_name_base)(x)
x = Conv2D(int(nb_filter * compression), (1, 1), name=conv_name_base, use_bias=False)(x)
if dropout_rate:
x = Dropout(dropout_rate)(x)
x = AveragePooling2D((2, 2), strides=(2, 2), name=pool_name_base)(x)
return x
def dense_block(x, stage, nb_layers, nb_filter, growth_rate, dropout_rate=None, weight_decay=1e-4, grow_nb_filters=True):
''' Build a dense_block where the output of each conv_block is fed to subsequent ones
# Arguments
x: input tensor
stage: index for dense block
nb_layers: the number of layers of conv_block to append to the model.
nb_filter: number of filters
growth_rate: growth rate
dropout_rate: dropout rate
weight_decay: weight decay factor
grow_nb_filters: flag to decide to allow number of filters to grow
'''
eps = 1.1e-5
concat_feat = x
for i in range(nb_layers):
branch = i+1
x = conv_block(concat_feat, stage, branch, growth_rate, dropout_rate, weight_decay)
concat_feat = merge([concat_feat, x], mode='concat', concat_axis=concat_axis, name='concat_'+str(stage)+'_'+str(branch))
if grow_nb_filters:
nb_filter += growth_rate
return concat_feat, nb_filter
def GetJpgList(p):
if p == "":
return []
# p = p.replace("/", "\\")
if p[-1] != "/":
p = p + "/"
file_list = os.listdir(p)
jpg_list = []
for i in file_list:
if os.path.isfile(p + i):
name, suffix = os.path.splitext(p + i)
if ('.jpg' == suffix):
jpg_list.append(i)
return jpg_list
if __name__ == '__main__':
# Example to fine-tune on 3000 samples from Cifar10
img_rows, img_cols = 224, 224 # Resolution of inputs
channel = 3
num_classes = 80
# batch_size = 1
batch_size = 8
# nb_epoch = 10
nb_epoch = 1
# Load Scene data. Please implement your own load_data() module for your own dataset
if os.path.exists(SCENE_TEST_DATA_FOLDER_PATH):
test_data_files = GetJpgList(SCENE_TEST_DATA_FOLDER_PATH)
else:
print('Test data folder can not find ...')
# Load our model
LAST_SAVED_MODEL = "MODEL_2017_10_26_19_44_12.h5"
LAST_SAVED_MODEL_PATH = os.path.join(SCENE_MODEL_SAVE_PATH, LAST_SAVED_MODEL)
# model = load_model(LAST_SAVED_MODEL)
model = densenet161_model(img_rows=img_rows, img_cols=img_cols, color_type=channel, num_classes=num_classes)
# Make predictions
predict_json = []
count = 1
totalnum = str(len(test_data_files))
# predict_annotation_dic_temp = {}
# predict_annotation_dic_temp['image_id'] = "1.jpg"
# predict_annotation_dic_temp['label_id'] = [1, 2, 3]
# predict_json.append(predict_annotation_dic_temp)
# predict_annotation_dic_temp = {}
# predict_annotation_dic_temp['image_id'] = "2.jpg"
# predict_annotation_dic_temp['label_id'] = [2, 3, 4]
# predict_json.append(predict_annotation_dic_temp)
for i in test_data_files:
im = Image.open(os.path.join(SCENE_TEST_DATA_FOLDER_PATH, i))
im_array = np.array(im).reshape(1, img_rows, img_cols, channel)
predictions_valid = model.predict(im_array, verbose=0)
predict_annotation_dic_temp = {}
predict_annotation_dic_temp['image_id'] = i
predict_label_id = predictions_valid[0].argsort()[-3:][::-1]
predict_annotation_dic_temp['label_id'] = predict_label_id.tolist()
if (count % 100 == 0):
print(str(count) + "/" + totalnum)
# print(predict_annotation_dic_temp)
# print(predict_label_id)
count += 1
predict_json.append(predict_annotation_dic_temp)
(filepath, tempfilename) = os.path.split(LAST_SAVED_MODEL_PATH)
(shotname, extension) = os.path.splitext(tempfilename)
predict_json_file_path = open(shotname + "_train_predict_result.json", "w")
json.dump(predict_json, predict_json_file_path)
gc.collect()
|
|
# -*- coding: utf-8 -*-
"""
Feature correlation analysis
Created on Sun Jan 31 21:09:18 2016
@author: kok
"""
import numpy as np
from FeatureUtils import *
from Crime import Tract
from foursquarePOI import getFourSquarePOIDistribution, getFourSquarePOIDistributionHeader
from scipy.stats import pearsonr
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from pylab import rcParams
rcParams['figure.figsize'] = (4*1.6,3*1.7)
rcParams['pdf.fonttype'] = 42
rcParams['ps.fonttype'] = 42
def correlation_POIdist_crime():
"""
we calculate the correlation between POI distribution and crime for each
community area(CA).
Within each CA, the crime count is number of crime in each tract.
The POI count is number of POIs in each tract.
"""
tracts = Tract.createAllTractObjects()
ordkey = sorted(tracts.keys())
CAs = {}
for key, val in tracts.items():
if val.CA not in CAs:
CAs[val.CA] = [key]
else:
CAs[val.CA].append(key)
Y = retrieve_crime_count(2010, col=['total'], region='tract')
poi_dist = getFourSquarePOIDistribution(gridLevel='tract')
Pearson = {}
for cakey, calist in CAs.items():
crime = []
pois = []
for tractkey in calist:
crime.append(Y[tractkey])
pois.append(poi_dist[ordkey.index(tractkey)])
# calculate correlation
pois = np.array(pois)
crime = np.array(crime)
pearson = []
for i in range(pois.shape[1]):
r = np.vstack( (pois[:,i], crime) )
pearson.append( np.corrcoef(r)[0,1] )
Pearson[cakey] = np.nan_to_num( pearson )
P = []
for key in range(1, 78):
P.append(Pearson[key])
np.savetxt("../R/poi_correlation_ca.csv", P, delimiter=",")
return np.array(P)
def correlation_POI_crime(gridLevel='tract', poiRatio=False):
"""
calculate correlation for different POI category
"""
Y = retrieve_crime_count(2010, col=['total'], region=gridLevel)
h, D = generate_corina_features(region='ca')
popul = D[:,0].reshape(D.shape[0],1)
poi_dist = getFourSquarePOIDistribution(gridLevel=gridLevel, useRatio=poiRatio)
cate_label = ['Food', 'Residence', 'Travel', 'Arts & Entertainment',
'Outdoors & Recreation', 'College & Education', 'Nightlife',
'Professional', 'Shops', 'Event']
if gridLevel == 'tract':
tracts = Tract.createAllTractObjects()
ordkey = sorted(tracts.keys())
crime = []
pois = []
for tractkey in ordkey:
crime.append(Y[tractkey])
pois.append(poi_dist[ordkey.index(tractkey)])
pois = np.array(pois)
crime = np.array(crime)
for i in range(pois.shape[1]):
r = np.vstack( (pois[:,i], crime) )
pcc = np.corrcoef(r)[0,1]
print pcc
elif gridLevel == 'ca':
Y = np.divide(Y, popul) * 10000
Y = Y.reshape( (len(Y),) )
poi_dist = np.transpose(poi_dist)
for i in range(poi_dist.shape[0]):
poi = np.reshape(poi_dist[i,:], Y.shape )
r, p = pearsonr(poi, Y)
print cate_label[i], r, p
def line_POI_crime():
d = getFourSquarePOIDistribution(gridLevel='ca')
y = retrieve_crime_count(2010, col=['total'], region='ca')
h, D = generate_corina_features(region='ca')
popul = D[:,0].reshape(D.shape[0],1)
hd = getFourSquarePOIDistributionHeader()
yhat = np.divide(y, popul) * 10000
for i in range(6,8):
plt.figure()
plt.scatter(d[:,i], y)
plt.xlim(0, 1000)
plt.xlabel('POI count -- {0} category'.format(hd[i]))
plt.ylabel('Crime count')
plt.figure()
plt.scatter(d[:,i], yhat)
plt.xlim(0, 1000)
plt.xlabel('POI count -- {0} category'.format(hd[i]))
plt.ylabel('Crime rate (per 10,000)')
def correlation_demo_crime():
"""
demographics correlation with crime
"""
Y = retrieve_crime_count(year=2010, col=['total'], region='ca')
h, D = generate_corina_features(region='ca')
print h
popul = D[:,0].reshape(D.shape[0],1)
Y = np.divide(Y, popul) * 10000
Y = Y.reshape( (len(Y),) )
D = D.transpose()
for i in range(D.shape[0]):
demo = D[i,:].reshape( (Y.shape ) )
r, p = pearsonr(demo, Y)
print r, p
def correlation_socialflow_crime(region='tract', useRate=False,
weightSocialFlow=False):
"""
calculate the correlation between social flow and crime count.
"""
if region == 'ca':
W = generate_transition_SocialLag(region='ca')
W2 = generate_geographical_SpatialLag_ca()
Y = retrieve_crime_count(2010, region='ca')
elif region == 'tract':
W = generate_transition_SocialLag(region='tract')
W2, tractkey = generate_geographical_SpatialLag()
Ymap = retrieve_crime_count(2010, col=['total'], region='tract')
Y = np.array( [Ymap[k] for k in tractkey] ).reshape(len(Ymap), 1)
U = generate_corina_features(region)
if useRate:
print 'Use crime rate per 10,000 population'
if region == 'tract':
C_mtx = []
cnt = 0
for k in tractkey:
if k in U[1]:
C_mtx.append(U[1][k])
else:
cnt += 1
C_mtx.append( [1] + [0 for i in range(6)] ) # population 1
U = ( U[0], np.array( C_mtx ) )
print len(tractkey), cnt
popul = U[1][:,0].reshape(U[1].shape[0],1)
Y = np.divide(Y, popul) * 10000
if weightSocialFlow:
wC = 130.0 if useRate else 32.0 # constant parameter
poverty = U[1][:,2]
for i in range(W.shape[0]):
for j in range (W.shape[1]):
s = np.exp( - np.abs(poverty[i] - poverty[j]) / wC )
W[i][j] *= s
f1 = np.dot(W, Y)
r = np.transpose( np.hstack( (Y, f1) ) )
pcc1 = np.corrcoef(r)
f2 = np.dot(W2, Y)
r = np.transpose( np.hstack( (Y, f2) ) )
pcc2 = np.corrcoef(r)
print '{0}: social lag {1}, spatial lag {2}'.format(region, pcc1[0,1], pcc2[0,1])
def line_socialflow_crime():
W = generate_transition_SocialLag(region='ca')
C = generate_corina_features()
poverty = C[1][:,2]
for i in range(W.shape[0]):
for j in range (W.shape[1]):
W[i][j] *= np.exp( - np.abs(poverty[i] - poverty[j]) / 32 )
Y = retrieve_crime_count(2010, col=['total'], region='ca')
h, D = generate_corina_features(region='ca')
popul = D[:,0].reshape(D.shape[0],1)
Y = np.divide(Y, popul) * 10000
f1 = np.dot(W, Y)
plt.scatter(f1, Y)
plt.xlabel('Social lag weighted by demographic similarity')
plt.ylabel('crime rate')
def line_spatialflow_crime():
W = generate_geographical_SpatialLag_ca()
Y = retrieve_crime_count(2010, col=['total'], region='ca')
h, D = generate_corina_features(region='ca')
popul = D[:,0].reshape(D.shape[0],1)
Y = np.divide(Y, popul) * 10000
f1 = np.dot(W, Y)
plt.figure()
plt.scatter(f1, Y)
plt.axis([0,700000, 0, 6000])
idx = [31, 75, 37]
sf1 = f1[idx]
sY = Y[idx]
plt.scatter(sf1, sY, edgecolors='red', s=50, linewidths=2 )
plt.figtext(0.43, 0.78, '#32', fontsize='large')
plt.figtext(0.15, 0.37, '#76', fontsize='large')
plt.figtext(0.79, 0.33, '#38', fontsize='large')
plt.xlabel('Geographical influence feature value', fontsize='x-large')
plt.ylabel('Crime rate', fontsize='x-large')
plt.savefig('spatial-crime-rate.pdf', format='pdf')
return Y
from taxiFlow import getTaxiFlow
def line_taxiflow_crime():
s = getTaxiFlow(normalization='bydestination')
Y = retrieve_crime_count(2010, col=['total'], region='ca')
h, D = generate_corina_features(region='ca')
popul = D[:,0].reshape(D.shape[0],1)
Y = np.divide(Y, popul) * 10000
f1 = np.dot(s, Y)
plt.figure()
plt.scatter(f1, Y)
plt.axis([0, 6000, 0, 6000])
idx = [31, 46]
sf1 = f1[idx]
sY = Y[idx]
plt.scatter(sf1, sY, edgecolors='red', s=50, linewidths=2 )
plt.figtext(0.33, 0.8, '#32', fontsize='large')
plt.figtext(0.75, 0.34, '#47', fontsize='large')
plt.xlabel('Hyperlink by taxi flow feature value', fontsize='x-large')
plt.ylabel('Crime rate', fontsize='x-large')
plt.savefig('taxi-flow-percent.pdf', format='pdf')
return f1
def correlation_taxiflow_crime(flowPercentage=True, crimeRate=True):
"""
correlation between taxi flow and crime
"""
s = getTaxiFlow(usePercentage=flowPercentage)
Y = retrieve_crime_count(2010, region='ca')
if crimeRate:
h, D = generate_corina_features(region='ca')
popul = D[:,0].reshape(D.shape[0],1)
Y = np.divide(Y, popul) * 10000
f1 = np.dot(s, Y)
r = np.hstack( (f1, Y) )
r = np.transpose(r)
pcc = np.corrcoef(r)
print pcc
if __name__ == '__main__':
# correlation_POIdist_crime()
# correlation_POI_crime('ca')
# r = line_taxiflow_crime()
# line_POI_crime()
# line_socialflow_crime()
# r = line_spatialflow_crime()
# correlation_socialflow_crime(region='ca', useRate=True, weightSocialFlow=True)
r = correlation_demo_crime()
# correlation_taxiflow_crime(flowPercentage=True, crimeRate=True)
|
|
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# 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.
import contextlib
import mock
from oslo_serialization import jsonutils
from oslo_utils import units
from oslo_utils import uuidutils
from oslo_vmware import exceptions as vexc
from oslo_vmware.objects import datastore as ds_obj
from oslo_vmware import vim_util as vutil
import six
from nova.compute import power_state
from nova import context
from nova import exception
from nova.network import model as network_model
from nova import objects
from nova import test
from nova.tests.unit import fake_flavor
from nova.tests.unit import fake_instance
import nova.tests.unit.image.fake
from nova.tests.unit.virt.vmwareapi import fake as vmwareapi_fake
from nova.tests.unit.virt.vmwareapi import stubs
from nova import utils
from nova import version
from nova.virt import hardware
from nova.virt.vmwareapi import constants
from nova.virt.vmwareapi import driver
from nova.virt.vmwareapi import ds_util
from nova.virt.vmwareapi import images
from nova.virt.vmwareapi import vif
from nova.virt.vmwareapi import vim_util
from nova.virt.vmwareapi import vm_util
from nova.virt.vmwareapi import vmops
class DsPathMatcher(object):
def __init__(self, expected_ds_path_str):
self.expected_ds_path_str = expected_ds_path_str
def __eq__(self, ds_path_param):
return str(ds_path_param) == self.expected_ds_path_str
class VMwareVMOpsTestCase(test.NoDBTestCase):
def setUp(self):
super(VMwareVMOpsTestCase, self).setUp()
vmwareapi_fake.reset()
stubs.set_stubs(self.stubs)
self.flags(enabled=True, group='vnc')
self.flags(image_cache_subdirectory_name='vmware_base',
my_ip='',
flat_injected=True)
self._context = context.RequestContext('fake_user', 'fake_project')
self._session = driver.VMwareAPISession()
self._virtapi = mock.Mock()
self._image_id = nova.tests.unit.image.fake.get_valid_image_id()
fake_ds_ref = vmwareapi_fake.ManagedObjectReference('fake-ds')
self._ds = ds_obj.Datastore(
ref=fake_ds_ref, name='fake_ds',
capacity=10 * units.Gi,
freespace=10 * units.Gi)
self._dc_info = vmops.DcInfo(
ref='fake_dc_ref', name='fake_dc',
vmFolder='fake_vm_folder')
cluster = vmwareapi_fake.create_cluster('fake_cluster', fake_ds_ref)
self._instance_values = {
'display_name': 'fake_display_name',
'name': 'fake_name',
'uuid': 'fake_uuid',
'vcpus': 1,
'memory_mb': 512,
'image_ref': self._image_id,
'root_gb': 10,
'node': '%s(%s)' % (cluster.mo_id, cluster.name),
'expected_attrs': ['system_metadata'],
}
self._instance = fake_instance.fake_instance_obj(
self._context, **self._instance_values)
self._flavor = objects.Flavor(name='m1.small', memory_mb=512, vcpus=1,
root_gb=10, ephemeral_gb=0, swap=0,
extra_specs={})
self._instance.flavor = self._flavor
self._vmops = vmops.VMwareVMOps(self._session, self._virtapi, None,
cluster=cluster.obj)
self._cluster = cluster
self._image_meta = objects.ImageMeta.from_dict({})
subnet_4 = network_model.Subnet(cidr='192.168.0.1/24',
dns=[network_model.IP('192.168.0.1')],
gateway=
network_model.IP('192.168.0.1'),
ips=[
network_model.IP('192.168.0.100')],
routes=None)
subnet_6 = network_model.Subnet(cidr='dead:beef::1/64',
dns=None,
gateway=
network_model.IP('dead:beef::1'),
ips=[network_model.IP(
'dead:beef::dcad:beff:feef:0')],
routes=None)
network = network_model.Network(id=0,
bridge='fa0',
label='fake',
subnets=[subnet_4, subnet_6],
vlan=None,
bridge_interface=None,
injected=True)
self._network_values = {
'id': None,
'address': 'DE:AD:BE:EF:00:00',
'network': network,
'type': None,
'devname': None,
'ovs_interfaceid': None,
'rxtx_cap': 3
}
self.network_info = network_model.NetworkInfo([
network_model.VIF(**self._network_values)
])
pure_IPv6_network = network_model.Network(id=0,
bridge='fa0',
label='fake',
subnets=[subnet_6],
vlan=None,
bridge_interface=None,
injected=True)
self.pure_IPv6_network_info = network_model.NetworkInfo([
network_model.VIF(id=None,
address='DE:AD:BE:EF:00:00',
network=pure_IPv6_network,
type=None,
devname=None,
ovs_interfaceid=None,
rxtx_cap=3)
])
self._metadata = (
"name:fake_display_name\n"
"userid:fake_user\n"
"username:None\n"
"projectid:fake_project\n"
"projectname:None\n"
"flavor:name:m1.micro\n"
"flavor:memory_mb:6\n"
"flavor:vcpus:28\n"
"flavor:ephemeral_gb:8128\n"
"flavor:root_gb:496\n"
"flavor:swap:33550336\n"
"imageid:70a599e0-31e7-49b7-b260-868f441e862b\n"
"package:%s\n" % version.version_string_with_package())
def test_get_machine_id_str(self):
result = vmops.VMwareVMOps._get_machine_id_str(self.network_info)
self.assertEqual('DE:AD:BE:EF:00:00;192.168.0.100;255.255.255.0;'
'192.168.0.1;192.168.0.255;192.168.0.1#', result)
result = vmops.VMwareVMOps._get_machine_id_str(
self.pure_IPv6_network_info)
self.assertEqual('DE:AD:BE:EF:00:00;;;;;#', result)
def _setup_create_folder_mocks(self):
ops = vmops.VMwareVMOps(mock.Mock(), mock.Mock(), mock.Mock())
base_name = 'folder'
ds_name = "datastore"
ds_ref = mock.Mock()
ds_ref.value = 1
dc_ref = mock.Mock()
ops._datastore_dc_mapping[ds_ref.value] = vmops.DcInfo(
ref=dc_ref,
name='fake-name',
vmFolder='fake-folder')
path = ds_obj.DatastorePath(ds_name, base_name)
return ds_name, ds_ref, ops, path, dc_ref
@mock.patch.object(ds_util, 'mkdir')
def test_create_folder_if_missing(self, mock_mkdir):
ds_name, ds_ref, ops, path, dc = self._setup_create_folder_mocks()
ops._create_folder_if_missing(ds_name, ds_ref, 'folder')
mock_mkdir.assert_called_with(ops._session, path, dc)
@mock.patch.object(ds_util, 'mkdir')
def test_create_folder_if_missing_exception(self, mock_mkdir):
ds_name, ds_ref, ops, path, dc = self._setup_create_folder_mocks()
ds_util.mkdir.side_effect = vexc.FileAlreadyExistsException()
ops._create_folder_if_missing(ds_name, ds_ref, 'folder')
mock_mkdir.assert_called_with(ops._session, path, dc)
@mock.patch.object(vutil, 'continue_retrieval', return_value=None)
def test_get_valid_vms_from_retrieve_result(self, _mock_cont):
ops = vmops.VMwareVMOps(self._session, mock.Mock(), mock.Mock())
fake_objects = vmwareapi_fake.FakeRetrieveResult()
fake_objects.add_object(vmwareapi_fake.VirtualMachine(
name=uuidutils.generate_uuid()))
fake_objects.add_object(vmwareapi_fake.VirtualMachine(
name=uuidutils.generate_uuid()))
fake_objects.add_object(vmwareapi_fake.VirtualMachine(
name=uuidutils.generate_uuid()))
vms = ops._get_valid_vms_from_retrieve_result(fake_objects)
self.assertEqual(3, len(vms))
@mock.patch.object(vutil, 'continue_retrieval', return_value=None)
def test_get_valid_vms_from_retrieve_result_with_invalid(self,
_mock_cont):
ops = vmops.VMwareVMOps(self._session, mock.Mock(), mock.Mock())
fake_objects = vmwareapi_fake.FakeRetrieveResult()
fake_objects.add_object(vmwareapi_fake.VirtualMachine(
name=uuidutils.generate_uuid()))
invalid_vm1 = vmwareapi_fake.VirtualMachine(
name=uuidutils.generate_uuid())
invalid_vm1.set('runtime.connectionState', 'orphaned')
invalid_vm2 = vmwareapi_fake.VirtualMachine(
name=uuidutils.generate_uuid())
invalid_vm2.set('runtime.connectionState', 'inaccessible')
fake_objects.add_object(invalid_vm1)
fake_objects.add_object(invalid_vm2)
vms = ops._get_valid_vms_from_retrieve_result(fake_objects)
self.assertEqual(1, len(vms))
def test_delete_vm_snapshot(self):
def fake_call_method(module, method, *args, **kwargs):
self.assertEqual('RemoveSnapshot_Task', method)
self.assertEqual('fake_vm_snapshot', args[0])
self.assertFalse(kwargs['removeChildren'])
self.assertTrue(kwargs['consolidate'])
return 'fake_remove_snapshot_task'
with contextlib.nested(
mock.patch.object(self._session, '_wait_for_task'),
mock.patch.object(self._session, '_call_method', fake_call_method)
) as (_wait_for_task, _call_method):
self._vmops._delete_vm_snapshot(self._instance,
"fake_vm_ref", "fake_vm_snapshot")
_wait_for_task.assert_has_calls([
mock.call('fake_remove_snapshot_task')])
def test_create_vm_snapshot(self):
method_list = ['CreateSnapshot_Task', 'get_dynamic_property']
def fake_call_method(module, method, *args, **kwargs):
expected_method = method_list.pop(0)
self.assertEqual(expected_method, method)
if (expected_method == 'CreateSnapshot_Task'):
self.assertEqual('fake_vm_ref', args[0])
self.assertFalse(kwargs['memory'])
self.assertTrue(kwargs['quiesce'])
return 'fake_snapshot_task'
elif (expected_method == 'get_dynamic_property'):
task_info = mock.Mock()
task_info.result = "fake_snapshot_ref"
self.assertEqual(('fake_snapshot_task', 'Task', 'info'), args)
return task_info
with contextlib.nested(
mock.patch.object(self._session, '_wait_for_task'),
mock.patch.object(self._session, '_call_method', fake_call_method)
) as (_wait_for_task, _call_method):
snap = self._vmops._create_vm_snapshot(self._instance,
"fake_vm_ref")
self.assertEqual("fake_snapshot_ref", snap)
_wait_for_task.assert_has_calls([
mock.call('fake_snapshot_task')])
def test_update_instance_progress(self):
with mock.patch.object(self._instance, 'save') as mock_save:
self._vmops._update_instance_progress(self._instance._context,
self._instance, 5, 10)
mock_save.assert_called_once_with()
self.assertEqual(50, self._instance.progress)
@mock.patch.object(vm_util, 'get_vm_ref', return_value='fake_ref')
def test_get_info(self, mock_get_vm_ref):
result = {
'summary.config.numCpu': 4,
'summary.config.memorySizeMB': 128,
'runtime.powerState': 'poweredOn'
}
def mock_call_method(module, method, *args, **kwargs):
if method == 'continue_retrieval':
return
return result
with mock.patch.object(self._session, '_call_method',
mock_call_method):
info = self._vmops.get_info(self._instance)
mock_get_vm_ref.assert_called_once_with(self._session,
self._instance)
expected = hardware.InstanceInfo(state=power_state.RUNNING,
max_mem_kb=128 * 1024,
mem_kb=128 * 1024,
num_cpu=4)
self.assertEqual(expected, info)
@mock.patch.object(vm_util, 'get_vm_ref', return_value='fake_ref')
def test_get_info_when_ds_unavailable(self, mock_get_vm_ref):
result = {
'runtime.powerState': 'poweredOff'
}
def mock_call_method(module, method, *args, **kwargs):
if method == 'continue_retrieval':
return
return result
with mock.patch.object(self._session, '_call_method',
mock_call_method):
info = self._vmops.get_info(self._instance)
mock_get_vm_ref.assert_called_once_with(self._session,
self._instance)
self.assertEqual(hardware.InstanceInfo(state=power_state.SHUTDOWN),
info)
def _test_get_datacenter_ref_and_name(self, ds_ref_exists=False):
instance_ds_ref = mock.Mock()
instance_ds_ref.value = "ds-1"
_vcvmops = vmops.VMwareVMOps(self._session, None, None)
if ds_ref_exists:
ds_ref = mock.Mock()
ds_ref.value = "ds-1"
else:
ds_ref = None
self._continue_retrieval = True
self._fake_object1 = vmwareapi_fake.FakeRetrieveResult()
self._fake_object2 = vmwareapi_fake.FakeRetrieveResult()
def fake_call_method(module, method, *args, **kwargs):
self._fake_object1.add_object(vmwareapi_fake.Datacenter(
ds_ref=ds_ref))
if not ds_ref:
# Token is set for the fake_object1, so it will continue to
# fetch the next object.
setattr(self._fake_object1, 'token', 'token-0')
if self._continue_retrieval:
if self._continue_retrieval:
self._continue_retrieval = False
self._fake_object2.add_object(
vmwareapi_fake.Datacenter())
return self._fake_object2
return
if method == "continue_retrieval":
return
return self._fake_object1
with mock.patch.object(self._session, '_call_method',
side_effect=fake_call_method) as fake_call:
dc_info = _vcvmops.get_datacenter_ref_and_name(instance_ds_ref)
if ds_ref:
self.assertEqual(1, len(_vcvmops._datastore_dc_mapping))
calls = [mock.call(vim_util, "get_objects", "Datacenter",
["name", "datastore", "vmFolder"]),
mock.call(vutil, 'continue_retrieval',
self._fake_object1)]
fake_call.assert_has_calls(calls)
self.assertEqual("ha-datacenter", dc_info.name)
else:
calls = [mock.call(vim_util, "get_objects", "Datacenter",
["name", "datastore", "vmFolder"]),
mock.call(vutil, 'continue_retrieval',
self._fake_object2)]
fake_call.assert_has_calls(calls)
self.assertIsNone(dc_info)
def test_get_datacenter_ref_and_name(self):
self._test_get_datacenter_ref_and_name(ds_ref_exists=True)
def test_get_datacenter_ref_and_name_with_no_datastore(self):
self._test_get_datacenter_ref_and_name()
@mock.patch.object(vm_util, 'power_off_instance')
@mock.patch.object(ds_util, 'disk_copy')
@mock.patch.object(vm_util, 'get_vm_ref', return_value='fake-ref')
@mock.patch.object(vm_util, 'find_rescue_device')
@mock.patch.object(vm_util, 'get_vm_boot_spec')
@mock.patch.object(vm_util, 'reconfigure_vm')
@mock.patch.object(vm_util, 'power_on_instance')
@mock.patch.object(ds_obj, 'get_datastore_by_ref')
def test_rescue(self, mock_get_ds_by_ref, mock_power_on, mock_reconfigure,
mock_get_boot_spec, mock_find_rescue,
mock_get_vm_ref, mock_disk_copy,
mock_power_off):
_volumeops = mock.Mock()
self._vmops._volumeops = _volumeops
ds = ds_obj.Datastore('fake-ref', 'ds1')
mock_get_ds_by_ref.return_value = ds
mock_find_rescue.return_value = 'fake-rescue-device'
mock_get_boot_spec.return_value = 'fake-boot-spec'
device = vmwareapi_fake.DataObject()
backing = vmwareapi_fake.DataObject()
backing.datastore = ds.ref
device.backing = backing
vmdk = vm_util.VmdkInfo('[fake] uuid/root.vmdk',
'fake-adapter',
'fake-disk',
'fake-capacity',
device)
with contextlib.nested(
mock.patch.object(self._vmops, 'get_datacenter_ref_and_name'),
mock.patch.object(vm_util, 'get_vmdk_info',
return_value=vmdk)
) as (_get_dc_ref_and_name, fake_vmdk_info):
dc_info = mock.Mock()
_get_dc_ref_and_name.return_value = dc_info
self._vmops.rescue(
self._context, self._instance, None, self._image_meta)
mock_power_off.assert_called_once_with(self._session,
self._instance,
'fake-ref')
uuid = self._instance.image_ref
cache_path = ds.build_path('vmware_base', uuid, uuid + '.vmdk')
rescue_path = ds.build_path('fake_uuid', uuid + '-rescue.vmdk')
mock_disk_copy.assert_called_once_with(self._session, dc_info.ref,
cache_path, rescue_path)
_volumeops.attach_disk_to_vm.assert_called_once_with('fake-ref',
self._instance, mock.ANY, mock.ANY, rescue_path)
mock_get_boot_spec.assert_called_once_with(mock.ANY,
'fake-rescue-device')
mock_reconfigure.assert_called_once_with(self._session,
'fake-ref',
'fake-boot-spec')
mock_power_on.assert_called_once_with(self._session,
self._instance,
vm_ref='fake-ref')
def test_unrescue_power_on(self):
self._test_unrescue(True)
def test_unrescue_power_off(self):
self._test_unrescue(False)
def _test_unrescue(self, power_on):
_volumeops = mock.Mock()
self._vmops._volumeops = _volumeops
vm_ref = mock.Mock()
def fake_call_method(module, method, *args, **kwargs):
expected_args = (vm_ref, 'VirtualMachine',
'config.hardware.device')
self.assertEqual('get_dynamic_property', method)
self.assertEqual(expected_args, args)
with contextlib.nested(
mock.patch.object(vm_util, 'power_on_instance'),
mock.patch.object(vm_util, 'find_rescue_device'),
mock.patch.object(vm_util, 'get_vm_ref', return_value=vm_ref),
mock.patch.object(self._session, '_call_method',
fake_call_method),
mock.patch.object(vm_util, 'power_off_instance')
) as (_power_on_instance, _find_rescue, _get_vm_ref,
_call_method, _power_off):
self._vmops.unrescue(self._instance, power_on=power_on)
if power_on:
_power_on_instance.assert_called_once_with(self._session,
self._instance, vm_ref=vm_ref)
else:
self.assertFalse(_power_on_instance.called)
_get_vm_ref.assert_called_once_with(self._session,
self._instance)
_power_off.assert_called_once_with(self._session, self._instance,
vm_ref)
_volumeops.detach_disk_from_vm.assert_called_once_with(
vm_ref, self._instance, mock.ANY, destroy_disk=True)
def _test_finish_migration(self, power_on=True, resize_instance=False):
with contextlib.nested(
mock.patch.object(self._vmops,
'_resize_create_ephemerals_and_swap'),
mock.patch.object(self._vmops, "_update_instance_progress"),
mock.patch.object(vm_util, "power_on_instance"),
mock.patch.object(vm_util, "get_vm_ref",
return_value='fake-ref')
) as (fake_resize_create_ephemerals_and_swap,
fake_update_instance_progress, fake_power_on, fake_get_vm_ref):
self._vmops.finish_migration(context=self._context,
migration=None,
instance=self._instance,
disk_info=None,
network_info=None,
block_device_info=None,
resize_instance=resize_instance,
image_meta=None,
power_on=power_on)
fake_resize_create_ephemerals_and_swap.called_once_with(
'fake-ref', self._instance, None)
if power_on:
fake_power_on.assert_called_once_with(self._session,
self._instance,
vm_ref='fake-ref')
else:
self.assertFalse(fake_power_on.called)
calls = [
mock.call(self._context, self._instance, step=5,
total_steps=vmops.RESIZE_TOTAL_STEPS),
mock.call(self._context, self._instance, step=6,
total_steps=vmops.RESIZE_TOTAL_STEPS)]
fake_update_instance_progress.assert_has_calls(calls)
def test_finish_migration_power_on(self):
self._test_finish_migration(power_on=True, resize_instance=False)
def test_finish_migration_power_off(self):
self._test_finish_migration(power_on=False, resize_instance=False)
def test_finish_migration_power_on_resize(self):
self._test_finish_migration(power_on=True, resize_instance=True)
@mock.patch.object(vmops.VMwareVMOps, '_get_extra_specs')
@mock.patch.object(vmops.VMwareVMOps, '_resize_create_ephemerals_and_swap')
@mock.patch.object(vmops.VMwareVMOps, '_remove_ephemerals_and_swap')
@mock.patch.object(ds_util, 'disk_delete')
@mock.patch.object(ds_util, 'disk_move')
@mock.patch.object(ds_util, 'file_exists',
return_value=True)
@mock.patch.object(vmops.VMwareVMOps, '_get_ds_browser',
return_value='fake-browser')
@mock.patch.object(vm_util, 'reconfigure_vm')
@mock.patch.object(vm_util, 'get_vm_resize_spec',
return_value='fake-spec')
@mock.patch.object(vm_util, 'power_off_instance')
@mock.patch.object(vm_util, 'get_vm_ref', return_value='fake-ref')
@mock.patch.object(vm_util, 'power_on_instance')
def _test_finish_revert_migration(self, fake_power_on,
fake_get_vm_ref, fake_power_off,
fake_resize_spec, fake_reconfigure_vm,
fake_get_browser,
fake_original_exists, fake_disk_move,
fake_disk_delete,
fake_remove_ephemerals_and_swap,
fake_resize_create_ephemerals_and_swap,
fake_get_extra_specs,
power_on):
"""Tests the finish_revert_migration method on vmops."""
datastore = ds_obj.Datastore(ref='fake-ref', name='fake')
device = vmwareapi_fake.DataObject()
backing = vmwareapi_fake.DataObject()
backing.datastore = datastore.ref
device.backing = backing
vmdk = vm_util.VmdkInfo('[fake] uuid/root.vmdk',
'fake-adapter',
'fake-disk',
'fake-capacity',
device)
dc_info = vmops.DcInfo(ref='fake_ref', name='fake',
vmFolder='fake_folder')
extra_specs = vm_util.ExtraSpecs()
fake_get_extra_specs.return_value = extra_specs
with contextlib.nested(
mock.patch.object(self._vmops, 'get_datacenter_ref_and_name',
return_value=dc_info),
mock.patch.object(vm_util, 'get_vmdk_info',
return_value=vmdk)
) as (fake_get_dc_ref_and_name, fake_get_vmdk_info):
self._vmops._volumeops = mock.Mock()
mock_attach_disk = self._vmops._volumeops.attach_disk_to_vm
mock_detach_disk = self._vmops._volumeops.detach_disk_from_vm
self._vmops.finish_revert_migration(self._context,
instance=self._instance,
network_info=None,
block_device_info=None,
power_on=power_on)
fake_get_vm_ref.assert_called_once_with(self._session,
self._instance)
fake_power_off.assert_called_once_with(self._session,
self._instance,
'fake-ref')
# Validate VM reconfiguration
metadata = ('name:fake_display_name\n'
'userid:fake_user\n'
'username:None\n'
'projectid:fake_project\n'
'projectname:None\n'
'flavor:name:m1.small\n'
'flavor:memory_mb:512\n'
'flavor:vcpus:1\n'
'flavor:ephemeral_gb:0\n'
'flavor:root_gb:10\n'
'flavor:swap:0\n'
'imageid:70a599e0-31e7-49b7-b260-868f441e862b\n'
'package:%s\n' % version.version_string_with_package())
fake_resize_spec.assert_called_once_with(
self._session.vim.client.factory,
int(self._instance.vcpus),
int(self._instance.memory_mb),
extra_specs,
metadata=metadata)
fake_reconfigure_vm.assert_called_once_with(self._session,
'fake-ref',
'fake-spec')
# Validate disk configuration
fake_get_vmdk_info.assert_called_once_with(
self._session, 'fake-ref', uuid=self._instance.uuid)
fake_get_browser.assert_called_once_with('fake-ref')
fake_original_exists.assert_called_once_with(
self._session, 'fake-browser',
ds_obj.DatastorePath(datastore.name, 'uuid'),
'original.vmdk')
mock_detach_disk.assert_called_once_with('fake-ref',
self._instance,
device)
fake_disk_delete.assert_called_once_with(
self._session, dc_info.ref, '[fake] uuid/root.vmdk')
fake_disk_move.assert_called_once_with(
self._session, dc_info.ref,
'[fake] uuid/original.vmdk',
'[fake] uuid/root.vmdk')
mock_attach_disk.assert_called_once_with(
'fake-ref', self._instance, 'fake-adapter', 'fake-disk',
'[fake] uuid/root.vmdk')
fake_remove_ephemerals_and_swap.called_once_with('fake-ref')
fake_resize_create_ephemerals_and_swap.called_once_with(
'fake-ref', self._instance, None)
if power_on:
fake_power_on.assert_called_once_with(self._session,
self._instance)
else:
self.assertFalse(fake_power_on.called)
def test_finish_revert_migration_power_on(self):
self._test_finish_revert_migration(power_on=True)
def test_finish_revert_migration_power_off(self):
self._test_finish_revert_migration(power_on=False)
@mock.patch.object(vmops.VMwareVMOps, '_get_instance_metadata')
@mock.patch.object(vmops.VMwareVMOps, '_get_extra_specs')
@mock.patch.object(vm_util, 'reconfigure_vm')
@mock.patch.object(vm_util, 'get_vm_resize_spec',
return_value='fake-spec')
def test_resize_vm(self, fake_resize_spec, fake_reconfigure,
fake_get_extra_specs, fake_get_metadata):
extra_specs = vm_util.ExtraSpecs()
fake_get_extra_specs.return_value = extra_specs
fake_get_metadata.return_value = self._metadata
flavor = objects.Flavor(name='m1.small',
memory_mb=1024,
vcpus=2,
extra_specs={})
self._vmops._resize_vm(self._context, self._instance, 'vm-ref', flavor,
None)
fake_resize_spec.assert_called_once_with(
self._session.vim.client.factory, 2, 1024, extra_specs,
metadata=self._metadata)
fake_reconfigure.assert_called_once_with(self._session,
'vm-ref', 'fake-spec')
@mock.patch.object(vmops.VMwareVMOps, '_extend_virtual_disk')
@mock.patch.object(ds_util, 'disk_move')
@mock.patch.object(ds_util, 'disk_copy')
def test_resize_disk(self, fake_disk_copy, fake_disk_move,
fake_extend):
datastore = ds_obj.Datastore(ref='fake-ref', name='fake')
device = vmwareapi_fake.DataObject()
backing = vmwareapi_fake.DataObject()
backing.datastore = datastore.ref
device.backing = backing
vmdk = vm_util.VmdkInfo('[fake] uuid/root.vmdk',
'fake-adapter',
'fake-disk',
self._instance.root_gb * units.Gi,
device)
dc_info = vmops.DcInfo(ref='fake_ref', name='fake',
vmFolder='fake_folder')
with mock.patch.object(self._vmops, 'get_datacenter_ref_and_name',
return_value=dc_info) as fake_get_dc_ref_and_name:
self._vmops._volumeops = mock.Mock()
mock_attach_disk = self._vmops._volumeops.attach_disk_to_vm
mock_detach_disk = self._vmops._volumeops.detach_disk_from_vm
flavor = fake_flavor.fake_flavor_obj(self._context,
root_gb=self._instance.root_gb + 1)
self._vmops._resize_disk(self._instance, 'fake-ref', vmdk, flavor)
fake_get_dc_ref_and_name.assert_called_once_with(datastore.ref)
fake_disk_copy.assert_called_once_with(
self._session, dc_info.ref, '[fake] uuid/root.vmdk',
'[fake] uuid/resized.vmdk')
mock_detach_disk.assert_called_once_with('fake-ref',
self._instance,
device)
fake_extend.assert_called_once_with(
self._instance, flavor['root_gb'] * units.Mi,
'[fake] uuid/resized.vmdk', dc_info.ref)
calls = [
mock.call(self._session, dc_info.ref,
'[fake] uuid/root.vmdk',
'[fake] uuid/original.vmdk'),
mock.call(self._session, dc_info.ref,
'[fake] uuid/resized.vmdk',
'[fake] uuid/root.vmdk')]
fake_disk_move.assert_has_calls(calls)
mock_attach_disk.assert_called_once_with(
'fake-ref', self._instance, 'fake-adapter', 'fake-disk',
'[fake] uuid/root.vmdk')
@mock.patch.object(vm_util, 'detach_devices_from_vm')
@mock.patch.object(vm_util, 'get_swap')
@mock.patch.object(vm_util, 'get_ephemerals')
def test_remove_ephemerals_and_swap(self, get_ephemerals, get_swap,
detach_devices):
get_ephemerals.return_value = [mock.sentinel.ephemeral0,
mock.sentinel.ephemeral1]
get_swap.return_value = mock.sentinel.swap
devices = [mock.sentinel.ephemeral0, mock.sentinel.ephemeral1,
mock.sentinel.swap]
self._vmops._remove_ephemerals_and_swap(mock.sentinel.vm_ref)
detach_devices.assert_called_once_with(self._vmops._session,
mock.sentinel.vm_ref, devices)
@mock.patch.object(ds_util, 'disk_delete')
@mock.patch.object(ds_util, 'file_exists',
return_value=True)
@mock.patch.object(vmops.VMwareVMOps, '_get_ds_browser',
return_value='fake-browser')
@mock.patch.object(vm_util, 'get_vm_ref', return_value='fake-ref')
def test_confirm_migration(self, fake_get_vm_ref, fake_get_browser,
fake_original_exists,
fake_disk_delete):
"""Tests the confirm_migration method on vmops."""
datastore = ds_obj.Datastore(ref='fake-ref', name='fake')
device = vmwareapi_fake.DataObject()
backing = vmwareapi_fake.DataObject()
backing.datastore = datastore.ref
device.backing = backing
vmdk = vm_util.VmdkInfo('[fake] uuid/root.vmdk',
'fake-adapter',
'fake-disk',
'fake-capacity',
device)
dc_info = vmops.DcInfo(ref='fake_ref', name='fake',
vmFolder='fake_folder')
with contextlib.nested(
mock.patch.object(self._vmops, 'get_datacenter_ref_and_name',
return_value=dc_info),
mock.patch.object(vm_util, 'get_vmdk_info',
return_value=vmdk)
) as (fake_get_dc_ref_and_name, fake_get_vmdk_info):
self._vmops.confirm_migration(None,
self._instance,
None)
fake_get_vm_ref.assert_called_once_with(self._session,
self._instance)
fake_get_vmdk_info.assert_called_once_with(
self._session, 'fake-ref', uuid=self._instance.uuid)
fake_get_browser.assert_called_once_with('fake-ref')
fake_original_exists.assert_called_once_with(
self._session, 'fake-browser',
ds_obj.DatastorePath(datastore.name, 'uuid'),
'original.vmdk')
fake_disk_delete.assert_called_once_with(
self._session, dc_info.ref, '[fake] uuid/original.vmdk')
def test_migrate_disk_and_power_off(self):
self._test_migrate_disk_and_power_off(
flavor_root_gb=self._instance.root_gb + 1)
def test_migrate_disk_and_power_off_zero_disk_flavor(self):
self._instance.root_gb = 0
self._test_migrate_disk_and_power_off(flavor_root_gb=0)
def test_migrate_disk_and_power_off_disk_shrink(self):
self.assertRaises(exception.InstanceFaultRollback,
self._test_migrate_disk_and_power_off,
flavor_root_gb=self._instance.root_gb - 1)
@mock.patch.object(vmops.VMwareVMOps, "_remove_ephemerals_and_swap")
@mock.patch.object(vm_util, 'get_vmdk_info')
@mock.patch.object(vmops.VMwareVMOps, "_resize_disk")
@mock.patch.object(vmops.VMwareVMOps, "_resize_vm")
@mock.patch.object(vm_util, 'power_off_instance')
@mock.patch.object(vmops.VMwareVMOps, "_update_instance_progress")
@mock.patch.object(vm_util, 'get_vm_ref', return_value='fake-ref')
def _test_migrate_disk_and_power_off(self, fake_get_vm_ref, fake_progress,
fake_power_off, fake_resize_vm,
fake_resize_disk, fake_get_vmdk_info,
fake_remove_ephemerals_and_swap,
flavor_root_gb):
vmdk = vm_util.VmdkInfo('[fake] uuid/root.vmdk',
'fake-adapter',
'fake-disk',
self._instance.root_gb * units.Gi,
'fake-device')
fake_get_vmdk_info.return_value = vmdk
flavor = fake_flavor.fake_flavor_obj(self._context,
root_gb=flavor_root_gb)
self._vmops.migrate_disk_and_power_off(self._context,
self._instance,
None,
flavor)
fake_get_vm_ref.assert_called_once_with(self._session,
self._instance)
fake_power_off.assert_called_once_with(self._session,
self._instance,
'fake-ref')
fake_resize_vm.assert_called_once_with(self._context, self._instance,
'fake-ref', flavor, mock.ANY)
fake_resize_disk.assert_called_once_with(self._instance, 'fake-ref',
vmdk, flavor)
calls = [mock.call(self._context, self._instance, step=i,
total_steps=vmops.RESIZE_TOTAL_STEPS)
for i in range(4)]
fake_progress.assert_has_calls(calls)
@mock.patch.object(vmops.VMwareVMOps, '_attach_cdrom_to_vm')
@mock.patch.object(vmops.VMwareVMOps, '_create_config_drive')
def test_configure_config_drive(self,
mock_create_config_drive,
mock_attach_cdrom_to_vm):
injected_files = mock.Mock()
admin_password = mock.Mock()
vm_ref = mock.Mock()
mock_create_config_drive.return_value = "fake_iso_path"
self._vmops._configure_config_drive(
self._instance, vm_ref, self._dc_info, self._ds,
injected_files, admin_password)
upload_iso_path = self._ds.build_path("fake_iso_path")
mock_create_config_drive.assert_called_once_with(self._instance,
injected_files, admin_password, self._ds.name,
self._dc_info.name, self._instance.uuid, "Fake-CookieJar")
mock_attach_cdrom_to_vm.assert_called_once_with(
vm_ref, self._instance, self._ds.ref, str(upload_iso_path))
@mock.patch.object(vmops.LOG, 'debug')
@mock.patch.object(vmops.VMwareVMOps, '_fetch_image_if_missing')
@mock.patch.object(vmops.VMwareVMOps, '_get_vm_config_info')
@mock.patch.object(vmops.VMwareVMOps, 'build_virtual_machine')
@mock.patch.object(vmops.lockutils, 'lock')
def test_spawn_mask_block_device_info_password(self, mock_lock,
mock_build_virtual_machine, mock_get_vm_config_info,
mock_fetch_image_if_missing, mock_debug):
# Very simple test that just ensures block_device_info auth_password
# is masked when logged; the rest of the test just fails out early.
data = {'auth_password': 'scrubme'}
bdm = [{'boot_index': 0, 'disk_bus': constants.DEFAULT_ADAPTER_TYPE,
'connection_info': {'data': data}}]
bdi = {'block_device_mapping': bdm}
self.password_logged = False
# Tests that the parameters to the to_xml method are sanitized for
# passwords when logged.
def fake_debug(*args, **kwargs):
if 'auth_password' in args[0]:
self.password_logged = True
self.assertNotIn('scrubme', args[0])
mock_debug.side_effect = fake_debug
self.flags(flat_injected=False)
self.flags(enabled=False, group='vnc')
# Call spawn(). We don't care what it does as long as it generates
# the log message, which we check below.
with mock.patch.object(self._vmops, '_volumeops') as mock_vo:
mock_vo.attach_root_volume.side_effect = test.TestingException
try:
self._vmops.spawn(
self._context, self._instance, self._image_meta,
injected_files=None, admin_password=None,
network_info=[], block_device_info=bdi
)
except test.TestingException:
pass
# Check that the relevant log message was generated, and therefore
# that we checked it was scrubbed
self.assertTrue(self.password_logged)
def _get_metadata(self, is_image_used=True):
if is_image_used:
image_id = '70a599e0-31e7-49b7-b260-868f441e862b'
else:
image_id = None
return ("name:fake_display_name\n"
"userid:fake_user\n"
"username:None\n"
"projectid:fake_project\n"
"projectname:None\n"
"flavor:name:m1.small\n"
"flavor:memory_mb:512\n"
"flavor:vcpus:1\n"
"flavor:ephemeral_gb:0\n"
"flavor:root_gb:10\n"
"flavor:swap:0\n"
"imageid:%(image_id)s\n"
"package:%(version)s\n" % {
'image_id': image_id,
'version': version.version_string_with_package()})
@mock.patch('nova.virt.vmwareapi.vm_util.power_on_instance')
@mock.patch.object(vmops.VMwareVMOps, '_use_disk_image_as_linked_clone')
@mock.patch.object(vmops.VMwareVMOps, '_fetch_image_if_missing')
@mock.patch(
'nova.virt.vmwareapi.imagecache.ImageCacheManager.enlist_image')
@mock.patch.object(vmops.VMwareVMOps, 'build_virtual_machine')
@mock.patch.object(vmops.VMwareVMOps, '_get_vm_config_info')
@mock.patch.object(vmops.VMwareVMOps, '_get_extra_specs')
@mock.patch.object(nova.virt.vmwareapi.images.VMwareImage,
'from_image')
def test_spawn_non_root_block_device(self, from_image,
get_extra_specs,
get_vm_config_info,
build_virtual_machine,
enlist_image, fetch_image,
use_disk_image,
power_on_instance):
self._instance.flavor = self._flavor
extra_specs = get_extra_specs.return_value
connection_info1 = {'data': 'fake-data1', 'serial': 'volume-fake-id1'}
connection_info2 = {'data': 'fake-data2', 'serial': 'volume-fake-id2'}
bdm = [{'connection_info': connection_info1,
'disk_bus': constants.ADAPTER_TYPE_IDE,
'mount_device': '/dev/sdb'},
{'connection_info': connection_info2,
'disk_bus': constants.DEFAULT_ADAPTER_TYPE,
'mount_device': '/dev/sdc'}]
bdi = {'block_device_mapping': bdm, 'root_device_name': '/dev/sda'}
self.flags(flat_injected=False)
self.flags(enabled=False, group='vnc')
image_size = (self._instance.root_gb) * units.Gi / 2
image_info = images.VMwareImage(
image_id=self._image_id,
file_size=image_size)
vi = get_vm_config_info.return_value
from_image.return_value = image_info
build_virtual_machine.return_value = 'fake-vm-ref'
with mock.patch.object(self._vmops, '_volumeops') as volumeops:
self._vmops.spawn(self._context, self._instance, self._image_meta,
injected_files=None, admin_password=None,
network_info=[], block_device_info=bdi)
from_image.assert_called_once_with(self._instance.image_ref,
self._image_meta)
get_vm_config_info.assert_called_once_with(self._instance,
image_info, extra_specs)
build_virtual_machine.assert_called_once_with(self._instance,
image_info, vi.dc_info, vi.datastore, [],
extra_specs, self._get_metadata())
enlist_image.assert_called_once_with(image_info.image_id,
vi.datastore, vi.dc_info.ref)
fetch_image.assert_called_once_with(self._context, vi)
use_disk_image.assert_called_once_with('fake-vm-ref', vi)
volumeops.attach_volume.assert_any_call(
connection_info1, self._instance, constants.ADAPTER_TYPE_IDE)
volumeops.attach_volume.assert_any_call(
connection_info2, self._instance,
constants.DEFAULT_ADAPTER_TYPE)
@mock.patch('nova.virt.vmwareapi.vm_util.power_on_instance')
@mock.patch.object(vmops.VMwareVMOps, 'build_virtual_machine')
@mock.patch.object(vmops.VMwareVMOps, '_get_vm_config_info')
@mock.patch.object(vmops.VMwareVMOps, '_get_extra_specs')
@mock.patch.object(nova.virt.vmwareapi.images.VMwareImage,
'from_image')
def test_spawn_with_no_image_and_block_devices(self, from_image,
get_extra_specs,
get_vm_config_info,
build_virtual_machine,
power_on_instance):
self._instance.image_ref = None
self._instance.flavor = self._flavor
extra_specs = get_extra_specs.return_value
connection_info1 = {'data': 'fake-data1', 'serial': 'volume-fake-id1'}
connection_info2 = {'data': 'fake-data2', 'serial': 'volume-fake-id2'}
connection_info3 = {'data': 'fake-data3', 'serial': 'volume-fake-id3'}
bdm = [{'boot_index': 0,
'connection_info': connection_info1,
'disk_bus': constants.ADAPTER_TYPE_IDE},
{'boot_index': 1,
'connection_info': connection_info2,
'disk_bus': constants.DEFAULT_ADAPTER_TYPE},
{'boot_index': 2,
'connection_info': connection_info3,
'disk_bus': constants.ADAPTER_TYPE_LSILOGICSAS}]
bdi = {'block_device_mapping': bdm}
self.flags(flat_injected=False)
self.flags(enabled=False, group='vnc')
image_info = mock.sentinel.image_info
vi = get_vm_config_info.return_value
from_image.return_value = image_info
build_virtual_machine.return_value = 'fake-vm-ref'
with mock.patch.object(self._vmops, '_volumeops') as volumeops:
self._vmops.spawn(self._context, self._instance, self._image_meta,
injected_files=None, admin_password=None,
network_info=[], block_device_info=bdi)
from_image.assert_called_once_with(self._instance.image_ref,
self._image_meta)
get_vm_config_info.assert_called_once_with(self._instance,
image_info, extra_specs)
build_virtual_machine.assert_called_once_with(self._instance,
image_info, vi.dc_info, vi.datastore, [],
extra_specs, self._get_metadata(is_image_used=False))
volumeops.attach_root_volume.assert_called_once_with(
connection_info1, self._instance, vi.datastore.ref,
constants.ADAPTER_TYPE_IDE)
volumeops.attach_volume.assert_any_call(
connection_info2, self._instance,
constants.DEFAULT_ADAPTER_TYPE)
volumeops.attach_volume.assert_any_call(
connection_info3, self._instance,
constants.ADAPTER_TYPE_LSILOGICSAS)
@mock.patch('nova.virt.vmwareapi.vm_util.power_on_instance')
@mock.patch.object(vmops.VMwareVMOps, 'build_virtual_machine')
@mock.patch.object(vmops.VMwareVMOps, '_get_vm_config_info')
@mock.patch.object(vmops.VMwareVMOps, '_get_extra_specs')
@mock.patch.object(nova.virt.vmwareapi.images.VMwareImage,
'from_image')
def test_spawn_unsupported_hardware(self, from_image,
get_extra_specs,
get_vm_config_info,
build_virtual_machine,
power_on_instance):
self._instance.image_ref = None
self._instance.flavor = self._flavor
extra_specs = get_extra_specs.return_value
connection_info = {'data': 'fake-data', 'serial': 'volume-fake-id'}
bdm = [{'boot_index': 0,
'connection_info': connection_info,
'disk_bus': 'invalid_adapter_type'}]
bdi = {'block_device_mapping': bdm}
self.flags(flat_injected=False)
self.flags(enabled=False, group='vnc')
image_info = mock.sentinel.image_info
vi = get_vm_config_info.return_value
from_image.return_value = image_info
build_virtual_machine.return_value = 'fake-vm-ref'
self.assertRaises(exception.UnsupportedHardware, self._vmops.spawn,
self._context, self._instance, self._image_meta,
injected_files=None,
admin_password=None, network_info=[],
block_device_info=bdi)
from_image.assert_called_once_with(self._instance.image_ref,
self._image_meta)
get_vm_config_info.assert_called_once_with(
self._instance, image_info, extra_specs)
build_virtual_machine.assert_called_once_with(self._instance,
image_info, vi.dc_info, vi.datastore, [],
extra_specs, self._get_metadata(is_image_used=False))
def test_get_ds_browser(self):
cache = self._vmops._datastore_browser_mapping
ds_browser = mock.Mock()
moref = vmwareapi_fake.ManagedObjectReference('datastore-100')
self.assertIsNone(cache.get(moref.value))
mock_call_method = mock.Mock(return_value=ds_browser)
with mock.patch.object(self._session, '_call_method',
mock_call_method):
ret = self._vmops._get_ds_browser(moref)
mock_call_method.assert_called_once_with(vim_util,
'get_dynamic_property', moref, 'Datastore', 'browser')
self.assertIs(ds_browser, ret)
self.assertIs(ds_browser, cache.get(moref.value))
@mock.patch.object(
vmops.VMwareVMOps, '_sized_image_exists', return_value=False)
@mock.patch.object(vmops.VMwareVMOps, '_extend_virtual_disk')
@mock.patch.object(vm_util, 'copy_virtual_disk')
def _test_use_disk_image_as_linked_clone(self,
mock_copy_virtual_disk,
mock_extend_virtual_disk,
mock_sized_image_exists,
flavor_fits_image=False):
extra_specs = vm_util.ExtraSpecs()
file_size = 10 * units.Gi if flavor_fits_image else 5 * units.Gi
image_info = images.VMwareImage(
image_id=self._image_id,
file_size=file_size,
linked_clone=False)
cache_root_folder = self._ds.build_path("vmware_base", self._image_id)
mock_imagecache = mock.Mock()
mock_imagecache.get_image_cache_folder.return_value = cache_root_folder
vi = vmops.VirtualMachineInstanceConfigInfo(
self._instance, image_info,
self._ds, self._dc_info, mock_imagecache, extra_specs)
sized_cached_image_ds_loc = cache_root_folder.join(
"%s.%s.vmdk" % (self._image_id, vi.root_gb))
self._vmops._volumeops = mock.Mock()
mock_attach_disk_to_vm = self._vmops._volumeops.attach_disk_to_vm
self._vmops._use_disk_image_as_linked_clone("fake_vm_ref", vi)
mock_copy_virtual_disk.assert_called_once_with(
self._session, self._dc_info.ref,
str(vi.cache_image_path),
str(sized_cached_image_ds_loc))
if not flavor_fits_image:
mock_extend_virtual_disk.assert_called_once_with(
self._instance, vi.root_gb * units.Mi,
str(sized_cached_image_ds_loc),
self._dc_info.ref)
mock_attach_disk_to_vm.assert_called_once_with(
"fake_vm_ref", self._instance, vi.ii.adapter_type,
vi.ii.disk_type,
str(sized_cached_image_ds_loc),
vi.root_gb * units.Mi, False,
disk_io_limits=vi._extra_specs.disk_io_limits)
def test_use_disk_image_as_linked_clone(self):
self._test_use_disk_image_as_linked_clone()
def test_use_disk_image_as_linked_clone_flavor_fits_image(self):
self._test_use_disk_image_as_linked_clone(flavor_fits_image=True)
@mock.patch.object(vmops.VMwareVMOps, '_extend_virtual_disk')
@mock.patch.object(vm_util, 'copy_virtual_disk')
def _test_use_disk_image_as_full_clone(self,
mock_copy_virtual_disk,
mock_extend_virtual_disk,
flavor_fits_image=False):
extra_specs = vm_util.ExtraSpecs()
file_size = 10 * units.Gi if flavor_fits_image else 5 * units.Gi
image_info = images.VMwareImage(
image_id=self._image_id,
file_size=file_size,
linked_clone=False)
cache_root_folder = self._ds.build_path("vmware_base", self._image_id)
mock_imagecache = mock.Mock()
mock_imagecache.get_image_cache_folder.return_value = cache_root_folder
vi = vmops.VirtualMachineInstanceConfigInfo(
self._instance, image_info,
self._ds, self._dc_info, mock_imagecache,
extra_specs)
self._vmops._volumeops = mock.Mock()
mock_attach_disk_to_vm = self._vmops._volumeops.attach_disk_to_vm
self._vmops._use_disk_image_as_full_clone("fake_vm_ref", vi)
mock_copy_virtual_disk.assert_called_once_with(
self._session, self._dc_info.ref,
str(vi.cache_image_path),
'[fake_ds] fake_uuid/fake_uuid.vmdk')
if not flavor_fits_image:
mock_extend_virtual_disk.assert_called_once_with(
self._instance, vi.root_gb * units.Mi,
'[fake_ds] fake_uuid/fake_uuid.vmdk', self._dc_info.ref)
mock_attach_disk_to_vm.assert_called_once_with(
"fake_vm_ref", self._instance, vi.ii.adapter_type,
vi.ii.disk_type, '[fake_ds] fake_uuid/fake_uuid.vmdk',
vi.root_gb * units.Mi, False,
disk_io_limits=vi._extra_specs.disk_io_limits)
def test_use_disk_image_as_full_clone(self):
self._test_use_disk_image_as_full_clone()
def test_use_disk_image_as_full_clone_image_too_big(self):
self._test_use_disk_image_as_full_clone(flavor_fits_image=True)
@mock.patch.object(vmops.VMwareVMOps, '_attach_cdrom_to_vm')
@mock.patch.object(vm_util, 'create_virtual_disk')
def _test_use_iso_image(self,
mock_create_virtual_disk,
mock_attach_cdrom,
with_root_disk):
extra_specs = vm_util.ExtraSpecs()
image_info = images.VMwareImage(
image_id=self._image_id,
file_size=10 * units.Mi,
linked_clone=True)
cache_root_folder = self._ds.build_path("vmware_base", self._image_id)
mock_imagecache = mock.Mock()
mock_imagecache.get_image_cache_folder.return_value = cache_root_folder
vi = vmops.VirtualMachineInstanceConfigInfo(
self._instance, image_info,
self._ds, self._dc_info, mock_imagecache, extra_specs)
self._vmops._volumeops = mock.Mock()
mock_attach_disk_to_vm = self._vmops._volumeops.attach_disk_to_vm
self._vmops._use_iso_image("fake_vm_ref", vi)
mock_attach_cdrom.assert_called_once_with(
"fake_vm_ref", self._instance, self._ds.ref,
str(vi.cache_image_path))
if with_root_disk:
mock_create_virtual_disk.assert_called_once_with(
self._session, self._dc_info.ref,
vi.ii.adapter_type, vi.ii.disk_type,
'[fake_ds] fake_uuid/fake_uuid.vmdk',
vi.root_gb * units.Mi)
linked_clone = False
mock_attach_disk_to_vm.assert_called_once_with(
"fake_vm_ref", self._instance,
vi.ii.adapter_type, vi.ii.disk_type,
'[fake_ds] fake_uuid/fake_uuid.vmdk',
vi.root_gb * units.Mi, linked_clone,
disk_io_limits=vi._extra_specs.disk_io_limits)
def test_use_iso_image_with_root_disk(self):
self._test_use_iso_image(with_root_disk=True)
def test_use_iso_image_without_root_disk(self):
self._test_use_iso_image(with_root_disk=False)
def _verify_spawn_method_calls(self, mock_call_method, extras=None):
# TODO(vui): More explicit assertions of spawn() behavior
# are waiting on additional refactoring pertaining to image
# handling/manipulation. Till then, we continue to assert on the
# sequence of VIM operations invoked.
expected_methods = ['get_dynamic_property',
'SearchDatastore_Task',
'CreateVirtualDisk_Task',
'DeleteDatastoreFile_Task',
'MoveDatastoreFile_Task',
'DeleteDatastoreFile_Task',
'SearchDatastore_Task',
'ExtendVirtualDisk_Task',
]
if extras:
expected_methods.extend(extras)
recorded_methods = [c[1][1] for c in mock_call_method.mock_calls]
self.assertEqual(expected_methods, recorded_methods)
@mock.patch(
'nova.virt.vmwareapi.vmops.VMwareVMOps._update_vnic_index')
@mock.patch(
'nova.virt.vmwareapi.vmops.VMwareVMOps._configure_config_drive')
@mock.patch('nova.virt.vmwareapi.ds_util.get_datastore')
@mock.patch(
'nova.virt.vmwareapi.vmops.VMwareVMOps.get_datacenter_ref_and_name')
@mock.patch('nova.virt.vmwareapi.vif.get_vif_info',
return_value=[])
@mock.patch('nova.utils.is_neutron',
return_value=False)
@mock.patch('nova.virt.vmwareapi.vm_util.get_vm_create_spec',
return_value='fake_create_spec')
@mock.patch('nova.virt.vmwareapi.vm_util.create_vm',
return_value='fake_vm_ref')
@mock.patch('nova.virt.vmwareapi.ds_util.mkdir')
@mock.patch('nova.virt.vmwareapi.vmops.VMwareVMOps._set_machine_id')
@mock.patch(
'nova.virt.vmwareapi.imagecache.ImageCacheManager.enlist_image')
@mock.patch.object(vmops.VMwareVMOps, '_get_and_set_vnc_config')
@mock.patch('nova.virt.vmwareapi.vm_util.power_on_instance')
@mock.patch('nova.virt.vmwareapi.vm_util.copy_virtual_disk')
# TODO(dims): Need to add tests for create_virtual_disk after the
# disk/image code in spawn gets refactored
def _test_spawn(self,
mock_copy_virtual_disk,
mock_power_on_instance,
mock_get_and_set_vnc_config,
mock_enlist_image,
mock_set_machine_id,
mock_mkdir,
mock_create_vm,
mock_get_create_spec,
mock_is_neutron,
mock_get_vif_info,
mock_get_datacenter_ref_and_name,
mock_get_datastore,
mock_configure_config_drive,
mock_update_vnic_index,
block_device_info=None,
extra_specs=None,
config_drive=False):
if extra_specs is None:
extra_specs = vm_util.ExtraSpecs()
image_size = (self._instance.root_gb) * units.Gi / 2
image = {
'id': self._image_id,
'disk_format': 'vmdk',
'size': image_size,
}
image = objects.ImageMeta.from_dict(image)
image_info = images.VMwareImage(
image_id=self._image_id,
file_size=image_size)
vi = self._vmops._get_vm_config_info(
self._instance, image_info, extra_specs)
self._vmops._volumeops = mock.Mock()
network_info = mock.Mock()
mock_get_datastore.return_value = self._ds
mock_get_datacenter_ref_and_name.return_value = self._dc_info
mock_call_method = mock.Mock(return_value='fake_task')
if extra_specs is None:
extra_specs = vm_util.ExtraSpecs()
with contextlib.nested(
mock.patch.object(self._session, '_wait_for_task'),
mock.patch.object(self._session, '_call_method',
mock_call_method),
mock.patch.object(uuidutils, 'generate_uuid',
return_value='tmp-uuid'),
mock.patch.object(images, 'fetch_image'),
mock.patch.object(self._vmops, '_get_extra_specs',
return_value=extra_specs),
mock.patch.object(self._vmops, '_get_instance_metadata',
return_value='fake-metadata')
) as (_wait_for_task, _call_method, _generate_uuid, _fetch_image,
_get_extra_specs, _get_instance_metadata):
self._vmops.spawn(self._context, self._instance, image,
injected_files='fake_files',
admin_password='password',
network_info=network_info,
block_device_info=block_device_info)
mock_is_neutron.assert_called_once_with()
self.assertEqual(2, mock_mkdir.call_count)
mock_get_vif_info.assert_called_once_with(
self._session, self._cluster.obj, False,
constants.DEFAULT_VIF_MODEL, network_info)
mock_get_create_spec.assert_called_once_with(
self._session.vim.client.factory,
self._instance,
'fake_ds',
[],
extra_specs,
constants.DEFAULT_OS_TYPE,
profile_spec=None,
metadata='fake-metadata')
mock_create_vm.assert_called_once_with(
self._session,
self._instance,
'fake_vm_folder',
'fake_create_spec',
self._cluster.resourcePool)
mock_get_and_set_vnc_config.assert_called_once_with(
self._session.vim.client.factory,
self._instance,
'fake_vm_ref')
mock_set_machine_id.assert_called_once_with(
self._session.vim.client.factory,
self._instance,
network_info,
vm_ref='fake_vm_ref')
mock_power_on_instance.assert_called_once_with(
self._session, self._instance, vm_ref='fake_vm_ref')
if (block_device_info and
'block_device_mapping' in block_device_info):
bdms = block_device_info['block_device_mapping']
for bdm in bdms:
mock_attach_root = (
self._vmops._volumeops.attach_root_volume)
mock_attach = self._vmops._volumeops.attach_volume
adapter_type = bdm.get('disk_bus') or vi.ii.adapter_type
if bdm.get('boot_index') == 0:
mock_attach_root.assert_any_call(
bdm['connection_info'], self._instance,
self._ds.ref, adapter_type)
else:
mock_attach.assert_any_call(
bdm['connection_info'], self._instance,
self._ds.ref, adapter_type)
mock_enlist_image.assert_called_once_with(
self._image_id, self._ds, self._dc_info.ref)
upload_file_name = 'vmware_temp/tmp-uuid/%s/%s-flat.vmdk' % (
self._image_id, self._image_id)
_fetch_image.assert_called_once_with(
self._context,
self._instance,
self._session._host,
self._session._port,
self._dc_info.name,
self._ds.name,
upload_file_name,
cookies='Fake-CookieJar')
self.assertTrue(len(_wait_for_task.mock_calls) > 0)
extras = None
if block_device_info and ('ephemerals' in block_device_info or
'swap' in block_device_info):
extras = ['CreateVirtualDisk_Task']
self._verify_spawn_method_calls(_call_method, extras)
dc_ref = 'fake_dc_ref'
source_file = six.text_type('[fake_ds] vmware_base/%s/%s.vmdk' %
(self._image_id, self._image_id))
dest_file = six.text_type('[fake_ds] vmware_base/%s/%s.%d.vmdk' %
(self._image_id, self._image_id,
self._instance['root_gb']))
# TODO(dims): add more tests for copy_virtual_disk after
# the disk/image code in spawn gets refactored
mock_copy_virtual_disk.assert_called_with(self._session,
dc_ref,
source_file,
dest_file)
if config_drive:
mock_configure_config_drive.assert_called_once_with(
self._instance, 'fake_vm_ref', self._dc_info,
self._ds, 'fake_files', 'password')
mock_update_vnic_index.assert_called_once_with(
self._context, self._instance, network_info)
@mock.patch.object(ds_util, 'get_datastore')
@mock.patch.object(vmops.VMwareVMOps, 'get_datacenter_ref_and_name')
def _test_get_spawn_vm_config_info(self,
mock_get_datacenter_ref_and_name,
mock_get_datastore,
image_size_bytes=0):
image_info = images.VMwareImage(
image_id=self._image_id,
file_size=image_size_bytes,
linked_clone=True)
mock_get_datastore.return_value = self._ds
mock_get_datacenter_ref_and_name.return_value = self._dc_info
extra_specs = vm_util.ExtraSpecs()
vi = self._vmops._get_vm_config_info(self._instance, image_info,
extra_specs)
self.assertEqual(image_info, vi.ii)
self.assertEqual(self._ds, vi.datastore)
self.assertEqual(self._instance.root_gb, vi.root_gb)
self.assertEqual(self._instance, vi.instance)
self.assertEqual(self._instance.uuid, vi.instance.uuid)
self.assertEqual(extra_specs, vi._extra_specs)
cache_image_path = '[%s] vmware_base/%s/%s.vmdk' % (
self._ds.name, self._image_id, self._image_id)
self.assertEqual(cache_image_path, str(vi.cache_image_path))
cache_image_folder = '[%s] vmware_base/%s' % (
self._ds.name, self._image_id)
self.assertEqual(cache_image_folder, str(vi.cache_image_folder))
def test_get_spawn_vm_config_info(self):
image_size = (self._instance.root_gb) * units.Gi / 2
self._test_get_spawn_vm_config_info(image_size_bytes=image_size)
def test_get_spawn_vm_config_info_image_too_big(self):
image_size = (self._instance.root_gb + 1) * units.Gi
self.assertRaises(exception.InstanceUnacceptable,
self._test_get_spawn_vm_config_info,
image_size_bytes=image_size)
def test_spawn(self):
self._test_spawn()
def test_spawn_config_drive_enabled(self):
self.flags(force_config_drive=True)
self._test_spawn(config_drive=True)
def test_spawn_with_block_device_info(self):
block_device_info = {
'block_device_mapping': [{'boot_index': 0,
'connection_info': 'fake',
'mount_device': '/dev/vda'}]
}
self._test_spawn(block_device_info=block_device_info)
def test_spawn_with_block_device_info_with_config_drive(self):
self.flags(force_config_drive=True)
block_device_info = {
'block_device_mapping': [{'boot_index': 0,
'connection_info': 'fake',
'mount_device': '/dev/vda'}]
}
self._test_spawn(block_device_info=block_device_info,
config_drive=True)
def _spawn_with_block_device_info_ephemerals(self, ephemerals):
block_device_info = {'ephemerals': ephemerals}
self._test_spawn(block_device_info=block_device_info)
def test_spawn_with_block_device_info_ephemerals(self):
ephemerals = [{'device_type': 'disk',
'disk_bus': 'virtio',
'device_name': '/dev/vdb',
'size': 1}]
self._spawn_with_block_device_info_ephemerals(ephemerals)
def test_spawn_with_block_device_info_ephemerals_no_disk_bus(self):
ephemerals = [{'device_type': 'disk',
'disk_bus': None,
'device_name': '/dev/vdb',
'size': 1}]
self._spawn_with_block_device_info_ephemerals(ephemerals)
def test_spawn_with_block_device_info_swap(self):
block_device_info = {'swap': {'disk_bus': None,
'swap_size': 512,
'device_name': '/dev/sdb'}}
self._test_spawn(block_device_info=block_device_info)
@mock.patch('nova.virt.vmwareapi.vm_util.power_on_instance')
@mock.patch.object(vmops.VMwareVMOps, '_create_and_attach_thin_disk')
@mock.patch.object(vmops.VMwareVMOps, '_use_disk_image_as_linked_clone')
@mock.patch.object(vmops.VMwareVMOps, '_fetch_image_if_missing')
@mock.patch(
'nova.virt.vmwareapi.imagecache.ImageCacheManager.enlist_image')
@mock.patch.object(vmops.VMwareVMOps, 'build_virtual_machine')
@mock.patch.object(vmops.VMwareVMOps, '_get_vm_config_info')
@mock.patch.object(vmops.VMwareVMOps, '_get_extra_specs')
@mock.patch.object(nova.virt.vmwareapi.images.VMwareImage,
'from_image')
def test_spawn_with_ephemerals_and_swap(self, from_image,
get_extra_specs,
get_vm_config_info,
build_virtual_machine,
enlist_image,
fetch_image,
use_disk_image,
create_and_attach_thin_disk,
power_on_instance):
self._instance.flavor = objects.Flavor(vcpus=1, memory_mb=512,
name="m1.tiny", root_gb=1,
ephemeral_gb=1, swap=512,
extra_specs={})
extra_specs = self._vmops._get_extra_specs(self._instance.flavor)
ephemerals = [{'device_type': 'disk',
'disk_bus': None,
'device_name': '/dev/vdb',
'size': 1},
{'device_type': 'disk',
'disk_bus': None,
'device_name': '/dev/vdc',
'size': 1}]
swap = {'disk_bus': None, 'swap_size': 512, 'device_name': '/dev/vdd'}
bdi = {'block_device_mapping': [], 'root_device_name': '/dev/sda',
'ephemerals': ephemerals, 'swap': swap}
metadata = self._vmops._get_instance_metadata(self._context,
self._instance)
self.flags(enabled=False, group='vnc')
self.flags(flat_injected=False)
image_size = (self._instance.root_gb) * units.Gi / 2
image_info = images.VMwareImage(
image_id=self._image_id,
file_size=image_size)
vi = get_vm_config_info.return_value
from_image.return_value = image_info
build_virtual_machine.return_value = 'fake-vm-ref'
self._vmops.spawn(self._context, self._instance, {},
injected_files=None, admin_password=None,
network_info=[], block_device_info=bdi)
from_image.assert_called_once_with(self._instance.image_ref, {})
get_vm_config_info.assert_called_once_with(self._instance,
image_info, extra_specs)
build_virtual_machine.assert_called_once_with(self._instance,
image_info, vi.dc_info, vi.datastore, [], extra_specs, metadata)
enlist_image.assert_called_once_with(image_info.image_id,
vi.datastore, vi.dc_info.ref)
fetch_image.assert_called_once_with(self._context, vi)
use_disk_image.assert_called_once_with('fake-vm-ref', vi)
# _create_and_attach_thin_disk should be called for each ephemeral
# and swap disk
eph0_path = str(ds_obj.DatastorePath(vi.datastore.name, 'fake_uuid',
'ephemeral_0.vmdk'))
eph1_path = str(ds_obj.DatastorePath(vi.datastore.name, 'fake_uuid',
'ephemeral_1.vmdk'))
swap_path = str(ds_obj.DatastorePath(vi.datastore.name, 'fake_uuid',
'swap.vmdk'))
create_and_attach_thin_disk.assert_has_calls([
mock.call(self._instance, 'fake-vm-ref', vi.dc_info,
ephemerals[0]['size'] * units.Mi, vi.ii.adapter_type,
eph0_path),
mock.call(self._instance, 'fake-vm-ref', vi.dc_info,
ephemerals[1]['size'] * units.Mi, vi.ii.adapter_type,
eph1_path),
mock.call(self._instance, 'fake-vm-ref', vi.dc_info,
swap['swap_size'] * units.Ki, vi.ii.adapter_type,
swap_path)
])
power_on_instance.assert_called_once_with(self._session,
self._instance,
vm_ref='fake-vm-ref')
def _get_fake_vi(self):
image_info = images.VMwareImage(
image_id=self._image_id,
file_size=7,
linked_clone=False)
vi = vmops.VirtualMachineInstanceConfigInfo(
self._instance, image_info,
self._ds, self._dc_info, mock.Mock())
return vi
@mock.patch.object(vm_util, 'create_virtual_disk')
def test_create_and_attach_thin_disk(self, mock_create):
vi = self._get_fake_vi()
self._vmops._volumeops = mock.Mock()
mock_attach_disk_to_vm = self._vmops._volumeops.attach_disk_to_vm
path = str(ds_obj.DatastorePath(vi.datastore.name, 'fake_uuid',
'fake-filename'))
self._vmops._create_and_attach_thin_disk(self._instance,
'fake-vm-ref',
vi.dc_info, 1,
'fake-adapter-type',
path)
mock_create.assert_called_once_with(
self._session, self._dc_info.ref, 'fake-adapter-type',
'thin', path, 1)
mock_attach_disk_to_vm.assert_called_once_with(
'fake-vm-ref', self._instance, 'fake-adapter-type',
'thin', path, 1, False)
def test_create_ephemeral_with_bdi(self):
ephemerals = [{'device_type': 'disk',
'disk_bus': 'virtio',
'device_name': '/dev/vdb',
'size': 1}]
block_device_info = {'ephemerals': ephemerals}
vi = self._get_fake_vi()
with mock.patch.object(
self._vmops, '_create_and_attach_thin_disk') as mock_caa:
self._vmops._create_ephemeral(block_device_info,
self._instance,
'fake-vm-ref',
vi.dc_info, vi.datastore,
'fake_uuid',
vi.ii.adapter_type)
mock_caa.assert_called_once_with(
self._instance, 'fake-vm-ref',
vi.dc_info, 1 * units.Mi, 'virtio',
'[fake_ds] fake_uuid/ephemeral_0.vmdk')
def _test_create_ephemeral_from_instance(self, bdi):
vi = self._get_fake_vi()
with mock.patch.object(
self._vmops, '_create_and_attach_thin_disk') as mock_caa:
self._vmops._create_ephemeral(bdi,
self._instance,
'fake-vm-ref',
vi.dc_info, vi.datastore,
'fake_uuid',
vi.ii.adapter_type)
mock_caa.assert_called_once_with(
self._instance, 'fake-vm-ref',
vi.dc_info, 1 * units.Mi, constants.DEFAULT_ADAPTER_TYPE,
'[fake_ds] fake_uuid/ephemeral_0.vmdk')
def test_create_ephemeral_with_bdi_but_no_ephemerals(self):
block_device_info = {'ephemerals': []}
self._instance.ephemeral_gb = 1
self._test_create_ephemeral_from_instance(block_device_info)
def test_create_ephemeral_with_no_bdi(self):
self._instance.ephemeral_gb = 1
self._test_create_ephemeral_from_instance(None)
def _test_create_swap_from_instance(self, bdi):
vi = self._get_fake_vi()
flavor = objects.Flavor(vcpus=1, memory_mb=1024, ephemeral_gb=1,
swap=1024, extra_specs={})
self._instance.flavor = flavor
with mock.patch.object(
self._vmops, '_create_and_attach_thin_disk'
) as create_and_attach:
self._vmops._create_swap(bdi, self._instance, 'fake-vm-ref',
vi.dc_info, vi.datastore, 'fake_uuid',
'lsiLogic')
size = flavor.swap * units.Ki
if bdi is not None:
swap = bdi.get('swap', {})
size = swap.get('swap_size', 0) * units.Ki
path = str(ds_obj.DatastorePath(vi.datastore.name, 'fake_uuid',
'swap.vmdk'))
create_and_attach.assert_called_once_with(self._instance,
'fake-vm-ref', vi.dc_info, size, 'lsiLogic', path)
def test_create_swap_with_bdi(self):
block_device_info = {'swap': {'disk_bus': None,
'swap_size': 512,
'device_name': '/dev/sdb'}}
self._test_create_swap_from_instance(block_device_info)
def test_create_swap_with_no_bdi(self):
self._test_create_swap_from_instance(None)
def test_build_virtual_machine(self):
image_id = nova.tests.unit.image.fake.get_valid_image_id()
image = images.VMwareImage(image_id=image_id)
extra_specs = vm_util.ExtraSpecs()
vm_ref = self._vmops.build_virtual_machine(self._instance,
image, self._dc_info,
self._ds,
self.network_info,
extra_specs,
self._metadata)
vm = vmwareapi_fake._get_object(vm_ref)
# Test basic VM parameters
self.assertEqual(self._instance.uuid, vm.name)
self.assertEqual(self._instance.uuid,
vm.get('summary.config.instanceUuid'))
self.assertEqual(self._instance_values['vcpus'],
vm.get('summary.config.numCpu'))
self.assertEqual(self._instance_values['memory_mb'],
vm.get('summary.config.memorySizeMB'))
# Test NSX config
for optval in vm.get('config.extraConfig').OptionValue:
if optval.key == 'nvp.vm-uuid':
self.assertEqual(self._instance_values['uuid'], optval.value)
break
else:
self.fail('nvp.vm-uuid not found in extraConfig')
# Test that the VM is associated with the specified datastore
datastores = vm.datastore.ManagedObjectReference
self.assertEqual(1, len(datastores))
datastore = vmwareapi_fake._get_object(datastores[0])
self.assertEqual(self._ds.name, datastore.get('summary.name'))
# Test that the VM's network is configured as specified
devices = vm.get('config.hardware.device').VirtualDevice
for device in devices:
if device.obj_name != 'ns0:VirtualE1000':
continue
self.assertEqual(self._network_values['address'],
device.macAddress)
break
else:
self.fail('NIC not configured')
def test_spawn_cpu_limit(self):
cpu_limits = vm_util.Limits(limit=7)
extra_specs = vm_util.ExtraSpecs(cpu_limits=cpu_limits)
self._test_spawn(extra_specs=extra_specs)
def test_spawn_cpu_reservation(self):
cpu_limits = vm_util.Limits(reservation=7)
extra_specs = vm_util.ExtraSpecs(cpu_limits=cpu_limits)
self._test_spawn(extra_specs=extra_specs)
def test_spawn_cpu_allocations(self):
cpu_limits = vm_util.Limits(limit=7,
reservation=6)
extra_specs = vm_util.ExtraSpecs(cpu_limits=cpu_limits)
self._test_spawn(extra_specs=extra_specs)
def test_spawn_cpu_shares_level(self):
cpu_limits = vm_util.Limits(shares_level='high')
extra_specs = vm_util.ExtraSpecs(cpu_limits=cpu_limits)
self._test_spawn(extra_specs=extra_specs)
def test_spawn_cpu_shares_custom(self):
cpu_limits = vm_util.Limits(shares_level='custom',
shares_share=1948)
extra_specs = vm_util.ExtraSpecs(cpu_limits=cpu_limits)
self._test_spawn(extra_specs=extra_specs)
def test_spawn_memory_limit(self):
memory_limits = vm_util.Limits(limit=7)
extra_specs = vm_util.ExtraSpecs(memory_limits=memory_limits)
self._test_spawn(extra_specs=extra_specs)
def test_spawn_memory_reservation(self):
memory_limits = vm_util.Limits(reservation=7)
extra_specs = vm_util.ExtraSpecs(memory_limits=memory_limits)
self._test_spawn(extra_specs=extra_specs)
def test_spawn_memory_allocations(self):
memory_limits = vm_util.Limits(limit=7,
reservation=6)
extra_specs = vm_util.ExtraSpecs(memory_limits=memory_limits)
self._test_spawn(extra_specs=extra_specs)
def test_spawn_memory_shares_level(self):
memory_limits = vm_util.Limits(shares_level='high')
extra_specs = vm_util.ExtraSpecs(memory_limits=memory_limits)
self._test_spawn(extra_specs=extra_specs)
def test_spawn_memory_shares_custom(self):
memory_limits = vm_util.Limits(shares_level='custom',
shares_share=1948)
extra_specs = vm_util.ExtraSpecs(memory_limits=memory_limits)
self._test_spawn(extra_specs=extra_specs)
def _validate_extra_specs(self, expected, actual):
self.assertEqual(expected.cpu_limits.limit,
actual.cpu_limits.limit)
self.assertEqual(expected.cpu_limits.reservation,
actual.cpu_limits.reservation)
self.assertEqual(expected.cpu_limits.shares_level,
actual.cpu_limits.shares_level)
self.assertEqual(expected.cpu_limits.shares_share,
actual.cpu_limits.shares_share)
def _validate_flavor_extra_specs(self, flavor_extra_specs, expected):
# Validate that the extra specs are parsed correctly
flavor = objects.Flavor(name='my-flavor',
memory_mb=6,
vcpus=28,
root_gb=496,
ephemeral_gb=8128,
swap=33550336,
extra_specs=flavor_extra_specs)
flavor_extra_specs = self._vmops._get_extra_specs(flavor, None)
self._validate_extra_specs(expected, flavor_extra_specs)
def test_extra_specs_cpu_limit(self):
flavor_extra_specs = {'quota:cpu_limit': 7}
cpu_limits = vm_util.Limits(limit=7)
extra_specs = vm_util.ExtraSpecs(cpu_limits=cpu_limits)
self._validate_flavor_extra_specs(flavor_extra_specs, extra_specs)
def test_extra_specs_cpu_reservations(self):
flavor_extra_specs = {'quota:cpu_reservation': 7}
cpu_limits = vm_util.Limits(reservation=7)
extra_specs = vm_util.ExtraSpecs(cpu_limits=cpu_limits)
self._validate_flavor_extra_specs(flavor_extra_specs, extra_specs)
def test_extra_specs_cpu_allocations(self):
flavor_extra_specs = {'quota:cpu_limit': 7,
'quota:cpu_reservation': 6}
cpu_limits = vm_util.Limits(limit=7,
reservation=6)
extra_specs = vm_util.ExtraSpecs(cpu_limits=cpu_limits)
self._validate_flavor_extra_specs(flavor_extra_specs, extra_specs)
def test_extra_specs_cpu_shares_level(self):
flavor_extra_specs = {'quota:cpu_shares_level': 'high'}
cpu_limits = vm_util.Limits(shares_level='high')
extra_specs = vm_util.ExtraSpecs(cpu_limits=cpu_limits)
self._validate_flavor_extra_specs(flavor_extra_specs, extra_specs)
def test_extra_specs_cpu_shares_custom(self):
flavor_extra_specs = {'quota:cpu_shares_level': 'custom',
'quota:cpu_shares_share': 1948}
cpu_limits = vm_util.Limits(shares_level='custom',
shares_share=1948)
extra_specs = vm_util.ExtraSpecs(cpu_limits=cpu_limits)
self._validate_flavor_extra_specs(flavor_extra_specs, extra_specs)
def _make_vm_config_info(self, is_iso=False, is_sparse_disk=False):
disk_type = (constants.DISK_TYPE_SPARSE if is_sparse_disk
else constants.DEFAULT_DISK_TYPE)
file_type = (constants.DISK_FORMAT_ISO if is_iso
else constants.DEFAULT_DISK_FORMAT)
image_info = images.VMwareImage(
image_id=self._image_id,
file_size=10 * units.Mi,
file_type=file_type,
disk_type=disk_type,
linked_clone=True)
cache_root_folder = self._ds.build_path("vmware_base", self._image_id)
mock_imagecache = mock.Mock()
mock_imagecache.get_image_cache_folder.return_value = cache_root_folder
vi = vmops.VirtualMachineInstanceConfigInfo(
self._instance, image_info,
self._ds, self._dc_info, mock_imagecache)
return vi
@mock.patch.object(vmops.VMwareVMOps, 'check_cache_folder')
@mock.patch.object(vmops.VMwareVMOps, '_fetch_image_as_file')
@mock.patch.object(vmops.VMwareVMOps, '_prepare_iso_image')
@mock.patch.object(vmops.VMwareVMOps, '_prepare_sparse_image')
@mock.patch.object(vmops.VMwareVMOps, '_prepare_flat_image')
@mock.patch.object(vmops.VMwareVMOps, '_cache_iso_image')
@mock.patch.object(vmops.VMwareVMOps, '_cache_sparse_image')
@mock.patch.object(vmops.VMwareVMOps, '_cache_flat_image')
@mock.patch.object(vmops.VMwareVMOps, '_delete_datastore_file')
def _test_fetch_image_if_missing(self,
mock_delete_datastore_file,
mock_cache_flat_image,
mock_cache_sparse_image,
mock_cache_iso_image,
mock_prepare_flat_image,
mock_prepare_sparse_image,
mock_prepare_iso_image,
mock_fetch_image_as_file,
mock_check_cache_folder,
is_iso=False,
is_sparse_disk=False):
tmp_dir_path = mock.Mock()
tmp_image_path = mock.Mock()
if is_iso:
mock_prepare = mock_prepare_iso_image
mock_cache = mock_cache_iso_image
elif is_sparse_disk:
mock_prepare = mock_prepare_sparse_image
mock_cache = mock_cache_sparse_image
else:
mock_prepare = mock_prepare_flat_image
mock_cache = mock_cache_flat_image
mock_prepare.return_value = tmp_dir_path, tmp_image_path
vi = self._make_vm_config_info(is_iso, is_sparse_disk)
self._vmops._fetch_image_if_missing(self._context, vi)
mock_check_cache_folder.assert_called_once_with(
self._ds.name, self._ds.ref)
mock_prepare.assert_called_once_with(vi)
mock_fetch_image_as_file.assert_called_once_with(
self._context, vi, tmp_image_path)
mock_cache.assert_called_once_with(vi, tmp_image_path)
mock_delete_datastore_file.assert_called_once_with(
str(tmp_dir_path), self._dc_info.ref)
def test_fetch_image_if_missing(self):
self._test_fetch_image_if_missing()
def test_fetch_image_if_missing_with_sparse(self):
self._test_fetch_image_if_missing(
is_sparse_disk=True)
def test_fetch_image_if_missing_with_iso(self):
self._test_fetch_image_if_missing(
is_iso=True)
def test_get_esx_host_and_cookies(self):
datastore = mock.Mock()
datastore.get_connected_hosts.return_value = ['fira-host']
file_path = mock.Mock()
def fake_invoke(module, method, *args, **kwargs):
if method == 'AcquireGenericServiceTicket':
ticket = mock.Mock()
ticket.id = 'fira-ticket'
return ticket
elif method == 'get_object_property':
return 'fira-host'
with contextlib.nested(
mock.patch.object(self._session, 'invoke_api', fake_invoke),
):
result = self._vmops._get_esx_host_and_cookies(datastore,
'ha-datacenter',
file_path)
self.assertEqual('fira-host', result[0])
cookies = result[1]
self.assertEqual(1, len(cookies))
self.assertEqual('vmware_cgi_ticket', cookies[0].name)
self.assertEqual('"fira-ticket"', cookies[0].value)
@mock.patch.object(images, 'fetch_image')
@mock.patch.object(vmops.VMwareVMOps, '_get_esx_host_and_cookies')
def test_fetch_image_as_file(self,
mock_get_esx_host_and_cookies,
mock_fetch_image):
vi = self._make_vm_config_info()
image_ds_loc = mock.Mock()
host = mock.Mock()
dc_name = 'ha-datacenter'
cookies = mock.Mock()
mock_get_esx_host_and_cookies.return_value = host, cookies
self._vmops._fetch_image_as_file(self._context, vi, image_ds_loc)
mock_get_esx_host_and_cookies.assert_called_once_with(
vi.datastore,
dc_name,
image_ds_loc.rel_path)
mock_fetch_image.assert_called_once_with(
self._context,
vi.instance,
host,
self._session._port,
dc_name,
self._ds.name,
image_ds_loc.rel_path,
cookies=cookies)
@mock.patch.object(images, 'fetch_image')
@mock.patch.object(vmops.VMwareVMOps, '_get_esx_host_and_cookies')
def test_fetch_image_as_file_exception(self,
mock_get_esx_host_and_cookies,
mock_fetch_image):
vi = self._make_vm_config_info()
image_ds_loc = mock.Mock()
dc_name = 'ha-datacenter'
mock_get_esx_host_and_cookies.side_effect = \
exception.HostNotFound(host='')
self._vmops._fetch_image_as_file(self._context, vi, image_ds_loc)
mock_get_esx_host_and_cookies.assert_called_once_with(
vi.datastore,
dc_name,
image_ds_loc.rel_path)
mock_fetch_image.assert_called_once_with(
self._context,
vi.instance,
self._session._host,
self._session._port,
self._dc_info.name,
self._ds.name,
image_ds_loc.rel_path,
cookies='Fake-CookieJar')
@mock.patch.object(images, 'fetch_image_stream_optimized')
def test_fetch_image_as_vapp(self, mock_fetch_image):
vi = self._make_vm_config_info()
image_ds_loc = mock.Mock()
image_ds_loc.parent.basename = 'fake-name'
self._vmops._fetch_image_as_vapp(self._context, vi, image_ds_loc)
mock_fetch_image.assert_called_once_with(
self._context,
vi.instance,
self._session,
'fake-name',
self._ds.name,
vi.dc_info.vmFolder,
self._vmops._root_resource_pool)
@mock.patch.object(uuidutils, 'generate_uuid', return_value='tmp-uuid')
def test_prepare_iso_image(self, mock_generate_uuid):
vi = self._make_vm_config_info(is_iso=True)
tmp_dir_loc, tmp_image_ds_loc = self._vmops._prepare_iso_image(vi)
expected_tmp_dir_path = '[%s] vmware_temp/tmp-uuid' % (self._ds.name)
expected_image_path = '[%s] vmware_temp/tmp-uuid/%s/%s.iso' % (
self._ds.name, self._image_id, self._image_id)
self.assertEqual(str(tmp_dir_loc), expected_tmp_dir_path)
self.assertEqual(str(tmp_image_ds_loc), expected_image_path)
@mock.patch.object(uuidutils, 'generate_uuid', return_value='tmp-uuid')
def test_prepare_sparse_image(self, mock_generate_uuid):
vi = self._make_vm_config_info(is_sparse_disk=True)
tmp_dir_loc, tmp_image_ds_loc = self._vmops._prepare_sparse_image(vi)
expected_tmp_dir_path = '[%s] vmware_temp/tmp-uuid' % (self._ds.name)
expected_image_path = '[%s] vmware_temp/tmp-uuid/%s/%s' % (
self._ds.name, self._image_id, "tmp-sparse.vmdk")
self.assertEqual(str(tmp_dir_loc), expected_tmp_dir_path)
self.assertEqual(str(tmp_image_ds_loc), expected_image_path)
@mock.patch.object(ds_util, 'mkdir')
@mock.patch.object(vm_util, 'create_virtual_disk')
@mock.patch.object(vmops.VMwareVMOps, '_delete_datastore_file')
@mock.patch.object(uuidutils, 'generate_uuid', return_value='tmp-uuid')
def test_prepare_flat_image(self,
mock_generate_uuid,
mock_delete_datastore_file,
mock_create_virtual_disk,
mock_mkdir):
vi = self._make_vm_config_info()
tmp_dir_loc, tmp_image_ds_loc = self._vmops._prepare_flat_image(vi)
expected_tmp_dir_path = '[%s] vmware_temp/tmp-uuid' % (self._ds.name)
expected_image_path = '[%s] vmware_temp/tmp-uuid/%s/%s-flat.vmdk' % (
self._ds.name, self._image_id, self._image_id)
expected_image_path_parent = '[%s] vmware_temp/tmp-uuid/%s' % (
self._ds.name, self._image_id)
expected_path_to_create = '[%s] vmware_temp/tmp-uuid/%s/%s.vmdk' % (
self._ds.name, self._image_id, self._image_id)
mock_mkdir.assert_called_once_with(
self._session, DsPathMatcher(expected_image_path_parent),
self._dc_info.ref)
self.assertEqual(str(tmp_dir_loc), expected_tmp_dir_path)
self.assertEqual(str(tmp_image_ds_loc), expected_image_path)
image_info = vi.ii
mock_create_virtual_disk.assert_called_once_with(
self._session, self._dc_info.ref,
image_info.adapter_type,
image_info.disk_type,
DsPathMatcher(expected_path_to_create),
image_info.file_size_in_kb)
mock_delete_datastore_file.assert_called_once_with(
DsPathMatcher(expected_image_path),
self._dc_info.ref)
@mock.patch.object(ds_util, 'file_move')
def test_cache_iso_image(self, mock_file_move):
vi = self._make_vm_config_info(is_iso=True)
tmp_image_ds_loc = mock.Mock()
self._vmops._cache_iso_image(vi, tmp_image_ds_loc)
mock_file_move.assert_called_once_with(
self._session, self._dc_info.ref,
tmp_image_ds_loc.parent,
DsPathMatcher('[fake_ds] vmware_base/%s' % self._image_id))
@mock.patch.object(ds_util, 'file_move')
def test_cache_flat_image(self, mock_file_move):
vi = self._make_vm_config_info()
tmp_image_ds_loc = mock.Mock()
self._vmops._cache_flat_image(vi, tmp_image_ds_loc)
mock_file_move.assert_called_once_with(
self._session, self._dc_info.ref,
tmp_image_ds_loc.parent,
DsPathMatcher('[fake_ds] vmware_base/%s' % self._image_id))
@mock.patch.object(ds_util, 'disk_move')
@mock.patch.object(ds_util, 'mkdir')
def test_cache_stream_optimized_image(self, mock_mkdir, mock_disk_move):
vi = self._make_vm_config_info()
self._vmops._cache_stream_optimized_image(vi, mock.sentinel.tmp_image)
mock_mkdir.assert_called_once_with(
self._session,
DsPathMatcher('[fake_ds] vmware_base/%s' % self._image_id),
self._dc_info.ref)
mock_disk_move.assert_called_once_with(
self._session, self._dc_info.ref,
mock.sentinel.tmp_image,
DsPathMatcher('[fake_ds] vmware_base/%s/%s.vmdk' %
(self._image_id, self._image_id)))
@mock.patch.object(ds_util, 'file_move')
@mock.patch.object(vm_util, 'copy_virtual_disk')
@mock.patch.object(vmops.VMwareVMOps, '_delete_datastore_file')
@mock.patch.object(vmops.VMwareVMOps, '_update_image_size')
def test_cache_sparse_image(self,
mock_update_image_size,
mock_delete_datastore_file,
mock_copy_virtual_disk,
mock_file_move):
vi = self._make_vm_config_info(is_sparse_disk=True)
sparse_disk_path = "[%s] vmware_temp/tmp-uuid/%s/tmp-sparse.vmdk" % (
self._ds.name, self._image_id)
tmp_image_ds_loc = ds_obj.DatastorePath.parse(sparse_disk_path)
self._vmops._cache_sparse_image(vi, tmp_image_ds_loc)
target_disk_path = "[%s] vmware_temp/tmp-uuid/%s/%s.vmdk" % (
self._ds.name,
self._image_id, self._image_id)
mock_copy_virtual_disk.assert_called_once_with(
self._session, self._dc_info.ref,
sparse_disk_path,
DsPathMatcher(target_disk_path))
mock_update_image_size.assert_called_once_with(vi)
def test_get_storage_policy_none(self):
flavor = objects.Flavor(name='m1.small',
memory_mb=6,
vcpus=28,
root_gb=496,
ephemeral_gb=8128,
swap=33550336,
extra_specs={})
self.flags(pbm_enabled=True,
pbm_default_policy='fake-policy', group='vmware')
extra_specs = self._vmops._get_extra_specs(flavor, None)
self.assertEqual('fake-policy', extra_specs.storage_policy)
def test_get_storage_policy_extra_specs(self):
extra_specs = {'vmware:storage_policy': 'flavor-policy'}
flavor = objects.Flavor(name='m1.small',
memory_mb=6,
vcpus=28,
root_gb=496,
ephemeral_gb=8128,
swap=33550336,
extra_specs=extra_specs)
self.flags(pbm_enabled=True,
pbm_default_policy='default-policy', group='vmware')
extra_specs = self._vmops._get_extra_specs(flavor, None)
self.assertEqual('flavor-policy', extra_specs.storage_policy)
def test_get_base_folder_not_set(self):
self.flags(image_cache_subdirectory_name='vmware_base')
base_folder = self._vmops._get_base_folder()
self.assertEqual('vmware_base', base_folder)
def test_get_base_folder_host_ip(self):
self.flags(my_ip='7.7.7.7',
image_cache_subdirectory_name='_base')
base_folder = self._vmops._get_base_folder()
self.assertEqual('7.7.7.7_base', base_folder)
def test_get_base_folder_cache_prefix(self):
self.flags(cache_prefix='my_prefix', group='vmware')
self.flags(image_cache_subdirectory_name='_base')
base_folder = self._vmops._get_base_folder()
self.assertEqual('my_prefix_base', base_folder)
def _test_reboot_vm(self, reboot_type="SOFT"):
expected_methods = ['get_object_properties_dict']
if reboot_type == "SOFT":
expected_methods.append('RebootGuest')
else:
expected_methods.append('ResetVM_Task')
query = {}
query['runtime.powerState'] = "poweredOn"
query['summary.guest.toolsStatus'] = "toolsOk"
query['summary.guest.toolsRunningStatus'] = "guestToolsRunning"
def fake_call_method(module, method, *args, **kwargs):
expected_method = expected_methods.pop(0)
self.assertEqual(expected_method, method)
if (expected_method == 'get_object_properties_dict'):
return query
elif (expected_method == 'ResetVM_Task'):
return 'fake-task'
with contextlib.nested(
mock.patch.object(vm_util, "get_vm_ref",
return_value='fake-vm-ref'),
mock.patch.object(self._session, "_call_method",
fake_call_method),
mock.patch.object(self._session, "_wait_for_task")
) as (_get_vm_ref, fake_call_method, _wait_for_task):
self._vmops.reboot(self._instance, self.network_info, reboot_type)
_get_vm_ref.assert_called_once_with(self._session,
self._instance)
if reboot_type == "HARD":
_wait_for_task.assert_has_calls([
mock.call('fake-task')])
def test_reboot_vm_soft(self):
self._test_reboot_vm()
def test_reboot_vm_hard(self):
self._test_reboot_vm(reboot_type="HARD")
def test_get_instance_metadata(self):
flavor = objects.Flavor(id=7,
name='m1.small',
memory_mb=6,
vcpus=28,
root_gb=496,
ephemeral_gb=8128,
swap=33550336,
extra_specs={})
self._instance.flavor = flavor
metadata = self._vmops._get_instance_metadata(
self._context, self._instance)
expected = ("name:fake_display_name\n"
"userid:fake_user\n"
"username:None\n"
"projectid:fake_project\n"
"projectname:None\n"
"flavor:name:m1.small\n"
"flavor:memory_mb:6\n"
"flavor:vcpus:28\n"
"flavor:ephemeral_gb:8128\n"
"flavor:root_gb:496\n"
"flavor:swap:33550336\n"
"imageid:70a599e0-31e7-49b7-b260-868f441e862b\n"
"package:%s\n" % version.version_string_with_package())
self.assertEqual(expected, metadata)
@mock.patch.object(vm_util, 'reconfigure_vm')
@mock.patch.object(vm_util, 'get_network_attach_config_spec',
return_value='fake-attach-spec')
@mock.patch.object(vm_util, 'get_attach_port_index', return_value=1)
@mock.patch.object(vm_util, 'get_vm_ref', return_value='fake-ref')
def test_attach_interface(self, mock_get_vm_ref,
mock_get_attach_port_index,
mock_get_network_attach_config_spec,
mock_reconfigure_vm):
_network_api = mock.Mock()
self._vmops._network_api = _network_api
vif_info = vif.get_vif_dict(self._session, self._cluster,
'VirtualE1000',
utils.is_neutron(),
self._network_values)
self._vmops.attach_interface(self._instance, self._image_meta,
self._network_values)
mock_get_vm_ref.assert_called_once_with(self._session, self._instance)
mock_get_attach_port_index(self._session, 'fake-ref')
mock_get_network_attach_config_spec.assert_called_once_with(
self._session.vim.client.factory, vif_info, 1)
mock_reconfigure_vm.assert_called_once_with(self._session,
'fake-ref',
'fake-attach-spec')
_network_api.update_instance_vnic_index(mock.ANY,
self._instance, self._network_values, 1)
@mock.patch.object(vif, 'get_network_device', return_value='device')
@mock.patch.object(vm_util, 'reconfigure_vm')
@mock.patch.object(vm_util, 'get_network_detach_config_spec',
return_value='fake-detach-spec')
@mock.patch.object(vm_util, 'get_vm_detach_port_index', return_value=1)
@mock.patch.object(vm_util, 'get_vm_ref', return_value='fake-ref')
def test_detach_interface(self, mock_get_vm_ref,
mock_get_detach_port_index,
mock_get_network_detach_config_spec,
mock_reconfigure_vm,
mock_get_network_device):
_network_api = mock.Mock()
self._vmops._network_api = _network_api
with mock.patch.object(self._session, '_call_method',
return_value='hardware-devices'):
self._vmops.detach_interface(self._instance, self._network_values)
mock_get_vm_ref.assert_called_once_with(self._session, self._instance)
mock_get_detach_port_index(self._session, 'fake-ref')
mock_get_network_detach_config_spec.assert_called_once_with(
self._session.vim.client.factory, 'device', 1)
mock_reconfigure_vm.assert_called_once_with(self._session,
'fake-ref',
'fake-detach-spec')
_network_api.update_instance_vnic_index(mock.ANY,
self._instance, self._network_values, None)
@mock.patch.object(vm_util, 'get_vm_ref', return_value='fake-ref')
def test_get_mks_console(self, mock_get_vm_ref):
ticket = mock.MagicMock()
ticket.host = 'esx1'
ticket.port = 902
ticket.ticket = 'fira'
ticket.sslThumbprint = 'aa:bb:cc:dd:ee:ff'
ticket.cfgFile = '[ds1] fira/foo.vmx'
with mock.patch.object(self._session, '_call_method',
return_value=ticket):
console = self._vmops.get_mks_console(self._instance)
self.assertEqual('esx1', console.host)
self.assertEqual(902, console.port)
path = jsonutils.loads(console.internal_access_path)
self.assertEqual('fira', path['ticket'])
self.assertEqual('aabbccddeeff', path['thumbprint'])
self.assertEqual('[ds1] fira/foo.vmx', path['cfgFile'])
def test_get_cores_per_socket(self):
extra_specs = {'hw:cpu_sockets': 7}
flavor = objects.Flavor(name='m1.small',
memory_mb=6,
vcpus=28,
root_gb=496,
ephemeral_gb=8128,
swap=33550336,
extra_specs=extra_specs)
extra_specs = self._vmops._get_extra_specs(flavor, None)
self.assertEqual(4, int(extra_specs.cores_per_socket))
|
|
# Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2010 Gabor Rapcsanyi ([email protected]), University of Szeged
# Copyright (C) 2011 Apple 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 Google 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.
import logging
import optparse
import os
import sys
import traceback
from webkitpy.common.host import Host
from webkitpy.layout_tests.controllers.manager import Manager
from webkitpy.layout_tests.models import test_run_results
from webkitpy.layout_tests.port import configuration_options, platform_options
from webkitpy.layout_tests.views import buildbot_results
from webkitpy.layout_tests.views import printing
from webkitpy.layout_tests.generate_results_dashboard import DashBoardGenerator
_log = logging.getLogger(__name__)
def main(argv, stdout, stderr):
options, args = parse_args(argv)
if options.platform and 'test' in options.platform and not 'browser_test' in options.platform:
# It's a bit lame to import mocks into real code, but this allows the user
# to run tests against the test platform interactively, which is useful for
# debugging test failures.
from webkitpy.common.host_mock import MockHost
host = MockHost()
else:
host = Host()
if options.lint_test_files:
from webkitpy.layout_tests.lint_test_expectations import run_checks
return run_checks(host, options, stderr)
try:
port = host.port_factory.get(options.platform, options)
except NotImplementedError, e:
# FIXME: is this the best way to handle unsupported port names?
print >> stderr, str(e)
return test_run_results.UNEXPECTED_ERROR_EXIT_STATUS
try:
run_details = run(port, options, args, stderr)
if ((run_details.exit_code not in test_run_results.ERROR_CODES or
run_details.exit_code == test_run_results.EARLY_EXIT_STATUS) and
not run_details.initial_results.keyboard_interrupted):
bot_printer = buildbot_results.BuildBotPrinter(stdout, options.debug_rwt_logging)
bot_printer.print_results(run_details)
gen_dash_board = DashBoardGenerator(port)
gen_dash_board.generate()
return run_details.exit_code
# We need to still handle KeyboardInterrupt, atleast for webkitpy unittest cases.
except KeyboardInterrupt:
return test_run_results.INTERRUPTED_EXIT_STATUS
except test_run_results.TestRunException as e:
print >> stderr, e.msg
return e.code
except BaseException as e:
if isinstance(e, Exception):
print >> stderr, '\n%s raised: %s' % (e.__class__.__name__, str(e))
traceback.print_exc(file=stderr)
return test_run_results.UNEXPECTED_ERROR_EXIT_STATUS
def parse_args(args):
option_group_definitions = []
option_group_definitions.append(("Platform options", platform_options()))
option_group_definitions.append(("Configuration options", configuration_options()))
option_group_definitions.append(("Printing Options", printing.print_options()))
option_group_definitions.append(("Android-specific Options", [
optparse.make_option("--adb-device",
action="append", default=[],
help="Run Android layout tests on these devices."),
# FIXME: Flip this to be off by default once we can log the device setup more cleanly.
optparse.make_option("--no-android-logging",
action="store_false", dest='android_logging', default=True,
help="Do not log android-specific debug messages (default is to log as part of --debug-rwt-logging"),
]))
option_group_definitions.append(("Results Options", [
optparse.make_option("--add-platform-exceptions", action="store_true", default=False,
help="Save generated results into the *most-specific-platform* directory rather than the *generic-platform* directory"),
optparse.make_option("--additional-drt-flag", action="append",
default=[], help="Additional command line flag to pass to the driver "
"Specify multiple times to add multiple flags."),
optparse.make_option("--additional-expectations", action="append", default=[],
help="Path to a test_expectations file that will override previous expectations. "
"Specify multiple times for multiple sets of overrides."),
optparse.make_option("--additional-platform-directory", action="append",
default=[], help="Additional directory where to look for test "
"baselines (will take precendence over platform baselines). "
"Specify multiple times to add multiple search path entries."),
optparse.make_option("--build-directory",
help="Path to the directory under which build files are kept (should not include configuration)"),
optparse.make_option("--clobber-old-results", action="store_true",
default=False, help="Clobbers test results from previous runs."),
optparse.make_option("--compare-port", action="store", default=None,
help="Use the specified port's baselines first"),
optparse.make_option("--driver-name", type="string",
help="Alternative driver binary to use"),
optparse.make_option("--full-results-html", action="store_true",
default=False,
help="Show all failures in results.html, rather than only regressions"),
optparse.make_option("--new-baseline", action="store_true",
default=False, help="Save generated results as new baselines "
"into the *most-specific-platform* directory, overwriting whatever's "
"already there. Equivalent to --reset-results --add-platform-exceptions"),
optparse.make_option("--no-new-test-results", action="store_false",
dest="new_test_results", default=True,
help="Don't create new baselines when no expected results exist"),
optparse.make_option("--no-show-results", action="store_false",
default=True, dest="show_results",
help="Don't launch a browser with results after the tests "
"are done"),
optparse.make_option("-p", "--pixel", "--pixel-tests", action="store_true",
dest="pixel_tests", help="Enable pixel-to-pixel PNG comparisons"),
optparse.make_option("--no-pixel", "--no-pixel-tests", action="store_false",
dest="pixel_tests", help="Disable pixel-to-pixel PNG comparisons"),
#FIXME: we should support a comma separated list with --pixel-test-directory as well.
optparse.make_option("--pixel-test-directory", action="append", default=[], dest="pixel_test_directories",
help="A directory where it is allowed to execute tests as pixel tests. "
"Specify multiple times to add multiple directories. "
"This option implies --pixel-tests. If specified, only those tests "
"will be executed as pixel tests that are located in one of the "
"directories enumerated with the option. Some ports may ignore this "
"option while others can have a default value that can be overridden here."),
optparse.make_option("--reset-results", action="store_true",
default=False, help="Reset expectations to the "
"generated results in their existing location."),
optparse.make_option("--results-directory", help="Location of test results"),
optparse.make_option("--skip-failing-tests", action="store_true",
default=False, help="Skip tests that are expected to fail. "
"Note: When using this option, you might miss new crashes "
"in these tests."),
optparse.make_option("--smoke", action="store_true",
help="Run just the SmokeTests"),
optparse.make_option("--no-smoke", dest="smoke", action="store_false",
help="Do not run just the SmokeTests"),
]))
option_group_definitions.append(("Testing Options", [
optparse.make_option("--additional-env-var", type="string", action="append", default=[],
help="Passes that environment variable to the tests (--additional-env-var=NAME=VALUE)"),
optparse.make_option("--batch-size",
help=("Run a the tests in batches (n), after every n tests, "
"the driver is relaunched."), type="int", default=None),
optparse.make_option("--build", dest="build",
action="store_true", default=True,
help="Check to ensure the build is up-to-date (default)."),
optparse.make_option("--no-build", dest="build",
action="store_false", help="Don't check to see if the build is up-to-date."),
optparse.make_option("--child-processes",
help="Number of drivers to run in parallel."),
optparse.make_option("--disable-breakpad", action="store_true",
help="Don't use breakpad to symbolize unexpected crashes."),
optparse.make_option("--driver-logging", action="store_true",
help="Print detailed logging of the driver/content_shell"),
optparse.make_option("--enable-leak-detection", action="store_true",
help="Enable the leak detection of DOM objects."),
optparse.make_option("--enable-sanitizer", action="store_true",
help="Only alert on sanitizer-related errors and crashes"),
optparse.make_option("--exit-after-n-crashes-or-timeouts", type="int",
default=None, help="Exit after the first N crashes instead of "
"running all tests"),
optparse.make_option("--exit-after-n-failures", type="int", default=None,
help="Exit after the first N failures instead of running all "
"tests"),
optparse.make_option("--ignore-builder-category", action="store",
help=("The category of builders to use with the --ignore-flaky-tests "
"option ('layout' or 'deps').")),
optparse.make_option("--ignore-flaky-tests", action="store",
help=("Control whether tests that are flaky on the bots get ignored."
"'very-flaky' == Ignore any tests that flaked more than once on the bot."
"'maybe-flaky' == Ignore any tests that flaked once on the bot."
"'unexpected' == Ignore any tests that had unexpected results on the bot.")),
optparse.make_option("--iterations", type="int", default=1, help="Number of times to run the set of tests (e.g. ABCABCABC)"),
optparse.make_option("--max-locked-shards", type="int", default=0,
help="Set the maximum number of locked shards"),
optparse.make_option("--no-retry-failures", action="store_false",
dest="retry_failures",
help="Don't re-try any tests that produce unexpected results."),
optparse.make_option("--nocheck-sys-deps", action="store_true",
default=False,
help="Don't check the system dependencies (themes)"),
optparse.make_option("--order", action="store", default="natural",
help=("determine the order in which the test cases will be run. "
"'none' == use the order in which the tests were listed either in arguments or test list, "
"'natural' == use the natural order (default), "
"'random-seeded' == randomize the test order using a fixed seed, "
"'random' == randomize the test order.")),
optparse.make_option("--profile", action="store_true",
help="Output per-test profile information."),
optparse.make_option("--profiler", action="store",
help="Output per-test profile information, using the specified profiler."),
optparse.make_option("--repeat-each", type="int", default=1, help="Number of times to run each test (e.g. AAABBBCCC)"),
optparse.make_option("--retry-failures", action="store_true",
help="Re-try any tests that produce unexpected results. Default is to not retry if an explicit list of tests is passed to run-webkit-tests."),
optparse.make_option("--run-chunk",
help=("Run a specified chunk (n:l), the nth of len l, "
"of the layout tests")),
optparse.make_option("--run-part", help=("Run a specified part (n:m), "
"the nth of m parts, of the layout tests")),
optparse.make_option("--run-singly", action="store_true",
default=False, help="DEPRECATED, same as --batch-size=1 --verbose"),
optparse.make_option("--skipped", action="store", default=None,
help=("control how tests marked SKIP are run. "
"'default' == Skip tests unless explicitly listed on the command line, "
"'ignore' == Run them anyway, "
"'only' == only run the SKIP tests, "
"'always' == always skip, even if listed on the command line.")),
optparse.make_option("--test-list", action="append",
help="read list of tests to run from file", metavar="FILE"),
optparse.make_option("--time-out-ms",
help="Set the timeout for each test"),
optparse.make_option("--wrapper",
help="wrapper command to insert before invocations of "
"the driver; option is split on whitespace before "
"running. (Example: --wrapper='valgrind --smc-check=all')"),
# FIXME: Display default number of child processes that will run.
optparse.make_option("-f", "--fully-parallel", action="store_true",
help="run all tests in parallel"),
optparse.make_option("-i", "--ignore-tests", action="append", default=[],
help="directories or test to ignore (may specify multiple times)"),
optparse.make_option("-n", "--dry-run", action="store_true",
default=False,
help="Do everything but actually run the tests or upload results."),
]))
option_group_definitions.append(("Miscellaneous Options", [
optparse.make_option("--lint-test-files", action="store_true",
default=False, help=("Makes sure the test files parse for all "
"configurations. Does not run any tests.")),
]))
# FIXME: Move these into json_results_generator.py
option_group_definitions.append(("Result JSON Options", [
optparse.make_option("--build-name", default="DUMMY_BUILD_NAME",
help=("The name of the builder used in its path, e.g. "
"webkit-rel.")),
optparse.make_option("--build-number", default="DUMMY_BUILD_NUMBER",
help=("The build number of the builder running this script.")),
optparse.make_option("--builder-name", default="",
help=("The name of the builder shown on the waterfall running "
"this script e.g. WebKit.")),
optparse.make_option("--master-name", help="The name of the buildbot master."),
optparse.make_option("--test-results-server", default="",
help=("If specified, upload results json files to this appengine "
"server.")),
optparse.make_option("--write-full-results-to",
help=("If specified, copy full_results.json from the results dir "
"to the specified path.")),
]))
option_parser = optparse.OptionParser()
for group_name, group_options in option_group_definitions:
option_group = optparse.OptionGroup(option_parser, group_name)
option_group.add_options(group_options)
option_parser.add_option_group(option_group)
return option_parser.parse_args(args)
def _set_up_derived_options(port, options, args):
"""Sets the options values that depend on other options values."""
if not options.child_processes:
options.child_processes = os.environ.get("WEBKIT_TEST_CHILD_PROCESSES",
str(port.default_child_processes()))
if not options.max_locked_shards:
options.max_locked_shards = int(os.environ.get("WEBKIT_TEST_MAX_LOCKED_SHARDS",
str(port.default_max_locked_shards())))
if not options.configuration:
options.configuration = port.default_configuration()
if options.pixel_tests is None:
options.pixel_tests = port.default_pixel_tests()
if not options.time_out_ms:
options.time_out_ms = str(port.default_timeout_ms())
options.slow_time_out_ms = str(5 * int(options.time_out_ms))
if options.additional_platform_directory:
additional_platform_directories = []
for path in options.additional_platform_directory:
additional_platform_directories.append(port.host.filesystem.abspath(path))
options.additional_platform_directory = additional_platform_directories
if options.new_baseline:
options.reset_results = True
options.add_platform_exceptions = True
if options.pixel_test_directories:
options.pixel_tests = True
varified_dirs = set()
pixel_test_directories = options.pixel_test_directories
for directory in pixel_test_directories:
# FIXME: we should support specifying the directories all the ways we support it for additional
# arguments specifying which tests and directories to run. We should also move the logic for that
# to Port.
filesystem = port.host.filesystem
if not filesystem.isdir(filesystem.join(port.layout_tests_dir(), directory)):
_log.warning("'%s' was passed to --pixel-test-directories, which doesn't seem to be a directory" % str(directory))
else:
varified_dirs.add(directory)
options.pixel_test_directories = list(varified_dirs)
if options.run_singly:
options.batch_size = 1
options.verbose = True
if not args and not options.test_list and options.smoke is None:
options.smoke = port.default_smoke_test_only()
if options.smoke:
if not args and not options.test_list and options.retry_failures is None:
# Retry failures by default if we're doing just a smoke test (no additional tests).
options.retry_failures = True
if not options.test_list:
options.test_list = []
options.test_list.append(port.host.filesystem.join(port.layout_tests_dir(), 'SmokeTests'))
if not options.skipped:
options.skipped = 'always'
if not options.skipped:
options.skipped = 'default'
def run(port, options, args, logging_stream):
logger = logging.getLogger()
logger.setLevel(logging.DEBUG if options.debug_rwt_logging else logging.INFO)
try:
printer = printing.Printer(port, options, logging_stream, logger=logger)
_set_up_derived_options(port, options, args)
manager = Manager(port, options, printer)
printer.print_config(port.results_directory())
run_details = manager.run(args)
_log.debug("Testing completed, Exit status: %d" % run_details.exit_code)
return run_details
finally:
printer.cleanup()
if __name__ == '__main__':
sys.exit(main(sys.argv[1:], sys.stdout, sys.stderr))
|
|
# coding=utf-8
from . import messages
from . import models
from google.appengine.ext import ndb
from google.appengine.ext.ndb import msgprop
from google.appengine.ext import blobstore
import appengine_config
import datetime
import os
import re
import webapp2
DOWNLOAD_URL_FORMAT = 'https://www.googleapis.com/drive/v3/files/{resource_id}?alt=media&key={key}'
THUMBNAIL_URL_FORMAT = 'https://drive.google.com/thumbnail?sz=w{size}&id={resource_id}'
CONFIG = appengine_config.CONFIG
VARIANT_IDENTIFIERS = (
('_STD_', 'Standard'),
('_DBS_', 'Double-sided'),
('_SGS_', 'Single-sided'),
('_15A_', '15 degree angle'),
('_30A_', '30 degree angle'),
)
MESSAGING_IDENTIFIERS = (
('_ALL_', 'All'),
('_BASES_', 'Bases'),
('_CO-BRAND_1PK_', '1 Pack Co-branding (UK Only)'),
('_CO-BRAND_2PK_', '2 Pack Co-branding (UK Only)'),
('_CO-BRAND_', 'Co-branding'),
('_CTA_', 'Call-to-action'),
('_MAPS_', 'Maps'),
('_MUSIC_', 'Music'),
('_PHOTOS_', 'Photos'),
('_PROMOV1_', 'Promotional Single'),
('_PROMOV2_', 'Promotional Lifestyle'),
('_PROMOV3_', 'Promotional Multipack'),
('_PROMOV4_', 'Promotional Twinpack'),
('_PROMO_1PK_', '1 Pack Promotional (UK, DE, FR)'),
('_PROMO_2PK_', '2 Pack Promotional (UK, DE, FR)'),
('_PROMO_3PK_', '3 Pack Promotional (UK, DE, FR)'),
('_PROMO_', 'Promotional'),
('_SEARCH_', 'Search'),
('_SOCIALMEDIA_', 'Social media'),
('_STANDALONE_1PK_', '1 Pack Standalone (UK, DE, FR)'),
('_STANDALONE_2PK_', '2 Pack Standalone (UK, DE, FR)'),
('_STANDALONE_3PK_', '3 Pack Standalone (UK, DE, FR)'),
('_STANDALONE_', 'Standalone'),
('_STDV1_', 'Standard Single'),
('_STDV2_', 'Standard Device'),
('_STDV3_', 'Standard Multipack'),
('_STDV4_', 'Standard Twinpack'),
('_STD_1PK_', '1 Pack Standard (UK, DE, FR)'),
('_STD_2PK_', '2 Pack Standard (UK, DE, FR)'),
('_STD_3PK_', '3 Pack Standard (UK, DE, FR)'),
('_STD_', 'Standard'),
('_YOUTUBE_', 'YouTube'),
('CC4K_', 'Chromecast Ultra'),
('CCA_', 'Chromecast Audio'),
('CC_CC4K_', 'Chromecast & Chromecast Ultra'),
('CC_CC4K_CCA_', 'Chromecast, Chromecast Ultra & Chromecast Audio'),
('CC_CCA_', 'Chromecast & Chromecast Audio'),
('CC_', 'Chromecast'),
('DV_US_STD_COMMIT_COMBO_4x4', 'Demo + Product Card'),
('PARTNER_LOGO_PROMO_CARD', 'Partner Logo Promo Card'),
)
FILENAME_IDENTIFIERS_TO_LOCALES = (
('_AF_', 'af'),
('_AR-AE_', 'ar-ae'),
('_AR-BH_', 'ar-bh'),
('_AR-DZ_', 'ar-dz'),
('_AR-EG_', 'ar-eg'),
('_AR-IQ_', 'ar-iq'),
('_AR-JO_', 'ar-jo'),
('_AR-KW_', 'ar-kw'),
('_AR-LB_', 'ar-lb'),
('_AR-LY_', 'ar-ly'),
('_AR-MA_', 'ar-ma'),
('_AR-OM_', 'ar-om'),
('_AR-QA_', 'ar-qa'),
('_AR-SA_', 'ar-sa'),
('_AR-SY_', 'ar-sy'),
('_AR-TN_', 'ar-tn'),
('_AR-YE_', 'ar-ye'),
('_AR_', 'ar'),
('_BE_', 'be'),
('_BG_', 'bg'),
('_CS_', 'cs'),
('_CY_', 'cy'),
('_DA_', 'da'),
('_DK_', 'da'),
('_DE-AT_', 'de-at'),
('_DE-CH_', 'de-ch'),
('_DE-LI_', 'de-li'),
('_DE-LU_', 'de-lu'),
('_DE_', 'de'),
('_DE_', 'de'),
('_DE_', 'de'),
('_EL_', 'el'),
('_EN_AU_', 'en-au'),
('_EN_BZ_', 'en-bz'),
('_EN_CA_', 'en-ca'),
('_EN_GB_', 'en-gb'),
('_EN_IE_', 'en-ie'),
('_EN_IN_', 'en-in'),
('_EN_JM_', 'en-jm'),
('_EN_NZ_', 'en-nz'),
('_EN_HK_', 'en-hk'),
('_EN_MY_', 'en-my'),
('_EN_PH_', 'en-ph'),
('_EN_SG_', 'en-sg'),
('_EN_TT_', 'en-tt'),
('_EN_US_', 'en-us'),
('_EN_ZA_', 'en-za'),
('_EN_', 'en'),
('_ES-AR_', 'es-ar'),
('_ES-BO_', 'es-bo'),
('_ES-CL_', 'es-cl'),
('_ES-CO_', 'es-co'),
('_ES-CR_', 'es-cr'),
('_ES-DO_', 'es-do'),
('_ES-EC_', 'es-ec'),
('_ES-GT_', 'es-gt'),
('_ES-HN_', 'es-hn'),
('_ES-MX_', 'es-mx'),
('_ES-NI_', 'es-ni'),
('_ES-PA_', 'es-pa'),
('_ES-PE_', 'es-pe'),
('_ES-PR_', 'es-pr'),
('_ES-PY_', 'es-py'),
('_ES-SV_', 'es-sv'),
('_ES-UY_', 'es-uy'),
('_ES-VE_', 'es-ve'),
('_ES_', 'es'),
('_ES_', 'es'),
('_ET_', 'et'),
('_EU_', 'eu'),
('_FA_', 'fa'),
('_FI_', 'fi'),
('_FIL_', 'fil'),
('_FO_', 'fo'),
('_FR_BE_', 'fr-be'),
('_FR_CA_', 'fr-ca'),
('_FR_CH_', 'fr-ch'),
('_FR_LU_', 'fr-lu'),
('_FR_', 'fr'),
('_FR_', 'fr'),
('_GA_', 'ga'),
('_GD_', 'gd'),
('_HE_', 'he'),
('_HI_', 'hi'),
('_HR_', 'hr'),
('_HU_', 'hu'),
('_ID_', 'id'),
('_IS_', 'is'),
('_IT-CH_', 'it-ch'),
('_IT_', 'it'),
('_IT_', 'it'),
('_JA_', 'ja'),
('_JP_', 'ja'),
('_JI_', 'ji'),
('_KO_', 'ko'),
('_KR_', 'ko'),
('_KU_', 'ku'),
('_LT_', 'lt'),
('_LV_', 'lv'),
('_MK_', 'mk'),
('_ML_', 'ml'),
('_MS_', 'ms'),
('_MT_', 'mt'),
('_NB_', 'nb'),
('_NL-BE_', 'nl-be'),
('_NL_', 'nl'),
('_NL_', 'nl'),
('_NN_', 'nn'),
('_NO_', 'no'),
('_PA_', 'pa'),
('_PL_', 'pl'),
('_PL_', 'pl'),
('_PT-BR_', 'pt-br'),
('_PT_', 'pt'),
('_PT_', 'pt'),
('_RM_', 'rm'),
('_RO-MD_', 'ro-md'),
('_RO_', 'ro'),
('_RU-MD_', 'ru-md'),
('_RU_', 'ru'),
('_RU_', 'ru'),
('_SB_', 'sb'),
('_SK_', 'sk'),
('_SL_', 'sl'),
('_SQ_', 'sq'),
('_SR_', 'sr'),
('_SV-FI_', 'sv-fi'),
('_SV_', 'sv'),
('_SE_', 'sv'),
('_TH_', 'th'),
('_TH_', 'th'),
('_TN_', 'tn'),
('_TR_', 'tr'),
('_TR_', 'tr'),
('_TS_', 'ts'),
('_UK_', 'uk'),
('_UR_', 'ur'),
('_VE_', 've'),
('_VI_', 'vi'),
('_XH_', 'xh'),
('_ZH-CN_', 'zh-cn'),
('_ZH_CN_', 'zh-cn'),
('_ZH-HK_', 'zh-hk'),
('_ZH_HK_', 'zh-hk'),
('_ZH-SG_', 'zh-sg'),
('_ZH-TW_', 'zh-tw'),
('_ZH_TW_', 'zh-tw'),
('_ZU_', 'zu'),
('_CA_', 'ca'),
)
class Asset(models.BaseResourceModel):
size = ndb.IntegerProperty()
build = ndb.IntegerProperty()
mimetype = ndb.StringProperty()
md5 = ndb.StringProperty()
parents = ndb.KeyProperty(repeated=True)
basename = ndb.StringProperty()
ext = ndb.StringProperty()
url = ndb.StringProperty()
icon_url = ndb.StringProperty()
num_downloads = ndb.IntegerProperty(default=0)
gcs_path = ndb.StringProperty()
gcs_thumbnail_path = ndb.StringProperty()
etag = ndb.StringProperty()
metadata = msgprop.MessageProperty(
messages.AssetMetadata, indexed_fields=['width', 'height', 'label'])
@classmethod
def process(cls, resp, gcs_path=None, gcs_thumbnail_path=None):
if '.preview' in resp['title']: # Don't store previews.
return
resource_id = resp['id']
ent = cls.get_or_instantiate(resource_id)
ent.resource_id = resource_id
ent.mimetype = resp['mimeType']
ent.size = int(resp['fileSize'])
ent.url = resp['webContentLink']
ent.icon_url = resp['iconLink']
ent.parse_title(resp['title'])
ent.md5 = resp['md5Checksum']
ent.etag = resp['etag']
if gcs_path:
ent.gcs_path = gcs_path
if gcs_thumbnail_path:
ent.gcs_thumbnail_path = gcs_thumbnail_path
ent.modified = cls.parse_datetime_string(resp['modifiedDate'])
ent.synced = datetime.datetime.now()
ent.parents = cls.generate_parent_keys(resp['parents'])
ent.basename, ent.ext = os.path.splitext(resp['title'])
ent.set_metadata(resp)
ent.put()
@classmethod
def get_group(cls, parent_key=None):
query = cls.query()
query = query.filter(cls.parents == parent_key)
ents = query.fetch()
asset_messages = [
ent.to_message() for ent in ents
if '.preview' not in ent.title]
for message in asset_messages:
if message.metadata and not message.metadata.label:
message.metadata.label = 'Standard'
folder = parent_key.get()
if folder:
folder_message = folder.to_message()
else:
folder_message = None
return folder_message, asset_messages
@classmethod
def get_by_basename(cls, basename):
query = cls.query()
query = query.filter(cls.basename == basename)
return query.get()
def set_metadata(self, resp):
metadata = messages.AssetMetadata()
# Formatted: CB_US_STD_ATTRACT_HANGING_LANDSCAPE_48x24.ext
title = resp['title']
base, ext = os.path.splitext(resp['title'])
metadata.base = base
metadata.ext = ext
# Language.
for key, value in FILENAME_IDENTIFIERS_TO_LOCALES:
if key in base:
metadata.language = value
break
# Variant.
metadata.variant = 'Standard'
for key, value in VARIANT_IDENTIFIERS:
if key in base:
metadata.variant = value
break
# Meassaging.
metadata.label = 'Standard'
for key, value in MESSAGING_IDENTIFIERS:
if key in base:
metadata.label = value
break
# Width and height.
for part in base.split('_'):
part = re.sub('[p][x]', '', part)
match = re.match('(\d*)x(\d*)', part)
if match:
width, height = match.groups()
if width and height:
metadata.width = int(width)
metadata.height = int(height)
metadata.dimensions = '{}x{}'.format(width, height)
self.metadata = metadata
@property
def media_url(self):
return DOWNLOAD_URL_FORMAT.format(
resource_id=self.resource_id,
key=CONFIG['apikey'])
@property
def thumbnail_url(self):
return '/thumbnails/{}'.format(self.resource_id)
@classmethod
def create_thumbnail_url(cls, resource_id):
return THUMBNAIL_URL_FORMAT.format(
resource_id=resource_id,
size=250)
@property
def download_url(self):
return '/assets/{}'.format(self.resource_id)
@classmethod
def search_by_downloads(cls):
query = cls.query()
query = query.filter(cls.num_downloads != 0)
query = query.order(-cls.num_downloads)
return query.fetch()
@webapp2.cached_property
def parent(self):
if self.parents:
return self.parents[0].get()
def create_blob_key(self, thumbnail=False):
if thumbnail:
return blobstore.create_gs_key('/gs{}'.format(self.gcs_thumbnail_path))
return blobstore.create_gs_key('/gs{}'.format(self.gcs_path))
def to_message(self):
message = messages.AssetMessage()
message.ident = self.ident
message.download_url = self.download_url
message.title = self.title
message.size = self.size
message.thumbnail_url = self.thumbnail_url
message.metadata = self.metadata
message.has_thumbnail = bool(self.gcs_thumbnail_path)
return message
|
|
#!/usr/bin/env python3
# dinkum/sudoku/test_puzzles.py
''' Provides a test suite of sudoku puzzles.
The class SolvedPuzzle will contain:
name of the input board
input string for the input board
constructed input Board
answer Board
string output of answer Board
all_known_puzzles is a [] of all puzzles in this module.
Some may not have a solution recorded and/or aren't currently
solvable.
all_known_solved_puzzles is a [] of all known puzzles and solutions
which are known to be solvable and have a solution recorded.
all_known_unsolved_puzzles is a [] of puzzles which can't be solved and/or
do not solution recorded
all_known_puzzles_names is a {} of all_known_puzzles. Key:name Value:SolvedPuzzle
Performs a couple of sanity checks which trigger a
failed assertion on any errors.
read/write_prior_stats() return (or write) a {} to/from a file
which is keyed by puzzle_name and the value is last written sudoku.Stats
of that puzzle, regardless of whether the puzzle is solved or not
'''
# 2019-11-26 tc Initial
# 2019-11-30 tc bug fix for cyclic import of Board
# added all_known_[un]solved_puzzles
# 2019-12-02 tc Added empty_board
# 2019-12-03 tc Added a couple of globe puzzles
# 2019-12-04 tc Added read/write_prior_solve_times_secs()
# 2019-12-09 tc read/write_prior_solve_times_secs() ==>
# read/write_prior_solve_stats()
# 2019-12-10 tc move import testing of solvability to unittests
# fixed bug in pre_solved and real_easy
# 2019-12-16 tc Solved the saturday globe
from copy import deepcopy
import pickle
import os
from dinkum.sudoku import *
from dinkum.sudoku.board import Board
from dinkum.sudoku.stats import *
class SolvedPuzzle :
''' Constructor receives spec for input_board,
spec for solution_board, and the name to use
for input board. The name for the solution_board is
<input_name>-solution.
Constructs and remembers input_board and solution_board.
'''
def __init__(self, name, desc, input_spec, solution_spec) :
''' Constructor. Inputs
name Optional Name of input board
desc Optional Description of it
input_spec [[1,3,...][2,9,0,...]....]
solution_spec ditto
Keeps a copy of it's arguments, plus
input_board Board(input_spec)
solution_name Name of solution board
solution_description Same description as input_board
solution_board Board(solution_spec)
'''
self.name = name
self.desc = desc
self.solution_name = name + "-solution"
self.input_spec = input_spec
self.input_board = Board(input_spec, name, desc)
self.solution_spec = solution_spec
self.solution_board = Board(solution_spec,
self.solution_name, self.input_board.description )
# all_known_[un]solved_puzzles are lists of all puzzles that
# are solved or unsolved. They will be combined later to
# form all_known_puzzles
all_known_solved_puzzles = []
all_known_unsolved_puzzles = []
# Each puzzle definition below must add the puzzle to
# one of these lists
# Define some puzzles
# *** empty
empty_row = [0]*RCB_SIZE
input_spec = [ deepcopy(empty_row) for i in range(RCB_SIZE)]
desc="No initial values, unsolvable"
empty = SolvedPuzzle("empty", desc, input_spec, None)
all_known_unsolved_puzzles.append(empty)
# *** pre_solved
desc= "All cells filled in initially"
input_spec = [[3, 4, 6, 1, 2, 7, 9, 5, 8],
[7, 0, 5, 6, 9, 4, 1, 3, 2],
[2, 1, 9, 3, 8, 5, 4, 6, 7],
[4, 6, 2, 5, 3, 1, 8, 7, 9],
[9, 3, 1, 2, 7, 8, 6, 4, 5],
[8, 5, 7, 9, 4, 6, 2, 1, 3],
[5, 9, 8, 4, 1, 3, 7, 2, 6],
[6, 2, 4, 7, 5, 9, 3, 8, 1],
[1, 7, 3, 8, 6, 2, 5, 9, 4]]
solution_spec= [[3, 4, 6, 1, 2, 7, 9, 5, 8],
[7, 8, 5, 6, 9, 4, 1, 3, 2],
[2, 1, 9, 3, 8, 5, 4, 6, 7],
[4, 6, 2, 5, 3, 1, 8, 7, 9],
[9, 3, 1, 2, 7, 8, 6, 4, 5],
[8, 5, 7, 9, 4, 6, 2, 1, 3],
[5, 9, 8, 4, 1, 3, 7, 2, 6],
[6, 2, 4, 7, 5, 9, 3, 8, 1],
[1, 7, 3, 8, 6, 2, 5, 9, 4]]
pre_solved = SolvedPuzzle("pre_solved", desc, input_spec, solution_spec)
all_known_solved_puzzles.append(pre_solved)
# *** real_easy
desc="only one cell to solve"
real_easy = [[0, 4, 6, 1, 2, 7, 9, 5, 8],
[7, 8, 5, 6, 9, 4, 1, 3, 2],
[2, 1, 9, 3, 0, 5, 4, 6, 7],
[4, 6, 2, 0, 3, 1, 8, 7, 9],
[9, 3, 0, 2, 7, 8, 6, 4, 5],
[8, 5, 7, 9, 4, 6, 2, 1, 3],
[5, 9, 8, 4, 0, 3, 7, 2, 6],
[6, 2, 4, 7, 5, 9, 3, 8, 1],
[1, 7, 3, 8, 6, 2, 5, 9, 4]]
real_easy_ans = [[3, 4, 6, 1, 2, 7, 9, 5, 8],
[7, 8, 5, 6, 9, 4, 1, 3, 2],
[2, 1, 9, 3, 8, 5, 4, 6, 7],
[4, 6, 2, 5, 3, 1, 8, 7, 9],
[9, 3, 1, 2, 7, 8, 6, 4, 5],
[8, 5, 7, 9, 4, 6, 2, 1, 3],
[5, 9, 8, 4, 1, 3, 7, 2, 6],
[6, 2, 4, 7, 5, 9, 3, 8, 1],
[1, 7, 3, 8, 6, 2, 5, 9, 4]]
real_easy = SolvedPuzzle("real_easy", desc, real_easy, real_easy_ans)
all_known_solved_puzzles.append(real_easy)
# ***
name="globe_mon_2019_12_02"
desc="Boston Globe mon, 2019-12-02, www.sudoku.com"
puzzle_in = '''
001 605 400
028 000 760
000 080 000
600 804 005
072 000 940
100 209 008
000 050 000
057 000 310
009 106 200
'''
puzzle_ans = '''
731 695 482
528 413 769
964 782 531
693 874 125
872 561 943
145 239 678
216 357 894
457 928 316
389 146 257
'''
puzzle = SolvedPuzzle(name, desc, puzzle_in, puzzle_ans)
all_known_solved_puzzles.append(puzzle)
# ***
name="globe_sat_2019_11_02"
desc="Boston Globe sat, 2019-11-02, www.sudoku.com"
puzzle_in = '''
001 603 000
900 047 010
000 000 700
390 025 600
000 000 000
004 360 059
003 000 000
040 170 006
000 206 500
'''
puzzle_ans = '''
781 653 942
962 847 315
435 912 768
398 425 671
156 789 423
274 361 859
623 594 187
549 178 236
817 236 594
'''
puzzle = SolvedPuzzle(name, desc, puzzle_in, puzzle_ans)
all_known_solved_puzzles.append(puzzle)
# ***
name="kato_puzzle"
desc="Sample in https://www.codewars.com/kata/hard-sudoku-solver-1/train/python"
puzzle_in = [[0, 0, 6, 1, 0, 0, 0, 0, 8],
[0, 8, 0, 0, 9, 0, 0, 3, 0],
[2, 0, 0, 0, 0, 5, 4, 0, 0],
[4, 0, 0, 0, 0, 1, 8, 0, 0],
[0, 3, 0, 0, 7, 0, 0, 4, 0],
[0, 0, 7, 9, 0, 0, 0, 0, 3],
[0, 0, 8, 4, 0, 0, 0, 0, 6],
[0, 2, 0, 0, 5, 0, 0, 8, 0],
[1, 0, 0, 0, 0, 2, 5, 0, 0]]
puzzle_ans = [[3, 4, 6, 1, 2, 7, 9, 5, 8],
[7, 8, 5, 6, 9, 4, 1, 3, 2],
[2, 1, 9, 3, 8, 5, 4, 6, 7],
[4, 6, 2, 5, 3, 1, 8, 7, 9],
[9, 3, 1, 2, 7, 8, 6, 4, 5],
[8, 5, 7, 9, 4, 6, 2, 1, 3],
[5, 9, 8, 4, 1, 3, 7, 2, 6],
[6, 2, 4, 7, 5, 9, 3, 8, 1],
[1, 7, 3, 8, 6, 2, 5, 9, 4]]
puzzle = SolvedPuzzle(name, desc, puzzle_in, puzzle_ans)
all_known_unsolved_puzzles.append(puzzle) # Can't solve it yet
# All the puzzles we know about
all_known_puzzles = all_known_solved_puzzles + all_known_unsolved_puzzles
# Make a dictionary of names
all_known_puzzle_names = {}
for sp in all_known_puzzles :
all_known_puzzle_names[sp.name] = sp
# Some standalone functions
# Where we pickle/unpickle the {}
def prior_stats_filename() :
''' returns the filename where statistics are
stored on disk.
'''
# We write the file in the same directory we live in
# at the time of this writing it was
# ..../dinkum/sudoku/test_data
dir = os.path.dirname(__file__) # .../dinkum/sudoku/test_data
file = os.path.join(dir, "prior_solve_stats.pickled")
return file
def read_prior_stats() :
''' Read and return {} of board.solved_stats from file
and return it. Keyed by puzzle_name, value is
sudoku.Stats.
These are the stats last written by write_prior_solve_stats()
'''
stats = {} # in case of file not found
try:
with open(prior_stats_filename(), "rb") as pickle_file :
stats = pickle.load(pickle_file)
except FileNotFoundError:
pass # We'll just return the initial empty dictionary
return stats
def write_prior_stats(stats) :
''' Writes stats to a disk file.
It can be read via read_prior_stats()
Current implementation pickles it.
'''
pickle.dump(stats, open(prior_stats_filename(), "wb"))
# Test code
import unittest
class Test_test_puzzles(unittest.TestCase) :
# Much of the test code is run in sanity check
# above at import time with an assertion failure
def test_simple_construction(self) :
name = "whatever"
desc = "who knows?"
sp = SolvedPuzzle(name, desc, input_spec, solution_spec)
self.assertEqual (name, sp.name )
self.assertEqual (name+"-solution", sp.solution_name)
self.assertEqual (desc, sp.input_board.description)
self.assertEqual (desc, sp.solution_board.description)
self.assertEqual (input_spec, sp.input_spec )
self.assertEqual (solution_spec, sp.solution_spec )
def test_all_known_puzzle_names(self) :
# Make sure every puzzle is in the dictionary
for sp in all_known_puzzles :
self.assertIn (sp.name, all_known_puzzle_names)
self.assertIs (sp, all_known_puzzle_names[sp.name])
def test_solvability(self) :
# Sanity checks
for sp in all_known_solved_puzzles :
# All solved puzzles must have solution
self.assertTrue (sp.solution_board, "Board %s in all_known_solved_puzzles, but has no solution")
# Make sure input cells which are set have
# the same value in the solution
self.assertTrue( sp.input_board.is_subset_of( sp.solution_board))
# Verify we can solve all the solvable puzzles
for sp in all_known_solved_puzzles :
# Verify an answer is supplied
self.assertTrue (sp.solution_spec, "%s:No solution_spec" % sp.solution_spec)
self.assertTrue (sp.solution_board, "%s:No solution_board" % sp.solution_board)
our_solution = sp.input_board.solve()
self.assertTrue (our_solution, "%s: Cannot solve a solvable puzzle" % sp.name)
self.assertTrue (our_solution == sp.solution_board, "%s: solutions differ" % sp.name)
# Verify we can't solvable the unsolvable
for sp in all_known_unsolved_puzzles :
our_solution = sp.input_board.solve()
if our_solution :
# we just solved an unsolvable puzzle
# print out it's value so they can edit in the solution
print("\nboard_name:", sp.input_board.name )
print (our_solution)
self.assertIsNone (our_solution, "%s: we can solve an unsolvable puzzle")
if __name__ == "__main__" :
# Run the unittests
unittest.main()
|
|
"""
Cycler
======
Cycling through combinations of values, producing dictionaries.
You can add cyclers::
from cycler import cycler
cc = (cycler(color=list('rgb')) +
cycler(linestyle=['-', '--', '-.']))
for d in cc:
print(d)
Results in::
{'color': 'r', 'linestyle': '-'}
{'color': 'g', 'linestyle': '--'}
{'color': 'b', 'linestyle': '-.'}
You can multiply cyclers::
from cycler import cycler
cc = (cycler(color=list('rgb')) *
cycler(linestyle=['-', '--', '-.']))
for d in cc:
print(d)
Results in::
{'color': 'r', 'linestyle': '-'}
{'color': 'r', 'linestyle': '--'}
{'color': 'r', 'linestyle': '-.'}
{'color': 'g', 'linestyle': '-'}
{'color': 'g', 'linestyle': '--'}
{'color': 'g', 'linestyle': '-.'}
{'color': 'b', 'linestyle': '-'}
{'color': 'b', 'linestyle': '--'}
{'color': 'b', 'linestyle': '-.'}
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from itertools import product, cycle
from six.moves import zip, reduce
from operator import mul, add
import copy
__version__ = '0.10.0'
def _process_keys(left, right):
"""
Helper function to compose cycler keys
Parameters
----------
left, right : iterable of dictionaries or None
The cyclers to be composed
Returns
-------
keys : set
The keys in the composition of the two cyclers
"""
l_peek = next(iter(left)) if left is not None else {}
r_peek = next(iter(right)) if right is not None else {}
l_key = set(l_peek.keys())
r_key = set(r_peek.keys())
if l_key & r_key:
raise ValueError("Can not compose overlapping cycles")
return l_key | r_key
class Cycler(object):
"""
Composable cycles
This class has compositions methods:
``+``
for 'inner' products (zip)
``+=``
in-place ``+``
``*``
for outer products (itertools.product) and integer multiplication
``*=``
in-place ``*``
and supports basic slicing via ``[]``
Parameters
----------
left : Cycler or None
The 'left' cycler
right : Cycler or None
The 'right' cycler
op : func or None
Function which composes the 'left' and 'right' cyclers.
"""
def __call__(self):
return cycle(self)
def __init__(self, left, right=None, op=None):
"""Semi-private init
Do not use this directly, use `cycler` function instead.
"""
if isinstance(left, Cycler):
self._left = Cycler(left._left, left._right, left._op)
elif left is not None:
# Need to copy the dictionary or else that will be a residual
# mutable that could lead to strange errors
self._left = [copy.copy(v) for v in left]
else:
self._left = None
if isinstance(right, Cycler):
self._right = Cycler(right._left, right._right, right._op)
elif right is not None:
# Need to copy the dictionary or else that will be a residual
# mutable that could lead to strange errors
self._right = [copy.copy(v) for v in right]
else:
self._right = None
self._keys = _process_keys(self._left, self._right)
self._op = op
@property
def keys(self):
"""
The keys this Cycler knows about
"""
return set(self._keys)
def change_key(self, old, new):
"""
Change a key in this cycler to a new name.
Modification is performed in-place.
Does nothing if the old key is the same as the new key.
Raises a ValueError if the new key is already a key.
Raises a KeyError if the old key isn't a key.
"""
if old == new:
return
if new in self._keys:
raise ValueError("Can't replace %s with %s, %s is already a key" %
(old, new, new))
if old not in self._keys:
raise KeyError("Can't replace %s with %s, %s is not a key" %
(old, new, old))
self._keys.remove(old)
self._keys.add(new)
if self._right is not None and old in self._right.keys:
self._right.change_key(old, new)
# self._left should always be non-None
# if self._keys is non-empty.
elif isinstance(self._left, Cycler):
self._left.change_key(old, new)
else:
# It should be completely safe at this point to
# assume that the old key can be found in each
# iteration.
self._left = [{new: entry[old]} for entry in self._left]
def _compose(self):
"""
Compose the 'left' and 'right' components of this cycle
with the proper operation (zip or product as of now)
"""
for a, b in self._op(self._left, self._right):
out = dict()
out.update(a)
out.update(b)
yield out
@classmethod
def _from_iter(cls, label, itr):
"""
Class method to create 'base' Cycler objects
that do not have a 'right' or 'op' and for which
the 'left' object is not another Cycler.
Parameters
----------
label : str
The property key.
itr : iterable
Finite length iterable of the property values.
Returns
-------
cycler : Cycler
New 'base' `Cycler`
"""
ret = cls(None)
ret._left = list({label: v} for v in itr)
ret._keys = set([label])
return ret
def __getitem__(self, key):
# TODO : maybe add numpy style fancy slicing
if isinstance(key, slice):
trans = self.by_key()
return reduce(add, (_cycler(k, v[key])
for k, v in six.iteritems(trans)))
else:
raise ValueError("Can only use slices with Cycler.__getitem__")
def __iter__(self):
if self._right is None:
return iter(dict(l) for l in self._left)
return self._compose()
def __add__(self, other):
"""
Pair-wise combine two equal length cycles (zip)
Parameters
----------
other : Cycler
The second Cycler
"""
if len(self) != len(other):
raise ValueError("Can only add equal length cycles, "
"not {0} and {1}".format(len(self), len(other)))
return Cycler(self, other, zip)
def __mul__(self, other):
"""
Outer product of two cycles (`itertools.product`) or integer
multiplication.
Parameters
----------
other : Cycler or int
The second Cycler or integer
"""
if isinstance(other, Cycler):
return Cycler(self, other, product)
elif isinstance(other, int):
trans = self.by_key()
return reduce(add, (_cycler(k, v*other)
for k, v in six.iteritems(trans)))
else:
return NotImplemented
def __rmul__(self, other):
return self * other
def __len__(self):
op_dict = {zip: min, product: mul}
if self._right is None:
return len(self._left)
l_len = len(self._left)
r_len = len(self._right)
return op_dict[self._op](l_len, r_len)
def __iadd__(self, other):
"""
In-place pair-wise combine two equal length cycles (zip)
Parameters
----------
other : Cycler
The second Cycler
"""
if not isinstance(other, Cycler):
raise TypeError("Cannot += with a non-Cycler object")
# True shallow copy of self is fine since this is in-place
old_self = copy.copy(self)
self._keys = _process_keys(old_self, other)
self._left = old_self
self._op = zip
self._right = Cycler(other._left, other._right, other._op)
return self
def __imul__(self, other):
"""
In-place outer product of two cycles (`itertools.product`)
Parameters
----------
other : Cycler
The second Cycler
"""
if not isinstance(other, Cycler):
raise TypeError("Cannot *= with a non-Cycler object")
# True shallow copy of self is fine since this is in-place
old_self = copy.copy(self)
self._keys = _process_keys(old_self, other)
self._left = old_self
self._op = product
self._right = Cycler(other._left, other._right, other._op)
return self
def __eq__(self, other):
"""
Check equality
"""
if len(self) != len(other):
return False
if self.keys ^ other.keys:
return False
return all(a == b for a, b in zip(self, other))
def __repr__(self):
op_map = {zip: '+', product: '*'}
if self._right is None:
lab = self.keys.pop()
itr = list(v[lab] for v in self)
return "cycler({lab!r}, {itr!r})".format(lab=lab, itr=itr)
else:
op = op_map.get(self._op, '?')
msg = "({left!r} {op} {right!r})"
return msg.format(left=self._left, op=op, right=self._right)
def _repr_html_(self):
# an table showing the value of each key through a full cycle
output = "<table>"
sorted_keys = sorted(self.keys, key=repr)
for key in sorted_keys:
output += "<th>{key!r}</th>".format(key=key)
for d in iter(self):
output += "<tr>"
for k in sorted_keys:
output += "<td>{val!r}</td>".format(val=d[k])
output += "</tr>"
output += "</table>"
return output
def by_key(self):
"""Values by key
This returns the transposed values of the cycler. Iterating
over a `Cycler` yields dicts with a single value for each key,
this method returns a `dict` of `list` which are the values
for the given key.
The returned value can be used to create an equivalent `Cycler`
using only `+`.
Returns
-------
transpose : dict
dict of lists of the values for each key.
"""
# TODO : sort out if this is a bottle neck, if there is a better way
# and if we care.
keys = self.keys
# change this to dict comprehension when drop 2.6
out = dict((k, list()) for k in keys)
for d in self:
for k in keys:
out[k].append(d[k])
return out
# for back compatibility
_transpose = by_key
def simplify(self):
"""Simplify the Cycler
Returned as a composition using only sums (no multiplications)
Returns
-------
simple : Cycler
An equivalent cycler using only summation"""
# TODO: sort out if it is worth the effort to make sure this is
# balanced. Currently it is is
# (((a + b) + c) + d) vs
# ((a + b) + (c + d))
# I would believe that there is some performance implications
trans = self.by_key()
return reduce(add, (_cycler(k, v) for k, v in six.iteritems(trans)))
def concat(self, other):
"""Concatenate this cycler and an other.
The keys must match exactly.
This returns a single Cycler which is equivalent to
`itertools.chain(self, other)`
Examples
--------
>>> num = cycler('a', range(3))
>>> let = cycler('a', 'abc')
>>> num.concat(let)
cycler('a', [0, 1, 2, 'a', 'b', 'c'])
Parameters
----------
other : `Cycler`
The `Cycler` to concatenate to this one.
Returns
-------
ret : `Cycler`
The concatenated `Cycler`
"""
return concat(self, other)
def concat(left, right):
"""Concatenate two cyclers.
The keys must match exactly.
This returns a single Cycler which is equivalent to
`itertools.chain(left, right)`
Examples
--------
>>> num = cycler('a', range(3))
>>> let = cycler('a', 'abc')
>>> num.concat(let)
cycler('a', [0, 1, 2, 'a', 'b', 'c'])
Parameters
----------
left, right : `Cycler`
The two `Cycler` instances to concatenate
Returns
-------
ret : `Cycler`
The concatenated `Cycler`
"""
if left.keys != right.keys:
msg = '\n\t'.join(["Keys do not match:",
"Intersection: {both!r}",
"Disjoint: {just_one!r}"]).format(
both=left.keys & right.keys,
just_one=left.keys ^ right.keys)
raise ValueError(msg)
_l = left.by_key()
_r = right.by_key()
return reduce(add, (_cycler(k, _l[k] + _r[k]) for k in left.keys))
def cycler(*args, **kwargs):
"""
Create a new `Cycler` object from a single positional argument,
a pair of positional arguments, or the combination of keyword arguments.
cycler(arg)
cycler(label1=itr1[, label2=iter2[, ...]])
cycler(label, itr)
Form 1 simply copies a given `Cycler` object.
Form 2 composes a `Cycler` as an inner product of the
pairs of keyword arguments. In other words, all of the
iterables are cycled simultaneously, as if through zip().
Form 3 creates a `Cycler` from a label and an iterable.
This is useful for when the label cannot be a keyword argument
(e.g., an integer or a name that has a space in it).
Parameters
----------
arg : Cycler
Copy constructor for Cycler (does a shallow copy of iterables).
label : name
The property key. In the 2-arg form of the function,
the label can be any hashable object. In the keyword argument
form of the function, it must be a valid python identifier.
itr : iterable
Finite length iterable of the property values.
Can be a single-property `Cycler` that would
be like a key change, but as a shallow copy.
Returns
-------
cycler : Cycler
New `Cycler` for the given property
"""
if args and kwargs:
raise TypeError("cyl() can only accept positional OR keyword "
"arguments -- not both.")
if len(args) == 1:
if not isinstance(args[0], Cycler):
raise TypeError("If only one positional argument given, it must "
" be a Cycler instance.")
return Cycler(args[0])
elif len(args) == 2:
return _cycler(*args)
elif len(args) > 2:
raise TypeError("Only a single Cycler can be accepted as the lone "
"positional argument. Use keyword arguments instead.")
if kwargs:
return reduce(add, (_cycler(k, v) for k, v in six.iteritems(kwargs)))
raise TypeError("Must have at least a positional OR keyword arguments")
def _cycler(label, itr):
"""
Create a new `Cycler` object from a property name and
iterable of values.
Parameters
----------
label : hashable
The property key.
itr : iterable
Finite length iterable of the property values.
Returns
-------
cycler : Cycler
New `Cycler` for the given property
"""
if isinstance(itr, Cycler):
keys = itr.keys
if len(keys) != 1:
msg = "Can not create Cycler from a multi-property Cycler"
raise ValueError(msg)
lab = keys.pop()
# Doesn't need to be a new list because
# _from_iter() will be creating that new list anyway.
itr = (v[lab] for v in itr)
return Cycler._from_iter(label, itr)
|
|
"""
Base class for freezing scripts into executables.
"""
import datetime
import distutils.sysconfig
import imp
import marshal
import os
import shutil
import socket
import stat
import struct
import sys
import time
import zipfile
import cx_Freeze
__all__ = [ "ConfigError", "ConstantsModule", "Executable", "Freezer" ]
EXTENSION_LOADER_SOURCE = \
"""
def __bootstrap__():
sys = __import__("sys")
os = __import__("os")
imp = __import__("imp")
global __bootstrap__, __loader__
__loader__ = None; del __bootstrap__, __loader__
found = False
for p in sys.path:
if not os.path.isdir(p):
continue
f = os.path.join(p, "%s")
if not os.path.exists(f):
continue
m = imp.load_dynamic(__name__, f)
import sys
sys.modules[__name__] = m
found = True
break
if not found:
del sys.modules[__name__]
raise ImportError("No module named %%s" %% __name__)
__bootstrap__()
"""
MSVCR_MANIFEST_TEMPLATE = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<noInheritable/>
<assemblyIdentity
type="win32"
name="Microsoft.VC90.CRT"
version="9.0.21022.8"
processorArchitecture="{PROC_ARCH}"
publicKeyToken="1fc8b3b9a1e18e3b"/>
<file name="MSVCR90.DLL"/>
<file name="MSVCM90.DLL"/>
<file name="MSVCP90.DLL"/>
</assembly>
"""
class Freezer(object):
def __init__(self, executables, constantsModules = [], includes = [],
excludes = [], packages = [], replacePaths = [], compress = None,
optimizeFlag = 0, copyDependentFiles = None, initScript = None,
base = None, path = None, createLibraryZip = None,
appendScriptToExe = None, appendScriptToLibrary = None,
targetDir = None, binIncludes = [], binExcludes = [],
binPathIncludes = [], binPathExcludes = [], icon = None,
includeFiles = [], zipIncludes = [], silent = False,
namespacePackages = [], metadata = None,
includeMSVCR = False):
self.executables = list(executables)
self.constantsModules = list(constantsModules)
self.includes = list(includes)
self.excludes = list(excludes)
self.packages = list(packages)
self.namespacePackages = list(namespacePackages)
self.replacePaths = list(replacePaths)
self.compress = compress
self.optimizeFlag = optimizeFlag
self.copyDependentFiles = copyDependentFiles
self.initScript = initScript
self.base = base
self.path = path
self.createLibraryZip = createLibraryZip
self.includeMSVCR = includeMSVCR
self.appendScriptToExe = appendScriptToExe
self.appendScriptToLibrary = appendScriptToLibrary
self.targetDir = targetDir
self.binIncludes = [os.path.normcase(n) \
for n in self._GetDefaultBinIncludes() + binIncludes]
self.binExcludes = [os.path.normcase(n) \
for n in self._GetDefaultBinExcludes() + binExcludes]
self.binPathIncludes = [os.path.normcase(n) for n in binPathIncludes]
self.binPathExcludes = [os.path.normcase(n) \
for n in self._GetDefaultBinPathExcludes() + binPathExcludes]
self.icon = icon
self.includeFiles = list(includeFiles)
self.includeFiles = self._ProcessPathSpecs(includeFiles)
self.zipIncludes = self._ProcessPathSpecs(zipIncludes)
self.silent = silent
self.metadata = metadata
self._VerifyConfiguration()
def _AddVersionResource(self, fileName):
try:
from win32verstamp import stamp
except:
print("*** WARNING *** unable to create version resource")
print("install pywin32 extensions first")
return
versionInfo = VersionInfo(self.metadata.version,
comments = self.metadata.long_description,
description = self.metadata.description,
company = self.metadata.author,
product = self.metadata.name)
stamp(fileName, versionInfo)
def _CopyFile(self, source, target, copyDependentFiles = False,
includeMode = False):
normalizedSource = os.path.normcase(os.path.normpath(source))
normalizedTarget = os.path.normcase(os.path.normpath(target))
if normalizedTarget in self.filesCopied:
return
if normalizedSource == normalizedTarget:
return
self._RemoveFile(target)
targetDir = os.path.dirname(target)
self._CreateDirectory(targetDir)
if not self.silent:
sys.stdout.write("copying %s -> %s\n" % (source, target))
shutil.copyfile(source, target)
shutil.copystat(source, target)
if includeMode:
shutil.copymode(source, target)
self.filesCopied[normalizedTarget] = None
if copyDependentFiles:
for source in self._GetDependentFiles(source):
target = os.path.join(targetDir, os.path.basename(source))
self._CopyFile(source, target, copyDependentFiles)
def _CreateDirectory(self, path):
if not os.path.isdir(path):
if not self.silent:
sys.stdout.write("creating directory %s\n" % path)
os.makedirs(path)
def _FreezeExecutable(self, exe):
if self.createLibraryZip:
finder = self.finder
else:
finder = self._GetModuleFinder(exe)
if exe.script is None:
scriptModule = None
else:
scriptModule = finder.IncludeFile(exe.script, exe.moduleName)
self._CopyFile(exe.base, exe.targetName, exe.copyDependentFiles,
includeMode = True)
if self.includeMSVCR:
self._IncludeMSVCR(exe)
if exe.icon is not None:
if sys.platform == "win32":
import cx_Freeze.util
cx_Freeze.util.AddIcon(exe.targetName, exe.icon)
else:
targetName = os.path.join(os.path.dirname(exe.targetName),
os.path.basename(exe.icon))
self._CopyFile(exe.icon, targetName,
copyDependentFiles = False)
if not os.access(exe.targetName, os.W_OK):
mode = os.stat(exe.targetName).st_mode
os.chmod(exe.targetName, mode | stat.S_IWUSR)
if self.metadata is not None and sys.platform == "win32":
self._AddVersionResource(exe.targetName)
if not exe.appendScriptToLibrary:
if exe.appendScriptToExe:
fileName = exe.targetName
else:
baseFileName, ext = os.path.splitext(exe.targetName)
fileName = baseFileName + ".zip"
self._RemoveFile(fileName)
if not self.createLibraryZip and exe.copyDependentFiles:
scriptModule = None
self._WriteModules(fileName, exe.initScript, finder, exe.compress,
exe.copyDependentFiles, scriptModule)
def _GetBaseFileName(self, argsSource = None):
if argsSource is None:
argsSource = self
name = argsSource.base
if name is None:
if argsSource.copyDependentFiles:
name = "Console"
else:
name = "ConsoleKeepPath"
ext = ".exe" if sys.platform == "win32" else ""
argsSource.base = self._GetFileName("bases", name, ext)
if argsSource.base is None:
raise ConfigError("no base named %s", name)
def _GetDefaultBinExcludes(self):
"""Return the file names of libraries that need not be included because
they would normally be expected to be found on the target system or
because they are part of a package which requires independent
installation anyway."""
if sys.platform == "win32":
return ["comctl32.dll", "oci.dll", "cx_Logging.pyd"]
else:
return ["libclntsh.so", "libwtc9.so"]
def _GetDefaultBinIncludes(self):
"""Return the file names of libraries which must be included for the
frozen executable to work."""
if sys.platform == "win32":
pythonDll = "python%s%s.dll" % sys.version_info[:2]
return [pythonDll, "gdiplus.dll", "mfc71.dll", "msvcp71.dll",
"msvcr71.dll"]
else:
soName = distutils.sysconfig.get_config_var("INSTSONAME")
if soName is None:
return []
pythonSharedLib = self._RemoveVersionNumbers(soName)
return [pythonSharedLib]
def _GetDefaultBinPathExcludes(self):
"""Return the paths of directories which contain files that should not
be included, generally because they contain standard system
libraries."""
if sys.platform == "win32":
import cx_Freeze.util
systemDir = cx_Freeze.util.GetSystemDir()
windowsDir = cx_Freeze.util.GetWindowsDir()
return [windowsDir, systemDir, os.path.join(windowsDir, "WinSxS")]
elif sys.platform == "darwin":
return ["/lib", "/usr/lib", "/System/Library/Frameworks"]
else:
return ["/lib", "/lib32", "/lib64", "/usr/lib", "/usr/lib32",
"/usr/lib64"]
def _GetDependentFiles(self, path):
"""Return the file's dependencies using platform-specific tools (the
imagehlp library on Windows, otool on Mac OS X and ldd on Linux);
limit this list by the exclusion lists as needed"""
dependentFiles = self.dependentFiles.get(path)
if dependentFiles is None:
if sys.platform == "win32":
origPath = os.environ["PATH"]
os.environ["PATH"] = origPath + os.pathsep + \
os.pathsep.join(sys.path)
import cx_Freeze.util
dependentFiles = cx_Freeze.util.GetDependentFiles(path)
os.environ["PATH"] = origPath
else:
dependentFiles = []
if sys.platform == "darwin":
command = 'otool -L "%s"' % path
splitString = " (compatibility"
dependentFileIndex = 0
else:
command = 'ldd "%s"' % path
splitString = " => "
dependentFileIndex = 1
for line in os.popen(command):
parts = line.expandtabs().strip().split(splitString)
if len(parts) != 2:
continue
dependentFile = parts[dependentFileIndex].strip()
if dependentFile in ("not found", "(file not found)"):
fileName = parts[0]
if fileName not in self.linkerWarnings:
self.linkerWarnings[fileName] = None
message = "WARNING: cannot find %s\n" % fileName
sys.stdout.write(message)
continue
if dependentFile.startswith("("):
continue
pos = dependentFile.find(" (")
if pos >= 0:
dependentFile = dependentFile[:pos].strip()
if dependentFile:
dependentFiles.append(dependentFile)
dependentFiles = self.dependentFiles[path] = \
[f for f in dependentFiles if self._ShouldCopyFile(f)]
return dependentFiles
def _GetFileName(self, dirName, name, ext):
if os.path.isabs(name):
return name
name = os.path.normcase(name)
fullDir = os.path.join(os.path.dirname(cx_Freeze.__file__), dirName)
if os.path.isdir(fullDir):
for fileName in os.listdir(fullDir):
checkName, checkExt = \
os.path.splitext(os.path.normcase(fileName))
if name == checkName and ext == checkExt:
return os.path.join(fullDir, fileName)
def _GetInitScriptFileName(self, argsSource = None):
if argsSource is None:
argsSource = self
name = argsSource.initScript
if name is None:
if argsSource.copyDependentFiles:
name = "Console"
else:
name = "ConsoleKeepPath"
if sys.version_info[0] >= 3:
name += "3"
argsSource.initScript = self._GetFileName("initscripts", name, ".py")
if argsSource.initScript is None:
raise ConfigError("no initscript named %s", name)
def _GetModuleFinder(self, argsSource = None):
if argsSource is None:
argsSource = self
finder = cx_Freeze.ModuleFinder(self.includeFiles, argsSource.excludes,
argsSource.path, argsSource.replacePaths,
argsSource.copyDependentFiles, compress = argsSource.compress)
for name in argsSource.namespacePackages:
package = finder.IncludeModule(name, namespace = True)
package.ExtendPath()
for name in argsSource.includes:
finder.IncludeModule(name)
for name in argsSource.packages:
finder.IncludePackage(name)
return finder
def _IncludeMSVCR(self, exe):
msvcRuntimeDll = None
targetDir = os.path.dirname(exe.targetName)
for fullName in self.filesCopied:
path, name = os.path.split(os.path.normcase(fullName))
if name.startswith("msvcr") and name.endswith(".dll"):
msvcRuntimeDll = name
for otherName in [name.replace("r", c) for c in "mp"]:
sourceName = os.path.join(self.msvcRuntimeDir, otherName)
if not os.path.exists(sourceName):
continue
targetName = os.path.join(targetDir, otherName)
self._CopyFile(sourceName, targetName)
break
if msvcRuntimeDll is not None and msvcRuntimeDll == "msvcr90.dll":
if struct.calcsize("P") == 4:
arch = "x86"
else:
arch = "amd64"
manifest = MSVCR_MANIFEST_TEMPLATE.strip().replace("{PROC_ARCH}",
arch)
fileName = os.path.join(targetDir, "Microsoft.VC90.CRT.manifest")
sys.stdout.write("creating %s\n" % fileName)
open(fileName, "w").write(manifest)
def _PrintReport(self, fileName, modules):
sys.stdout.write("writing zip file %s\n\n" % fileName)
sys.stdout.write(" %-25s %s\n" % ("Name", "File"))
sys.stdout.write(" %-25s %s\n" % ("----", "----"))
for module in modules:
if module.path:
sys.stdout.write("P")
else:
sys.stdout.write("m")
sys.stdout.write(" %-25s %s\n" % (module.name, module.file or ""))
sys.stdout.write("\n")
def _ProcessPathSpecs(self, specs):
processedSpecs = []
for spec in specs:
if not isinstance(spec, (list, tuple)):
source = target = spec
elif len(spec) != 2:
raise ConfigError("path spec must be a list or tuple of "
"length two")
else:
source, target = spec
source = os.path.normpath(source)
if not target:
dirName, target = os.path.split(source)
elif os.path.isabs(target):
raise ConfigError("target path for include file may not be "
"an absolute path")
processedSpecs.append((source, target))
return processedSpecs
def _RemoveFile(self, path):
if os.path.exists(path):
os.chmod(path, stat.S_IWRITE)
os.remove(path)
def _RemoveVersionNumbers(self, libName):
tweaked = False
parts = libName.split(".")
while parts:
if not parts[-1].isdigit():
break
parts.pop(-1)
tweaked = True
if tweaked:
libName = ".".join(parts)
return libName
def _ShouldCopyFile(self, path):
"""Return true if the file should be copied to the target machine. This
is done by checking the binPathIncludes, binPathExcludes,
binIncludes and binExcludes configuration variables using first the
full file name, then just the base file name, then the file name
without any version numbers.
Files are included unless specifically excluded but inclusions take
precedence over exclusions."""
# check for C runtime, if desired
path = os.path.normcase(path)
dirName, fileName = os.path.split(path)
if fileName.startswith("msvcr") and fileName.endswith(".dll"):
self.msvcRuntimeDir = dirName
return self.includeMSVCR
# check the full path
if path in self.binIncludes:
return True
if path in self.binExcludes:
return False
# check the file name by itself (with any included version numbers)
if fileName in self.binIncludes:
return True
if fileName in self.binExcludes:
return False
# check the file name by itself (version numbers removed)
name = self._RemoveVersionNumbers(fileName)
if name in self.binIncludes:
return True
if name in self.binExcludes:
return False
# check the path for inclusion/exclusion
for path in self.binPathIncludes:
if dirName.startswith(path):
return True
for path in self.binPathExcludes:
if dirName.startswith(path):
return False
return True
def _VerifyCanAppendToLibrary(self):
if not self.createLibraryZip:
raise ConfigError("script cannot be appended to library zip if "
"one is not being created")
def _VerifyConfiguration(self):
if self.compress is None:
self.compress = True
if self.copyDependentFiles is None:
self.copyDependentFiles = True
if self.createLibraryZip is None:
self.createLibraryZip = True
if self.appendScriptToExe is None:
self.appendScriptToExe = False
if self.appendScriptToLibrary is None:
self.appendScriptToLibrary = \
self.createLibraryZip and not self.appendScriptToExe
if self.targetDir is None:
self.targetDir = os.path.abspath("dist")
self._GetInitScriptFileName()
self._GetBaseFileName()
if self.path is None:
self.path = sys.path
if self.appendScriptToLibrary:
self._VerifyCanAppendToLibrary()
for sourceFileName, targetFileName in \
self.includeFiles + self.zipIncludes:
if not os.path.exists(sourceFileName):
raise ConfigError("cannot find file/directory named %s",
sourceFileName)
if os.path.isabs(targetFileName):
raise ConfigError("target file/directory cannot be absolute")
for executable in self.executables:
executable._VerifyConfiguration(self)
def _WriteModules(self, fileName, initScript, finder, compress,
copyDependentFiles, scriptModule = None):
initModule = finder.IncludeFile(initScript, "cx_Freeze__init__")
if scriptModule is None:
for module in self.constantsModules:
module.Create(finder)
modules = [m for m in finder.modules \
if m.name not in self.excludeModules]
else:
modules = [initModule, scriptModule]
self.excludeModules[initModule.name] = None
self.excludeModules[scriptModule.name] = None
itemsToSort = [(m.name, m) for m in modules]
itemsToSort.sort()
modules = [m for n, m in itemsToSort]
if not self.silent:
self._PrintReport(fileName, modules)
if scriptModule is None:
finder.ReportMissingModules()
targetDir = os.path.dirname(fileName)
self._CreateDirectory(targetDir)
filesToCopy = []
if os.path.exists(fileName):
mode = "a"
else:
mode = "w"
outFile = zipfile.PyZipFile(fileName, mode, zipfile.ZIP_DEFLATED)
for module in modules:
if module.code is None and module.file is not None:
fileName = os.path.basename(module.file)
baseFileName, ext = os.path.splitext(fileName)
if baseFileName != module.name and module.name != "zlib":
if "." in module.name:
fileName = module.name + ext
generatedFileName = "ExtensionLoader_%s.py" % \
module.name.replace(".", "_")
module.code = compile(EXTENSION_LOADER_SOURCE % fileName,
generatedFileName, "exec")
target = os.path.join(targetDir, fileName)
filesToCopy.append((module, target))
if module.code is None:
continue
fileName = "/".join(module.name.split("."))
if module.path:
fileName += "/__init__"
if module.file is not None and os.path.exists(module.file):
mtime = os.stat(module.file).st_mtime
else:
mtime = time.time()
zipTime = time.localtime(mtime)[:6]
# starting with Python 3.3 the pyc file format contains the source
# size; it is not actually used for anything except determining if
# the file is up to date so we can safely set this value to zero
if sys.version_info[:2] < (3, 3):
header = imp.get_magic() + struct.pack("<i", int(mtime))
else:
header = imp.get_magic() + struct.pack("<ii", int(mtime), 0)
data = header + marshal.dumps(module.code)
zinfo = zipfile.ZipInfo(fileName + ".pyc", zipTime)
if compress:
zinfo.compress_type = zipfile.ZIP_DEFLATED
outFile.writestr(zinfo, data)
for sourceFileName, targetFileName in self.zipIncludes:
outFile.write(sourceFileName, targetFileName)
outFile.close()
origPath = os.environ["PATH"]
for module, target in filesToCopy:
try:
if module.parent is not None:
path = os.pathsep.join([origPath] + module.parent.path)
os.environ["PATH"] = path
self._CopyFile(module.file, target, copyDependentFiles)
finally:
os.environ["PATH"] = origPath
def Freeze(self):
self.finder = None
self.excludeModules = {}
self.dependentFiles = {}
self.filesCopied = {}
self.linkerWarnings = {}
self.msvcRuntimeDir = None
import cx_Freeze.util
cx_Freeze.util.SetOptimizeFlag(self.optimizeFlag)
if self.createLibraryZip:
self.finder = self._GetModuleFinder()
for executable in self.executables:
self._FreezeExecutable(executable)
if self.createLibraryZip:
fileName = os.path.join(self.targetDir, "library.zip")
self._RemoveFile(fileName)
self._WriteModules(fileName, self.initScript, self.finder,
self.compress, self.copyDependentFiles)
for sourceFileName, targetFileName in self.includeFiles:
if os.path.isdir(sourceFileName):
for path, dirNames, fileNames in os.walk(sourceFileName):
shortPath = path[len(sourceFileName) + 1:]
if ".svn" in dirNames:
dirNames.remove(".svn")
if "CVS" in dirNames:
dirNames.remove("CVS")
fullTargetDir = os.path.join(self.targetDir,
targetFileName, shortPath)
self._CreateDirectory(fullTargetDir)
for fileName in fileNames:
fullSourceName = os.path.join(path, fileName)
fullTargetName = os.path.join(fullTargetDir, fileName)
self._CopyFile(fullSourceName, fullTargetName,
copyDependentFiles = False)
else:
fullName = os.path.join(self.targetDir, targetFileName)
self._CopyFile(sourceFileName, fullName,
copyDependentFiles = False)
class ConfigError(Exception):
def __init__(self, format, *args):
self.what = format % args
def __str__(self):
return self.what
class Executable(object):
def __init__(self, script, initScript = None, base = None, path = None,
targetDir = None, targetName = None, includes = None,
excludes = None, packages = None, replacePaths = None,
compress = None, copyDependentFiles = None,
appendScriptToExe = None, appendScriptToLibrary = None,
icon = None, namespacePackages = None, shortcutName = None,
shortcutDir = None):
self.script = script
self.initScript = initScript
self.base = base
self.path = path
self.targetDir = targetDir
self.targetName = targetName
self.includes = includes
self.excludes = excludes
self.packages = packages
self.namespacePackages = namespacePackages
self.replacePaths = replacePaths
self.compress = compress
self.copyDependentFiles = copyDependentFiles
self.appendScriptToExe = appendScriptToExe
self.appendScriptToLibrary = appendScriptToLibrary
self.icon = icon
self.shortcutName = shortcutName
self.shortcutDir = shortcutDir
def __repr__(self):
return "<Executable script=%s>" % self.script
def _VerifyConfiguration(self, freezer):
if self.path is None:
self.path = freezer.path
if self.targetDir is None:
self.targetDir = freezer.targetDir
if self.includes is None:
self.includes = freezer.includes
if self.excludes is None:
self.excludes = freezer.excludes
if self.packages is None:
self.packages = freezer.packages
if self.namespacePackages is None:
self.namespacePackages = freezer.namespacePackages
if self.replacePaths is None:
self.replacePaths = freezer.replacePaths
if self.compress is None:
self.compress = freezer.compress
if self.copyDependentFiles is None:
self.copyDependentFiles = freezer.copyDependentFiles
if self.appendScriptToExe is None:
self.appendScriptToExe = freezer.appendScriptToExe
if self.appendScriptToLibrary is None:
self.appendScriptToLibrary = freezer.appendScriptToLibrary
if self.initScript is None:
self.initScript = freezer.initScript
else:
freezer._GetInitScriptFileName(self)
if self.base is None:
self.base = freezer.base
else:
freezer._GetBaseFileName(self)
if self.appendScriptToLibrary:
freezer._VerifyCanAppendToLibrary()
if self.icon is None:
self.icon = freezer.icon
if self.targetName is None:
name, ext = os.path.splitext(os.path.basename(self.script))
baseName, ext = os.path.splitext(self.base)
self.targetName = name + ext
if self.appendScriptToLibrary:
name, ext = os.path.splitext(self.targetName)
self.moduleName = "%s__main__" % os.path.normcase(name)
else:
self.moduleName = "__main__"
self.targetName = os.path.join(self.targetDir, self.targetName)
class ConstantsModule(object):
def __init__(self, releaseString = None, copyright = None,
moduleName = "BUILD_CONSTANTS", timeFormat = "%B %d, %Y %H:%M:%S"):
self.moduleName = moduleName
self.timeFormat = timeFormat
self.values = {}
self.values["BUILD_RELEASE_STRING"] = releaseString
self.values["BUILD_COPYRIGHT"] = copyright
def Create(self, finder):
"""Create the module which consists of declaration statements for each
of the values."""
today = datetime.datetime.today()
sourceTimestamp = 0
for module in finder.modules:
if module.file is None:
continue
if module.inZipFile:
continue
if not os.path.exists(module.file):
raise ConfigError("no file named %s (for module %s)",
module.file, module.name)
timestamp = os.stat(module.file).st_mtime
sourceTimestamp = max(sourceTimestamp, timestamp)
sourceTimestamp = datetime.datetime.fromtimestamp(sourceTimestamp)
self.values["BUILD_TIMESTAMP"] = today.strftime(self.timeFormat)
self.values["BUILD_HOST"] = socket.gethostname().split(".")[0]
self.values["SOURCE_TIMESTAMP"] = \
sourceTimestamp.strftime(self.timeFormat)
module = finder._AddModule(self.moduleName)
sourceParts = []
names = list(self.values.keys())
names.sort()
for name in names:
value = self.values[name]
sourceParts.append("%s = %r" % (name, value))
source = "\n".join(sourceParts)
module.code = compile(source, "%s.py" % self.moduleName, "exec")
return module
class VersionInfo(object):
def __init__(self, version, internalName = None, originalFileName = None,
comments = None, company = None, description = None,
copyright = None, trademarks = None, product = None, dll = False,
debug = False, verbose = True):
parts = version.split(".")
while len(parts) < 4:
parts.append("0")
self.version = ".".join(parts)
self.internal_name = internalName
self.original_filename = originalFileName
self.comments = comments
self.company = company
self.description = description
self.copyright = copyright
self.trademarks = trademarks
self.product = product
self.dll = dll
self.debug = debug
self.verbose = verbose
|
|
import errno
import json
import os
import subprocess
import sys
from collections import defaultdict
MISC_XML = """<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component
name="ProjectRootManager"
version="2"
languageLevel="%(java_language_level)s"
assert-keyword="true"
jdk-15="true"
project-jdk-name="%(project_jdk_name)s"
project-jdk-type="%(project_jdk_type)s">
%(project_output_url)s
</component>
</project>"""
MODULE_XML_START = """<?xml version="1.0" encoding="UTF-8"?>
<module type="%(type)s" version="4">"""
MODULE_XML_END = """
</module>
"""
ANDROID_FACET = """
<component name="FacetManager">
<facet type="android" name="Android">
<configuration>
<option name="ENABLE_SOURCES_AUTOGENERATION" value="%(enable_sources_autogeneration)s" />
<option name="GEN_FOLDER_RELATIVE_PATH_APT" value="%(module_gen_path)s" />
<option name="GEN_FOLDER_RELATIVE_PATH_AIDL" value="%(module_gen_path)s" />
<option name="MANIFEST_FILE_RELATIVE_PATH" value="%(android_manifest)s" />
<option name="RES_FOLDER_RELATIVE_PATH" value="%(res)s" />
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="%(asset_folder)s" />
<option name="LIBS_FOLDER_RELATIVE_PATH" value="%(libs_path)s" />
<option name="USE_CUSTOM_APK_RESOURCE_FOLDER" value="false" />
<option name="CUSTOM_APK_RESOURCE_FOLDER" value="" />
<option name="USE_CUSTOM_COMPILER_MANIFEST" value="false" />
<option name="CUSTOM_COMPILER_MANIFEST" value="" />
<option name="APK_PATH" value="%(apk_path)s" />
<option name="LIBRARY_PROJECT" value="%(is_android_library_project)s" />
<option name="RUN_PROCESS_RESOURCES_MAVEN_TASK" value="true" />
<option name="GENERATE_UNSIGNED_APK" value="false" />
<option name="CUSTOM_DEBUG_KEYSTORE_PATH" value="%(keystore)s" />
<option name="PACK_TEST_CODE" value="false" />
<option name="RUN_PROGUARD" value="%(run_proguard)s" />
<option name="PROGUARD_CFG_PATH" value="%(proguard_config)s" />
<resOverlayFolders />
<includeSystemProguardFile>false</includeSystemProguardFile>
<includeAssetsFromLibraries>true</includeAssetsFromLibraries>
<additionalNativeLibs />
</configuration>
</facet>
</component>"""
ALL_MODULES_XML_START = """<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>"""
ALL_MODULES_XML_END = """
</modules>
</component>
</project>
"""
AAR_XML_START = """<component name="libraryTable">
<library name="%(name)s">
<CLASSES>
<root url="jar://$PROJECT_DIR$/%(binary_jar)s!/" />"""
AAR_XML_RESOURCE = """
<root url="file://$PROJECT_DIR$/%(resource_path)s/" />"""
AAR_XML_END = """
</CLASSES>
</library>
</component>
"""
LIBRARY_XML_START = """<component name="libraryTable">
<library name="%(name)s">
<CLASSES>
<root url="jar://$PROJECT_DIR$/%(binary_jar)s!/" />
</CLASSES>"""
LIBRARY_XML_WITH_JAVADOC = """
<JAVADOC>
<root url="%(javadoc_url)s" />
</JAVADOC>"""
LIBRARY_XML_NO_JAVADOC = """
<JAVADOC />"""
LIBRARY_XML_WITH_SOURCES = """
<SOURCES>
<root url="jar://$PROJECT_DIR$/%(source_jar)s!/" />
</SOURCES>"""
LIBRARY_XML_NO_SOURCES = """
<SOURCES />"""
LIBRARY_XML_END = """
</library>
</component>
"""
RUN_CONFIG_XML_START = """<component name="ProjectRunConfigurationManager">"""
RUN_CONFIG_XML_END = "</component>"
REMOTE_RUN_CONFIG_XML = """
<configuration default="false" name="%(name)s" type="Remote" factoryName="Remote">
<option name="USE_SOCKET_TRANSPORT" value="true" />
<option name="SERVER_MODE" value="false" />
<option name="SHMEM_ADDRESS" value="javadebug" />
<option name="HOST" value="localhost" />
<option name="PORT" value="5005" />
<RunnerSettings RunnerId="Debug">
<option name="DEBUG_PORT" value="5005" />
<option name="TRANSPORT" value="0" />
<option name="LOCAL" value="false" />
</RunnerSettings>
<ConfigurationWrapper RunnerId="Debug" />
<method />
</configuration>
"""
# Files that were written by this script.
# If `buck project` is working properly, most of the time it will be a no-op
# and no files will need to be written.
MODIFIED_FILES = []
# Files that are part of the project being run. We will delete all .iml files
# that are not checked in and not in this set.
PROJECT_FILES = set()
# Marker for a directory in the module tree that contains an .iml file.
# Intentionally chosen to be an illegal file name in both unix and windows.
CONTAINS_IML_MARKER = '/*contains_iml*/'
def tree():
""" Create an autovivification tree """
return defaultdict(tree)
def create_additional_excludes(modules):
"""Create set of directories to also be excluded."""
# Tree representation of all modules.
module_tree = tree()
additional_excludes = defaultdict(list)
for module in modules:
normalized_iml = os.path.dirname(os.path.normpath(
module['pathToImlFile']))
# Add this path to our build tree
current_directory = module_tree
if normalized_iml:
for part in normalized_iml.split(os.path.sep):
current_directory = current_directory[part]
current_directory[CONTAINS_IML_MARKER] = module
for root, dirs, _files in os.walk('.', topdown=True, followlinks=True):
current_directory = module_tree
normalized_root = os.path.normpath(root)
if normalized_root == '.':
continue
highest_iml_file = None
for part in normalized_root.split(os.path.sep):
if CONTAINS_IML_MARKER in current_directory:
module = current_directory[CONTAINS_IML_MARKER]
found_relevant_source_folder = False
for source_folder in module['sourceFolders']:
# If we find a module that specifies the directory as the
# source folder, then keep all folders under that module.
#
# TODO(rowillia): Be smarter here and actually keep track of
# the additional directories being tracked by sub modules.
if source_folder['url'] != 'file://$MODULE_DIR$/gen':
found_relevant_source_folder = True
break
# If we found a module containing subdirectories as
# sourceFolders, bail on trying to find a higher IML file.
if found_relevant_source_folder:
break
highest_iml_file = module['pathToImlFile']
if part not in current_directory:
if part != 'res' and highest_iml_file:
additional_excludes[highest_iml_file].append(
normalized_root)
dirs[:] = []
break
else:
current_directory = current_directory[part]
return additional_excludes
def get_path_from_map(map, key, fallback=None):
if key in map:
return '/' + map[key]
if None != fallback:
return '/' + fallback
return ''
def write_modules(modules, generate_minimum_project, android_auto_generation_disabled):
"""Writes one XML file for each module."""
additional_excludes = defaultdict(list)
if generate_minimum_project:
additional_excludes = create_additional_excludes(modules)
for module in modules:
# Build up the XML.
module_type = 'JAVA_MODULE'
if 'isIntelliJPlugin' in module and module['isIntelliJPlugin']:
module_type = 'PLUGIN_MODULE'
xml = MODULE_XML_START % {
'type': module_type,
}
# Android facet, if appropriate.
if module.get('hasAndroidFacet') is True:
if 'keystorePath' in module:
keystore = 'file://$MODULE_DIR$/%s' % module['keystorePath']
else:
keystore = ''
android_manifest = get_path_from_map(module, 'androidManifest', 'AndroidManifest.xml')
res_folder = get_path_from_map(module, 'resFolder', 'res')
asset_folder = get_path_from_map(module, 'assetFolder', 'assets')
is_library_project = module['isAndroidLibraryProject']
android_params = {
'android_manifest': android_manifest,
'res': res_folder,
'asset_folder': asset_folder,
'is_android_library_project': str(is_library_project).lower(),
'run_proguard': 'false',
'module_gen_path': get_path_from_map(module, 'moduleGenPath'),
'proguard_config': '/proguard.cfg',
'keystore': keystore,
'libs_path': '/%s' % module.get('nativeLibs', 'libs'),
'apk_path': get_path_from_map(module, 'binaryPath'),
}
if android_auto_generation_disabled:
android_params['enable_sources_autogeneration'] = 'false'
else:
android_params['enable_sources_autogeneration'] = 'true'
xml += ANDROID_FACET % android_params
# Source code and libraries component.
xml += '\n <component name="NewModuleRootManager" inherit-compiler-output="true">'
# Empirically, if there are multiple source folders, then the
# <content> element for the buck-out/android/gen folder should be
# listed before the other source folders.
num_source_folders = len(module['sourceFolders'])
if num_source_folders > 1 and module['hasAndroidFacet']:
xml = add_buck_android_source_folder(xml, module)
# Source folders.
xml += '\n <content url="file://$MODULE_DIR$">'
for source_folder in module['sourceFolders']:
if 'packagePrefix' in source_folder:
package_prefix = 'packagePrefix="%s" ' % source_folder['packagePrefix']
else:
package_prefix = ''
xml += '\n <sourceFolder url="%(url)s" isTestSource="%(is_test_source)s" %(package_prefix)s/>' % {
'url': source_folder['url'],
'is_test_source': str(source_folder['isTestSource']).lower(),
'package_prefix': package_prefix
}
for exclude_folder in module['excludeFolders']:
xml += '\n <excludeFolder url="%s" />' % exclude_folder['url']
for exclude_folder in sorted(additional_excludes[module['pathToImlFile']]):
normalized_dir = os.path.dirname(os.path.normpath(
module['pathToImlFile']))
xml += '\n <excludeFolder url="file://$MODULE_DIR$/%s" />' % os.path.relpath(exclude_folder, normalized_dir)
xml += '\n </content>'
xml = add_annotation_generated_source_folder(xml, module)
# Empirically, if there is one source folder, then the <content>
# element for the buck-out/android/gen folder should be listed after
# the other source folders.
if num_source_folders <= 1 and module['hasAndroidFacet']:
xml = add_buck_android_source_folder(xml, module)
# Dependencies.
dependencies = module['dependencies']
module_name = module['name']
# We need to filter out some of the modules in the dependency list:
# (1) The module may list itself as a dependency with scope="TEST",
# which is bad.
# (2) The module may list another module as a dependency with both
# COMPILE and TEST scopes, in which case the COMPILE scope should
# win.
# compile_dependencies will be the set of names of dependent modules
# that do not have scope="TEST"
compile_dependencies = filter(
lambda dep: dep['type'] == 'module' and
((not ('scope' in dep)) or dep['scope'] != 'TEST'),
dependencies)
compile_dependencies = map(
lambda dep: dep['moduleName'], compile_dependencies)
compile_dependencies = set(compile_dependencies)
# Filter dependencies to satisfy (1) and (2) defined above.
filtered_dependencies = []
for dep in dependencies:
if dep['type'] != 'module':
# Non-module dependencies should still be included.
filtered_dependencies.append(dep)
else:
# dep must be a module
dep_module_name = dep['moduleName']
if dep_module_name == module_name:
# Exclude self-references!
continue
elif 'scope' in dep and dep['scope'] == 'TEST':
# If this is a scope="TEST" module and the module is going
# to be included as a scope="COMPILE" module, then exclude
# it.
if not (dep_module_name in compile_dependencies):
filtered_dependencies.append(dep)
else:
# Non-test modules should still be included.
filtered_dependencies.append(dep)
# Now that we have filtered the dependencies, we can convert the
# remaining ones directly into XML.
excluded_deps_names = set()
if module_type == 'PLUGIN_MODULE':
# all the jars below are parts of IntelliJ SDK and even though they
# are required for language plugins to work standalone, they cannot
# be included as the plugin module dependency because they would
# clash with IntelliJ
excluded_deps_names = set([
'annotations', # org/intellij/lang/annotations, org/jetbrains/annotations
'extensions', # com/intellij/openapi/extensions/
'idea', # org/intellij, com/intellij
'jdom', # org/jdom
'junit', # junit/
'light_psi_all', # light psi library
'openapi', # com/intellij/openapi
'picocontainer', # org/picocontainer
'trove4j', # gnu/trove
'util', # com/intellij/util
])
for dep in filtered_dependencies:
if 'scope' in dep:
dep_scope = 'scope="%s" ' % dep['scope']
else:
dep_scope = ''
dep_type = dep['type']
if dep_type == 'library':
if dep['name'] in excluded_deps_names:
continue
xml += '\n <orderEntry type="library" exported="" %sname="%s" level="project" />' % (dep_scope, dep['name'])
elif dep_type == 'module':
dep_module_name = dep['moduleName']
# TODO(bolinfest): Eliminate this special-case for jackson. It
# exists because jackson is not an ordinary module: it is a
# module that functions as a library. Project.java should add
# it as such in project.json to eliminate this special case.
if dep_module_name == 'module_first_party_orca_third_party_jackson':
exported = 'exported="" '
else:
exported = ''
xml += '\n <orderEntry type="module" module-name="%s" %s%s/>' % (dep_module_name, exported, dep_scope)
elif dep_type == 'inheritedJdk':
xml += '\n <orderEntry type="inheritedJdk" />'
elif dep_type == 'jdk':
xml += '\n <orderEntry type="jdk" jdkName="%s" jdkType="%s" />' % (dep['jdkName'], dep['jdkType'])
elif dep_type == 'sourceFolder':
xml += '\n <orderEntry type="sourceFolder" forTests="false" />'
# Close source code and libraries component.
xml += '\n </component>'
# Close XML.
xml += MODULE_XML_END
# Write the module to a file.
write_file_if_changed(module['pathToImlFile'], xml)
def add_buck_android_source_folder(xml, module):
# Apparently if we write R.java and friends to a gen/ directory under
# buck-out/android/ then IntelliJ wants that to be included as a separate
# source root.
if 'moduleGenPath' in module:
xml += '\n <content url="file://$MODULE_DIR$/%s">' % module['moduleGenPath']
xml += '\n <sourceFolder url="file://$MODULE_DIR$/%s" isTestSource="false" />'\
% module['moduleGenPath']
xml += '\n </content>'
if 'moduleRJavaPath' in module:
xml += '\n <content url="file://$MODULE_DIR$/%s">' % module['moduleRJavaPath']
xml += '\n <sourceFolder '
xml += 'url="file://$MODULE_DIR$/%s" ' % module['moduleRJavaPath']
xml += 'isTestSource="false" />'
xml += '\n </content>'
return xml
def add_annotation_generated_source_folder(xml, module):
if 'annotationGenPath' in module:
annotation_gen_is_for_test = ('annotationGenIsForTest' in module and
module['annotationGenIsForTest'])
is_test_source = str(annotation_gen_is_for_test).lower()
xml += '\n <content url="file://$MODULE_DIR$/%s">' % module['annotationGenPath']
xml += '\n <sourceFolder url="file://$MODULE_DIR$/%s" isTestSource="%s" />'\
% (module['annotationGenPath'], is_test_source)
xml += '\n </content>'
return xml
def write_all_modules(modules):
"""Writes a modules.xml file that defines all of the modules in the project."""
# Build up the XML.
xml = ALL_MODULES_XML_START
# Alpha-sort modules by path before writing them out.
# This ensures that the ordering within modules.xml is stable.
modules.sort(key=lambda module: module['pathToImlFile'])
for module in modules:
relative_path = module['pathToImlFile']
xml += '\n <module fileurl="file://$PROJECT_DIR$/%s" filepath="$PROJECT_DIR$/%s" %s/>' % (
relative_path,
relative_path,
'group="modules"' if not module['isRootModule'] else '')
xml += ALL_MODULES_XML_END
# Write the modules to a file.
write_file_if_changed('.idea/modules.xml', xml)
def write_misc_file(java_settings):
"""Writes a misc.xml file to define some settings specific to the project."""
output_url = '<output url="file://$PROJECT_DIR$/' + \
java_settings.get('outputUrl', 'build-ij/classes') + '" />'
xml = MISC_XML % {
'java_language_level': java_settings.get('languageLevel', 'JDK_1_6'),
'project_jdk_name': java_settings.get('jdkName', 'Android API 21 Platform'),
'project_jdk_type': java_settings.get('jdkType', 'Android SDK'),
'project_output_url': output_url
}
write_file_if_changed('.idea/misc.xml', xml)
def write_aars(aars):
"""Writes an XML file to define each prebuilt aar."""
mkdir_p('.idea/libraries')
for aar in aars:
# Build up the XML.
name = aar['name']
xml = AAR_XML_START % {
'name': name,
'binary_jar': aar['jar'],
}
if 'res' in aar:
xml += AAR_XML_RESOURCE % {'resource_path': aar['res']}
if 'assets' in aar:
xml += AAR_XML_RESOURCE % {'resource_path': aar['assets']}
xml += AAR_XML_END
# Write the library to a file
write_file_if_changed('.idea/libraries/%s.xml' % name, xml)
def write_libraries(libraries):
"""Writes an XML file to define each library."""
mkdir_p('.idea/libraries')
for library in libraries:
# Build up the XML.
name = library['name']
xml = LIBRARY_XML_START % {
'name': name,
'binary_jar': library['binaryJar'],
}
if 'javadocUrl' in library:
xml += LIBRARY_XML_WITH_JAVADOC % {
'javadoc_url': library['javadocUrl'],
}
else:
xml += LIBRARY_XML_NO_JAVADOC
if 'sourceJar' in library:
xml += LIBRARY_XML_WITH_SOURCES % {
'source_jar': library['sourceJar'],
}
else:
xml += LIBRARY_XML_NO_SOURCES
xml += LIBRARY_XML_END
# Write the library to a file
write_file_if_changed('.idea/libraries/%s.xml' % name, xml)
def write_run_configs():
"""Writes the run configurations that should be available"""
mkdir_p('.idea/runConfigurations')
xml = RUN_CONFIG_XML_START
xml += REMOTE_RUN_CONFIG_XML % {'name': "Debug Buck test"}
xml += RUN_CONFIG_XML_END
write_file_if_changed('.idea/runConfigurations/Debug_Buck_test.xml', xml)
def write_file_if_changed(path, content):
PROJECT_FILES.add(path)
if os.path.exists(path):
file_content_as_string = open(path, 'r').read()
needs_update = content.strip() != file_content_as_string.strip()
else:
needs_update = True
if needs_update:
dirname = os.path.dirname(path)
if dirname:
mkdir_p(dirname)
out = open(path, 'wb')
out.write(content)
MODIFIED_FILES.append(path)
def mkdir_p(path):
"""Runs the equivalent of `mkdir -p`
Taken from http://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
Args:
path: an absolute path
"""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST:
pass
else:
raise
def clean_old_files():
if os.path.isdir('.git'):
try:
files_to_clean = subprocess.check_output([
'git',
'ls-files',
'--other'])
for file_name in files_to_clean.splitlines():
if (file_name.endswith('.iml') and
file_name not in PROJECT_FILES):
os.remove(file_name)
return
except Exception as e:
pass
if __name__ == '__main__':
json_file = sys.argv[1]
generate_minimum_project = False
android_auto_generation_disabled = False
for key in sys.argv[2:]:
if key == '--generate_minimum_project':
generate_minimum_project = True
if key == '--disable_android_auto_generation_setting':
android_auto_generation_disabled = True
parsed_json = json.load(open(json_file, 'r'))
libraries = parsed_json['libraries']
write_libraries(libraries)
aars = parsed_json['aars']
write_aars(aars)
modules = parsed_json['modules']
write_modules(modules, generate_minimum_project, android_auto_generation_disabled)
write_all_modules(modules)
write_run_configs()
java_settings = parsed_json['java']
write_misc_file(java_settings)
# Write the list of modified files to stdout
for path in MODIFIED_FILES:
print path
print >> sys.stderr, (' :: Please resynchronize IntelliJ via File->Synchronize ' +
'or Cmd-Opt-Y (Mac) or Ctrl-Alt-Y (PC/Linux)')
|
|
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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.
#
from google.auth.transport.requests import AuthorizedSession # type: ignore
import json # type: ignore
import grpc # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.api_core import rest_helpers
from google.api_core import rest_streaming
from google.api_core import path_template
from google.api_core import gapic_v1
from requests import __version__ as requests_version
import dataclasses
import re
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object] # type: ignore
from google.cloud.compute_v1.types import compute
from .base import (
GlobalOperationsTransport,
DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO,
)
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
grpc_version=None,
rest_version=requests_version,
)
class GlobalOperationsRestInterceptor:
"""Interceptor for GlobalOperations.
Interceptors are used to manipulate requests, request metadata, and responses
in arbitrary ways.
Example use cases include:
* Logging
* Verifying requests according to service or custom semantics
* Stripping extraneous information from responses
These use cases and more can be enabled by injecting an
instance of a custom subclass when constructing the GlobalOperationsRestTransport.
.. code-block:: python
class MyCustomGlobalOperationsInterceptor(GlobalOperationsRestInterceptor):
def pre_aggregated_list(request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
def post_aggregated_list(response):
logging.log(f"Received response: {response}")
def pre_delete(request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
def post_delete(response):
logging.log(f"Received response: {response}")
def pre_get(request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
def post_get(response):
logging.log(f"Received response: {response}")
def pre_list(request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
def post_list(response):
logging.log(f"Received response: {response}")
def pre_wait(request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
def post_wait(response):
logging.log(f"Received response: {response}")
transport = GlobalOperationsRestTransport(interceptor=MyCustomGlobalOperationsInterceptor())
client = GlobalOperationsClient(transport=transport)
"""
def pre_aggregated_list(
self,
request: compute.AggregatedListGlobalOperationsRequest,
metadata: Sequence[Tuple[str, str]],
) -> Tuple[
compute.AggregatedListGlobalOperationsRequest, Sequence[Tuple[str, str]]
]:
"""Pre-rpc interceptor for aggregated_list
Override in a subclass to manipulate the request or metadata
before they are sent to the GlobalOperations server.
"""
return request, metadata
def post_aggregated_list(
self, response: compute.OperationAggregatedList
) -> compute.OperationAggregatedList:
"""Post-rpc interceptor for aggregated_list
Override in a subclass to manipulate the response
after it is returned by the GlobalOperations server but before
it is returned to user code.
"""
return response
def pre_delete(
self,
request: compute.DeleteGlobalOperationRequest,
metadata: Sequence[Tuple[str, str]],
) -> Tuple[compute.DeleteGlobalOperationRequest, Sequence[Tuple[str, str]]]:
"""Pre-rpc interceptor for delete
Override in a subclass to manipulate the request or metadata
before they are sent to the GlobalOperations server.
"""
return request, metadata
def post_delete(
self, response: compute.DeleteGlobalOperationResponse
) -> compute.DeleteGlobalOperationResponse:
"""Post-rpc interceptor for delete
Override in a subclass to manipulate the response
after it is returned by the GlobalOperations server but before
it is returned to user code.
"""
return response
def pre_get(
self,
request: compute.GetGlobalOperationRequest,
metadata: Sequence[Tuple[str, str]],
) -> Tuple[compute.GetGlobalOperationRequest, Sequence[Tuple[str, str]]]:
"""Pre-rpc interceptor for get
Override in a subclass to manipulate the request or metadata
before they are sent to the GlobalOperations server.
"""
return request, metadata
def post_get(self, response: compute.Operation) -> compute.Operation:
"""Post-rpc interceptor for get
Override in a subclass to manipulate the response
after it is returned by the GlobalOperations server but before
it is returned to user code.
"""
return response
def pre_list(
self,
request: compute.ListGlobalOperationsRequest,
metadata: Sequence[Tuple[str, str]],
) -> Tuple[compute.ListGlobalOperationsRequest, Sequence[Tuple[str, str]]]:
"""Pre-rpc interceptor for list
Override in a subclass to manipulate the request or metadata
before they are sent to the GlobalOperations server.
"""
return request, metadata
def post_list(self, response: compute.OperationList) -> compute.OperationList:
"""Post-rpc interceptor for list
Override in a subclass to manipulate the response
after it is returned by the GlobalOperations server but before
it is returned to user code.
"""
return response
def pre_wait(
self,
request: compute.WaitGlobalOperationRequest,
metadata: Sequence[Tuple[str, str]],
) -> Tuple[compute.WaitGlobalOperationRequest, Sequence[Tuple[str, str]]]:
"""Pre-rpc interceptor for wait
Override in a subclass to manipulate the request or metadata
before they are sent to the GlobalOperations server.
"""
return request, metadata
def post_wait(self, response: compute.Operation) -> compute.Operation:
"""Post-rpc interceptor for wait
Override in a subclass to manipulate the response
after it is returned by the GlobalOperations server but before
it is returned to user code.
"""
return response
@dataclasses.dataclass
class GlobalOperationsRestStub:
_session: AuthorizedSession
_host: str
_interceptor: GlobalOperationsRestInterceptor
class GlobalOperationsRestTransport(GlobalOperationsTransport):
"""REST backend transport for GlobalOperations.
The GlobalOperations API.
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends JSON representations of protocol buffers over HTTP/1.1
"""
_STUBS: Dict[str, GlobalOperationsRestStub] = {}
def __init__(
self,
*,
host: str = "compute.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
url_scheme: str = "https",
interceptor: Optional[GlobalOperationsRestInterceptor] = None,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional(Sequence[str])): A list of scopes. This argument is
ignored if ``channel`` is provided.
client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
certificate to configure mutual TLS HTTP channel. It is ignored
if ``channel`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you are developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
url_scheme: the protocol scheme for the API endpoint. Normally
"https", but for testing or local servers,
"http" can be specified.
"""
# Run the base constructor
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
# credentials object
maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
if maybe_url_match is None:
raise ValueError(
f"Unexpected hostname structure: {host}"
) # pragma: NO COVER
url_match_items = maybe_url_match.groupdict()
host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
super().__init__(
host=host,
credentials=credentials,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
)
self._session = AuthorizedSession(
self._credentials, default_host=self.DEFAULT_HOST
)
if client_cert_source_for_mtls:
self._session.configure_mtls_channel(client_cert_source_for_mtls)
self._interceptor = interceptor or GlobalOperationsRestInterceptor()
self._prep_wrapped_messages(client_info)
class _AggregatedList(GlobalOperationsRestStub):
def __hash__(self):
return hash("AggregatedList")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
def __call__(
self,
request: compute.AggregatedListGlobalOperationsRequest,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.OperationAggregatedList:
r"""Call the aggregated list method over HTTP.
Args:
request (~.compute.AggregatedListGlobalOperationsRequest):
The request object. A request message for
GlobalOperations.AggregatedList. See the
method description for details.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.compute.OperationAggregatedList:
"""
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/compute/v1/projects/{project}/aggregated/operations",
},
]
request, metadata = self._interceptor.pre_aggregated_list(request, metadata)
request_kwargs = compute.AggregatedListGlobalOperationsRequest.to_dict(
request
)
transcoded_request = path_template.transcode(http_options, **request_kwargs)
uri = transcoded_request["uri"]
method = transcoded_request["method"]
# Jsonify the query params
query_params = json.loads(
compute.AggregatedListGlobalOperationsRequest.to_json(
compute.AggregatedListGlobalOperationsRequest(
transcoded_request["query_params"]
),
including_default_value_fields=False,
use_integers_for_enums=False,
)
)
query_params.update(self._get_unset_required_fields(query_params))
# Send the request
headers = dict(metadata)
headers["Content-Type"] = "application/json"
response = getattr(self._session, method)(
"{host}{uri}".format(host=self._host, uri=uri),
timeout=timeout,
headers=headers,
params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
# subclass.
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
# Return the response
resp = compute.OperationAggregatedList.from_json(
response.content, ignore_unknown_fields=True
)
resp = self._interceptor.post_aggregated_list(resp)
return resp
class _Delete(GlobalOperationsRestStub):
def __hash__(self):
return hash("Delete")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
def __call__(
self,
request: compute.DeleteGlobalOperationRequest,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.DeleteGlobalOperationResponse:
r"""Call the delete method over HTTP.
Args:
request (~.compute.DeleteGlobalOperationRequest):
The request object. A request message for
GlobalOperations.Delete. See the method
description for details.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.compute.DeleteGlobalOperationResponse:
A response message for
GlobalOperations.Delete. See the method
description for details.
"""
http_options: List[Dict[str, str]] = [
{
"method": "delete",
"uri": "/compute/v1/projects/{project}/global/operations/{operation}",
},
]
request, metadata = self._interceptor.pre_delete(request, metadata)
request_kwargs = compute.DeleteGlobalOperationRequest.to_dict(request)
transcoded_request = path_template.transcode(http_options, **request_kwargs)
uri = transcoded_request["uri"]
method = transcoded_request["method"]
# Jsonify the query params
query_params = json.loads(
compute.DeleteGlobalOperationRequest.to_json(
compute.DeleteGlobalOperationRequest(
transcoded_request["query_params"]
),
including_default_value_fields=False,
use_integers_for_enums=False,
)
)
query_params.update(self._get_unset_required_fields(query_params))
# Send the request
headers = dict(metadata)
headers["Content-Type"] = "application/json"
response = getattr(self._session, method)(
"{host}{uri}".format(host=self._host, uri=uri),
timeout=timeout,
headers=headers,
params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
# subclass.
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
# Return the response
resp = compute.DeleteGlobalOperationResponse.from_json(
response.content, ignore_unknown_fields=True
)
resp = self._interceptor.post_delete(resp)
return resp
class _Get(GlobalOperationsRestStub):
def __hash__(self):
return hash("Get")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
def __call__(
self,
request: compute.GetGlobalOperationRequest,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.Operation:
r"""Call the get method over HTTP.
Args:
request (~.compute.GetGlobalOperationRequest):
The request object. A request message for
GlobalOperations.Get. See the method
description for details.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.compute.Operation:
Represents an Operation resource. Google Compute Engine
has three Operation resources: \*
`Global </compute/docs/reference/rest/v1/globalOperations>`__
\*
`Regional </compute/docs/reference/rest/v1/regionOperations>`__
\*
`Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
You can use an operation resource to manage asynchronous
API requests. For more information, read Handling API
responses. Operations can be global, regional or zonal.
- For global operations, use the ``globalOperations``
resource. - For regional operations, use the
``regionOperations`` resource. - For zonal operations,
use the ``zonalOperations`` resource. For more
information, read Global, Regional, and Zonal Resources.
"""
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/compute/v1/projects/{project}/global/operations/{operation}",
},
]
request, metadata = self._interceptor.pre_get(request, metadata)
request_kwargs = compute.GetGlobalOperationRequest.to_dict(request)
transcoded_request = path_template.transcode(http_options, **request_kwargs)
uri = transcoded_request["uri"]
method = transcoded_request["method"]
# Jsonify the query params
query_params = json.loads(
compute.GetGlobalOperationRequest.to_json(
compute.GetGlobalOperationRequest(
transcoded_request["query_params"]
),
including_default_value_fields=False,
use_integers_for_enums=False,
)
)
query_params.update(self._get_unset_required_fields(query_params))
# Send the request
headers = dict(metadata)
headers["Content-Type"] = "application/json"
response = getattr(self._session, method)(
"{host}{uri}".format(host=self._host, uri=uri),
timeout=timeout,
headers=headers,
params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
# subclass.
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
# Return the response
resp = compute.Operation.from_json(
response.content, ignore_unknown_fields=True
)
resp = self._interceptor.post_get(resp)
return resp
class _List(GlobalOperationsRestStub):
def __hash__(self):
return hash("List")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
def __call__(
self,
request: compute.ListGlobalOperationsRequest,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.OperationList:
r"""Call the list method over HTTP.
Args:
request (~.compute.ListGlobalOperationsRequest):
The request object. A request message for
GlobalOperations.List. See the method
description for details.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.compute.OperationList:
Contains a list of Operation
resources.
"""
http_options: List[Dict[str, str]] = [
{
"method": "get",
"uri": "/compute/v1/projects/{project}/global/operations",
},
]
request, metadata = self._interceptor.pre_list(request, metadata)
request_kwargs = compute.ListGlobalOperationsRequest.to_dict(request)
transcoded_request = path_template.transcode(http_options, **request_kwargs)
uri = transcoded_request["uri"]
method = transcoded_request["method"]
# Jsonify the query params
query_params = json.loads(
compute.ListGlobalOperationsRequest.to_json(
compute.ListGlobalOperationsRequest(
transcoded_request["query_params"]
),
including_default_value_fields=False,
use_integers_for_enums=False,
)
)
query_params.update(self._get_unset_required_fields(query_params))
# Send the request
headers = dict(metadata)
headers["Content-Type"] = "application/json"
response = getattr(self._session, method)(
"{host}{uri}".format(host=self._host, uri=uri),
timeout=timeout,
headers=headers,
params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
# subclass.
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
# Return the response
resp = compute.OperationList.from_json(
response.content, ignore_unknown_fields=True
)
resp = self._interceptor.post_list(resp)
return resp
class _Wait(GlobalOperationsRestStub):
def __hash__(self):
return hash("Wait")
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}
@classmethod
def _get_unset_required_fields(cls, message_dict):
return {
k: v
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
if k not in message_dict
}
def __call__(
self,
request: compute.WaitGlobalOperationRequest,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> compute.Operation:
r"""Call the wait method over HTTP.
Args:
request (~.compute.WaitGlobalOperationRequest):
The request object. A request message for
GlobalOperations.Wait. See the method
description for details.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.compute.Operation:
Represents an Operation resource. Google Compute Engine
has three Operation resources: \*
`Global </compute/docs/reference/rest/v1/globalOperations>`__
\*
`Regional </compute/docs/reference/rest/v1/regionOperations>`__
\*
`Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
You can use an operation resource to manage asynchronous
API requests. For more information, read Handling API
responses. Operations can be global, regional or zonal.
- For global operations, use the ``globalOperations``
resource. - For regional operations, use the
``regionOperations`` resource. - For zonal operations,
use the ``zonalOperations`` resource. For more
information, read Global, Regional, and Zonal Resources.
"""
http_options: List[Dict[str, str]] = [
{
"method": "post",
"uri": "/compute/v1/projects/{project}/global/operations/{operation}/wait",
},
]
request, metadata = self._interceptor.pre_wait(request, metadata)
request_kwargs = compute.WaitGlobalOperationRequest.to_dict(request)
transcoded_request = path_template.transcode(http_options, **request_kwargs)
uri = transcoded_request["uri"]
method = transcoded_request["method"]
# Jsonify the query params
query_params = json.loads(
compute.WaitGlobalOperationRequest.to_json(
compute.WaitGlobalOperationRequest(
transcoded_request["query_params"]
),
including_default_value_fields=False,
use_integers_for_enums=False,
)
)
query_params.update(self._get_unset_required_fields(query_params))
# Send the request
headers = dict(metadata)
headers["Content-Type"] = "application/json"
response = getattr(self._session, method)(
"{host}{uri}".format(host=self._host, uri=uri),
timeout=timeout,
headers=headers,
params=rest_helpers.flatten_query_params(query_params),
)
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
# subclass.
if response.status_code >= 400:
raise core_exceptions.from_http_response(response)
# Return the response
resp = compute.Operation.from_json(
response.content, ignore_unknown_fields=True
)
resp = self._interceptor.post_wait(resp)
return resp
@property
def aggregated_list(
self,
) -> Callable[
[compute.AggregatedListGlobalOperationsRequest], compute.OperationAggregatedList
]:
stub = self._STUBS.get("aggregated_list")
if not stub:
stub = self._STUBS["aggregated_list"] = self._AggregatedList(
self._session, self._host, self._interceptor
)
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
# In C++ this would require a dynamic_cast
return stub # type: ignore
@property
def delete(
self,
) -> Callable[
[compute.DeleteGlobalOperationRequest], compute.DeleteGlobalOperationResponse
]:
stub = self._STUBS.get("delete")
if not stub:
stub = self._STUBS["delete"] = self._Delete(
self._session, self._host, self._interceptor
)
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
# In C++ this would require a dynamic_cast
return stub # type: ignore
@property
def get(self) -> Callable[[compute.GetGlobalOperationRequest], compute.Operation]:
stub = self._STUBS.get("get")
if not stub:
stub = self._STUBS["get"] = self._Get(
self._session, self._host, self._interceptor
)
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
# In C++ this would require a dynamic_cast
return stub # type: ignore
@property
def list(
self,
) -> Callable[[compute.ListGlobalOperationsRequest], compute.OperationList]:
stub = self._STUBS.get("list")
if not stub:
stub = self._STUBS["list"] = self._List(
self._session, self._host, self._interceptor
)
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
# In C++ this would require a dynamic_cast
return stub # type: ignore
@property
def wait(self) -> Callable[[compute.WaitGlobalOperationRequest], compute.Operation]:
stub = self._STUBS.get("wait")
if not stub:
stub = self._STUBS["wait"] = self._Wait(
self._session, self._host, self._interceptor
)
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
# In C++ this would require a dynamic_cast
return stub # type: ignore
def close(self):
self._session.close()
__all__ = ("GlobalOperationsRestTransport",)
|
|
# -----------------------------------------------------------
# Copyright (C) 2008 StatPro Italia s.r.l.
#
# StatPro Italia
# Via G. B. Vico 4
# I-20123 Milano
# ITALY
#
# phone: +39 02 96875 1
# fax: +39 02 96875 605
#
# This program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the license for more details.
# -----------------------------------------------------------
#
# Author: Enrico Sirola <[email protected]>
"""\
A python package for DRM job submission and control.
This package is an implementation of the DRMAA 1.0 Python language
binding specification (http://www.ogf.org/documents/GFD.143.pdf). See
http://drmaa-python.googlecode.com for package info and download.
"""
__docformat__ = "restructuredtext en"
import ctypes as _ct
try:
import namedtuple as _nt
except ImportError: # pre 2.6 behaviour
import nt as _nt
__version__ = "$Revision$"[11:-2]
import drmaa.const as _c
from drmaa.const import JobState, JobControlAction, JobSubmissionState
import drmaa.wrappers as _w
import drmaa.helpers as _h
from drmaa.errors import (AlreadyActiveSessionException,
AuthorizationException,
ConflictingAttributeValuesException,
DefaultContactStringException,
DeniedByDrmException,
DrmCommunicationException,
DrmsExitException,
DrmsInitException,
ExitTimeoutException,
HoldInconsistentStateException,
IllegalStateException,
InternalException,
InvalidAttributeFormatException,
InvalidContactStringException,
InvalidJobException,
InvalidJobTemplateException,
NoActiveSessionException,
NoDefaultContactStringSelectedException,
ReleaseInconsistentStateException,
ResumeInconsistentStateException,
SuspendInconsistentStateException,
TryLaterException,
UnsupportedAttributeException,
InvalidArgumentException,
InvalidAttributeValueException,
OutOfMemoryException,)
Version = _h.Version
JobInfo = _nt.namedtuple("JobInfo",
"""jobId hasExited hasSignal terminatedSignal
hasCoreDump wasAborted exitStatus resourceUsage""")
# FileTransferMode = _nt.namedtuple("FileTransferMode",
# """transferInputStream transferOutputStream
# transferErrorStream""")
class JobTemplate(object):
"""A job to be submitted to the DRM."""
HOME_DIRECTORY = '$drmaa_hd_ph$'
"""Home directory placeholder."""
WORKING_DIRECTORY = '$drmaa_wd_ph$'
"""Working directory placeholder."""
PARAMETRIC_INDEX = '$drmaa_incr_ph$'
"""Parametric index (for job arrays / bulk jobs) placeholder."""
@property
def attributeNames(self):
"""\
The list of supported DRMAA scalar attribute names.
This is apparently useless now, and should probably substituted by the
list of attribute names of the JobTemplate instances.
"""
return list(_h.attribute_names_iterator())
# scalar attributes
remoteCommand = _h.Attribute(_c.REMOTE_COMMAND )
"""The command to be executed."""
jobSubmissionState = _h.Attribute(_c.JS_STATE )
"""The job status."""
workingDirectory = _h.Attribute(_c.WD )
"""The job working directory."""
jobCategory = _h.Attribute(_c.JOB_CATEGORY )
"""The job category."""
nativeSpecification = _h.Attribute(_c.NATIVE_SPECIFICATION )
"""\
A (DRM-dependant) opaque string to be passed to the DRM representing
other directives.
"""
blockEmail = _h.Attribute(
_c.BLOCK_EMAIL,
type_converter=_h.BoolConverter(true='1', false='0'))
"""False id this job should send an email, True otherwise."""
startTime = _h.Attribute(_c.START_TIME )
"""The job start time, a partial timestamp string."""
jobName = _h.Attribute(_c.JOB_NAME )
"""The job Name."""
inputPath = _h.Attribute(_c.INPUT_PATH )
"""The path to a file representing job's stdin."""
outputPath = _h.Attribute(_c.OUTPUT_PATH )
"""The path to a file representing job's stdout."""
errorPath = _h.Attribute(_c.ERROR_PATH )
"""The path to a file representing job's stderr."""
joinFiles = _h.Attribute(
_c.JOIN_FILES,
type_converter=_h.BoolConverter())
"""True if stdin and stdout should be merged, False otherwise."""
# the following is available on ge6.2 only if enabled via cluster
# configuration
transferFiles = _h.Attribute(_c.TRANSFER_FILES )
"""\
True if file transfer should be enabled, False otherwise.
This option might require specific DRM configuration (it does on SGE).
"""
# the following are apparently not available on ge 6.2
# it will raise if you try to access these attrs
deadlineTime = _h.Attribute(_c.DEADLINE_TIME )
"""The job deadline time, a partial timestamp string."""
hardWallclockTimeLimit = _h.Attribute(_c.WCT_HLIMIT, _h.IntConverter)
"""\
'Hard' Wallclock time limit, in seconds.
The job will be killed by the DRM if it takes more than
'hardWallclockTimeLimit' to complete.
"""
softWallclockTimeLimit = _h.Attribute(_c.WCT_SLIMIT, _h.IntConverter)
"""\
'Soft' Wallclock time limit, in seconds.
The job will be signaled by the DRM if it takes more than
'hardWallclockTimeLimit' to complete.
"""
hardRunDurationLimit = _h.Attribute(_c.DURATION_HLIMIT, _h.IntConverter)
"""\
WRITE ME.
"""
softRunDurationLimit = _h.Attribute(_c.DURATION_SLIMIT, _h.IntConverter)
"""\
WRITE ME.
"""
# vector attributes
email = _h.VectorAttribute(_c.V_EMAIL)
"""email addresses to whom send job completion info."""
args = _h.VectorAttribute(_c.V_ARGV)
"""The job's command argument list."""
# dict attributes
jobEnvironment = _h.DictAttribute(_c.V_ENV)
"""The job's environment dict."""
_as_parameter_ = None
def __init__(self, **kwargs):
"""\
Builds a JobTemplate instance.
Attributes can be passed as keyword arguments."""
jt = _ct.pointer(_ct.POINTER(_w.drmaa_job_template_t)())
_h.c(_w.drmaa_allocate_job_template, jt)
self._jt = self._as_parameter_ = jt.contents
try:
for aname in kwargs:
setattr(self, aname, kwargs.get(aname))
except:
self.delete()
raise
def delete(self):
"""Deallocate the underlying DRMAA job template."""
_h.c(_w.drmaa_delete_job_template, self)
def __enter__(self):
"""context manager enter routine"""
return self
def __exit__(self, *_):
"""\
context manager exit routine.
Stops communication with the DRM.
"""
self.delete()
return False
class Session(object):
"""\
The DRMAA Session.
This class is the entry point for communicating with the DRM system
"""
TIMEOUT_WAIT_FOREVER = _c.TIMEOUT_WAIT_FOREVER
TIMEOUT_NO_WAIT = _c.TIMEOUT_NO_WAIT
JOB_IDS_SESSION_ANY = _c.JOB_IDS_SESSION_ANY
JOB_IDS_SESSION_ALL = _c.JOB_IDS_SESSION_ALL
contact = _h.SessionStringAttribute(_w.drmaa_get_contact)
"""\
a comma delimited string list containing the contact strings available
from the default DRMAA implementation, one element per DRM system
available. If called after initialize(), this method returns the
contact String for the DRM system to which the session is
attached. The returned strings are implementation dependent.
"""
drmsInfo = _h.SessionStringAttribute(_w.drmaa_get_DRM_system)
"""\
If called before initialize(), this method returns a comma delimited
list of DRM systems, one element per DRM system implementation
provided. If called after initialize(), this method returns the
selected DRM system. The returned String is implementation dependent.
"""
drmaaImplementation = _h.SessionStringAttribute(
_w.drmaa_get_DRMAA_implementation)
"""\
If called before initialize(), this method returns a comma delimited
list of DRMAA implementations, one element for each DRMAA
implementation provided. If called after initialize(), this method
returns the selected DRMAA implementation. The returned String is
implementation dependent and may contain the DRM system as a
component.
"""
version = _h.SessionVersionAttribute()
"""\
a Version object containing the major and minor version numbers of the
DRMAA library. For DRMAA 1.0, major is 1 and minor is 0.
"""
def __init__(self, contactString=None):
self.contactString = contactString
# no return value
@staticmethod
def initialize(contactString=None):
"""\
Used to initialize a DRMAA session for use.
:Parameters:
contactString : string or None
implementation-dependent string that
may be used to specify which DRM system to use
This method must be called before any other DRMAA calls. If
contactString is None, the default DRM system is used, provided there
is only one DRMAA implementation available. If there is more than one
DRMAA implementation available, initialize() throws a
NoDefaultContactStringSelectedException. initialize() should be called
only once, by only one of the threads. The main thread is
recommended. A call to initialize() by another thread or additional
calls to initialize() by the same thread with throw a
SessionAlreadyActiveException.
"""
_w.init(contactString)
# no return value
@staticmethod
def exit():
"""\
Used to disengage from DRM.
This routine ends the current DRMAA session but doesn't affect any
jobs (e.g., queued and running jobs remain queued and
running). exit() should be called only once, by only one of the
threads. Additional calls to exit() beyond the first will throw a
NoActiveSessionException.
"""
_w.exit()
# returns JobTemplate instance
@staticmethod
def createJobTemplate():
"""\
Allocates a new job template.
The job template is used to set the environment for jobs to be
submitted. Once the job template has been created, it should also be
deleted (via deleteJobTemplate()) when no longer needed. Failure to do
so may result in a memory leak.
"""
return JobTemplate()
# takes JobTemplate instance, no return value
@staticmethod
def deleteJobTemplate(jobTemplate):
"""\
Deallocate a job template.
:Parameters:
jobTemplate : JobTemplate
the job temptare to be deleted
This routine has no effect on running jobs.
"""
jobTemplate.delete()
# takes JobTemplate instance, returns string
@staticmethod
def runJob(jobTemplate):
"""\
Submit a job with attributes defined in the job template.
:Parameters:
jobTemplate : JobTemplate
the template representing the job to be run
The returned job identifier is a String identical to that returned
from the underlying DRM system.
"""
jid = _ct.create_string_buffer(128)
_h.c(_w.drmaa_run_job, jid, _ct.sizeof(jid), jobTemplate)
return jid.value
# takes JobTemplate instance and num values, returns string list
@staticmethod
def runBulkJobs(jobTemplate, beginIndex, endIndex, step):
"""\
Submit a set of parametric jobs, each with attributes defined in the job template.
:Parameters:
jobTemplate : JobTemplate
the template representng jobs to be run
beginIndex : int
index of the first job
endIndex : int
index of the last job
step : int
the step between job ids
The returned job identifiers are Strings identical to those returned
from the underlying DRM system. The JobTemplate class defines a
`JobTemplate.PARAMETRIC_INDEX` placeholder for use in specifying paths.
This placeholder is used to represent the individual identifiers of
the tasks submitted through this method.
"""
return list(_h.run_bulk_job(jobTemplate, beginIndex, endIndex, step))
# takes string and JobControlAction value, no return value
@staticmethod
def control(jobId, operation):
"""\
Used to hold, release, suspend, resume, or kill the job identified by jobId.
:Parameters:
jobId : string
if jobId is `Session.JOB_IDS_SESSION_ALL` then this routine acts on
all jobs submitted during this DRMAA session up to the moment
control() is called. The legal values for
action and their meanings are
operation : string
possible values are:
`JobControlAction.SUSPEND`
stop the job
`JobControlAction.RESUME`
(re)start the job
`JobControlAction.HOLD`
put the job on-hold
`JobControlAction.RELEASE`
release the hold on the job
`JobControlAction.TERMINATE`
kill the job
To avoid thread races in multithreaded applications, the DRMAA
implementation user should explicitly synchronize this call with
any other job submission calls or control calls that may change
the number of remote jobs.
This method returns once the action has been acknowledged by the DRM
system, but does not necessarily wait until the action has been
completed. Some DRMAA implementations may allow this method to be
used to control jobs submitted external to the DRMAA session, such as
jobs submitted by other DRMAA session in other DRMAA implementations
or jobs submitted via native utilities.
"""
_h.c(_w.drmaa_control, jobId, _c.string_to_control_action(operation))
# takes string list, num value and boolean, no return value
@staticmethod
def synchronize(jobIds, timeout=-1, dispose=False):
"""\
Waits until all jobs specified by jobList have finished execution.
:Parameters:
jobIds
If jobIds contains `Session.JOB_IDS_SESSION_ALL`, then this
method waits for all jobs submitted during this DRMAA session up to
the moment synchronize() is called
timeout : int
maximum time (in seconds) to be waited for the completion of a job.
The value `Session.TIMEOUT_WAIT_FOREVER` may be specified to wait
indefinitely for a result. The value `Session.TIMEOUT_NO_WAIT` may
be specified to return immediately if no result is available.
dispose : bool
specifies how to treat the reaping of the remote job's internal
data record, which includes a record of the job's consumption of
system resources during its execution and other statistical
information. If set to True, the DRM will dispose of the job's
data record at the end of the synchroniize() call. If set to
False, the data record will be left for future access via the
wait() method.
To avoid thread race conditions in multithreaded applications, the
DRMAA implementation user should explicitly synchronize this call with
any other job submission calls or control calls that may change the
number of remote jobs.
If the call exits before the
timeout has elapsed, all the jobs have been waited on or there was an
interrupt. If the invocation exits on timeout, an ExitTimeoutException
is thrown. The caller should check system time before and after this
call in order to be sure of how much time has passed.
"""
if dispose: d = 1
else: d = 0
_h.c(_w.drmaa_synchronize, _h.string_vector(jobIds), timeout, d)
# takes string and long, returns JobInfo instance
@staticmethod
def wait(jobId, timeout=-1):
"""\
Wait for a job with jobId to finish execution or fail.
:Parameters:
`jobId` : str
The job id to wait completion for.
If the special string, `Session.JOB_IDS_SESSION_ANY`, is provided as the
jobId, this routine will wait for any job from the session
`timeout` : float
The timeout value is used to specify the desired behavior when a
result is not immediately available.
The value `Session.TIMEOUT_WAIT_FOREVER` may be specified to wait
indefinitely for a result. The value `Session.TIMEOUT_NO_WAIT` may
be specified to return immediately if no result is
available. Alternatively, a number of seconds may be specified to
indicate how long to wait for a result to become available
This routine is modeled on the wait3 POSIX routine. If the call exits
before timeout, either the job has been waited on successfully or
there was an interrupt. If the invocation exits on timeout, an
`ExitTimeoutException` is thrown. The caller should check system time
before and after this call in order to be sure how much time has
passed. The routine reaps job data records on a successful call, so
any subsequent calls to wait() will fail, throwing an
`InvalidJobException`, meaning that the job's data record has been
already reaped. This exception is the same as if the job were
unknown. (The only case where wait() can be successfully called on a
single job more than once is when the previous call to wait() timed
out before the job finished.)
"""
stat = _ct.c_int()
jid_out = _ct.create_string_buffer(128)
job_id_out = _ct.c_int()
rusage = _ct.pointer(_ct.POINTER(_w.drmaa_attr_values_t)())
_h.c(_w.drmaa_wait, jobId, jid_out, _ct.sizeof(jid_out),
_ct.byref(stat), timeout, rusage)
res_usage = _h.adapt_rusage(rusage)
exited = _ct.c_int()
_h.c(_w.drmaa_wifexited, _ct.byref(exited), stat)
aborted = _ct.c_int()
_h.c(_w.drmaa_wifaborted, _ct.byref(aborted), stat)
signaled = _ct.c_int()
_h.c(_w.drmaa_wifsignaled, _ct.byref(signaled), stat)
coredumped = _ct.c_int()
_h.c(_w.drmaa_wcoredump, _ct.byref(coredumped), stat)
exit_status = _ct.c_int()
_h.c(_w.drmaa_wexitstatus, _ct.byref(exit_status), stat)
term_signal = _ct.create_string_buffer(_c.SIGNAL_BUFFER)
_h.c(_w.drmaa_wtermsig, term_signal, _ct.sizeof(term_signal), stat)
return JobInfo(jid_out.value, bool(exited), bool(signaled),
term_signal.value, bool(coredumped),
bool(aborted), int(exit_status.value), res_usage)
# takes string, returns JobState instance
@staticmethod
def jobStatus(jobName):
"""\
returns the program status of the job identified by jobId.
The possible values returned from
this method are:
* `JobState.UNDETERMINED`: process status cannot be determined,
* `JobState.QUEUED_ACTIVE`: job is queued and active,
* `JobState.SYSTEM_ON_HOLD`: job is queued and in system hold,
* `JobState.USER_ON_HOLD`: job is queued and in user hold,
* `JobState.USER_SYSTEM_ON_HOLD`: job is queued and in user and system hold,
* `JobState.RUNNING`: job is running,
* `JobState.SYSTEM_SUSPENDED`: job is system suspended,
* `JobState.USER_SUSPENDED`: job is user suspended,
* `JobState.DONE`: job finished normally, and
* `JobState.FAILED`: job finished, but failed.
The DRMAA implementation should always get the status of the job from
the DRM system unless the status has already been determined to be
FAILED or DONE and the status has been successfully cached. Terminated
jobs return a FAILED status.
"""
status = _ct.c_int()
_h.c(_w.drmaa_job_ps, jobName, _ct.byref(status))
return _c.status_to_string(status.value)
def __enter__(self):
"""Context manager enter function"""
self.initialize(self.contactString)
return self
def __exit__(self, *_):
"""Context manager exit function."""
self.exit()
return False
|
|
""" Processing various file types for MAGeCK count
"""
from __future__ import print_function
import sys
import math
import logging
import string
def mageckcount_gini(x):
'''
Return the Gini index of an array
Calculation is based on http://en.wikipedia.org/wiki/Gini_coefficient
'''
xs=sorted(x)
n=len(xs)
gssum=sum([ (i+1.0)*xs[i] for i in range(n)])
ysum=sum(xs)
if ysum==0.0:
ysum=1.0
gs=1.0-2.0*(n-gssum/ysum)/(n-1)
return gs
def mageckcount_trim5_auto(filename,args,genedict):
'''
Automatically determine the trim 5 length in one fastq file
Parameters
----------
filename
Fastq filename to be sequence
args
Arguments
Return value
-----------
'''
# ctab={}
logging.info('Determining the trim-5 length of FASTQ file '+filename+'...')
if len(genedict)==0:
logging.error('Library file must be provided to automatically determine the trim-5 length in fastq file.')
# checking possible sgRNA length
lengthpool={}
for k in genedict.keys():
if len(k) not in lengthpool:
lengthpool[len(k)]=0
lengthpool[len(k)]+=1
lengthpoolkeys=sorted(lengthpool.keys(),reverse=True)
minlengthpool=min(lengthpool)
trimkey={}
readlenkey={}
logging.info('Possible gRNA lengths:'+','.join([str(t) for t in lengthpoolkeys]))
if filename.upper().endswith('.GZ'):
import gzip
openobj=gzip.open(filename,'rt')
else:
openobj=open(filename)
nline=0
maxline=100000 # maximum reads tested
nreadcount=0
for line in openobj:
# line=line.encode('utf-8')
nline=nline+1
if nline%4 == 2:
nreadcount+=1
if nreadcount>maxline:
break
if nreadcount%100000==1:
logging.info('Processing '+str(round(nreadcount/1000000))+ 'M reads ...')
fseq=line.strip()
if len(fseq) not in readlenkey:
readlenkey[len(fseq)]=0
readlenkey[len(fseq)]+=1
# check length
# for l in lengthpool.keys():
for triml in range(len(fseq)-minlengthpool+1):
fseqtrim=fseq[triml:]
findrecord=False
for l in lengthpoolkeys: # iterate all possible lengths
testl=l
if len(fseqtrim)<testl:
continue
fseqc=fseqtrim[:testl]
if fseqc.count('N')>0 and args.count_n==False:
continue
if fseqc not in genedict:
continue
else:
# find the record
if triml not in trimkey:
trimkey[triml]=0
trimkey[triml]+=1
findrecord=True
break
# end for l
if findrecord:
break
# end for triml
# end for line
openobj.close()
keysorted=sorted(trimkey.items(),key=lambda z: z[1], reverse=True)
totalmappedreads=sum([x[1] for x in trimkey.items()])
totalfrac=totalmappedreads*1.0/nreadcount
logging.info('Read length:'+','.join([str(x) for x in readlenkey.keys()]))
logging.info('Total tested reads: '+str(nreadcount)+', mapped: '+str(totalmappedreads)+ '('+str(totalfrac)+')')
if totalfrac < 0.01:
logging.error('Cannot automatically determine the --trim-5 length. Only ' + str(totalfrac*100 )+ ' % of the reads can be identified. ')
sys.exit(-1)
elif totalfrac < 0.5:
logging.warning('Only ' + str(totalfrac*100 )+ ' % of the reads can be identified. ')
candidatetrim5=[]
candidatetrim5frac=[]
lastfrac=0.01
logging.info('--trim-5 test data: (trim_length reads fraction)')
for ks in keysorted:
ksfrac=ks[1]*1.0/totalmappedreads
logging.info('\t'.join([str(x) for x in [ks[0],ks[1],ksfrac]]))
for ks in keysorted:
ksfrac=ks[1]*1.0/totalmappedreads
# logging.info('\t'.join([str(x) for x in [ks[0],ks[1],ksfrac]]))
if lastfrac>ksfrac*3.0:
break
candidatetrim5+=[ks[0]]
candidatetrim5frac+=[ksfrac]
if sum(candidatetrim5frac)>0.75:
break
if len(candidatetrim5)>0 and ksfrac<0.05:
break
lastfrac=ksfrac
logging.info('Auto determination of trim5 results: '+','.join([str(x) for x in candidatetrim5]))
return candidatetrim5
# return 0
def mageckcount_processonefile(filename,args,ctab,genedict,datastat):
'''
Go through one fastq file
Parameters
----------
filename
Fastq filename to be sequence
args
Arguments
ctab
A dictionary of sgRNA sequence and count
genedict
{sequence:(sgRNA_id,gene_id)} dictionary
datastat
Statistics of datasets ({key:value})
Return value
-----------
datastat
a dictionary structure of statistics
'''
# ctab={}
nline=0
logging.info('Parsing FASTQ file '+filename+'...')
nreadcount=0
nmappedcount=0
# checking possible trimming lengths
candidate_trim5=[0]
if args.trim_5.upper() == 'AUTO' or args.trim_5.upper() == 'AUTOTEST':
candidate_trim5=mageckcount_trim5_auto(filename,args,genedict)
else:
try:
cadidate_trim5=[int(x) for x in args.trim_5.split(',')]
except ValueError:
logging.error('Integer values must be specified in --trim-5 option')
# do not allow multiple trim_5 options without library file
if len(candidate_trim5)>1 and len(genedict)==0:
logging.error('A library file has to be provided if multiple trimming lengths are specified in --trim-5 option.')
sys.exit(-1)
if len(candidate_trim5)>1 and args.unmapped_to_file:
logging.error('The --unmapped-to-file option is not allowed if multiple trimming lengths are specified in --trim-5 option.')
sys.exit(-1)
# checking possible sgRNA length
lengthpool={}
for k in genedict.keys():
if len(k) not in lengthpool:
lengthpool[len(k)]=0
lengthpool[len(k)]+=1
lengthpoolkeys=sorted(lengthpool.keys(),reverse=True)
logging.info('Possible gRNA lengths:'+','.join([str(t) for t in lengthpoolkeys]))
if filename.upper().endswith('.GZ'):
import gzip
openobj=gzip.open(filename,'rt')
else:
openobj=open(filename)
for line in openobj:
# line=line.encode('utf-8')
nline=nline+1
if nline%4 != 2:
continue
nreadcount+=1
if nreadcount%1000000==1:
logging.info('Processing '+str(round(nreadcount/1000000))+ 'M reads ..')
if nreadcount>1000000 and hasattr(args, 'test_run') and args.test_run:
break
fseq0=line.strip()
#if args.trim_5 >0:
# fseq=fseq0[args.trim_5:]
for triml in candidate_trim5:
# check length
fseq=fseq0[triml:]
# for l in lengthpool.keys():
if len(genedict)==0:
if len(fseq)<args.sgrna_len:
continue
fseq=fseq[:args.sgrna_len]
if fseq.count('N')>0 and args.count_n==False:
continue
if fseq not in ctab:
ctab[fseq]=0
ctab[fseq]=ctab[fseq]+1
else:
findrecord=False
for l in lengthpoolkeys: # iterate all possible lengths
testl=l
if len(fseq)<testl:
continue
fseqc=fseq[:testl]
if fseqc.count('N')>0 and args.count_n==False:
continue
if fseqc not in genedict:
continue
else:
if fseqc not in ctab:
ctab[fseqc]=0
ctab[fseqc]=ctab[fseqc]+1
findrecord=True
nmappedcount+=1
break
# end for l
# save unmapped file
if args.unmapped_to_file and findrecord==False:
if len(fseq)<args.sgrna_len:
continue
fseqc=fseq[:args.sgrna_len]
if fseqc.count('N')>0 and args.count_n==False:
continue
if fseqc not in ctab:
ctab[fseqc]=0
ctab[fseqc]=ctab[fseqc]+1
# end if
# end if/else
# end for triml
#
logging.info('Total: '+str((nreadcount))+ '.')
logging.info('Mapped: '+str((nmappedcount))+ '.')
openobj.close()
# calculate statistics
datastat['reads']=nreadcount
# check if a library is provided
if len(genedict)==0:
datastat['mappedreads']=0
datastat['totalsgrnas']=0
datastat['zerosgrnas']=0
datastat['giniindex']=1
else:
nmapped=0
nrdcnt=[]
for (k,v) in ctab.items():
if k in genedict:
nmapped+=v
nrdcnt+=[math.log(v+1.0)]
nzerosg=0
for (k,v) in genedict.items():
if k not in ctab:
nzerosg+=1
nrdcnt+=[math.log(0.0+1.0)]
# logging.info('mapped:'+str(nmapped))
datastat['mappedreads']=nmapped
datastat['totalsgrnas']=len(genedict);
datastat['zerosgrnas']=nzerosg
datastat['giniindex']=mageckcount_gini(nrdcnt)
#return ctab
return 0
def mageckcount_processonefile_bam(filename,args,ctab,genedict,datastat):
'''
Go through bam file
Parameters
----------
filename
Fastq filename to be sequence
args
Arguments
ctab
A dictionary of sgRNA sequence and count
genedict
{sequence:(sgRNA_id,gene_id)} dictionary
datastat
Statistics of datasets ({key:value})
Return value
-----------
datastat
a dictionary structure of statistics
# important note for the alignment
1. Make sure 5' and 3' adapters are properly removed before mapping. Either use cutadapt or --trim5/--trim3 option in bowtie2.
2. Make sure no reverse-complement mapping is allowed; otherwise, there will be multiple mappings for sgRNAs whose sequnces are reverse complemented. In bowtie2, --no-rc parameter should be specified.
3. Carefully check the alignment strategy used in the aligner. Some sequences may map to multiple sgRNAs and are counted multiple times.
4. When building index, some aligners (like bowtie2) will remove sgRNAs with identical sequence. This will create some warning messages "sgRNA in the BAM file does not match th provided library file".
Reference:
BAM specification
https://samtools.github.io/hts-specs/SAMv1.pdf
Reference: Tao Liu's MACS2
https://github.com/taoliu/MACS/blob/master/MACS2/IO/Parser.pyx
'''
import sys
import gzip
import io
import math
import struct
from struct import unpack
"""
Encode table
ACMGRSVTWYHKDBNN -> [0,15]
Code int bit bit(reverse) int(reverse)
0 0000
A 1 0001
C 2 0010
M 3 0011
G 4 0100
R 5 0101
S 6 0110
V 7 0111
T 8 1000
W 9 1001
Y 10 1010
H 11 1011
K 12 1100
D 13 1101
B 14 1110
N 15 1111
"""
encodetable='NACMGRSVTWYHKDBN'
nline=0
logging.info('Parsing BAM file '+filename+'...')
nreadcount=0
# start processing the bam file
# open bam file
fhd=io.BufferedReader( gzip.open( filename, mode='rb' ) )
# check the first 3 character must be BAM
fhd.seek(0)
magic_header = fhd.read( 3 )
if magic_header.decode("utf-8")!= "BAM":
logging.error('Error: not recognized BAM file: '+filename+', header:'+magic_header.decode("utf-8"))
sys.exit(-1)
# check header
fhd.seek( 4 )
header_len = unpack( '<i', fhd.read( 4 ) )[ 0 ]
fhd.seek( header_len + fhd.tell() )
# next, get chromosome, and check whether it matches the given genedict
genedict_sgid={v[0]:k for (k,v) in genedict.items()}
nc = unpack( '<i', fhd.read( 4 ) )[ 0 ]
refnames=['']*nc
refnameslen=[0]*nc
nwarningsg=0
for x in range( nc ):
# read each chromosome name
nlength = unpack( '<i' , fhd.read( 4 ) )[ 0 ]
refstr=fhd.read( nlength ).decode("utf-8")
# jump over chromosome size, we don't need it
refstrlen = unpack( '<i', fhd.read( 4 ) )[ 0 ]
#fhd.seek( fhd.tell() + 4 )
#print(refstr+':'+str(refstrlen))
refstr=refstr[:-1]
refnames[x]=refstr
refnameslen[x]=refstrlen
if refstr not in genedict_sgid:
# logging.warning('sgRNA ID '+ refstr+' in the BAM file does not not match the provided library file. Please double check.')
if nwarningsg<3:
logging.warning('sgRNA ID '+ refstr+' in the BAM file is missing in the provided library file (it may have duplicated sequences with other sgRNAs). Please double check.')
nwarningsg+=1
logging.info(str(nc)+' references detected in the BAM file.')
if nwarningsg>3:
logging.warning('Total sgRNAs that are missing in the library (may be due to duplicated sequences):'+str(nwarningsg))
nwarningsg=0
#
# next, iterate the bam file
while True:
nline=nline+1
if nline%1000000==1:
logging.info('Processing '+str(round(nline/1000000))+ 'M records ..')
if nline>1000000 and hasattr(args, 'test_run') and args.test_run:
break
#
nreadcount+=1
tmpdata=fhd.read(4)
if len(tmpdata)==0:
break
entrylength = unpack( '<i', tmpdata )[ 0 ]
data = fhd.read( entrylength )
# refid, position
refid=unpack( '<i', data[:4] )[ 0 ]
if refid == -1:
# didn't find any match
refstr='*'
else:
# find matches
refstr=refnames[refid]
if refstr not in genedict_sgid:
# logging.warning('sgRNA ID: '+refstr+' is not present in the library file. Please double-check the consistency between library file and SAM/BAM file.')
if nwarningsg<3:
logging.warning('sgRNA ID: '+refstr+' is not present in the library file. Please double-check the consistency between library file and SAM/BAM file.')
nwarningsg+=1
continue
fseqc=genedict_sgid[refstr]
if fseqc not in ctab:
ctab[fseqc]=0
ctab[fseqc]=ctab[fseqc]+1
# other fields in BAM file; not used
if False:
position=unpack( '<i', data[4:8] )[ 0 ]
bin_mq_nl=unpack( '<i', data[8:12] )[ 0 ]
read_name_len=bin_mq_nl&0x000000ff
# print('name length:'+str(read_name_len))
flag_nc=unpack( '<i', data[12:16] )[ 0 ]
n_cigar_op=flag_nc&0x0000ffff
flag=flag_nc>>16
# length
readlen = unpack( '<i', data[16:20] )[ 0 ]
next_refID=unpack( '<i', data[20:24] )[ 0 ]
next_pos=unpack( '<i', data[24:28] )[ 0 ]
tlen=unpack( '<i', data[28:32] )[ 0 ]
read_name=data[32:32+read_name_len]
# cigar
tstart=32+read_name_len
tend=tstart+n_cigar_op*4
# the following is the only 1st int of cigar string
cigarstr=unpack('<i',data[tstart:tstart+4])
# seq, encoded
tstart=tend
tend=tstart+int(math.ceil((readlen+1)/2))
seq=data[tstart:tend]
# quality
tstart=tend
tend=tstart+readlen
phredqual=data[tstart:tend]
if nline<10 and False: # only for debug purposes
logging.info('refid: '+str(refid)+' '+refstr+', position:'+str(position)+', name:'+read_name)
# decode the sequence
nseqcode=int(math.floor((readlen+1)/2))
seqstring=''
for i in range(nseqcode):
iit=seq[i]
iit_int=unpack('<B',iit)[0]
k1=iit_int>>4
k2=iit_int&0xf
seqstring+=encodetable[k1]
if readlen %2==1 and i==nseqcode-1:
pass
else:
seqstring+=encodetable[k2]
# end for
logging.info(seqstring)
# end if
# end if FALSE
# end while
if nwarningsg>3:
logging.warning('Total records that are not in the library:'+str(nwarningsg))
fhd.close()
# calculate statistics
datastat['reads']=nreadcount
nmapped=0
nrdcnt=[]
for (k,v) in ctab.items():
if k in genedict:
nmapped+=v
nrdcnt+=[math.log(v+1.0)]
nzerosg=0
for (k,v) in genedict.items():
if k not in ctab:
nzerosg+=1
nrdcnt+=[math.log(0.0+1.0)]
logging.info('mapped:'+str(nmapped))
datastat['mappedreads']=nmapped
datastat['totalsgrnas']=len(genedict);
datastat['zerosgrnas']=nzerosg
datastat['giniindex']=mageckcount_gini(nrdcnt)
#return ctab
return 0
def mageckcount_processonefile_sam(filename,args,ctab,genedict,datastat):
'''
Go through sam file
Parameters
----------
filename
Fastq filename to be sequence
args
Arguments
ctab
A dictionary of sgRNA sequence and count
genedict
{sequence:(sgRNA_id,gene_id)} dictionary
datastat
Statistics of datasets ({key:value})
Return value
-----------
datastat
a dictionary structure of statistics
# important note for the alignment
# Please see the notes for bam files
Reference:
BAM specification
https://samtools.github.io/hts-specs/SAMv1.pdf
Reference: Tao Liu's MACS2
https://github.com/taoliu/MACS/blob/master/MACS2/IO/Parser.pyx
'''
import sys
import gzip
import io
import math
import struct
nline=0
logging.info('Parsing SAM file '+filename+'...')
nreadcount=0
# the {sgRNA_id: sequence} directory
genedict_sgid={v[0]:k for (k,v) in genedict.items()}
# whether the warning of particular sgRNA id is already present
sgrnaid_haswarning={}
# start processing the sam file
for line in open(filename):
if line[0]=='@':
continue
nline=nline+1
if nline%1000000==1:
logging.info('Processing '+str(round(nline/1000000))+ 'M records ..')
if nline>1000000 and hasattr(args, 'test_run') and args.test_run:
break
#
nreadcount+=1
field=line.strip().split()
# refid, position
refid=field[2]
if refid != "*":
# find matches
refstr= refid
if refstr not in genedict_sgid:
if refstr not in sgrnaid_haswarning:
# logging.warning('sgRNA ID: '+refstr+' in the SAM file does not match the provided library file. Please double-check.')
sgrnaid_haswarning[refstr]=1
continue
fseqc=genedict_sgid[refstr]
if fseqc not in ctab:
ctab[fseqc]=0
ctab[fseqc]=ctab[fseqc]+1
# end while
# calculate statistics
datastat['reads']=nreadcount
nmapped=0
nrdcnt=[]
for (k,v) in ctab.items():
if k in genedict:
nmapped+=v
nrdcnt+=[math.log(v+1.0)]
nzerosg=0
for (k,v) in genedict.items():
if k not in ctab:
nzerosg+=1
nrdcnt+=[math.log(0.0+1.0)]
logging.info('mapped:'+str(nmapped))
logging.warning('sgRNAs not in the library (may be due to duplicated sequences):'+str(len(sgrnaid_haswarning)))
datastat['mappedreads']=nmapped
datastat['totalsgrnas']=len(genedict);
datastat['zerosgrnas']=nzerosg
datastat['giniindex']=mageckcount_gini(nrdcnt)
#return ctab
return 0
|
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
# pylint: disable=line-too-long
"""This library provides a set of classes and functions that helps train models.
## Optimizers
The Optimizer base class provides methods to compute gradients for a loss and
apply gradients to variables. A collection of subclasses implement classic
optimization algorithms such as GradientDescent and Adagrad.
You never instantiate the Optimizer class itself, but instead instantiate one
of the subclasses.
@@Optimizer
@@GradientDescentOptimizer
@@AdadeltaOptimizer
@@AdagradOptimizer
@@AdagradDAOptimizer
@@MomentumOptimizer
@@AdamOptimizer
@@FtrlOptimizer
@@ProximalGradientDescentOptimizer
@@ProximalAdagradOptimizer
@@RMSPropOptimizer
## Gradient Computation
TensorFlow provides functions to compute the derivatives for a given
TensorFlow computation graph, adding operations to the graph. The
optimizer classes automatically compute derivatives on your graph, but
creators of new Optimizers or expert users can call the lower-level
functions below.
@@gradients
@@AggregationMethod
@@stop_gradient
@@hessians
## Gradient Clipping
TensorFlow provides several operations that you can use to add clipping
functions to your graph. You can use these functions to perform general data
clipping, but they're particularly useful for handling exploding or vanishing
gradients.
@@clip_by_value
@@clip_by_norm
@@clip_by_average_norm
@@clip_by_global_norm
@@global_norm
## Decaying the learning rate
@@exponential_decay
@@inverse_time_decay
@@natural_exp_decay
@@piecewise_constant
@@polynomial_decay
## Moving Averages
Some training algorithms, such as GradientDescent and Momentum often benefit
from maintaining a moving average of variables during optimization. Using the
moving averages for evaluations often improve results significantly.
@@ExponentialMovingAverage
## Coordinator and QueueRunner
See [Threading and Queues](../../how_tos/threading_and_queues/index.md)
for how to use threads and queues. For documentation on the Queue API,
see [Queues](../../api_docs/python/io_ops.md#queues).
@@Coordinator
@@QueueRunner
@@LooperThread
@@add_queue_runner
@@start_queue_runners
## Distributed execution
See [Distributed TensorFlow](../../how_tos/distributed/index.md) for
more information about how to configure a distributed TensorFlow program.
@@Server
@@Supervisor
@@SessionManager
@@ClusterSpec
@@replica_device_setter
@@MonitoredTrainingSession
@@MonitoredSession
@@SingularMonitoredSession
@@Scaffold
@@SessionCreator
@@ChiefSessionCreator
@@WorkerSessionCreator
## Reading Summaries from Event Files
See [Summaries and
TensorBoard](../../how_tos/summaries_and_tensorboard/index.md) for an
overview of summaries, event files, and visualization in TensorBoard.
@@summary_iterator
## Training Hooks
Hooks are tools that run in the process of training/evaluation of the model.
@@SessionRunHook
@@SessionRunArgs
@@SessionRunContext
@@SessionRunValues
@@LoggingTensorHook
@@StopAtStepHook
@@CheckpointSaverHook
@@NewCheckpointReader
@@StepCounterHook
@@NanLossDuringTrainingError
@@NanTensorHook
@@SummarySaverHook
@@GlobalStepWaiterHook
@@FinalOpsHook
@@FeedFnHook
## Training Utilities
@@global_step
@@basic_train_loop
@@get_global_step
@@assert_global_step
@@write_graph
"""
# pylint: enable=line-too-long
# Optimizers.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys as _sys
from tensorflow.python.ops import io_ops as _io_ops
from tensorflow.python.ops import state_ops as _state_ops
from tensorflow.python.util.all_util import remove_undocumented
# pylint: disable=g-bad-import-order,unused-import
from tensorflow.python.training.adadelta import AdadeltaOptimizer
from tensorflow.python.training.adagrad import AdagradOptimizer
from tensorflow.python.training.adagrad_da import AdagradDAOptimizer
from tensorflow.python.training.proximal_adagrad import ProximalAdagradOptimizer
from tensorflow.python.training.adam import AdamOptimizer
from tensorflow.python.training.ftrl import FtrlOptimizer
from tensorflow.python.training.momentum import MomentumOptimizer
from tensorflow.python.training.moving_averages import ExponentialMovingAverage
from tensorflow.python.training.optimizer import Optimizer
from tensorflow.python.training.rmsprop import RMSPropOptimizer
from tensorflow.python.training.gradient_descent import GradientDescentOptimizer
from tensorflow.python.training.proximal_gradient_descent import ProximalGradientDescentOptimizer
from tensorflow.python.training.sync_replicas_optimizer import SyncReplicasOptimizer
# Utility classes for training.
from tensorflow.python.training.coordinator import Coordinator
from tensorflow.python.training.coordinator import LooperThread
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.python.training.queue_runner import *
# For the module level doc.
from tensorflow.python.training import input as _input
from tensorflow.python.training.input import *
# pylint: enable=wildcard-import
from tensorflow.python.training.basic_session_run_hooks import SecondOrStepTimer
from tensorflow.python.training.basic_session_run_hooks import LoggingTensorHook
from tensorflow.python.training.basic_session_run_hooks import StopAtStepHook
from tensorflow.python.training.basic_session_run_hooks import CheckpointSaverHook
from tensorflow.python.training.basic_session_run_hooks import StepCounterHook
from tensorflow.python.training.basic_session_run_hooks import NanLossDuringTrainingError
from tensorflow.python.training.basic_session_run_hooks import NanTensorHook
from tensorflow.python.training.basic_session_run_hooks import SummarySaverHook
from tensorflow.python.training.basic_session_run_hooks import GlobalStepWaiterHook
from tensorflow.python.training.basic_session_run_hooks import FinalOpsHook
from tensorflow.python.training.basic_session_run_hooks import FeedFnHook
from tensorflow.python.training.basic_loops import basic_train_loop
from tensorflow.python.training.device_setter import replica_device_setter
from tensorflow.python.training.monitored_session import Scaffold
from tensorflow.python.training.monitored_session import MonitoredTrainingSession
from tensorflow.python.training.monitored_session import SessionCreator
from tensorflow.python.training.monitored_session import ChiefSessionCreator
from tensorflow.python.training.monitored_session import WorkerSessionCreator
from tensorflow.python.training.monitored_session import MonitoredSession
from tensorflow.python.training.monitored_session import SingularMonitoredSession
from tensorflow.python.training.saver import Saver
from tensorflow.python.training.saver import checkpoint_exists
from tensorflow.python.training.saver import generate_checkpoint_state_proto
from tensorflow.python.training.saver import get_checkpoint_mtimes
from tensorflow.python.training.saver import get_checkpoint_state
from tensorflow.python.training.saver import latest_checkpoint
from tensorflow.python.training.saver import update_checkpoint_state
from tensorflow.python.training.saver import export_meta_graph
from tensorflow.python.training.saver import import_meta_graph
from tensorflow.python.training.session_run_hook import SessionRunHook
from tensorflow.python.training.session_run_hook import SessionRunArgs
from tensorflow.python.training.session_run_hook import SessionRunContext
from tensorflow.python.training.session_run_hook import SessionRunValues
from tensorflow.python.training.session_manager import SessionManager
from tensorflow.python.training.summary_io import summary_iterator
from tensorflow.python.training.supervisor import Supervisor
from tensorflow.python.training.training_util import write_graph
from tensorflow.python.training.training_util import global_step
from tensorflow.python.training.training_util import get_global_step
from tensorflow.python.training.training_util import assert_global_step
from tensorflow.python.pywrap_tensorflow import do_quantize_training_on_graphdef
from tensorflow.python.pywrap_tensorflow import NewCheckpointReader
# pylint: disable=wildcard-import
# Training data protos.
from tensorflow.core.example.example_pb2 import *
from tensorflow.core.example.feature_pb2 import *
from tensorflow.core.protobuf.saver_pb2 import *
# Utility op. Open Source. TODO(touts): move to nn?
from tensorflow.python.training.learning_rate_decay import *
# pylint: enable=wildcard-import
# Distributed computing support.
from tensorflow.core.protobuf.tensorflow_server_pb2 import ClusterDef
from tensorflow.core.protobuf.tensorflow_server_pb2 import JobDef
from tensorflow.core.protobuf.tensorflow_server_pb2 import ServerDef
from tensorflow.python.training.server_lib import ClusterSpec
from tensorflow.python.training.server_lib import Server
# Symbols whitelisted for export without documentation.
_allowed_symbols = [
# TODO(cwhipkey): review these and move to contrib or expose through
# documentation.
"generate_checkpoint_state_proto", # Used internally by saver.
"checkpoint_exists", # Only used in test?
"get_checkpoint_mtimes", # Only used in test?
# Legacy: remove.
"do_quantize_training_on_graphdef", # At least use grah_def, not graphdef.
# No uses within tensorflow.
"queue_runner", # Use tf.train.start_queue_runner etc directly.
# This is also imported internally.
# TODO(drpng): document these. The reference in howtos/distributed does
# not link.
"SyncReplicasOptimizer",
# Protobufs:
"BytesList", # from example_pb2.
"ClusterDef",
"Example", # from example_pb2
"Feature", # from example_pb2
"Features", # from example_pb2
"FeatureList", # from example_pb2
"FeatureLists", # from example_pb2
"FloatList", # from example_pb2.
"Int64List", # from example_pb2.
"JobDef",
"SaverDef", # From saver_pb2.
"SequenceExample", # from example_pb2.
"ServerDef",
]
# Include extra modules for docstrings because:
# * Input methods in tf.train are documented in io_ops.
# * Saver methods in tf.train are documented in state_ops.
remove_undocumented(__name__, _allowed_symbols,
[_sys.modules[__name__], _io_ops, _state_ops])
|
|
import copy
import inspect
import os
from six.moves import http_client as httplib
import contextlib2
import mock
import pytest
import yaml
from vcr.cassette import Cassette
from vcr.errors import UnhandledHTTPRequestError
from vcr.patch import force_reset
from vcr.stubs import VCRHTTPSConnection
def test_cassette_load(tmpdir):
a_file = tmpdir.join('test_cassette.yml')
a_file.write(yaml.dump({'interactions': [
{'request': {'body': '', 'uri': 'foo', 'method': 'GET', 'headers': {}},
'response': 'bar'}
]}))
a_cassette = Cassette.load(path=str(a_file))
assert len(a_cassette) == 1
def test_cassette_not_played():
a = Cassette('test')
assert not a.play_count
def test_cassette_append():
a = Cassette('test')
a.append('foo', 'bar')
assert a.requests == ['foo']
assert a.responses == ['bar']
def test_cassette_len():
a = Cassette('test')
a.append('foo', 'bar')
a.append('foo2', 'bar2')
assert len(a) == 2
def _mock_requests_match(request1, request2, matchers):
return request1 == request2
@mock.patch('vcr.cassette.requests_match', _mock_requests_match)
def test_cassette_contains():
a = Cassette('test')
a.append('foo', 'bar')
assert 'foo' in a
@mock.patch('vcr.cassette.requests_match', _mock_requests_match)
def test_cassette_responses_of():
a = Cassette('test')
a.append('foo', 'bar')
assert a.responses_of('foo') == ['bar']
@mock.patch('vcr.cassette.requests_match', _mock_requests_match)
def test_cassette_get_missing_response():
a = Cassette('test')
with pytest.raises(UnhandledHTTPRequestError):
a.responses_of('foo')
@mock.patch('vcr.cassette.requests_match', _mock_requests_match)
def test_cassette_cant_read_same_request_twice():
a = Cassette('test')
a.append('foo', 'bar')
a.play_response('foo')
with pytest.raises(UnhandledHTTPRequestError):
a.play_response('foo')
def make_get_request():
conn = httplib.HTTPConnection("www.python.org")
conn.request("GET", "/index.html")
return conn.getresponse()
@mock.patch('vcr.cassette.requests_match', return_value=True)
@mock.patch('vcr.cassette.load_cassette', lambda *args, **kwargs: (('foo',), (mock.MagicMock(),)))
@mock.patch('vcr.cassette.Cassette.can_play_response_for', return_value=True)
@mock.patch('vcr.stubs.VCRHTTPResponse')
def test_function_decorated_with_use_cassette_can_be_invoked_multiple_times(*args):
decorated_function = Cassette.use(path='test')(make_get_request)
for i in range(4):
decorated_function()
def test_arg_getter_functionality():
arg_getter = mock.Mock(return_value={'path': 'test'})
context_decorator = Cassette.use_arg_getter(arg_getter)
with context_decorator as cassette:
assert cassette._path == 'test'
arg_getter.return_value = {'path': 'other'}
with context_decorator as cassette:
assert cassette._path == 'other'
arg_getter.return_value = {'path': 'other', 'filter_headers': ('header_name',)}
@context_decorator
def function():
pass
with mock.patch.object(
Cassette, 'load',
return_value=mock.MagicMock(inject=False)
) as cassette_load:
function()
cassette_load.assert_called_once_with(**arg_getter.return_value)
def test_cassette_not_all_played():
a = Cassette('test')
a.append('foo', 'bar')
assert not a.all_played
@mock.patch('vcr.cassette.requests_match', _mock_requests_match)
def test_cassette_all_played():
a = Cassette('test')
a.append('foo', 'bar')
a.play_response('foo')
assert a.all_played
def test_before_record_response():
before_record_response = mock.Mock(return_value='mutated')
cassette = Cassette('test', before_record_response=before_record_response)
cassette.append('req', 'res')
before_record_response.assert_called_once_with('res')
assert cassette.responses[0] == 'mutated'
def assert_get_response_body_is(value):
conn = httplib.HTTPConnection("www.python.org")
conn.request("GET", "/index.html")
assert conn.getresponse().read().decode('utf8') == value
@mock.patch('vcr.cassette.requests_match', _mock_requests_match)
@mock.patch('vcr.cassette.Cassette.can_play_response_for', return_value=True)
@mock.patch('vcr.cassette.Cassette._save', return_value=True)
def test_nesting_cassette_context_managers(*args):
first_response = {'body': {'string': b'first_response'}, 'headers': {},
'status': {'message': 'm', 'code': 200}}
second_response = copy.deepcopy(first_response)
second_response['body']['string'] = b'second_response'
with contextlib2.ExitStack() as exit_stack:
first_cassette = exit_stack.enter_context(Cassette.use(path='test'))
exit_stack.enter_context(mock.patch.object(first_cassette, 'play_response',
return_value=first_response))
assert_get_response_body_is('first_response')
# Make sure a second cassette can supercede the first
with Cassette.use(path='test') as second_cassette:
with mock.patch.object(second_cassette, 'play_response', return_value=second_response):
assert_get_response_body_is('second_response')
# Now the first cassette should be back in effect
assert_get_response_body_is('first_response')
def test_nesting_context_managers_by_checking_references_of_http_connection():
original = httplib.HTTPConnection
with Cassette.use(path='test'):
first_cassette_HTTPConnection = httplib.HTTPConnection
with Cassette.use(path='test'):
second_cassette_HTTPConnection = httplib.HTTPConnection
assert second_cassette_HTTPConnection is not first_cassette_HTTPConnection
with Cassette.use(path='test'):
assert httplib.HTTPConnection is not second_cassette_HTTPConnection
with force_reset():
assert httplib.HTTPConnection is original
assert httplib.HTTPConnection is second_cassette_HTTPConnection
assert httplib.HTTPConnection is first_cassette_HTTPConnection
def test_custom_patchers():
class Test(object):
attribute = None
with Cassette.use(path='custom_patches',
custom_patches=((Test, 'attribute', VCRHTTPSConnection),)):
assert issubclass(Test.attribute, VCRHTTPSConnection)
assert VCRHTTPSConnection is not Test.attribute
old_attribute = Test.attribute
with Cassette.use(path='custom_patches',
custom_patches=((Test, 'attribute', VCRHTTPSConnection),)):
assert issubclass(Test.attribute, VCRHTTPSConnection)
assert VCRHTTPSConnection is not Test.attribute
assert Test.attribute is not old_attribute
assert issubclass(Test.attribute, VCRHTTPSConnection)
assert VCRHTTPSConnection is not Test.attribute
assert Test.attribute is old_attribute
def test_decorated_functions_are_reentrant():
info = {"second": False}
original_conn = httplib.HTTPConnection
@Cassette.use(path='whatever', inject=True)
def test_function(cassette):
if info['second']:
assert httplib.HTTPConnection is not info['first_conn']
else:
info['first_conn'] = httplib.HTTPConnection
info['second'] = True
test_function()
assert httplib.HTTPConnection is info['first_conn']
test_function()
assert httplib.HTTPConnection is original_conn
def test_cassette_use_called_without_path_uses_function_to_generate_path():
@Cassette.use(inject=True)
def function_name(cassette):
assert cassette._path == 'function_name'
function_name()
def test_path_transformer_with_function_path():
path_transformer = lambda path: os.path.join('a', path)
@Cassette.use(inject=True, path_transformer=path_transformer)
def function_name(cassette):
assert cassette._path == os.path.join('a', 'function_name')
function_name()
def test_path_transformer_with_context_manager():
with Cassette.use(
path='b', path_transformer=lambda *args: 'a'
) as cassette:
assert cassette._path == 'a'
def test_func_path_generator():
def generator(function):
return os.path.join(os.path.dirname(inspect.getfile(function)),
function.__name__)
@Cassette.use(inject=True, func_path_generator=generator)
def function_name(cassette):
assert cassette._path == os.path.join(os.path.dirname(__file__), 'function_name')
function_name()
|
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import codecs
import csv
import fnmatch
import inspect
import locale
import os
import openerp.pooler as pooler
import openerp.sql_db as sql_db
import re
import logging
import tarfile
import tempfile
import threading
from babel.messages import extract
from os.path import join
from datetime import datetime
from lxml import etree
import config
import misc
from misc import UpdateableStr
from misc import SKIPPED_ELEMENT_TYPES
import osutil
from openerp import SUPERUSER_ID
_logger = logging.getLogger(__name__)
# used to notify web client that these translations should be loaded in the UI
WEB_TRANSLATION_COMMENT = "openerp-web"
_LOCALE2WIN32 = {
'af_ZA': 'Afrikaans_South Africa',
'sq_AL': 'Albanian_Albania',
'ar_SA': 'Arabic_Saudi Arabia',
'eu_ES': 'Basque_Spain',
'be_BY': 'Belarusian_Belarus',
'bs_BA': 'Serbian (Latin)',
'bg_BG': 'Bulgarian_Bulgaria',
'ca_ES': 'Catalan_Spain',
'hr_HR': 'Croatian_Croatia',
'zh_CN': 'Chinese_China',
'zh_TW': 'Chinese_Taiwan',
'cs_CZ': 'Czech_Czech Republic',
'da_DK': 'Danish_Denmark',
'nl_NL': 'Dutch_Netherlands',
'et_EE': 'Estonian_Estonia',
'fa_IR': 'Farsi_Iran',
'ph_PH': 'Filipino_Philippines',
'fi_FI': 'Finnish_Finland',
'fr_FR': 'French_France',
'fr_BE': 'French_France',
'fr_CH': 'French_France',
'fr_CA': 'French_France',
'ga': 'Scottish Gaelic',
'gl_ES': 'Galician_Spain',
'ka_GE': 'Georgian_Georgia',
'de_DE': 'German_Germany',
'el_GR': 'Greek_Greece',
'gu': 'Gujarati_India',
'he_IL': 'Hebrew_Israel',
'hi_IN': 'Hindi',
'hu': 'Hungarian_Hungary',
'is_IS': 'Icelandic_Iceland',
'id_ID': 'Indonesian_indonesia',
'it_IT': 'Italian_Italy',
'ja_JP': 'Japanese_Japan',
'kn_IN': 'Kannada',
'km_KH': 'Khmer',
'ko_KR': 'Korean_Korea',
'lo_LA': 'Lao_Laos',
'lt_LT': 'Lithuanian_Lithuania',
'lat': 'Latvian_Latvia',
'ml_IN': 'Malayalam_India',
'mi_NZ': 'Maori',
'mn': 'Cyrillic_Mongolian',
'no_NO': 'Norwegian_Norway',
'nn_NO': 'Norwegian-Nynorsk_Norway',
'pl': 'Polish_Poland',
'pt_PT': 'Portuguese_Portugal',
'pt_BR': 'Portuguese_Brazil',
'ro_RO': 'Romanian_Romania',
'ru_RU': 'Russian_Russia',
'sr_CS': 'Serbian (Cyrillic)_Serbia and Montenegro',
'sk_SK': 'Slovak_Slovakia',
'sl_SI': 'Slovenian_Slovenia',
#should find more specific locales for spanish countries,
#but better than nothing
'es_AR': 'Spanish_Spain',
'es_BO': 'Spanish_Spain',
'es_CL': 'Spanish_Spain',
'es_CO': 'Spanish_Spain',
'es_CR': 'Spanish_Spain',
'es_DO': 'Spanish_Spain',
'es_EC': 'Spanish_Spain',
'es_ES': 'Spanish_Spain',
'es_GT': 'Spanish_Spain',
'es_HN': 'Spanish_Spain',
'es_MX': 'Spanish_Spain',
'es_NI': 'Spanish_Spain',
'es_PA': 'Spanish_Spain',
'es_PE': 'Spanish_Spain',
'es_PR': 'Spanish_Spain',
'es_PY': 'Spanish_Spain',
'es_SV': 'Spanish_Spain',
'es_UY': 'Spanish_Spain',
'es_VE': 'Spanish_Spain',
'sv_SE': 'Swedish_Sweden',
'ta_IN': 'English_Australia',
'th_TH': 'Thai_Thailand',
'tr_TR': 'Turkish_Turkey',
'uk_UA': 'Ukrainian_Ukraine',
'vi_VN': 'Vietnamese_Viet Nam',
'tlh_TLH': 'Klingon',
}
class UNIX_LINE_TERMINATOR(csv.excel):
lineterminator = '\n'
csv.register_dialect("UNIX", UNIX_LINE_TERMINATOR)
#
# Warning: better use self.pool.get('ir.translation')._get_source if you can
#
def translate(cr, name, source_type, lang, source=None):
if source and name:
cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s and src=%s', (lang, source_type, str(name), source))
elif name:
cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s', (lang, source_type, str(name)))
elif source:
cr.execute('select value from ir_translation where lang=%s and type=%s and src=%s', (lang, source_type, source))
res_trans = cr.fetchone()
res = res_trans and res_trans[0] or False
return res
class GettextAlias(object):
def _get_db(self):
# find current DB based on thread/worker db name (see netsvc)
db_name = getattr(threading.currentThread(), 'dbname', None)
if db_name:
return sql_db.db_connect(db_name)
def _get_cr(self, frame, allow_create=True):
is_new_cr = False
cr = frame.f_locals.get('cr', frame.f_locals.get('cursor'))
if not cr:
s = frame.f_locals.get('self', {})
cr = getattr(s, 'cr', None)
if not cr and allow_create:
db = self._get_db()
if db:
cr = db.cursor()
is_new_cr = True
return cr, is_new_cr
def _get_uid(self, frame):
return frame.f_locals.get('uid') or frame.f_locals.get('user')
def _get_lang(self, frame):
lang = None
ctx = frame.f_locals.get('context')
if not ctx:
kwargs = frame.f_locals.get('kwargs')
if kwargs is None:
args = frame.f_locals.get('args')
if args and isinstance(args, (list, tuple)) \
and isinstance(args[-1], dict):
ctx = args[-1]
elif isinstance(kwargs, dict):
ctx = kwargs.get('context')
if ctx:
lang = ctx.get('lang')
s = frame.f_locals.get('self', {})
if not lang:
c = getattr(s, 'localcontext', None)
if c:
lang = c.get('lang')
if not lang:
# Last resort: attempt to guess the language of the user
# Pitfall: some operations are performed in sudo mode, and we
# don't know the originial uid, so the language may
# be wrong when the admin language differs.
pool = getattr(s, 'pool', None)
(cr, dummy) = self._get_cr(frame, allow_create=False)
uid = self._get_uid(frame)
if pool and cr and uid:
lang = pool.get('res.users').context_get(cr, uid)['lang']
return lang
def __call__(self, source):
res = source
cr = None
is_new_cr = False
try:
frame = inspect.currentframe()
if frame is None:
return source
frame = frame.f_back
if not frame:
return source
lang = self._get_lang(frame)
if lang:
cr, is_new_cr = self._get_cr(frame)
if cr:
# Try to use ir.translation to benefit from global cache if possible
pool = pooler.get_pool(cr.dbname)
res = pool.get('ir.translation')._get_source(cr, SUPERUSER_ID, None, ('code','sql_constraint'), lang, source)
else:
_logger.debug('no context cursor detected, skipping translation for "%r"', source)
else:
_logger.debug('no translation language detected, skipping translation for "%r" ', source)
except Exception:
_logger.debug('translation went wrong for "%r", skipped', source)
# if so, double-check the root/base translations filenames
finally:
if cr and is_new_cr:
cr.close()
return res
_ = GettextAlias()
def quote(s):
"""Returns quoted PO term string, with special PO characters escaped"""
assert r"\n" not in s, "Translation terms may not include escaped newlines ('\\n'), please use only literal newlines! (in '%s')" % s
return '"%s"' % s.replace('\\','\\\\') \
.replace('"','\\"') \
.replace('\n', '\\n"\n"')
re_escaped_char = re.compile(r"(\\.)")
re_escaped_replacements = {'n': '\n', }
def _sub_replacement(match_obj):
return re_escaped_replacements.get(match_obj.group(1)[1], match_obj.group(1)[1])
def unquote(str):
"""Returns unquoted PO term string, with special PO characters unescaped"""
return re_escaped_char.sub(_sub_replacement, str[1:-1])
# class to handle po files
class TinyPoFile(object):
def __init__(self, buffer):
self.buffer = buffer
def warn(self, msg, *args):
_logger.warning(msg, *args)
def __iter__(self):
self.buffer.seek(0)
self.lines = self._get_lines()
self.lines_count = len(self.lines)
self.first = True
self.extra_lines= []
return self
def _get_lines(self):
lines = self.buffer.readlines()
# remove the BOM (Byte Order Mark):
if len(lines):
lines[0] = unicode(lines[0], 'utf8').lstrip(unicode( codecs.BOM_UTF8, "utf8"))
lines.append('') # ensure that the file ends with at least an empty line
return lines
def cur_line(self):
return self.lines_count - len(self.lines)
def next(self):
trans_type = name = res_id = source = trad = None
if self.extra_lines:
trans_type, name, res_id, source, trad, comments = self.extra_lines.pop(0)
if not res_id:
res_id = '0'
else:
comments = []
targets = []
line = None
fuzzy = False
while not line:
if 0 == len(self.lines):
raise StopIteration()
line = self.lines.pop(0).strip()
while line.startswith('#'):
if line.startswith('#~ '):
break
if line.startswith('#.'):
line = line[2:].strip()
if not line.startswith('module:'):
comments.append(line)
elif line.startswith('#:'):
for lpart in line[2:].strip().split(' '):
trans_info = lpart.strip().split(':',2)
if trans_info and len(trans_info) == 2:
# looks like the translation trans_type is missing, which is not
# unexpected because it is not a GetText standard. Default: 'code'
trans_info[:0] = ['code']
if trans_info and len(trans_info) == 3:
# this is a ref line holding the destination info (model, field, record)
targets.append(trans_info)
elif line.startswith('#,') and (line[2:].strip() == 'fuzzy'):
fuzzy = True
line = self.lines.pop(0).strip()
while not line:
# allow empty lines between comments and msgid
line = self.lines.pop(0).strip()
if line.startswith('#~ '):
while line.startswith('#~ ') or not line.strip():
if 0 == len(self.lines):
raise StopIteration()
line = self.lines.pop(0)
# This has been a deprecated entry, don't return anything
return self.next()
if not line.startswith('msgid'):
raise Exception("malformed file: bad line: %s" % line)
source = unquote(line[6:])
line = self.lines.pop(0).strip()
if not source and self.first:
# if the source is "" and it's the first msgid, it's the special
# msgstr with the informations about the traduction and the
# traductor; we skip it
self.extra_lines = []
while line:
line = self.lines.pop(0).strip()
return self.next()
while not line.startswith('msgstr'):
if not line:
raise Exception('malformed file at %d'% self.cur_line())
source += unquote(line)
line = self.lines.pop(0).strip()
trad = unquote(line[7:])
line = self.lines.pop(0).strip()
while line:
trad += unquote(line)
line = self.lines.pop(0).strip()
if targets and not fuzzy:
trans_type, name, res_id = targets.pop(0)
for t, n, r in targets:
if t == trans_type == 'code': continue
self.extra_lines.append((t, n, r, source, trad, comments))
self.first = False
if name is None:
if not fuzzy:
self.warn('Missing "#:" formated comment at line %d for the following source:\n\t%s',
self.cur_line(), source[:30])
return self.next()
return trans_type, name, res_id, source, trad, '\n'.join(comments)
def write_infos(self, modules):
import openerp.release as release
self.buffer.write("# Translation of %(project)s.\n" \
"# This file contains the translation of the following modules:\n" \
"%(modules)s" \
"#\n" \
"msgid \"\"\n" \
"msgstr \"\"\n" \
'''"Project-Id-Version: %(project)s %(version)s\\n"\n''' \
'''"Report-Msgid-Bugs-To: \\n"\n''' \
'''"POT-Creation-Date: %(now)s\\n"\n''' \
'''"PO-Revision-Date: %(now)s\\n"\n''' \
'''"Last-Translator: <>\\n"\n''' \
'''"Language-Team: \\n"\n''' \
'''"MIME-Version: 1.0\\n"\n''' \
'''"Content-Type: text/plain; charset=UTF-8\\n"\n''' \
'''"Content-Transfer-Encoding: \\n"\n''' \
'''"Plural-Forms: \\n"\n''' \
"\n"
% { 'project': release.description,
'version': release.version,
'modules': reduce(lambda s, m: s + "#\t* %s\n" % m, modules, ""),
'now': datetime.utcnow().strftime('%Y-%m-%d %H:%M')+"+0000",
}
)
def write(self, modules, tnrs, source, trad, comments=None):
plurial = len(modules) > 1 and 's' or ''
self.buffer.write("#. module%s: %s\n" % (plurial, ', '.join(modules)))
if comments:
self.buffer.write(''.join(('#. %s\n' % c for c in comments)))
code = False
for typy, name, res_id in tnrs:
self.buffer.write("#: %s:%s:%s\n" % (typy, name, res_id))
if typy == 'code':
code = True
if code:
# only strings in python code are python formated
self.buffer.write("#, python-format\n")
if not isinstance(trad, unicode):
trad = unicode(trad, 'utf8')
if not isinstance(source, unicode):
source = unicode(source, 'utf8')
msg = "msgid %s\n" \
"msgstr %s\n\n" \
% (quote(source), quote(trad))
self.buffer.write(msg.encode('utf8'))
# Methods to export the translation file
def trans_export(lang, modules, buffer, format, cr):
def _process(format, modules, rows, buffer, lang):
if format == 'csv':
writer = csv.writer(buffer, 'UNIX')
# write header first
writer.writerow(("module","type","name","res_id","src","value"))
for module, type, name, res_id, src, trad, comments in rows:
# Comments are ignored by the CSV writer
writer.writerow((module, type, name, res_id, src, trad))
elif format == 'po':
writer = TinyPoFile(buffer)
writer.write_infos(modules)
# we now group the translations by source. That means one translation per source.
grouped_rows = {}
for module, type, name, res_id, src, trad, comments in rows:
row = grouped_rows.setdefault(src, {})
row.setdefault('modules', set()).add(module)
if not row.get('translation') and trad != src:
row['translation'] = trad
row.setdefault('tnrs', []).append((type, name, res_id))
row.setdefault('comments', set()).update(comments)
for src, row in grouped_rows.items():
if not lang:
# translation template, so no translation value
row['translation'] = ''
elif not row.get('translation'):
row['translation'] = src
writer.write(row['modules'], row['tnrs'], src, row['translation'], row['comments'])
elif format == 'tgz':
rows_by_module = {}
for row in rows:
module = row[0]
rows_by_module.setdefault(module, []).append(row)
tmpdir = tempfile.mkdtemp()
for mod, modrows in rows_by_module.items():
tmpmoddir = join(tmpdir, mod, 'i18n')
os.makedirs(tmpmoddir)
pofilename = (lang if lang else mod) + ".po" + ('t' if not lang else '')
buf = file(join(tmpmoddir, pofilename), 'w')
_process('po', [mod], modrows, buf, lang)
buf.close()
tar = tarfile.open(fileobj=buffer, mode='w|gz')
tar.add(tmpdir, '')
tar.close()
else:
raise Exception(_('Unrecognized extension: must be one of '
'.csv, .po, or .tgz (received .%s).' % format))
trans_lang = lang
if not trans_lang and format == 'csv':
# CSV files are meant for translators and they need a starting point,
# so we at least put the original term in the translation column
trans_lang = 'en_US'
translations = trans_generate(lang, modules, cr)
modules = set([t[0] for t in translations[1:]])
_process(format, modules, translations, buffer, lang)
del translations
def trans_parse_xsl(de):
return list(set(trans_parse_xsl_aux(de, False)))
def trans_parse_xsl_aux(de, t):
res = []
for n in de:
t = t or n.get("t")
if t:
if isinstance(n, SKIPPED_ELEMENT_TYPES) or n.tag.startswith('{http://www.w3.org/1999/XSL/Transform}'):
continue
if n.text:
l = n.text.strip().replace('\n',' ')
if len(l):
res.append(l.encode("utf8"))
if n.tail:
l = n.tail.strip().replace('\n',' ')
if len(l):
res.append(l.encode("utf8"))
res.extend(trans_parse_xsl_aux(n, t))
return res
def trans_parse_rml(de):
res = []
for n in de:
for m in n:
if isinstance(m, SKIPPED_ELEMENT_TYPES) or not m.text:
continue
string_list = [s.replace('\n', ' ').strip() for s in re.split('\[\[.+?\]\]', m.text)]
for s in string_list:
if s:
res.append(s.encode("utf8"))
res.extend(trans_parse_rml(n))
return res
def trans_parse_view(de):
res = []
if not isinstance(de, SKIPPED_ELEMENT_TYPES) and de.text and de.text.strip():
res.append(de.text.strip().encode("utf8"))
if de.tail and de.tail.strip():
res.append(de.tail.strip().encode("utf8"))
if de.tag == 'attribute' and de.get("name") == 'string':
if de.text:
res.append(de.text.encode("utf8"))
if de.get("string"):
res.append(de.get('string').encode("utf8"))
if de.get("help"):
res.append(de.get('help').encode("utf8"))
if de.get("sum"):
res.append(de.get('sum').encode("utf8"))
if de.get("confirm"):
res.append(de.get('confirm').encode("utf8"))
if de.get("placeholder"):
res.append(de.get('placeholder').encode("utf8"))
for n in de:
res.extend(trans_parse_view(n))
return res
# tests whether an object is in a list of modules
def in_modules(object_name, modules):
if 'all' in modules:
return True
module_dict = {
'ir': 'base',
'res': 'base',
'workflow': 'base',
}
module = object_name.split('.')[0]
module = module_dict.get(module, module)
return module in modules
def babel_extract_qweb(fileobj, keywords, comment_tags, options):
"""Babel message extractor for qweb template files.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should
be recognized as translation functions
:param comment_tags: a list of translator tags to search for and
include in the results
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)``
tuples
:rtype: ``iterator``
"""
result = []
def handle_text(text, lineno):
text = (text or "").strip()
if len(text) > 1: # Avoid mono-char tokens like ':' ',' etc.
result.append((lineno, None, text, []))
# not using elementTree.iterparse because we need to skip sub-trees in case
# the ancestor element had a reason to be skipped
def iter_elements(current_element):
for el in current_element:
if isinstance(el, SKIPPED_ELEMENT_TYPES): continue
if "t-js" not in el.attrib and \
not ("t-jquery" in el.attrib and "t-operation" not in el.attrib) and \
not ("t-translation" in el.attrib and el.attrib["t-translation"].strip() == "off"):
handle_text(el.text, el.sourceline)
for att in ('title', 'alt', 'label', 'placeholder'):
if att in el.attrib:
handle_text(el.attrib[att], el.sourceline)
iter_elements(el)
handle_text(el.tail, el.sourceline)
tree = etree.parse(fileobj)
iter_elements(tree.getroot())
return result
def trans_generate(lang, modules, cr):
dbname = cr.dbname
pool = pooler.get_pool(dbname)
trans_obj = pool.get('ir.translation')
model_data_obj = pool.get('ir.model.data')
uid = 1
l = pool.models.items()
l.sort()
query = 'SELECT name, model, res_id, module' \
' FROM ir_model_data'
query_models = """SELECT m.id, m.model, imd.module
FROM ir_model AS m, ir_model_data AS imd
WHERE m.id = imd.res_id AND imd.model = 'ir.model' """
if 'all_installed' in modules:
query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') '
query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') "
query_param = None
if 'all' not in modules:
query += ' WHERE module IN %s'
query_models += ' AND imd.module in %s'
query_param = (tuple(modules),)
query += ' ORDER BY module, model, name'
query_models += ' ORDER BY module, model'
cr.execute(query, query_param)
_to_translate = []
def push_translation(module, type, name, id, source, comments=None):
tuple = (module, source, name, id, type, comments or [])
# empty and one-letter terms are ignored, they probably are not meant to be
# translated, and would be very hard to translate anyway.
if not source or len(source.strip()) <= 1:
_logger.debug("Ignoring empty or 1-letter source term: %r", tuple)
return
if tuple not in _to_translate:
_to_translate.append(tuple)
def encode(s):
if isinstance(s, unicode):
return s.encode('utf8')
return s
for (xml_name,model,res_id,module) in cr.fetchall():
module = encode(module)
model = encode(model)
xml_name = "%s.%s" % (module, encode(xml_name))
if not pool.get(model):
_logger.error("Unable to find object %r", model)
continue
exists = pool.get(model).exists(cr, uid, res_id)
if not exists:
_logger.warning("Unable to find object %r with id %d", model, res_id)
continue
obj = pool.get(model).browse(cr, uid, res_id)
if model=='ir.ui.view':
d = etree.XML(encode(obj.arch))
for t in trans_parse_view(d):
push_translation(module, 'view', encode(obj.model), 0, t)
elif model=='ir.actions.wizard':
service_name = 'wizard.'+encode(obj.wiz_name)
import openerp.netsvc as netsvc
if netsvc.Service._services.get(service_name):
obj2 = netsvc.Service._services[service_name]
for state_name, state_def in obj2.states.iteritems():
if 'result' in state_def:
result = state_def['result']
if result['type'] != 'form':
continue
name = "%s,%s" % (encode(obj.wiz_name), state_name)
def_params = {
'string': ('wizard_field', lambda s: [encode(s)]),
'selection': ('selection', lambda s: [encode(e[1]) for e in ((not callable(s)) and s or [])]),
'help': ('help', lambda s: [encode(s)]),
}
# export fields
if not result.has_key('fields'):
_logger.warning("res has no fields: %r", result)
continue
for field_name, field_def in result['fields'].iteritems():
res_name = name + ',' + field_name
for fn in def_params:
if fn in field_def:
transtype, modifier = def_params[fn]
for val in modifier(field_def[fn]):
push_translation(module, transtype, res_name, 0, val)
# export arch
arch = result['arch']
if arch and not isinstance(arch, UpdateableStr):
d = etree.XML(arch)
for t in trans_parse_view(d):
push_translation(module, 'wizard_view', name, 0, t)
# export button labels
for but_args in result['state']:
button_name = but_args[0]
button_label = but_args[1]
res_name = name + ',' + button_name
push_translation(module, 'wizard_button', res_name, 0, button_label)
elif model=='ir.model.fields':
try:
field_name = encode(obj.name)
except AttributeError, exc:
_logger.error("name error in %s: %s", xml_name, str(exc))
continue
objmodel = pool.get(obj.model)
if not objmodel or not field_name in objmodel._columns:
continue
field_def = objmodel._columns[field_name]
name = "%s,%s" % (encode(obj.model), field_name)
push_translation(module, 'field', name, 0, encode(field_def.string))
if field_def.help:
push_translation(module, 'help', name, 0, encode(field_def.help))
if field_def.translate:
ids = objmodel.search(cr, uid, [])
obj_values = objmodel.read(cr, uid, ids, [field_name])
for obj_value in obj_values:
res_id = obj_value['id']
if obj.name in ('ir.model', 'ir.ui.menu'):
res_id = 0
model_data_ids = model_data_obj.search(cr, uid, [
('model', '=', model),
('res_id', '=', res_id),
])
if not model_data_ids:
push_translation(module, 'model', name, 0, encode(obj_value[field_name]))
if hasattr(field_def, 'selection') and isinstance(field_def.selection, (list, tuple)):
for dummy, val in field_def.selection:
push_translation(module, 'selection', name, 0, encode(val))
elif model=='ir.actions.report.xml':
name = encode(obj.report_name)
fname = ""
if obj.report_rml:
fname = obj.report_rml
parse_func = trans_parse_rml
report_type = "report"
elif obj.report_xsl:
fname = obj.report_xsl
parse_func = trans_parse_xsl
report_type = "xsl"
if fname and obj.report_type in ('pdf', 'xsl'):
try:
report_file = misc.file_open(fname)
try:
d = etree.parse(report_file)
for t in parse_func(d.iter()):
push_translation(module, report_type, name, 0, t)
finally:
report_file.close()
except (IOError, etree.XMLSyntaxError):
_logger.exception("couldn't export translation for report %s %s %s", name, report_type, fname)
for field_name,field_def in obj._table._columns.items():
if field_def.translate:
name = model + "," + field_name
try:
trad = getattr(obj, field_name) or ''
except:
trad = ''
push_translation(module, 'model', name, xml_name, encode(trad))
# End of data for ir.model.data query results
cr.execute(query_models, query_param)
def push_constraint_msg(module, term_type, model, msg):
if not hasattr(msg, '__call__'):
push_translation(encode(module), term_type, encode(model), 0, encode(msg))
def push_local_constraints(module, model, cons_type='sql_constraints'):
"""Climb up the class hierarchy and ignore inherited constraints
from other modules"""
term_type = 'sql_constraint' if cons_type == 'sql_constraints' else 'constraint'
msg_pos = 2 if cons_type == 'sql_constraints' else 1
for cls in model.__class__.__mro__:
if getattr(cls, '_module', None) != module:
continue
constraints = getattr(cls, '_local_' + cons_type, [])
for constraint in constraints:
push_constraint_msg(module, term_type, model._name, constraint[msg_pos])
for (_, model, module) in cr.fetchall():
model_obj = pool.get(model)
if not model_obj:
_logger.error("Unable to find object %r", model)
continue
if model_obj._constraints:
push_local_constraints(module, model_obj, 'constraints')
if model_obj._sql_constraints:
push_local_constraints(module, model_obj, 'sql_constraints')
def get_module_from_path(path, mod_paths=None):
if not mod_paths:
# First, construct a list of possible paths
def_path = os.path.abspath(os.path.join(config.config['root_path'], 'addons')) # default addons path (base)
ad_paths= map(lambda m: os.path.abspath(m.strip()),config.config['addons_path'].split(','))
mod_paths=[def_path]
for adp in ad_paths:
mod_paths.append(adp)
if not os.path.isabs(adp):
mod_paths.append(adp)
elif adp.startswith(def_path):
mod_paths.append(adp[len(def_path)+1:])
for mp in mod_paths:
if path.startswith(mp) and (os.path.dirname(path) != mp):
path = path[len(mp)+1:]
return path.split(os.path.sep)[0]
return 'base' # files that are not in a module are considered as being in 'base' module
modobj = pool.get('ir.module.module')
installed_modids = modobj.search(cr, uid, [('state', '=', 'installed')])
installed_modules = map(lambda m: m['name'], modobj.read(cr, uid, installed_modids, ['name']))
root_path = os.path.join(config.config['root_path'], 'addons')
apaths = map(os.path.abspath, map(str.strip, config.config['addons_path'].split(',')))
if root_path in apaths:
path_list = apaths
else :
path_list = [root_path,] + apaths
# Also scan these non-addon paths
for bin_path in ['osv', 'report' ]:
path_list.append(os.path.join(config.config['root_path'], bin_path))
_logger.debug("Scanning modules at paths: ", path_list)
mod_paths = []
def verified_module_filepaths(fname, path, root):
fabsolutepath = join(root, fname)
frelativepath = fabsolutepath[len(path):]
display_path = "addons%s" % frelativepath
module = get_module_from_path(fabsolutepath, mod_paths=mod_paths)
if ('all' in modules or module in modules) and module in installed_modules:
return module, fabsolutepath, frelativepath, display_path
return None, None, None, None
def babel_extract_terms(fname, path, root, extract_method="python", trans_type='code',
extra_comments=None, extract_keywords={'_': None}):
module, fabsolutepath, _, display_path = verified_module_filepaths(fname, path, root)
extra_comments = extra_comments or []
if module:
src_file = open(fabsolutepath, 'r')
try:
for extracted in extract.extract(extract_method, src_file,
keywords=extract_keywords):
# Babel 0.9.6 yields lineno, message, comments
# Babel 1.3 yields lineno, message, comments, context
lineno, message, comments = extracted[:3]
push_translation(module, trans_type, display_path, lineno,
encode(message), comments + extra_comments)
except Exception:
_logger.exception("Failed to extract terms from %s", fabsolutepath)
finally:
src_file.close()
for path in path_list:
_logger.debug("Scanning files of modules at %s", path)
for root, dummy, files in osutil.walksymlinks(path):
for fname in fnmatch.filter(files, '*.py'):
babel_extract_terms(fname, path, root)
# mako provides a babel extractor: http://docs.makotemplates.org/en/latest/usage.html#babel
for fname in fnmatch.filter(files, '*.mako'):
babel_extract_terms(fname, path, root, 'mako', trans_type='report')
# Javascript source files in the static/src/js directory, rest is ignored (libs)
if fnmatch.fnmatch(root, '*/static/src/js*'):
for fname in fnmatch.filter(files, '*.js'):
babel_extract_terms(fname, path, root, 'javascript',
extra_comments=[WEB_TRANSLATION_COMMENT],
extract_keywords={'_t': None, '_lt': None})
# QWeb template files
if fnmatch.fnmatch(root, '*/static/src/xml*'):
for fname in fnmatch.filter(files, '*.xml'):
babel_extract_terms(fname, path, root, 'openerp.tools.translate:babel_extract_qweb',
extra_comments=[WEB_TRANSLATION_COMMENT])
out = []
_to_translate.sort()
# translate strings marked as to be translated
for module, source, name, id, type, comments in _to_translate:
trans = '' if not lang else trans_obj._get_source(cr, uid, name, type, lang, source)
out.append([module, type, name, id, source, encode(trans) or '', comments])
return out
def trans_load(cr, filename, lang, verbose=True, module_name=None, context=None):
try:
fileobj = misc.file_open(filename)
_logger.info("loading %s", filename)
fileformat = os.path.splitext(filename)[-1][1:].lower()
result = trans_load_data(cr, fileobj, fileformat, lang, verbose=verbose, module_name=module_name, context=context)
fileobj.close()
return result
except IOError:
if verbose:
_logger.error("couldn't read translation file %s", filename)
return None
def trans_load_data(cr, fileobj, fileformat, lang, lang_name=None, verbose=True, module_name=None, context=None):
"""Populates the ir_translation table."""
if verbose:
_logger.info('loading translation file for language %s', lang)
if context is None:
context = {}
db_name = cr.dbname
pool = pooler.get_pool(db_name)
lang_obj = pool.get('res.lang')
trans_obj = pool.get('ir.translation')
iso_lang = misc.get_iso_codes(lang)
try:
ids = lang_obj.search(cr, SUPERUSER_ID, [('code','=', lang)])
if not ids:
# lets create the language with locale information
lang_obj.load_lang(cr, SUPERUSER_ID, lang=lang, lang_name=lang_name)
# now, the serious things: we read the language file
fileobj.seek(0)
if fileformat == 'csv':
reader = csv.reader(fileobj, quotechar='"', delimiter=',')
# read the first line of the file (it contains columns titles)
for row in reader:
f = row
break
elif fileformat == 'po':
reader = TinyPoFile(fileobj)
f = ['type', 'name', 'res_id', 'src', 'value', 'comments']
else:
_logger.error('Bad file format: %s', fileformat)
raise Exception(_('Bad file format'))
# read the rest of the file
line = 1
irt_cursor = trans_obj._get_import_cursor(cr, SUPERUSER_ID, context=context)
for row in reader:
line += 1
# skip empty rows and rows where the translation field (=last fiefd) is empty
#if (not row) or (not row[-1]):
# continue
# dictionary which holds values for this line of the csv file
# {'lang': ..., 'type': ..., 'name': ..., 'res_id': ...,
# 'src': ..., 'value': ..., 'module':...}
dic = dict.fromkeys(('name', 'res_id', 'src', 'type', 'imd_model', 'imd_name', 'module', 'value', 'comments'))
dic['lang'] = lang
for i, field in enumerate(f):
dic[field] = row[i]
# This would skip terms that fail to specify a res_id
if not dic.get('res_id'):
continue
res_id = dic.pop('res_id')
if res_id and isinstance(res_id, (int, long)) \
or (isinstance(res_id, basestring) and res_id.isdigit()):
dic['res_id'] = int(res_id)
dic['module'] = module_name
else:
tmodel = dic['name'].split(',')[0]
if '.' in res_id:
tmodule, tname = res_id.split('.', 1)
else:
tmodule = False
tname = res_id
dic['imd_model'] = tmodel
dic['imd_name'] = tname
dic['module'] = tmodule
dic['res_id'] = None
irt_cursor.push(dic)
irt_cursor.finish()
trans_obj.clear_caches()
if verbose:
_logger.info("translation file loaded succesfully")
except IOError:
filename = '[lang: %s][format: %s]' % (iso_lang or 'new', fileformat)
_logger.exception("couldn't read translation file %s", filename)
def get_locales(lang=None):
if lang is None:
lang = locale.getdefaultlocale()[0]
if os.name == 'nt':
lang = _LOCALE2WIN32.get(lang, lang)
def process(enc):
ln = locale._build_localename((lang, enc))
yield ln
nln = locale.normalize(ln)
if nln != ln:
yield nln
for x in process('utf8'): yield x
prefenc = locale.getpreferredencoding()
if prefenc:
for x in process(prefenc): yield x
prefenc = {
'latin1': 'latin9',
'iso-8859-1': 'iso8859-15',
'cp1252': '1252',
}.get(prefenc.lower())
if prefenc:
for x in process(prefenc): yield x
yield lang
def resetlocale():
# locale.resetlocale is bugged with some locales.
for ln in get_locales():
try:
return locale.setlocale(locale.LC_ALL, ln)
except locale.Error:
continue
def load_language(cr, lang):
"""Loads a translation terms for a language.
Used mainly to automate language loading at db initialization.
:param lang: language ISO code with optional _underscore_ and l10n flavor (ex: 'fr', 'fr_BE', but not 'fr-BE')
:type lang: str
"""
pool = pooler.get_pool(cr.dbname)
language_installer = pool.get('base.language.install')
uid = 1
oid = language_installer.create(cr, uid, {'lang': lang})
language_installer.lang_install(cr, uid, [oid], context=None)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
|
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Various classes representing TPU distributed values.
Note that the tests are in values_test.py .
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
from tensorflow.python.distribute import packed_distributed_variable as packed
from tensorflow.python.distribute import tpu_util
from tensorflow.python.distribute import values
from tensorflow.python.distribute import values_util
from tensorflow.python.eager import context
from tensorflow.python.eager import tape
from tensorflow.python.framework import ops
from tensorflow.python.ops import gen_resource_variable_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope
@contextlib.contextmanager
def _maybe_enter_graph(tensor):
# Note: might have an eager tensor but not be executing eagerly when
# building functions.
if (context.executing_eagerly() or isinstance(tensor, ops.EagerTensor) or
ops.has_default_graph()):
yield
else:
with tensor.graph.as_default():
yield
@contextlib.contextmanager
def _maybe_on_device(var):
# Add a device scope for packed variables.
if isinstance(var, packed.PackedVarAndDevice):
with ops.device(var.device):
yield
else:
yield
def _make_raw_assign_fn(raw_assign_fn): # pylint: disable=missing-docstring
def assign_fn(var, value, use_locking=False, name=None, read_value=True): # pylint: disable=missing-docstring
del use_locking # Unused.
handle = var.handle
with _maybe_enter_graph(handle), _maybe_on_device(var):
op = raw_assign_fn(
handle, ops.convert_to_tensor(value, dtype=var.dtype), name=name)
with ops.control_dependencies([op]):
return var._read_variable_op() if read_value else op # pylint: disable=protected-access
return assign_fn
class TPUVariableMixin(object):
"""Mixin for TPU variables."""
def __init__(self, *args, **kwargs):
super(TPUVariableMixin, self).__init__(*args, **kwargs)
# Handle ID is needed for `get_replicated_var_handle` to cache the variables
# correctly since in eager mode different variables can have the same name.
if ops.executing_eagerly_outside_functions():
self._handle_id = self._common_name + "_" + str(id(self._primary))
else:
self._handle_id = self._common_name
def __getattr__(self, name):
if tpu_util.enclosing_tpu_context() is None:
return super(TPUVariableMixin, self).__getattr__(name)
else:
raise AttributeError(
"'{}' not accessible within a TPU context.".format(name))
def get(self):
if tpu_util.enclosing_tpu_context() is None:
return super(TPUVariableMixin, self).get()
else:
raise NotImplementedError(
"`TPUVariableMixin.get()` is not supported within a TPU context.")
def _get_as_operand(self):
return self.read_value()
def _is_mirrored(self):
raise NotImplementedError(
"`TPUVariableMixin._is_mirrored()` must be implemented by subclasses.")
@property
def handle(self):
"""The handle by which this variable can be accessed."""
# If we're in a tpu.rewrite(), return the replicated handle.
tpu_context = tpu_util.enclosing_tpu_context()
if tpu_context is None or context.executing_eagerly():
var = self._get_on_device_or_primary()
if isinstance(var, packed.PackedVarAndDevice):
return var.on_device_handle()
else:
return var.handle
else:
is_packed = self._packed_var is not None
val = self._values
if is_packed:
val = [self._packed_var]
return tpu_context.get_replicated_var_handle(self._handle_id, val,
self._is_mirrored(),
is_packed)
@property
def device(self):
return self.handle.device
def _read_variable_op(self):
"""Reads the value of this variable."""
if self.trainable:
tape.variable_accessed(self)
handle = self.handle
if getattr(handle, "is_packed", False):
# Add a device scope for a packed variable handle.
with ops.device(self._get_on_device_or_primary().device):
return gen_resource_variable_ops.read_variable_op(handle, self.dtype)
else:
return gen_resource_variable_ops.read_variable_op(handle, self.dtype)
def read_value(self):
if tpu_util.enclosing_tpu_context() is None:
return super(TPUVariableMixin, self).read_value()
else:
return self._read_variable_op()
def value(self):
if tpu_util.enclosing_tpu_context() is None:
return super(TPUVariableMixin, self).value()
else:
return self._read_variable_op()
def _as_graph_element(self):
if tpu_util.enclosing_tpu_context() is None:
return super(TPUVariableMixin, self)._as_graph_element() # pylint: disable=protected-access
else:
return None
@property
def op(self):
if values_util.is_saving_non_distributed():
return self._primary.op
return values.DistributedVarOp(self._primary.op.name,
self._primary.op.graph,
self._primary.op.traceback,
self._primary.op.type)
def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False):
"""Converts a variable to a tensor."""
# pylint: disable=protected-access
if tpu_util.enclosing_tpu_context() is None:
return super(TPUVariableMixin, self)._dense_var_to_tensor(
dtype=dtype, name=name, as_ref=as_ref)
# pylint: enable=protected-access
elif dtype is not None and dtype != self.dtype:
return math_ops.cast(self.read_value(), dtype)
else:
return self.handle if as_ref else self.read_value()
class TPUDistributedVariable(TPUVariableMixin, values.DistributedVariable):
"""DistributedVariable subclass for TPUStrategy."""
def _is_mirrored(self):
return self._policy._is_mirrored() # pylint: disable=protected-access
def assign_sub(self, value, use_locking=False, name=None, read_value=True):
if values_util.is_saving_non_distributed():
return self._primary.assign_sub(value, use_locking, name, read_value)
return self._policy.assign_sub(
self, value, use_locking=use_locking, name=name, read_value=read_value)
def assign_add(self, value, use_locking=False, name=None, read_value=True):
if values_util.is_saving_non_distributed():
return self._primary.assign_add(value, use_locking, name, read_value)
return self._policy.assign_add(
self, value, use_locking=use_locking, name=name, read_value=read_value)
def assign(self, value, use_locking=False, name=None, read_value=True):
if values_util.is_saving_non_distributed():
return self._primary.assign(value, use_locking, name, read_value)
return self._policy.assign(
self, value, use_locking=use_locking, name=name, read_value=read_value)
def scatter_sub(self, sparse_delta, use_locking=False, name=None):
if values_util.is_saving_non_distributed():
return self._primary.scatter_sub(sparse_delta, use_locking, name)
return self._policy.scatter_sub(
self, sparse_delta, use_locking=use_locking, name=name)
def scatter_add(self, sparse_delta, use_locking=False, name=None):
if values_util.is_saving_non_distributed():
return self._primary.scatter_add(sparse_delta, use_locking, name)
return self._policy.scatter_add(
self, sparse_delta, use_locking=use_locking, name=name)
def scatter_mul(self, sparse_delta, use_locking=False, name=None):
if values_util.is_saving_non_distributed():
return self._primary.scatter_mul(sparse_delta, use_locking, name)
return self._policy.scatter_mul(
self, sparse_delta, use_locking=use_locking, name=name)
def scatter_div(self, sparse_delta, use_locking=False, name=None):
if values_util.is_saving_non_distributed():
return self._primary.scatter_div(sparse_delta, use_locking, name)
return self._policy.scatter_div(
self, sparse_delta, use_locking=use_locking, name=name)
def scatter_min(self, sparse_delta, use_locking=False, name=None):
if values_util.is_saving_non_distributed():
return self._primary.scatter_min(sparse_delta, use_locking, name)
return self._policy.scatter_min(
self, sparse_delta, use_locking=use_locking, name=name)
def scatter_max(self, sparse_delta, use_locking=False, name=None):
if values_util.is_saving_non_distributed():
return self._primary.scatter_max(sparse_delta, use_locking, name)
return self._policy.scatter_max(
self, sparse_delta, use_locking=use_locking, name=name)
def scatter_update(self, sparse_delta, use_locking=False, name=None):
if values_util.is_saving_non_distributed():
return self._primary.scatter_update(sparse_delta, use_locking, name)
return self._policy.scatter_update(
self, sparse_delta, use_locking=use_locking, name=name)
class TPUMirroredVariable(TPUVariableMixin, values.MirroredVariable):
"""Holds a map from replica to TPU variables whose values are kept in sync."""
def assign_sub(self, value, use_locking=False, name=None, read_value=True):
if (tpu_util.enclosing_tpu_context() and
self.aggregation == variable_scope.VariableAggregation.NONE):
return _make_raw_assign_fn(
gen_resource_variable_ops.assign_sub_variable_op)(
self,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
return assign_sub(
self, value, use_locking=use_locking, name=name, read_value=read_value)
def assign_add(self, value, use_locking=False, name=None, read_value=True):
if (tpu_util.enclosing_tpu_context() and
self.aggregation == variable_scope.VariableAggregation.NONE):
return _make_raw_assign_fn(
gen_resource_variable_ops.assign_add_variable_op)(
self,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
return assign_add(
self, value, use_locking=use_locking, name=name, read_value=read_value)
def assign(self, value, use_locking=False, name=None, read_value=True):
if (tpu_util.enclosing_tpu_context() and
self.aggregation == variable_scope.VariableAggregation.NONE):
return _make_raw_assign_fn(gen_resource_variable_ops.assign_variable_op)(
self,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
return assign(
self, value, use_locking=use_locking, name=name, read_value=read_value)
def scatter_sub(self, *args, **kwargs):
if values_util.is_saving_non_distributed():
return self._primary.scatter_sub(*args, **kwargs)
raise NotImplementedError
def scatter_add(self, *args, **kwargs):
if values_util.is_saving_non_distributed():
return self._primary.scatter_add(*args, **kwargs)
raise NotImplementedError
def scatter_max(self, *args, **kwargs):
if values_util.is_saving_non_distributed():
return self._primary.scatter_max(*args, **kwargs)
raise NotImplementedError
def scatter_min(self, *args, **kwargs):
if values_util.is_saving_non_distributed():
return self._primary.scatter_min(*args, **kwargs)
raise NotImplementedError
def scatter_mul(self, *args, **kwargs):
if values_util.is_saving_non_distributed():
return self._primary.scatter_mul(*args, **kwargs)
raise NotImplementedError
def scatter_div(self, *args, **kwargs):
if values_util.is_saving_non_distributed():
return self._primary.scatter_div(*args, **kwargs)
raise NotImplementedError
def scatter_update(self, *args, **kwargs):
if values_util.is_saving_non_distributed():
return self._primary.scatter_update(*args, **kwargs)
raise NotImplementedError
def _is_mirrored(self):
return True
class TPUSyncOnReadVariable(TPUVariableMixin, values.SyncOnReadVariable):
"""Holds a map from replica to variables whose values are reduced on save."""
def assign_sub(self, *args, **kwargs):
if tpu_util.enclosing_tpu_context() is None:
return values.SyncOnReadVariable.assign_sub(self, *args, **kwargs)
else:
return _make_raw_assign_fn(
gen_resource_variable_ops.assign_sub_variable_op)(self, *args,
**kwargs)
def assign_add(self, *args, **kwargs):
if tpu_util.enclosing_tpu_context() is None:
return values.SyncOnReadVariable.assign_add(self, *args, **kwargs)
else:
return _make_raw_assign_fn(
gen_resource_variable_ops.assign_add_variable_op)(self, *args,
**kwargs)
def assign(self, *args, **kwargs):
if tpu_util.enclosing_tpu_context() is None:
return values.SyncOnReadVariable.assign(self, *args, **kwargs)
else:
return _make_raw_assign_fn(gen_resource_variable_ops.assign_variable_op)(
self, *args, **kwargs)
def _is_mirrored(self):
return False
# Common method between OnWrite and Mirrored variables.
def assign_sub(var, value, use_locking=False, name=None, read_value=True):
assign_sub_fn = _make_raw_assign_fn(
gen_resource_variable_ops.assign_sub_variable_op)
return var._update( # pylint: disable=protected-access
update_fn=assign_sub_fn,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
def assign_add(var, value, use_locking=False, name=None, read_value=True):
assign_add_fn = _make_raw_assign_fn(
gen_resource_variable_ops.assign_add_variable_op)
return var._update( # pylint: disable=protected-access
update_fn=assign_add_fn,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
def assign(var, value, use_locking=False, name=None, read_value=True):
assign_fn = _make_raw_assign_fn(gen_resource_variable_ops.assign_variable_op)
return var._update( # pylint: disable=protected-access
update_fn=assign_fn,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
class TPUOnWritePolicy(values.OnWritePolicy):
"""Policy defined for `tf.VariableSynchronization.ON_WRITE` synchronization.
This policy is created when `synchronization` is set to
`tf.VariableSynchronization.AUTO` or `tf.VariableSynchronization.ON_WRITE`.
"""
def assign_sub(self,
var,
value,
use_locking=False,
name=None,
read_value=True):
if (tpu_util.enclosing_tpu_context() and
var.aggregation == variable_scope.VariableAggregation.NONE):
return _make_raw_assign_fn(
gen_resource_variable_ops.assign_sub_variable_op)(
var,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
return assign_sub(
var, value, use_locking=use_locking, name=name, read_value=read_value)
def assign_add(self,
var,
value,
use_locking=False,
name=None,
read_value=True):
if (tpu_util.enclosing_tpu_context() and
var.aggregation == variable_scope.VariableAggregation.NONE):
return _make_raw_assign_fn(
gen_resource_variable_ops.assign_add_variable_op)(
var,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
return assign_add(
var, value, use_locking=use_locking, name=name, read_value=read_value)
def assign(self, var, value, use_locking=False, name=None, read_value=True):
if (tpu_util.enclosing_tpu_context() and
var.aggregation == variable_scope.VariableAggregation.NONE):
return _make_raw_assign_fn(gen_resource_variable_ops.assign_variable_op)(
var,
value=value,
use_locking=use_locking,
name=name,
read_value=read_value)
return assign(
var, value, use_locking=use_locking, name=name, read_value=read_value)
def scatter_sub(self, *args, **kwargs):
raise NotImplementedError
def scatter_add(self, *args, **kwargs):
raise NotImplementedError
def scatter_max(self, *args, **kwargs):
raise NotImplementedError
def scatter_min(self, *args, **kwargs):
raise NotImplementedError
def scatter_mul(self, *args, **kwargs):
raise NotImplementedError
def scatter_div(self, *args, **kwargs):
raise NotImplementedError
def scatter_update(self, *args, **kwargs):
raise NotImplementedError
def _is_mirrored(self):
return True
class TPUOnReadPolicy(values.OnReadPolicy):
"""Policy defined for `tf.VariableSynchronization.ON_READ` synchronization.
This policy is created when `synchronization` is set to
`tf.VariableSynchronization.ON_READ` and `aggregation` is set to any of the
values allowed by the `tf.VariableAggregation` enum such as `NONE`, `SUM`,
`MEAN` or `ONLY_FIRST_REPLICA`when creating a `tf.Variable` in `tf.distribute`
scope.
"""
def assign_sub(self, var, *args, **kwargs):
if tpu_util.enclosing_tpu_context() is None:
return super(TPUOnReadPolicy, self).assign_sub(var, *args, **kwargs)
else:
return _make_raw_assign_fn(
gen_resource_variable_ops.assign_sub_variable_op)(var, *args,
**kwargs)
def assign_add(self, var, *args, **kwargs):
if tpu_util.enclosing_tpu_context() is None:
return super(TPUOnReadPolicy, self).assign_add(var, *args, **kwargs)
else:
return _make_raw_assign_fn(
gen_resource_variable_ops.assign_add_variable_op)(var, *args,
**kwargs)
def assign(self, var, *args, **kwargs):
if tpu_util.enclosing_tpu_context() is None:
return super(TPUOnReadPolicy, self).assign(var, *args, **kwargs)
else:
return _make_raw_assign_fn(gen_resource_variable_ops.assign_variable_op)(
var, *args, **kwargs)
def _is_mirrored(self):
return False
def scatter_sub(self, *args, **kwargs):
raise NotImplementedError
def scatter_add(self, *args, **kwargs):
raise NotImplementedError
def scatter_max(self, *args, **kwargs):
raise NotImplementedError
def scatter_min(self, *args, **kwargs):
raise NotImplementedError
def scatter_mul(self, *args, **kwargs):
raise NotImplementedError
def scatter_div(self, *args, **kwargs):
raise NotImplementedError
def scatter_update(self, *args, **kwargs):
raise NotImplementedError
|
|
#
# 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.
import json
import os
import mock
from oslo_config import fixture as config_fixture
import six
from heat.api.aws import exception
import heat.api.cfn.v1.stacks as stacks
from heat.common import exception as heat_exception
from heat.common import identifier
from heat.common import policy
from heat.common import wsgi
from heat.rpc import api as rpc_api
from heat.rpc import client as rpc_client
from heat.tests import common
from heat.tests import utils
policy_path = os.path.dirname(os.path.realpath(__file__)) + "/../../policy/"
class CfnStackControllerTest(common.HeatTestCase):
"""Tests the API class CfnStackController.
Tests the API class which acts as the WSGI controller,
the endpoint processing API requests after they are routed
"""
def setUp(self):
super(CfnStackControllerTest, self).setUp()
self.fixture = self.useFixture(config_fixture.Config())
self.fixture.conf(args=['--config-dir', policy_path])
self.topic = rpc_api.ENGINE_TOPIC
self.api_version = '1.0'
self.template = {u'AWSTemplateFormatVersion': u'2010-09-09',
u'Foo': u'bar'}
# Create WSGI controller instance
class DummyConfig(object):
bind_port = 8000
cfgopts = DummyConfig()
self.controller = stacks.StackController(options=cfgopts)
self.controller.policy.enforcer.policy_path = (policy_path +
'deny_stack_user.json')
self.addCleanup(self.m.VerifyAll)
def test_default(self):
self.assertRaises(
exception.HeatInvalidActionError, self.controller.default, None)
def tearDown(self):
super(CfnStackControllerTest, self).tearDown()
def _dummy_GET_request(self, params=None):
# Mangle the params dict into a query string
params = params or {}
qs = "&".join(["=".join([k, str(params[k])]) for k in params])
environ = {'REQUEST_METHOD': 'GET', 'QUERY_STRING': qs}
req = wsgi.Request(environ)
req.context = utils.dummy_context()
return req
def _stub_enforce(self, req, action, allowed=True):
self.m.StubOutWithMock(policy.Enforcer, 'enforce')
if allowed:
policy.Enforcer.enforce(req.context, action
).AndReturn(True)
else:
policy.Enforcer.enforce(req.context, action
).AndRaise(heat_exception.Forbidden)
self.m.ReplayAll()
# The tests
def test_stackid_addprefix(self):
self.m.ReplayAll()
response = self.controller._id_format({
'StackName': 'Foo',
'StackId': {
u'tenant': u't',
u'stack_name': u'Foo',
u'stack_id': u'123',
u'path': u''
}
})
expected = {'StackName': 'Foo',
'StackId': 'arn:openstack:heat::t:stacks/Foo/123'}
self.assertEqual(expected, response)
def test_enforce_ok(self):
params = {'Action': 'ListStacks'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'ListStacks')
response = self.controller._enforce(dummy_req, 'ListStacks')
self.assertIsNone(response)
def test_enforce_denied(self):
self.m.ReplayAll()
params = {'Action': 'ListStacks'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'ListStacks', False)
self.assertRaises(exception.HeatAccessDeniedError,
self.controller._enforce, dummy_req, 'ListStacks')
def test_enforce_ise(self):
params = {'Action': 'ListStacks'}
dummy_req = self._dummy_GET_request(params)
dummy_req.context.roles = ['heat_stack_user']
self.m.StubOutWithMock(policy.Enforcer, 'enforce')
policy.Enforcer.enforce(dummy_req.context, 'ListStacks'
).AndRaise(AttributeError)
self.m.ReplayAll()
self.assertRaises(exception.HeatInternalFailureError,
self.controller._enforce, dummy_req, 'ListStacks')
@mock.patch.object(rpc_client.EngineClient, 'call')
def test_list(self, mock_call):
# Format a dummy GET request to pass into the WSGI handler
params = {'Action': 'ListStacks'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'ListStacks')
# Stub out the RPC call to the engine with a pre-canned response
engine_resp = [{u'stack_identity': {u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'1',
u'path': u''},
u'updated_time': u'2012-07-09T09:13:11Z',
u'template_description': u'blah',
u'stack_status_reason': u'Stack successfully created',
u'creation_time': u'2012-07-09T09:12:45Z',
u'stack_name': u'wordpress',
u'stack_action': u'CREATE',
u'stack_status': u'COMPLETE'}]
mock_call.return_value = engine_resp
# Call the list controller function and compare the response
result = self.controller.list(dummy_req)
expected = {'ListStacksResponse': {'ListStacksResult':
{'StackSummaries':
[{u'StackId': u'arn:openstack:heat::t:stacks/wordpress/1',
u'LastUpdatedTime': u'2012-07-09T09:13:11Z',
u'TemplateDescription': u'blah',
u'StackStatusReason': u'Stack successfully created',
u'CreationTime': u'2012-07-09T09:12:45Z',
u'StackName': u'wordpress',
u'StackStatus': u'CREATE_COMPLETE'}]}}}
self.assertEqual(expected, result)
default_args = {'limit': None, 'sort_keys': None, 'marker': None,
'sort_dir': None, 'filters': None, 'tenant_safe': True,
'show_deleted': False, 'show_nested': False,
'show_hidden': False, 'tags': None,
'tags_any': None, 'not_tags': None,
'not_tags_any': None}
mock_call.assert_called_once_with(
dummy_req.context, ('list_stacks', default_args), version='1.8')
@mock.patch.object(rpc_client.EngineClient, 'call')
def test_list_rmt_aterr(self, mock_call):
params = {'Action': 'ListStacks'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'ListStacks')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
mock_call.side_effect = AttributeError
# Call the list controller function and compare the response
result = self.controller.list(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
mock_call.assert_called_once_with(
dummy_req.context, ('list_stacks', mock.ANY), version='1.8')
@mock.patch.object(rpc_client.EngineClient, 'call')
def test_list_rmt_interr(self, mock_call):
params = {'Action': 'ListStacks'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'ListStacks')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
mock_call.side_effect = Exception()
# Call the list controller function and compare the response
result = self.controller.list(dummy_req)
self.assertIsInstance(result, exception.HeatInternalFailureError)
mock_call.assert_called_once_with(
dummy_req.context, ('list_stacks', mock.ANY), version='1.8')
def test_describe_last_updated_time(self):
params = {'Action': 'DescribeStacks'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStacks')
engine_resp = [{u'updated_time': '1970-01-01',
u'parameters': {},
u'stack_action': u'CREATE',
u'stack_status': u'COMPLETE'}]
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('show_stack', {'stack_identity': None,
'resolve_outputs': True}),
version='1.20'
).AndReturn(engine_resp)
self.m.ReplayAll()
response = self.controller.describe(dummy_req)
result = response['DescribeStacksResponse']['DescribeStacksResult']
stack = result['Stacks'][0]
self.assertEqual('1970-01-01', stack['LastUpdatedTime'])
def test_describe_no_last_updated_time(self):
params = {'Action': 'DescribeStacks'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStacks')
engine_resp = [{u'updated_time': None,
u'parameters': {},
u'stack_action': u'CREATE',
u'stack_status': u'COMPLETE'}]
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('show_stack', {'stack_identity': None,
'resolve_outputs': True}),
version='1.20'
).AndReturn(engine_resp)
self.m.ReplayAll()
response = self.controller.describe(dummy_req)
result = response['DescribeStacksResponse']['DescribeStacksResult']
stack = result['Stacks'][0]
self.assertNotIn('LastUpdatedTime', stack)
def test_describe(self):
# Format a dummy GET request to pass into the WSGI handler
stack_name = u"wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'DescribeStacks', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStacks')
# Stub out the RPC call to the engine with a pre-canned response
# Note the engine returns a load of keys we don't actually use
# so this is a subset of the real response format
engine_resp = [{u'stack_identity':
{u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u''},
u'updated_time': u'2012-07-09T09:13:11Z',
u'parameters': {u'DBUsername': u'admin',
u'LinuxDistribution': u'F17',
u'InstanceType': u'm1.large',
u'DBRootPassword': u'admin',
u'DBPassword': u'admin',
u'DBName': u'wordpress'},
u'outputs':
[{u'output_key': u'WebsiteURL',
u'description': u'URL for Wordpress wiki',
u'output_value': u'http://10.0.0.8/wordpress'}],
u'stack_status_reason': u'Stack successfully created',
u'creation_time': u'2012-07-09T09:12:45Z',
u'stack_name': u'wordpress',
u'notification_topics': [],
u'stack_action': u'CREATE',
u'stack_status': u'COMPLETE',
u'description': u'blah',
u'disable_rollback': 'true',
u'timeout_mins':60,
u'capabilities':[]}]
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context,
('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
rpc_client.EngineClient.call(
dummy_req.context,
('show_stack', {'stack_identity': identity,
'resolve_outputs': True}),
version='1.20'
).AndReturn(engine_resp)
self.m.ReplayAll()
# Call the list controller function and compare the response
response = self.controller.describe(dummy_req)
expected = {'DescribeStacksResponse':
{'DescribeStacksResult':
{'Stacks':
[{'StackId': u'arn:openstack:heat::t:stacks/wordpress/6',
'StackStatusReason': u'Stack successfully created',
'Description': u'blah',
'Parameters':
[{'ParameterValue': u'wordpress',
'ParameterKey': u'DBName'},
{'ParameterValue': u'admin',
'ParameterKey': u'DBPassword'},
{'ParameterValue': u'admin',
'ParameterKey': u'DBRootPassword'},
{'ParameterValue': u'admin',
'ParameterKey': u'DBUsername'},
{'ParameterValue': u'm1.large',
'ParameterKey': u'InstanceType'},
{'ParameterValue': u'F17',
'ParameterKey': u'LinuxDistribution'}],
'Outputs':
[{'OutputKey': u'WebsiteURL',
'OutputValue': u'http://10.0.0.8/wordpress',
'Description': u'URL for Wordpress wiki'}],
'TimeoutInMinutes': 60,
'CreationTime': u'2012-07-09T09:12:45Z',
'Capabilities': [],
'StackName': u'wordpress',
'NotificationARNs': [],
'StackStatus': u'CREATE_COMPLETE',
'DisableRollback': 'true',
'LastUpdatedTime': u'2012-07-09T09:13:11Z'}]}}}
stacks = (response['DescribeStacksResponse']['DescribeStacksResult']
['Stacks'])
stacks[0]['Parameters'] = sorted(
stacks[0]['Parameters'], key=lambda k: k['ParameterKey'])
response['DescribeStacksResponse']['DescribeStacksResult'] = (
{'Stacks': stacks})
self.assertEqual(expected, response)
def test_describe_arn(self):
# Format a dummy GET request to pass into the WSGI handler
stack_name = u"wordpress"
stack_identifier = identifier.HeatIdentifier('t', stack_name, '6')
identity = dict(stack_identifier)
params = {'Action': 'DescribeStacks',
'StackName': stack_identifier.arn()}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStacks')
# Stub out the RPC call to the engine with a pre-canned response
# Note the engine returns a load of keys we don't actually use
# so this is a subset of the real response format
engine_resp = [{u'stack_identity': {u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u''},
u'updated_time': u'2012-07-09T09:13:11Z',
u'parameters': {u'DBUsername': u'admin',
u'LinuxDistribution': u'F17',
u'InstanceType': u'm1.large',
u'DBRootPassword': u'admin',
u'DBPassword': u'admin',
u'DBName': u'wordpress'},
u'outputs':
[{u'output_key': u'WebsiteURL',
u'description': u'URL for Wordpress wiki',
u'output_value': u'http://10.0.0.8/wordpress'}],
u'stack_status_reason': u'Stack successfully created',
u'creation_time': u'2012-07-09T09:12:45Z',
u'stack_name': u'wordpress',
u'notification_topics': [],
u'stack_action': u'CREATE',
u'stack_status': u'COMPLETE',
u'description': u'blah',
u'disable_rollback': 'true',
u'timeout_mins':60,
u'capabilities':[]}]
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context,
('show_stack', {'stack_identity': identity,
'resolve_outputs': True}),
version='1.20'
).AndReturn(engine_resp)
self.m.ReplayAll()
# Call the list controller function and compare the response
response = self.controller.describe(dummy_req)
expected = {'DescribeStacksResponse':
{'DescribeStacksResult':
{'Stacks':
[{'StackId': u'arn:openstack:heat::t:stacks/wordpress/6',
'StackStatusReason': u'Stack successfully created',
'Description': u'blah',
'Parameters':
[{'ParameterValue': u'wordpress',
'ParameterKey': u'DBName'},
{'ParameterValue': u'admin',
'ParameterKey': u'DBPassword'},
{'ParameterValue': u'admin',
'ParameterKey': u'DBRootPassword'},
{'ParameterValue': u'admin',
'ParameterKey': u'DBUsername'},
{'ParameterValue': u'm1.large',
'ParameterKey': u'InstanceType'},
{'ParameterValue': u'F17',
'ParameterKey': u'LinuxDistribution'}],
'Outputs':
[{'OutputKey': u'WebsiteURL',
'OutputValue': u'http://10.0.0.8/wordpress',
'Description': u'URL for Wordpress wiki'}],
'TimeoutInMinutes': 60,
'CreationTime': u'2012-07-09T09:12:45Z',
'Capabilities': [],
'StackName': u'wordpress',
'NotificationARNs': [],
'StackStatus': u'CREATE_COMPLETE',
'DisableRollback': 'true',
'LastUpdatedTime': u'2012-07-09T09:13:11Z'}]}}}
stacks = (response['DescribeStacksResponse']['DescribeStacksResult']
['Stacks'])
stacks[0]['Parameters'] = sorted(
stacks[0]['Parameters'], key=lambda k: k['ParameterKey'])
response['DescribeStacksResponse']['DescribeStacksResult'] = (
{'Stacks': stacks})
self.assertEqual(expected, response)
def test_describe_arn_invalidtenant(self):
# Format a dummy GET request to pass into the WSGI handler
stack_name = u"wordpress"
stack_identifier = identifier.HeatIdentifier('wibble', stack_name, '6')
identity = dict(stack_identifier)
params = {'Action': 'DescribeStacks',
'StackName': stack_identifier.arn()}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStacks')
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('show_stack', {'stack_identity': identity,
'resolve_outputs': True},),
version='1.20'
).AndRaise(heat_exception.InvalidTenant(target='test',
actual='test'))
self.m.ReplayAll()
result = self.controller.describe(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_describe_aterr(self):
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'DescribeStacks', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStacks')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
rpc_client.EngineClient.call(
dummy_req.context, ('show_stack', {'stack_identity': identity,
'resolve_outputs': True}),
version='1.20'
).AndRaise(AttributeError())
self.m.ReplayAll()
result = self.controller.describe(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_describe_bad_name(self):
stack_name = "wibble"
params = {'Action': 'DescribeStacks', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStacks')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndRaise(heat_exception.EntityNotFound(entity='Stack', name='test'))
self.m.ReplayAll()
result = self.controller.describe(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_get_template_int_body(self):
"""Test the internal _get_template function."""
params = {'TemplateBody': "abcdef"}
dummy_req = self._dummy_GET_request(params)
result = self.controller._get_template(dummy_req)
expected = "abcdef"
self.assertEqual(expected, result)
# TODO(shardy) : test the _get_template TemplateUrl case
def _stub_rpc_create_stack_call_failure(self, req_context, stack_name,
engine_parms, engine_args,
failure, need_stub=True):
if need_stub:
self.m.StubOutWithMock(policy.Enforcer, 'enforce')
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
policy.Enforcer.enforce(req_context,
'CreateStack').AndReturn(True)
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
rpc_client.EngineClient.call(
req_context,
('create_stack',
{'stack_name': stack_name,
'template': self.template,
'params': engine_parms,
'files': {},
'environment_files': None,
'args': engine_args,
'owner_id': None,
'nested_depth': 0,
'user_creds_id': None,
'parent_resource_name': None,
'stack_user_project_id': None}),
version='1.23'
).AndRaise(failure)
def _stub_rpc_create_stack_call_success(self, stack_name, engine_parms,
engine_args, parameters):
dummy_req = self._dummy_GET_request(parameters)
self._stub_enforce(dummy_req, 'CreateStack')
# Stub out the RPC call to the engine with a pre-canned response
engine_resp = {u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'1',
u'path': u''}
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context,
('create_stack',
{'stack_name': stack_name,
'template': self.template,
'params': engine_parms,
'files': {},
'environment_files': None,
'args': engine_args,
'owner_id': None,
'nested_depth': 0,
'user_creds_id': None,
'parent_resource_name': None,
'stack_user_project_id': None}),
version='1.23'
).AndReturn(engine_resp)
self.m.ReplayAll()
return dummy_req
def test_create(self):
# Format a dummy request
stack_name = "wordpress"
json_template = json.dumps(self.template)
params = {'Action': 'CreateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template,
'TimeoutInMinutes': 30,
'DisableRollback': 'true',
'Parameters.member.1.ParameterKey': 'InstanceType',
'Parameters.member.1.ParameterValue': 'm1.xlarge'}
engine_parms = {u'InstanceType': u'm1.xlarge'}
engine_args = {'timeout_mins': u'30', 'disable_rollback': 'true'}
dummy_req = self._stub_rpc_create_stack_call_success(stack_name,
engine_parms,
engine_args,
params)
response = self.controller.create(dummy_req)
expected = {
'CreateStackResponse': {
'CreateStackResult': {
u'StackId': u'arn:openstack:heat::t:stacks/wordpress/1'
}
}
}
self.assertEqual(expected, response)
def test_create_rollback(self):
# Format a dummy request
stack_name = "wordpress"
json_template = json.dumps(self.template)
params = {'Action': 'CreateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template,
'TimeoutInMinutes': 30,
'DisableRollback': 'false',
'Parameters.member.1.ParameterKey': 'InstanceType',
'Parameters.member.1.ParameterValue': 'm1.xlarge'}
engine_parms = {u'InstanceType': u'm1.xlarge'}
engine_args = {'timeout_mins': u'30', 'disable_rollback': 'false'}
dummy_req = self._stub_rpc_create_stack_call_success(stack_name,
engine_parms,
engine_args,
params)
response = self.controller.create(dummy_req)
expected = {
'CreateStackResponse': {
'CreateStackResult': {
u'StackId': u'arn:openstack:heat::t:stacks/wordpress/1'
}
}
}
self.assertEqual(expected, response)
def test_create_onfailure_true(self):
# Format a dummy request
stack_name = "wordpress"
json_template = json.dumps(self.template)
params = {'Action': 'CreateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template,
'TimeoutInMinutes': 30,
'OnFailure': 'DO_NOTHING',
'Parameters.member.1.ParameterKey': 'InstanceType',
'Parameters.member.1.ParameterValue': 'm1.xlarge'}
engine_parms = {u'InstanceType': u'm1.xlarge'}
engine_args = {'timeout_mins': u'30', 'disable_rollback': 'true'}
dummy_req = self._stub_rpc_create_stack_call_success(stack_name,
engine_parms,
engine_args,
params)
response = self.controller.create(dummy_req)
expected = {
'CreateStackResponse': {
'CreateStackResult': {
u'StackId': u'arn:openstack:heat::t:stacks/wordpress/1'
}
}
}
self.assertEqual(expected, response)
def test_create_onfailure_false_delete(self):
# Format a dummy request
stack_name = "wordpress"
json_template = json.dumps(self.template)
params = {'Action': 'CreateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template,
'TimeoutInMinutes': 30,
'OnFailure': 'DELETE',
'Parameters.member.1.ParameterKey': 'InstanceType',
'Parameters.member.1.ParameterValue': 'm1.xlarge'}
engine_parms = {u'InstanceType': u'm1.xlarge'}
engine_args = {'timeout_mins': u'30', 'disable_rollback': 'false'}
dummy_req = self._stub_rpc_create_stack_call_success(stack_name,
engine_parms,
engine_args,
params)
response = self.controller.create(dummy_req)
expected = {
'CreateStackResponse': {
'CreateStackResult': {
u'StackId': u'arn:openstack:heat::t:stacks/wordpress/1'
}
}
}
self.assertEqual(expected, response)
def test_create_onfailure_false_rollback(self):
# Format a dummy request
stack_name = "wordpress"
json_template = json.dumps(self.template)
params = {'Action': 'CreateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template,
'TimeoutInMinutes': 30,
'OnFailure': 'ROLLBACK',
'Parameters.member.1.ParameterKey': 'InstanceType',
'Parameters.member.1.ParameterValue': 'm1.xlarge'}
engine_parms = {u'InstanceType': u'm1.xlarge'}
engine_args = {'timeout_mins': u'30', 'disable_rollback': 'false'}
dummy_req = self._stub_rpc_create_stack_call_success(stack_name,
engine_parms,
engine_args,
params)
response = self.controller.create(dummy_req)
expected = {
'CreateStackResponse': {
'CreateStackResult': {
u'StackId': u'arn:openstack:heat::t:stacks/wordpress/1'
}
}
}
self.assertEqual(expected, response)
def test_create_onfailure_err(self):
# Format a dummy request
stack_name = "wordpress"
json_template = json.dumps(self.template)
params = {'Action': 'CreateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template,
'TimeoutInMinutes': 30,
'DisableRollback': 'true',
'OnFailure': 'DO_NOTHING',
'Parameters.member.1.ParameterKey': 'InstanceType',
'Parameters.member.1.ParameterValue': 'm1.xlarge'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'CreateStack')
self.assertRaises(exception.HeatInvalidParameterCombinationError,
self.controller.create, dummy_req)
def test_create_err_no_template(self):
# Format a dummy request with a missing template field
stack_name = "wordpress"
params = {'Action': 'CreateStack', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'CreateStack')
result = self.controller.create(dummy_req)
self.assertIsInstance(result, exception.HeatMissingParameterError)
def test_create_err_inval_template(self):
# Format a dummy request with an invalid TemplateBody
stack_name = "wordpress"
json_template = "!$%**_+}@~?"
params = {'Action': 'CreateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'CreateStack')
result = self.controller.create(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_create_err_rpcerr(self):
# Format a dummy request
stack_name = "wordpress"
json_template = json.dumps(self.template)
params = {'Action': 'CreateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template,
'TimeoutInMinutes': 30,
'Parameters.member.1.ParameterKey': 'InstanceType',
'Parameters.member.1.ParameterValue': 'm1.xlarge'}
engine_parms = {u'InstanceType': u'm1.xlarge'}
engine_args = {'timeout_mins': u'30'}
dummy_req = self._dummy_GET_request(params)
self._stub_rpc_create_stack_call_failure(dummy_req.context,
stack_name,
engine_parms,
engine_args,
AttributeError())
failure = heat_exception.UnknownUserParameter(key='test')
self._stub_rpc_create_stack_call_failure(dummy_req.context,
stack_name,
engine_parms,
engine_args,
failure,
False)
failure = heat_exception.UserParameterMissing(key='test')
self._stub_rpc_create_stack_call_failure(dummy_req.context,
stack_name,
engine_parms,
engine_args,
failure,
False)
self.m.ReplayAll()
result = self.controller.create(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
result = self.controller.create(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
result = self.controller.create(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_create_err_exists(self):
# Format a dummy request
stack_name = "wordpress"
json_template = json.dumps(self.template)
params = {'Action': 'CreateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template,
'TimeoutInMinutes': 30,
'Parameters.member.1.ParameterKey': 'InstanceType',
'Parameters.member.1.ParameterValue': 'm1.xlarge'}
engine_parms = {u'InstanceType': u'm1.xlarge'}
engine_args = {'timeout_mins': u'30'}
failure = heat_exception.StackExists(stack_name='test')
dummy_req = self._dummy_GET_request(params)
self._stub_rpc_create_stack_call_failure(dummy_req.context,
stack_name,
engine_parms,
engine_args,
failure)
self.m.ReplayAll()
result = self.controller.create(dummy_req)
self.assertIsInstance(result, exception.AlreadyExistsError)
def test_create_err_engine(self):
# Format a dummy request
stack_name = "wordpress"
json_template = json.dumps(self.template)
params = {'Action': 'CreateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template,
'TimeoutInMinutes': 30,
'Parameters.member.1.ParameterKey': 'InstanceType',
'Parameters.member.1.ParameterValue': 'm1.xlarge'}
engine_parms = {u'InstanceType': u'm1.xlarge'}
engine_args = {'timeout_mins': u'30'}
failure = heat_exception.StackValidationFailed(
message='Something went wrong')
dummy_req = self._dummy_GET_request(params)
self._stub_rpc_create_stack_call_failure(dummy_req.context,
stack_name,
engine_parms,
engine_args,
failure)
self.m.ReplayAll()
result = self.controller.create(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_update(self):
# Format a dummy request
stack_name = "wordpress"
json_template = json.dumps(self.template)
params = {'Action': 'UpdateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template,
'Parameters.member.1.ParameterKey': 'InstanceType',
'Parameters.member.1.ParameterValue': 'm1.xlarge'}
engine_parms = {u'InstanceType': u'm1.xlarge'}
engine_args = {}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'UpdateStack')
# Stub out the RPC call to the engine with a pre-canned response
identity = dict(identifier.HeatIdentifier('t', stack_name, '1'))
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context,
('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
rpc_client.EngineClient.call(
dummy_req.context,
('update_stack',
{'stack_identity': identity,
'template': self.template,
'params': engine_parms,
'files': {},
'environment_files': None,
'args': engine_args}),
version='1.23'
).AndReturn(identity)
self.m.ReplayAll()
response = self.controller.update(dummy_req)
expected = {
'UpdateStackResponse': {
'UpdateStackResult': {
u'StackId': u'arn:openstack:heat::t:stacks/wordpress/1'
}
}
}
self.assertEqual(expected, response)
def test_cancel_update(self):
# Format a dummy request
stack_name = "wordpress"
params = {'Action': 'CancelUpdateStack', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'CancelUpdateStack')
# Stub out the RPC call to the engine with a pre-canned response
identity = dict(identifier.HeatIdentifier('t', stack_name, '1'))
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context,
('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
rpc_client.EngineClient.call(
dummy_req.context,
('stack_cancel_update',
{'stack_identity': identity,
'cancel_with_rollback': True}),
version='1.14'
).AndReturn(identity)
self.m.ReplayAll()
response = self.controller.cancel_update(dummy_req)
expected = {
'CancelUpdateStackResponse': {
'CancelUpdateStackResult': {}
}
}
self.assertEqual(response, expected)
def test_update_bad_name(self):
stack_name = "wibble"
json_template = json.dumps(self.template)
params = {'Action': 'UpdateStack', 'StackName': stack_name,
'TemplateBody': '%s' % json_template,
'Parameters.member.1.ParameterKey': 'InstanceType',
'Parameters.member.1.ParameterValue': 'm1.xlarge'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'UpdateStack')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context,
('identify_stack', {'stack_name': stack_name})
).AndRaise(heat_exception.EntityNotFound(entity='Stack', name='test'))
self.m.ReplayAll()
result = self.controller.update(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_create_or_update_err(self):
result = self.controller.create_or_update(req={}, action="dsdgfdf")
self.assertIsInstance(result, exception.HeatInternalFailureError)
def test_get_template(self):
# Format a dummy request
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'GetTemplate', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'GetTemplate')
# Stub out the RPC call to the engine with a pre-canned response
engine_resp = self.template
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context,
('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
rpc_client.EngineClient.call(
dummy_req.context,
('get_template', {'stack_identity': identity})
).AndReturn(engine_resp)
self.m.ReplayAll()
response = self.controller.get_template(dummy_req)
expected = {'GetTemplateResponse':
{'GetTemplateResult':
{'TemplateBody': self.template}}}
self.assertEqual(expected, response)
def test_get_template_err_rpcerr(self):
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'GetTemplate', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'GetTemplate')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
rpc_client.EngineClient.call(
dummy_req.context, ('get_template', {'stack_identity': identity})
).AndRaise(AttributeError())
self.m.ReplayAll()
result = self.controller.get_template(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_get_template_bad_name(self):
stack_name = "wibble"
params = {'Action': 'GetTemplate', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'GetTemplate')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context,
('identify_stack', {'stack_name': stack_name})
).AndRaise(heat_exception.EntityNotFound(entity='Stack', name='test'))
self.m.ReplayAll()
result = self.controller.get_template(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_get_template_err_none(self):
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'GetTemplate', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'GetTemplate')
# Stub out the RPC call to the engine to return None
# this test the "no such stack" error path
engine_resp = None
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
rpc_client.EngineClient.call(
dummy_req.context, ('get_template', {'stack_identity': identity})
).AndReturn(engine_resp)
self.m.ReplayAll()
result = self.controller.get_template(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_validate_err_no_template(self):
# Format a dummy request with a missing template field
params = {'Action': 'ValidateTemplate'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'ValidateTemplate')
result = self.controller.validate_template(dummy_req)
self.assertIsInstance(result, exception.HeatMissingParameterError)
def test_validate_err_inval_template(self):
# Format a dummy request with an invalid TemplateBody
json_template = "!$%**_+}@~?"
params = {'Action': 'ValidateTemplate',
'TemplateBody': '%s' % json_template}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'ValidateTemplate')
result = self.controller.validate_template(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_bad_resources_in_template(self):
# Format a dummy request
json_template = {
'AWSTemplateFormatVersion': '2010-09-09',
'Resources': {
'Type': 'AWS: : EC2: : Instance',
},
}
params = {'Action': 'ValidateTemplate',
'TemplateBody': '%s' % json.dumps(json_template)}
response = {'Error': 'Resources must contain Resource. '
'Found a [string] instead'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'ValidateTemplate')
# Stub out the RPC call to the engine with a pre-canned response
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context,
('validate_template', {'template': json_template, 'params': None,
'files': None, 'environment_files': None,
'show_nested': False,
'ignorable_errors': None}),
version='1.24'
).AndReturn(response)
self.m.ReplayAll()
response = self.controller.validate_template(dummy_req)
expected = {'ValidateTemplateResponse':
{'ValidateTemplateResult':
'Resources must contain Resource. '
'Found a [string] instead'}}
self.assertEqual(expected, response)
def test_delete(self):
# Format a dummy request
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '1'))
params = {'Action': 'DeleteStack', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DeleteStack')
# Stub out the RPC call to the engine with a pre-canned response
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
# Engine returns None when delete successful
rpc_client.EngineClient.call(
dummy_req.context,
('delete_stack', {'stack_identity': identity})
).AndReturn(None)
self.m.ReplayAll()
response = self.controller.delete(dummy_req)
expected = {'DeleteStackResponse': {'DeleteStackResult': ''}}
self.assertEqual(expected, response)
def test_delete_err_rpcerr(self):
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '1'))
params = {'Action': 'DeleteStack', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DeleteStack')
# Stub out the RPC call to the engine with a pre-canned response
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
rpc_client.EngineClient.call(
dummy_req.context, ('delete_stack', {'stack_identity': identity})
).AndRaise(AttributeError())
self.m.ReplayAll()
result = self.controller.delete(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_delete_bad_name(self):
stack_name = "wibble"
params = {'Action': 'DeleteStack', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DeleteStack')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndRaise(heat_exception.EntityNotFound(entity='Stack', name='test'))
self.m.ReplayAll()
result = self.controller.delete(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_events_list_event_id_integer(self):
self._test_events_list('42')
def test_events_list_event_id_uuid(self):
self._test_events_list('a3455d8c-9f88-404d-a85b-5315293e67de')
def _test_events_list(self, event_id):
# Format a dummy request
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'DescribeStackEvents', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStackEvents')
# Stub out the RPC call to the engine with a pre-canned response
engine_resp = [{u'stack_name': u'wordpress',
u'event_time': u'2012-07-23T13:05:39Z',
u'stack_identity': {u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u''},
u'resource_name': u'WikiDatabase',
u'resource_status_reason': u'state changed',
u'event_identity':
{u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u'/resources/WikiDatabase/events/{0}'.format(
event_id)},
u'resource_action': u'TEST',
u'resource_status': u'IN_PROGRESS',
u'physical_resource_id': None,
u'resource_properties': {u'UserData': u'blah'},
u'resource_type': u'AWS::EC2::Instance'}]
kwargs = {'stack_identity': identity,
'limit': None, 'sort_keys': None, 'marker': None,
'sort_dir': None, 'filters': None}
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
rpc_client.EngineClient.call(
dummy_req.context, ('list_events', kwargs)
).AndReturn(engine_resp)
self.m.ReplayAll()
response = self.controller.events_list(dummy_req)
expected = {'DescribeStackEventsResponse':
{'DescribeStackEventsResult':
{'StackEvents':
[{'EventId': six.text_type(event_id),
'StackId': u'arn:openstack:heat::t:stacks/wordpress/6',
'ResourceStatus': u'TEST_IN_PROGRESS',
'ResourceType': u'AWS::EC2::Instance',
'Timestamp': u'2012-07-23T13:05:39Z',
'StackName': u'wordpress',
'ResourceProperties':
json.dumps({u'UserData': u'blah'}),
'PhysicalResourceId': None,
'ResourceStatusReason': u'state changed',
'LogicalResourceId': u'WikiDatabase'}]}}}
self.assertEqual(expected, response)
def test_events_list_err_rpcerr(self):
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'DescribeStackEvents', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStackEvents')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
rpc_client.EngineClient.call(
dummy_req.context, ('list_events', {'stack_identity': identity})
).AndRaise(Exception())
self.m.ReplayAll()
result = self.controller.events_list(dummy_req)
self.assertIsInstance(result, exception.HeatInternalFailureError)
def test_events_list_bad_name(self):
stack_name = "wibble"
params = {'Action': 'DescribeStackEvents', 'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStackEvents')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndRaise(heat_exception.EntityNotFound(entity='Stack', name='test'))
self.m.ReplayAll()
result = self.controller.events_list(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_describe_stack_resource(self):
# Format a dummy request
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'DescribeStackResource',
'StackName': stack_name,
'LogicalResourceId': "WikiDatabase"}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStackResource')
# Stub out the RPC call to the engine with a pre-canned response
engine_resp = {u'description': u'',
u'resource_identity': {
u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u'resources/WikiDatabase'
},
u'stack_name': u'wordpress',
u'resource_name': u'WikiDatabase',
u'resource_status_reason': None,
u'updated_time': u'2012-07-23T13:06:00Z',
u'stack_identity': {u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u''},
u'resource_action': u'CREATE',
u'resource_status': u'COMPLETE',
u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance',
u'metadata': {u'wordpress': []}}
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
args = {
'stack_identity': identity,
'resource_name': dummy_req.params.get('LogicalResourceId'),
'with_attr': False,
}
rpc_client.EngineClient.call(
dummy_req.context, ('describe_stack_resource', args), version='1.2'
).AndReturn(engine_resp)
self.m.ReplayAll()
response = self.controller.describe_stack_resource(dummy_req)
expected = {'DescribeStackResourceResponse':
{'DescribeStackResourceResult':
{'StackResourceDetail':
{'StackId': u'arn:openstack:heat::t:stacks/wordpress/6',
'ResourceStatus': u'CREATE_COMPLETE',
'Description': u'',
'ResourceType': u'AWS::EC2::Instance',
'ResourceStatusReason': None,
'LastUpdatedTimestamp': u'2012-07-23T13:06:00Z',
'StackName': u'wordpress',
'PhysicalResourceId':
u'a3455d8c-9f88-404d-a85b-5315293e67de',
'Metadata': {u'wordpress': []},
'LogicalResourceId': u'WikiDatabase'}}}}
self.assertEqual(expected, response)
def test_describe_stack_resource_nonexistent_stack(self):
# Format a dummy request
stack_name = "wibble"
params = {'Action': 'DescribeStackResource',
'StackName': stack_name,
'LogicalResourceId': "WikiDatabase"}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStackResource')
# Stub out the RPC call to the engine with a pre-canned response
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndRaise(heat_exception.EntityNotFound(entity='Stack', name='test'))
self.m.ReplayAll()
result = self.controller.describe_stack_resource(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_describe_stack_resource_nonexistent(self):
# Format a dummy request
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'DescribeStackResource',
'StackName': stack_name,
'LogicalResourceId': "wibble"}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStackResource')
# Stub out the RPC call to the engine with a pre-canned response
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
args = {
'stack_identity': identity,
'resource_name': dummy_req.params.get('LogicalResourceId'),
'with_attr': False,
}
rpc_client.EngineClient.call(
dummy_req.context, ('describe_stack_resource', args), version='1.2'
).AndRaise(heat_exception.ResourceNotFound(
resource_name='test', stack_name='test'))
self.m.ReplayAll()
result = self.controller.describe_stack_resource(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_describe_stack_resources(self):
# Format a dummy request
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'DescribeStackResources',
'StackName': stack_name,
'LogicalResourceId': "WikiDatabase"}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStackResources')
# Stub out the RPC call to the engine with a pre-canned response
engine_resp = [{u'description': u'',
u'resource_identity': {
u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u'resources/WikiDatabase'
},
u'stack_name': u'wordpress',
u'resource_name': u'WikiDatabase',
u'resource_status_reason': None,
u'updated_time': u'2012-07-23T13:06:00Z',
u'stack_identity': {u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u''},
u'resource_action': u'CREATE',
u'resource_status': u'COMPLETE',
u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance',
u'metadata': {u'ensureRunning': u'true''true'}}]
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
args = {
'stack_identity': identity,
'resource_name': dummy_req.params.get('LogicalResourceId'),
}
rpc_client.EngineClient.call(
dummy_req.context, ('describe_stack_resources', args)
).AndReturn(engine_resp)
self.m.ReplayAll()
response = self.controller.describe_stack_resources(dummy_req)
expected = {'DescribeStackResourcesResponse':
{'DescribeStackResourcesResult':
{'StackResources':
[{'StackId': u'arn:openstack:heat::t:stacks/wordpress/6',
'ResourceStatus': u'CREATE_COMPLETE',
'Description': u'',
'ResourceType': u'AWS::EC2::Instance',
'Timestamp': u'2012-07-23T13:06:00Z',
'ResourceStatusReason': None,
'StackName': u'wordpress',
'PhysicalResourceId':
u'a3455d8c-9f88-404d-a85b-5315293e67de',
'LogicalResourceId': u'WikiDatabase'}]}}}
self.assertEqual(expected, response)
def test_describe_stack_resources_bad_name(self):
stack_name = "wibble"
params = {'Action': 'DescribeStackResources',
'StackName': stack_name,
'LogicalResourceId': "WikiDatabase"}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStackResources')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndRaise(heat_exception.EntityNotFound(entity='Stack', name='test'))
self.m.ReplayAll()
result = self.controller.describe_stack_resources(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
def test_describe_stack_resources_physical(self):
# Format a dummy request
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'DescribeStackResources',
'LogicalResourceId': "WikiDatabase",
'PhysicalResourceId': 'a3455d8c-9f88-404d-a85b-5315293e67de'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStackResources')
# Stub out the RPC call to the engine with a pre-canned response
engine_resp = [{u'description': u'',
u'resource_identity': {
u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u'resources/WikiDatabase'
},
u'stack_name': u'wordpress',
u'resource_name': u'WikiDatabase',
u'resource_status_reason': None,
u'updated_time': u'2012-07-23T13:06:00Z',
u'stack_identity': {u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u''},
u'resource_action': u'CREATE',
u'resource_status': u'COMPLETE',
u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance',
u'metadata': {u'ensureRunning': u'true''true'}}]
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context,
('find_physical_resource',
{'physical_resource_id': 'a3455d8c-9f88-404d-a85b-5315293e67de'})
).AndReturn(identity)
args = {
'stack_identity': identity,
'resource_name': dummy_req.params.get('LogicalResourceId'),
}
rpc_client.EngineClient.call(
dummy_req.context, ('describe_stack_resources', args)
).AndReturn(engine_resp)
self.m.ReplayAll()
response = self.controller.describe_stack_resources(dummy_req)
expected = {'DescribeStackResourcesResponse':
{'DescribeStackResourcesResult':
{'StackResources':
[{'StackId': u'arn:openstack:heat::t:stacks/wordpress/6',
'ResourceStatus': u'CREATE_COMPLETE',
'Description': u'',
'ResourceType': u'AWS::EC2::Instance',
'Timestamp': u'2012-07-23T13:06:00Z',
'ResourceStatusReason': None,
'StackName': u'wordpress',
'PhysicalResourceId':
u'a3455d8c-9f88-404d-a85b-5315293e67de',
'LogicalResourceId': u'WikiDatabase'}]}}}
self.assertEqual(expected, response)
def test_describe_stack_resources_physical_not_found(self):
# Format a dummy request
params = {'Action': 'DescribeStackResources',
'LogicalResourceId': "WikiDatabase",
'PhysicalResourceId': 'aaaaaaaa-9f88-404d-cccc-ffffffffffff'}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStackResources')
# Stub out the RPC call to the engine with a pre-canned response
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context,
('find_physical_resource',
{'physical_resource_id': 'aaaaaaaa-9f88-404d-cccc-ffffffffffff'})
).AndRaise(heat_exception.EntityNotFound(entity='Resource', name='1'))
self.m.ReplayAll()
response = self.controller.describe_stack_resources(dummy_req)
self.assertIsInstance(response,
exception.HeatInvalidParameterValueError)
def test_describe_stack_resources_err_inval(self):
# Format a dummy request containing both StackName and
# PhysicalResourceId, which is invalid and should throw a
# HeatInvalidParameterCombinationError
stack_name = "wordpress"
params = {'Action': 'DescribeStackResources',
'StackName': stack_name,
'PhysicalResourceId': "123456"}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'DescribeStackResources')
ret = self.controller.describe_stack_resources(dummy_req)
self.assertIsInstance(ret,
exception.HeatInvalidParameterCombinationError)
def test_list_stack_resources(self):
# Format a dummy request
stack_name = "wordpress"
identity = dict(identifier.HeatIdentifier('t', stack_name, '6'))
params = {'Action': 'ListStackResources',
'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'ListStackResources')
# Stub out the RPC call to the engine with a pre-canned response
engine_resp = [{u'resource_identity':
{u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u'/resources/WikiDatabase'},
u'stack_name': u'wordpress',
u'resource_name': u'WikiDatabase',
u'resource_status_reason': None,
u'updated_time': u'2012-07-23T13:06:00Z',
u'stack_identity': {u'tenant': u't',
u'stack_name': u'wordpress',
u'stack_id': u'6',
u'path': u''},
u'resource_action': u'CREATE',
u'resource_status': u'COMPLETE',
u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance'}]
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndReturn(identity)
rpc_client.EngineClient.call(
dummy_req.context,
('list_stack_resources', {'stack_identity': identity,
'nested_depth': 0,
'with_detail': False,
'filters': None}),
version='1.25'
).AndReturn(engine_resp)
self.m.ReplayAll()
response = self.controller.list_stack_resources(dummy_req)
expected = {'ListStackResourcesResponse': {'ListStackResourcesResult':
{'StackResourceSummaries':
[{'ResourceStatus': u'CREATE_COMPLETE',
'ResourceType': u'AWS::EC2::Instance',
'ResourceStatusReason': None,
'LastUpdatedTimestamp': u'2012-07-23T13:06:00Z',
'PhysicalResourceId':
u'a3455d8c-9f88-404d-a85b-5315293e67de',
'LogicalResourceId': u'WikiDatabase'}]}}}
self.assertEqual(expected, response)
def test_list_stack_resources_bad_name(self):
stack_name = "wibble"
params = {'Action': 'ListStackResources',
'StackName': stack_name}
dummy_req = self._dummy_GET_request(params)
self._stub_enforce(dummy_req, 'ListStackResources')
# Insert an engine RPC error and ensure we map correctly to the
# heat exception type
self.m.StubOutWithMock(rpc_client.EngineClient, 'call')
rpc_client.EngineClient.call(
dummy_req.context, ('identify_stack', {'stack_name': stack_name})
).AndRaise(heat_exception.EntityNotFound(entity='Stack', name='test'))
self.m.ReplayAll()
result = self.controller.list_stack_resources(dummy_req)
self.assertIsInstance(result, exception.HeatInvalidParameterValueError)
|
|
"""
## SCRIPT HEADER ##
Created By : Muhammad Fredo
Email : [email protected]
Start Date : 16 Sep 2020
Info :
"""
import copy
import pymel.core as pm
from . import scene_info, naming
def clean_unknown_plugins():
"""Remove all unknown plugins expect nodes that exist in scene.
http://mayastation.typepad.com/maya-station/2015/04/how-to-prevent-maya-writing-a-requires-command-for-a-plug-in.html
Some unknown plugins may needed in another environment.
example: Vray plugin will not available to animator but will available to lighting artist.
"""
unknown_nodes = set()
for unknown_node in pm.ls(type = ["unknown", "unknownDag"], editable = True):
unknown_nodes.add(pm.unknownNode(unknown_node, q = True, plugin = True))
for unknown_plugin in pm.unknownPlugin(query = True, list = True) or []:
if unknown_plugin in unknown_nodes:
pass
else:
try:
pm.unknownPlugin(unknown_plugin, remove = True)
except Exception as err:
print(err)
def clean_mentalray_nodes():
"""Remove all mental ray nodes in the scene."""
mentalray_nodes = ['mentalrayGlobals', 'mentalrayItemsList', 'mentalrayOptions', 'mentalrayFramebuffer']
result = pm.ls(type = mentalray_nodes)
result.extend(pm.ls([o + '*' for o in mentalray_nodes]))
pm.delete(result)
def clean_namespace(namespace_list = None):
"""Remove all namespace or supplied namespace list.
:key namespace_list: Namespace list that need to be removed.
:type namespace_list: list of str
"""
if namespace_list is None:
namespace_list = scene_info.get_namespaces(exclude_ref = True)
for o in namespace_list:
try:
pm.namespace(removeNamespace = o, mergeNamespaceWithParent = True)
except Exception as e:
print('{}, {}'.format(o, e))
def clean_anim_layer(exception_list = None):
"""Remove all animation layer in the scene.
:key exception_list: Animation layer name that need to be keep.
:type exception_list: list of str
"""
if exception_list is None:
exception_list = []
layer_node = pm.ls(type = ['animLayer'])
delete_later = []
dirty_layer = []
for o in layer_node:
if o.getParent() is None:
delete_later.append(o)
continue
if o not in exception_list:
dirty_layer.append(o)
pm.delete(dirty_layer)
pm.delete(delete_later)
def clean_display_layer(exception_list = None):
"""Remove all display layer in the scene.
:key exception_list: Display layer name that need to be keep.
:type exception_list: list of str
"""
if exception_list is None:
exception_list = []
exception_list.append('defaultLayer')
layer_node = pm.ls(type = ['displayLayer'])
dirty_layer = [o for o in layer_node if o not in exception_list]
pm.delete(dirty_layer)
def fix_shading_engine_intermediate(input_shape_intermediate = None):
"""Re-wire shading engine connection that connect to
intermediate shape to non intermediate shape.
:key input_shape_intermediate: Intermediate shape that have shading engine connection and need re-wire.
:type input_shape_intermediate: list of pm.PyNode
"""
if input_shape_intermediate is not None:
# shape_inter_list = copy.deepcopy(input_shape_intermediate)
shape_inter_list = []
# if there is non shape, get the shape intermediate
for each_obj in input_shape_intermediate:
if issubclass(each_obj.__class__, pm.nt.Transform):
shape_inter_list.extend([o for o in pm.ls(each_obj.getShapes(), io = True) if o.shadingGroups()])
elif issubclass(each_obj.__class__, pm.nt.Shape) and each_obj.shadingGroups():
shape_inter_list.append(each_obj)
else:
shape_inter_list = scene_info.get_shading_engine_intermediate()
for shape_intermediate in shape_inter_list:
inter_shd_engine_list = shape_intermediate.shadingGroups()
inter_connection = shape_intermediate.outputs(type = 'shadingEngine', plugs = True)
if inter_shd_engine_list[0].name() == 'initialShadingGroup':
shape_intermediate.instObjGroups[0].disconnect(inter_connection[0])
continue
# find shape deformed
shape_deformed = shape_intermediate.getParent().getShape(noIntermediate = True)
# noninter_shd_engine_list = shape_deformed.shadingGroups()
noninter_connection = shape_deformed.outputs(type = 'shadingEngine', plugs = True)
if noninter_connection:
shape_deformed.instObjGroups[0].disconnect(noninter_connection[0])
shape_deformed.instObjGroups[0].connect(inter_connection[0])
def clean_dag_pose():
"""Remove all dagPose/bindPose nodes in the scene."""
pm.delete(pm.ls(type = 'dagPose'))
def clean_animation_node():
"""Remove all animation nodes in the scene, set driven key will not get deleted."""
pm.delete(pm.ls(type = ["animCurveTU", "animCurveTL", "animCurveTA"], editable=True))
def clean_unknown_node(exception_list = None):
"""Remove all unknown nodes in the scene except the nodes that
originated from plugin specified in exception_list.
:key exception_list: Unknown nodes plugin name that need to keep.
:type exception_list: list of str
"""
if exception_list is None:
exception_list = []
unknown_nodes = []
node_list = pm.ls(type = ['unknown', 'unknownDag'], editable = True)
for each_node in node_list:
if pm.unknownNode(each_node, q = True, plugin = True) not in exception_list:
unknown_nodes.append(each_node)
pm.delete(unknown_nodes)
def clean_unused_node():
"""Remove all unused nodes in the scene."""
pm.mel.MLdeleteUnused()
def clean_ngskin_node():
"""Remove all ngskin nodes in the scene."""
ngskin_nodes = pm.ls(type = ['ngSkinLayerData', 'ngSkinLayerDisplay'])
pm.delete(ngskin_nodes)
def clean_turtle_node():
"""Remove all presistant turtle node from the scene then unload turtle plugin."""
turtle_nodes = ['TurtleDefaultBakeLayer', 'TurtleBakeLayerManager', 'TurtleRenderOptions', 'TurtleUIOptions']
for each_node in turtle_nodes:
if pm.objExists(each_node):
turtle_node = pm.PyNode(each_node)
turtle_node.unlock()
pm.delete(turtle_node)
pm.mel.ilrDynamicAttributes(0)
try:
pm.pluginInfo('Turtle.mll', edit = True, autoload = False)
pm.unloadPlugin('Turtle.mll', force = True)
except Exception as e:
pass
def fix_duplicate_name(input_duplicate_name = None):
"""Rename specified node into unique name.
:key input_duplicate_name: PyNode needs to make the name unique.
:type input_duplicate_name: list of pm.PyNode
"""
if input_duplicate_name is not None:
duplicate_name_list = copy.deepcopy(input_duplicate_name)
else:
duplicate_name_list = scene_info.get_duplicate_name()
for duplicate_node in duplicate_name_list:
duplicate_name = duplicate_node.longName()
shortname = duplicate_node.nodeName()
newshortname = naming.get_unique_name(shortname)
pm.rename(duplicate_name, newshortname)
def clean_empty_mesh():
"""Remove all mesh object which don't have face or vertex data"""
pm.delete(scene_info.get_empty_mesh())
|
|
# coding=utf-8
import os
import re
import sys
import functools
import threading
import cherrypy
import json
import subprocess
import traceback
import webbrowser
import argparse
import shlex
from mako.template import Template
from uuid import uuid4
import telenium
from telenium.client import TeleniumHttpClient
from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
from ws4py.websocket import WebSocket
from os.path import dirname, join, realpath
from time import time, sleep
SESSION_FN = ".telenium.dat"
TPL_EXPORT_UNITTEST = u"""<%!
def capitalize(text):
return text.capitalize()
def camelcase(text):
return "".join([x.strip().capitalize() for x in text.split()])
def funcname(text):
if text == "init":
return "init"
import re
suffix = re.sub(r"[^a-z0-9_]", "_", text.lower().strip())
return "test_{}".format(suffix)
def getarg(text):
import re
return re.match("^(\w+)", text).groups()[0]
%># coding=utf-8
import time
from telenium.tests import TeleniumTestCase
class ${settings["project"]|camelcase}TestCase(TeleniumTestCase):
% if env:
cmd_env = ${ env }
% endif
cmd_entrypoint = [u'${ settings["entrypoint"] }']
% for test in tests:
% if test["name"] == "setUpClass":
<% vself = "cls" %>
@classmethod
def setUpClass(cls):
super(${settings["project"]|camelcase}TestCase, cls).setUpClass()
% else:
<% vself = "self" %>
def ${test["name"]|funcname}(self):
% if not test["steps"]:
pass
% endif
% endif
% for key, value, arg1, arg2 in test["steps"]:
% if key == "wait":
${vself}.cli.wait('${value}', timeout=${settings["command-timeout"]})
% elif key == "wait_click":
${vself}.cli.wait_click('${value}', timeout=${settings["command-timeout"]})
% elif key == "assertExists":
${vself}.assertExists('${value}', timeout=${settings["command-timeout"]})
% elif key == "assertNotExists":
${vself}.assertNotExists('${value}', timeout=${settings["command-timeout"]})
% elif key == "assertAttributeValue":
attr_name = '${arg1|getarg}'
attr_value = ${vself}.cli.getattr('${value}', attr_name)
${vself}.assertTrue(eval('${arg1}', {attr_name: attr_value}))
% elif key == "setAttribute":
${vself}.cli.setattr('${value}', '${arg1}', ${arg2})
% elif key == "sendKeycode":
${vself}.cli.send_keycode('${value}')
% elif key == "sleep":
time.sleep(${value})
% elif key == "executeCode":
${vself}.assertTrue(self.cli.execute('${value}'))
% endif
% endfor
% endfor
"""
FILE_API_VERSION = 3
local_filename = None
def threaded(f):
@functools.wraps(f)
def _threaded(*args, **kwargs):
thread = threading.Thread(target=f, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread
return _threaded
def funcname(text):
return text.lower().replace(" ", "_").strip()
def getarg(text):
return re.match("^(\w+)", text).groups()[0]
class ApiWebSocket(WebSocket):
t_process = None
cli = None
progress_count = 0
progress_total = 0
session = {
"settings": {
"project": "Test",
"entrypoint": "main.py",
"application-timeout": "10",
"command-timeout": "5",
"args": ""
},
"env": {},
"tests": [{
"id": str(uuid4()),
"name": "New test",
"steps": []
}]
}
def opened(self):
super(ApiWebSocket, self).opened()
self.load()
def closed(self, code, reason=None):
pass
def received_message(self, message):
msg = json.loads(message.data)
try:
getattr(self, "cmd_{}".format(msg["cmd"]))(msg["options"])
except:
traceback.print_exc()
def send_object(self, obj):
data = json.dumps(obj)
self.send(data, False)
def save(self):
self.session["version_format"] = FILE_API_VERSION
# check if the file changed
if local_filename is not None:
changed = False
try:
with open(local_filename) as fd:
data = json.loads(fd.read())
changed = data != self.session
except:
changed = True
self.send_object(["changed", changed])
with open(SESSION_FN, "w") as fd:
fd.write(json.dumps(self.session))
def load(self):
try:
with open(SESSION_FN) as fd:
session = json.loads(fd.read())
session = upgrade_version(session)
self.session.update(session)
except:
pass
def get_test(self, test_id):
for test in self.session["tests"]:
if test["id"] == test_id:
return test
def get_test_by_name(self, name):
for test in self.session["tests"]:
if test["name"] == name:
return test
@property
def is_running(self):
return self.t_process is not None
# command implementation
def cmd_recover(self, options):
if local_filename:
self.send_object(["is_local", True])
self.send_object(["settings", self.session["settings"]])
self.send_object(["env", dict(self.session["env"].items())])
tests = [{
"name": x["name"],
"id": x["id"]
} for x in self.session["tests"]]
self.send_object(["tests", tests])
if self.t_process is not None:
self.send_object(["status", "running"])
def cmd_save_local(self, options):
try:
assert local_filename is not None
# save json source
data = self.export("json")
with open(local_filename, "w") as fd:
fd.write(data)
# auto export to python
filename = local_filename.replace(".json", ".py")
data = self.export("python")
with open(filename, "w") as fd:
fd.write(data)
self.send_object(["save_local", "ok"])
self.send_object(["changed", False])
except Exception as e:
traceback.print_exc()
self.send_object(["save_local", "error", repr(e)])
def cmd_sync_env(self, options):
while self.session["env"]:
self.session["env"].pop(self.session["env"].keys()[0])
for key, value in options.get("env", {}).items():
self.session["env"][key] = value
self.save()
def cmd_sync_settings(self, options):
self.session["settings"] = options["settings"]
self.save()
def cmd_sync_test(self, options):
uid = options["id"]
for test in self.session["tests"]:
if test["id"] == uid:
test["name"] = options["name"]
test["steps"] = options["steps"]
self.save()
def cmd_add_test(self, options):
self.session["tests"].append({
"id": str(uuid4()),
"name": "New test",
"steps": []
})
self.save()
self.send_object(["tests", self.session["tests"]])
def cmd_clone_test(self, options):
for test in self.session["tests"]:
if test["id"] != options["test_id"]:
continue
clone_test = test.copy()
clone_test["id"] = str(uuid4())
clone_test["name"] += " (1)"
self.session["tests"].append(clone_test)
break
self.save()
self.send_object(["tests", self.session["tests"]])
def cmd_delete_test(self, options):
for test in self.session["tests"][:]:
if test["id"] == options["id"]:
self.session["tests"].remove(test)
if not self.session["tests"]:
self.cmd_add_test(None)
self.save()
self.send_object(["tests", self.session["tests"]])
def cmd_select(self, options):
if not self.cli:
status = "error"
results = "Application not running"
else:
try:
results = self.cli.highlight(options["selector"])
status = "ok"
except Exception as e:
status = "error"
results = u"{}".format(e)
self.send_object(["select", options["selector"], status, results])
def cmd_select_test(self, options):
test = self.get_test(options["id"])
self.send_object(["test", test])
@threaded
def cmd_pick(self, options):
if not self.cli:
return self.send_object(["pick", "error", "App is not started"])
objs = self.cli.pick(True)
return self.send_object(["pick", "success", objs])
@threaded
def cmd_execute(self, options):
self.execute()
def cmd_run_step(self, options):
self.run_step(options["id"], options["index"])
@threaded
def cmd_run_steps(self, options):
test = self.get_test(options["id"])
if test is None:
self.send_object(["alert", "Test not found"])
return
if not self.is_running:
ev_start, ev_stop = self.execute()
ev_start.wait()
if ev_stop.is_set():
return
self.run_test(test)
@threaded
def cmd_run_tests(self, options):
# restart always from scratch
self.send_object(["progress", "started"])
# precalculate the number of steps to run
count = sum([len(x["steps"]) for x in self.session["tests"]])
self.progress_count = 0
self.progress_total = count
try:
ev_start, ev_stop = self.execute()
ev_start.wait()
if ev_stop.is_set():
return
setup = self.get_test_by_name("setUpClass")
if setup:
if not self.run_test(setup):
return
setup = self.get_test_by_name("init")
if setup:
if not self.run_test(setup):
return
for test in self.session["tests"]:
if test["name"] in ("setUpClass", "init"):
continue
if not self.run_test(test):
return
finally:
self.send_object(["progress", "finished"])
def cmd_stop(self, options):
if self.t_process:
self.t_process.terminate()
def cmd_export(self, options):
try:
dtype = options["type"]
mimetype = {
"python": "text/plain",
"json": "application/json"
}[dtype]
ext = {"python": "py", "json": "json"}[dtype]
key = funcname(self.session["settings"]["project"])
filename = "test_ui_{}.{}".format(key, ext)
export = self.export(options["type"])
self.send_object(["export", export, mimetype, filename, dtype])
except Exception as e:
self.send_object(["export", "error", u"{}".format(e)])
def export(self, kind):
if kind == "python":
return Template(TPL_EXPORT_UNITTEST).render(
session=self.session, **self.session)
elif kind == "json":
self.session["version_format"] = FILE_API_VERSION
return json.dumps(
self.session, sort_keys=True, indent=4, separators=(',', ': '))
def execute(self):
ev_start = threading.Event()
ev_stop = threading.Event()
self._execute(ev_start=ev_start, ev_stop=ev_stop)
return ev_start, ev_stop
@threaded
def _execute(self, ev_start, ev_stop):
self.t_process = None
try:
self.start_process()
ev_start.set()
self.t_process.communicate()
self.send_object(["status", "stopped", None])
except Exception as e:
try:
self.t_process.terminate()
except:
pass
try:
self.send_object(["status", "stopped", u"{}".format(e)])
except:
pass
finally:
self.t_process = None
ev_stop.set()
def start_process(self):
url = "http://localhost:9901/jsonrpc"
process_start_timeout = 10
telenium_token = str(uuid4())
self.cli = cli = TeleniumHttpClient(url=url, timeout=10)
# entry no any previous telenium is running
try:
cli.app_quit()
sleep(2)
except:
pass
# prepare the application
entrypoint = self.session["settings"]["entrypoint"]
print(self.session)
args = shlex.split(self.session["settings"].get("args", ""))
cmd = [sys.executable, "-m", "telenium.execute", entrypoint] + args
cwd = dirname(entrypoint)
if not os.path.isabs(cwd):
cwd = os.getcwd()
env = os.environ.copy()
env.update(self.session["env"])
env["TELENIUM_TOKEN"] = telenium_token
# start the application
self.t_process = subprocess.Popen(cmd, env=env, cwd=cwd)
# wait for telenium server to be online
start = time()
while True:
try:
if cli.app_ready():
break
except Exception:
if time() - start > process_start_timeout:
raise Exception("timeout")
sleep(1)
# ensure the telenium we are connected are the same as the one we
# launched here
if cli.get_token() != telenium_token:
raise Exception("Connected to another telenium server")
self.send_object(["status", "running"])
def run_test(self, test):
test_id = test["id"]
try:
self.send_object(["test", test])
self.send_object(["run_test", test_id, "running"])
for index, step in enumerate(test["steps"]):
if not self.run_step(test_id, index):
return
return True
except Exception as e:
self.send_object(["run_test", test_id, "error", str(e)])
else:
self.send_object(["run_test", test_id, "finished"])
def run_step(self, test_id, index):
self.progress_count += 1
self.send_object(
["progress", "update", self.progress_count, self.progress_total])
try:
self.send_object(["run_step", test_id, index, "running"])
success = self._run_step(test_id, index)
if success:
self.send_object(["run_step", test_id, index, "success"])
return True
else:
self.send_object(["run_step", test_id, index, "error"])
except Exception as e:
self.send_object(["run_step", test_id, index, "error", str(e)])
def _run_step(self, test_id, index):
test = self.get_test(test_id)
if not test:
raise Exception("Unknown test")
cmd, selector, arg1, arg2 = test["steps"][index]
timeout = 5
if cmd == "wait":
return self.cli.wait(selector, timeout=timeout)
elif cmd == "wait_click":
self.cli.wait_click(selector, timeout=timeout)
return True
elif cmd == "wait_drag":
self.cli.wait_drag(
selector, target=arg1, duration=arg2, timeout=timeout)
return True
elif cmd == "assertExists":
return self.cli.wait(selector, timeout=timeout) is True
elif cmd == "assertNotExists":
return self.assertNotExists(self.cli, selector, timeout=timeout)
elif cmd == "assertAttributeValue":
attr_name = getarg(arg1)
attr_value = self.cli.getattr(selector, attr_name)
return bool(eval(arg1, {attr_name: attr_value}))
elif cmd == "setAttribute":
return self.cli.setattr(selector, arg1, eval(arg2))
elif cmd == "sendKeycode":
self.cli.send_keycode(selector)
return True
elif cmd == "sleep":
sleep(float(selector))
return True
elif cmd == "executeCode":
return self.cli.execute(selector)
def assertNotExists(self, cli, selector, timeout=-1):
start = time()
while True:
matches = cli.select(selector)
if not matches:
return True
if timeout == -1:
raise AssertionError("selector matched elements")
if timeout > 0 and time() - start > timeout:
raise Exception("Timeout")
sleep(0.1)
class Root(object):
@cherrypy.expose
def index(self):
raise cherrypy.HTTPRedirect("/static/index.html")
@cherrypy.expose
def ws(self):
pass
class WebSocketServer(object):
def __init__(self, host="0.0.0.0", port=8080, open_webbrowser=True):
super(WebSocketServer, self).__init__()
self.host = host
self.port = port
self.daemon = True
self.open_webbrowser = open_webbrowser
def run(self):
cherrypy.config.update({
"global": {
"environment": "production"
},
"server.socket_port": self.port,
"server.socket_host": self.host,
})
cherrypy.tree.mount(
Root(),
"/",
config={
"/": {
"tools.sessions.on": True
},
"/ws": {
"tools.websocket.on": True,
"tools.websocket.handler_cls": ApiWebSocket
},
"/static": {
"tools.staticdir.on":
True,
"tools.staticdir.dir":
join(realpath(dirname(__file__)), "static"),
"tools.staticdir.index":
"index.html"
}
})
cherrypy.engine.start()
url = "http://{}:{}/".format(self.host, self.port)
print("Telenium {} ready at {}".format(telenium.__version__, url))
if self.open_webbrowser:
webbrowser.open(url)
cherrypy.engine.block()
def stop(self):
cherrypy.engine.exit()
cherrypy.server.stop()
def preload_session(filename):
global local_filename
local_filename = filename
if not local_filename.endswith(".json"):
print("You can load only telenium-json files.")
sys.exit(1)
if not os.path.exists(filename):
print("Create new file at {}".format(local_filename))
if os.path.exists(SESSION_FN):
os.unlink(SESSION_FN)
else:
with open(filename) as fd:
session = json.loads(fd.read())
session = upgrade_version(session)
with open(SESSION_FN, "w") as fd:
fd.write(json.dumps(session))
def upgrade_version(session):
# automatically upgrade to latest version
version_format = session.get("version_format")
if version_format is None or version_format == FILE_API_VERSION:
return session
session["version_format"] += 1
version_format = session["version_format"]
print("Upgrade to version {}".format(version_format))
if version_format == 2:
# arg added in steps, so steps must have 3 arguments not 2.
for test in session["tests"]:
for step in test["steps"]:
if len(step) == 2:
step.append(None)
elif version_format == 3:
# arg added in steps, so steps must have 4 arguments not 3.
for test in session["tests"]:
for step in test["steps"]:
if len(step) == 3:
step.append(None)
return session
WebSocketPlugin(cherrypy.engine).subscribe()
cherrypy.tools.websocket = WebSocketTool()
def run():
parser = argparse.ArgumentParser(description="Telenium IDE")
parser.add_argument(
"filename",
type=str,
default=None,
nargs="?",
help="Telenium JSON file")
parser.add_argument(
"--new", action="store_true", help="Start a new session")
parser.add_argument(
"--port", type=int, default=8080, help="Telenium IDE port")
parser.add_argument(
"--notab",
action="store_true",
help="Prevent opening the IDE in the browser")
args = parser.parse_args()
if args.new:
if os.path.exists(SESSION_FN):
os.unlink(SESSION_FN)
if args.filename:
preload_session(args.filename)
server = WebSocketServer(port=args.port, open_webbrowser=not args.notab)
server.run()
server.stop()
if __name__ == "__main__":
run()
|
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Cloudscaling Group, Inc
#
# 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.
"""
The MatchMaker classes should except a Topic or Fanout exchange key and
return keys for direct exchanges, per (approximate) AMQP parlance.
"""
import contextlib
import eventlet
from oslo.config import cfg
from heat.openstack.common.gettextutils import _ # noqa
from heat.openstack.common import log as logging
matchmaker_opts = [
cfg.IntOpt('matchmaker_heartbeat_freq',
default=300,
help='Heartbeat frequency'),
cfg.IntOpt('matchmaker_heartbeat_ttl',
default=600,
help='Heartbeat time-to-live.'),
]
CONF = cfg.CONF
CONF.register_opts(matchmaker_opts)
LOG = logging.getLogger(__name__)
contextmanager = contextlib.contextmanager
class MatchMakerException(Exception):
"""Signified a match could not be found."""
message = _("Match not found by MatchMaker.")
class Exchange(object):
"""Implements lookups.
Subclass this to support hashtables, dns, etc.
"""
def __init__(self):
pass
def run(self, key):
raise NotImplementedError()
class Binding(object):
"""A binding on which to perform a lookup."""
def __init__(self):
pass
def test(self, key):
raise NotImplementedError()
class MatchMakerBase(object):
"""Match Maker Base Class.
Build off HeartbeatMatchMakerBase if building a heartbeat-capable
MatchMaker.
"""
def __init__(self):
# Array of tuples. Index [2] toggles negation, [3] is last-if-true
self.bindings = []
self.no_heartbeat_msg = _('Matchmaker does not implement '
'registration or heartbeat.')
def register(self, key, host):
"""Register a host on a backend.
Heartbeats, if applicable, may keepalive registration.
"""
pass
def ack_alive(self, key, host):
"""Acknowledge that a key.host is alive.
Used internally for updating heartbeats, but may also be used
publically to acknowledge a system is alive (i.e. rpc message
successfully sent to host)
"""
pass
def is_alive(self, topic, host):
"""Checks if a host is alive."""
pass
def expire(self, topic, host):
"""Explicitly expire a host's registration."""
pass
def send_heartbeats(self):
"""Send all heartbeats.
Use start_heartbeat to spawn a heartbeat greenthread,
which loops this method.
"""
pass
def unregister(self, key, host):
"""Unregister a topic."""
pass
def start_heartbeat(self):
"""Spawn heartbeat greenthread."""
pass
def stop_heartbeat(self):
"""Destroys the heartbeat greenthread."""
pass
def add_binding(self, binding, rule, last=True):
self.bindings.append((binding, rule, False, last))
#NOTE(ewindisch): kept the following method in case we implement the
# underlying support.
#def add_negate_binding(self, binding, rule, last=True):
# self.bindings.append((binding, rule, True, last))
def queues(self, key):
workers = []
# bit is for negate bindings - if we choose to implement it.
# last stops processing rules if this matches.
for (binding, exchange, bit, last) in self.bindings:
if binding.test(key):
workers.extend(exchange.run(key))
# Support last.
if last:
return workers
return workers
class HeartbeatMatchMakerBase(MatchMakerBase):
"""Base for a heart-beat capable MatchMaker.
Provides common methods for registering, unregistering, and maintaining
heartbeats.
"""
def __init__(self):
self.hosts = set()
self._heart = None
self.host_topic = {}
super(HeartbeatMatchMakerBase, self).__init__()
def send_heartbeats(self):
"""Send all heartbeats.
Use start_heartbeat to spawn a heartbeat greenthread,
which loops this method.
"""
for key, host in self.host_topic:
self.ack_alive(key, host)
def ack_alive(self, key, host):
"""Acknowledge that a host.topic is alive.
Used internally for updating heartbeats, but may also be used
publically to acknowledge a system is alive (i.e. rpc message
successfully sent to host)
"""
raise NotImplementedError("Must implement ack_alive")
def backend_register(self, key, host):
"""Implements registration logic.
Called by register(self,key,host)
"""
raise NotImplementedError("Must implement backend_register")
def backend_unregister(self, key, key_host):
"""Implements de-registration logic.
Called by unregister(self,key,host)
"""
raise NotImplementedError("Must implement backend_unregister")
def register(self, key, host):
"""Register a host on a backend.
Heartbeats, if applicable, may keepalive registration.
"""
self.hosts.add(host)
self.host_topic[(key, host)] = host
key_host = '.'.join((key, host))
self.backend_register(key, key_host)
self.ack_alive(key, host)
def unregister(self, key, host):
"""Unregister a topic."""
if (key, host) in self.host_topic:
del self.host_topic[(key, host)]
self.hosts.discard(host)
self.backend_unregister(key, '.'.join((key, host)))
LOG.info(_("Matchmaker unregistered: %(key)s, %(host)s"),
{'key': key, 'host': host})
def start_heartbeat(self):
"""Implementation of MatchMakerBase.start_heartbeat.
Launches greenthread looping send_heartbeats(),
yielding for CONF.matchmaker_heartbeat_freq seconds
between iterations.
"""
if not self.hosts:
raise MatchMakerException(
_("Register before starting heartbeat."))
def do_heartbeat():
while True:
self.send_heartbeats()
eventlet.sleep(CONF.matchmaker_heartbeat_freq)
self._heart = eventlet.spawn(do_heartbeat)
def stop_heartbeat(self):
"""Destroys the heartbeat greenthread."""
if self._heart:
self._heart.kill()
class DirectBinding(Binding):
"""Specifies a host in the key via a '.' character.
Although dots are used in the key, the behavior here is
that it maps directly to a host, thus direct.
"""
def test(self, key):
return '.' in key
class TopicBinding(Binding):
"""Where a 'bare' key without dots.
AMQP generally considers topic exchanges to be those *with* dots,
but we deviate here in terminology as the behavior here matches
that of a topic exchange (whereas where there are dots, behavior
matches that of a direct exchange.
"""
def test(self, key):
return '.' not in key
class FanoutBinding(Binding):
"""Match on fanout keys, where key starts with 'fanout.' string."""
def test(self, key):
return key.startswith('fanout~')
class StubExchange(Exchange):
"""Exchange that does nothing."""
def run(self, key):
return [(key, None)]
class LocalhostExchange(Exchange):
"""Exchange where all direct topics are local."""
def __init__(self, host='localhost'):
self.host = host
super(Exchange, self).__init__()
def run(self, key):
return [('.'.join((key.split('.')[0], self.host)), self.host)]
class DirectExchange(Exchange):
"""Exchange where all topic keys are split, sending to second half.
i.e. "compute.host" sends a message to "compute.host" running on "host"
"""
def __init__(self):
super(Exchange, self).__init__()
def run(self, key):
e = key.split('.', 1)[1]
return [(key, e)]
class MatchMakerLocalhost(MatchMakerBase):
"""Match Maker where all bare topics resolve to localhost.
Useful for testing.
"""
def __init__(self, host='localhost'):
super(MatchMakerLocalhost, self).__init__()
self.add_binding(FanoutBinding(), LocalhostExchange(host))
self.add_binding(DirectBinding(), DirectExchange())
self.add_binding(TopicBinding(), LocalhostExchange(host))
class MatchMakerStub(MatchMakerBase):
"""Match Maker where topics are untouched.
Useful for testing, or for AMQP/brokered queues.
Will not work where knowledge of hosts is known (i.e. zeromq)
"""
def __init__(self):
super(MatchMakerStub, self).__init__()
self.add_binding(FanoutBinding(), StubExchange())
self.add_binding(DirectBinding(), StubExchange())
self.add_binding(TopicBinding(), StubExchange())
|
|
# -*- test-case-name: txdav.caldav.datastore.test.test_file -*-
##
# Copyright (c) 2010-2015 Apple Inc. All rights reserved.
#
# 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.
##
from twistedcaldav.datafilters.peruserdata import PerUserDataFilter
"""
File calendar store.
"""
__all__ = [
"CalendarStore",
"CalendarStoreTransaction",
"CalendarHome",
"Calendar",
"CalendarObject",
]
import hashlib
import uuid
from errno import ENOENT
from twisted.internet.defer import inlineCallbacks, returnValue, succeed, fail
from twistedcaldav.ical import Component as VComponent
from txdav.xml import element as davxml
from txdav.xml.rfc2518 import GETContentType
from txweb2.dav.resource import TwistedGETContentMD5
from txweb2.http_headers import generateContentType, MimeType
from twistedcaldav import caldavxml, customxml, ical
from twistedcaldav.caldavxml import ScheduleCalendarTransp, Opaque, Transparent
from twistedcaldav.config import config
from twistedcaldav.ical import InvalidICalendarDataError
from txdav.caldav.icalendarstore import IAttachment, AttachmentSizeTooLarge
from txdav.caldav.icalendarstore import ICalendar, ICalendarObject
from txdav.caldav.icalendarstore import ICalendarHome
from txdav.caldav.datastore.index_file import Index as OldIndex, \
IndexSchedule as OldInboxIndex
from txdav.caldav.datastore.util import (
validateCalendarComponent, dropboxIDFromCalendarObject, CalendarObjectBase,
StorageTransportBase, AttachmentRetrievalTransport
)
from txdav.common.datastore.file import (
CommonDataStore, CommonStoreTransaction, CommonHome, CommonHomeChild,
CommonObjectResource, CommonStubResource)
from txdav.caldav.icalendarstore import QuotaExceeded
from txdav.common.icommondatastore import ConcurrentModification
from txdav.common.icommondatastore import InternalDataStoreError
from txdav.base.datastore.file import writeOperation, hidden, FileMetaDataMixin
from txdav.base.propertystore.base import PropertyName
from zope.interface import implements
contentTypeKey = PropertyName.fromElement(GETContentType)
md5key = PropertyName.fromElement(TwistedGETContentMD5)
CalendarStore = CommonDataStore
CalendarStoreTransaction = CommonStoreTransaction
IGNORE_NAMES = ('dropbox', 'notification', 'freebusy')
class CalendarHome(CommonHome):
implements(ICalendarHome)
_topPath = "calendars"
_notifierPrefix = "CalDAV"
_componentCalendarName = {
"VEVENT": "calendar",
"VTODO": "tasks",
"VJOURNAL": "journals",
"VAVAILABILITY": "available",
"VPOLL": "polls",
}
def __init__(self, uid, path, calendarStore, transaction):
super(CalendarHome, self).__init__(uid, path, calendarStore, transaction)
self._childClass = Calendar
createCalendarWithName = CommonHome.createChildWithName
removeCalendarWithName = CommonHome.removeChildWithName
def childWithName(self, name):
if name in IGNORE_NAMES:
# "dropbox" is a file storage area, not a calendar.
return None
else:
return super(CalendarHome, self).childWithName(name)
calendarWithName = childWithName
def children(self):
"""
Return a generator of the child resource objects.
"""
for child in self.listCalendars():
yield self.calendarWithName(child)
calendars = children
def listChildren(self):
"""
Return a generator of the child resource names.
"""
for name in super(CalendarHome, self).listChildren():
if name in IGNORE_NAMES:
continue
yield name
listCalendars = listChildren
loadCalendars = CommonHome.loadChildren
@inlineCallbacks
def hasCalendarResourceUIDSomewhereElse(self, uid, ok_object, type):
objectResources = (yield self.getCalendarResourcesForUID(uid))
for objectResource in objectResources:
if ok_object and objectResource._path == ok_object._path:
continue
matched_type = "schedule" if objectResource.isScheduleObject else "calendar"
if type == "schedule" or matched_type == "schedule":
returnValue(objectResource)
returnValue(None)
@inlineCallbacks
def getCalendarResourcesForUID(self, uid):
results = (yield self.objectResourcesWithUID(uid, ("inbox",)))
returnValue(results)
@inlineCallbacks
def calendarObjectWithDropboxID(self, dropboxID):
"""
Implement lookup with brute-force scanning.
"""
for calendar in self.calendars():
for calendarObject in calendar.calendarObjects():
if dropboxID == (yield calendarObject.dropboxID()):
returnValue(calendarObject)
@inlineCallbacks
def getAllDropboxIDs(self):
dropboxIDs = []
for calendar in self.calendars():
for calendarObject in calendar.calendarObjects():
component = calendarObject.component()
if (
component.hasPropertyInAnyComponent("X-APPLE-DROPBOX") or
component.hasPropertyInAnyComponent("ATTACH")
):
dropboxID = (yield calendarObject.dropboxID())
dropboxIDs.append(dropboxID)
returnValue(dropboxIDs)
@property
def _calendarStore(self):
return self._dataStore
def createdHome(self):
# Check whether components type must be separate
if config.RestrictCalendarsToOneComponentType:
for name in ical.allowedStoreComponents:
cal = self.createCalendarWithName(self._componentCalendarName[name])
cal.setSupportedComponents(name)
props = cal.properties()
if name not in ("VEVENT", "VAVAILABILITY",):
props[PropertyName(*ScheduleCalendarTransp.qname())] = ScheduleCalendarTransp(Transparent())
else:
props[PropertyName(*ScheduleCalendarTransp.qname())] = ScheduleCalendarTransp(Opaque())
else:
cal = self.createCalendarWithName("calendar")
self.createCalendarWithName("inbox")
def ensureDefaultCalendarsExist(self):
"""
Double check that we have calendars supporting at least VEVENT and VTODO,
and create if missing.
"""
# Double check that we have calendars supporting at least VEVENT and VTODO
if config.RestrictCalendarsToOneComponentType:
supported_components = set()
names = set()
for calendar in self.calendars():
if calendar.name() == "inbox":
continue
names.add(calendar.name())
result = calendar.getSupportedComponents()
supported_components.update(result.split(","))
def _requireCalendarWithType(support_component, tryname):
if support_component not in supported_components:
newname = tryname
if newname in names:
newname = str(uuid.uuid4())
newcal = self.createCalendarWithName(newname)
newcal.setSupportedComponents(support_component)
_requireCalendarWithType("VEVENT", "calendar")
_requireCalendarWithType("VTODO", "tasks")
class Calendar(CommonHomeChild):
"""
File-based implementation of L{ICalendar}.
"""
implements(ICalendar)
def __init__(self, name, calendarHome, owned, realName=None):
"""
Initialize a calendar pointing at a path on disk.
@param name: the subdirectory of calendarHome where this calendar
resides.
@type name: C{str}
@param calendarHome: the home containing this calendar.
@type calendarHome: L{CalendarHome}
@param realName: If this calendar was just created, the name which it
will eventually have on disk.
@type realName: C{str}
"""
super(Calendar, self).__init__(name, calendarHome, owned, realName=realName)
self._index = Index(self)
self._objectResourceClass = CalendarObject
@property
def _calendarHome(self):
return self._home
ownerCalendarHome = CommonHomeChild.ownerHome
viewerCalendarHome = CommonHomeChild.viewerHome
calendarObjects = CommonHomeChild.objectResources
listCalendarObjects = CommonHomeChild.listObjectResources
calendarObjectWithName = CommonHomeChild.objectResourceWithName
calendarObjectWithUID = CommonHomeChild.objectResourceWithUID
createCalendarObjectWithName = CommonHomeChild.createObjectResourceWithName
calendarObjectsSinceToken = CommonHomeChild.objectResourcesSinceToken
def _createCalendarObjectWithNameInternal(self, name, component, internal_state, options=None):
return self.createCalendarObjectWithName(name, component, options)
def calendarObjectsInTimeRange(self, start, end, timeZone):
raise NotImplementedError()
def setSupportedComponents(self, supported_components):
"""
Update the private property with the supported components. Technically this should only happen once
on collection creation, but for migration we may need to change after the fact - hence a separate api.
"""
pname = PropertyName.fromElement(customxml.TwistedCalendarSupportedComponents)
if supported_components:
self.properties()[pname] = customxml.TwistedCalendarSupportedComponents.fromString(supported_components)
elif pname in self.properties():
del self.properties()[pname]
def getSupportedComponents(self):
result = str(self.properties().get(PropertyName.fromElement(customxml.TwistedCalendarSupportedComponents), ""))
return result if result else None
def isSupportedComponent(self, componentType):
supported = self.getSupportedComponents()
if supported:
return componentType.upper() in supported.split(",")
else:
return True
def initPropertyStore(self, props):
# Setup peruser special properties
props.setSpecialProperties(
(
PropertyName.fromElement(caldavxml.CalendarDescription),
PropertyName.fromElement(caldavxml.CalendarTimeZone),
),
(
PropertyName.fromElement(customxml.GETCTag),
PropertyName.fromElement(caldavxml.SupportedCalendarComponentSet),
),
(),
)
def contentType(self):
"""
The content type of Calendar objects is text/calendar.
"""
return MimeType.fromString("text/calendar; charset=utf-8")
def splitCollectionByComponentTypes(self):
"""
If the calendar contains iCalendar data with different component types, then split it into separate collections
each containing only one component type. When doing this make sure properties and sharing state are preserved
on any new calendars created.
"""
# TODO: implement this for filestore
pass
def _countComponentTypes(self):
"""
Count each component type in this calendar.
@return: a C{tuple} of C{tuple} containing the component type name and count.
"""
rows = self._index._oldIndex.componentTypeCounts()
result = tuple([(componentType, componentCount) for componentType, componentCount in sorted(rows, key=lambda x:x[0])])
return result
def _splitComponentType(self, component):
"""
Create a new calendar and move all components of the specified component type into the new one.
Make sure properties and sharing state is preserved on the new calendar.
@param component: Component type to split out
@type component: C{str}
"""
# TODO: implement this for filestore
pass
def _transferSharingDetails(self, newcalendar, component):
"""
If the current calendar is shared, make the new calendar shared in the same way, but tweak the name.
"""
# TODO: implement this for filestore
pass
def _transferCalendarObjects(self, newcalendar, component):
"""
Move all calendar components of the specified type to the specified calendar.
"""
# TODO: implement this for filestore
pass
class CalendarObject(CommonObjectResource, CalendarObjectBase):
"""
@ivar _path: The path of the .ics file on disk
@type _path: L{FilePath}
"""
implements(ICalendarObject)
def __init__(self, name, calendar, metadata=None):
super(CalendarObject, self).__init__(name, calendar)
self._attachments = {}
if metadata is not None:
self.accessMode = metadata.get("accessMode", "")
self.isScheduleObject = metadata.get("isScheduleObject", False)
self.scheduleTag = metadata.get("scheduleTag", "")
self.scheduleEtags = metadata.get("scheduleEtags", "")
self.hasPrivateComment = metadata.get("hasPrivateComment", False)
@property
def _calendar(self):
return self._parentCollection
def calendar(self):
return self._calendar
@writeOperation
def setComponent(self, component, inserting=False):
validateCalendarComponent(self, self._calendar, component, inserting, self._transaction._migrating)
self._calendar.retrieveOldIndex().addResource(
self.name(), component
)
componentText = str(component)
self._objectText = componentText
def do():
# Mark all properties as dirty, so they can be added back
# to the newly updated file.
self.properties().update(self.properties())
backup = None
if self._path.exists():
backup = hidden(self._path.temporarySibling())
self._path.moveTo(backup)
fh = self._path.open("w")
try:
# FIXME: concurrency problem; if this write is interrupted
# halfway through, the underlying file will be corrupt.
fh.write(componentText)
finally:
fh.close()
md5 = hashlib.md5(componentText).hexdigest()
self.properties()[md5key] = TwistedGETContentMD5.fromString(md5)
# Now re-write the original properties on the updated file
self.properties().flush()
def undo():
if backup:
backup.moveTo(self._path)
else:
self._path.remove()
return undo
self._transaction.addOperation(do, "set calendar component %r" % (self.name(),))
self._calendar.notifyChanged()
def component(self):
"""
Read calendar data and validate/fix it. Do not raise a store error here if there are unfixable
errors as that could prevent the overall request to fail. Instead we will hand bad data off to
the caller - that is not ideal but in theory we should have checked everything on the way in and
only allowed in good data.
"""
text = self._text()
try:
component = VComponent.fromString(text)
except InvalidICalendarDataError, e:
# This is a really bad situation, so do raise
raise InternalDataStoreError(
"File corruption detected (%s) in file: %s"
% (e, self._path.path)
)
# Fix any bogus data we can
fixed, unfixed = component.validCalendarData(doFix=True, doRaise=False)
if unfixed:
self.log.error("Calendar data at %s had unfixable problems:\n %s" % (self._path.path, "\n ".join(unfixed),))
if fixed:
self.log.error("Calendar data at %s had fixable problems:\n %s" % (self._path.path, "\n ".join(fixed),))
return component
def componentForUser(self, user_uuid=None):
"""
Return the iCalendar component filtered for the specified user's per-user data.
@param user_uuid: the user UUID to filter on
@type user_uuid: C{str}
@return: the filtered calendar component
@rtype: L{twistedcaldav.ical.Component}
"""
if user_uuid is None:
user_uuid = self._parentCollection.viewerHome().uid()
return PerUserDataFilter(user_uuid).filter(self.component().duplicate())
def _text(self):
if self._objectText is not None:
return self._objectText
try:
fh = self._path.open()
except IOError, e:
if e[0] == ENOENT:
raise ConcurrentModification()
else:
raise
try:
text = fh.read()
finally:
fh.close()
if not (
text.startswith("BEGIN:VCALENDAR\r\n") or
text.endswith("\r\nEND:VCALENDAR\r\n")
):
# Handle case of old wiki data written using \n instead of \r\n
if (
text.startswith("BEGIN:VCALENDAR\n") and
text.endswith("\nEND:VCALENDAR\n")
):
text = text.replace("\n", "\r\n")
else:
# Cannot deal with this data
raise InternalDataStoreError(
"File corruption detected (improper start) in file: %s"
% (self._path.path,)
)
self._objectText = text
return text
def uid(self):
if not hasattr(self, "_uid"):
self._uid = self.component().resourceUID()
return self._uid
def componentType(self):
if not hasattr(self, "_componentType"):
self._componentType = self.component().mainType()
return self._componentType
def organizer(self):
return self.component().getOrganizer()
def getMetadata(self):
metadata = {}
metadata["accessMode"] = self.accessMode
metadata["isScheduleObject"] = self.isScheduleObject
metadata["scheduleTag"] = self.scheduleTag
metadata["scheduleEtags"] = self.scheduleEtags
metadata["hasPrivateComment"] = self.hasPrivateComment
return metadata
def _get_accessMode(self):
return str(self.properties().get(PropertyName.fromElement(customxml.TwistedCalendarAccessProperty), ""))
def _set_accessMode(self, value):
pname = PropertyName.fromElement(customxml.TwistedCalendarAccessProperty)
if value:
self.properties()[pname] = customxml.TwistedCalendarAccessProperty(value)
elif pname in self.properties():
del self.properties()[pname]
accessMode = property(_get_accessMode, _set_accessMode)
def _get_isScheduleObject(self):
"""
If the property is not present, then return None, else return a bool based on the
str "true" or "false" value.
"""
prop = self.properties().get(PropertyName.fromElement(customxml.TwistedSchedulingObjectResource))
if prop is not None:
prop = str(prop) == "true"
return prop
def _set_isScheduleObject(self, value):
pname = PropertyName.fromElement(customxml.TwistedSchedulingObjectResource)
if value is not None:
self.properties()[pname] = customxml.TwistedSchedulingObjectResource.fromString("true" if value else "false")
elif pname in self.properties():
del self.properties()[pname]
isScheduleObject = property(_get_isScheduleObject, _set_isScheduleObject)
def _get_scheduleTag(self):
return str(self.properties().get(PropertyName.fromElement(caldavxml.ScheduleTag), ""))
def _set_scheduleTag(self, value):
pname = PropertyName.fromElement(caldavxml.ScheduleTag)
if value:
self.properties()[pname] = caldavxml.ScheduleTag.fromString(value)
elif pname in self.properties():
del self.properties()[pname]
scheduleTag = property(_get_scheduleTag, _set_scheduleTag)
def _get_scheduleEtags(self):
return tuple([str(etag) for etag in self.properties().get(PropertyName.fromElement(customxml.TwistedScheduleMatchETags), customxml.TwistedScheduleMatchETags()).children])
def _set_scheduleEtags(self, value):
if value:
etags = [davxml.GETETag.fromString(etag) for etag in value]
self.properties()[PropertyName.fromElement(customxml.TwistedScheduleMatchETags)] = customxml.TwistedScheduleMatchETags(*etags)
else:
try:
del self.properties()[PropertyName.fromElement(customxml.TwistedScheduleMatchETags)]
except KeyError:
pass
scheduleEtags = property(_get_scheduleEtags, _set_scheduleEtags)
def _get_hasPrivateComment(self):
return PropertyName.fromElement(customxml.TwistedCalendarHasPrivateCommentsProperty) in self.properties()
def _set_hasPrivateComment(self, value):
pname = PropertyName.fromElement(customxml.TwistedCalendarHasPrivateCommentsProperty)
if value:
self.properties()[pname] = customxml.TwistedCalendarHasPrivateCommentsProperty()
elif pname in self.properties():
del self.properties()[pname]
hasPrivateComment = property(_get_hasPrivateComment, _set_hasPrivateComment)
def addAttachment(self, pathpattern, rids, content_type, filename, stream):
raise NotImplementedError
def updateAttachment(self, pathpattern, managed_id, content_type, filename, stream):
raise NotImplementedError
def removeAttachment(self, rids, managed_id):
raise NotImplementedError
@inlineCallbacks
def createAttachmentWithName(self, name):
"""
Implement L{ICalendarObject.removeAttachmentWithName}.
"""
# Make a (FIXME: temp, remember rollbacks) file in dropbox-land
dropboxPath = yield self._dropboxPath()
attachment = Attachment(self, name, dropboxPath)
self._attachments[name] = attachment
returnValue(attachment)
@inlineCallbacks
def removeAttachmentWithName(self, name):
"""
Implement L{ICalendarObject.removeAttachmentWithName}.
"""
# FIXME: rollback, tests for rollback
attachment = (yield self.attachmentWithName(name))
oldSize = attachment.size()
(yield self._dropboxPath()).child(name).remove()
if name in self._attachments:
del self._attachments[name]
# Adjust quota
self._calendar._home.adjustQuotaUsedBytes(-oldSize)
@inlineCallbacks
def attachmentWithName(self, name):
# Attachments can be local or remote, but right now we only care about
# local. So we're going to base this on the listing of files in the
# dropbox and not on the calendar data. However, we COULD examine the
# 'attach' properties.
if name in self._attachments:
returnValue(self._attachments[name])
# FIXME: cache consistently (put it in self._attachments)
dbp = yield self._dropboxPath()
if dbp.child(name).exists():
returnValue(Attachment(self, name, dbp))
else:
# FIXME: test for non-existent attachment.
returnValue(None)
def attendeesCanManageAttachments(self):
return self.component().hasPropertyInAnyComponent("X-APPLE-DROPBOX")
def dropboxID(self):
# NB: Deferred
return dropboxIDFromCalendarObject(self)
@inlineCallbacks
def _dropboxPath(self):
dropboxPath = self._parentCollection._home._path.child(
"dropbox"
).child((yield self.dropboxID()))
if not dropboxPath.isdir():
dropboxPath.makedirs()
returnValue(dropboxPath)
@inlineCallbacks
def attachments(self):
# See comment on attachmentWithName.
dropboxPath = (yield self._dropboxPath())
returnValue(
[Attachment(self, name, dropboxPath)
for name in dropboxPath.listdir()
if not name.startswith(".")]
)
def initPropertyStore(self, props):
# Setup peruser special properties
props.setSpecialProperties(
(
),
(
PropertyName.fromElement(customxml.TwistedCalendarAccessProperty),
PropertyName.fromElement(customxml.TwistedSchedulingObjectResource),
PropertyName.fromElement(caldavxml.ScheduleTag),
PropertyName.fromElement(customxml.TwistedScheduleMatchETags),
PropertyName.fromElement(customxml.TwistedCalendarHasPrivateCommentsProperty),
PropertyName.fromElement(customxml.ScheduleChanges),
),
(),
)
# IDataStoreObject
def contentType(self):
"""
The content type of Calendar objects is text/calendar.
"""
return MimeType.fromString("text/calendar; charset=utf-8")
class AttachmentStorageTransport(StorageTransportBase):
def __init__(self, attachment, contentType, dispositionName):
"""
Initialize this L{AttachmentStorageTransport} and open its file for
writing.
@param attachment: The attachment whose data is being filled out.
@type attachment: L{Attachment}
"""
super(AttachmentStorageTransport, self).__init__(
attachment, contentType, dispositionName)
self._path = self._attachment._path.temporarySibling()
self._file = self._path.open("w")
self._txn.postAbort(self.aborted)
@property
def _txn(self):
return self._attachment._txn
def aborted(self):
"""
Transaction aborted - clean up temp files.
"""
if self._path.exists():
self._path.remove()
def write(self, data):
# FIXME: multiple chunks
self._file.write(data)
return super(AttachmentStorageTransport, self).write(data)
def loseConnection(self):
home = self._attachment._calendarObject._calendar._home
oldSize = self._attachment.size()
newSize = self._file.tell()
# FIXME: do anything
self._file.close()
# Check max size for attachment
if newSize > config.MaximumAttachmentSize:
self._path.remove()
return fail(AttachmentSizeTooLarge())
# Check overall user quota
allowed = home.quotaAllowedBytes()
if allowed is not None and allowed < (home.quotaUsedBytes()
+ (newSize - oldSize)):
self._path.remove()
return fail(QuotaExceeded())
self._path.moveTo(self._attachment._path)
md5 = hashlib.md5(self._attachment._path.getContent()).hexdigest()
props = self._attachment.properties()
props[contentTypeKey] = GETContentType(
generateContentType(self._contentType)
)
props[md5key] = TwistedGETContentMD5.fromString(md5)
# Adjust quota
home.adjustQuotaUsedBytes(newSize - oldSize)
props.flush()
return succeed(None)
class Attachment(FileMetaDataMixin):
"""
An L{Attachment} is a container for the data associated with a I{locally-
stored} calendar attachment. That is to say, there will only be
L{Attachment} objects present on the I{organizer's} copy of and event, and
only for C{ATTACH} properties where this server is storing the resource.
(For example, the organizer may specify an C{ATTACH} property that
references an URI on a remote server.)
"""
implements(IAttachment)
def __init__(self, calendarObject, name, dropboxPath):
self._calendarObject = calendarObject
self._name = name
self._dropboxPath = dropboxPath
@property
def _txn(self):
return self._calendarObject._txn
def name(self):
return self._name
def properties(self):
home = self._calendarObject._parentCollection._home
uid = home.uid()
propStoreClass = home._dataStore._propertyStoreClass
return propStoreClass(uid, lambda: self._path)
def store(self, contentType, dispositionName=None):
return AttachmentStorageTransport(self, contentType, dispositionName)
def retrieve(self, protocol):
return AttachmentRetrievalTransport(self._path).start(protocol)
@property
def _path(self):
return self._dropboxPath.child(self.name())
class CalendarStubResource(CommonStubResource):
"""
Just enough resource to keep the calendar's sql DB classes going.
"""
def isCalendarCollection(self):
return True
def getChild(self, name):
calendarObject = self.resource.calendarObjectWithName(name)
if calendarObject:
class ChildResource(object):
def __init__(self, calendarObject):
self.calendarObject = calendarObject
def iCalendar(self):
return self.calendarObject.component()
return ChildResource(calendarObject)
else:
return None
class Index(object):
#
# OK, here's where we get ugly.
# The index code needs to be rewritten also, but in the meantime...
#
def __init__(self, calendar):
self.calendar = calendar
stubResource = CalendarStubResource(calendar)
if self.calendar.name() == 'inbox':
indexClass = OldInboxIndex
else:
indexClass = OldIndex
self._oldIndex = indexClass(stubResource)
def calendarObjects(self):
calendar = self.calendar
for name, uid, componentType in self._oldIndex.bruteForceSearch():
calendarObject = calendar.calendarObjectWithName(name)
# Precache what we found in the index
calendarObject._uid = uid
calendarObject._componentType = componentType
yield calendarObject
|
|
import fnmatch
import six
import yaml
from conans.errors import ConanException
from conans.util.sha import sha1
_falsey_options = ["false", "none", "0", "off", ""]
def option_wrong_value_msg(name, value, value_range):
""" The provided value is not among the range of values that it should
be
"""
return ("'%s' is not a valid 'options.%s' value.\nPossible values are %s"
% (value, name, value_range))
def option_not_exist_msg(option_name, existing_options):
""" Someone is referencing an option that is not available in the current package
options
"""
result = ["option '%s' doesn't exist" % option_name,
"Possible options are %s" % existing_options or "none"]
return "\n".join(result)
def option_undefined_msg(name):
return "'%s' value not defined" % name
class PackageOptionValue(str):
""" thin wrapper around a string value that allows to check for several false string
and also promote other types to string for homegeneous comparison
"""
def __bool__(self):
return self.lower() not in _falsey_options
def __nonzero__(self):
return self.__bool__()
def __eq__(self, other):
return str(other).__eq__(self)
def __ne__(self, other):
return not self.__eq__(other)
class PackageOptionValues(object):
""" set of key(string)-value(PackageOptionValue) for options of a package.
Not prefixed by package name:
static: True
optimized: 2
These are non-validating, not constrained.
Used for UserOptions, which is a dict{package_name: PackageOptionValues}
"""
def __init__(self):
self._dict = {} # {option_name: PackageOptionValue}
self._modified = {}
self._freeze = False
def __bool__(self):
return bool(self._dict)
def __contains__(self, key):
return key in self._dict
def __nonzero__(self):
return self.__bool__()
def __getattr__(self, attr):
if attr not in self._dict:
raise ConanException(option_not_exist_msg(attr, list(self._dict.keys())))
return self._dict[attr]
def __delattr__(self, attr):
if attr not in self._dict:
return
del self._dict[attr]
def clear(self):
self._dict.clear()
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
return self._dict == other._dict
def __setattr__(self, attr, value):
if attr[0] == "_":
return super(PackageOptionValues, self).__setattr__(attr, value)
self._dict[attr] = PackageOptionValue(value)
def copy(self):
result = PackageOptionValues()
for k, v in self._dict.items():
result._dict[k] = v
return result
@property
def fields(self):
return sorted(list(self._dict.keys()))
def keys(self):
return self._dict.keys()
def items(self):
return sorted(list(self._dict.items()))
def add(self, option_text):
assert isinstance(option_text, six.string_types)
name, value = option_text.split("=")
self._dict[name.strip()] = PackageOptionValue(value.strip())
def add_option(self, option_name, option_value):
self._dict[option_name] = PackageOptionValue(option_value)
def update(self, other):
assert isinstance(other, PackageOptionValues)
self._dict.update(other._dict)
def remove(self, option_name):
del self._dict[option_name]
def freeze(self):
self._freeze = True
def propagate_upstream(self, down_package_values, down_ref, own_ref, package_name):
if not down_package_values:
return
assert isinstance(down_package_values, PackageOptionValues)
for (name, value) in down_package_values.items():
if name in self._dict and self._dict.get(name) == value:
continue
if self._freeze:
raise ConanException("%s tried to change %s option %s to %s\n"
"but it was already defined as %s"
% (down_ref, own_ref, name, value, self._dict.get(name)))
modified = self._modified.get(name)
if modified is not None:
modified_value, modified_ref = modified
raise ConanException("%s tried to change %s option %s:%s to %s\n"
"but it was already assigned to %s by %s"
% (down_ref, own_ref, package_name, name, value,
modified_value, modified_ref))
else:
self._modified[name] = (value, down_ref)
self._dict[name] = value
def serialize(self):
return self.items()
@property
def sha(self):
result = []
for name, value in self.items():
# It is important to discard None values, so migrations in settings can be done
# without breaking all existing packages SHAs, by adding a first "None" option
# that doesn't change the final sha
if value:
result.append("%s=%s" % (name, value))
return sha1('\n'.join(result).encode())
class OptionsValues(object):
""" static= True,
Boost.static = False,
Poco.optimized = True
"""
def __init__(self, values=None):
self._package_values = PackageOptionValues()
self._reqs_options = {} # {name("Boost": PackageOptionValues}
if not values:
return
# convert tuple "Pkg:option=value", "..." to list of tuples(name, value)
if isinstance(values, tuple):
values = [item.split("=", 1) for item in values]
# convert dict {"Pkg:option": "value", "..": "..", ...} to list of tuples (name, value)
if isinstance(values, dict):
values = [(k, v) for k, v in values.items()]
# handle list of tuples (name, value)
for (k, v) in values:
k = k.strip()
v = v.strip() if isinstance(v, six.string_types) else v
tokens = k.split(":")
if len(tokens) == 2:
package, option = tokens
if package.endswith("/*"):
# Compatibility with 2.0, only allowed /*, at Conan 2.0 a version or any
# pattern would be allowed
package = package[:-2]
package_values = self._reqs_options.setdefault(package.strip(),
PackageOptionValues())
package_values.add_option(option, v)
else:
self._package_values.add_option(k, v)
def update(self, other):
self._package_values.update(other._package_values)
for package_name, package_values in other._reqs_options.items():
pkg_values = self._reqs_options.setdefault(package_name, PackageOptionValues())
pkg_values.update(package_values)
def scope_options(self, name):
if self._package_values:
self._reqs_options.setdefault(name, PackageOptionValues()).update(self._package_values)
self._package_values = PackageOptionValues()
def descope_options(self, name):
package_values = self._reqs_options.pop(name, None)
if package_values:
self._package_values.update(package_values)
def clear_unscoped_options(self):
self._package_values.clear()
def __contains__(self, item):
return item in self._package_values
def __getitem__(self, item):
return self._reqs_options.setdefault(item, PackageOptionValues())
def __setitem__(self, item, value):
self._reqs_options[item] = value
def pop(self, item):
return self._reqs_options.pop(item, None)
def remove(self, name, package=None):
if package:
self._reqs_options[package].remove(name)
else:
self._package_values.remove(name)
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
if not self._package_values == other._package_values:
return False
# It is possible that the entry in the dict is not defined
for key, pkg_values in self._reqs_options.items():
other_values = other[key]
if not pkg_values == other_values:
return False
return True
def __repr__(self):
return self.dumps()
def __getattr__(self, attr):
return getattr(self._package_values, attr)
def copy(self):
result = OptionsValues()
result._package_values = self._package_values.copy()
for k, v in self._reqs_options.items():
result._reqs_options[k] = v.copy()
return result
def __setattr__(self, attr, value):
if attr[0] == "_":
return super(OptionsValues, self).__setattr__(attr, value)
return setattr(self._package_values, attr, value)
def __delattr__(self, attr):
delattr(self._package_values, attr)
def clear_indirect(self):
for v in self._reqs_options.values():
v.clear()
def filter_used(self, used_pkg_names):
self._reqs_options = {k: v for k, v in self._reqs_options.items() if k in used_pkg_names}
def as_list(self):
result = []
options_list = self._package_values.items()
if options_list:
result.extend(options_list)
for package_name, package_values in sorted(self._reqs_options.items()):
for option_name, option_value in package_values.items():
result.append(("%s:%s" % (package_name, option_name), option_value))
return result
def dumps(self):
result = []
for key, value in self.as_list():
result.append("%s=%s" % (key, value))
return "\n".join(result)
@staticmethod
def loads(text):
""" parses a multiline text in the form
Package:option=value
other_option=3
OtherPack:opt3=12.1
"""
options = tuple(line.strip() for line in text.splitlines() if line.strip())
return OptionsValues(options)
@property
def sha(self):
result = [self._package_values.sha]
for key in sorted(list(self._reqs_options.keys())):
result.append(self._reqs_options[key].sha)
return sha1('\n'.join(result).encode())
def serialize(self):
ret = {"options": self._package_values.serialize(),
"req_options": {}}
for name, values in self._reqs_options.items():
ret["req_options"][name] = values.serialize()
return ret
def clear(self):
self._package_values.clear()
self._reqs_options.clear()
class PackageOption(object):
def __init__(self, possible_values, name):
self._name = name
self._value = None
if possible_values == "ANY":
self._possible_values = "ANY"
else:
self._possible_values = sorted(str(v) for v in possible_values)
def copy(self):
result = PackageOption(self._possible_values, self._name)
return result
def __bool__(self):
if not self._value:
return False
return self._value.lower() not in _falsey_options
def __nonzero__(self):
return self.__bool__()
def __str__(self):
return str(self._value)
def __int__(self):
return int(self._value)
def _check_option_value(self, value):
""" checks that the provided value is allowed by current restrictions
"""
if self._possible_values != "ANY" and value not in self._possible_values:
raise ConanException(option_wrong_value_msg(self._name, value, self._possible_values))
def __eq__(self, other):
if other is None:
return self._value is None
other = str(other)
self._check_option_value(other)
return other == self.__str__()
def __ne__(self, other):
return not self.__eq__(other)
def remove(self, values):
if self._possible_values == "ANY":
return
if not isinstance(values, (list, tuple, set)):
values = [values]
values = [str(v) for v in values]
self._possible_values = [v for v in self._possible_values if v not in values]
if self._value is not None:
self._check_option_value(self._value)
@property
def value(self):
return self._value
@value.setter
def value(self, v):
v = str(v)
self._check_option_value(v)
self._value = v
def validate(self):
if self._value is None and "None" not in self._possible_values:
raise ConanException(option_undefined_msg(self._name))
class PackageOptions(object):
def __init__(self, definition):
definition = definition or {}
self._data = {str(k): PackageOption(v, str(k))
for k, v in definition.items()}
self._modified = {}
self._freeze = False
def copy(self):
result = PackageOptions(None)
result._data = {k: v.copy() for k, v in self._data.items()}
return result
def __contains__(self, option):
return str(option) in self._data
@staticmethod
def loads(text):
return PackageOptions(yaml.safe_load(text) or {})
def get_safe(self, field, default=None):
return self._data.get(field, default)
def validate(self):
for child in self._data.values():
child.validate()
@property
def fields(self):
return sorted(list(self._data.keys()))
def remove(self, item):
if not isinstance(item, (list, tuple, set)):
item = [item]
for it in item:
it = str(it)
self._data.pop(it, None)
def clear(self):
self._data = {}
def _ensure_exists(self, field):
if field not in self._data:
raise ConanException(option_not_exist_msg(field, list(self._data.keys())))
def __getattr__(self, field):
assert field[0] != "_", "ERROR %s" % field
self._ensure_exists(field)
return self._data[field]
def __delattr__(self, field):
assert field[0] != "_", "ERROR %s" % field
self._ensure_exists(field)
del self._data[field]
def __setattr__(self, field, value):
if field[0] == "_" or field.startswith("values"):
return super(PackageOptions, self).__setattr__(field, value)
self._ensure_exists(field)
self._data[field].value = value
@property
def values(self):
result = PackageOptionValues()
for field, package_option in self._data.items():
result.add_option(field, package_option.value)
return result
def _items(self):
result = []
for field, package_option in sorted(list(self._data.items())):
result.append((field, package_option.value))
return result
def items(self):
return self._items()
def iteritems(self):
return self._items()
@values.setter
def values(self, vals):
assert isinstance(vals, PackageOptionValues)
for (name, value) in vals.items():
self._ensure_exists(name)
self._data[name].value = value
def initialize_patterns(self, values):
# Need to apply only those that exists
for option, value in values.items():
if option in self._data:
self._data[option].value = value
def freeze(self):
self._freeze = True
def propagate_upstream(self, package_values, down_ref, own_ref, pattern_options):
"""
:param: package_values: PackageOptionValues({"shared": "True"}
:param: pattern_options: Keys from the "package_values" e.g. ["shared"] that shouldn't raise
if they are not existing options for the current object
"""
if not package_values:
return
for (name, value) in package_values.items():
if name in self._data and self._data.get(name) == value:
continue
if self._freeze:
raise ConanException("%s tried to change %s option %s to %s\n"
"but it was already defined as %s"
% (down_ref, own_ref, name, value, self._data.get(name)))
modified = self._modified.get(name)
if modified is not None:
modified_value, modified_ref = modified
raise ConanException("%s tried to change %s option %s to %s\n"
"but it was already assigned to %s by %s"
% (down_ref, own_ref, name, value,
modified_value, modified_ref))
else:
if name in pattern_options: # If it is a pattern-matched option, should check field
if name in self._data:
self._data[name].value = value
self._modified[name] = (value, down_ref)
else:
self._ensure_exists(name)
self._data[name].value = value
self._modified[name] = (value, down_ref)
class Options(object):
""" All options of a package, both its own options and the upstream ones.
Owned by ConanFile.
"""
def __init__(self, options):
assert isinstance(options, PackageOptions)
self._package_options = options
# Addressed only by name, as only 1 configuration is allowed
# if more than 1 is present, 1 should be "private" requirement and its options
# are not public, not overridable
self._deps_package_values = {} # {name("Boost": PackageOptionValues}
def copy(self):
""" deepcopy, same as Settings"""
result = Options(self._package_options.copy())
result._deps_package_values = {k: v.copy() for k, v in self._deps_package_values.items()}
return result
def freeze(self):
self._package_options.freeze()
for v in self._deps_package_values.values():
v.freeze()
@property
def deps_package_values(self):
return self._deps_package_values
def clear(self):
self._package_options.clear()
def __contains__(self, option):
return option in self._package_options
def __getitem__(self, item):
return self._deps_package_values.setdefault(item, PackageOptionValues())
def __getattr__(self, attr):
return getattr(self._package_options, attr)
def __setattr__(self, attr, value):
if attr[0] == "_" or attr == "values":
return super(Options, self).__setattr__(attr, value)
return setattr(self._package_options, attr, value)
def __delattr__(self, field):
try:
self._package_options.__delattr__(field)
except ConanException:
pass
@property
def values(self):
result = OptionsValues()
result._package_values = self._package_options.values
for k, v in self._deps_package_values.items():
result._reqs_options[k] = v.copy()
return result
@values.setter
def values(self, v):
assert isinstance(v, OptionsValues)
self._package_options.values = v._package_values
self._deps_package_values.clear()
for k, v in v._reqs_options.items():
self._deps_package_values[k] = v.copy()
def propagate_upstream(self, down_package_values, down_ref, own_ref):
""" used to propagate from downstream the options to the upper requirements
:param: down_package_values => {"*": PackageOptionValues({"shared": "True"})}
:param: down_ref
:param: own_ref: Reference of the current package => ConanFileReference
"""
if not down_package_values:
return
assert isinstance(down_package_values, dict)
option_values = PackageOptionValues()
# First step is to accumulate all matching patterns, in sorted()=alphabetical order
# except the exact match
for package_pattern, package_option_values in sorted(down_package_values.items()):
if own_ref.name != package_pattern and fnmatch.fnmatch(own_ref.name, package_pattern):
option_values.update(package_option_values)
# These are pattern options, shouldn't raise if not existing
pattern_options = list(option_values.keys())
# Now, update with the exact match, that has higher priority
down_options = down_package_values.get(own_ref.name)
if down_options is not None:
option_values.update(down_options)
self._package_options.propagate_upstream(option_values, down_ref, own_ref,
pattern_options=pattern_options)
# Upstream propagation to deps
for name, option_values in sorted(list(down_package_values.items())):
if name != own_ref.name:
pkg_values = self._deps_package_values.setdefault(name, PackageOptionValues())
pkg_values.propagate_upstream(option_values, down_ref, own_ref, name)
def initialize_upstream(self, user_values, name=None):
""" used to propagate from downstream the options to the upper requirements
"""
if user_values is not None:
assert isinstance(user_values, OptionsValues)
# This code is necessary to process patterns like *:shared=True
# To apply to the current consumer, which might not have name
for pattern, pkg_options in sorted(user_values._reqs_options.items()):
# pattern = & means the consumer, irrespective of name
if fnmatch.fnmatch(name or "", pattern) or pattern == "&":
self._package_options.initialize_patterns(pkg_options)
# Then, the normal assignment of values, which could override patterns
self._package_options.values = user_values._package_values
for package_name, package_values in user_values._reqs_options.items():
pkg_values = self._deps_package_values.setdefault(package_name,
PackageOptionValues())
pkg_values.update(package_values)
def validate(self):
return self._package_options.validate()
def propagate_downstream(self, ref, options):
assert isinstance(options, OptionsValues)
self._deps_package_values[ref.name] = options._package_values
for k, v in options._reqs_options.items():
self._deps_package_values[k] = v.copy()
def clear_unused(self, prefs):
""" remove all options not related to the passed references,
that should be the upstream requirements
"""
existing_names = [pref.ref.name for pref in prefs]
self._deps_package_values = {k: v for k, v in self._deps_package_values.items()
if k in existing_names}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.